forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB576f72dTahinli3 months ago1275 commits

decode.rs15244 lines, 631.6 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, find_mv_stack_with_sign_bias, reference_mode_ctx, single_ref_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 SB_MI: u32 = 16;
55const BLOCK_MI: u32 = 8;
56
57// How many `use_filter_intra` symbols this decoder has read as `1`, across
58// every call on the current thread -- the cheap counter [`filter_intra_hits`] gate
59// tests read (before/after, not the absolute value) to prove a stream
60// actually exercised the filter-intra predictor rather than silently
61// skipping it.
62thread_local! {
63 static FILTER_INTRA_HITS: std::cell::Cell<usize> =
64 const { std::cell::Cell::new(0) };
65}
66
67/// Current value of [`FILTER_INTRA_HITS`].
68pub(crate) fn filter_intra_hits() -> usize {
69 FILTER_INTRA_HITS.with(|c| c.get())
70}
71
72// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
73// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
74// frame-level flag through the recursive block decode -- `0` (the default)
75// makes every call a true no-op, matching every existing gate stream's
76// `cdef_bits == 0` behaviour exactly.
77thread_local! {
78 static CDEF_BITS: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
79}
80// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
81// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
82// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
83// blocks every non-8-bit stream from reaching a decode call, so this is `8`
84// on every path that runs today -- threading it now (rather than the literal
85// `8`) is stage 1 of widening past that refusal without re-deriving every
86// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
87// depth (this decoder's own internal choice, matches dav1d/libaom).
88thread_local! {
89 static BIT_DEPTH: std::cell::Cell<u8> = const { std::cell::Cell::new(8) };
90}
91/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
92/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
93pub(crate) fn sample_max() -> i32 {
94 (1i32 << BIT_DEPTH.with(std::cell::Cell::get)) - 1
95}
96/// The current stream's bit depth, for callers (e.g. dequant) that need the
97/// raw value rather than the derived clamp bound.
98pub(crate) fn bit_depth() -> u8 {
99 BIT_DEPTH.with(std::cell::Cell::get)
100}
101/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
102/// [`crate::stream`]'s decode loop.
103pub(crate) fn set_bit_depth(bit_depth: u8) {
104 BIT_DEPTH.with(|c| c.set(bit_depth));
105}
106// Whether this superblock's single CDEF unit (this decoder has no 128x128
107// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
108// read -- reset to `false` at the top of each superblock in the two tile
109// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
110thread_local! {
111 static CDEF_TRANSMITTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
112}
113// Number of superblock columns in the current tile's grid, so
114// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
115// [`CDEF_IDX_GRID`].
116thread_local! {
117 static CDEF_SB_COLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
118}
119// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
120// which of the header's `1 << cdef.bits` strength pairs applies to that
121// superblock's samples.
122thread_local! {
123 static CDEF_IDX_GRID: std::cell::RefCell<Vec<u8>> = std::cell::RefCell::new(Vec::new());
124}
125// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
126// has read, across every call on the current thread -- the gate's proof that a
127// `cdef_bits > 0` stream actually reached the new reader rather than every
128// superblock coincidentally being all-skip.
129thread_local! {
130 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
131}
132
133/// Current value of [`CDEF_IDX_HITS`].
134pub(crate) fn cdef_idx_hits() -> usize {
135 CDEF_IDX_HITS.with(|c| c.get())
136}
137
138// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
139// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
140// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
141// true no-op, matching every existing gate stream's `delta_q_present == 0`
142// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
143thread_local! {
144 static DELTA_Q_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
145 static DELTA_Q_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
146}
147// The running quantizer index (spec `CurrentQIndex`, libaom
148// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
149// top of every tile (spec `decode_tile`), carried across superblocks within
150// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
151// dequantization call sites instead of the frame-constant `base_q_idx`.
152thread_local! {
153 static CURRENT_Q_IDX: std::cell::Cell<i32> = const { std::cell::Cell::new(0) };
154}
155// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
156// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
157// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
158// back at every dequantization call site keyed on which plane it is doing.
159thread_local! {
160 static QUANT_DELTAS: std::cell::Cell<crate::quant::QuantDeltas> = const {
161 std::cell::Cell::new(crate::quant::QuantDeltas {
162 y_dc: 0,
163 u_dc: 0,
164 u_ac: 0,
165 v_dc: 0,
166 v_ac: 0,
167 })
168 };
169}
170// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
171// read, across every call on the current thread -- the gate's proof that a
172// `delta_q_present` stream actually reached the new reader.
173thread_local! {
174 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
175}
176
177/// Current value of [`DELTA_Q_HITS`].
178pub(crate) fn delta_q_hits() -> usize {
179 DELTA_Q_HITS.with(|c| c.get())
180}
181
182/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
183/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
184/// one), so it is always `0` here.
185fn plane_q_delta(plane_idx: usize) -> (i32, i32) {
186 let d = QUANT_DELTAS.with(|c| c.get());
187 match plane_idx {
188 0 => (d.y_dc, 0),
189 1 => (d.u_dc, d.u_ac),
190 _ => (d.v_dc, d.v_ac),
191 }
192}
193
194/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
195/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
196/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
197/// A no-op when `delta_q_present` is unset, or when this block is not at the
198/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
199/// libaom, collapsed here to a position check since a partition tree's
200/// top-left leaf is the only block that can ever land there), or when that
201/// leaf both *is* the whole superblock and is `skip` (the one case libaom
202/// itself skips the read, state carrying over unchanged).
203fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
204 if !DELTA_Q_PRESENT.with(|c| c.get()) {
205 return;
206 }
207 if mi_r % SB_MI as usize != 0 || mi_c % SB_MI as usize != 0 {
208 return;
209 }
210 if is_whole_sb && skip {
211 return;
212 }
213 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
214 const DELTA_Q_SMALL: i32 = 3;
215 if abs >= DELTA_Q_SMALL {
216 let rem_bits = dec.literal(3) + 1;
217 let thr = (1i32 << rem_bits) + 1;
218 abs = dec.literal(rem_bits) as i32 + thr;
219 }
220 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
221 let reduced = if sign_negative { -abs } else { abs };
222 DELTA_Q_HITS.with(|c| c.set(c.get() + 1));
223 let res = DELTA_Q_RES.with(|c| c.get());
224 CURRENT_Q_IDX.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
225}
226
227// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
228// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
229thread_local! {
230 static DELTA_LF_PRESENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
231 static DELTA_LF_RES: std::cell::Cell<i32> = const { std::cell::Cell::new(1) };
232 static DELTA_LF_MULTI: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
233}
234// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
235// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
236// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
237// updates index 0 and every reader treats that as the value for all 4
238// indices (spec `read_delta_lf_params`'s own single-cdf branch).
239thread_local! {
240 static CURRENT_DELTA_LF: std::cell::Cell<[i32; 4]> = const { std::cell::Cell::new([0; 4]) };
241}
242// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
243// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
244thread_local! {
245 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
246}
247
248/// Current value of [`DELTA_LF_HITS`].
249pub(crate) fn delta_lf_hits() -> usize {
250 DELTA_LF_HITS.with(|c| c.get())
251}
252
253/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
254/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
255/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
256/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
257/// read once into index 0 otherwise.
258fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool) {
259 if !DELTA_LF_PRESENT.with(|c| c.get()) {
260 return;
261 }
262 if mi_r % SB_MI as usize != 0 || mi_c % SB_MI as usize != 0 {
263 return;
264 }
265 if is_whole_sb && skip {
266 return;
267 }
268 let multi = DELTA_LF_MULTI.with(|c| c.get());
269 let res = DELTA_LF_RES.with(|c| c.get());
270 let count = if multi { 4 } else { 1 };
271 let mut cur = CURRENT_DELTA_LF.with(|c| c.get());
272 for i in 0..count {
273 let mut abs = if multi {
274 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
275 } else {
276 dec.symbol(&mut cdfs.delta_lf) as i32
277 };
278 const DELTA_LF_SMALL: i32 = 3;
279 if abs >= DELTA_LF_SMALL {
280 let rem_bits = dec.literal(3) + 1;
281 let thr = (1i32 << rem_bits) + 1;
282 abs = dec.literal(rem_bits) as i32 + thr;
283 }
284 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
285 let reduced = if sign_negative { -abs } else { abs };
286 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
287 DELTA_LF_HITS.with(|c| c.set(c.get() + 1));
288 }
289 CURRENT_DELTA_LF.with(|c| c.set(cur));
290}
291
292/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
293/// after `skip` is known at every block-decode call site. A no-op at
294/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
295/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
296/// `allow_intrabc`, so neither needs a separate check here. Reads once per
297/// superblock, at the first non-skip block.
298fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool) {
299 let bits = CDEF_BITS.with(|c| c.get());
300 if bits == 0 || skip || CDEF_TRANSMITTED.with(|c| c.get()) {
301 return;
302 }
303 let idx = dec.literal(u32::from(bits)) as u8;
304 CDEF_TRANSMITTED.with(|c| c.set(true));
305 CDEF_IDX_HITS.with(|c| c.set(c.get() + 1));
306 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
307 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
308 if sb_cols > 0 {
309 CDEF_IDX_GRID.with(|g| {
310 let mut g = g.borrow_mut();
311 let i = sb_r * sb_cols + sb_c;
312 if i < g.len() {
313 g[i] = idx;
314 }
315 });
316 }
317}
318
319// ---------------------------------------------------------------------------
320// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
321// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
322// the two consumers a real stream exercises: the per-segment quantizer index
323// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
324// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
325// `read_intra_segment_id`/`read_inter_segment_id` and
326// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
327// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
328// is what the oracle every gate here compares against actually does.
329thread_local! {
330 static SEG: std::cell::RefCell<SegmentationParams> =
331 std::cell::RefCell::new(SegmentationParams::default());
332 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
333 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
334 static SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
335 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
336 /// this frame has no primary reference (spec `load_previous_segment_ids`).
337 static PREV_SEG_IDS: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
338 /// `(mi_rows, mi_cols)` for both maps above.
339 static SEG_MI_DIMS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
340 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
341 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
342 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
343 static ABOVE_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
344 static LEFT_SEG_PRED: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
345 /// The block currently being decoded -- read back by [`block_q_idx`].
346 static CUR_SEGMENT_ID: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
347 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
348 static SEG_TILE_ORIGIN: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
349 /// How many real `segment_id` symbols were read, and the set of segment
350 /// ids any block ended up with -- the gate's proof the feature fired.
351 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
352 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
353 /// How many `seg_id_predicted` symbols were read (temporal update).
354 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
355}
356
357/// Installs this frame's segmentation parameters and allocates its map, with
358/// `prev` the primary reference frame's saved map (spec
359/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
360/// slot). Called once per frame, whether or not segmentation is enabled.
361pub(crate) fn set_segmentation(
362 seg: SegmentationParams,
363 mi_rows: usize,
364 mi_cols: usize,
365 prev: Option<&[u8]>,
366) {
367 SEG.with(|s| *s.borrow_mut() = seg);
368 SEG_MI_DIMS.with(|c| c.set((mi_rows, mi_cols)));
369 SEG_IDS.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
370 PREV_SEG_IDS.with(|m| {
371 let mut m = m.borrow_mut();
372 m.clear();
373 if let Some(p) = prev {
374 if p.len() == mi_rows * mi_cols {
375 m.extend_from_slice(p);
376 }
377 }
378 });
379 ABOVE_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
380 LEFT_SEG_PRED.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
381 CUR_SEGMENT_ID.with(|c| c.set(0));
382}
383
384/// This frame's decoded segment map, to be stored into whichever reference
385/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
386pub(crate) fn take_segment_ids() -> Vec<u8> {
387 SEG_IDS.with(|m| m.borrow().clone())
388}
389
390/// How many `segment_id` symbols have been read (never reset per frame).
391pub(crate) fn segment_id_hits() -> usize {
392 SEG_ID_HITS.with(|c| c.get())
393}
394
395/// How many distinct segment ids any decoded block has carried.
396pub(crate) fn segment_ids_seen() -> usize {
397 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
398}
399
400/// How many `seg_id_predicted` symbols have been read (temporal update).
401pub(crate) fn segment_pred_hits() -> usize {
402 SEG_PRED_HITS.with(|c| c.get())
403}
404
405/// Resets the segmentation hit counters (gate setup).
406pub(crate) fn reset_segment_hits() {
407 SEG_ID_HITS.with(|c| c.set(0));
408 SEG_IDS_SEEN.with(|c| c.set(0));
409 SEG_PRED_HITS.with(|c| c.set(0));
410}
411
412/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
413/// being decoded, with its `FeatureData` value.
414fn seg_feature(segment_id: usize, feature: usize) -> Option<i32> {
415 SEG.with(|s| {
416 let s = s.borrow();
417 s.feature_active(segment_id, feature)
418 .then(|| i32::from(s.feature_data[segment_id][feature]))
419 })
420}
421
422/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
423/// `av1_get_qindex`) for the block currently being decoded: the running
424/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
425/// Every dequant call site reads the block's quantizer through here.
426fn block_q_idx() -> i32 {
427 let base = CURRENT_Q_IDX.with(|c| c.get());
428 let seg_id = CUR_SEGMENT_ID.with(|c| c.get()) as usize;
429 match seg_feature(seg_id, SEG_LVL_ALT_Q) {
430 Some(data) => (base + data).clamp(0, 255),
431 None => base,
432 }
433}
434
435/// The segment id recorded for one mi cell of the current frame's map.
436fn segment_id_at(mi_r: usize, mi_c: usize) -> u8 {
437 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
438 if mi_r >= mi_rows || mi_c >= mi_cols {
439 return 0;
440 }
441 SEG_IDS.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
442}
443
444/// `set_segment_id`: stamps `id` over every mi cell this block covers.
445fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8) {
446 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
447 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
448 SEG_IDS.with(|m| {
449 let mut m = m.borrow_mut();
450 for y in 0..y_mis {
451 for x in 0..x_mis {
452 m[(mi_r + y) * mi_cols + mi_c + x] = id;
453 }
454 }
455 });
456 CUR_SEGMENT_ID.with(|c| c.set(id));
457 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
458}
459
460/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
461/// `last_frame_seg_map`): the minimum previous-frame segment id over the
462/// block's own mi footprint. `0` when there is no previous map.
463fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize) -> u8 {
464 let (mi_rows, mi_cols) = SEG_MI_DIMS.with(|c| c.get());
465 PREV_SEG_IDS.with(|m| {
466 let m = m.borrow();
467 if m.is_empty() {
468 return 0;
469 }
470 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
471 let mut id = u8::MAX;
472 for y in 0..y_mis {
473 for x in 0..x_mis {
474 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
475 }
476 }
477 if id == u8::MAX { 0 } else { id }
478 })
479}
480
481/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
482fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
483 if reference == 0 {
484 return diff;
485 }
486 if reference >= max - 1 {
487 return max - diff - 1;
488 }
489 let half = if 2 * reference < max {
490 diff <= 2 * reference
491 } else {
492 diff <= 2 * (max - reference - 1)
493 };
494 if half {
495 return if diff & 1 != 0 {
496 reference + ((diff + 1) >> 1)
497 } else {
498 reference - (diff >> 1)
499 };
500 }
501 if 2 * reference < max { diff } else { max - (diff + 1) }
502}
503
504/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
505/// frame's already-decoded above/left/above-left neighbours.
506fn spatial_seg_pred(mi_r: usize, mi_c: usize) -> (i32, usize) {
507 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
508 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
509 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1)));
510 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c)));
511 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1)));
512 let ctx = match prev_ul {
513 None => 0,
514 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
515 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
516 Some(_) => 0,
517 };
518 let pred = match (prev_u, prev_l) {
519 (None, l) => l.unwrap_or(0),
520 (Some(u), None) => u,
521 (Some(u), Some(l)) => {
522 if prev_ul == Some(u) {
523 u
524 } else {
525 l
526 }
527 }
528 };
529 (pred, ctx)
530}
531
532/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
533/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
534/// that prediction. Does NOT write the map -- callers do.
535fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool) -> u8 {
536 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c);
537 if skip {
538 return pred as u8;
539 }
540 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
541 SEG_ID_HITS.with(|c| c.set(c.get() + 1));
542 let last_active = SEG.with(|s| i32::from(s.borrow().last_active_seg_id));
543 neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active) as u8
544}
545
546/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
547/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
548/// caller decides which by passing `pre_skip`).
549fn intra_segment_id(
550 dec: &mut SymbolDecoder,
551 cdfs: &mut Cdfs,
552 mi_r: usize,
553 mi_c: usize,
554 w_mi: usize,
555 h_mi: usize,
556 skip: bool,
557) {
558 if !SEG.with(|s| s.borrow().enabled) {
559 return;
560 }
561 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip);
562 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
563}
564
565/// Whether this frame's intra blocks read their `segment_id` before `skip`
566/// (`SegIdPreSkip`); `false` also when segmentation is off.
567fn seg_id_pre_skip() -> bool {
568 SEG.with(|s| {
569 let s = s.borrow();
570 s.enabled && s.seg_id_pre_skip
571 })
572}
573
574/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
575/// Called at both spec positions of an inter frame's block: `pre_skip = true`
576/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
577fn inter_segment_id(
578 dec: &mut SymbolDecoder,
579 cdfs: &mut Cdfs,
580 mi_r: usize,
581 mi_c: usize,
582 w_mi: usize,
583 h_mi: usize,
584 skip: bool,
585 pre_skip: bool,
586) {
587 let (enabled, update_map, temporal_update, pre_skip_frame) = SEG.with(|s| {
588 let s = s.borrow();
589 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
590 });
591 if !enabled {
592 return;
593 }
594 if !update_map {
595 // The map is inherited wholesale from the previous frame.
596 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi);
597 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
598 return;
599 }
600 if pre_skip && !pre_skip_frame {
601 return;
602 }
603 if !pre_skip && skip {
604 // libaom: a skipped block never codes `seg_id_predicted`, and its
605 // segment id is the spatial prediction.
606 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0);
607 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true);
608 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
609 return;
610 }
611 let id = if temporal_update {
612 let ctx = seg_pred_ctx(mi_r, mi_c);
613 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
614 SEG_PRED_HITS.with(|c| c.set(c.get() + 1));
615 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted));
616 if predicted {
617 predicted_segment_id(mi_r, mi_c, w_mi, h_mi)
618 } else {
619 read_segment_id(dec, cdfs, mi_r, mi_c, false)
620 }
621 } else {
622 read_segment_id(dec, cdfs, mi_r, mi_c, false)
623 };
624 write_segment_id(mi_r, mi_c, w_mi, h_mi, id);
625}
626
627/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
628fn seg_pred_ctx(mi_r: usize, mi_c: usize) -> usize {
629 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
630 // so contribute 0) outside the tile -- the availability check here is
631 // what keeps a previous tile's stamps out of this tile's context.
632 let (row0, col0) = SEG_TILE_ORIGIN.with(|c| c.get());
633 let above = if mi_r > row0 {
634 ABOVE_SEG_PRED.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
635 } else {
636 0
637 };
638 let left = if mi_c > col0 {
639 LEFT_SEG_PRED.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
640 } else {
641 0
642 };
643 usize::from(above + left)
644}
645
646/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
647fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8) {
648 ABOVE_SEG_PRED.with(|m| {
649 let mut m = m.borrow_mut();
650 for i in 0..w_mi {
651 if let Some(cell) = m.get_mut(mi_c + i) {
652 *cell = value;
653 }
654 }
655 });
656 LEFT_SEG_PRED.with(|m| {
657 let mut m = m.borrow_mut();
658 for i in 0..h_mi {
659 if let Some(cell) = m.get_mut(mi_r + i) {
660 *cell = value;
661 }
662 }
663 });
664}
665
666// How many key-frame luma blocks resolved `smooth_neighbor` (spec
667// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
668// counter, proving a stream actually put a directional block next to a
669// smooth-predicted neighbour rather than every block reading the (previously
670// hardcoded `false`) edge-filter strength bucket unchanged.
671thread_local! {
672 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
673 const { std::cell::Cell::new(0) };
674}
675
676/// Current value of [`SMOOTH_LUMA_HITS`].
677pub(crate) fn smooth_luma_hits() -> usize {
678 SMOOTH_LUMA_HITS.with(|c| c.get())
679}
680
681// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
682// across every call on the current thread -- lane-chroma r3's own before/after
683// counter, proving a stream actually exercised chroma's smooth/paeth
684// predictor (the previously-refused round-2 gap) rather than every block
685// landing on DC/CFL/directional.
686thread_local! {
687 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
688 const { std::cell::Cell::new(0) };
689}
690
691/// Current value of [`SMOOTH_UV_HITS`].
692pub(crate) fn smooth_uv_hits() -> usize {
693 SMOOTH_UV_HITS.with(|c| c.get())
694}
695
696// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
697// full superblock walk over, across every call on the current thread --
698// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
699// multi-tile stream must prove more than one tile actually fired, not just
700// that the stream carried tile_info.cols > 1.
701thread_local! {
702 static TILE_HITS: std::cell::Cell<usize> =
703 const { std::cell::Cell::new(0) };
704}
705/// Current value of [`TILE_HITS`].
706pub(crate) fn tile_hits() -> usize {
707 TILE_HITS.with(|c| c.get())
708}
709
710// How many 4-pixel deblocking edge groups [`edge_params`] has actually
711// selected for filtering, across every call on the current thread -- the same
712// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
713// exercised `apply_deblock` rather than every edge landing on level 0.
714thread_local! {
715 static DEBLOCK_HITS: std::cell::Cell<usize> =
716 const { std::cell::Cell::new(0) };
717}
718/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
719/// mirroring stream.rs's `pictures_decoded` so the two dumps index
720/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
721static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
722 std::sync::atomic::AtomicUsize::new(0);
723
724/// Current value of [`DEBLOCK_HITS`].
725pub(crate) fn deblock_hits() -> usize {
726 DEBLOCK_HITS.with(|c| c.get())
727}
728
729// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
730// the block's own side, across every call on the current thread -- the same
731// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
732// actually exercised a *split* transform under `TxMode::Select` rather than
733// every block coincidentally resolving `depth=0` (indistinguishable from
734// `TxMode::Largest` pixel-wise).
735thread_local! {
736 static TX_DEPTH_HITS: std::cell::Cell<usize> =
737 const { std::cell::Cell::new(0) };
738}
739
740/// Current value of [`TX_DEPTH_HITS`].
741pub(crate) fn tx_depth_hits() -> usize {
742 TX_DEPTH_HITS.with(|c| c.get())
743}
744
745// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
746// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
747// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
748// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
749// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
750// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
751// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
752// path above).
753thread_local! {
754 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
755 const { std::cell::Cell::new(0) };
756}
757
758/// Current value of [`VERT_B_INTRA_HITS`].
759pub(crate) fn vert_b_intra_hits() -> usize {
760 VERT_B_INTRA_HITS.with(|c| c.get())
761}
762
763// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
764// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
765// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
766// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
767// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
768// superblock's z-order recursion, not raster mi position).
769thread_local! {
770 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
771 const { std::cell::Cell::new(0) };
772}
773
774/// Current value of [`HORZ_VERT_INTRA_HITS`].
775pub(crate) fn horz_vert_intra_hits() -> usize {
776 HORZ_VERT_INTRA_HITS.with(|c| c.get())
777}
778
779// How many HORZ/VERT intra strips resolved a SPLIT luma transform
780// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
781// the case every rect path here refused by name before, and the first
782// refusal the user's ReelB extract (600s in) stops at.
783thread_local! {
784 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
785 const { std::cell::Cell::new(0) };
786}
787
788/// Current value of [`RECT_SPLIT_TX_HITS`].
789pub(crate) fn rect_split_tx_hits() -> usize {
790 RECT_SPLIT_TX_HITS.with(|c| c.get())
791}
792
793// How many HORZ/VERT intra strips actually predicted with filter intra
794// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
795// ("this decoder predicts square-only") until `predict_filter_intra` took
796// `bw`x`bh`.
797thread_local! {
798 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
799 const { std::cell::Cell::new(0) };
800}
801
802/// Current value of [`FILTER_INTRA_RECT_HITS`].
803pub(crate) fn filter_intra_rect_hits() -> usize {
804 FILTER_INTRA_RECT_HITS.with(|c| c.get())
805}
806
807// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
808// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
809// call on the current thread -- the same before/after counter pattern as
810// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
811// `eob_pt`/1D-neighbour context path rather than every block coincidentally
812// landing on `DCT_DCT`.
813thread_local! {
814 static TX_CLASS1_HITS: std::cell::Cell<usize> =
815 const { std::cell::Cell::new(0) };
816}
817
818// How many `uv_mode` reads resolved to a directional chroma mode (neither
819// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
820// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
821// actually exercised chroma's own directional predictor.
822thread_local! {
823 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
824 const { std::cell::Cell::new(0) };
825}
826
827/// Current value of [`DIRECTIONAL_UV_HITS`].
828pub(crate) fn directional_uv_hits() -> usize {
829 DIRECTIONAL_UV_HITS.with(|c| c.get())
830}
831
832// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
833// something other than [`ANGLE_DELTA_ZERO`], across every call in the
834// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
835// proving a stream actually exercised a nonzero angle delta.
836thread_local! {
837 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
838 const { std::cell::Cell::new(0) };
839}
840
841// How many [`read_single_ref`] reads resolved to a reference other than
842// `LAST_FRAME`, across every call on the current thread -- the same before/after
843// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
844// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
845// only other supported one so far) rather than every block coincidentally
846// resolving `LAST_FRAME`.
847thread_local! {
848 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
849 const { std::cell::Cell::new(0) };
850}
851
852/// Current value of [`NON_LAST_REF_HITS`].
853pub(crate) fn non_last_ref_hits() -> usize {
854 NON_LAST_REF_HITS.with(|c| c.get())
855}
856
857// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
858// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
859// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
860// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
861// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
862// `GOLDEN_FRAME` draw it did not ask for.
863thread_local! {
864 static LAST2_HITS: std::cell::Cell<usize> =
865 const { std::cell::Cell::new(0) };
866}
867thread_local! {
868 static LAST3_HITS: std::cell::Cell<usize> =
869 const { std::cell::Cell::new(0) };
870}
871thread_local! {
872 static GOLDEN_HITS: std::cell::Cell<usize> =
873 const { std::cell::Cell::new(0) };
874}
875thread_local! {
876 static BWDREF_HITS: std::cell::Cell<usize> =
877 const { std::cell::Cell::new(0) };
878}
879thread_local! {
880 static ALTREF2_HITS: std::cell::Cell<usize> =
881 const { std::cell::Cell::new(0) };
882}
883thread_local! {
884 static ALTREF_HITS: std::cell::Cell<usize> =
885 const { std::cell::Cell::new(0) };
886}
887
888// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
889// -- proves a `reference_select` stream actually reached a block that picked
890// compound, not just that the header bit was set. Every such block is
891// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
892// so this only ever counts attempted reads, never a completed decode.
893thread_local! {
894 static COMP_MODE_HITS: std::cell::Cell<usize> =
895 const { std::cell::Cell::new(0) };
896}
897
898/// Current value of [`COMP_MODE_HITS`].
899pub(crate) fn comp_mode_hits() -> usize {
900 COMP_MODE_HITS.with(|c| c.get())
901}
902
903// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
904// use for, across every call on the current thread -- the same before/after
905// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
906// exercised palette reconstruction rather than only reading and refusing the
907// `palette_y_mode` symbol.
908thread_local! {
909 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
910}
911
912/// Current value of [`PALETTE_HITS`].
913pub(crate) fn palette_hits() -> usize {
914 PALETTE_HITS.with(|c| c.get())
915}
916
917// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
918// palette use -- proves a stream actually reconstructed UV palette pixels,
919// not just read and refused the `palette_uv_mode` symbol.
920thread_local! {
921 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
922}
923
924/// Current value of [`PALETTE_UV_HITS`].
925pub(crate) fn palette_uv_hits() -> usize {
926 PALETTE_UV_HITS.with(|c| c.get())
927}
928
929// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
930// decoded a real palette-Y use -- proves the rect strip's own palette syntax
931// (not just the square path's) actually fired.
932thread_local! {
933 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
934}
935
936/// Current value of [`PALETTE_RECT_HITS`].
937pub(crate) fn palette_rect_hits() -> usize {
938 PALETTE_RECT_HITS.with(|c| c.get())
939}
940
941// lane-palette2 r1: how many palette-Y blocks decoded with a split luma
942// transform (`tx_select && logical_tx != side`) -- proves the per-TU index-map
943// slicing actually ran, not just that the whole-block path stayed exact.
944thread_local! {
945 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
946}
947
948/// Current value of [`PALETTE_SPLIT_TX_HITS`].
949pub(crate) fn palette_split_tx_hits() -> usize {
950 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
951}
952
953thread_local! {
954 /// A just-decoded palette-Y block's own predicted pixels
955 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
956 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
957 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
958 /// per-block override through `read_plane`'s two dozen call sites is the
959 /// alternative this avoids). Always empty again once that call consumes
960 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
961 /// sees stale state.
962 static PALETTE_PRED: std::cell::RefCell<Option<Vec<u16>>> =
963 const { std::cell::RefCell::new(None) };
964}
965
966thread_local! {
967 /// The current frame's `mi` grid, kept only while a frame header set
968 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
969 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
970 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
971 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
972 /// does not allow intrabc (so nothing is paid for it).
973 ///
974 /// corner-cut: only [`decode_block`] (the square path) records into it,
975 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
976 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
977 /// be wrong there; upgrade = record from the rect/leaf paths too.
978 static INTRABC_MI_GRID: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>> =
979 const { std::cell::RefCell::new(None) };
980 /// The block vector [`read_intra_mode`] just decoded, handed to
981 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
982 /// which the alternative -- a tenth tuple member through every caller --
983 /// already avoids). Always `.take()`n by the block that reads it.
984 static INTRABC_DV: std::cell::Cell<Option<(i32, i32)>> = const { std::cell::Cell::new(None) };
985 /// How many blocks decoded `use_intrabc == 1` -- the gate's hit counter.
986 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
987}
988
989/// Current value of [`INTRABC_HITS`].
990pub(crate) fn intrabc_hits() -> usize {
991 INTRABC_HITS.with(|c| c.get())
992}
993
994/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
995pub(crate) fn reset_intrabc_hits() {
996 INTRABC_HITS.with(|c| c.set(0));
997}
998
999/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
1000/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
1001/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
1002/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
1003fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>) {
1004 INTRABC_MI_GRID.with(|g| {
1005 let mut g = g.borrow_mut();
1006 let Some((grid, _, _)) = g.as_mut() else {
1007 return;
1008 };
1009 let info = crate::mvstack::MiInfo {
1010 is_inter: dv.is_some(),
1011 ref_frame: 0,
1012 ref_frame1: None,
1013 mv: dv.unwrap_or((0, 0)),
1014 mv1: None,
1015 is_new_mv: dv.is_some(),
1016 is_global_mv0: false,
1017 is_global_mv1: false,
1018 size: n4,
1019 size_h: n4,
1020 };
1021 for r in mi_r..mi_r + n4 {
1022 for c in mi_c..mi_c + n4 {
1023 grid.set(r, c, info);
1024 }
1025 }
1026 });
1027}
1028
1029// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
1030// proves a real `skip_mode_present` stream actually reached a block that
1031// picked it, not just that the frame header bit was set.
1032thread_local! {
1033 static SKIP_MODE_HITS: std::cell::Cell<usize> =
1034 const { std::cell::Cell::new(0) };
1035}
1036
1037/// Current value of [`SKIP_MODE_HITS`].
1038pub(crate) fn skip_mode_hits() -> usize {
1039 SKIP_MODE_HITS.with(|c| c.get())
1040}
1041
1042// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
1043// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
1044// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
1045// reached [`obmc_blend`], not just the header bit.
1046thread_local! {
1047 static OBMC_HITS: std::cell::Cell<usize> =
1048 const { std::cell::Cell::new(0) };
1049}
1050
1051/// Current value of [`OBMC_HITS`].
1052pub(crate) fn obmc_hits() -> usize {
1053 OBMC_HITS.with(|c| c.get())
1054}
1055
1056// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
1057// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
1058// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
1059// 8x8-leaf OBMC block apart from a 16x16+ one.
1060thread_local! {
1061 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1062}
1063
1064// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
1065// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
1066// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
1067// -- the gate's proof that a fixture really exercises the alphabet this
1068// round changed, even though the block itself still refuses (warp
1069// estimation/filter not ported).
1070thread_local! {
1071 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
1072 const { std::cell::Cell::new(0) };
1073}
1074
1075/// Current value of [`WARP_SELECTED_HITS`].
1076pub(crate) fn warp_selected_hits() -> usize {
1077 WARP_SELECTED_HITS.with(|c| c.get())
1078}
1079
1080// How many blocks decoded `interintra == 1` with the non-wedge blended
1081// prediction applied (lane-interintra r1) -- the gate's proof that a
1082// stream actually exercised interintra.
1083thread_local! {
1084 static INTERINTRA_HITS: std::cell::Cell<usize> =
1085 const { std::cell::Cell::new(0) };
1086}
1087
1088/// Current value of [`INTERINTRA_HITS`].
1089pub(crate) fn interintra_hits() -> usize {
1090 INTERINTRA_HITS.with(|c| c.get())
1091}
1092
1093// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
1094// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
1095// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
1096// gate fixture actually exercises this alphabet, even though the block
1097// still refuses (the mask blend itself is unported).
1098thread_local! {
1099 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
1100 const { std::cell::Cell::new(0) };
1101}
1102
1103/// Current value of [`MASKED_COMPOUND_HITS`].
1104pub(crate) fn masked_compound_hits() -> usize {
1105 MASKED_COMPOUND_HITS.with(|c| c.get())
1106}
1107
1108// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
1109// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
1110// actually exercised the wedge blend, not just the DIFFWTD half of
1111// `MASKED_COMPOUND_HITS`.
1112thread_local! {
1113 static WEDGE_HITS: std::cell::Cell<usize> =
1114 const { std::cell::Cell::new(0) };
1115}
1116
1117/// Current value of [`WEDGE_HITS`].
1118pub(crate) fn wedge_hits() -> usize {
1119 WEDGE_HITS.with(|c| c.get())
1120}
1121
1122// How many blocks decoded a real wedge-INTERINTRA block
1123// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
1124// a gate fixture exercised the wedge blend (fixed sign 0), not just the
1125// smooth arm counted by `INTERINTRA_HITS`.
1126thread_local! {
1127 static WII_HITS: std::cell::Cell<usize> =
1128 const { std::cell::Cell::new(0) };
1129}
1130
1131/// Current value of [`WII_HITS`].
1132pub(crate) fn wii_hits() -> usize {
1133 WII_HITS.with(|c| c.get())
1134}
1135
1136/// Current value of [`OBMC_HITS_8`].
1137pub(crate) fn obmc_hits_8() -> usize {
1138 OBMC_HITS_8.with(|c| c.get())
1139}
1140
1141// lane-rectgate r1: how many 32x32 quadrants actually decoded a
1142// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
1143// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
1144// `VERT_B` all still fall into the generic "a partition type this encoder
1145// never writes" refusal below) -- the gate's proof that a free-partition
1146// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
1147// coincidentally never selecting one.
1148thread_local! {
1149 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
1150 const { std::cell::Cell::new(0) };
1151}
1152
1153/// Current value of [`EXTENDED_PARTITION_HITS`].
1154pub(crate) fn extended_partition_hits() -> usize {
1155 EXTENDED_PARTITION_HITS.with(|c| c.get())
1156}
1157
1158// lane-partitions r1: how many 32x32 quadrants decoded a real
1159// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
1160// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
1161// gate's proof this round's arms actually fired.
1162thread_local! {
1163 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
1164 const { std::cell::Cell::new(0) };
1165}
1166
1167/// Current value of [`RECT_PARTITION_HITS`].
1168pub(crate) fn rect_partition_hits() -> usize {
1169 RECT_PARTITION_HITS.with(|c| c.get())
1170}
1171
1172// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
1173// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
1174// rect coefficient reader itself fired, not just the strip-level partition
1175// symbol [`RECT_PARTITION_HITS`] already counts.
1176thread_local! {
1177 static RECT_COEFF_HITS: std::cell::Cell<usize> =
1178 const { std::cell::Cell::new(0) };
1179}
1180
1181/// Current value of [`RECT_COEFF_HITS`].
1182pub(crate) fn rect_coeff_hits() -> usize {
1183 RECT_COEFF_HITS.with(|c| c.get())
1184}
1185
1186// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
1187// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
1188// gate's proof this round's arms actually reached a real block, not just
1189// that `partition_w64` read one of those two symbol values.
1190thread_local! {
1191 static SB_RECT_HITS: std::cell::Cell<usize> =
1192 const { std::cell::Cell::new(0) };
1193}
1194
1195/// Current value of [`SB_RECT_HITS`].
1196pub(crate) fn sb_rect_hits() -> usize {
1197 SB_RECT_HITS.with(|c| c.get())
1198}
1199
1200// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
1201// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
1202// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
1203// just inert-compiled. Zero forever on a passing gate means that gate's
1204// stream never carries `delta_q_present=1` through a rect64 block.
1205thread_local! {
1206 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
1207 const { std::cell::Cell::new(0) };
1208}
1209
1210/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
1211pub(crate) fn rect64_qidx_drift_hits() -> usize {
1212 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
1213}
1214
1215// lane-partab r1: how many 32x32 quadrants decoded an AB partition
1216// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
1217// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
1218// free-partition gate's proof this round's arms actually fired.
1219thread_local! {
1220 static PARTAB_HITS: std::cell::Cell<usize> =
1221 const { std::cell::Cell::new(0) };
1222}
1223
1224/// Current value of [`PARTAB_HITS`].
1225pub(crate) fn partab_hits() -> usize {
1226 PARTAB_HITS.with(|c| c.get())
1227}
1228
1229// How many [`read_inter_compound_mode`] reads actually happened
1230// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
1231// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
1232// mvstack build), not just that `comp_mode` fired. Still refused right
1233// after (no MV assignment or MC wired), so this only counts attempted
1234// reads.
1235thread_local! {
1236 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
1237 const { std::cell::Cell::new(0) };
1238}
1239
1240/// Current value of [`COMPOUND_MODE_HITS`].
1241pub(crate) fn compound_mode_hits() -> usize {
1242 COMPOUND_MODE_HITS.with(|c| c.get())
1243}
1244
1245/// How many query blocks folded in at least one temporal MV candidate
1246/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
1247/// temporal-MV gate's own firing counter (lane-av1tmvp).
1248///
1249/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
1250/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
1251/// this file (`decode_inter_block`) still passes `tpl: None` -- this
1252/// counter compiles and the projection math it counts is unit-tested
1253/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
1254/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
1255/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
1256/// against any real stream today. See the module doc on
1257/// `crate::motion_field` and this crate's ledger for the remaining wiring.
1258pub(crate) fn tmv_hits() -> usize {
1259 crate::mvstack::tmv_hits()
1260}
1261
1262/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
1263/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
1264/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
1265/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
1266/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
1267/// needs to turn a query block's own resolved `ref_frame` into
1268/// `TplArgs::cur_offset_0` (spec 7.9.3).
1269pub(crate) struct TplFrameArgs<'a> {
1270 pub field: &'a crate::motion_field::TplField,
1271 pub order_hint_bits: u32,
1272 pub order_hint: u32,
1273 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
1274 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
1275 /// frame's own `ref_frame_idx` names for each single reference.
1276 pub ref_order_hints: [u32; 7],
1277}
1278
1279/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
1280/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
1281/// decoded `grid`: every 4x4 unit an inter block covers reads the same
1282/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
1283/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
1284/// exact — every block this crate ever codes is at least 8x8, so no 8x8
1285/// cell straddles two different blocks' values.
1286pub(crate) fn build_motion_field(
1287 grid: &MiGrid,
1288 mi_cols: usize,
1289 mi_rows: usize,
1290 order_hint: u32,
1291 ref_order_hints: [u32; 7],
1292) -> crate::motion_field::MotionField {
1293 let mut field =
1294 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints);
1295 for row in 0..mi_rows {
1296 for col in 0..mi_cols {
1297 if let Some(info) = grid.get(row, col)
1298 && info.is_inter
1299 && info.ref_frame > 0
1300 {
1301 field.set(
1302 row,
1303 col,
1304 crate::motion_field::SavedMv {
1305 mv: info.mv,
1306 ref_frame: info.ref_frame,
1307 },
1308 );
1309 }
1310 }
1311 }
1312 field
1313}
1314
1315/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
1316/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
1317pub(crate) fn ref_hits(ref_frame: i8) -> usize {
1318 let c = match ref_frame {
1319 LAST2_FRAME => &LAST2_HITS,
1320 LAST3_FRAME => &LAST3_HITS,
1321 GOLDEN_FRAME => &GOLDEN_HITS,
1322 BWDREF_FRAME => &BWDREF_HITS,
1323 ALTREF2_FRAME => &ALTREF2_HITS,
1324 ALTREF_FRAME => &ALTREF_HITS,
1325 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
1326 };
1327 c.with(|v| v.get())
1328}
1329
1330thread_local! {
1331 /// The sequence header's `enable_intra_edge_filter`, set once per
1332 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
1333 /// own read of it, kept off the call stack (see that function's own doc
1334 /// comment for why) rather than threaded through every `read_plane`/
1335 /// `decode_block`/`decode_leaf8` call between here and there.
1336 static ENABLE_EDGE_FILTER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1337}
1338
1339/// Set [`ENABLE_EDGE_FILTER`] for this thread.
1340///
1341/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
1342/// never did -- so an inter frame's intra blocks read whatever value the last
1343/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
1344/// harmless (its own key frame sets it first), but a caller that decodes an
1345/// inter frame directly, or a test harness running several streams on one
1346/// thread, inherits a foreign sequence's bit: decode stops being a pure
1347/// function of the bitstream. `decode_stream` now calls this once per stream
1348/// from the sequence header, which covers every frame including inter ones.
1349pub(crate) fn set_enable_edge_filter(value: bool) {
1350 ENABLE_EDGE_FILTER.with(|f| f.set(value));
1351}
1352
1353/// Current value of [`ANGLE_DELTA_HITS`].
1354pub(crate) fn angle_delta_hits() -> usize {
1355 ANGLE_DELTA_HITS.with(|c| c.get())
1356}
1357
1358/// Current value of [`TX_CLASS1_HITS`].
1359pub(crate) fn tx_class1_hits() -> usize {
1360 TX_CLASS1_HITS.with(|c| c.get())
1361}
1362const SUB_MI: u32 = 4;
1363const MI: usize = 4;
1364const SB: usize = 64;
1365const BLOCK: usize = 32;
1366const SUB: usize = 16;
1367const TX32: usize = 32;
1368const TX16: usize = 16;
1369const TX8: usize = 8;
1370const TX4: usize = 4;
1371const DC_PRED: usize = 0;
1372/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
1373/// carries an angle delta — [`crate::tile`]'s own private copy of the same
1374/// constant.
1375const V_PRED: usize = 1;
1376const H_PRED: usize = 2;
1377/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
1378/// `Fimode_To_Intradir`, libaom `blockd.h`).
1379const D157_PRED: usize = 6;
1380/// The last directional mode, `D67_PRED`.
1381const D67_PRED: usize = 8;
1382/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
1383/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
1384/// codes anything else, so this decoder never reads anything else either.
1385const ANGLE_DELTA_ZERO: usize = 3;
1386const NUM_BASE_LEVELS: i32 = 2;
1387const COEFF_BASE_RANGE: i32 = 12;
1388const BR_STEP: i32 = 3;
1389const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
1390
1391/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
1392/// whose probability mass a superblock or block half outside the frame
1393/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
1394/// duplicated here (that module is another lane's territory this round) and
1395/// kept in step with it by the byte-exact round-trip tests below rather than
1396/// by sharing code.
1397const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
1398const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
1399
1400fn element_prob(cdf: &[u16], element: usize) -> u16 {
1401 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
1402}
1403
1404/// The two-symbol CDF a partial superblock/block's forced-split flag is read
1405/// with: the mass of `elements` becomes the probability of the one partition
1406/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
1407/// (the encoder's non-adapting counterpart to this read).
1408fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
1409 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
1410 [32768 - split, 32768, 0]
1411}
1412
1413fn unsupported(what: impl Into<String>) -> Error {
1414 Error::unsupported("AV1 tile", what.into())
1415}
1416
1417/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
1418/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
1419/// same rule.
1420pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
1421 match base_q_idx {
1422 0..=20 => 0,
1423 21..=60 => 1,
1424 61..=120 => 2,
1425 _ => 3,
1426 }
1427}
1428
1429/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
1430/// [`crate::tile`]'s writer generates its scan tables with.
1431fn default_scan(side: usize) -> Vec<u16> {
1432 let mut scan = Vec::with_capacity(side * side);
1433 for d in 0..(2 * side - 1) {
1434 let lo = d.saturating_sub(side - 1);
1435 let hi = d.min(side - 1);
1436 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
1437 if d % 2 == 0 {
1438 scan.extend(diagonal.rev());
1439 } else {
1440 scan.extend(diagonal);
1441 }
1442 }
1443 scan
1444}
1445
1446/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
1447/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
1448/// in, instead of the default zigzag. libaom's own tables are keyed by a
1449/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
1450/// physically column-major level buffer, but they decompose to the exact
1451/// same (row, col) walk as a flat row-major traversal of *our* row-major
1452/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
1453/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
1454/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
1455/// transposed (column 0 down every row, then column 1, ...).
1456fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
1457 match class {
1458 TxClass::Vert => (0..(side * side) as u16).collect(),
1459 TxClass::Horiz => (0..side)
1460 .flat_map(|col| (0..side).map(move |row| (row * side + col) as u16))
1461 .collect(),
1462 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
1463 }
1464}
1465
1466fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
1467 match scan_idx {
1468 0 => 0,
1469 i if i <= area / 8 => 1,
1470 i if i <= area / 4 => 2,
1471 _ => 3,
1472 }
1473}
1474
1475fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
1476 if row >= side || col >= side {
1477 0
1478 } else {
1479 grid[row * side + col]
1480 }
1481}
1482
1483/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
1484/// `txb_common.h`): everything but the two lone-axis-identity types this
1485/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
1486#[derive(Clone, Copy, PartialEq, Eq)]
1487enum TxClass {
1488 TwoD,
1489 Horiz,
1490 Vert,
1491}
1492
1493impl TxClass {
1494 fn of(tx_type: TxType) -> Self {
1495 match tx_type {
1496 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
1497 // key on axis alone -- FLIPADST is still ADST for this purpose.
1498 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
1499 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
1500 _ => Self::TwoD,
1501 }
1502 }
1503}
1504
1505/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
1506/// table (indexed by the position along the transform's *coded* axis --
1507/// `col` for horiz, `row` for vert) that places their contexts past the 2D
1508/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
1509/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
1510fn nz_map_ctx_offset_1d(i: usize) -> usize {
1511 match i {
1512 0 => 26,
1513 1 => 31,
1514 _ => 36,
1515 }
1516}
1517
1518fn base_ctx(
1519 grid: &[i32],
1520 side: usize,
1521 row: usize,
1522 col: usize,
1523 class: TxClass,
1524 rect_shape: Option<(usize, usize)>,
1525) -> usize {
1526 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
1527 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
1528 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
1529 // position through the full 1D neighbour sum and offset table. Skipping
1530 // that for every class desynced the last (DC) coefficient of a
1531 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
1532 // 0, which then read one extra `BR` symbol at the max and forced a
1533 // spurious third Golomb call).
1534 if class == TxClass::TwoD && row == 0 && col == 0 {
1535 return 0;
1536 }
1537 let offsets: [(usize, usize); 5] = match class {
1538 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
1539 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
1540 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
1541 };
1542 let mag: i32 = offsets
1543 .iter()
1544 .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
1545 .sum();
1546 let ctx = ((mag + 1) >> 1).min(4) as usize;
1547 match class {
1548 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
1549 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
1550 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
1551 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
1552 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
1553 // strip, which own a genuinely different table from the square one
1554 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
1555 // square table vs the real ctx 13 the rect table gives).
1556 TxClass::TwoD => {
1557 let table = match rect_shape {
1558 Some((w, h)) if w < h => &cdf::NZ_MAP_CTX_OFFSET_32X64,
1559 Some((w, h)) if w > h => &cdf::NZ_MAP_CTX_OFFSET_64X32,
1560 _ => &cdf::NZ_MAP_CTX_OFFSET_32,
1561 };
1562 ctx + table[row.min(4)][col.min(4)] as usize
1563 }
1564 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
1565 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
1566 }
1567}
1568
1569fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize, class: TxClass) -> usize {
1570 let extra = match class {
1571 TxClass::TwoD => neighbour(grid, side, row + 1, col + 1).abs(),
1572 TxClass::Horiz => neighbour(grid, side, row, col + 2).abs(),
1573 TxClass::Vert => neighbour(grid, side, row + 2, col).abs(),
1574 };
1575 let mag = neighbour(grid, side, row + 1, col).abs()
1576 + neighbour(grid, side, row, col + 1).abs()
1577 + extra;
1578 let mag = (((mag + 1) >> 1).min(6)) as usize;
1579 if row == 0 && col == 0 {
1580 return mag;
1581 }
1582 let near_origin = match class {
1583 TxClass::TwoD => row < 2 && col < 2,
1584 TxClass::Horiz => col == 0,
1585 TxClass::Vert => row == 0,
1586 };
1587 if near_origin { mag + 7 } else { mag + 14 }
1588}
1589
1590/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
1591/// transposed from libaom's column-major buffer into this decoder's row-major
1592/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
1593/// against the real table). Not the square zigzag formula generalized to
1594/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
1595const SCAN_32X16: [u16; 512] = [
1596 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
1597 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
1598 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
1599 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
1600 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
1601 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
1602 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
1603 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
1604 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
1605 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
1606 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
1607 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
1608 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
1609 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
1610 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
1611 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
1612 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
1613 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
1614 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
1615 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
1616 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
1617 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
1618 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
1619 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
1620 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
1621 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
1622 509, 478, 447, 510, 479, 511,
1623];
1624
1625/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
1626/// [`SCAN_32X16`]'s doc comment).
1627const SCAN_16X32: [u16; 512] = [
1628 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,
1629 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
1630 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
1631 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
1632 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
1633 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
1634 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
1635 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
1636 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
1637 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
1638 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
1639 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
1640 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
1641 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
1642 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
1643 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
1644 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
1645 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
1646 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
1647 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
1648 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
1649 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
1650 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
1651 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
1652 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
1653 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
1654];
1655
1656/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
1657/// [`SCAN_32X16`]'s doc comment).
1658const SCAN_16X8: [u16; 128] = [
1659 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,
1660 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
1661 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
1662 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
1663 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
1664 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
1665];
1666
1667/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
1668/// [`SCAN_32X16`]'s doc comment).
1669const SCAN_8X16: [u16; 128] = [
1670 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,
1671 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
1672 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
1673 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
1674 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
1675 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
1676];
1677
1678/// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents
1679/// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s
1680/// asymmetric-extent pattern).
1681fn neighbour_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> i32 {
1682 if row >= h || col >= w {
1683 0
1684 } else {
1685 grid[row * w + col]
1686 }
1687}
1688
1689/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
1690/// the rect generalization is libaom's own comment in
1691/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
1692/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
1693/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
1694/// [`decode_block_rect`] codes (see that function's own doc comment).
1695fn base_ctx_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> usize {
1696 if row == 0 && col == 0 {
1697 return 0;
1698 }
1699 const OFFSETS: [(usize, usize); 5] = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)];
1700 let mag: i32 = OFFSETS
1701 .iter()
1702 .map(|&(dr, dc)| neighbour_rect(grid, w, h, row + dr, col + dc).abs().min(3))
1703 .sum();
1704 let ctx = ((mag + 1) >> 1).min(4) as usize;
1705 if w < h && row < 2 {
1706 return ctx + 11;
1707 }
1708 if w > h && col < 2 {
1709 return ctx + 16;
1710 }
1711 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
1712}
1713
1714/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
1715/// neighbour-offset math itself is shape-independent, only the boundary
1716/// clamp needs the real bound in each axis.
1717fn br_ctx_rect(grid: &[i32], w: usize, h: usize, row: usize, col: usize) -> usize {
1718 let extra = neighbour_rect(grid, w, h, row + 1, col + 1).abs();
1719 let mag = neighbour_rect(grid, w, h, row + 1, col).abs()
1720 + neighbour_rect(grid, w, h, row, col + 1).abs()
1721 + extra;
1722 let mag = (((mag + 1) >> 1).min(6)) as usize;
1723 if row == 0 && col == 0 {
1724 return mag;
1725 }
1726 if row < 2 && col < 2 { mag + 7 } else { mag + 14 }
1727}
1728
1729fn dc_vote(dc: Option<bool>) -> i32 {
1730 match dc {
1731 None => 0,
1732 Some(true) => -1,
1733 Some(false) => 1,
1734 }
1735}
1736
1737fn dc_sign_ctx(vote: i32) -> usize {
1738 match vote.signum() {
1739 0 => 0,
1740 -1 => 1,
1741 _ => 2,
1742 }
1743}
1744
1745/// The remainder of a level the base and base-range syntax could not reach
1746/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
1747/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
1748fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
1749 let mut length = 1u32;
1750 while dec.literal(1) == 0 {
1751 length += 1;
1752 if length > 20 {
1753 return Err(unsupported("a Golomb tail longer than this decoder reads"));
1754 }
1755 }
1756 let mut x = 1u32;
1757 for _ in 1..length {
1758 x = (x << 1) | dec.literal(1);
1759 }
1760 Ok(x - 1)
1761}
1762
1763/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
1764/// [`crate::tile`]'s `write_eob`.
1765fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
1766 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
1767 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1768
1769 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
1770 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
1771 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
1772 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
1773 // `eob_multi_ctx`). Missing that split desynced the very first
1774 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
1775 // against a real aomdec trace).
1776 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
1777 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
1778 (_, Some(class1)) => class1,
1779 };
1780 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && eob_pt.len() == 12 {
1781 let (range, value) = dec.debug_state();
1782 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
1783 }
1784 let group = dec.symbol(eob_pt) + 1;
1785 if trace {
1786 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
1787 }
1788 let bits = OFFSET_BITS[group];
1789 let mut offset = 0u32;
1790 if bits > 0 {
1791 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
1792 if trace {
1793 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
1794 }
1795 offset = top << (bits - 1);
1796 if bits > 1 {
1797 offset |= dec.literal(bits - 1);
1798 }
1799 }
1800 GROUP_START[group] + offset as usize
1801}
1802
1803/// One transform block's levels, the inverse of [`crate::tile`]'s
1804/// `write_coeffs`, returned as a `side * side` grid in raster order, along
1805/// with the transform type that grid was coded under (`DCT_DCT` when the
1806/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
1807/// 64-point transforms, which never code anything else).
1808///
1809/// # Errors
1810/// Returns an error if the `tx_type` symbol decodes to a value outside its
1811/// CDF's own set (a corrupt or unsupported bitstream) — every value the
1812/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
1813/// produce dispatches to a real inverse transform.
1814/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
1815/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
1816/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
1817/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
1818/// the plane's own predicted mode instead. Every entry this table can
1819/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
1820/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
1821/// table ever names), so unlike the CDF-coded luma path there is no
1822/// ext-tx-set membership check to fall back from here.
1823fn default_intra_tx_type(mode: u8) -> TxType {
1824 use crate::intra::{
1825 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
1826 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
1827 };
1828 match mode {
1829 DC_PRED | D45_PRED => TxType::DctDct,
1830 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
1831 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
1832 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
1833 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
1834 }
1835}
1836
1837/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
1838/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
1839/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
1840fn is_smooth_mode(mode: usize) -> bool {
1841 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
1842}
1843
1844fn read_coeffs(
1845 dec: &mut SymbolDecoder,
1846 coding: &mut TxbTables,
1847 scan: &[u16],
1848 skip_ctx: usize,
1849 sign_ctx: usize,
1850 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
1851 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
1852 // nothing at all; `DctDct` for every luma call and every chroma call at
1853 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
1854 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
1855 default_tx_type: TxType,
1856 // `Some((w, h))` with `w != h` when this read is a superblock-level
1857 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
1858 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
1859 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
1860 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
1861 // caller's block genuinely is `side` x `side`.
1862 rect_shape: Option<(usize, usize)>,
1863) -> Result<(Vec<i32>, TxType)> {
1864 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
1865 let side = coding.side;
1866 let mut grid = vec![0i32; side * side];
1867 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
1868 let (range, value) = dec.debug_state();
1869 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
1870 }
1871 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
1872 if std::env::var_os("EC_TRACE_COEFF").is_some() {
1873 let (rng, _) = dec.debug_state();
1874 eprintln!(
1875 "EC_COEFF_STEP tag=all_zero ctx={skip_ctx} all_zero={} rng={rng}",
1876 all_zero as i32
1877 );
1878 }
1879 if std::env::var_os("EC_AV1_TELL").is_some() {
1880 eprintln!(
1881 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
1882 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
1883 );
1884 }
1885 if trace {
1886 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
1887 }
1888 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
1889 let (range, value) = dec.debug_state();
1890 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
1891 }
1892 if all_zero {
1893 return Ok((grid, TxType::DctDct));
1894 }
1895 let mut tx_type = default_tx_type;
1896 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
1897 // The CDF row's own width names its set (lane-cdffwd2: extended
1898 // past the original two-way intra split once wider `reduced_tx_set
1899 // == 0` inter sets joined the table): 17 slots (16 symbols) is
1900 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
1901 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
1902 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
1903 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
1904 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
1905 let len = tx_type_cdf.len();
1906 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() && len == 3 {
1907 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
1908 }
1909 let t = dec.symbol(tx_type_cdf);
1910 if std::env::var_os("EC_TRACE_COEFF").is_some() {
1911 let (rng, _) = dec.debug_state();
1912 eprintln!("EC_COEFF_STEP tag=tx_type rng={rng}");
1913 }
1914 if std::env::var_os("EC_AV1_EOBPT_CDF").is_some() {
1915 let (range, value) = dec.debug_state();
1916 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
1917 }
1918 if trace {
1919 eprintln!("TRACE tx_type value={t} len={len}");
1920 }
1921 tx_type = match len {
1922 17 => TxType::from_symbol_all16(t),
1923 13 => TxType::from_symbol_set2_12(t),
1924 8 => TxType::from_symbol_set1(t),
1925 _ => TxType::from_symbol(t),
1926 }
1927 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
1928 }
1929
1930 let class = TxClass::of(tx_type);
1931 if class != TxClass::TwoD {
1932 TX_CLASS1_HITS.with(|c| c.set(c.get() + 1));
1933 }
1934 let eob = read_eob(dec, coding, class);
1935 if trace {
1936 eprintln!("TRACE eob value={eob}");
1937 }
1938 let ec_trace_coeff = std::env::var_os("EC_TRACE_COEFF").is_some();
1939 if ec_trace_coeff {
1940 let (rng, _) = dec.debug_state();
1941 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={rng}");
1942 }
1943 let class_scan;
1944 let scan: &[u16] = if class == TxClass::TwoD {
1945 scan
1946 } else {
1947 class_scan = class_scan_table(side, class);
1948 &class_scan
1949 };
1950 let mut levels = vec![0i32; side * side];
1951 for scan_idx in (0..eob).rev() {
1952 let pos = scan[scan_idx] as usize;
1953 let (row, col) = (pos / side, pos % side);
1954 let level = if scan_idx == eob - 1 {
1955 let ctx = eob_coeff_ctx(scan_idx, side * side);
1956 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
1957 if trace {
1958 eprintln!(
1959 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
1960 );
1961 }
1962 v
1963 } else {
1964 let ctx = base_ctx(&levels, side, row, col, class, rect_shape);
1965 let v = dec.symbol(&mut coding.base[ctx]) as i32;
1966 if trace {
1967 eprintln!(
1968 "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
1969 );
1970 }
1971 v
1972 };
1973 let level = if level > NUM_BASE_LEVELS {
1974 let ctx = br_ctx(&levels, side, row, col, class);
1975 let mut level = level;
1976 let mut sent = 0;
1977 loop {
1978 let k = dec.symbol(&mut coding.br[ctx]) as i32;
1979 if trace {
1980 eprintln!(
1981 "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
1982 );
1983 }
1984 level += k;
1985 sent += BR_STEP;
1986 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
1987 break;
1988 }
1989 }
1990 level
1991 } else {
1992 level
1993 };
1994 if ec_trace_coeff && scan_idx == eob - 1 {
1995 let (rng, _) = dec.debug_state();
1996 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
1997 }
1998 levels[pos] = level;
1999 }
2000 if ec_trace_coeff {
2001 let (rng, _) = dec.debug_state();
2002 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
2003 }
2004
2005 for (c, &pos) in scan[..eob].iter().enumerate() {
2006 let level = levels[pos as usize];
2007 if level == 0 {
2008 continue;
2009 }
2010 let negative = if pos == 0 {
2011 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
2012 if trace {
2013 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
2014 }
2015 v
2016 } else {
2017 dec.literal(1) == 1
2018 };
2019 if ec_trace_coeff {
2020 let (rng, _) = dec.debug_state();
2021 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
2022 }
2023 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
2024 let g = read_golomb(dec)?;
2025 if trace {
2026 eprintln!("TRACE golomb pos={pos} value={g}");
2027 }
2028 level + g as i32
2029 } else {
2030 level
2031 };
2032 if ec_trace_coeff {
2033 let (rng, _) = dec.debug_state();
2034 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
2035 }
2036 grid[pos as usize] = if negative { -level } else { level };
2037 }
2038 Ok((grid, tx_type))
2039}
2040
2041/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire), restricted to
2042/// `TxClass::TwoD` -- the only class either rect size pair this decoder codes
2043/// can ever produce (see [`decode_block_rect`]'s doc comment): refuses by
2044/// name rather than guess-decode if a `tx_type` symbol or non-2D class ever
2045/// shows up here, since neither `base_ctx_rect`/`br_ctx_rect` nor
2046/// [`class_scan_table`] have a rect form for those.
2047fn read_coeffs_rect(
2048 dec: &mut SymbolDecoder,
2049 coding: &mut TxbTables,
2050 scan: &[u16],
2051 w: usize,
2052 h: usize,
2053 skip_ctx: usize,
2054 sign_ctx: usize,
2055 default_tx_type: TxType,
2056) -> Result<(Vec<i32>, TxType)> {
2057 let mut grid = vec![0i32; w * h];
2058 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
2059 if all_zero {
2060 return Ok((grid, TxType::DctDct));
2061 }
2062 if coding.tx_type.is_some() {
2063 return Err(unsupported(
2064 "a tx_type symbol on a rectangular transform (never expected at this size)",
2065 ));
2066 }
2067 let tx_type = default_tx_type;
2068 if TxClass::of(tx_type) != TxClass::TwoD {
2069 return Err(unsupported(
2070 "a non-2D tx class on a rectangular transform (never expected at this size)",
2071 ));
2072 }
2073 let eob = read_eob(dec, coding, TxClass::TwoD);
2074 let mut levels = vec![0i32; w * h];
2075 for scan_idx in (0..eob).rev() {
2076 let pos = scan[scan_idx] as usize;
2077 let (row, col) = (pos / w, pos % w);
2078 let level = if scan_idx == eob - 1 {
2079 let ctx = eob_coeff_ctx(scan_idx, w * h);
2080 dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1
2081 } else {
2082 let ctx = base_ctx_rect(&levels, w, h, row, col);
2083 dec.symbol(&mut coding.base[ctx]) as i32
2084 };
2085 let level = if level > NUM_BASE_LEVELS {
2086 let ctx = br_ctx_rect(&levels, w, h, row, col);
2087 let mut level = level;
2088 let mut sent = 0;
2089 loop {
2090 let k = dec.symbol(&mut coding.br[ctx]) as i32;
2091 level += k;
2092 sent += BR_STEP;
2093 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
2094 break;
2095 }
2096 }
2097 level
2098 } else {
2099 level
2100 };
2101 levels[pos] = level;
2102 }
2103 for &pos in &scan[..eob] {
2104 let level = levels[pos as usize];
2105 if level == 0 {
2106 continue;
2107 }
2108 let negative = if pos == 0 {
2109 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
2110 } else {
2111 dec.literal(1) == 1
2112 };
2113 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
2114 let g = read_golomb(dec)?;
2115 level + g as i32
2116 } else {
2117 level
2118 };
2119 grid[pos as usize] = if negative { -level } else { level };
2120 }
2121 Ok((grid, tx_type))
2122}
2123
2124/// What one coded block leaves behind for the blocks that read it as a
2125/// neighbour: whether it coded anything at all, and the sign of its DC —
2126/// [`crate::tile`]'s own private `Neighbour`.
2127#[derive(Clone, Copy, Default)]
2128struct Neighbour {
2129 /// The transform unit's cumulative coefficient level (spec `cul_level`,
2130 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
2131 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
2132 /// boolean (`level != 0`) is enough for every context this decoder read
2133 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
2134 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
2135 /// needs the actual magnitude tier of its above/left neighbours, not
2136 /// just whether they coded anything.
2137 level: u8,
2138 dc: Option<bool>,
2139}
2140
2141fn neighbour_state(grid: &[i32]) -> Neighbour {
2142 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
2143 Neighbour {
2144 level: cul.min(7) as u8,
2145 dc: (grid[0] != 0).then_some(grid[0] < 0),
2146 }
2147}
2148
2149/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
2150/// transform unit smaller than the block it sits in): `top`/`left` are the
2151/// above/left neighbours' magnitude tiers, each already clamped to 4.
2152const SKIP_CONTEXTS: [[usize; 5]; 5] = [
2153 [1, 2, 2, 2, 3],
2154 [2, 4, 4, 4, 5],
2155 [2, 4, 4, 4, 5],
2156 [2, 4, 4, 4, 5],
2157 [3, 5, 5, 5, 6],
2158];
2159
2160/// The neighbour state a block's contexts are read from — a duplicate of
2161/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
2162/// territory this round), kept at the same two granularities the real writer
2163/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
2164/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
2165/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
2166/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
2167/// chroma transform straddling the true, odd-sized frame edge see its
2168/// neighbour's state clamped at its own subsampled edge rather than luma's.
2169struct Neighbours {
2170 above: Vec<[Neighbour; 3]>,
2171 left: Vec<[Neighbour; 3]>,
2172 above_mode: Vec<usize>,
2173 left_mode: Vec<usize>,
2174 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
2175 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
2176 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
2177 /// luma one -- the same block can (and often does) code a different
2178 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
2179 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
2180 /// within-block neighbour finer than this grid) is luma-only -- a known,
2181 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
2182 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
2183 above_uv_mode: Vec<usize>,
2184 left_uv_mode: Vec<usize>,
2185 above_side: Vec<usize>,
2186 left_side: Vec<usize>,
2187 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
2188 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
2189 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
2190 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
2191 /// array cannot tell the second leaf's partition symbol that the first
2192 /// one was coded at 8x8.
2193 above_side_mi: Vec<usize>,
2194 left_side_mi: Vec<usize>,
2195 /// Whether the block above/left of this column/row was coded `skip` --
2196 /// an inter frame's own `skip` context (spec `SkipContext`), which the
2197 /// key-frame writer never tracks (its skip context is always zero); a
2198 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
2199 /// `left_skip`.
2200 above_skip: Vec<bool>,
2201 left_skip: Vec<bool>,
2202 /// Whether the block above/left of this column/row coded `skip_mode`
2203 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
2204 /// lane-av1comp round 14.
2205 above_skip_mode: Vec<bool>,
2206 left_skip_mode: Vec<bool>,
2207 /// Whether the block above/left was coded inter -- the `is_inter`
2208 /// context (spec `av1_get_intra_inter_context`), a duplicate of
2209 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
2210 above_inter: Vec<bool>,
2211 left_inter: Vec<bool>,
2212 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
2213 /// alphabet) the block above/left of this column/row coded, or `-1` for
2214 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
2215 /// functions (`mvstack::ref_ctx` family) need the real reference, not
2216 /// just "was it inter" (lane-av1refs: every inter block used to be
2217 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
2218 /// enough).
2219 above_ref: Vec<i8>,
2220 left_ref: Vec<i8>,
2221 /// The block above/left's *second* reference frame when it was coded
2222 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
2223 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
2224 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
2225 /// `i8`, once a compound `read_ref_frames` lands. Always `None` today
2226 /// (no decode path here ever produces a compound block yet).
2227 above_ref1: Vec<Option<i8>>,
2228 left_ref1: Vec<Option<i8>>,
2229 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
2230 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
2231 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
2232 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
2233 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
2234 above_comp_group_idx: Vec<u8>,
2235 left_comp_group_idx: Vec<u8>,
2236 above_compound_idx: Vec<u8>,
2237 left_compound_idx: Vec<u8>,
2238 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
2239 /// `3` = "no info": an intra neighbour or the frame's own border) of the
2240 /// block above/left of this column/row -- spec
2241 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
2242 above_filter: Vec<[u8; 2]>,
2243 left_filter: Vec<[u8; 2]>,
2244 mi_cols: usize,
2245 mi_rows: usize,
2246 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
2247 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
2248 /// 7.15) never filters an 8x8 luma block whose covering coded block read
2249 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
2250 /// grain [`Self::record_mi`] already writes at), read back at 8x8
2251 /// granularity by [`apply_cdef`] since `skip` is constant across every
2252 /// mi cell one coded block covers.
2253 skip_grid: Vec<bool>,
2254 skip_grid_cols_mi: usize,
2255 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
2256 /// never splits a coded block's transform below its own size (round 2:
2257 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
2258 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
2259 /// edge-length lookup (`apply_deblock`).
2260 tx_grid: Vec<u8>,
2261 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
2262 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
2263 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
2264 tx_h_grid: Vec<u8>,
2265 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
2266 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
2267 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
2268 /// does NOT follow luma's `tx_depth` split, so deriving it as
2269 /// `tx_grid / 2` invented chroma transform edges the deblocker then
2270 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
2271 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
2272 /// every caller routes through.
2273 uv_tx_grid: Vec<u8>,
2274 uv_tx_h_grid: Vec<u8>,
2275 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
2276 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
2277 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
2278 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
2279 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
2280 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
2281 /// reference onto `LAST_FRAME`'s own delta).
2282 ref_grid: Vec<i8>,
2283 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
2284 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
2285 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
2286 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
2287 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
2288 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
2289 /// to know which mode produced the value.
2290 delta_lf_grid: Vec<[i8; 4]>,
2291 /// The block above/left's own palette-Y size (0 = not a palette block)
2292 /// and its base colours -- `av1_get_palette_mode_ctx`/
2293 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
2294 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
2295 above_palette_size: Vec<usize>,
2296 left_palette_size: Vec<usize>,
2297 above_palette_colors: Vec<[u16; 8]>,
2298 left_palette_colors: Vec<[u16; 8]>,
2299 /// As the four fields above, for the neighbour's own chroma (U-channel
2300 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
2301 /// palette size/colours (lane-palette2 r1).
2302 above_palette_uv_size: Vec<usize>,
2303 left_palette_uv_size: Vec<usize>,
2304 above_palette_uv_colors: Vec<[u16; 8]>,
2305 left_palette_uv_colors: Vec<[u16; 8]>,
2306 /// This tile's own top-left corner, in 4x4 mode-info units (spec
2307 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
2308 /// neighbour" check compares against this instead of literal `0`, since a
2309 /// block at the tile's own top/left edge has no usable neighbour even
2310 /// though a decoded block sits there in the picture (spec `decode_tile`'s
2311 /// per-tile `clear_above_context`/`left_available`/`up_available`).
2312 /// `0` for a single-tile frame, matching every existing caller exactly.
2313 tile_row0_mi: usize,
2314 tile_col0_mi: usize,
2315}
2316
2317impl Neighbours {
2318 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
2319 /// true (unpadded) size in 4x4 mode-info units.
2320 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
2321 Self {
2322 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
2323 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
2324 above_mode: vec![DC_PRED; cols],
2325 left_mode: vec![DC_PRED; rows],
2326 above_uv_mode: vec![DC_PRED; cols],
2327 left_uv_mode: vec![DC_PRED; rows],
2328 above_side: vec![SB; cols],
2329 left_side: vec![SB; rows],
2330 above_side_mi: vec![SB; cols * (SUB / MI)],
2331 left_side_mi: vec![SB; rows * (SUB / MI)],
2332 above_skip: vec![false; cols],
2333 left_skip: vec![false; rows],
2334 above_skip_mode: vec![false; cols],
2335 left_skip_mode: vec![false; rows],
2336 above_inter: vec![false; cols],
2337 left_inter: vec![false; rows],
2338 above_ref: vec![-1; cols],
2339 left_ref: vec![-1; rows],
2340 above_ref1: vec![None; cols],
2341 left_ref1: vec![None; rows],
2342 above_comp_group_idx: vec![0; cols],
2343 left_comp_group_idx: vec![0; rows],
2344 above_compound_idx: vec![0; cols],
2345 left_compound_idx: vec![0; rows],
2346 above_filter: vec![[3u8; 2]; cols],
2347 left_filter: vec![[3u8; 2]; rows],
2348 mi_cols,
2349 mi_rows,
2350 skip_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
2351 skip_grid_cols_mi: cols * (SUB / MI),
2352 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
2353 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
2354 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
2355 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
2356 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
2357 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
2358 above_palette_size: vec![0; cols],
2359 left_palette_size: vec![0; rows],
2360 above_palette_colors: vec![[0u16; 8]; cols],
2361 left_palette_colors: vec![[0u16; 8]; rows],
2362 above_palette_uv_size: vec![0; cols],
2363 left_palette_uv_size: vec![0; rows],
2364 above_palette_uv_colors: vec![[0u16; 8]; cols],
2365 left_palette_uv_colors: vec![[0u16; 8]; rows],
2366 tile_row0_mi: 0,
2367 tile_col0_mi: 0,
2368 }
2369 }
2370
2371 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
2372 /// tile's own column span (`col1_mi` exclusive), plus recording
2373 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
2374 /// availability check below. Left context resets every superblock row
2375 /// regardless of tile ([`Self::start_row`], already called once per SB
2376 /// row by every caller) so it needs no tile-specific reset here.
2377 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize) {
2378 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
2379 // are tile-relative, same as every other neighbour lookup here.
2380 SEG_TILE_ORIGIN.with(|c| c.set((row0_mi, col0_mi)));
2381 self.tile_row0_mi = row0_mi;
2382 self.tile_col0_mi = col0_mi;
2383 let end = col1_mi.min(self.above.len());
2384 for i in col0_mi.min(end)..end {
2385 self.above[i] = Default::default();
2386 self.above_side_mi[i] = SB;
2387 }
2388 let (sc0, sc1) = (
2389 col0_mi / (SUB / MI),
2390 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
2391 );
2392 for i in sc0.min(sc1)..sc1 {
2393 self.above_mode[i] = DC_PRED;
2394 self.above_side[i] = SB;
2395 self.above_skip[i] = false;
2396 self.above_skip_mode[i] = false;
2397 self.above_inter[i] = false;
2398 self.above_ref[i] = -1;
2399 self.above_ref1[i] = None;
2400 self.above_comp_group_idx[i] = 0;
2401 self.above_compound_idx[i] = 0;
2402 self.above_filter[i] = [3u8; 2];
2403 }
2404 }
2405
2406 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
2407 /// for a non-palette block, clearing any stale neighbour state) into every
2408 /// [`SUB`]-grid cell it covers on both the above and left edges --
2409 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
2410 /// call sites are all square blocks).
2411 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
2412 let (r, c) = at;
2413 for cell in 0..side / SUB {
2414 self.above_palette_size[c + cell] = size;
2415 self.above_palette_colors[c + cell] = colors;
2416 }
2417 for cell in 0..side / SUB {
2418 self.left_palette_size[r + cell] = size;
2419 self.left_palette_colors[r + cell] = colors;
2420 }
2421 }
2422
2423 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
2424 /// neighbours that are themselves a palette-Y block, plus
2425 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
2426 /// cache (pred_common.c:73) -- the above neighbour is excluded at a
2427 /// superblock's own top row (`r % 4 == 0` in [`SUB`]-grid units, 4 cells
2428 /// per 64px SB, `MIN_SB_SIZE_LOG2`), the left neighbour never is.
2429 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
2430 let (r, c) = at;
2431 let above_ok = r % 4 != 0;
2432 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
2433 (self.above_palette_size[c], self.above_palette_colors[c])
2434 } else {
2435 (0, [0u16; 8])
2436 };
2437 let (left_n, left_colors) = if self.left_palette_size[r] > 0 {
2438 (self.left_palette_size[r], self.left_palette_colors[r])
2439 } else {
2440 (0, [0u16; 8])
2441 };
2442 let ctx = usize::from(above_n > 0) + usize::from(left_n > 0);
2443 let mut cache = Vec::with_capacity(16);
2444 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
2445 if cache.last() != Some(&v) {
2446 cache.push(v);
2447 }
2448 };
2449 let (mut ai, mut li) = (0usize, 0usize);
2450 while ai < above_n && li < left_n {
2451 let (va, vl) = (above_colors[ai], left_colors[li]);
2452 if vl < va {
2453 push_dedup(&mut cache, vl);
2454 li += 1;
2455 } else {
2456 push_dedup(&mut cache, va);
2457 ai += 1;
2458 if vl == va {
2459 li += 1;
2460 }
2461 }
2462 }
2463 while ai < above_n {
2464 push_dedup(&mut cache, above_colors[ai]);
2465 ai += 1;
2466 }
2467 while li < left_n {
2468 push_dedup(&mut cache, left_colors[li]);
2469 li += 1;
2470 }
2471 (ctx, cache)
2472 }
2473
2474 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
2475 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
2476 /// same way (lane-palette2 r1).
2477 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
2478 let (r, c) = at;
2479 for cell in 0..side / SUB {
2480 self.above_palette_uv_size[c + cell] = size;
2481 self.above_palette_uv_colors[c + cell] = colors;
2482 }
2483 for cell in 0..side / SUB {
2484 self.left_palette_uv_size[r + cell] = size;
2485 self.left_palette_uv_colors[r + cell] = colors;
2486 }
2487 }
2488
2489 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
2490 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
2491 /// no neighbour lookup at all (it is this block's own just-decided Y
2492 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
2493 /// so only the cache is wanted here.
2494 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
2495 let (r, c) = at;
2496 let above_ok = r % 4 != 0;
2497 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
2498 (self.above_palette_uv_size[c], self.above_palette_uv_colors[c])
2499 } else {
2500 (0, [0u16; 8])
2501 };
2502 let (left_n, left_colors) = if self.left_palette_uv_size[r] > 0 {
2503 (self.left_palette_uv_size[r], self.left_palette_uv_colors[r])
2504 } else {
2505 (0, [0u16; 8])
2506 };
2507 let mut cache = Vec::with_capacity(16);
2508 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
2509 if cache.last() != Some(&v) {
2510 cache.push(v);
2511 }
2512 };
2513 let (mut ai, mut li) = (0usize, 0usize);
2514 while ai < above_n && li < left_n {
2515 let (va, vl) = (above_colors[ai], left_colors[li]);
2516 if vl < va {
2517 push_dedup(&mut cache, vl);
2518 li += 1;
2519 } else {
2520 push_dedup(&mut cache, va);
2521 ai += 1;
2522 if vl == va {
2523 li += 1;
2524 }
2525 }
2526 }
2527 while ai < above_n {
2528 push_dedup(&mut cache, above_colors[ai]);
2529 ai += 1;
2530 }
2531 while li < left_n {
2532 push_dedup(&mut cache, left_colors[li]);
2533 li += 1;
2534 }
2535 cache
2536 }
2537
2538 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
2539 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
2540 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
2541 /// units as [`Self::fill_skip_grid`].
2542 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8) {
2543 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame);
2544 }
2545
2546 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
2547 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
2548 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
2549 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
2550 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
2551 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
2552 fn fill_lf_grid_rect(
2553 &mut self,
2554 at_mi: (usize, usize),
2555 w_mi: usize,
2556 h_mi: usize,
2557 tx_px: u8,
2558 tx_h_px: u8,
2559 ref_frame: i8,
2560 ) {
2561 let (mi_r, mi_c) = at_mi;
2562 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
2563 // half its luma one (min 4 px, the smallest transform), capped at
2564 // TX_32X32 -- independent of this block's luma `tx_depth`.
2565 let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
2566 let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
2567 let cur = CURRENT_DELTA_LF.with(|c| c.get());
2568 let snapshot: [i8; 4] = if DELTA_LF_MULTI.with(|c| c.get()) {
2569 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
2570 } else {
2571 [cur[0].clamp(-63, 63) as i8; 4]
2572 };
2573 for rr in 0..h_mi {
2574 for cc in 0..w_mi {
2575 let idx = (mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc);
2576 if let Some(cell) = self.tx_grid.get_mut(idx) {
2577 *cell = tx_px;
2578 }
2579 if let Some(cell) = self.tx_h_grid.get_mut(idx) {
2580 *cell = tx_h_px;
2581 }
2582 if let Some(cell) = self.uv_tx_grid.get_mut(idx) {
2583 *cell = uv_tx_w;
2584 }
2585 if let Some(cell) = self.uv_tx_h_grid.get_mut(idx) {
2586 *cell = uv_tx_h;
2587 }
2588 if let Some(cell) = self.ref_grid.get_mut(idx) {
2589 *cell = ref_frame;
2590 }
2591 if let Some(cell) = self.delta_lf_grid.get_mut(idx) {
2592 *cell = snapshot;
2593 }
2594 }
2595 }
2596 }
2597
2598 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
2599 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
2600 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
2601 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
2602 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
2603 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
2604 }
2605
2606 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
2607 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
2608 let (mi_r, mi_c) = at_mi;
2609 for rr in 0..h_mi {
2610 for cc in 0..w_mi {
2611 if let Some(cell) = self
2612 .skip_grid
2613 .get_mut((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
2614 {
2615 *cell = skip;
2616 }
2617 }
2618 }
2619 }
2620
2621 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
2622 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
2623 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
2624 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
2625 /// straddle the region with a mix of skip/non-skip blocks).
2626 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
2627 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
2628 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
2629 /// filtered edge's two sides are each exactly one coded block wide.
2630 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
2631 self.skip_grid
2632 .get(mi_r * self.skip_grid_cols_mi + mi_c)
2633 .copied()
2634 .unwrap_or(false)
2635 }
2636
2637 /// The `skip_txfm` context of a block whose top-left mi cell is
2638 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
2639 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
2640 /// with an absent neighbour contributing 0. The mi grid is per tile, so
2641 /// row/column 0 is a tile edge and has no neighbour on that axis.
2642 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
2643 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
2644 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
2645 }
2646
2647 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
2648 (0..2).all(|rr| {
2649 (0..2).all(|cc| {
2650 self.skip_grid
2651 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
2652 .copied()
2653 .unwrap_or(false)
2654 })
2655 })
2656 }
2657
2658 fn start_row(&mut self) {
2659 self.left.iter_mut().for_each(|l| *l = Default::default());
2660 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
2661 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
2662 self.left_side.iter_mut().for_each(|s| *s = SB);
2663 self.left_side_mi.iter_mut().for_each(|s| *s = SB);
2664 self.left_skip.iter_mut().for_each(|s| *s = false);
2665 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
2666 self.left_inter.iter_mut().for_each(|i| *i = false);
2667 self.left_ref.iter_mut().for_each(|r| *r = -1);
2668 self.left_ref1.iter_mut().for_each(|r| *r = None);
2669 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
2670 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
2671 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
2672 }
2673
2674 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
2675 /// block that reads it as a neighbour -- [`crate::tile`]'s
2676 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
2677 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
2678 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
2679 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
2680 /// the real value, not just `is_inter`).
2681 fn record_inter(
2682 &mut self,
2683 at: (usize, usize),
2684 side: usize,
2685 skip: bool,
2686 is_inter: bool,
2687 ref_frame: i8,
2688 filter: [u8; 2],
2689 skip_mode: bool,
2690 ) {
2691 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
2692 }
2693
2694 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
2695 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
2696 /// r1: a true rectangular strip's above-context span (its own width) and
2697 /// left-context span (its own height) differ, unlike every caller before
2698 /// this round (class neighbour-votes-all-its-fields).
2699 #[allow(clippy::too_many_arguments)]
2700 fn record_inter_rect(
2701 &mut self,
2702 at: (usize, usize),
2703 w_sub: usize,
2704 h_sub: usize,
2705 skip: bool,
2706 is_inter: bool,
2707 ref_frame: i8,
2708 filter: [u8; 2],
2709 skip_mode: bool,
2710 ) {
2711 let (r, c) = at;
2712 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
2713 for cell in 0..w_sub / SUB {
2714 self.above_skip[c + cell] = skip;
2715 self.above_skip_mode[c + cell] = skip_mode;
2716 self.above_inter[c + cell] = is_inter;
2717 self.above_ref[c + cell] = ref_frame;
2718 // lane-av1comp: no caller of `record_inter` ever decodes a
2719 // compound block yet (see [`Self::above_ref1`]'s doc); the
2720 // parameter this becomes lands with `read_ref_frames`.
2721 self.above_ref1[c + cell] = None;
2722 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
2723 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
2724 // as `3`/`1` even though this block has no second reference.
2725 // `record_compound_ctx` overwrites this with the real bit for an
2726 // actual compound block's cells, called right after this one.
2727 self.above_comp_group_idx[c + cell] = if altref { 3 } else { 0 };
2728 self.above_compound_idx[c + cell] = u8::from(altref);
2729 self.above_filter[c + cell] = filter;
2730 }
2731 for cell in 0..h_sub / SUB {
2732 self.left_skip[r + cell] = skip;
2733 self.left_skip_mode[r + cell] = skip_mode;
2734 self.left_inter[r + cell] = is_inter;
2735 self.left_ref[r + cell] = ref_frame;
2736 self.left_ref1[r + cell] = None;
2737 self.left_comp_group_idx[r + cell] = if altref { 3 } else { 0 };
2738 self.left_compound_idx[r + cell] = u8::from(altref);
2739 self.left_filter[r + cell] = filter;
2740 }
2741 }
2742
2743 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
2744 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
2745 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
2746 /// `get_comp_index_context`) -- called right after `record_inter` for
2747 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
2748 /// stamps `above_ref1`/`left_ref1` with the block's real second
2749 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
2750 /// this is the one caller that actually knows it) -- so the next block's
2751 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
2752 /// neighbour instead of `record_inter`'s single-ref default.
2753 fn record_compound_ctx(
2754 &mut self,
2755 at: (usize, usize),
2756 side: usize,
2757 ref1: i8,
2758 comp_group_idx: u8,
2759 compound_idx: u8,
2760 ) {
2761 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
2762 }
2763
2764 /// [`Self::record_compound_ctx`] with independent above/left extents,
2765 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
2766 #[allow(clippy::too_many_arguments)]
2767 fn record_compound_ctx_rect(
2768 &mut self,
2769 at: (usize, usize),
2770 w_sub: usize,
2771 h_sub: usize,
2772 ref1: i8,
2773 comp_group_idx: u8,
2774 compound_idx: u8,
2775 ) {
2776 let (r, c) = at;
2777 for cell in 0..w_sub / SUB {
2778 self.above_ref1[c + cell] = Some(ref1);
2779 self.above_comp_group_idx[c + cell] = comp_group_idx;
2780 self.above_compound_idx[c + cell] = compound_idx;
2781 }
2782 for cell in 0..h_sub / SUB {
2783 self.left_ref1[r + cell] = Some(ref1);
2784 self.left_comp_group_idx[r + cell] = comp_group_idx;
2785 self.left_compound_idx[r + cell] = compound_idx;
2786 }
2787 }
2788
2789 /// The context of a block's partition symbol: delegates to the mi-precise
2790 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
2791 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
2792 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
2793 /// only touches the finer mi arrays -- leaves them stale for the *next*
2794 /// sibling's own partition symbol.
2795 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
2796 let (r, c) = at;
2797 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
2798 }
2799
2800 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
2801 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
2802 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
2803 /// than the enclosing 16x16 slot's stale, shared state.
2804 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
2805 2 * usize::from(self.left_side_mi[mi_r] * 2 <= side)
2806 + usize::from(self.above_side_mi[mi_c] * 2 <= side)
2807 }
2808
2809 /// The gathered coded/DC-sign state of the blocks above and to the left
2810 /// of a block `side` samples across, per plane.
2811 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
2812 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
2813 }
2814
2815 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
2816 /// units, for the same reason [`Self::record_mi`] does.
2817 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
2818 let side_mi = side / MI;
2819 std::array::from_fn(|plane| {
2820 let mut above_coded = false;
2821 let mut left_coded = false;
2822 let mut vote = 0;
2823 for cell in 0..side_mi {
2824 let above = &self.above[mi_c + cell][plane];
2825 let left = &self.left[mi_r + cell][plane];
2826 above_coded |= above.level != 0;
2827 left_coded |= left.level != 0;
2828 vote += dc_vote(above.dc) + dc_vote(left.dc);
2829 }
2830 (above_coded, left_coded, vote)
2831 })
2832 }
2833
2834 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
2835 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
2836 /// extent pattern for a true rectangular strip's own coefficient context.
2837 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
2838 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
2839 }
2840
2841 /// [`Self::around_rect`] taking the block's position directly in 4x4
2842 /// mode-info units, mirroring [`Self::around_mi`].
2843 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
2844 let (w_mi, h_mi) = (w / MI, h / MI);
2845 std::array::from_fn(|plane| {
2846 let mut above_coded = false;
2847 let mut left_coded = false;
2848 let mut vote = 0;
2849 for cell in 0..w_mi {
2850 let above = &self.above[mi_c + cell][plane];
2851 above_coded |= above.level != 0;
2852 vote += dc_vote(above.dc);
2853 }
2854 for cell in 0..h_mi {
2855 let left = &self.left[mi_r + cell][plane];
2856 left_coded |= left.level != 0;
2857 vote += dc_vote(left.dc);
2858 }
2859 (above_coded, left_coded, vote)
2860 })
2861 }
2862
2863 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
2864 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
2865 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
2866 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
2867 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
2868 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
2869 /// is always 0, spec's `plane_bsize == tx_size` branch).
2870 fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize {
2871 let mut top = 0u8;
2872 let mut left = 0u8;
2873 for cell in 0..side_mi {
2874 top |= self.above[mi_c + cell][0].level;
2875 left |= self.left[mi_r + cell][0].level;
2876 }
2877 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
2878 if std::env::var_os("EC_AV1_TRACE").is_some() {
2879 eprintln!(
2880 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx}"
2881 );
2882 }
2883 ctx
2884 }
2885
2886 /// Writes one coded block into every cell it covers, on both grids: the
2887 /// mode/side arrays up to `side`'s own width, and the coefficient-context
2888 /// arrays up to the true frame edge — the units past it are left at their
2889 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
2890 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
2891 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
2892 /// not from this block's own side).
2893 fn record(
2894 &mut self,
2895 at: (usize, usize),
2896 side: usize,
2897 mode: usize,
2898 uv_mode: usize,
2899 grids: &[Vec<i32>; 3],
2900 ) {
2901 self.record_rect(at, side, side, mode, uv_mode, grids);
2902 }
2903
2904 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
2905 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
2906 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
2907 /// spec's per-edge partition-context rule, so a true rectangular block
2908 /// naturally wants two different values here rather than one.
2909 fn record_rect(
2910 &mut self,
2911 at: (usize, usize),
2912 w: usize,
2913 h: usize,
2914 mode: usize,
2915 uv_mode: usize,
2916 grids: &[Vec<i32>; 3],
2917 ) {
2918 let (r, c) = at;
2919 for cell in 0..w / SUB {
2920 self.above_mode[c + cell] = mode;
2921 self.above_uv_mode[c + cell] = uv_mode;
2922 self.above_side[c + cell] = w;
2923 }
2924 for cell in 0..h / SUB {
2925 self.left_mode[r + cell] = mode;
2926 self.left_uv_mode[r + cell] = uv_mode;
2927 self.left_side[r + cell] = h;
2928 }
2929 self.record_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h, grids);
2930 }
2931
2932 /// The coefficient-context half of [`Self::record`], taking the block's
2933 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
2934 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
2935 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
2936 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
2937 self.record_mi_rect(at_mi, side, side, grids);
2938 }
2939
2940 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
2941 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
2942 fn record_mi_rect(
2943 &mut self,
2944 at_mi: (usize, usize),
2945 w: usize,
2946 h: usize,
2947 grids: &[Vec<i32>; 3],
2948 ) {
2949 let (mi_r, mi_c) = at_mi;
2950 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
2951 let (w_mi, h_mi) = (w / MI, h / MI);
2952 for cell in 0..h_mi {
2953 self.left_side_mi[mi_r + cell] = h;
2954 }
2955 for cell in 0..w_mi {
2956 self.above_side_mi[mi_c + cell] = w;
2957 }
2958 // A chroma 4x4 unit straddling the true luma edge is still whole in
2959 // chroma's own halved grid, so libaom rounds the luma bound up to the
2960 // plane's own 4x4 unit before clamping a subsampled plane
2961 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
2962 let round_up_even = |n: usize| n.div_ceil(2) * 2;
2963 let bound_h = [
2964 self.mi_rows,
2965 round_up_even(self.mi_rows),
2966 round_up_even(self.mi_rows),
2967 ];
2968 let bound_w = [
2969 self.mi_cols,
2970 round_up_even(self.mi_cols),
2971 round_up_even(self.mi_cols),
2972 ];
2973 for cell in 0..h_mi {
2974 self.left[mi_r + cell] = std::array::from_fn(|plane| {
2975 if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
2976 states[plane]
2977 } else {
2978 Default::default()
2979 }
2980 });
2981 }
2982 for cell in 0..w_mi {
2983 self.above[mi_c + cell] = std::array::from_fn(|plane| {
2984 if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
2985 states[plane]
2986 } else {
2987 Default::default()
2988 }
2989 });
2990 }
2991 }
2992
2993 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
2994 /// inside a coded block whose luma transform is smaller than its own
2995 /// side (`TxMode::Select`): the real per-transform-unit coefficient
2996 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
2997 /// coarse per-block `tx_grid`/`fill_lf_grid` state
2998 /// [`Self::record_split_luma`] still writes once for the whole block.
2999 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
3000 /// the caller's own [`Self::record_split_luma`] call sets those once,
3001 /// at the block's own true side, not this TU's.
3002 fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) {
3003 let state = neighbour_state(grid);
3004 let side_mi = tx_px / MI;
3005 for cell in 0..side_mi {
3006 if mi_r + cell < self.mi_rows {
3007 self.left[mi_r + cell][0] = state;
3008 }
3009 if mi_c + cell < self.mi_cols {
3010 self.above[mi_c + cell][0] = state;
3011 }
3012 }
3013 }
3014
3015 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
3016 /// block whose luma was decoded as several transform units through
3017 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
3018 /// whole-block luma write -- everything [`Self::record`] does except
3019 /// plane 0, which is already correct per-TU by the time this runs.
3020 fn record_split_luma(
3021 &mut self,
3022 at: (usize, usize),
3023 side: usize,
3024 mode: usize,
3025 uv_mode: usize,
3026 chroma_grids: [&[i32]; 2],
3027 ) {
3028 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
3029 }
3030
3031 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
3032 /// extents in pixels (lane-rectsplit r1), the same relationship
3033 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
3034 /// luma transform split into several square units needs exactly this
3035 /// bookkeeping, at its own true rectangular extents.
3036 fn record_split_luma_rect(
3037 &mut self,
3038 at: (usize, usize),
3039 w: usize,
3040 h: usize,
3041 mode: usize,
3042 uv_mode: usize,
3043 chroma_grids: [&[i32]; 2],
3044 ) {
3045 let (r, c) = at;
3046 for cell in 0..w / SUB {
3047 self.above_mode[c + cell] = mode;
3048 self.above_uv_mode[c + cell] = uv_mode;
3049 self.above_side[c + cell] = w;
3050 }
3051 for cell in 0..h / SUB {
3052 self.left_mode[r + cell] = mode;
3053 self.left_uv_mode[r + cell] = uv_mode;
3054 self.left_side[r + cell] = h;
3055 }
3056 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
3057 let (w_mi, h_mi) = (w / MI, h / MI);
3058 for cell in 0..h_mi {
3059 self.left_side_mi[mi_r + cell] = h;
3060 }
3061 for cell in 0..w_mi {
3062 self.above_side_mi[mi_c + cell] = w;
3063 }
3064 let round_up_even = |n: usize| n.div_ceil(2) * 2;
3065 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
3066 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
3067 let plane = plane_idx + 1;
3068 let state = neighbour_state(grid);
3069 for cell in 0..h_mi {
3070 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
3071 self.left[mi_r + cell][plane] = state;
3072 }
3073 }
3074 for cell in 0..w_mi {
3075 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
3076 self.above[mi_c + cell][plane] = state;
3077 }
3078 }
3079 }
3080 }
3081}
3082
3083/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
3084/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
3085/// exactly — including its skip context, which the real key-frame writer
3086/// always writes at a fixed context of zero (it never tracks a neighbour-based
3087/// one for intra blocks; that is the inter-frame writer's rule instead).
3088/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
3089/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
3090/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
3091/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
3092/// plain DC chroma.
3093/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
3094/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
3095/// bound (spec `filter_intra_mode_info` never reads a symbol there).
3096fn filter_intra_size_class(side: usize) -> Option<usize> {
3097 match side {
3098 4 => Some(0),
3099 8 => Some(1),
3100 16 => Some(2),
3101 32 => Some(3),
3102 _ => None,
3103 }
3104}
3105
3106/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
3107/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
3108/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
3109/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
3110fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
3111 match (bw, bh) {
3112 (32, 16) => Some(4),
3113 (16, 32) => Some(5),
3114 _ if bw == bh => filter_intra_size_class(bw),
3115 _ => None,
3116 }
3117}
3118
3119/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
3120/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
3121/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
3122/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
3123/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
3124fn palette_bsize_ctx(side: usize) -> Option<usize> {
3125 palette_bsize_ctx_wh(side, side)
3126}
3127
3128/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
3129/// (lane-palette2 r1) -- the same `log2(bw*bh) - 6` formula, this decoder's
3130/// square call sites are just `bw == bh`.
3131fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
3132 match (bw, bh) {
3133 (8, 8) => Some(0),
3134 (16, 16) => Some(2),
3135 (32, 16) | (16, 32) => Some(3),
3136 (32, 32) => Some(4),
3137 (64, 64) => Some(6),
3138 _ => None,
3139 }
3140}
3141
3142/// A just-decoded palette-Y block's own size, base colours (only the first
3143/// `size` entries are real), and per-pixel colour-index map (`side*side`,
3144/// row-major, each entry `< size`).
3145struct PaletteY {
3146 size: usize,
3147 colors: [u16; 8],
3148 map: Vec<u8>,
3149}
3150
3151/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
3152/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
3153/// shared between U and V, both co-located after 4:2:0 subsampling) plus
3154/// each plane's own base colours.
3155struct PaletteUv {
3156 size: usize,
3157 u_colors: [u16; 8],
3158 v_colors: [u16; 8],
3159 map: Vec<u8>,
3160}
3161
3162/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
3163/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
3164/// `get_unsigned_bits`, which is the same formula): smallest `n` with
3165/// `2^n >= x`, `0` for `x <= 1`.
3166fn ceil_log2(x: u32) -> u32 {
3167 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
3168}
3169
3170/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
3171/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
3172fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
3173 let l = ceil_log2(n as u32);
3174 let m = (1usize << l) - n;
3175 let v = dec.literal(l - 1) as usize;
3176 if v < m {
3177 v
3178 } else {
3179 (v << 1) - m + dec.literal(1) as usize
3180 }
3181}
3182
3183/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
3184/// colours (already-known, from the above/left neighbours) with the
3185/// ascending `transmitted` ones (delta-coded off the wire) back into one
3186/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
3187/// value picks the cached copy first, matching the C `<=`.
3188fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
3189 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
3190 let (mut ci, mut ti) = (0, 0);
3191 while ci < cached.len() && ti < transmitted.len() {
3192 if cached[ci] <= transmitted[ti] {
3193 out.push(cached[ci]);
3194 ci += 1;
3195 } else {
3196 out.push(transmitted[ti]);
3197 ti += 1;
3198 }
3199 }
3200 out.extend_from_slice(&cached[ci..]);
3201 out.extend_from_slice(&transmitted[ti..]);
3202 out
3203}
3204
3205/// `read_palette_colors_y` (decodemv.c:478), bit_depth fixed at 8 (this
3206/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
3207/// (one flag bit each, in cache order), then delta-codes the remainder
3208/// (first value raw, each following delta `>= 1` off a shrinking bit width),
3209/// and merges the two ascending lists back together.
3210fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> [u16; 8] {
3211 let mut cached = Vec::with_capacity(n);
3212 for &c in cache {
3213 if cached.len() >= n {
3214 break;
3215 }
3216 if dec.literal(1) == 1 {
3217 cached.push(c);
3218 }
3219 }
3220 let mut colors = [0u16; 8];
3221 let n_cached = cached.len();
3222 if n_cached < n {
3223 let mut transmitted = Vec::with_capacity(n - n_cached);
3224 let first = dec.literal(8) as u16;
3225 transmitted.push(first);
3226 if n_cached + 1 < n {
3227 let min_bits = 8u32 - 3;
3228 let mut bits = min_bits + dec.literal(2);
3229 let mut range = 255i32 - i32::from(first) - 1;
3230 for _ in (n_cached + 1)..n {
3231 let delta = dec.literal(bits) as i32 + 1;
3232 let prev = *transmitted.last().unwrap();
3233 let val = (i32::from(prev) + delta).clamp(0, 255) as u16;
3234 range -= i32::from(val) - i32::from(prev);
3235 bits = bits.min(ceil_log2(range.max(0) as u32));
3236 transmitted.push(val);
3237 }
3238 }
3239 let merged = merge_colors(&transmitted, &cached);
3240 colors[..n].copy_from_slice(&merged);
3241 } else {
3242 colors[..n].copy_from_slice(&cached[..n]);
3243 }
3244 colors
3245}
3246
3247/// `read_palette_colors_uv` (decodemv.c:509), bit_depth fixed at 8: U reads
3248/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
3249/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
3250/// unbiased by `+1` -- both differences from Y's own reader, matching the C
3251/// side by side). V never uses a cache: a leading bit picks either `n` raw
3252/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
3253/// rather than clamp.
3254fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16]) -> ([u16; 8], [u16; 8]) {
3255 let mut cached = Vec::with_capacity(n);
3256 for &c in cache {
3257 if cached.len() >= n {
3258 break;
3259 }
3260 if dec.literal(1) == 1 {
3261 cached.push(c);
3262 }
3263 }
3264 let mut u_colors = [0u16; 8];
3265 let n_cached = cached.len();
3266 if n_cached < n {
3267 let mut transmitted = Vec::with_capacity(n - n_cached);
3268 let first = dec.literal(8) as u16;
3269 transmitted.push(first);
3270 if n_cached + 1 < n {
3271 let min_bits = 8u32 - 3;
3272 let mut bits = min_bits + dec.literal(2);
3273 let mut range = 255i32 - i32::from(first);
3274 for _ in (n_cached + 1)..n {
3275 let delta = dec.literal(bits) as i32;
3276 let prev = *transmitted.last().unwrap();
3277 let val = (i32::from(prev) + delta).clamp(0, 255) as u16;
3278 range -= i32::from(val) - i32::from(prev);
3279 bits = bits.min(ceil_log2(range.max(0) as u32));
3280 transmitted.push(val);
3281 }
3282 }
3283 let merged = merge_colors(&transmitted, &cached);
3284 u_colors[..n].copy_from_slice(&merged);
3285 } else {
3286 u_colors[..n].copy_from_slice(&cached[..n]);
3287 }
3288 let mut v_colors = [0u16; 8];
3289 if dec.literal(1) == 1 {
3290 let min_bits_v = 8u32 - 4;
3291 let bits = min_bits_v + dec.literal(2);
3292 v_colors[0] = dec.literal(8) as u16;
3293 for i in 1..n {
3294 let mut delta = dec.literal(bits) as i32;
3295 if delta != 0 && dec.literal(1) == 1 {
3296 delta = -delta;
3297 }
3298 let mut val = i32::from(v_colors[i - 1]) + delta;
3299 if val < 0 {
3300 val += 256;
3301 }
3302 if val >= 256 {
3303 val -= 256;
3304 }
3305 v_colors[i] = val as u16;
3306 }
3307 } else {
3308 for i in 0..n {
3309 v_colors[i] = dec.literal(8) as u16;
3310 }
3311 }
3312 (u_colors, v_colors)
3313}
3314
3315/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
3316/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
3317/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
3318const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
3319
3320/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
3321/// map's own per-pixel context and colour-order permutation, from the
3322/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
3323/// selection sort). `map`'s stride is `side` (this decoder never crops a
3324/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
3325/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
3326/// actual colour index to store.
3327fn palette_color_index_context(
3328 map: &[u8],
3329 side: usize,
3330 row: usize,
3331 col: usize,
3332 n: usize,
3333) -> (usize, [u8; 8]) {
3334 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
3335 let up_left = if col >= 1 && row >= 1 {
3336 Some(map[(row - 1) * side + col - 1])
3337 } else {
3338 None
3339 };
3340 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
3341 let mut scores = [0i32; 8];
3342 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
3343 if let Some(v) = neighbour {
3344 scores[v as usize] += weight;
3345 }
3346 }
3347 let mut color_order = [0u8; 8];
3348 for i in 0..8 {
3349 color_order[i] = i as u8;
3350 }
3351 for i in 0..3 {
3352 let mut max = scores[i];
3353 let mut max_idx = i;
3354 for j in (i + 1)..n {
3355 if scores[j] > max {
3356 max = scores[j];
3357 max_idx = j;
3358 }
3359 }
3360 if max_idx != i {
3361 let max_score = scores[max_idx];
3362 let max_color = color_order[max_idx];
3363 for k in (i + 1..=max_idx).rev() {
3364 scores[k] = scores[k - 1];
3365 color_order[k] = color_order[k - 1];
3366 }
3367 scores[i] = max_score;
3368 color_order[i] = max_color;
3369 }
3370 }
3371 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
3372 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
3373 (ctx as usize, color_order)
3374}
3375
3376/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
3377/// map's wavefront decode over a `side x side` grid -- this decoder's
3378/// palette blocks are always square and never straddle the frame's true
3379/// (possibly odd) edge without already allocating the full `side*side`
3380/// region (every other skip/residual path here does the same), so no
3381/// rows/cols-vs-plane_width/height cropping special case is needed, unlike
3382/// libaom's own non-block-aligned split.
3383fn decode_color_index_map(
3384 dec: &mut SymbolDecoder,
3385 cdfs: &mut Cdfs,
3386 n: usize,
3387 side: usize,
3388 uv: bool,
3389) -> Vec<u8> {
3390 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
3391 let mut map = vec![0u8; side * side];
3392 if trace {
3393 let (rng, _) = dec.debug_state();
3394 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
3395 }
3396 map[0] = read_uniform(dec, n) as u8;
3397 if trace {
3398 let (rng, _) = dec.debug_state();
3399 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
3400 }
3401 for i in 1..(2 * side - 1) {
3402 let j_hi = i.min(side - 1);
3403 let j_lo = i.saturating_sub(side - 1);
3404 for j in (j_lo..=j_hi).rev() {
3405 let row = i - j;
3406 let col = j;
3407 let (ctx, color_order) = palette_color_index_context(&map, side, row, col, n);
3408 if trace {
3409 let (rng, _) = dec.debug_state();
3410 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} rng={rng}");
3411 }
3412 let symbol = if uv {
3413 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
3414 } else {
3415 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
3416 };
3417 map[row * side + col] = color_order[symbol];
3418 if trace {
3419 let (rng, _) = dec.debug_state();
3420 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
3421 }
3422 }
3423 }
3424 map
3425}
3426
3427/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
3428/// identical except the `use_filter_intra` size class comes from
3429/// [`filter_intra_size_class_rect`] instead of the square-only
3430/// [`filter_intra_size_class`] -- every other symbol this reads (`skip`,
3431/// `y_mode`, `angle_delta`, `uv_mode`, `cfl_alphas`) is indexed by mode or
3432/// neighbour state, never by block size.
3433#[allow(clippy::too_many_arguments)]
3434fn read_intra_mode_rect(
3435 dec: &mut SymbolDecoder,
3436 cdfs: &mut Cdfs,
3437 above_mode: usize,
3438 left_mode: usize,
3439 cfl: bool,
3440 bw: usize,
3441 bh: usize,
3442 enable_filter_intra: bool,
3443 skip_ctx: usize,
3444 allow_screen_content_tools: bool,
3445 mi_r: usize,
3446 mi_c: usize,
3447) -> Result<(
3448 bool,
3449 usize,
3450 i32,
3451 usize,
3452 i32,
3453 Option<(i32, i32)>,
3454 Option<usize>,
3455)> {
3456 // lane-screen consumes palette/intrabc syntax in the SQUARE reader only
3457 // (`palette_bsize_ctx` is keyed on a single side). A rect strip in a
3458 // screen-content frame would therefore skip symbols the encoder wrote and
3459 // desync the tile, so refuse it by name rather than decode it wrong.
3460 if allow_screen_content_tools {
3461 return Err(unsupported(
3462 "a HORZ/VERT intra strip in a screen-content frame (palette syntax \
3463 is consumed for square blocks only)",
3464 ));
3465 }
3466 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
3467 macro_rules! istep {
3468 ($name:literal, $val:expr) => {
3469 if ec_istep {
3470 let (rng, _) = dec.debug_state();
3471 eprintln!(
3472 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
3473 $name, $val
3474 );
3475 }
3476 };
3477 }
3478 // Same `intra_segment_id` placement as the square reader above.
3479 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
3480 if seg_id_pre_skip() {
3481 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
3482 }
3483 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
3484 istep!("skip", skip as i32);
3485 if !seg_id_pre_skip() {
3486 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
3487 }
3488 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
3489 istep!("cdef", 0);
3490 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
3491 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
3492 // `false`.
3493 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip);
3494 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip);
3495 istep!("dq", 0);
3496 let above_ctx = INTRA_MODE_CTX[above_mode];
3497 let left_ctx = INTRA_MODE_CTX[left_mode];
3498 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
3499 istep!("mode", mode as i32);
3500 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
3501 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
3502 } else {
3503 0
3504 };
3505 istep!("angle_y", angle_delta_y);
3506 let uv_mode = if cfl {
3507 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
3508 } else {
3509 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
3510 };
3511 istep!("uv_mode", uv_mode as i32);
3512 let alpha = if cfl && uv_mode == UV_CFL_PRED {
3513 Some(read_cfl_alphas(dec, cdfs))
3514 } else {
3515 None
3516 };
3517 if (9..=12).contains(&uv_mode) {
3518 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
3519 }
3520 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
3521 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
3522 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
3523 } else {
3524 0
3525 };
3526 istep!("angle_uv", angle_delta_uv);
3527 let mut filter_intra = None;
3528 if std::env::var_os("EC_AV1_TRACE").is_some() {
3529 let (rng, _) = dec.debug_state();
3530 eprintln!(
3531 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
3532 class={:?} rng={rng}",
3533 enable_filter_intra as i32,
3534 filter_intra_size_class_rect(bw, bh)
3535 );
3536 }
3537 if mode == DC_PRED
3538 && enable_filter_intra
3539 && let Some(class) = filter_intra_size_class_rect(bw, bh)
3540 {
3541 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
3542 if std::env::var_os("EC_AV1_TRACE").is_some() {
3543 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
3544 }
3545 if use_filter_intra {
3546 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
3547 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
3548 filter_intra = Some(fi_mode);
3549 }
3550 }
3551 Ok((
3552 skip,
3553 mode,
3554 angle_delta_y,
3555 uv_mode,
3556 angle_delta_uv,
3557 alpha,
3558 filter_intra,
3559 ))
3560}
3561
3562/// [`tx_size_context`] for a true `bw`x`bh` rect strip (lane-intradisp r1):
3563/// `get_tx_size_context` (libaom `pred_common.h`) compares the neighbour
3564/// above against this block's own *width* and the neighbour to the left
3565/// against its own *height* -- for a square block those are the same value,
3566/// which is why the square-only version can get away with one `own_side`.
3567fn tx_size_context_rect(
3568 n: &Neighbours,
3569 (mi_r, mi_c): (usize, usize),
3570 own_w: usize,
3571 own_h: usize,
3572) -> usize {
3573 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w;
3574 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h;
3575 usize::from(above) + usize::from(left)
3576}
3577
3578/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
3579fn cfl_ac_q3_rect(y: &PlaneBuf, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
3580 let (cw, ch) = (bw / 2, bh / 2);
3581 let mut ac = vec![0i32; cw * ch];
3582 let mut sum = 0i32;
3583 for cy in 0..ch {
3584 for cx in 0..cw {
3585 let (lx, ly) = (px + cx * 2, py + cy * 2);
3586 let q3 = (i32::from(y.data[ly * y.width + lx])
3587 + i32::from(y.data[ly * y.width + lx + 1])
3588 + i32::from(y.data[(ly + 1) * y.width + lx])
3589 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
3590 << 1;
3591 ac[cy * cw + cx] = q3;
3592 sum += q3;
3593 }
3594 }
3595 let num_pel = (cw * ch) as i32;
3596 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
3597 ac.iter_mut().for_each(|v| *v -= avg);
3598 ac
3599}
3600
3601/// Everything a rect strip already read out of the stream before its luma
3602/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
3603/// (nine values that would otherwise be nine more parameters).
3604struct RectStripModes {
3605 skip: bool,
3606 mode: usize,
3607 angle_delta_y: i32,
3608 uv_predict_mode: usize,
3609 angle_delta_uv: i32,
3610 alpha: Option<(i32, i32)>,
3611 filter_intra: Option<usize>,
3612 smooth_neighbor: bool,
3613 smooth_neighbor_uv: bool,
3614}
3615
3616/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
3617/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
3618/// rect path here refused by name until now ("per-unit rect prediction is not
3619/// ported").
3620///
3621/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
3622/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
3623/// strip the very first step already lands on a SQUARE transform
3624/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
3625/// every further step halves a square) -- so each unit is square and reads
3626/// through the ordinary square [`read_plane`]. What is genuinely rectangular
3627/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
3628/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
3629/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
3630/// split by luma's depth.
3631///
3632/// Each unit predicts off whatever the earlier units of this same block
3633/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
3634/// inside `av1_foreach_transformed_block`, raster order), which is exactly
3635/// what predicting the whole strip in one shot got wrong.
3636#[allow(clippy::too_many_arguments)]
3637fn decode_rect_split(
3638 dec: &mut SymbolDecoder,
3639 cdfs: &mut Cdfs,
3640 neighbours: &mut Neighbours,
3641 at: (usize, usize),
3642 bw: usize,
3643 bh: usize,
3644 tx: usize,
3645 m: &RectStripModes,
3646 y: &mut PlaneBuf,
3647 u: &mut PlaneBuf,
3648 v: &mut PlaneBuf,
3649 base_q_idx: u8,
3650 reduced_tx_set: bool,
3651) -> Result<()> {
3652 let (r, c) = at;
3653 let (px, py) = (c * SUB, r * SUB);
3654 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
3655 let (cpx, cpy) = (px / 2, py / 2);
3656 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
3657 // The chroma transform is picked before any symbol is read, so an
3658 // unsupported chroma shape refuses before this strip desyncs the tile.
3659 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
3660 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
3661 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
3662 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
3663 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
3664 _ => None,
3665 };
3666 if !m.skip && chroma.is_none() {
3667 return Err(unsupported(
3668 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
3669 ));
3670 }
3671 RECT_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1));
3672 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
3673 let luma_set = txbset_for(tx, reduced_tx_set);
3674 let luma_scan = default_scan(tx);
3675 let zero_tu = vec![0i32; tx * tx];
3676 // The strip's OWN edge availability, the fallback for a transform unit
3677 // whose top-right/bottom-left pixels fall outside the strip.
3678 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
3679 for tu_row in 0..bh / tx {
3680 for tu_col in 0..bw / tx {
3681 let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI));
3682 let (tu_px, tu_py) = (px + tu_col * tx, py + tu_row * tx);
3683 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
3684 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
3685 // transform unit INSIDE a block, which is a different rule from
3686 // the standalone-block table [`Reach::of`] applies -- and the
3687 // reason a depth-2 superblock strip came out one sample off
3688 // before this: `Reach::of(tx, ..)` answered as if the unit were
3689 // its own block at that superblock position.
3690 // * top-right: if the unit's right neighbour is still inside the
3691 // strip the pixels are already reconstructed (`col_off +
3692 // tx_wide < plane_bw`); otherwise only the strip's own top row
3693 // of units can reach past it, through the block-level answer.
3694 // * bottom-left: a unit that is not in the strip's left column
3695 // has none (`col_off > 0` returns 0); inside the strip
3696 // (`row_off + tx_high < plane_bh`) they are the left
3697 // neighbour's, already reconstructed; the last row falls back
3698 // to the block-level answer.
3699 let tu_reach = Reach {
3700 above_right: if col_off + tx < bw {
3701 true
3702 } else {
3703 row_off == 0 && block_reach.above_right
3704 },
3705 below_left: if col_off > 0 {
3706 false
3707 } else if row_off + tx < bh {
3708 true
3709 } else {
3710 block_reach.below_left
3711 },
3712 };
3713 if m.skip {
3714 y.reconstruct(
3715 tu_px,
3716 tu_py,
3717 tx,
3718 m.mode,
3719 m.angle_delta_y,
3720 tu_reach,
3721 &zero_tu,
3722 None,
3723 m.filter_intra,
3724 m.smooth_neighbor,
3725 );
3726 neighbours.record_mi_luma(tu_mi, tx, &zero_tu);
3727 } else {
3728 let tu_around = neighbours.around_mi(tu_mi, tx)[0];
3729 // This unit is smaller than the block it sits in, so
3730 // `txb_skip_ctx` is the neighbour-magnitude table, not the
3731 // lone-TU 0 (spec `get_txb_ctx_general`).
3732 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx / MI);
3733 let tu_grid = read_plane(
3734 dec,
3735 cdfs,
3736 luma_set,
3737 &luma_scan,
3738 0,
3739 tu_around,
3740 m.mode,
3741 m.mode,
3742 m.angle_delta_y,
3743 tu_reach,
3744 y,
3745 tu_px,
3746 tu_py,
3747 tx,
3748 tx,
3749 base_q_idx,
3750 None,
3751 m.filter_intra,
3752 Some(tu_skip_ctx),
3753 m.smooth_neighbor,
3754 )?;
3755 neighbours.record_mi_luma(tu_mi, tx, &tu_grid);
3756 }
3757 }
3758 }
3759 // CHROMA: one un-split rect transform for the whole strip.
3760 let ac = m.alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
3761 let reach = block_reach;
3762 let (u_grid, v_grid) = if m.skip {
3763 let zero = vec![0i32; chroma_w * chroma_h];
3764 u.reconstruct_rect(
3765 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
3766 m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv,
3767 );
3768 v.reconstruct_rect(
3769 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
3770 m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv,
3771 );
3772 (zero.clone(), zero)
3773 } else {
3774 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
3775 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
3776 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
3777 // so only the 16x8/8x16 pair takes the mode-indexed default.
3778 let default_tx = if chroma_w.max(chroma_h) >= 32 {
3779 TxType::DctDct
3780 } else {
3781 default_intra_tx_type(m.uv_predict_mode as u8)
3782 };
3783 let around = neighbours.around_rect(at, bw, bh);
3784 let mut grids: Vec<Vec<i32>> = Vec::with_capacity(2);
3785 for plane_idx in 1..=2 {
3786 let skip_ctx =
3787 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
3788 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
3789 let (levels, tx_type) = read_coeffs_rect(
3790 dec,
3791 &mut coding,
3792 chroma_scan,
3793 chroma_w,
3794 chroma_h,
3795 skip_ctx,
3796 dc_sign_ctx(around[plane_idx].2),
3797 default_tx,
3798 )?;
3799 let residual = dequant_and_inverse_typed_wh(
3800 &levels,
3801 chroma_w,
3802 chroma_h,
3803 crate::decode::bit_depth(),
3804 CURRENT_Q_IDX.with(|c| c.get()),
3805 plane_q_delta(plane_idx).0,
3806 plane_q_delta(plane_idx).1,
3807 tx_type,
3808 );
3809 let cfl = m
3810 .alpha
3811 .zip(ac.as_deref())
3812 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
3813 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
3814 plane.reconstruct_rect(
3815 cpx,
3816 cpy,
3817 chroma_w,
3818 chroma_h,
3819 m.uv_predict_mode,
3820 m.angle_delta_uv,
3821 reach,
3822 &residual,
3823 cfl,
3824 None,
3825 m.smooth_neighbor_uv,
3826 );
3827 grids.push(levels);
3828 }
3829 let mut it = grids.into_iter();
3830 (it.next().unwrap(), it.next().unwrap())
3831 };
3832 neighbours.record_split_luma_rect(at, bw, bh, m.mode, m.uv_predict_mode, [&u_grid, &v_grid]);
3833 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
3834 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx as u8, tx as u8, 0);
3835 if std::env::var_os("EC_AV1_TRACE").is_some() {
3836 let (rng, _) = dec.debug_state();
3837 eprintln!(
3838 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} tx={tx} rng={rng}"
3839 );
3840 }
3841 Ok(())
3842}
3843
3844/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
3845/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
3846/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
3847/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
3848/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
3849/// has no rectangular-transform coefficient reader, and a chroma plane here
3850/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
3851/// with no depth-based square-tiling escape the way luma's own resolved
3852/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
3853/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
3854#[allow(clippy::too_many_arguments)]
3855fn decode_block_rect(
3856 dec: &mut SymbolDecoder,
3857 cdfs: &mut Cdfs,
3858 neighbours: &mut Neighbours,
3859 at: (usize, usize),
3860 bw: usize,
3861 bh: usize,
3862 y: &mut PlaneBuf,
3863 u: &mut PlaneBuf,
3864 v: &mut PlaneBuf,
3865 enable_filter_intra: bool,
3866 allow_screen_content_tools: bool,
3867 base_q_idx: u8,
3868 tx_select: bool,
3869 reduced_tx_set: bool,
3870) -> Result<()> {
3871 let (r, c) = at;
3872 let (px, py) = (c * SUB, r * SUB);
3873 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
3874 read_intra_mode_rect(
3875 dec,
3876 cdfs,
3877 neighbours.above_mode[c],
3878 neighbours.left_mode[r],
3879 true,
3880 bw,
3881 bh,
3882 enable_filter_intra,
3883 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
3884 allow_screen_content_tools,
3885 r * (SUB / MI),
3886 c * (SUB / MI),
3887 )?;
3888 let smooth_neighbor =
3889 is_smooth_mode(neighbours.above_mode[c]) || is_smooth_mode(neighbours.left_mode[r]);
3890 if smooth_neighbor {
3891 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
3892 }
3893 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
3894 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
3895 // `uv_mode`, not the luma one.
3896 let smooth_neighbor_uv =
3897 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
3898 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
3899 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
3900 // rectangle just as happily), so a `use_filter_intra` strip at this level
3901 // predicts instead of refusing. The below-16x16 leaf arm
3902 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
3903 if filter_intra.is_some() {
3904 FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
3905 }
3906 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
3907 DC_PRED
3908 } else {
3909 uv_mode
3910 };
3911 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
3912 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
3913 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
3914 // one did not, so with `--enable-tx-size-search=0` -- which several gate
3915 // recipes use -- the decoder consumed a symbol the encoder never wrote and
3916 // desynced the tile from that point on. That is why both strips of the
3917 // pinned HORZ quadrant were wrong from their very first pixel, and why our
3918 // range after the read equalled the oracle's range for the whole block.
3919 let depth = if tx_select {
3920 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
3921 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
3922 } else {
3923 0
3924 };
3925 if depth != 0 {
3926 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
3927 // lane-rectsplit r1: a split transform is predicted and reconstructed
3928 // per transform unit, each unit taking its edges from the previous
3929 // unit's reconstruction inside this same strip (spec 5.11.36) --
3930 // [`decode_rect_split`]. `depth_to_tx_size` of a 2:1 strip is square
3931 // from the first step on, so `bw.min(bh) >> (depth - 1)` names it.
3932 let tx = bw.min(bh) >> (depth - 1);
3933 let modes = RectStripModes {
3934 skip,
3935 mode,
3936 angle_delta_y,
3937 uv_predict_mode,
3938 angle_delta_uv,
3939 alpha,
3940 filter_intra,
3941 smooth_neighbor,
3942 smooth_neighbor_uv,
3943 };
3944 decode_rect_split(
3945 dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set,
3946 )?;
3947 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
3948 return Ok(());
3949 }
3950 let (tx_w, tx_h) = (bw, bh);
3951 let (cpx, cpy) = (px / 2, py / 2);
3952 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
3953 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
3954 if std::env::var_os("EC_AV1_TRACE").is_some() {
3955 let (rng, _) = dec.debug_state();
3956 eprintln!(
3957 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
3958 skip={} tx={depth} rng={rng}",
3959 skip as i32
3960 );
3961 }
3962 if skip {
3963 y.reconstruct_rect(
3964 px,
3965 py,
3966 bw,
3967 bh,
3968 mode,
3969 angle_delta_y,
3970 reach,
3971 &vec![0i32; bw * bh],
3972 None,
3973 filter_intra,
3974 smooth_neighbor,
3975 );
3976 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
3977 u.reconstruct_rect(
3978 cpx,
3979 cpy,
3980 chroma_w,
3981 chroma_h,
3982 uv_predict_mode,
3983 angle_delta_uv,
3984 reach,
3985 &vec![0i32; chroma_w * chroma_h],
3986 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
3987 None,
3988 smooth_neighbor_uv,
3989 );
3990 v.reconstruct_rect(
3991 cpx,
3992 cpy,
3993 chroma_w,
3994 chroma_h,
3995 uv_predict_mode,
3996 angle_delta_uv,
3997 reach,
3998 &vec![0i32; chroma_w * chroma_h],
3999 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
4000 None,
4001 smooth_neighbor_uv,
4002 );
4003 neighbours.record_rect(
4004 at,
4005 bw,
4006 bh,
4007 mode,
4008 uv_predict_mode,
4009 &[
4010 vec![0i32; bw * bh],
4011 vec![0i32; chroma_w * chroma_h],
4012 vec![0i32; chroma_w * chroma_h],
4013 ],
4014 );
4015 } else if (bw, bh) != (32, 16) && (bw, bh) != (16, 32) {
4016 // lane-rect16 r1: a real (non-skip) coefficient read at this size
4017 // (8x16/16x32 VERT_B's own left strip) is not ported -- it needs its
4018 // own `TxbSet`/`eob_pt` tables (a true 128-position luma group has no
4019 // `EOB_PT_128_LUMA` in this decoder yet, only the *chroma* one
4020 // `lane-rectwire` built for `ChromaRect16x8`) and, unlike the 32x32
4021 // sqr-up case `LumaRect32x16` safely skips, `get_ext_tx_set_type`
4022 // does NOT return `EXT_TX_SET_DCTONLY` at a 16x16 sqr-up under this
4023 // encoder's reduced_tx_set -- a real `tx_type` symbol may be coded
4024 // that no table here reads. Refused by name rather than guess-decoded
4025 // or silently desynced.
4026 return Err(unsupported(
4027 "a coded (non-skip) HORZ_B/VERT_B rect strip below 16x16 (this decoder ports only \
4028 the skip case at this size)",
4029 ));
4030 } else {
4031 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
4032 // reduces both size pairs to their square-up CDF sets
4033 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
4034 // doc comments); the scan order and 2D context tables are the real
4035 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
4036 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
4037 (&SCAN_32X16, &SCAN_16X8)
4038 } else {
4039 (&SCAN_16X32, &SCAN_8X16)
4040 };
4041 // lane-rectwire r3: real coefficients desync a pixel-exact gate
4042 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
4043 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
4044 // pixel (not a subtle context-table off-by-one), while the sibling
4045 // non-rect quadrants of the same frame match. Range-ladder bisection
4046 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
4047 // but the intra key-frame path has no traced symbol between the
4048 // partition read and the first coefficient block (mode/skip/tx_depth
4049 // reads are all untraced in libaom's decodeframe.c intra path, unlike
4050 // the inter EC_TRACE_MODE this round added), so a same-length range
4051 // comparison wasn't reachable within budget -- see
4052 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
4053 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
4054 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
4055 // libaom and match). lane-rectwire r4: range-ladder against the
4056 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
4057 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
4058 // both confirmed in sync -- rng=58692 on both sides right after
4059 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
4060 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
4061 // immediately after: ours moves rng 58692 -> 43570, which cannot be
4062 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
4063 // its own tx_size read) unless oracle's tx symbol is a near-certainty
4064 // CDF that barely narrows the range -- i.e. this decoder's
4065 // `tx_size_context_rect` ctx or `cdfs.tx_size_cat2` CDF selection for
4066 // a 32x16/16x32 strip is the first diverging symbol, not the
4067 // coefficient-context math r3 already cleared. Not confirmed byte-
4068 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
4069 // `read_tx_size`'s own rng, not attempted this round -- budget), so
4070 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
4071 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
4072 // it unconditionally where both square paths gate on `tx_select`. With
4073 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
4074 // decoder consumed one that was never there.
4075 {
4076 let around = neighbours.around_rect(at, bw, bh);
4077 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
4078 let (luma_levels, luma_tx_type) = read_coeffs_rect(
4079 dec,
4080 &mut luma_coding,
4081 luma_scan,
4082 bw,
4083 bh,
4084 0,
4085 dc_sign_ctx(around[0].2),
4086 TxType::DctDct,
4087 )?;
4088 if std::env::var_os("EC_AV1_TRACE").is_some() {
4089 let (rng, _) = dec.debug_state();
4090 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
4091 }
4092 let luma_residual = dequant_and_inverse_typed_wh(
4093 &luma_levels,
4094 bw,
4095 bh,
4096 crate::decode::bit_depth(),
4097 block_q_idx(),
4098 plane_q_delta(0).0,
4099 plane_q_delta(0).1,
4100 luma_tx_type,
4101 );
4102 y.reconstruct_rect(
4103 px,
4104 py,
4105 bw,
4106 bh,
4107 mode,
4108 angle_delta_y,
4109 reach,
4110 &luma_residual,
4111 None,
4112 filter_intra,
4113 smooth_neighbor,
4114 );
4115 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
4116 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
4117 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
4118 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
4119 let (u_levels, u_tx_type) = read_coeffs_rect(
4120 dec,
4121 &mut u_coding,
4122 chroma_scan,
4123 chroma_w,
4124 chroma_h,
4125 u_skip_ctx,
4126 dc_sign_ctx(around[1].2),
4127 u_default_tx,
4128 )?;
4129 if std::env::var_os("EC_AV1_TRACE").is_some() {
4130 let (rng, _) = dec.debug_state();
4131 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
4132 }
4133 let u_residual = dequant_and_inverse_typed_wh(
4134 &u_levels,
4135 chroma_w,
4136 chroma_h,
4137 crate::decode::bit_depth(),
4138 block_q_idx(),
4139 plane_q_delta(1).0,
4140 plane_q_delta(1).1,
4141 u_tx_type,
4142 );
4143 u.reconstruct_rect(
4144 cpx,
4145 cpy,
4146 chroma_w,
4147 chroma_h,
4148 uv_predict_mode,
4149 angle_delta_uv,
4150 reach,
4151 &u_residual,
4152 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
4153 None,
4154 smooth_neighbor_uv,
4155 );
4156 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
4157 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
4158 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
4159 let (v_levels, v_tx_type) = read_coeffs_rect(
4160 dec,
4161 &mut v_coding,
4162 chroma_scan,
4163 chroma_w,
4164 chroma_h,
4165 v_skip_ctx,
4166 dc_sign_ctx(around[2].2),
4167 v_default_tx,
4168 )?;
4169 if std::env::var_os("EC_AV1_TRACE").is_some() {
4170 let (rng, _) = dec.debug_state();
4171 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
4172 }
4173 let v_residual = dequant_and_inverse_typed_wh(
4174 &v_levels,
4175 chroma_w,
4176 chroma_h,
4177 crate::decode::bit_depth(),
4178 block_q_idx(),
4179 plane_q_delta(2).0,
4180 plane_q_delta(2).1,
4181 v_tx_type,
4182 );
4183 v.reconstruct_rect(
4184 cpx,
4185 cpy,
4186 chroma_w,
4187 chroma_h,
4188 uv_predict_mode,
4189 angle_delta_uv,
4190 reach,
4191 &v_residual,
4192 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
4193 None,
4194 smooth_neighbor_uv,
4195 );
4196 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
4197 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
4198 }
4199 }
4200 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
4201 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
4202 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
4203 if std::env::var_os("EC_AV1_TRACE").is_some() {
4204 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
4205 }
4206 Ok(())
4207}
4208
4209/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
4210/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
4211/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
4212/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
4213/// the second strip of a HORZ/VERT split sits offset by half the 16x16
4214/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
4215/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
4216/// previous strip is directly above (same column, `mi_h` rows up) or
4217/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
4218/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
4219/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
4220/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
4221/// this strip's real position, never the coarse `record_rect` (which the
4222/// caller uses once, after both strips, exactly like the `VERT_B` arm next
4223/// to it). Only the skip case is ported -- see [`decode_block_rect`]'s own
4224/// doc for why a coded rect strip below 16x16 has no coefficient tables here
4225/// yet.
4226#[allow(clippy::too_many_arguments)]
4227fn decode_leaf_rect(
4228 dec: &mut SymbolDecoder,
4229 cdfs: &mut Cdfs,
4230 neighbours: &mut Neighbours,
4231 outer_at: (usize, usize),
4232 leaf_mi: (usize, usize),
4233 bw: usize,
4234 bh: usize,
4235 prev_leaf: Option<((usize, usize), usize)>,
4236 y: &mut PlaneBuf,
4237 u: &mut PlaneBuf,
4238 v: &mut PlaneBuf,
4239 enable_filter_intra: bool,
4240 allow_screen_content_tools: bool,
4241 base_q_idx: u8,
4242 tx_select: bool,
4243) -> Result<usize> {
4244 let _ = base_q_idx;
4245 let (r, c) = outer_at;
4246 let mut above_mode = neighbours.above_mode[c];
4247 let mut left_mode = neighbours.left_mode[r];
4248 let (mi_w, mi_h) = (bw / MI, bh / MI);
4249 if let Some(((pr, pc), pmode)) = prev_leaf {
4250 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
4251 above_mode = pmode;
4252 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
4253 left_mode = pmode;
4254 }
4255 }
4256 let smooth_neighbor =
4257 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
4258 if smooth_neighbor {
4259 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
4260 }
4261 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
4262 read_intra_mode_rect(
4263 dec,
4264 cdfs,
4265 above_mode,
4266 left_mode,
4267 true,
4268 bw,
4269 bh,
4270 enable_filter_intra,
4271 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
4272 allow_screen_content_tools,
4273 leaf_mi.0,
4274 leaf_mi.1,
4275 )?;
4276 if filter_intra.is_some() {
4277 return Err(unsupported(
4278 "filter intra on a HORZ/VERT strip (this decoder predicts square-only)",
4279 ));
4280 }
4281 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
4282 let depth = if tx_select {
4283 let ctx = tx_size_context_rect(neighbours, leaf_mi, bw, bh);
4284 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
4285 } else {
4286 0
4287 };
4288 if depth != 0 {
4289 return Err(unsupported(
4290 "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect \
4291 prediction is not ported)",
4292 ));
4293 }
4294 if !skip {
4295 return Err(unsupported(
4296 "a coded (non-skip) HORZ/VERT rect strip below 16x16 (this decoder ports only \
4297 the skip case at this size)",
4298 ));
4299 }
4300 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
4301 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
4302 let (cpx, cpy) = (px / 2, py / 2);
4303 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
4304 y.reconstruct_rect(
4305 px,
4306 py,
4307 bw,
4308 bh,
4309 mode,
4310 angle_delta_y,
4311 reach,
4312 &vec![0i32; bw * bh],
4313 None,
4314 filter_intra,
4315 smooth_neighbor,
4316 );
4317 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
4318 u.reconstruct_rect(
4319 cpx,
4320 cpy,
4321 chroma_w,
4322 chroma_h,
4323 uv_predict_mode,
4324 angle_delta_uv,
4325 reach,
4326 &vec![0i32; chroma_w * chroma_h],
4327 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
4328 None,
4329 false,
4330 );
4331 v.reconstruct_rect(
4332 cpx,
4333 cpy,
4334 chroma_w,
4335 chroma_h,
4336 uv_predict_mode,
4337 angle_delta_uv,
4338 reach,
4339 &vec![0i32; chroma_w * chroma_h],
4340 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
4341 None,
4342 false,
4343 );
4344 neighbours.record_mi_rect(
4345 leaf_mi,
4346 bw,
4347 bh,
4348 &[
4349 vec![0i32; bw * bh],
4350 vec![0i32; chroma_w * chroma_h],
4351 vec![0i32; chroma_w * chroma_h],
4352 ],
4353 );
4354 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
4355 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0);
4356 Ok(mode)
4357}
4358
4359/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
4360/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
4361/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
4362/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
4363/// cap, so LUMA needs the same corner truncation [`decode_block`] already
4364/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
4365/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
4366/// this function's own charter/report), so both strips read a real 32x32
4367/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
4368/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
4369/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
4370/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
4371/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
4372/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
4373/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
4374/// that function, only the single-transform-unit (`tx_depth == 0`) case is
4375/// supported: a split transform refuses by name rather than guess-decode.
4376#[allow(clippy::too_many_arguments)]
4377fn decode_block_rect64(
4378 dec: &mut SymbolDecoder,
4379 cdfs: &mut Cdfs,
4380 neighbours: &mut Neighbours,
4381 at: (usize, usize),
4382 bw: usize,
4383 bh: usize,
4384 y: &mut PlaneBuf,
4385 u: &mut PlaneBuf,
4386 v: &mut PlaneBuf,
4387 enable_filter_intra: bool,
4388 allow_screen_content_tools: bool,
4389 base_q_idx: u8,
4390 tx_select: bool,
4391 reduced_tx_set: bool,
4392) -> Result<()> {
4393 let (r, c) = at;
4394 let (px, py) = (c * SUB, r * SUB);
4395 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) =
4396 read_intra_mode_rect(
4397 dec,
4398 cdfs,
4399 neighbours.above_mode[c],
4400 neighbours.left_mode[r],
4401 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
4402 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
4403 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
4404 // correct), CFL must never be offered here -- passing `true`
4405 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
4406 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
4407 // from this block's very first symbol (lane-sbpart r3 bisect).
4408 false,
4409 bw,
4410 bh,
4411 enable_filter_intra,
4412 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
4413 allow_screen_content_tools,
4414 r * (SUB / MI),
4415 c * (SUB / MI),
4416 )?;
4417 let smooth_neighbor =
4418 is_smooth_mode(neighbours.above_mode[c]) || is_smooth_mode(neighbours.left_mode[r]);
4419 if smooth_neighbor {
4420 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
4421 }
4422 let smooth_neighbor_uv =
4423 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
4424 if filter_intra.is_some() {
4425 // `filter_intra_size_class_rect` already returns `None` for both
4426 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
4427 // 32 on both axes), so this symbol is never read at this level --
4428 // kept only as the same defensive refusal [`decode_block_rect`] has.
4429 return Err(unsupported(
4430 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
4431 av1_filter_intra_allowed_bsize caps at 32x32)",
4432 ));
4433 }
4434 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
4435 DC_PRED
4436 } else {
4437 uv_mode
4438 };
4439 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
4440 let depth = if tx_select {
4441 let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh);
4442 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
4443 // counts `sub_tx_size_map` steps from the block's own max rect
4444 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
4445 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
4446 // steps, so this level's category is 3 (the same one a 64x64 square
4447 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
4448 // here was a wrong-table read of a real symbol.
4449 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
4450 } else {
4451 0
4452 };
4453 if depth != 0 {
4454 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
4455 // lane-rectsplit r1: [`decode_rect_split`] handles this shape too
4456 // (`sub_tx_size_map[TX_64X32]` is `TX_32X32`, so a depth-1 unit here
4457 // is a plain square 32x32) and its 32x32-level sibling arm in
4458 // [`decode_block_rect`] is gated pixel-exact -- but at the SUPERBLOCK
4459 // level the gate
4460 // (`a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact`,
4461 // `#[ignore]`d with its measurement) still comes out ONE sample off
4462 // (seed 50, luma (171,56) ours 147 vs ffmpeg 148, inside a 64x32
4463 // strip whose transform resolved to depth 2 / TX_16X16). A refusal
4464 // this lane could not lift is not a refusal it may silently ship
4465 // wrong pixels past, so the named refusal stays until that gate is
4466 // green.
4467 return Err(unsupported(
4468 "a superblock-level HORZ/VERT strip with a split transform (per-unit rect \
4469 prediction is not ported)",
4470 ));
4471 }
4472 let (tx_w, tx_h) = (bw, bh);
4473 let (cpx, cpy) = (px / 2, py / 2);
4474 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
4475 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height);
4476 if skip {
4477 y.reconstruct_rect(
4478 px,
4479 py,
4480 bw,
4481 bh,
4482 mode,
4483 angle_delta_y,
4484 reach,
4485 &vec![0i32; bw * bh],
4486 None,
4487 filter_intra,
4488 smooth_neighbor,
4489 );
4490 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
4491 u.reconstruct_rect(
4492 cpx,
4493 cpy,
4494 chroma_w,
4495 chroma_h,
4496 uv_predict_mode,
4497 angle_delta_uv,
4498 reach,
4499 &vec![0i32; chroma_w * chroma_h],
4500 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
4501 None,
4502 smooth_neighbor_uv,
4503 );
4504 v.reconstruct_rect(
4505 cpx,
4506 cpy,
4507 chroma_w,
4508 chroma_h,
4509 uv_predict_mode,
4510 angle_delta_uv,
4511 reach,
4512 &vec![0i32; chroma_w * chroma_h],
4513 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
4514 None,
4515 smooth_neighbor_uv,
4516 );
4517 neighbours.record_rect(
4518 at,
4519 bw,
4520 bh,
4521 mode,
4522 uv_predict_mode,
4523 &[
4524 vec![0i32; bw * bh],
4525 vec![0i32; chroma_w * chroma_h],
4526 vec![0i32; chroma_w * chroma_h],
4527 ],
4528 );
4529 } else {
4530 let around = neighbours.around_rect(at, bw, bh);
4531 // LUMA: a real 32x32 corner, embedded top-left of the true bw x bh
4532 // grid (see this function's own doc comment).
4533 let scan32 = default_scan(TX32);
4534 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
4535 if std::env::var_os("EC_TRACE_COEFF").is_some() {
4536 let (rng, _) = dec.debug_state();
4537 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size=64corner rng={rng}");
4538 }
4539 let (luma_corner, luma_tx_type) = read_coeffs(
4540 dec,
4541 &mut luma_coding,
4542 &scan32,
4543 0,
4544 dc_sign_ctx(around[0].2),
4545 TxType::DctDct,
4546 Some((bw, bh)),
4547 )?;
4548 if std::env::var_os("EC_TRACE_COEFF").is_some() {
4549 let (rng, _) = dec.debug_state();
4550 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
4551 }
4552 let mut luma_levels = vec![0i32; bw * bh];
4553 for row in 0..32 {
4554 luma_levels[row * bw..][..32].copy_from_slice(&luma_corner[row * 32..][..32]);
4555 }
4556 {
4557 let cur = block_q_idx();
4558 if cur != i32::from(base_q_idx) {
4559 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
4560 }
4561 if std::env::var_os("EC_AV1_TRACE").is_some() {
4562 eprintln!(
4563 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
4564 );
4565 }
4566 }
4567 let luma_residual = dequant_and_inverse_typed_wh(
4568 &luma_levels,
4569 bw,
4570 bh,
4571 crate::decode::bit_depth(),
4572 block_q_idx(),
4573 plane_q_delta(0).0,
4574 plane_q_delta(0).1,
4575 luma_tx_type,
4576 );
4577 y.reconstruct_rect(
4578 px,
4579 py,
4580 bw,
4581 bh,
4582 mode,
4583 angle_delta_y,
4584 reach,
4585 &luma_residual,
4586 None,
4587 filter_intra,
4588 smooth_neighbor,
4589 );
4590 if std::env::var_os("EC_SBPART_DUMP64").is_some() {
4591 let leftcol: Vec<u16> = if px > 0 {
4592 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
4593 } else {
4594 vec![]
4595 };
4596 eprintln!(
4597 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
4598 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
4599 luma_corner.iter().any(|&v| v != 0),
4600 &y.data[py * y.width + px..][..bw],
4601 leftcol,
4602 );
4603 }
4604 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
4605 // corner crop needed (see doc comment).
4606 let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh));
4607 let chroma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
4608 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
4609 let mut u_coding = cdfs.txb(TxbSet::ChromaRect32x16, uv_predict_mode);
4610 if std::env::var_os("EC_TRACE_COEFF").is_some() {
4611 let (rng, _) = dec.debug_state();
4612 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
4613 }
4614 let (u_levels, u_tx_type) = read_coeffs_rect(
4615 dec,
4616 &mut u_coding,
4617 chroma_scan,
4618 chroma_w,
4619 chroma_h,
4620 u_skip_ctx,
4621 dc_sign_ctx(around[1].2),
4622 TxType::DctDct,
4623 )?;
4624 if std::env::var_os("EC_TRACE_COEFF").is_some() {
4625 let (rng, _) = dec.debug_state();
4626 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
4627 }
4628 {
4629 let cur = block_q_idx();
4630 if cur != i32::from(base_q_idx) {
4631 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
4632 }
4633 if std::env::var_os("EC_AV1_TRACE").is_some() {
4634 eprintln!(
4635 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
4636 );
4637 }
4638 }
4639 let u_residual = dequant_and_inverse_typed_wh(
4640 &u_levels,
4641 chroma_w,
4642 chroma_h,
4643 crate::decode::bit_depth(),
4644 block_q_idx(),
4645 plane_q_delta(1).0,
4646 plane_q_delta(1).1,
4647 u_tx_type,
4648 );
4649 u.reconstruct_rect(
4650 cpx,
4651 cpy,
4652 chroma_w,
4653 chroma_h,
4654 uv_predict_mode,
4655 angle_delta_uv,
4656 reach,
4657 &u_residual,
4658 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
4659 None,
4660 smooth_neighbor_uv,
4661 );
4662 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
4663 let mut v_coding = cdfs.txb(TxbSet::ChromaRect32x16, uv_predict_mode);
4664 if std::env::var_os("EC_TRACE_COEFF").is_some() {
4665 let (rng, _) = dec.debug_state();
4666 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
4667 }
4668 let (v_levels, v_tx_type) = read_coeffs_rect(
4669 dec,
4670 &mut v_coding,
4671 chroma_scan,
4672 chroma_w,
4673 chroma_h,
4674 v_skip_ctx,
4675 dc_sign_ctx(around[2].2),
4676 TxType::DctDct,
4677 )?;
4678 if std::env::var_os("EC_TRACE_COEFF").is_some() {
4679 let (rng, _) = dec.debug_state();
4680 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
4681 }
4682 {
4683 let cur = block_q_idx();
4684 if cur != i32::from(base_q_idx) {
4685 RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1));
4686 }
4687 if std::env::var_os("EC_AV1_TRACE").is_some() {
4688 eprintln!(
4689 "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
4690 );
4691 }
4692 }
4693 let v_residual = dequant_and_inverse_typed_wh(
4694 &v_levels,
4695 chroma_w,
4696 chroma_h,
4697 crate::decode::bit_depth(),
4698 block_q_idx(),
4699 plane_q_delta(2).0,
4700 plane_q_delta(2).1,
4701 v_tx_type,
4702 );
4703 v.reconstruct_rect(
4704 cpx,
4705 cpy,
4706 chroma_w,
4707 chroma_h,
4708 uv_predict_mode,
4709 angle_delta_uv,
4710 reach,
4711 &v_residual,
4712 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
4713 None,
4714 smooth_neighbor_uv,
4715 );
4716 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[luma_levels, u_levels, v_levels]);
4717 RECT_COEFF_HITS.with(|c| c.set(c.get() + 1));
4718 }
4719 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
4720 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0);
4721 SB_RECT_HITS.with(|c| c.set(c.get() + 1));
4722 if std::env::var_os("EC_AV1_TRACE").is_some() {
4723 let (rng, _) = dec.debug_state();
4724 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
4725 }
4726 Ok(())
4727}
4728
4729/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
4730/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
4731/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
4732/// it lands away from zero, for gate tests to prove a real stream fired one.
4733fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
4734 let symbol = dec.symbol(cdf);
4735 if symbol != ANGLE_DELTA_ZERO {
4736 ANGLE_DELTA_HITS.with(|c| c.set(c.get() + 1));
4737 }
4738 symbol as i32 - ANGLE_DELTA_ZERO as i32
4739}
4740
4741#[allow(clippy::too_many_arguments)]
4742fn read_intra_mode(
4743 dec: &mut SymbolDecoder,
4744 cdfs: &mut Cdfs,
4745 above_mode: usize,
4746 left_mode: usize,
4747 cfl: bool,
4748 side: usize,
4749 enable_filter_intra: bool,
4750 skip_ctx: usize,
4751 allow_screen_content_tools: bool,
4752 allow_intrabc: bool,
4753 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
4754 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
4755 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
4756 // `None` at the excluded call sites (the 8x8-leaf path), which still read
4757 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
4758 // decoder reads either way -- but refuse by name the moment it fires,
4759 // exactly the old behaviour.
4760 palette: Option<(usize, &[u16])>,
4761 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
4762 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
4763 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
4764 // `use_palette_y`, not a neighbour lookup).
4765 palette_uv_cache: &[u16],
4766 mi_r: usize,
4767 mi_c: usize,
4768) -> Result<(
4769 bool,
4770 usize,
4771 i32,
4772 usize,
4773 i32,
4774 Option<(i32, i32)>,
4775 Option<usize>,
4776 Option<PaletteY>,
4777 Option<PaletteUv>,
4778)> {
4779 let trace = std::env::var_os("EC_AV1_TRACE").is_some();
4780 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
4781 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
4782 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
4783 // line against the instrumented aomdec, not just `tell()`.
4784 let ec_istep = std::env::var_os("EC_TRACE_MODE_STEP").is_some();
4785 macro_rules! istep {
4786 ($name:literal, $val:expr) => {
4787 if ec_istep {
4788 let (rng, _) = dec.debug_state();
4789 eprintln!(
4790 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
4791 $name, $val
4792 );
4793 }
4794 };
4795 }
4796 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
4797 // `skip` when `SegIdPreSkip`, and after it otherwise.
4798 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
4799 if seg_id_pre_skip() {
4800 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false);
4801 }
4802 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
4803 if trace {
4804 eprintln!("TRACE skip value={}", skip as i32);
4805 }
4806 istep!("skip", skip as i32);
4807 if !seg_id_pre_skip() {
4808 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip);
4809 }
4810 // spec order (see the comment below on `read_intrabc_info`): `skip`,
4811 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
4812 maybe_read_cdef_idx(dec, mi_r, mi_c, skip);
4813 istep!("cdef", 0);
4814 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, side == 64, skip);
4815 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, side == 64, skip);
4816 istep!("dq", 0);
4817 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
4818 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
4819 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
4820 // intra frame whose header set `allow_intrabc`. Actual intra block copy
4821 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
4822 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
4823 // draws the line at consuming this one flag symbol and refusing by name
4824 // when it fires, so the arithmetic decoder still resyncs for a stream
4825 // that merely allows (but never uses) intrabc.
4826 if allow_intrabc {
4827 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
4828 if trace {
4829 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
4830 }
4831 if use_intrabc {
4832 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, side);
4833 if trace {
4834 eprintln!("TRACE intrabc dv={dv:?}");
4835 }
4836 INTRABC_DV.with(|c| c.set(Some(dv)));
4837 INTRABC_HITS.with(|c| c.set(c.get() + 1));
4838 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
4839 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
4840 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
4841 // `DC_PRED` (which is also what the neighbour mode contexts and
4842 // the loop filter then see).
4843 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
4844 }
4845 }
4846 let above_ctx = INTRA_MODE_CTX[above_mode];
4847 let left_ctx = INTRA_MODE_CTX[left_mode];
4848 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
4849 if trace {
4850 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode}");
4851 }
4852 istep!("mode", mode as i32);
4853 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
4854 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
4855 if trace {
4856 eprintln!(
4857 "TRACE angle_delta value={}",
4858 delta + ANGLE_DELTA_ZERO as i32
4859 );
4860 }
4861 delta
4862 } else {
4863 0
4864 };
4865 istep!("angle_y", angle_delta_y);
4866 let uv_mode = if cfl {
4867 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
4868 } else {
4869 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
4870 };
4871 if trace {
4872 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode}");
4873 }
4874 istep!("uv_mode", uv_mode as i32);
4875 let alpha = if cfl && uv_mode == UV_CFL_PRED {
4876 Some(read_cfl_alphas(dec, cdfs))
4877 } else {
4878 None
4879 };
4880 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
4881 // from this lane's directional chroma: a corner block with neither
4882 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
4883 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
4884 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
4885 // bug in that fallback this lane's own scope does not cover. Keep it
4886 // refused here rather than ship a silently-wrong decode.
4887 if (9..=12).contains(&uv_mode) {
4888 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
4889 }
4890 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
4891 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
4892 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
4893 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
4894 // the `else` branch below and never reads one either way.
4895 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
4896 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
4897 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
4898 } else {
4899 0
4900 };
4901 istep!("angle_uv", angle_delta_uv);
4902 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
4903 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
4904 // gated by `av1_allow_palette` (blockd.h -- size bound only,
4905 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
4906 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
4907 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
4908 // read the same CDF row whenever every neighbour really is non-palette).
4909 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
4910 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
4911 // neighbour lookup at all), so it is exact even at the excluded call
4912 // sites once Y decodes real syntax there too.
4913 //
4914 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
4915 // inline from `read_palette_mode_info` -- it runs later, from
4916 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
4917 // after the WHOLE mode-info read for the block, including UV palette
4918 // mode_info (`read_palette_mode_info`'s own second half, right below)
4919 // and `read_filter_intra_mode_info`. So this branch now only reads
4920 // mode/size/colours for both planes (deferring the two colour-index-map
4921 // decodes to after `filter_intra`, below) -- r6's range trace pinned
4922 // this exact ordering bug (`compare-range-not-tell`: ranges matched
4923 // bit-for-bit through the Y colours, diverged only at the old inline
4924 // `decode_color_index_map` call).
4925 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
4926 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
4927 if allow_screen_content_tools
4928 && let Some(bsize_ctx) = palette_bsize_ctx(side)
4929 {
4930 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
4931 if mode == DC_PRED {
4932 if trace {
4933 let (rng, _) = dec.debug_state();
4934 eprintln!(
4935 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
4936 );
4937 }
4938 }
4939 let use_palette_y =
4940 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
4941 if mode == DC_PRED && trace {
4942 let (rng, _) = dec.debug_state();
4943 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
4944 }
4945 if use_palette_y {
4946 if palette.is_none() {
4947 return Err(unsupported(
4948 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
4949 ));
4950 }
4951 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
4952 if trace {
4953 let (rng, _) = dec.debug_state();
4954 eprintln!("TRACE palette_y_size n={n} rng={rng}");
4955 }
4956 let colors = read_palette_colors_y(dec, n, cache);
4957 if trace {
4958 let (rng, _) = dec.debug_state();
4959 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
4960 }
4961 palette_y_pending = Some((n, colors));
4962 }
4963 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
4964 // unconditionally at this bit position whenever `uv_mode ==
4965 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
4966 // scope always reconstructs chroma alongside luma (`decode_block`
4967 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
4968 // is always true here and does not need threading in.
4969 let palette_uv_mode_ctx = usize::from(use_palette_y);
4970 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0 {
4971 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
4972 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache);
4973 palette_uv_pending = Some((n, u_colors, v_colors));
4974 }
4975 }
4976 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
4977 // `use_filter_intra` symbol this decoder never read at all until
4978 // lane-av1real r10 -- silently skipping it left every bit past a
4979 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
4980 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
4981 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
4982 // symbol's bits were never consumed).
4983 let mut filter_intra = None;
4984 if mode == DC_PRED
4985 && enable_filter_intra
4986 && let Some(class) = filter_intra_size_class(side)
4987 {
4988 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
4989 if trace {
4990 eprintln!(
4991 "TRACE use_filter_intra side={side} value={}",
4992 use_filter_intra as i32
4993 );
4994 }
4995 istep!("use_filter_intra", use_filter_intra as i32);
4996 if use_filter_intra {
4997 FILTER_INTRA_HITS.with(|c| c.set(c.get() + 1));
4998 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
4999 if trace {
5000 eprintln!("TRACE filter_intra_mode value={fi_mode}");
5001 }
5002 istep!("filter_intra_mode", fi_mode as i32);
5003 filter_intra = Some(fi_mode);
5004 }
5005 }
5006 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
5007 // shared U/V map) -- the same order libaom's own loop visits them in.
5008 let palette_y = palette_y_pending.map(|(n, colors)| {
5009 let map = decode_color_index_map(dec, cdfs, n, side, false);
5010 PALETTE_HITS.with(|c| c.set(c.get() + 1));
5011 if trace {
5012 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
5013 }
5014 PaletteY { size: n, colors, map }
5015 });
5016 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
5017 let map = decode_color_index_map(dec, cdfs, n, side / 2, true);
5018 PALETTE_UV_HITS.with(|c| c.set(c.get() + 1));
5019 if trace {
5020 eprintln!(
5021 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
5022 &u_colors[..n],
5023 &v_colors[..n]
5024 );
5025 }
5026 PaletteUv { size: n, u_colors, v_colors, map }
5027 });
5028 Ok((
5029 skip,
5030 mode,
5031 angle_delta_y,
5032 uv_mode,
5033 angle_delta_uv,
5034 alpha,
5035 filter_intra,
5036 palette_y,
5037 palette_uv,
5038 ))
5039}
5040
5041/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
5042/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
5043/// intra modes.
5044const UV_CFL_PRED: usize = 13;
5045
5046/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
5047/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
5048/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
5049/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
5050/// joint sign the same way. Returns each plane's final signed `alpha_q3`
5051/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
5052fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
5053 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
5054 let sign_u = ((joint_sign + 1) * 11) >> 5;
5055 let sign_v = (joint_sign + 1) - 3 * sign_u;
5056 let alpha_u = if sign_u == 0 {
5057 0
5058 } else {
5059 let ctx_u = (joint_sign + 1 - 3) as usize;
5060 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
5061 if sign_u == 2 { mag } else { -mag }
5062 };
5063 let alpha_v = if sign_v == 0 {
5064 0
5065 } else {
5066 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
5067 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
5068 if sign_v == 2 { mag } else { -mag }
5069 };
5070 (alpha_u, alpha_v)
5071}
5072
5073/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
5074/// the reconstructed luma samples under a `side`-square block, subsampled
5075/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
5076/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
5077/// to give the AC values [`cfl_scaled`] scales by alpha.
5078fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
5079 let cside = side / 2;
5080 let mut ac = vec![0i32; cside * cside];
5081 let mut sum = 0i32;
5082 for cy in 0..cside {
5083 for cx in 0..cside {
5084 let (lx, ly) = (px + cx * 2, py + cy * 2);
5085 let q3 = (i32::from(y.data[ly * y.width + lx])
5086 + i32::from(y.data[ly * y.width + lx + 1])
5087 + i32::from(y.data[(ly + 1) * y.width + lx])
5088 + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
5089 << 1;
5090 ac[cy * cside + cx] = q3;
5091 sum += q3;
5092 }
5093 }
5094 let num_pel = (cside * cside) as i32;
5095 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
5096 ac.iter_mut().for_each(|v| *v -= avg);
5097 ac
5098}
5099
5100/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
5101/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
5102/// ties away from zero on the shifted-out sign).
5103fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
5104 let v = alpha_q3 * ac_q3;
5105 if v >= 0 {
5106 (v + 32) >> 6
5107 } else {
5108 -((-v + 32) >> 6)
5109 }
5110}
5111
5112/// One plane's reconstruction buffer, `width * height` samples, and the
5113/// prediction/residual reads and writes into it — the decode-side twin of
5114/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
5115/// (own-edge and reach clamps both), passing what it gathers straight to
5116/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
5117/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
5118/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
5119fn dump_stage(var: &str, y: &PlaneBuf, u: &PlaneBuf, v: &PlaneBuf) {
5120 use std::io::Write;
5121 if let Ok(path) = std::env::var(var)
5122 && let Ok(mut f) = std::fs::File::create(format!("{path}.f0"))
5123 {
5124 for p in [y, u, v] {
5125 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
5126 let _ = f.write_all(&narrow);
5127 }
5128 }
5129}
5130
5131#[derive(Clone)]
5132struct PlaneBuf {
5133 data: Vec<u16>,
5134 width: usize,
5135 height: usize,
5136 /// The frame's true, decodable extent in this plane's own units — past
5137 /// this, samples are the padded coding surface's invented tail, never a
5138 /// real decoder's edge or reach reads.
5139 true_width: usize,
5140 true_height: usize,
5141 /// This plane's own tile's top-left pixel origin (spec: intra prediction
5142 /// never reaches across a tile boundary even though an earlier-decoded
5143 /// tile's real pixels sit right there in the shared buffer) — set via
5144 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
5145 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
5146 /// is threaded (the two-tile column-split stage 1 fixture's tile always
5147 /// ends at the frame's own right/bottom edge); a non-last tile's own
5148 /// right/bottom reach bound is still open, tracked in the report.
5149 tile_x0: usize,
5150 tile_y0: usize,
5151 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
5152 /// (exclusive) -- a non-last tile column/row's own reach must stop at
5153 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
5154 /// full padded extent) for the single-tile/last-tile case, matching the
5155 /// old unclipped behaviour exactly.
5156 tile_x1: usize,
5157 tile_y1: usize,
5158}
5159
5160/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
5161/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
5162/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
5163/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
5164/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
5165/// `ALTREF2`/`ALTREF`).
5166type RefSlots<'a> = [Option<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)>; 8];
5167
5168impl PlaneBuf {
5169 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
5170 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
5171 /// are already in this plane's own units (luma pixels for `y`, chroma
5172 /// pixels — halved — for `u`/`v`).
5173 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
5174 self.tile_x0 = x0;
5175 self.tile_y0 = y0;
5176 self.tile_x1 = x1;
5177 self.tile_y1 = y1;
5178 }
5179
5180 fn edges(
5181 &self,
5182 x: usize,
5183 y: usize,
5184 side: usize,
5185 reach: Reach,
5186 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
5187 let own_across = x + side.min(self.true_width.saturating_sub(x));
5188 let across = if reach.above_right {
5189 own_across + side.min(self.true_width.saturating_sub(own_across))
5190 } else {
5191 own_across
5192 }
5193 .min(self.width)
5194 .min(self.tile_x1);
5195 let own_down = y + side.min(self.true_height.saturating_sub(y));
5196 let down = if reach.below_left {
5197 own_down + side.min(self.true_height.saturating_sub(own_down))
5198 } else {
5199 own_down
5200 }
5201 .min(self.height)
5202 .min(self.tile_y1);
5203 let above = (y > self.tile_y0 && across > x)
5204 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
5205 let left = (x > self.tile_x0 && down > y).then(|| {
5206 (y..down)
5207 .map(|row| self.data[row * self.width + x - 1])
5208 .collect::<Vec<_>>()
5209 });
5210 let corner =
5211 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
5212 (above, left, corner)
5213 }
5214
5215 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
5216 /// the above/left reach each extend by their OWN axis (`bw` across,
5217 /// `bh` down), not one shared `side`.
5218 fn edges_rect(
5219 &self,
5220 x: usize,
5221 y: usize,
5222 bw: usize,
5223 bh: usize,
5224 reach: Reach,
5225 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
5226 let own_across = x + bw.min(self.true_width.saturating_sub(x));
5227 let across = if reach.above_right {
5228 own_across + bw.min(self.true_width.saturating_sub(own_across))
5229 } else {
5230 own_across
5231 }
5232 .min(self.width)
5233 .min(self.tile_x1);
5234 let own_down = y + bh.min(self.true_height.saturating_sub(y));
5235 let down = if reach.below_left {
5236 own_down + bh.min(self.true_height.saturating_sub(own_down))
5237 } else {
5238 own_down
5239 }
5240 .min(self.height)
5241 .min(self.tile_y1);
5242 let above = (y > self.tile_y0 && across > x)
5243 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
5244 let left = (x > self.tile_x0 && down > y).then(|| {
5245 (y..down)
5246 .map(|row| self.data[row * self.width + x - 1])
5247 .collect::<Vec<_>>()
5248 });
5249 let corner =
5250 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
5251 (above, left, corner)
5252 }
5253
5254 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
5255 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
5256 /// already-rect-capable `(bw, bh)` pair.
5257 #[allow(clippy::too_many_arguments)]
5258 fn reconstruct_rect(
5259 &mut self,
5260 x: usize,
5261 y: usize,
5262 bw: usize,
5263 bh: usize,
5264 mode: usize,
5265 angle_delta: i32,
5266 reach: Reach,
5267 residual: &[i32],
5268 cfl: Option<(i32, &[i32])>,
5269 filter_intra: Option<usize>,
5270 smooth_neighbor: bool,
5271 ) {
5272 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
5273 let mut prediction = vec![0u16; bw * bh];
5274 if let Some(fi_mode) = filter_intra {
5275 crate::intra::predict_filter_intra(
5276 fi_mode,
5277 above.as_deref(),
5278 left.as_deref(),
5279 corner,
5280 bw,
5281 bh,
5282 &mut prediction,
5283 );
5284 } else {
5285 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
5286 predict(
5287 mode as u8,
5288 angle_delta,
5289 above.as_deref(),
5290 left.as_deref(),
5291 corner,
5292 bw,
5293 bh,
5294 enable_edge_filter,
5295 smooth_neighbor,
5296 &mut prediction,
5297 );
5298 }
5299 for row in 0..bh {
5300 for col in 0..bw {
5301 let idx = row * bw + col;
5302 let mut base = i32::from(prediction[idx]);
5303 if let Some((alpha_q3, ac_q3)) = cfl {
5304 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
5305 }
5306 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
5307 self.data[(y + row) * self.width + x + col] = sample;
5308 }
5309 }
5310 }
5311
5312 /// Predicts under `mode` then adds `residual` (side*side, raster),
5313 /// writing the clamped reconstruction back into the plane at `(x, y)`.
5314 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
5315 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
5316 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
5317 /// order (cfl.c).
5318 fn reconstruct(
5319 &mut self,
5320 x: usize,
5321 y: usize,
5322 side: usize,
5323 mode: usize,
5324 angle_delta: i32,
5325 reach: Reach,
5326 residual: &[i32],
5327 cfl: Option<(i32, &[i32])>,
5328 filter_intra: Option<usize>,
5329 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
5330 // libaom `get_filt_type`): true when the block's above OR left
5331 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
5332 // Callers pass their own plane's neighbour-mode check
5333 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
5334 // callers until a smooth/paeth `uv_mode` can reach this call at all
5335 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
5336 // keeps `false` exact for chroma without this fn needing to know why.
5337 smooth_neighbor: bool,
5338 ) {
5339 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
5340 // takes priority over `predict()`/`predict_filter_intra` entirely --
5341 // palette prediction needs no edge pixels at all.
5342 let prediction = if let Some(buf) = PALETTE_PRED.with(|c| c.borrow_mut().take()) {
5343 buf
5344 } else {
5345 let (above, left, corner) = self.edges(x, y, side, reach);
5346 let mut prediction = vec![0u16; side * side];
5347 if let Some(fi_mode) = filter_intra {
5348 crate::intra::predict_filter_intra(
5349 fi_mode,
5350 above.as_deref(),
5351 left.as_deref(),
5352 corner,
5353 side,
5354 side,
5355 &mut prediction,
5356 );
5357 } else {
5358 // `enable_intra_edge_filter` is the sequence header's own flag
5359 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
5360 // call, never per-block) -- threading it through every
5361 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
5362 // dozen sites for a value that never changes mid-decode, so it
5363 // rides a thread-local instead (this decoder is single-threaded
5364 // per stream).
5365 let enable_edge_filter = ENABLE_EDGE_FILTER.with(std::cell::Cell::get);
5366 predict(
5367 mode as u8,
5368 angle_delta,
5369 above.as_deref(),
5370 left.as_deref(),
5371 corner,
5372 side,
5373 side,
5374 enable_edge_filter,
5375 smooth_neighbor,
5376 &mut prediction,
5377 );
5378 }
5379 prediction
5380 };
5381 for row in 0..side {
5382 for col in 0..side {
5383 let idx = row * side + col;
5384 let mut base = i32::from(prediction[idx]);
5385 if let Some((alpha_q3, ac_q3)) = cfl {
5386 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max());
5387 }
5388 let sample = (base + residual[idx]).clamp(0, sample_max()) as u16;
5389 self.data[(y + row) * self.width + x + col] = sample;
5390 }
5391 }
5392 }
5393}
5394
5395/// Reads one plane's transform block, reconstructs it into `plane` at
5396/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
5397#[allow(clippy::too_many_arguments)]
5398fn read_plane(
5399 dec: &mut SymbolDecoder,
5400 cdfs: &mut Cdfs,
5401 set: TxbSet,
5402 scan: &[u16],
5403 plane_idx: usize,
5404 around: (bool, bool, i32),
5405 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
5406 // it for every plane's `txb` lookup (it is what an intra transform type's
5407 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
5408 tx_mode: usize,
5409 predict_mode: usize,
5410 angle_delta: i32,
5411 reach: Reach,
5412 plane: &mut PlaneBuf,
5413 x: usize,
5414 y: usize,
5415 side: usize,
5416 tx_side: usize,
5417 base_q_idx: u8,
5418 cfl: Option<(i32, &[i32])>,
5419 filter_intra: Option<usize>,
5420 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
5421 // smaller than its own block (spec `get_txb_ctx_general`'s
5422 // `plane_bsize != tx_size` branch), carrying the already-looked-up
5423 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
5424 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
5425 // formula below.
5426 luma_skip_ctx: Option<usize>,
5427 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
5428 smooth_neighbor: bool,
5429) -> Result<Vec<i32>> {
5430 let skip_ctx = if plane_idx == 0 {
5431 luma_skip_ctx.unwrap_or(0)
5432 } else {
5433 usize::from(around.0) + usize::from(around.1)
5434 };
5435 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
5436 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
5437 // not by the block's ordinary `mode` (which is always DC_PRED whenever
5438 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
5439 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
5440 // filter-intra in AV1).
5441 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
5442 let tx_mode = if plane_idx == 0 {
5443 filter_intra.map_or(tx_mode, |fi| FIMODE_TO_INTRADIR[fi])
5444 } else {
5445 tx_mode
5446 };
5447 let mut coding = cdfs.txb(set, tx_mode);
5448 // Luma's `default_tx_type` is only a fallback for the sizes whose
5449 // `TxbSet` carries no symbol at all (32-point and up), which the spec
5450 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
5451 // *never* its own coded symbol (`coding.tx_type` is always `None` for
5452 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
5453 // the plane's own predicted mode (`default_intra_tx_type`) -- except
5454 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
5455 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
5456 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
5457 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
5458 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
5459 // narrows there — only `Chroma32` and up do).
5460 let default_tx_type = if plane_idx == 0 || side >= 32 {
5461 TxType::DctDct
5462 } else {
5463 default_intra_tx_type(predict_mode as u8)
5464 };
5465 let (grid, tx_type) = read_coeffs(
5466 dec,
5467 &mut coding,
5468 scan,
5469 skip_ctx,
5470 dc_sign_ctx(around.2),
5471 default_tx_type,
5472 None,
5473 )?;
5474 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
5475 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
5476 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
5477 // guard also assumes.
5478 let levels = if tx_side == side {
5479 grid
5480 } else {
5481 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
5482 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
5483 // keyed by that true size, not the coded corner's -- so the corner
5484 // goes into the top-left of a `side`-sized grid, not the reverse.
5485 let mut full = vec![0i32; side * side];
5486 for row in 0..tx_side {
5487 full[row * side..][..tx_side].copy_from_slice(&grid[row * tx_side..][..tx_side]);
5488 }
5489 full
5490 };
5491 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
5492 let residual = dequant_and_inverse_typed(&levels, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
5493 if std::env::var_os("EC_AV1_TRACE").is_some() {
5494 eprintln!(
5495 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={levels:?} residual={residual:?}",
5496 );
5497 }
5498 plane.reconstruct(
5499 x,
5500 y,
5501 side,
5502 predict_mode,
5503 angle_delta,
5504 reach,
5505 &residual,
5506 cfl,
5507 filter_intra,
5508 smooth_neighbor,
5509 );
5510 Ok(if tx_side == side {
5511 residual_grid_placeholder(&levels, side)
5512 } else {
5513 levels
5514 })
5515}
5516
5517/// `record`'s neighbour state only reads whether *the coded grid* (not the
5518/// residual) has nonzero entries, so the levels this function already built
5519/// are what it wants back; this helper exists only to name that clearly at
5520/// the one call site where `tx_side == side`.
5521fn residual_grid_placeholder(levels: &[i32], _tx_side: usize) -> Vec<i32> {
5522 levels.to_vec()
5523}
5524
5525/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
5526/// three planes, reconstructing them into `y`/`u`/`v` and updating
5527/// `neighbours`.
5528#[allow(clippy::too_many_arguments)]
5529fn decode_block(
5530 dec: &mut SymbolDecoder,
5531 cdfs: &mut Cdfs,
5532 neighbours: &mut Neighbours,
5533 at: (usize, usize),
5534 side: usize,
5535 luma_set: TxbSet,
5536 chroma_set: TxbSet,
5537 luma_tx: usize,
5538 chroma_tx: usize,
5539 scans: (&[u16], &[u16]),
5540 cfl: bool,
5541 y: &mut PlaneBuf,
5542 u: &mut PlaneBuf,
5543 v: &mut PlaneBuf,
5544 base_q_idx: u8,
5545 enable_filter_intra: bool,
5546 allow_screen_content_tools: bool,
5547 allow_intrabc: bool,
5548 scan32: &[u16],
5549 scan16: &[u16],
5550 scan8: &[u16],
5551 scan4: &[u16],
5552 tx_select: bool,
5553 reduced_tx_set: bool,
5554) -> Result<()> {
5555 let (r, c) = at;
5556 let (px, py) = (c * SUB, r * SUB);
5557 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
5558 let palette_uv_cache = neighbours.palette_uv_cache(at);
5559 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
5560 read_intra_mode(
5561 dec,
5562 cdfs,
5563 neighbours.above_mode[c],
5564 neighbours.left_mode[r],
5565 cfl,
5566 side,
5567 enable_filter_intra,
5568 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
5569 allow_screen_content_tools,
5570 allow_intrabc,
5571 Some((palette_ctx, &palette_cache)),
5572 &palette_uv_cache,
5573 r * (SUB / MI),
5574 c * (SUB / MI),
5575 )?;
5576 let intrabc_dv = INTRABC_DV.with(|c| c.take());
5577 // libaom `parse_decode_block`: an intrabc block is `inter_block_tx`, so
5578 // under `TX_MODE_SELECT` its transform size comes from the inter var-tx
5579 // partition tree (`read_var_tx_size`), a syntax element this decoder has
5580 // nowhere -- reading the intra `tx_depth` symbol instead would desync.
5581 if intrabc_dv.is_some() && tx_select && !skip {
5582 return Err(unsupported(
5583 "an intrabc block under TxMode::Select (its transform size is coded by the inter var-tx partition tree, which this decoder never reads)",
5584 ));
5585 }
5586 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
5587 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
5588 // actual chroma-from-luma correlation, same as this decoder always did.
5589 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
5590 DC_PRED
5591 } else {
5592 uv_mode
5593 };
5594 let smooth_neighbor =
5595 is_smooth_mode(neighbours.above_mode[c]) || is_smooth_mode(neighbours.left_mode[r]);
5596 if smooth_neighbor {
5597 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
5598 }
5599 let smooth_neighbor_uv =
5600 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
5601 if std::env::var_os("EC_AV1_TRACE").is_some() {
5602 eprintln!(
5603 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
5604 angle_delta_uv={angle_delta_uv}"
5605 );
5606 }
5607 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
5608 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
5609 // block, skipped or not. `logical_tx` is what the loop filter's edge
5610 // lookup and the next block's own `tx_size_context` want (the *nominal*
5611 // transform size -- 64 even for the 64x64 corner-scanned case, spec
5612 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
5613 // which only differs from it at that one corner case.
5614 let (logical_tx, coeff_tx_side) = if tx_select {
5615 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side);
5616 (resolved, if resolved == 64 { 32 } else { resolved })
5617 } else {
5618 (side, luma_tx)
5619 };
5620 let luma_set = if tx_select {
5621 txbset_for(logical_tx, reduced_tx_set)
5622 } else {
5623 luma_set
5624 };
5625 let luma_set = if intrabc_dv.is_some() {
5626 txbset_for_inter(logical_tx, reduced_tx_set)
5627 } else {
5628 luma_set
5629 };
5630 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
5631 let reach = Reach::of(side, px, py, y.width, y.height);
5632 let (cpx, cpy) = (px / 2, py / 2);
5633 let chroma_side = side / 2;
5634 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
5635 // frame's own pre-loop-filter reconstruction (all loop filters are off
5636 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
5637 // block vector, with the BILINEAR kernel libaom forces for intrabc --
5638 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
5639 // odd, which is exactly what the bilinear taps then interpolate.
5640 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
5641 let mut yb = vec![0u16; side * side];
5642 mc::predict_with_filter(
5643 &y.data, y.width, y.true_width, y.true_height,
5644 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
5645 side, side, mc::InterpFilterKind::Bilinear, &mut yb,
5646 );
5647 let mut ub = vec![0u16; chroma_side * chroma_side];
5648 mc::predict_with_filter(
5649 &u.data, u.width, u.true_width, u.true_height,
5650 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
5651 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub,
5652 );
5653 let mut vb = vec![0u16; chroma_side * chroma_side];
5654 mc::predict_with_filter(
5655 &v.data, v.width, v.true_width, v.true_height,
5656 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
5657 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb,
5658 );
5659 (yb, ub, vb)
5660 });
5661 if let Some((yb, _, _)) = &intrabc_bufs {
5662 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(yb.clone()));
5663 }
5664 // A palette-Y block's own prediction is the reconstructed colour-index
5665 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
5666 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
5667 // parameter through this function's dozen `y.reconstruct`/`read_plane`
5668 // sites. A split luma transform (`tx_select && logical_tx != side`)
5669 // would need the map sliced per-TU -- untested against a real
5670 // `--enable-palette=1` stream this round, so refuse by name rather than
5671 // guess at the slicing (charter's own named-acceptable fallback).
5672 if let Some(ref py) = palette_y {
5673 if tx_select && logical_tx != side {
5674 return Err(unsupported(
5675 "a palette block with a split luma transform (round 1)",
5676 ));
5677 }
5678 let buf: Vec<u16> = py
5679 .map
5680 .iter()
5681 .map(|&idx| py.colors[idx as usize])
5682 .collect();
5683 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(buf));
5684 }
5685 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
5686 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
5687 // plane's own `reconstruct`/`read_plane` call below (never both planes at
5688 // once), since Y's own set-then-take already emptied the slot by the time
5689 // either of these run.
5690 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
5691 (
5692 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
5693 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
5694 )
5695 });
5696 // The chroma half of the intrabc prediction rides the same per-plane
5697 // override slot the UV-palette buffers do (set fresh before each plane's
5698 // own `reconstruct`/`read_plane` call below).
5699 let palette_uv_bufs = match &intrabc_bufs {
5700 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
5701 None => palette_uv_bufs,
5702 };
5703 if skip {
5704 // A skipped block codes no residual syntax at all (spec 5.11.34):
5705 // straight prediction, on every plane.
5706 y.reconstruct(
5707 px,
5708 py,
5709 side,
5710 mode,
5711 angle_delta_y,
5712 reach,
5713 &vec![0i32; side * side],
5714 None,
5715 filter_intra,
5716 smooth_neighbor,
5717 );
5718 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
5719 if let Some((ub, _)) = &palette_uv_bufs {
5720 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(ub.clone()));
5721 }
5722 u.reconstruct(
5723 cpx,
5724 cpy,
5725 chroma_side,
5726 uv_predict_mode,
5727 angle_delta_uv,
5728 reach,
5729 &vec![0i32; chroma_side * chroma_side],
5730 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
5731 None,
5732 smooth_neighbor_uv,
5733 );
5734 if let Some((_, vb)) = &palette_uv_bufs {
5735 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(vb.clone()));
5736 }
5737 v.reconstruct(
5738 cpx,
5739 cpy,
5740 chroma_side,
5741 uv_predict_mode,
5742 angle_delta_uv,
5743 reach,
5744 &vec![0i32; chroma_side * chroma_side],
5745 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
5746 None,
5747 smooth_neighbor_uv,
5748 );
5749 let luma_grid = vec![0i32; side * side];
5750 let u_grid = vec![0i32; chroma_side * chroma_side];
5751 let v_grid = vec![0i32; chroma_side * chroma_side];
5752 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
5753 } else if !tx_select || logical_tx == side {
5754 // A single luma transform unit -- the old path, unchanged (including
5755 // the 64x64 corner case, `logical_tx == side == 64` with
5756 // `coeff_tx_side == 32`).
5757 let around = neighbours.around(at, side);
5758 let luma_grid = read_plane(
5759 dec,
5760 cdfs,
5761 luma_set,
5762 luma_scan,
5763 0,
5764 around[0],
5765 mode,
5766 mode,
5767 angle_delta_y,
5768 reach,
5769 y,
5770 px,
5771 py,
5772 side,
5773 coeff_tx_side,
5774 base_q_idx,
5775 None,
5776 filter_intra,
5777 None,
5778 smooth_neighbor,
5779 )?;
5780 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
5781 if let Some((ub, _)) = &palette_uv_bufs {
5782 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(ub.clone()));
5783 }
5784 let u_grid = read_plane(
5785 dec,
5786 cdfs,
5787 chroma_set,
5788 scans.1,
5789 1,
5790 around[1],
5791 mode,
5792 uv_predict_mode,
5793 angle_delta_uv,
5794 reach,
5795 u,
5796 cpx,
5797 cpy,
5798 chroma_side,
5799 chroma_tx,
5800 base_q_idx,
5801 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
5802 None,
5803 None,
5804 smooth_neighbor_uv,
5805 )?;
5806 if std::env::var_os("EC_AV1_TRACE").is_some() {
5807 eprintln!(
5808 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
5809 &u.data[cpy * u.width + cpx..][..chroma_side]
5810 );
5811 }
5812 if let Some((_, vb)) = &palette_uv_bufs {
5813 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(vb.clone()));
5814 }
5815 let v_grid = read_plane(
5816 dec,
5817 cdfs,
5818 chroma_set,
5819 scans.1,
5820 2,
5821 around[2],
5822 mode,
5823 uv_predict_mode,
5824 angle_delta_uv,
5825 reach,
5826 v,
5827 cpx,
5828 cpy,
5829 chroma_side,
5830 chroma_tx,
5831 base_q_idx,
5832 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
5833 None,
5834 None,
5835 smooth_neighbor_uv,
5836 )?;
5837 neighbours.record(at, side, mode, uv_predict_mode, &[luma_grid, u_grid, v_grid]);
5838 } else {
5839 // Several luma transform units, raster order (spec
5840 // `transform_block`'s loop): the block's resolved transform is
5841 // genuinely smaller than its own side, so each tile of it predicts
5842 // and codes independently, its own context read fresh off whatever
5843 // the earlier tiles in this same block already wrote -- the same
5844 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
5845 let n_axis = side / logical_tx;
5846 for tu_row in 0..n_axis {
5847 for tu_col in 0..n_axis {
5848 let tu_mi = (
5849 mi_r + tu_row * (logical_tx / MI),
5850 mi_c + tu_col * (logical_tx / MI),
5851 );
5852 let tu_px = px + tu_col * logical_tx;
5853 let tu_py = py + tu_row * logical_tx;
5854 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
5855 let tu_reach = Reach::of(logical_tx, tu_px, tu_py, y.width, y.height);
5856 // This transform unit's own bsize (`logical_tx`) is smaller
5857 // than the block it sits in (`side`), so `txb_skip_ctx` is
5858 // the neighbour-magnitude table, not the lone-TU 0 (spec
5859 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
5860 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
5861 let tu_grid = read_plane(
5862 dec,
5863 cdfs,
5864 luma_set,
5865 luma_scan,
5866 0,
5867 tu_around,
5868 mode,
5869 mode,
5870 angle_delta_y,
5871 tu_reach,
5872 y,
5873 tu_px,
5874 tu_py,
5875 logical_tx,
5876 logical_tx,
5877 base_q_idx,
5878 None,
5879 filter_intra,
5880 Some(tu_skip_ctx),
5881 smooth_neighbor,
5882 )?;
5883 if std::env::var_os("EC_AV1_TRACE").is_some() {
5884 eprintln!(
5885 "TRACE tu_bitpos mi=({},{}) tell={}",
5886 tu_mi.0,
5887 tu_mi.1,
5888 dec.debug_bitpos()
5889 );
5890 }
5891 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
5892 }
5893 }
5894 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
5895 let chroma_around = neighbours.around(at, side);
5896 if let Some((ub, _)) = &palette_uv_bufs {
5897 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(ub.clone()));
5898 }
5899 let u_grid = read_plane(
5900 dec,
5901 cdfs,
5902 chroma_set,
5903 scans.1,
5904 1,
5905 chroma_around[1],
5906 mode,
5907 uv_predict_mode,
5908 angle_delta_uv,
5909 reach,
5910 u,
5911 cpx,
5912 cpy,
5913 chroma_side,
5914 chroma_tx,
5915 base_q_idx,
5916 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
5917 None,
5918 None,
5919 smooth_neighbor_uv,
5920 )?;
5921 if let Some((_, vb)) = &palette_uv_bufs {
5922 PALETTE_PRED.with(|c| *c.borrow_mut() = Some(vb.clone()));
5923 }
5924 let v_grid = read_plane(
5925 dec,
5926 cdfs,
5927 chroma_set,
5928 scans.1,
5929 2,
5930 chroma_around[2],
5931 mode,
5932 uv_predict_mode,
5933 angle_delta_uv,
5934 reach,
5935 v,
5936 cpx,
5937 cpy,
5938 chroma_side,
5939 chroma_tx,
5940 base_q_idx,
5941 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
5942 None,
5943 None,
5944 smooth_neighbor_uv,
5945 )?;
5946 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&u_grid, &v_grid]);
5947 }
5948 // Unconditional, `size == 0` for a non-palette block: clears any stale
5949 // neighbour palette state the same way [`Neighbours::record`] always
5950 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
5951 // (the split-luma-TU branch above always refuses before reaching here
5952 // when `palette_y` is `Some`, so it is never live for that branch).
5953 let (py_size, py_colors) = palette_y
5954 .as_ref()
5955 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
5956 neighbours.record_palette_y(at, side, py_size, py_colors);
5957 let (puv_size, puv_colors) = palette_uv
5958 .as_ref()
5959 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
5960 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
5961 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
5962 neighbours.fill_lf_grid(
5963 (r * (SUB / MI), c * (SUB / MI)),
5964 side / MI,
5965 logical_tx as u8,
5966 0,
5967 );
5968 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv);
5969 Ok(())
5970}
5971
5972/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
5973/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
5974/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
5975/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
5976/// just-decoded mode, not the enclosing slot's stale one, is the true
5977/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
5978/// units, which is what its coefficient context (finer than [`SUB`]) is read
5979/// at. Returns the mode this leaf decoded, for the caller's own
5980/// `prev_leaf`/final mode-writeback bookkeeping.
5981#[allow(clippy::too_many_arguments)]
5982fn decode_leaf8(
5983 dec: &mut SymbolDecoder,
5984 cdfs: &mut Cdfs,
5985 neighbours: &mut Neighbours,
5986 outer_at: (usize, usize),
5987 leaf_mi: (usize, usize),
5988 scans: (&[u16], &[u16]),
5989 prev_leaf: Option<((usize, usize), usize)>,
5990 y: &mut PlaneBuf,
5991 u: &mut PlaneBuf,
5992 v: &mut PlaneBuf,
5993 base_q_idx: u8,
5994 enable_filter_intra: bool,
5995 allow_screen_content_tools: bool,
5996 allow_intrabc: bool,
5997 tx_select: bool,
5998 reduced_tx_set: bool,
5999) -> Result<usize> {
6000 let (r, c) = outer_at;
6001 let mut above_mode = neighbours.above_mode[c];
6002 let mut left_mode = neighbours.left_mode[r];
6003 if let Some(((pr, pc), pmode)) = prev_leaf {
6004 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
6005 above_mode = pmode;
6006 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
6007 left_mode = pmode;
6008 }
6009 }
6010 // See [`PlaneBuf::reconstruct`]'s doc: chroma stays `false` (exact) until
6011 // a smooth/paeth `uv_mode` can reach decode at all.
6012 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
6013 if smooth_neighbor {
6014 SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1));
6015 }
6016 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
6017 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
6018 // `decode_block` caller at 16x16 and up.
6019 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, _palette_y, _palette_uv) =
6020 read_intra_mode(
6021 dec,
6022 cdfs,
6023 above_mode,
6024 left_mode,
6025 true,
6026 8,
6027 enable_filter_intra,
6028 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
6029 allow_screen_content_tools,
6030 allow_intrabc,
6031 None,
6032 &[],
6033 leaf_mi.0,
6034 leaf_mi.1,
6035 )?;
6036 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
6037 DC_PRED
6038 } else {
6039 uv_mode
6040 };
6041 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
6042 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
6043 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
6044 // transform units, same raster-order per-TU pattern `decode_block`'s
6045 // multi-TU branch runs).
6046 let resolved = if tx_select {
6047 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8)
6048 } else {
6049 8
6050 };
6051 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
6052 let reach = Reach::of(8, px, py, y.width, y.height);
6053 let (cpx, cpy) = (px / 2, py / 2);
6054 let (luma_grid, u_grid, v_grid);
6055 if skip {
6056 y.reconstruct(
6057 px,
6058 py,
6059 8,
6060 mode,
6061 angle_delta_y,
6062 reach,
6063 &vec![0i32; 64],
6064 None,
6065 filter_intra,
6066 smooth_neighbor,
6067 );
6068 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
6069 u.reconstruct(
6070 cpx,
6071 cpy,
6072 4,
6073 uv_predict_mode,
6074 angle_delta_uv,
6075 reach,
6076 &vec![0i32; 16],
6077 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
6078 None,
6079 false,
6080 );
6081 v.reconstruct(
6082 cpx,
6083 cpy,
6084 4,
6085 uv_predict_mode,
6086 angle_delta_uv,
6087 reach,
6088 &vec![0i32; 16],
6089 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
6090 None,
6091 false,
6092 );
6093 luma_grid = vec![0i32; 64];
6094 u_grid = vec![0i32; 16];
6095 v_grid = vec![0i32; 16];
6096 } else if resolved != 4 {
6097 let around = neighbours.around_mi(leaf_mi, 8);
6098 luma_grid = read_plane(
6099 dec,
6100 cdfs,
6101 if reduced_tx_set {
6102 TxbSet::Luma8
6103 } else {
6104 TxbSet::Luma8Set1
6105 },
6106 scans.0,
6107 0,
6108 around[0],
6109 mode,
6110 mode,
6111 angle_delta_y,
6112 reach,
6113 y,
6114 px,
6115 py,
6116 8,
6117 TX8,
6118 base_q_idx,
6119 None,
6120 filter_intra,
6121 None,
6122 smooth_neighbor,
6123 )?;
6124 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
6125 u_grid = read_plane(
6126 dec,
6127 cdfs,
6128 TxbSet::Chroma4,
6129 scans.1,
6130 1,
6131 around[1],
6132 mode,
6133 uv_predict_mode,
6134 angle_delta_uv,
6135 reach,
6136 u,
6137 cpx,
6138 cpy,
6139 4,
6140 TX4,
6141 base_q_idx,
6142 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
6143 None,
6144 None,
6145 false,
6146 )?;
6147 v_grid = read_plane(
6148 dec,
6149 cdfs,
6150 TxbSet::Chroma4,
6151 scans.1,
6152 2,
6153 around[2],
6154 mode,
6155 uv_predict_mode,
6156 angle_delta_uv,
6157 reach,
6158 v,
6159 cpx,
6160 cpy,
6161 4,
6162 TX4,
6163 base_q_idx,
6164 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
6165 None,
6166 None,
6167 false,
6168 )?;
6169 } else {
6170 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
6171 // grid of 4x4 transform units, each predicted from the leaf's own
6172 // 8x8 `mode` and reading its own fresh context off the earlier
6173 // units in this same leaf (the same per-TU pattern `decode_block`'s
6174 // multi-TU branch runs at bigger blocks).
6175 luma_grid = vec![0i32; 64];
6176 for tu_row in 0..2 {
6177 for tu_col in 0..2 {
6178 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
6179 let tu_px = px + tu_col * 4;
6180 let tu_py = py + tu_row * 4;
6181 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
6182 let tu_reach = Reach::of(4, tu_px, tu_py, y.width, y.height);
6183 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
6184 let tu_grid = read_plane(
6185 dec,
6186 cdfs,
6187 if reduced_tx_set {
6188 TxbSet::Luma4
6189 } else {
6190 TxbSet::Luma4Set1
6191 },
6192 scans.1,
6193 0,
6194 tu_around,
6195 mode,
6196 mode,
6197 angle_delta_y,
6198 tu_reach,
6199 y,
6200 tu_px,
6201 tu_py,
6202 4,
6203 4,
6204 base_q_idx,
6205 None,
6206 filter_intra,
6207 Some(tu_skip_ctx),
6208 smooth_neighbor,
6209 )?;
6210 if std::env::var_os("EC_AV1_TRACE").is_some() {
6211 eprintln!(
6212 "TRACE tu_bitpos mi=({},{}) tell={}",
6213 tu_mi.0,
6214 tu_mi.1,
6215 dec.debug_bitpos()
6216 );
6217 }
6218 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
6219 }
6220 }
6221 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
6222 let chroma_around = neighbours.around_mi(leaf_mi, 8);
6223 u_grid = read_plane(
6224 dec,
6225 cdfs,
6226 TxbSet::Chroma4,
6227 scans.1,
6228 1,
6229 chroma_around[1],
6230 mode,
6231 uv_predict_mode,
6232 angle_delta_uv,
6233 reach,
6234 u,
6235 cpx,
6236 cpy,
6237 4,
6238 TX4,
6239 base_q_idx,
6240 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
6241 None,
6242 None,
6243 false,
6244 )?;
6245 v_grid = read_plane(
6246 dec,
6247 cdfs,
6248 TxbSet::Chroma4,
6249 scans.1,
6250 2,
6251 chroma_around[2],
6252 mode,
6253 uv_predict_mode,
6254 angle_delta_uv,
6255 reach,
6256 v,
6257 cpx,
6258 cpy,
6259 4,
6260 TX4,
6261 base_q_idx,
6262 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
6263 None,
6264 None,
6265 false,
6266 )?;
6267 // `record_split_luma` expects a `record`-style `(r, c)` position in
6268 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
6269 // already in mi units, so calling it here double-scaled the
6270 // position. Plane 0 is already correct per-TU from the
6271 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
6272 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
6273 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
6274 // leaf's own 8x8 side over `MI`).
6275 let side_mi = 2;
6276 for cell in 0..side_mi {
6277 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
6278 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
6279 }
6280 let round_up_even = |n: usize| n.div_ceil(2) * 2;
6281 let bound_h = round_up_even(neighbours.mi_rows);
6282 let bound_w = round_up_even(neighbours.mi_cols);
6283 let u_state = neighbour_state(&u_grid);
6284 let v_state = neighbour_state(&v_grid);
6285 for cell in 0..side_mi {
6286 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
6287 neighbours.left[leaf_mi.0 + cell][1] = u_state;
6288 neighbours.left[leaf_mi.0 + cell][2] = v_state;
6289 }
6290 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
6291 neighbours.above[leaf_mi.1 + cell][1] = u_state;
6292 neighbours.above[leaf_mi.1 + cell][2] = v_state;
6293 }
6294 }
6295 neighbours.fill_skip_grid(leaf_mi, 2, skip);
6296 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0);
6297 return Ok(mode);
6298 }
6299 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
6300 neighbours.fill_skip_grid(leaf_mi, 2, skip);
6301 neighbours.fill_lf_grid(leaf_mi, 2, 8, 0);
6302 Ok(mode)
6303}
6304
6305/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
6306/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
6307/// (mod 8) reuse the same table.
6308const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
6309 [(-1, 1), (-2, 2)],
6310 [(0, 1), (-1, 2)],
6311 [(0, 1), (0, 2)],
6312 [(0, 1), (1, 2)],
6313 [(1, 1), (2, 2)],
6314 [(1, 0), (2, 1)],
6315 [(1, 0), (2, 0)],
6316 [(1, 0), (2, -1)],
6317];
6318/// A neighbour tap outside the frame's true extent -- `constrain` reads this
6319/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
6320const CDEF_VERY_LARGE: i32 = 0x4000;
6321const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
6322const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
6323
6324fn cdef_msb(x: i32) -> i32 {
6325 31 - x.leading_zeros() as i32
6326}
6327
6328/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
6329/// centre sample a filter tap is allowed to contribute.
6330fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
6331 if threshold == 0 {
6332 return 0;
6333 }
6334 let shift = (damping - cdef_msb(threshold)).max(0);
6335 diff.signum() * (threshold - (diff.abs() >> shift)).clamp(0, diff.abs())
6336}
6337
6338/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
6339/// direction of an 8x8 luma window and the variance gap between it and its
6340/// orthogonal, `sample(row, col)` reading that window's own pixels.
6341fn cdef_find_dir(coeff_shift: i32, sample: impl Fn(usize, usize) -> i32) -> (usize, i32) {
6342 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
6343 let mut partial = [[0i64; 15]; 8];
6344 for i in 0..8i64 {
6345 for j in 0..8i64 {
6346 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
6347 // accumulating, same as `constrain`'s threshold shift below.
6348 let x = i64::from(sample(i as usize, j as usize) >> coeff_shift) - 128;
6349 partial[0][(i + j) as usize] += x;
6350 partial[1][(i + j / 2) as usize] += x;
6351 partial[2][i as usize] += x;
6352 partial[3][(3 + i - j / 2) as usize] += x;
6353 partial[4][(7 + i - j) as usize] += x;
6354 partial[5][(3 - i / 2 + j) as usize] += x;
6355 partial[6][j as usize] += x;
6356 partial[7][(i / 2 + j) as usize] += x;
6357 }
6358 }
6359 let mut cost = [0i64; 8];
6360 for i in 0..8usize {
6361 cost[2] += partial[2][i] * partial[2][i];
6362 cost[6] += partial[6][i] * partial[6][i];
6363 }
6364 cost[2] *= DIV_TABLE[8];
6365 cost[6] *= DIV_TABLE[8];
6366 for i in 0..7usize {
6367 cost[0] += (partial[0][i] * partial[0][i] + partial[0][14 - i] * partial[0][14 - i])
6368 * DIV_TABLE[i + 1];
6369 cost[4] += (partial[4][i] * partial[4][i] + partial[4][14 - i] * partial[4][14 - i])
6370 * DIV_TABLE[i + 1];
6371 }
6372 cost[0] += partial[0][7] * partial[0][7] * DIV_TABLE[8];
6373 cost[4] += partial[4][7] * partial[4][7] * DIV_TABLE[8];
6374 for i in (1..8).step_by(2) {
6375 for j in 0..5usize {
6376 cost[i] += partial[i][3 + j] * partial[i][3 + j];
6377 }
6378 cost[i] *= DIV_TABLE[8];
6379 for j in 0..3usize {
6380 cost[i] += (partial[i][j] * partial[i][j] + partial[i][10 - j] * partial[i][10 - j])
6381 * DIV_TABLE[2 * j + 2];
6382 }
6383 }
6384 let mut best_cost = 0i64;
6385 let mut best_dir = 0usize;
6386 for (i, &c) in cost.iter().enumerate() {
6387 if c > best_cost {
6388 best_cost = c;
6389 best_dir = i;
6390 }
6391 }
6392 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
6393 (best_dir, var as i32)
6394}
6395
6396/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
6397/// (high variance gap) gets more deringing than a flat or non-directional
6398/// one, only ever applied to the luma primary strength.
6399fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
6400 if var == 0 {
6401 return 0;
6402 }
6403 let i = if var >> 6 != 0 {
6404 cdef_msb(var >> 6).min(12)
6405 } else {
6406 0
6407 };
6408 (strength * (4 + i) + 8) >> 4
6409}
6410
6411/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
6412/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
6413/// previously-filtered neighbour must never feed this block's own sum).
6414#[allow(clippy::too_many_arguments)]
6415fn cdef_filter_block(
6416 sample: impl Fn(i32, i32) -> i32,
6417 dst: &mut PlaneBuf,
6418 ox: usize,
6419 oy: usize,
6420 bw: usize,
6421 bh: usize,
6422 pri_strength: i32,
6423 sec_strength: i32,
6424 dir: usize,
6425 pri_damping: i32,
6426 sec_damping: i32,
6427 enable_primary: bool,
6428 enable_secondary: bool,
6429 coeff_shift: i32,
6430) {
6431 let clipping_required = enable_primary && enable_secondary;
6432 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
6433 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
6434 // derivative) carries the bit-depth shift, so the tap-set parity bit
6435 // must be read back above that shift, not off the raw low bit.
6436 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
6437 for i in 0..bh {
6438 for j in 0..bw {
6439 let x = sample(i as i32, j as i32);
6440 let mut sum = 0i32;
6441 let mut max = x;
6442 let mut min = x;
6443 for k in 0..2usize {
6444 if enable_primary {
6445 let (tr, tc) = CDEF_DIRECTIONS[dir][k];
6446 let p0 = sample(i as i32 + tr, j as i32 + tc);
6447 let p1 = sample(i as i32 - tr, j as i32 - tc);
6448 sum += pri_taps[k] * cdef_constrain(p0 - x, pri_strength, pri_damping);
6449 sum += pri_taps[k] * cdef_constrain(p1 - x, pri_strength, pri_damping);
6450 if clipping_required {
6451 if p0 != CDEF_VERY_LARGE {
6452 max = max.max(p0);
6453 }
6454 if p1 != CDEF_VERY_LARGE {
6455 max = max.max(p1);
6456 }
6457 min = min.min(p0).min(p1);
6458 }
6459 }
6460 if enable_secondary {
6461 let (tr0, tc0) = CDEF_DIRECTIONS[(dir + 2) & 7][k];
6462 let (tr1, tc1) = CDEF_DIRECTIONS[(dir + 6) & 7][k];
6463 let s0 = sample(i as i32 + tr0, j as i32 + tc0);
6464 let s1 = sample(i as i32 - tr0, j as i32 - tc0);
6465 let s2 = sample(i as i32 + tr1, j as i32 + tc1);
6466 let s3 = sample(i as i32 - tr1, j as i32 - tc1);
6467 if clipping_required {
6468 for s in [s0, s1, s2, s3] {
6469 if s != CDEF_VERY_LARGE {
6470 max = max.max(s);
6471 }
6472 }
6473 min = min.min(s0).min(s1).min(s2).min(s3);
6474 }
6475 sum += CDEF_SEC_TAPS[k]
6476 * (cdef_constrain(s0 - x, sec_strength, sec_damping)
6477 + cdef_constrain(s1 - x, sec_strength, sec_damping)
6478 + cdef_constrain(s2 - x, sec_strength, sec_damping)
6479 + cdef_constrain(s3 - x, sec_strength, sec_damping));
6480 }
6481 }
6482 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
6483 if clipping_required {
6484 y = y.clamp(min, max);
6485 }
6486 dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, sample_max()) as u16;
6487 }
6488 }
6489}
6490
6491/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
6492/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
6493/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
6494/// every block's level comes from [`LoopFilterParams::level`] plus the
6495/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
6496/// `get_filter_level`, precomputed per-block here rather than cached in a
6497/// table the way libaom's `av1_loop_filter_frame_init` does).
6498///
6499/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
6500/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
6501fn apply_deblock(
6502 y: &mut PlaneBuf,
6503 u: &mut PlaneBuf,
6504 v: &mut PlaneBuf,
6505 lf: &LoopFilterParams,
6506 n: &Neighbours,
6507 frame_width: usize,
6508 frame_height: usize,
6509) {
6510 if lf.level[0] != 0 || lf.level[1] != 0 {
6511 deblock_plane(y, 0, lf, n, frame_width, frame_height);
6512 }
6513 if lf.level[2] != 0 {
6514 deblock_plane(u, 1, lf, n, frame_width, frame_height);
6515 }
6516 if lf.level[3] != 0 {
6517 deblock_plane(v, 2, lf, n, frame_width, frame_height);
6518 }
6519}
6520
6521/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
6522/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
6523/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
6524/// mi unit under this decoder's assumed 4:2:0 subsampling).
6525fn plane_to_mi(chroma: bool, coord: usize) -> usize {
6526 if chroma { coord / 2 } else { coord / 4 }
6527}
6528
6529/// This plane's own transform width in pixels at the covering block, spec
6530/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
6531/// width directly; chroma halves it (this decoder's UV transform is always
6532/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
6533/// under 4:2:0 and a block that never splits its own transform).
6534fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
6535 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
6536 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
6537}
6538
6539/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
6540/// edges step and gate by transform height, which differs from width only
6541/// on rect partition strips.
6542fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
6543 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
6544 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
6545}
6546
6547/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
6548/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
6549/// present only when its neighbour exists inside the true frame -- whether
6550/// the block immediately above (at this block's own leftmost mi column) or
6551/// to the left (at its own topmost mi row) coded a transform at least as wide
6552/// as `own_side`.
6553fn tx_size_context(n: &Neighbours, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
6554 let above = mi_r > n.tile_row0_mi && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_side;
6555 let left = mi_c > n.tile_col0_mi && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_side;
6556 usize::from(above) + usize::from(left)
6557}
6558
6559/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
6560/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
6561/// the transform's own side in pixels (`side >> depth`) -- this decoder's
6562/// four square categories (8/16/32/64) each halve at most twice, matching
6563/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
6564fn read_tx_size(
6565 dec: &mut SymbolDecoder,
6566 cdfs: &mut Cdfs,
6567 n: &Neighbours,
6568 at_mi: (usize, usize),
6569 side: usize,
6570) -> usize {
6571 let ctx = tx_size_context(n, at_mi, side);
6572 let depth = match side {
6573 8 => {
6574 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
6575 }
6576 16 => {
6577 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
6578 }
6579 32 => {
6580 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
6581 }
6582 64 => {
6583 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
6584 }
6585 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64"),
6586 };
6587 if std::env::var_os("EC_TRACE_MODE_STEP").is_some() {
6588 let (rng, _) = dec.debug_state();
6589 let (mi_r, mi_c) = at_mi;
6590 eprintln!(
6591 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
6592 );
6593 }
6594 if depth != 0 {
6595 TX_DEPTH_HITS.with(|c| c.set(c.get() + 1));
6596 }
6597 side >> depth
6598}
6599
6600/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
6601/// the only four sizes a `TxMode::Select` block's coded coefficient grid
6602/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
6603fn scan_for<'a>(
6604 tx_px: usize,
6605 scan32: &'a [u16],
6606 scan16: &'a [u16],
6607 scan8: &'a [u16],
6608 scan4: &'a [u16],
6609) -> &'a [u16] {
6610 match tx_px {
6611 32 => scan32,
6612 16 => scan16,
6613 8 => scan8,
6614 4 => scan4,
6615 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
6616 }
6617}
6618
6619/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
6620/// from -- 64 is only ever the 64x64-block, depth-0, corner-scanned case
6621/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
6622/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
6623/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
6624/// regardless of the flag (`av1_get_ext_tx_set_type`'s
6625/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
6626/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
6627/// second table ([`TxbSet::Luma8Set1`]/[`TxbSet::Luma4Set1`]).
6628/// [`txbset_for`], for a block libaom's `is_inter_block` calls inter -- which
6629/// an intrabc block is (`blockd.h:373`), so its `tx_type` comes off the
6630/// inter `ext_tx` sets, never the mode-indexed intra ones.
6631fn txbset_for_inter(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
6632 match tx_px {
6633 64 => TxbSet::Luma64,
6634 32 => TxbSet::Luma32Inter,
6635 16 if reduced_tx_set => TxbSet::Luma16Inter,
6636 16 => TxbSet::Luma16InterSet1,
6637 8 if reduced_tx_set => TxbSet::Luma8Inter,
6638 8 => TxbSet::Luma8InterSet1,
6639 _ => TxbSet::Luma64,
6640 }
6641}
6642
6643fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
6644 match tx_px {
6645 64 => TxbSet::Luma64,
6646 32 => TxbSet::Luma32,
6647 16 => TxbSet::Luma16,
6648 8 if reduced_tx_set => TxbSet::Luma8,
6649 8 => TxbSet::Luma8Set1,
6650 4 if reduced_tx_set => TxbSet::Luma4,
6651 4 => TxbSet::Luma4Set1,
6652 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
6653 }
6654}
6655
6656/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
6657/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
6658fn unit_log2(px: u32) -> i32 {
6659 if px == 0 {
6660 0
6661 } else {
6662 px.trailing_zeros() as i32 - 2
6663 }
6664}
6665
6666/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
6667/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
6668/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
6669/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
6670/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
6671/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
6672/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
6673/// block anywhere aborted the whole stream's decode before comparison).
6674fn lf_level(
6675 lf: &LoopFilterParams,
6676 plane_idx: usize,
6677 dir: usize,
6678 ref_frame: i8,
6679 delta_lf: i32,
6680 segment_id: u8,
6681) -> i32 {
6682 let base = i32::from(if plane_idx == 0 {
6683 lf.level[dir]
6684 } else if plane_idx == 1 {
6685 lf.level[2]
6686 } else {
6687 lf.level[3]
6688 });
6689 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
6690 // ref/mode delta scaling below, and regardless of `delta_enabled`
6691 // (that flag only gates `ref_deltas`/`mode_deltas`).
6692 let base = (base + delta_lf).clamp(0, 63);
6693 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
6694 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
6695 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
6696 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
6697 // for chroma.
6698 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
6699 let base = match seg_feature(usize::from(segment_id), feature) {
6700 Some(data) => (base + data).clamp(0, 63),
6701 None => base,
6702 };
6703 if !lf.delta_enabled {
6704 return base;
6705 }
6706 let scale = 1i32 << (base >> 5);
6707 let is_inter = ref_frame != 0;
6708 let is_globalmv = ref_frame < 0;
6709 let ref_idx = ref_frame.unsigned_abs() as usize;
6710 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
6711 if is_inter {
6712 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
6713 }
6714 lvl.clamp(0, 63)
6715}
6716
6717/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
6718/// no-segmentation, no-delta-LF path and to this decoder's own invariant
6719/// that a coded block's transform is always its own full size -- so a TU
6720/// edge is always also a PU edge, and the "both sides skipped, not a PU
6721/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
6722/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
6723/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
6724fn edge_params(
6725 lf: &LoopFilterParams,
6726 n: &Neighbours,
6727 plane_idx: usize,
6728 dir: usize,
6729 chroma: bool,
6730 x0: usize,
6731 y0: usize,
6732) -> Option<(u8, i32)> {
6733 let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0));
6734 let cur_tx = if dir == 0 {
6735 tx_px_at(n, chroma, mi_r, mi_c)
6736 } else {
6737 tx_h_px_at(n, chroma, mi_r, mi_c)
6738 };
6739 if cur_tx == 0 || (if dir == 0 { x0 } else { y0 }) % cur_tx as usize != 0 {
6740 return None;
6741 }
6742 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
6743 let (pv_mi_r, pv_mi_c) = if dir == 0 {
6744 (mi_r, mi_c - 1)
6745 } else {
6746 (mi_r - 1, mi_c)
6747 };
6748 let pv_tx = if dir == 0 {
6749 tx_px_at(n, chroma, pv_mi_r, pv_mi_c)
6750 } else {
6751 tx_h_px_at(n, chroma, pv_mi_r, pv_mi_c)
6752 };
6753 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
6754 let delta_idx = if plane_idx == 0 { dir } else { plane_idx + 1 };
6755 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][delta_idx]);
6756 let pv_delta_lf = i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][delta_idx]);
6757
6758 let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf, segment_id_at(mi_r, mi_c));
6759 let pv_level = lf_level(
6760 lf,
6761 plane_idx,
6762 dir,
6763 pv_ref,
6764 pv_delta_lf,
6765 segment_id_at(pv_mi_r, pv_mi_c),
6766 );
6767 if cur_level == 0 && pv_level == 0 {
6768 return None;
6769 }
6770 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
6771 let len: u8 = if chroma {
6772 if dim == 0 { 4 } else { 6 }
6773 } else {
6774 [4, 8, 14, 14, 14][dim]
6775 };
6776 let level = if cur_level != 0 { cur_level } else { pv_level };
6777 DEBLOCK_HITS.with(|c| c.set(c.get() + 1));
6778 Some((len, level))
6779}
6780
6781/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
6782fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
6783 let sharpness = i32::from(sharpness);
6784 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
6785 let mut lim = level >> shift;
6786 if sharpness > 0 {
6787 lim = lim.min(9 - sharpness);
6788 }
6789 lim = lim.max(1);
6790 (2 * (level + 2) + lim, lim, level >> 4)
6791}
6792
6793fn sclamp(v: i32) -> i32 {
6794 // libaom's `signed_char_clamp_high`: the clamp range scales with
6795 // `128 << (bit_depth - 8)` alongside the centering constant below.
6796 let scale = 1i32 << (bit_depth() - 8);
6797 v.clamp(-128 * scale, 128 * scale - 1)
6798}
6799
6800fn round_pow2(v: i32, n: u32) -> i32 {
6801 (v + (1 << (n - 1))) >> n
6802}
6803
6804/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
6805/// fallback.
6806fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32) -> [i32; 4] {
6807 if !mask {
6808 return [p1, p0, q0, q1];
6809 }
6810 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
6811 let centre = 128i32 << (bit_depth() - 8);
6812 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
6813 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
6814 let filter = sclamp(outer + 3 * (qs0 - ps0));
6815 let filter1 = sclamp(filter + 4) >> 3;
6816 let filter2 = sclamp(filter + 3) >> 3;
6817 let oq0 = sclamp(qs0 - filter1) + centre;
6818 let op0 = sclamp(ps0 + filter2) + centre;
6819 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
6820 let oq1 = sclamp(qs1 - tap) + centre;
6821 let op1 = sclamp(ps1 + tap) + centre;
6822 [op1, op0, oq0, oq1]
6823}
6824
6825/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
6826/// `filter4`'s narrow taps.
6827#[allow(clippy::too_many_arguments)]
6828fn filter6(
6829 mask: bool,
6830 thresh: i32,
6831 flat: bool,
6832 p2: i32,
6833 p1: i32,
6834 p0: i32,
6835 q0: i32,
6836 q1: i32,
6837 q2: i32,
6838) -> [i32; 4] {
6839 if flat && mask {
6840 [
6841 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
6842 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
6843 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
6844 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
6845 ]
6846 } else {
6847 filter4(mask, thresh, p1, p0, q0, q1)
6848 }
6849}
6850
6851/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
6852#[allow(clippy::too_many_arguments)]
6853fn filter8(
6854 mask: bool,
6855 thresh: i32,
6856 flat: bool,
6857 p3: i32,
6858 p2: i32,
6859 p1: i32,
6860 p0: i32,
6861 q0: i32,
6862 q1: i32,
6863 q2: i32,
6864 q3: i32,
6865) -> [i32; 6] {
6866 if flat && mask {
6867 [
6868 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
6869 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
6870 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
6871 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
6872 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
6873 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
6874 ]
6875 } else {
6876 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1);
6877 [p2, op1, op0, oq0, oq1, q2]
6878 }
6879}
6880
6881/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
6882/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
6883/// way -- they are only ever taps here, never written).
6884#[allow(clippy::too_many_arguments)]
6885fn filter14(
6886 mask: bool,
6887 thresh: i32,
6888 flat: bool,
6889 flat2: bool,
6890 p6: i32,
6891 p5: i32,
6892 p4: i32,
6893 p3: i32,
6894 p2: i32,
6895 p1: i32,
6896 p0: i32,
6897 q0: i32,
6898 q1: i32,
6899 q2: i32,
6900 q3: i32,
6901 q4: i32,
6902 q5: i32,
6903 q6: i32,
6904) -> [i32; 12] {
6905 if flat2 && flat && mask {
6906 [
6907 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
6908 round_pow2(
6909 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
6910 4,
6911 ),
6912 round_pow2(
6913 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
6914 4,
6915 ),
6916 round_pow2(
6917 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
6918 4,
6919 ),
6920 round_pow2(
6921 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
6922 4,
6923 ),
6924 round_pow2(
6925 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
6926 4,
6927 ),
6928 round_pow2(
6929 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
6930 4,
6931 ),
6932 round_pow2(
6933 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
6934 4,
6935 ),
6936 round_pow2(
6937 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
6938 4,
6939 ),
6940 round_pow2(
6941 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
6942 4,
6943 ),
6944 round_pow2(
6945 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
6946 4,
6947 ),
6948 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
6949 ]
6950 } else {
6951 let [op2, op1, op0, oq0, oq1, oq2] =
6952 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3);
6953 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
6954 }
6955}
6956
6957/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
6958/// the first (`q0`) sample past the edge, `outer_stride` advances to the
6959/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
6960/// the next along the edge's own filtering direction.
6961#[allow(clippy::too_many_arguments)]
6962fn filter_edge(
6963 data: &mut [u16],
6964 base: usize,
6965 outer_stride: isize,
6966 tap_stride: isize,
6967 len: u8,
6968 level: i32,
6969 sharpness: u8,
6970) {
6971 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
6972 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
6973 // every 8-bit threshold (including the flat masks' fixed `1`) is
6974 // compared against a raw pixel difference on the stream's own bit-depth
6975 // scale, so each is shifted left by `bit_depth - 8` before use.
6976 let shift = bit_depth() - 8;
6977 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
6978 let flat_thresh = 1i32 << shift;
6979 for i in 0..4isize {
6980 let center = (base as isize + i * outer_stride) as usize;
6981 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
6982 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
6983 match len {
6984 4 => {
6985 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
6986 let mask = (p1 - p0).abs() <= limit
6987 && (q1 - q0).abs() <= limit
6988 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
6989 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1);
6990 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
6991 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
6992 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
6993 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
6994 }
6995 6 => {
6996 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
6997 let mask = (p2 - p1).abs() <= limit
6998 && (p1 - p0).abs() <= limit
6999 && (q1 - q0).abs() <= limit
7000 && (q2 - q1).abs() <= limit
7001 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
7002 let flat = (p1 - p0).abs() <= flat_thresh
7003 && (q1 - q0).abs() <= flat_thresh
7004 && (p2 - p0).abs() <= flat_thresh
7005 && (q2 - q0).abs() <= flat_thresh;
7006 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2);
7007 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
7008 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
7009 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
7010 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
7011 }
7012 8 => {
7013 let (p3, p2, p1, p0, q0, q1, q2, q3) =
7014 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
7015 let mask = (p3 - p2).abs() <= limit
7016 && (p2 - p1).abs() <= limit
7017 && (p1 - p0).abs() <= limit
7018 && (q1 - q0).abs() <= limit
7019 && (q2 - q1).abs() <= limit
7020 && (q3 - q2).abs() <= limit
7021 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
7022 let flat = (p1 - p0).abs() <= flat_thresh
7023 && (q1 - q0).abs() <= flat_thresh
7024 && (p2 - p0).abs() <= flat_thresh
7025 && (q2 - q0).abs() <= flat_thresh
7026 && (p3 - p0).abs() <= flat_thresh
7027 && (q3 - q0).abs() <= flat_thresh;
7028 let [op2, op1, op0, oq0, oq1, oq2] =
7029 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3);
7030 data[idx(-3)] = op2.clamp(0, sample_max()) as u16;
7031 data[idx(-2)] = op1.clamp(0, sample_max()) as u16;
7032 data[idx(-1)] = op0.clamp(0, sample_max()) as u16;
7033 data[idx(0)] = oq0.clamp(0, sample_max()) as u16;
7034 data[idx(1)] = oq1.clamp(0, sample_max()) as u16;
7035 data[idx(2)] = oq2.clamp(0, sample_max()) as u16;
7036 }
7037 _ => {
7038 let (p6, p5, p4, p3, p2, p1, p0) =
7039 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
7040 let (q0, q1, q2, q3, q4, q5, q6) =
7041 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
7042 let mask = (p3 - p2).abs() <= limit
7043 && (p2 - p1).abs() <= limit
7044 && (p1 - p0).abs() <= limit
7045 && (q1 - q0).abs() <= limit
7046 && (q2 - q1).abs() <= limit
7047 && (q3 - q2).abs() <= limit
7048 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
7049 let flat = (p1 - p0).abs() <= flat_thresh
7050 && (q1 - q0).abs() <= flat_thresh
7051 && (p2 - p0).abs() <= flat_thresh
7052 && (q2 - q0).abs() <= flat_thresh
7053 && (p3 - p0).abs() <= flat_thresh
7054 && (q3 - q0).abs() <= flat_thresh;
7055 let flat2 = (p4 - p0).abs() <= flat_thresh
7056 && (q4 - q0).abs() <= flat_thresh
7057 && (p5 - p0).abs() <= flat_thresh
7058 && (q5 - q0).abs() <= flat_thresh
7059 && (p6 - p0).abs() <= flat_thresh
7060 && (q6 - q0).abs() <= flat_thresh;
7061 let out = filter14(
7062 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
7063 q6,
7064 );
7065 for (k, v) in (-6..=5isize).zip(out) {
7066 data[idx(k)] = v.clamp(0, sample_max()) as u16;
7067 }
7068 }
7069 }
7070 }
7071}
7072
7073/// One plane's worth of spec 7.14: every vertical edge across the plane,
7074/// then every horizontal edge (the order the spec and libaom both use).
7075fn deblock_plane(
7076 plane: &mut PlaneBuf,
7077 plane_idx: usize,
7078 lf: &LoopFilterParams,
7079 n: &Neighbours,
7080 frame_width: usize,
7081 frame_height: usize,
7082) {
7083 let chroma = plane_idx != 0;
7084 // r7: libaom clips the deblock loop to the CODED frame's own
7085 // width/height, not the mi-aligned `true_width`/`true_height` margin
7086 // (the padding up to the next 8-pixel/superblock boundary that
7087 // reconstruction still fills in but the loop filter never visits).
7088 // Confirmed against the superres gate: with the margin included, the
7089 // last coded mi column's horizontal edges were filtered when libaom's
7090 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
7091 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
7092 let (cw, ch) = if chroma {
7093 (frame_width.div_ceil(2), frame_height.div_ceil(2))
7094 } else {
7095 (frame_width, frame_height)
7096 };
7097 let (tw, th, stride) = (
7098 plane.true_width.min(cw),
7099 plane.true_height.min(ch),
7100 plane.width,
7101 );
7102 let mut y0 = 0usize;
7103 while y0 < th {
7104 let mut x0 = 4usize;
7105 while x0 < tw {
7106 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) {
7107 filter_edge(
7108 &mut plane.data,
7109 y0 * stride + x0,
7110 stride as isize,
7111 1,
7112 len,
7113 level,
7114 lf.sharpness,
7115 );
7116 }
7117 x0 += 4;
7118 }
7119 y0 += 4;
7120 }
7121 let mut x0 = 0usize;
7122 while x0 < tw {
7123 let mut y0 = 4usize;
7124 while y0 < th {
7125 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) {
7126 if std::env::var_os("EC_AV1_DEBLOCK_TRACE").is_some()
7127 && plane_idx == 0
7128 && x0 == 44
7129 {
7130 eprintln!(
7131 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
7132 lf.sharpness
7133 );
7134 }
7135 filter_edge(
7136 &mut plane.data,
7137 y0 * stride + x0,
7138 1,
7139 stride as isize,
7140 len,
7141 level,
7142 lf.sharpness,
7143 );
7144 }
7145 y0 += 4;
7146 }
7147 x0 += 4;
7148 }
7149}
7150
7151fn apply_cdef(
7152 y: &mut PlaneBuf,
7153 u: &mut PlaneBuf,
7154 v: &mut PlaneBuf,
7155 cdef: &CdefParams,
7156 skip_grid: &Neighbours,
7157) {
7158 // `cdef.bits == 0` still means "no filtering at all" whenever the single
7159 // (index 0) strength pair is all-zero -- the fast path every existing
7160 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
7161 // at every index, but that is rare enough not to special-case; the
7162 // per-superblock lookup below degrades to the same index-0 read anyway
7163 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
7164 if cdef.bits == 0
7165 && cdef.y_pri_strength[0] == 0
7166 && cdef.y_sec_strength[0] == 0
7167 && cdef.uv_pri_strength[0] == 0
7168 && cdef.uv_sec_strength[0] == 0
7169 {
7170 return;
7171 }
7172 let sb_cols = CDEF_SB_COLS.with(|c| c.get());
7173 let idx_grid = CDEF_IDX_GRID.with(|g| g.borrow().clone());
7174 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
7175 if sb_cols == 0 {
7176 return 0;
7177 }
7178 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
7179 idx_grid
7180 .get(sb_r * sb_cols + sb_c)
7181 .copied()
7182 .unwrap_or(0) as usize
7183 };
7184 let src_y = y.data.clone();
7185 let src_u = u.data.clone();
7186 let src_v = v.data.clone();
7187 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
7188 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
7189 let coeff_shift = i32::from(bit_depth()) - 8;
7190 let damping = i32::from(cdef.damping) + coeff_shift;
7191 let damping_uv = (damping - 1).max(0);
7192 let mut mi_r = 0usize;
7193 while mi_r < skip_grid.mi_rows {
7194 let mut mi_c = 0usize;
7195 while mi_c < skip_grid.mi_cols {
7196 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
7197 let sidx = strength_idx(mi_r, mi_c);
7198 let (ox, oy) = (mi_c * 4, mi_r * 4);
7199 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
7200 let sample_y = |r: i32, c: i32| -> i32 {
7201 let (ny, nx) = (oy as i32 + r, ox as i32 + c);
7202 if ny < 0 || nx < 0 || ny as usize >= y_true_h || nx as usize >= y_true_w {
7203 CDEF_VERY_LARGE
7204 } else {
7205 i32::from(src_y[ny as usize * y_stride + nx as usize])
7206 }
7207 };
7208 let (dir, var) = cdef_find_dir(coeff_shift, |r, c| {
7209 let (ny, nx) = ((oy + r).min(y_true_h - 1), (ox + c).min(y_true_w - 1));
7210 i32::from(src_y[ny * y_stride + nx])
7211 });
7212
7213 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
7214 // -- each plane zeroes the shared direction when *its own*
7215 // frame-level primary strength is 0, independent of the
7216 // per-block adjusted `t` and of the other plane's strength.
7217 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
7218 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
7219 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
7220 let t = cdef_adjust_strength(y_pri_strength, var);
7221 let enable_primary = t != 0;
7222 let enable_secondary = y_sec_strength != 0;
7223 if enable_primary || enable_secondary {
7224 cdef_filter_block(
7225 sample_y,
7226 y,
7227 ox,
7228 oy,
7229 8,
7230 8,
7231 t,
7232 y_sec_strength,
7233 y_dir,
7234 damping,
7235 damping,
7236 enable_primary,
7237 enable_secondary,
7238 coeff_shift,
7239 );
7240 }
7241
7242 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
7243 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
7244 let uv_dir = if t_uv != 0 { dir } else { 0 };
7245 let enable_primary_uv = t_uv != 0;
7246 let enable_secondary_uv = uv_sec_strength != 0;
7247 if enable_primary_uv || enable_secondary_uv {
7248 let (cox, coy) = (ox / 2, oy / 2);
7249 for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] {
7250 let (tw, th) = (plane.true_width, plane.true_height);
7251 let stride = plane.width;
7252 let sample_uv = |r: i32, c: i32| -> i32 {
7253 let (ny, nx) = (coy as i32 + r, cox as i32 + c);
7254 if ny < 0 || nx < 0 || ny as usize >= th || nx as usize >= tw {
7255 CDEF_VERY_LARGE
7256 } else {
7257 i32::from(src_p[ny as usize * stride + nx as usize])
7258 }
7259 };
7260 cdef_filter_block(
7261 sample_uv,
7262 plane,
7263 cox,
7264 coy,
7265 4,
7266 4,
7267 t_uv,
7268 uv_sec_strength,
7269 uv_dir,
7270 damping_uv,
7271 damping_uv,
7272 enable_primary_uv,
7273 enable_secondary_uv,
7274 coeff_shift,
7275 );
7276 }
7277 }
7278 }
7279 mi_c += 2;
7280 }
7281 mi_r += 2;
7282 }
7283}
7284
7285/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
7286/// ordering note: libaom also runs `superres_post_decode` between the two,
7287/// but this decoder never implements super-resolution, so there is nothing
7288/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
7289/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
7290/// restoration's stripe-boundary rows read from it instead of the
7291/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
7292#[allow(clippy::too_many_arguments)]
7293fn apply_loop_restoration(
7294 y: &mut PlaneBuf,
7295 u: &mut PlaneBuf,
7296 v: &mut PlaneBuf,
7297 deblocked_y: &PlaneBuf,
7298 deblocked_u: &PlaneBuf,
7299 deblocked_v: &PlaneBuf,
7300 lr: &LoopRestorationParams,
7301 grid: &crate::restoration::RestorationGrid,
7302) {
7303 y.data = crate::restoration::apply_loop_restoration_plane(
7304 &y.data,
7305 &deblocked_y.data,
7306 y.width,
7307 y.true_width,
7308 y.true_height,
7309 0,
7310 lr.frame_restoration_type[0],
7311 lr.loop_restoration_size[0],
7312 grid,
7313 0,
7314 );
7315 u.data = crate::restoration::apply_loop_restoration_plane(
7316 &u.data,
7317 &deblocked_u.data,
7318 u.width,
7319 u.true_width,
7320 u.true_height,
7321 1,
7322 lr.frame_restoration_type[1],
7323 lr.loop_restoration_size[1],
7324 grid,
7325 1,
7326 );
7327 v.data = crate::restoration::apply_loop_restoration_plane(
7328 &v.data,
7329 &deblocked_v.data,
7330 v.width,
7331 v.true_width,
7332 v.true_height,
7333 1,
7334 lr.frame_restoration_type[2],
7335 lr.loop_restoration_size[2],
7336 grid,
7337 2,
7338 );
7339}
7340
7341/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
7342/// returning the picture it reconstructs to.
7343///
7344/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
7345/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
7346/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
7347/// `compute_image_size` derives one from the other, but not losslessly: a
7348/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
7349/// what the reconstruction is cropped to on the way out, mirroring
7350/// [`crate::encode::crop_encoded`].
7351///
7352/// # Errors
7353/// Returns an error when a block's partition, mode, skip flag or transform
7354/// type is anything this decoder does not reconstruct (round 2: inter, tx
7355/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
7356/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
7357/// or when the tile payload runs out of the symbols this decode expects (a
7358/// genuinely foreign stream).
7359pub fn decode_key_frame_tile(
7360 data: &[u8],
7361 mi_cols: u32,
7362 mi_rows: u32,
7363 base_q_idx: u8,
7364 frame_width: u32,
7365 frame_height: u32,
7366 enable_filter_intra: bool,
7367 cdef: &CdefParams,
7368 loop_filter: &LoopFilterParams,
7369 tx_select: bool,
7370 reduced_tx_set: bool,
7371 allow_screen_content_tools: bool,
7372 allow_intrabc: bool,
7373) -> Result<Picture> {
7374 let delta = DeltaParams::default();
7375 let single_tile = TileInfo {
7376 mi_col_starts: vec![0, mi_cols],
7377 mi_row_starts: vec![0, mi_rows],
7378 ..TileInfo::default()
7379 };
7380 decode_key_frame_tile_with_cdfs(
7381 &[data],
7382 &single_tile,
7383 mi_cols,
7384 mi_rows,
7385 base_q_idx,
7386 crate::quant::QuantDeltas::default(),
7387 frame_width,
7388 frame_height,
7389 enable_filter_intra,
7390 false,
7391 cdef,
7392 loop_filter,
7393 &LoopRestorationParams::default(),
7394 None,
7395 tx_select,
7396 reduced_tx_set,
7397 allow_screen_content_tools,
7398 allow_intrabc,
7399 delta,
7400 )
7401 .map(|(picture, _)| picture)
7402}
7403
7404thread_local! {
7405 /// lane-superres r3: the real decoded margin beyond `frame_width` up to
7406 /// the mi-aligned `true_width`, set by the most recent
7407 /// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
7408 /// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
7409 /// their reconstructed buffer down from the same mi-aligned extent, so
7410 /// they share this one slot. See each function's own comment at its
7411 /// write site. `None` when there was no margin to save.
7412 static LAST_FRAME_WIDE_MARGIN: std::cell::RefCell<Option<Picture>> =
7413 const { std::cell::RefCell::new(None) };
7414}
7415
7416/// The margin the most recent key- or inter-frame tile decode stashed
7417/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
7418/// reads this immediately after the call, before any other frame
7419/// decode can overwrite it.
7420pub(crate) fn take_last_frame_wide_margin() -> Option<Picture> {
7421 LAST_FRAME_WIDE_MARGIN.with(|m| m.borrow_mut().take())
7422}
7423
7424/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
7425/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
7426/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
7427/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
7428/// since a key frame's own header always forces `primary_ref_frame ==
7429/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
7430/// alongside the picture, for the caller to save into whichever reference
7431/// slots this frame's `refresh_frame_flags` names.
7432pub(crate) fn decode_key_frame_tile_with_cdfs(
7433 tiles: &[&[u8]],
7434 tile_info: &TileInfo,
7435 mi_cols: u32,
7436 mi_rows: u32,
7437 base_q_idx: u8,
7438 // lane-sbpart r11: this frame header's own per-plane DC/AC quantizer
7439 // deltas (spec 5.9.12), threaded to [`QUANT_DELTAS`] at the top of every
7440 // tile alongside [`CURRENT_Q_IDX`].
7441 deltas: crate::quant::QuantDeltas,
7442 frame_width: u32,
7443 frame_height: u32,
7444 enable_filter_intra: bool,
7445 enable_edge_filter: bool,
7446 cdef: &CdefParams,
7447 loop_filter: &LoopFilterParams,
7448 lr: &LoopRestorationParams,
7449 initial_cdfs: Option<Cdfs>,
7450 tx_select: bool,
7451 reduced_tx_set: bool,
7452 allow_screen_content_tools: bool,
7453 allow_intrabc: bool,
7454 // lane-realworld r4: this frame header's own `delta` (spec 5.9.17/5.9.18)
7455 // -- only `q_present`/`q_res` are actually read ([`maybe_read_delta_q`]);
7456 // `stream.rs` still refuses a frame with `lf_present` set before this
7457 // function is ever called.
7458 delta: DeltaParams,
7459) -> Result<(Picture, Cdfs)> {
7460 if mi_cols == 0 || mi_rows == 0 {
7461 return Err(unsupported("a frame with no mode-info grid"));
7462 }
7463 ENABLE_EDGE_FILTER.with(|f| f.set(enable_edge_filter));
7464 let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
7465 INTRABC_MI_GRID.with(|g| {
7466 *g.borrow_mut() = allow_intrabc.then(|| {
7467 (
7468 crate::mvstack::MiGrid::new(mi_cols as usize, mi_rows as usize),
7469 mi_cols as usize,
7470 mi_rows as usize,
7471 )
7472 });
7473 });
7474 INTRABC_DV.with(|c| c.set(None));
7475 CDEF_BITS.with(|c| c.set(cdef.bits));
7476 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
7477 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
7478 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
7479 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
7480 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
7481 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
7482 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
7483 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
7484 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
7485 let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
7486
7487 let mut y = PlaneBuf {
7488 data: vec![0u16; width * height],
7489 width,
7490 height,
7491 true_width,
7492 true_height,
7493 tile_x0: 0,
7494 tile_y0: 0,
7495 tile_x1: width,
7496 tile_y1: height,
7497 };
7498 let mut u = PlaneBuf {
7499 data: vec![0u16; width * height / 4],
7500 width: width / 2,
7501 height: height / 2,
7502 true_width: true_width / 2,
7503 true_height: true_height / 2,
7504 tile_x0: 0,
7505 tile_y0: 0,
7506 tile_x1: width / 2,
7507 tile_y1: height / 2,
7508 };
7509 let mut v = PlaneBuf {
7510 data: vec![0u16; width * height / 4],
7511 width: width / 2,
7512 height: height / 2,
7513 true_width: true_width / 2,
7514 true_height: true_height / 2,
7515 tile_x0: 0,
7516 tile_y0: 0,
7517 tile_x1: width / 2,
7518 tile_y1: height / 2,
7519 };
7520
7521 let scan32 = default_scan(TX32);
7522 let scan16 = default_scan(TX16);
7523 let scan8 = default_scan(TX8);
7524 let scan4 = default_scan(TX4);
7525
7526 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
7527 let mut result_cdfs = base_cdfs.clone();
7528 let mut neighbours = Neighbours::new(
7529 cols32 as usize * 2,
7530 rows32 as usize * 2,
7531 mi_cols as usize,
7532 mi_rows as usize,
7533 );
7534 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
7535 let mut lr_reference = [(
7536 crate::restoration::WienerInfo::default(),
7537 crate::restoration::SgrprojInfo::default(),
7538 ); 3];
7539
7540 // lane-tiles r2: each tile gets its own fresh `SymbolDecoder` over its
7541 // own byte range and its own fresh copy of the frame's initial CDFs
7542 // (spec 5.11.2 `decode_tile`'s `init_symbol`); only the tile named by
7543 // `context_update_tile_id` has its end-of-tile adapted table kept as the
7544 // frame's own output (spec `exit_symbol`) -- every other tile's
7545 // adaptation is discarded, matching the refusal this replaces.
7546 for (tile_idx, &tile_bytes) in tiles.iter().enumerate() {
7547 let tile_num = tile_idx as u32;
7548 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
7549 let mi_row0 = tile_info.mi_row_starts[trow as usize];
7550 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
7551 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
7552 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
7553 // Tile boundaries are always superblock-aligned in mi units (spec
7554 // 5.9.15's uniform/non-uniform derivation both only ever emit
7555 // multiples of the superblock's own mi size), so plain division is
7556 // exact here -- no rounding needed.
7557 // `mi_row0`/`mi_col0` (this tile's own start, `0` or an interior
7558 // tile boundary) are always superblock-aligned by spec 5.9.15; the
7559 // frame's own true final edge (`mi_row_starts`/`mi_col_starts`'
7560 // last entry) is not, so the upper bound needs `div_ceil` the same
7561 // way the whole-frame `sb_rows`/`sb_cols` above does, to keep the
7562 // trailing partial superblock row/column in scope.
7563 let (sb_r0, sb_r1) = ((mi_row0 / SB_MI).min(sb_rows), mi_row1.div_ceil(SB_MI).min(sb_rows));
7564 let (sb_c0, sb_c1) = ((mi_col0 / SB_MI).min(sb_cols), mi_col1.div_ceil(SB_MI).min(sb_cols));
7565
7566 let mut cdfs = base_cdfs.clone();
7567 // spec `decode_tile`: `CurrentQIndex` resets to the frame's own
7568 // `base_q_idx` at the top of every tile, not once per frame.
7569 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
7570 QUANT_DELTAS.with(|c| c.set(deltas));
7571 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
7572 if std::env::var_os("EC_AV1_TRACE").is_some() {
7573 eprintln!(
7574 "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
7575 tile_bytes.len(),
7576 &tile_bytes[..tile_bytes.len().min(8)]
7577 );
7578 }
7579 let mut dec = SymbolDecoder::new(tile_bytes);
7580 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
7581 y.set_tile_origin(
7582 mi_col0 as usize * 4,
7583 mi_row0 as usize * 4,
7584 (mi_col1 as usize * 4).min(y.width),
7585 (mi_row1 as usize * 4).min(y.height),
7586 );
7587 u.set_tile_origin(
7588 mi_col0 as usize * 2,
7589 mi_row0 as usize * 2,
7590 (mi_col1 as usize * 2).min(u.width),
7591 (mi_row1 as usize * 2).min(u.height),
7592 );
7593 v.set_tile_origin(
7594 mi_col0 as usize * 2,
7595 mi_row0 as usize * 2,
7596 (mi_col1 as usize * 2).min(v.width),
7597 (mi_row1 as usize * 2).min(v.height),
7598 );
7599 TILE_HITS.with(|c| c.set(c.get() + 1));
7600
7601 for sb_r in sb_r0..sb_r1 {
7602 neighbours.start_row();
7603 for sb_c in sb_c0..sb_c1 {
7604 crate::restoration::read_lr(
7605 &mut dec,
7606 &mut cdfs,
7607 lr,
7608 &mut lr_grid,
7609 &mut lr_reference,
7610 sb_r * SB_MI,
7611 sb_c * SB_MI,
7612 SB_MI,
7613 );
7614 CDEF_TRANSMITTED.with(|c| c.set(false));
7615 let at = (sb_r as usize * 4, sb_c as usize * 4);
7616 let ctx = neighbours.partition_ctx(at, SB);
7617 let (has_cols, has_rows) = (
7618 sb_c * SB_MI + SB_MI / 2 < mi_cols,
7619 sb_r * SB_MI + SB_MI / 2 < mi_rows,
7620 );
7621 // Recomputed at this superblock's own half (spec
7622 // `decode_partition`): a full alphabet symbol when both halves are
7623 // inside the true frame, a single gathered bit when just one is
7624 // (the superblock cannot be left whole, so this is forced split),
7625 // and nothing at all (SPLIT inferred, no bits) when neither is —
7626 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
7627 // three-way write exactly.
7628 let part = if has_cols && has_rows {
7629 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
7630 if std::env::var_os("EC_AV1_TRACE").is_some() {
7631 eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
7632 }
7633 p
7634 } else {
7635 match (has_cols, has_rows) {
7636 (true, false) => {
7637 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
7638 }
7639 (false, true) => {
7640 dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
7641 }
7642 _ => {}
7643 }
7644 PARTITION_SPLIT
7645 };
7646 match part {
7647 PARTITION_NONE => {
7648 decode_block(
7649 &mut dec,
7650 &mut cdfs,
7651 &mut neighbours,
7652 at,
7653 SB,
7654 TxbSet::Luma64,
7655 TxbSet::Chroma32,
7656 TX32,
7657 TX32,
7658 (&scan32, &scan32),
7659 false,
7660 &mut y,
7661 &mut u,
7662 &mut v,
7663 base_q_idx,
7664 enable_filter_intra,
7665 allow_screen_content_tools,
7666 allow_intrabc,
7667 &scan32,
7668 &scan16,
7669 &scan8,
7670 &scan4,
7671 tx_select,
7672 reduced_tx_set,
7673 )?;
7674 }
7675 PARTITION_SPLIT => {
7676 for q in 0..4 {
7677 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
7678 if r32 >= rows32 || c32 >= cols32 {
7679 continue;
7680 }
7681 let at32 = (r32 as usize * 2, c32 as usize * 2);
7682 let ctx32 = neighbours.partition_ctx(at32, BLOCK);
7683 let (has_cols32, has_rows32) = (
7684 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
7685 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
7686 );
7687 let part32 = if has_cols32 && has_rows32 {
7688 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
7689 if std::env::var_os("EC_AV1_TRACE").is_some() {
7690 let (rng, _) = dec.debug_state();
7691 eprintln!(
7692 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
7693 r32 * BLOCK_MI,
7694 c32 * BLOCK_MI
7695 );
7696 }
7697 p
7698 } else {
7699 match (has_cols32, has_rows32) {
7700 (true, false) => {
7701 dec.symbol_fixed(&gather(
7702 &cdfs.partition_w32[ctx32],
7703 VERT_ALIKE,
7704 ));
7705 }
7706 (false, true) => {
7707 dec.symbol_fixed(&gather(
7708 &cdfs.partition_w32[ctx32],
7709 HORZ_ALIKE,
7710 ));
7711 }
7712 _ => {}
7713 }
7714 PARTITION_SPLIT
7715 };
7716 match part32 {
7717 PARTITION_NONE => {
7718 decode_block(
7719 &mut dec,
7720 &mut cdfs,
7721 &mut neighbours,
7722 at32,
7723 BLOCK,
7724 TxbSet::Luma32,
7725 TxbSet::Chroma16,
7726 TX32,
7727 TX16,
7728 (&scan32, &scan16),
7729 true,
7730 &mut y,
7731 &mut u,
7732 &mut v,
7733 base_q_idx,
7734 enable_filter_intra,
7735 allow_screen_content_tools,
7736 allow_intrabc,
7737 &scan32,
7738 &scan16,
7739 &scan8,
7740 &scan4,
7741 tx_select,
7742 reduced_tx_set,
7743 )?;
7744 }
7745 PARTITION_SPLIT => {
7746 for sub in 0..4 {
7747 let (sr, sc) =
7748 (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
7749 if (sr as u32) * SUB_MI >= mi_rows
7750 || (sc as u32) * SUB_MI >= mi_cols
7751 {
7752 continue;
7753 }
7754 let (has_cols16, has_rows16) = (
7755 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
7756 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
7757 );
7758 let at16 = (sr, sc);
7759 let ctx16 = neighbours.partition_ctx(at16, SUB);
7760 if has_cols16 && has_rows16 {
7761 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
7762 if std::env::var_os("EC_AV1_TRACE").is_some() {
7763 eprintln!(
7764 "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
7765 at16.0, at16.1
7766 );
7767 }
7768 if part16 == PARTITION_NONE {
7769 decode_block(
7770 &mut dec,
7771 &mut cdfs,
7772 &mut neighbours,
7773 at16,
7774 SUB,
7775 TxbSet::Luma16,
7776 TxbSet::Chroma8,
7777 TX16,
7778 TX8,
7779 (&scan16, &scan8),
7780 true,
7781 &mut y,
7782 &mut u,
7783 &mut v,
7784 base_q_idx,
7785 enable_filter_intra,
7786 allow_screen_content_tools,
7787 allow_intrabc,
7788 &scan32,
7789 &scan16,
7790 &scan8,
7791 &scan4,
7792 tx_select,
7793 reduced_tx_set,
7794 )?;
7795 continue;
7796 }
7797 if part16 == PARTITION_VERT_B {
7798 VERT_B_INTRA_HITS.with(|c| c.set(c.get() + 1));
7799 // Left rect: 8x16, real
7800 // `decode_block_rect`, sat at the
7801 // 16x16 parent's own origin (no
7802 // fractional-SUB-grid pixel
7803 // offset needed -- the plain
7804 // HORZ/VERT arms this lane's
7805 // charter named DO need one,
7806 // since their second half is
7807 // offset by half the parent;
7808 // unported, see decode_block_rect's
7809 // own doc comment).
7810 decode_block_rect(
7811 &mut dec,
7812 &mut cdfs,
7813 &mut neighbours,
7814 at16,
7815 8,
7816 16,
7817 &mut y,
7818 &mut u,
7819 &mut v,
7820 enable_filter_intra,
7821 allow_screen_content_tools,
7822 base_q_idx,
7823 tx_select,
7824 reduced_tx_set,
7825 )?;
7826 // Two 8x8 squares stacked on the
7827 // right, chained through
7828 // `prev_leaf` exactly like the
7829 // real (non-straddle) SPLIT path
7830 // below: the bottom leaf's ABOVE
7831 // context is the top leaf, not
7832 // the coarse SUB-grid array (a
7833 // real block never sat there).
7834 let (mi_row0, mi_col0) =
7835 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
7836 let top_right =
7837 (mi_row0 as usize, mi_col0 as usize + 2);
7838 let bot_right =
7839 (mi_row0 as usize + 2, mi_col0 as usize + 2);
7840 let mode_tr = decode_leaf8(
7841 &mut dec,
7842 &mut cdfs,
7843 &mut neighbours,
7844 at16,
7845 top_right,
7846 (&scan8, &scan4),
7847 None,
7848 &mut y,
7849 &mut u,
7850 &mut v,
7851 base_q_idx,
7852 enable_filter_intra,
7853 allow_screen_content_tools,
7854 allow_intrabc,
7855 tx_select,
7856 reduced_tx_set,
7857 )?;
7858 let mode_br = decode_leaf8(
7859 &mut dec,
7860 &mut cdfs,
7861 &mut neighbours,
7862 at16,
7863 bot_right,
7864 (&scan8, &scan4),
7865 Some((top_right, mode_tr)),
7866 &mut y,
7867 &mut u,
7868 &mut v,
7869 base_q_idx,
7870 enable_filter_intra,
7871 allow_screen_content_tools,
7872 allow_intrabc,
7873 tx_select,
7874 reduced_tx_set,
7875 )?;
7876 // `record()`'s above_mode/left_mode
7877 // write is a no-op at an 8x8
7878 // leaf's own side (same gap the
7879 // real-SPLIT path above patches):
7880 // force it from the last-decoded
7881 // (bottom-right) leaf.
7882 neighbours.above_mode[sc] = mode_br;
7883 neighbours.left_mode[sr] = mode_br;
7884 continue;
7885 }
7886 if part16 == PARTITION_HORZ {
7887 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
7888 let (mi_row0, mi_col0) = (
7889 sr as u32 * SUB_MI,
7890 sc as u32 * SUB_MI,
7891 );
7892 let top = (mi_row0 as usize, mi_col0 as usize);
7893 let bot = (mi_row0 as usize + 2, mi_col0 as usize);
7894 let mode_top = decode_leaf_rect(
7895 &mut dec,
7896 &mut cdfs,
7897 &mut neighbours,
7898 at16,
7899 top,
7900 16,
7901 8,
7902 None,
7903 &mut y,
7904 &mut u,
7905 &mut v,
7906 enable_filter_intra,
7907 allow_screen_content_tools,
7908 base_q_idx,
7909 tx_select,
7910 )?;
7911 let mode_bot = decode_leaf_rect(
7912 &mut dec,
7913 &mut cdfs,
7914 &mut neighbours,
7915 at16,
7916 bot,
7917 16,
7918 8,
7919 Some((top, mode_top)),
7920 &mut y,
7921 &mut u,
7922 &mut v,
7923 enable_filter_intra,
7924 allow_screen_content_tools,
7925 base_q_idx,
7926 tx_select,
7927 )?;
7928 neighbours.above_mode[sc] = mode_bot;
7929 neighbours.left_mode[sr] = mode_bot;
7930 continue;
7931 }
7932 if part16 == PARTITION_VERT {
7933 HORZ_VERT_INTRA_HITS.with(|c| c.set(c.get() + 1));
7934 let (mi_row0, mi_col0) = (
7935 sr as u32 * SUB_MI,
7936 sc as u32 * SUB_MI,
7937 );
7938 let left = (mi_row0 as usize, mi_col0 as usize);
7939 let right = (mi_row0 as usize, mi_col0 as usize + 2);
7940 let mode_left = decode_leaf_rect(
7941 &mut dec,
7942 &mut cdfs,
7943 &mut neighbours,
7944 at16,
7945 left,
7946 8,
7947 16,
7948 None,
7949 &mut y,
7950 &mut u,
7951 &mut v,
7952 enable_filter_intra,
7953 allow_screen_content_tools,
7954 base_q_idx,
7955 tx_select,
7956 )?;
7957 let mode_right = decode_leaf_rect(
7958 &mut dec,
7959 &mut cdfs,
7960 &mut neighbours,
7961 at16,
7962 right,
7963 8,
7964 16,
7965 Some((left, mode_left)),
7966 &mut y,
7967 &mut u,
7968 &mut v,
7969 enable_filter_intra,
7970 allow_screen_content_tools,
7971 base_q_idx,
7972 tx_select,
7973 )?;
7974 neighbours.above_mode[sc] = mode_right;
7975 neighbours.left_mode[sr] = mode_right;
7976 continue;
7977 }
7978 if part16 != PARTITION_SPLIT {
7979 return Err(unsupported(
7980 "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)",
7981 ));
7982 }
7983 // A real (non-straddle) SPLIT of a
7984 // whole 16x16 into four 8x8 leaves --
7985 // the same recursion the straddle
7986 // path below already runs when the
7987 // true frame edge forces it, just
7988 // over all four positions instead of
7989 // the one or two the edge leaves.
7990 let (mi_row0, mi_col0) =
7991 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
7992 let mut prev_leaf: Option<((usize, usize), usize)> = None;
7993 for i in 0..4 {
7994 let (mr, mc) =
7995 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
7996 let leaf_mi = (mr as usize, mc as usize);
7997 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
7998 let part8 =
7999 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
8000 if std::env::var_os("EC_AV1_TRACE").is_some() {
8001 eprintln!(
8002 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
8003 );
8004 }
8005 if part8 != PARTITION_NONE {
8006 return Err(unsupported(
8007 "a partition below 8x8 (this decoder codes no leaf smaller than 8x8)",
8008 ));
8009 }
8010 let leaf_mode = decode_leaf8(
8011 &mut dec,
8012 &mut cdfs,
8013 &mut neighbours,
8014 at16,
8015 leaf_mi,
8016 (&scan8, &scan4),
8017 prev_leaf,
8018 &mut y,
8019 &mut u,
8020 &mut v,
8021 base_q_idx,
8022 enable_filter_intra,
8023 allow_screen_content_tools,
8024 allow_intrabc,
8025 tx_select,
8026 reduced_tx_set,
8027 )?;
8028 prev_leaf = Some((leaf_mi, leaf_mode));
8029 }
8030 if let Some((_, mode)) = prev_leaf {
8031 neighbours.above_mode[sc] = mode;
8032 neighbours.left_mode[sr] = mode;
8033 }
8034 continue;
8035 }
8036 // The true edge falls inside this 16x16
8037 // leaf itself (mod-32==8 target sizes,
8038 // lane-av1-rect): one axis only -- an 8x8
8039 // leaf never itself straddles, so the
8040 // block splits cleanly along whichever
8041 // axis is short.
8042 if !has_cols16 && !has_rows16 {
8043 return Err(unsupported(
8044 "a 16x16 block whose true edge cuts through both \
8045 axes needs a rectangular transform this decoder \
8046 does not code yet",
8047 ));
8048 }
8049 if has_cols16 {
8050 dec.symbol_fixed(&gather(
8051 &cdfs.partition_w16[ctx16],
8052 VERT_ALIKE,
8053 ));
8054 } else {
8055 dec.symbol_fixed(&gather(
8056 &cdfs.partition_w16[ctx16],
8057 HORZ_ALIKE,
8058 ));
8059 }
8060 let (mi_row0, mi_col0) =
8061 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
8062 let leaf_positions: Vec<(u32, u32)> = (0..4)
8063 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
8064 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
8065 .collect();
8066 let mut prev_leaf: Option<((usize, usize), usize)> = None;
8067 for (mr, mc) in leaf_positions {
8068 let leaf_mi = (mr as usize, mc as usize);
8069 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
8070 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
8071 if std::env::var_os("EC_AV1_TRACE").is_some() {
8072 eprintln!(
8073 "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
8074 );
8075 }
8076 if part8 != PARTITION_NONE {
8077 return Err(unsupported(
8078 "a partition below 8x8 (this decoder codes no leaf smaller than 8x8)",
8079 ));
8080 }
8081 let leaf_mode = decode_leaf8(
8082 &mut dec,
8083 &mut cdfs,
8084 &mut neighbours,
8085 at16,
8086 leaf_mi,
8087 (&scan8, &scan4),
8088 prev_leaf,
8089 &mut y,
8090 &mut u,
8091 &mut v,
8092 base_q_idx,
8093 enable_filter_intra,
8094 allow_screen_content_tools,
8095 allow_intrabc,
8096 tx_select,
8097 reduced_tx_set,
8098 )?;
8099 prev_leaf = Some((leaf_mi, leaf_mode));
8100 }
8101 // `record()`'s `above_mode`/`left_mode`
8102 // write is a no-op at an 8x8 leaf's own
8103 // side, so force the write once the whole
8104 // 16x16 slot's leaves are done, from the
8105 // last leaf (mirrors the writer's r15
8106 // fix).
8107 if let Some((_, mode)) = prev_leaf {
8108 neighbours.above_mode[sc] = mode;
8109 neighbours.left_mode[sr] = mode;
8110 }
8111 }
8112 }
8113 PARTITION_HORZ => {
8114 // lane-intradisp r1: two true 32x16 strips.
8115 decode_block_rect(
8116 &mut dec,
8117 &mut cdfs,
8118 &mut neighbours,
8119 at32,
8120 32,
8121 16,
8122 &mut y,
8123 &mut u,
8124 &mut v,
8125 enable_filter_intra,
8126 allow_screen_content_tools,
8127 base_q_idx,
8128 tx_select,
8129 reduced_tx_set,
8130 )?;
8131 decode_block_rect(
8132 &mut dec,
8133 &mut cdfs,
8134 &mut neighbours,
8135 (at32.0 + 1, at32.1),
8136 32,
8137 16,
8138 &mut y,
8139 &mut u,
8140 &mut v,
8141 enable_filter_intra,
8142 allow_screen_content_tools,
8143 base_q_idx,
8144 tx_select,
8145 reduced_tx_set,
8146 )?;
8147 }
8148 PARTITION_VERT => {
8149 // lane-intradisp r1: mirror of PARTITION_HORZ
8150 // above with width/height swapped.
8151 decode_block_rect(
8152 &mut dec,
8153 &mut cdfs,
8154 &mut neighbours,
8155 at32,
8156 16,
8157 32,
8158 &mut y,
8159 &mut u,
8160 &mut v,
8161 enable_filter_intra,
8162 allow_screen_content_tools,
8163 base_q_idx,
8164 tx_select,
8165 reduced_tx_set,
8166 )?;
8167 decode_block_rect(
8168 &mut dec,
8169 &mut cdfs,
8170 &mut neighbours,
8171 (at32.0, at32.1 + 1),
8172 16,
8173 32,
8174 &mut y,
8175 &mut u,
8176 &mut v,
8177 enable_filter_intra,
8178 allow_screen_content_tools,
8179 base_q_idx,
8180 tx_select,
8181 reduced_tx_set,
8182 )?;
8183 }
8184 _ => {
8185 return Err(unsupported(format!(
8186 "a 32x32 partition type this decoder does not code (value={part32})"
8187 )));
8188 }
8189 }
8190 }
8191 }
8192 PARTITION_HORZ => {
8193 // lane-sbpart r2: two true 64x32 strips.
8194 decode_block_rect64(
8195 &mut dec,
8196 &mut cdfs,
8197 &mut neighbours,
8198 at,
8199 64,
8200 32,
8201 &mut y,
8202 &mut u,
8203 &mut v,
8204 enable_filter_intra,
8205 allow_screen_content_tools,
8206 base_q_idx,
8207 tx_select,
8208 reduced_tx_set,
8209 )?;
8210 decode_block_rect64(
8211 &mut dec,
8212 &mut cdfs,
8213 &mut neighbours,
8214 (at.0 + 2, at.1),
8215 64,
8216 32,
8217 &mut y,
8218 &mut u,
8219 &mut v,
8220 enable_filter_intra,
8221 allow_screen_content_tools,
8222 base_q_idx,
8223 tx_select,
8224 reduced_tx_set,
8225 )?;
8226 }
8227 PARTITION_VERT => {
8228 // lane-sbpart r2: mirror of PARTITION_HORZ above with
8229 // width/height swapped.
8230 decode_block_rect64(
8231 &mut dec,
8232 &mut cdfs,
8233 &mut neighbours,
8234 at,
8235 32,
8236 64,
8237 &mut y,
8238 &mut u,
8239 &mut v,
8240 enable_filter_intra,
8241 allow_screen_content_tools,
8242 base_q_idx,
8243 tx_select,
8244 reduced_tx_set,
8245 )?;
8246 decode_block_rect64(
8247 &mut dec,
8248 &mut cdfs,
8249 &mut neighbours,
8250 (at.0, at.1 + 2),
8251 32,
8252 64,
8253 &mut y,
8254 &mut u,
8255 &mut v,
8256 enable_filter_intra,
8257 allow_screen_content_tools,
8258 base_q_idx,
8259 tx_select,
8260 reduced_tx_set,
8261 )?;
8262 }
8263 _ => {
8264 return Err(unsupported(
8265 "a superblock-level partition type other than NONE or SPLIT (this \
8266 decoder's intra tile path codes only those two at 64x64)",
8267 ));
8268 }
8269 }
8270 }
8271 }
8272
8273 if tile_num == tile_info.context_update_tile_id {
8274 result_cdfs = cdfs;
8275 }
8276 }
8277
8278 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
8279 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
8280 // that isolate whether a decode-order frame's mismatch already exists
8281 // in reconstruction (this dump) vs is introduced by the loop filter
8282 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
8283 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
8284 use std::io::Write;
8285 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8286 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
8287 let narrow = |p: &PlaneBuf| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
8288 let _ = f.write_all(&narrow(&y));
8289 let _ = f.write_all(&narrow(&u));
8290 let _ = f.write_all(&narrow(&v));
8291 }
8292 } else {
8293 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8294 }
8295 if let Ok(path) = std::env::var("EC_AV1_PREFILT_WIDE_DUMP") {
8296 use std::io::Write;
8297 static IDX2: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
8298 let idx = IDX2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8299 let crop_wide = |plane: &PlaneBuf| -> Vec<u8> {
8300 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
8301 for row in 0..plane.true_height {
8302 out.extend(plane.data[row * plane.width..][..plane.true_width].iter().map(|&s| s as u8));
8303 }
8304 out
8305 };
8306 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
8307 let _ = f.write_all(&crop_wide(&y));
8308 let _ = f.write_all(&crop_wide(&u));
8309 let _ = f.write_all(&crop_wide(&v));
8310 }
8311 }
8312 apply_deblock(
8313 &mut y,
8314 &mut u,
8315 &mut v,
8316 loop_filter,
8317 &neighbours,
8318 frame_width as usize,
8319 frame_height as usize,
8320 );
8321 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
8322 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
8323 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
8324 // dump above these bisect WHICH filter stage introduced a mismatch.
8325 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
8326 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
8327 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
8328 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
8329
8330 let (fw, fh) = (frame_width as usize, frame_height as usize);
8331 if fw == width && fh == height {
8332 LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
8333 return Ok((
8334 Picture {
8335 width,
8336 height,
8337 y: y.data,
8338 u: u.data,
8339 v: v.data,
8340 },
8341 result_cdfs,
8342 ));
8343 }
8344 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u16> {
8345 let mut out = Vec::with_capacity(w * h);
8346 for row in 0..h {
8347 out.extend(plane.data[row * plane.width..][..w].iter().copied());
8348 }
8349 out
8350 };
8351 // lane-superres r3: `true_width`/`true_height` (`mi_cols`/`mi_rows` * 4)
8352 // is the real reconstructed extent -- columns `[fw, true_width)` hold
8353 // genuine decoded samples (the last coding block straddles the frame
8354 // edge whenever `frame_width` isn't 8-sample aligned), not padding.
8355 // libaom's superres upscale runs on that buffer's own border-extended
8356 // margin, so it reads those real columns, not a synthetic replicate of
8357 // column `fw - 1`. Stash them for `stream.rs`'s superres path (a real
8358 // aomenc 43->64 stream pinned column-by-column against libaom's own
8359 // `av1_convolve_horiz_rs_c` via `scripts/superres-pin-harness.c` --
8360 // `row6-realedgeval` proved the replicate-of-`fw-1` padding this
8361 // decoder used before was off by 1 at the columns the tap window
8362 // reaches into that real margin; `None` when there is no margin (this
8363 // frame's `true_width`/`true_height` already equal `fw`/`fh`, e.g. a
8364 // non-superres frame whose width just isn't 32-block aligned).
8365 LAST_FRAME_WIDE_MARGIN.with(|m| {
8366 *m.borrow_mut() = if true_width > fw || true_height > fh {
8367 let yc = crop(&y, true_width, true_height);
8368 if let Ok(path) = std::env::var("EC_AV1_MARGIN_DUMP") {
8369 use std::io::Write;
8370 static IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
8371 let idx = IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8372 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
8373 // corner-cut: this diagnostic dump stays 8-bit-narrowed
8374 // regardless of the stream's real bit depth (debug-only,
8375 // never read by a gate); widen if a >8-bit margin dump
8376 // is ever needed.
8377 let _ = f.write_all(&yc.iter().map(|&s| s as u8).collect::<Vec<u8>>());
8378 }
8379 }
8380 Some(Picture {
8381 width: true_width,
8382 height: true_height,
8383 y: yc,
8384 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
8385 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
8386 })
8387 } else {
8388 None
8389 }
8390 });
8391 Ok((
8392 Picture {
8393 width: fw,
8394 height: fh,
8395 y: crop(&y, fw, fh),
8396 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
8397 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
8398 },
8399 result_cdfs,
8400 ))
8401}
8402
8403/// `av1_get_pred_context_switchable_interp`'s context for `interp_filter[dir]`
8404/// -- `above`/`left` are the neighbour's own resolved index for this
8405/// direction (0..=2, or `3` = no info, spec `SWITCHABLE_FILTERS`).
8406/// `is_compound` folds in libaom `av1_get_pred_context_switchable_interp`'s
8407/// own `ctx_offset` term (`INTER_FILTER_COMP_OFFSET` = 4, added when *this*
8408/// block itself has a second reference) -- lane-av1idx: a stale "this
8409/// decoder never codes a compound reference" assumption baked this to
8410/// always-0, which desynced the CDF context bucket (not the decoded value
8411/// outright, hence small pixel deltas rather than a hard desync) the moment
8412/// lane-av1blend unmasked plain-average compound blocks on a Switchable-
8413/// filter frame.
8414fn switchable_interp_ctx(above: u8, left: u8, dir: usize, is_compound: bool) -> usize {
8415 let base = dir * 8 + if is_compound { 4 } else { 0 };
8416 let term = if left == above {
8417 left
8418 } else if left == 3 {
8419 above
8420 } else if above == 3 {
8421 left
8422 } else {
8423 3
8424 };
8425 base + term as usize
8426}
8427
8428/// Resolves the interpolation filter kernel(s) an inter block's motion
8429/// compensation reads (spec 5.11.10/5.11.20): a fixed-filter frame
8430/// (`interp_fixed = Some`) never reads a symbol; a `Switchable` frame
8431/// (`interp_fixed = None`) reads `interp_filter[0]` and, when
8432/// `enable_dual_filter`, a second `interp_filter[1]` -- unless
8433/// `force_regular` (this block's own `needs_interp_filter() == 0` case: a
8434/// `GLOBALMV` block, whose global motion is always `IDENTITY` in this
8435/// decoder's scope, spec 5.11.10's `large && YMode == GLOBALMV` branch),
8436/// which forces `EIGHTTAP` without reading anything.
8437#[allow(clippy::too_many_arguments)]
8438fn resolve_interp_filter(
8439 dec: &mut SymbolDecoder,
8440 cdfs: &mut Cdfs,
8441 interp_fixed: Option<mc::InterpFilterKind>,
8442 enable_dual_filter: bool,
8443 force_regular: bool,
8444 above: [u8; 2],
8445 left: [u8; 2],
8446 is_compound: bool,
8447) -> (mc::InterpFilterKind, mc::InterpFilterKind, [u8; 2]) {
8448 if let Some(kind) = interp_fixed {
8449 return (kind, kind, [3, 3]);
8450 }
8451 if force_regular {
8452 return (
8453 mc::InterpFilterKind::Regular,
8454 mc::InterpFilterKind::Regular,
8455 [0, 0],
8456 );
8457 }
8458 // libaom `av1_extract_interp_filter`/`read_mb_interp_filter`: the
8459 // symbol read at `dir=0` becomes the block's *vertical* (`y_filter`)
8460 // kernel, `dir=1` the *horizontal* (`x_filter`) one -- `dir` is not
8461 // "horizontal then vertical" despite `predict_with_filters`' own
8462 // `h_kind`/`v_kind` argument order, which is why this function returns
8463 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
8464 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
8465 if std::env::var_os("EC_AV1_IFDBG").is_some() {
8466 eprintln!(
8467 "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
8468 &cdfs.switchable_interp[ctx0][..3]
8469 );
8470 }
8471 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
8472 let sym1 = if enable_dual_filter {
8473 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
8474 if std::env::var_os("EC_AV1_IFDBG").is_some() {
8475 eprintln!(
8476 "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
8477 &cdfs.switchable_interp[ctx1][..3]
8478 );
8479 }
8480 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
8481 } else {
8482 sym0
8483 };
8484 (
8485 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
8486 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
8487 [sym0, sym1],
8488 )
8489}
8490
8491/// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
8492/// duplicating [`crate::tile`]'s private copy of the same rule.
8493pub(crate) fn intra_inter_ctx(
8494 has_above: bool,
8495 has_left: bool,
8496 above_inter: bool,
8497 left_inter: bool,
8498) -> usize {
8499 match (has_above, has_left) {
8500 (true, true) => {
8501 let (above_intra, left_intra) = (!above_inter, !left_inter);
8502 if above_intra && left_intra {
8503 3
8504 } else {
8505 usize::from(above_intra || left_intra)
8506 }
8507 }
8508 (true, false) => 2 * usize::from(!above_inter),
8509 (false, true) => 2 * usize::from(!left_inter),
8510 (false, false) => 0,
8511 }
8512}
8513
8514/// `CLASS0_SIZE << (class + 2)`, duplicating `crate::tile`'s private
8515/// `mv_class_base` (spec 3): the magnitude an `MV_CLASS_n` component's own
8516/// bits start counting from.
8517fn mv_class_base(class: usize) -> i32 {
8518 if class == 0 { 0 } else { 2i32 << (class + 2) }
8519}
8520
8521/// One motion vector component's non-zero diff (spec 5.11.32
8522/// `read_mv_component`), the inverse of [`crate::tile`]'s private
8523/// `write_mv_component`.
8524fn read_mv_component(
8525 dec: &mut SymbolDecoder,
8526 c: &mut MvComponentCdfs,
8527 allow_high_precision_mv: bool,
8528 force_integer_mv: bool,
8529) -> i32 {
8530 let sign = dec.symbol(&mut c.sign);
8531 let class = dec.symbol(&mut c.class);
8532 let local = if class == 0 {
8533 let bit = dec.symbol(&mut c.class0_bit);
8534 // spec 5.11.32 `mv_class0_fr`: not coded at all when the frame
8535 // forces integer motion vectors -- implicitly `3` (the top
8536 // fractional value) rather than read, else every symbol after it
8537 // in the tile desyncs by one read.
8538 let fr = if force_integer_mv {
8539 3
8540 } else {
8541 dec.symbol(&mut c.class0_fr[bit])
8542 };
8543 // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
8544 // high-precision motion vectors, else implicitly 1 (the low bit
8545 // stays at half-pel precision) -- this crate's own writer always
8546 // leaves the flag off, but a foreign stream can set it per frame.
8547 let hp = if allow_high_precision_mv {
8548 dec.symbol(&mut c.class0_hp)
8549 } else {
8550 1
8551 };
8552 (bit << 3) | (fr << 1) | hp
8553 } else {
8554 let mut d = 0;
8555 for i in 0..class {
8556 d |= dec.symbol(&mut c.bit[i]) << i;
8557 }
8558 // spec 5.11.32 `mv_fr`: same force_integer_mv carve-out as
8559 // `mv_class0_fr` above.
8560 let fr = if force_integer_mv { 3 } else { dec.symbol(&mut c.fr) };
8561 let hp = if allow_high_precision_mv {
8562 dec.symbol(&mut c.hp)
8563 } else {
8564 1
8565 };
8566 (d << 3) | (fr << 1) | hp
8567 };
8568 let mag = mv_class_base(class) + local as i32 + 1;
8569 if sign == 1 { -mag } else { mag }
8570}
8571
8572/// A motion vector coded as a residual against `pred` (spec 5.11.32
8573/// `read_mv`), the inverse of [`crate::tile`]'s private `write_mv`.
8574fn read_mv(
8575 dec: &mut SymbolDecoder,
8576 mv_comp: &mut [MvComponentCdfs; 2],
8577 mv_joint: &mut [u16; 5],
8578 pred: (i32, i32),
8579 allow_high_precision_mv: bool,
8580 force_integer_mv: bool,
8581) -> (i32, i32) {
8582 let joint = dec.symbol(mv_joint);
8583 let mut diff = (0, 0);
8584 if joint == 2 || joint == 3 {
8585 diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv, force_integer_mv);
8586 }
8587 if joint == 1 || joint == 3 {
8588 diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv, force_integer_mv);
8589 }
8590 (pred.0 + diff.0, pred.1 + diff.1)
8591}
8592
8593/// One intrabc block's block vector (spec 5.11.13 `read_intrabc_info` ->
8594/// `assign_mv` with `use_intrabc`, libaom `assign_dv`/`av1_find_ref_dv`).
8595///
8596/// The predictor is the ordinary MV stack built against `INTRA_FRAME`
8597/// (`av1_find_mv_refs(..., INTRA_FRAME, ...)`): `nearestmv`, or `nearmv`
8598/// when that is zero, or -- when both are -- the fixed fallback DV one
8599/// superblock up, or `INTRABC_DELAY_PIXELS` (256) plus one superblock to the
8600/// left when this is the tile's first superblock row. The predictor is then
8601/// rounded to full pel, and the difference reads off the *dv* nmv context
8602/// (libaom `ndvc`) at full-pel precision (`MV_SUBPEL_NONE`: no `fr`/`hp`
8603/// symbols, exactly this decoder's `force_integer_mv` carve-out). No DRL
8604/// symbol is coded for a DV, so none of this can move the bitstream
8605/// position -- only the reconstructed vector.
8606fn read_intrabc_dv(
8607 dec: &mut SymbolDecoder,
8608 cdfs: &mut Cdfs,
8609 mi_r: usize,
8610 mi_c: usize,
8611 side: usize,
8612) -> (i32, i32) {
8613 const INTRABC_DELAY_PIXELS: i32 = 256;
8614 let n4 = side / MI;
8615 let stack_pred = INTRABC_MI_GRID.with(|g| {
8616 let g = g.borrow();
8617 g.as_ref().map(|(grid, mi_cols, mi_rows)| {
8618 let stack = crate::mvstack::find_mv_stack(
8619 grid, mi_r, mi_c, n4, n4, 0, /* INTRA_FRAME */
8620 *mi_cols, *mi_rows,
8621 );
8622 if stack.nearest_mv == (0, 0) {
8623 stack.near_mv
8624 } else {
8625 stack.nearest_mv
8626 }
8627 })
8628 });
8629 let mut pred = stack_pred.unwrap_or((0, 0));
8630 if pred == (0, 0) {
8631 // `av1_find_ref_dv` (mvref_common.c). Tile row start is 0 here (the
8632 // single-tile-row case every intrabc gate stream is).
8633 let sb_px = SB_MI as i32 * MI as i32;
8634 pred = if mi_r < SB_MI as usize {
8635 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
8636 } else {
8637 (-sb_px * 8, 0)
8638 };
8639 }
8640 // "Ref DV should not have sub-pel" (`assign_dv`): floor to full pel.
8641 let pred = ((pred.0 >> 3) * 8, (pred.1 >> 3) * 8);
8642 read_mv(dec, &mut cdfs.dv_comp, &mut cdfs.dv_joint, pred, false, true)
8643}
8644
8645/// A 1/8-pel motion vector component converted to the 1/16-pel offset
8646/// [`mc::predict`] takes, duplicating [`crate::encode`]'s private `mv_to_q4`
8647/// (its own doc comment explains the `*2`/`*1` luma/chroma split).
8648fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
8649 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
8650}
8651
8652impl PlaneBuf {
8653 /// Adds `residual` onto an already-computed `prediction` (motion
8654 /// compensation's output, rather than [`predict`]'s intra one), writing
8655 /// the clamped reconstruction into the plane at `(x, y)` -- the inter
8656 /// counterpart of [`PlaneBuf::reconstruct`].
8657 fn reconstruct_mc(
8658 &mut self,
8659 x: usize,
8660 y: usize,
8661 side: usize,
8662 prediction: &[u16],
8663 residual: &[i32],
8664 ) {
8665 self.reconstruct_mc_rect(x, y, side, side, side, prediction, residual);
8666 }
8667
8668 /// [`Self::reconstruct_mc`], writing only a `w`x`h` sub-rectangle of the
8669 /// `side`x`side` `prediction`/`residual` buffers (which stay `side`-square
8670 /// for stride/indexing) -- lane-partitions r1: a true rectangular HORZ/
8671 /// VERT strip is predicted at its enclosing square `side` (matching
8672 /// `HORZ_B`'s already-accepted square-context corner-cut, lane-warp r5)
8673 /// but only its own true `w`x`h` footprint is committed to the plane, so
8674 /// two strips sharing a square's coordinate origin never clobber each
8675 /// other's real pixels.
8676 fn reconstruct_mc_rect(
8677 &mut self,
8678 x: usize,
8679 y: usize,
8680 side: usize,
8681 w: usize,
8682 h: usize,
8683 prediction: &[u16],
8684 residual: &[i32],
8685 ) {
8686 for row in 0..h {
8687 for col in 0..w {
8688 let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
8689 .clamp(0, crate::decode::sample_max()) as u16;
8690 self.data[(y + row) * self.width + x + col] = sample;
8691 }
8692 }
8693 }
8694}
8695
8696/// Reads one inter-coded plane's transform block and reconstructs it by
8697/// adding its residual onto a motion-compensated `prediction` -- the inter
8698/// counterpart of [`read_plane`] (every inter transform this decoder reads is
8699/// `side`-square with no oversized-64 case, so there is no padded-grid
8700/// branch to mirror).
8701#[allow(clippy::too_many_arguments)]
8702fn read_inter_plane(
8703 dec: &mut SymbolDecoder,
8704 cdfs: &mut Cdfs,
8705 set: TxbSet,
8706 scan: &[u16],
8707 plane_idx: usize,
8708 around: (bool, bool, i32),
8709 tx_mode: usize,
8710 plane: &mut PlaneBuf,
8711 x: usize,
8712 y: usize,
8713 side: usize,
8714 base_q_idx: u8,
8715 prediction: &[u16],
8716 // lane-chromau: this block's own luma transform's *actual coded*
8717 // `tx_type` -- `av1_get_tx_type` (libaom `blockd.h`): an inter block's
8718 // chroma plane never codes its own `tx_type` symbol, but (unlike an
8719 // intra block, which falls back to `Intra_Mode_To_Tx_Type`) it inherits
8720 // the colocated luma transform's coded type verbatim, clamped back to
8721 // `DCT_DCT` at the chroma tx sizes the spec forces DCT-only
8722 // (`av1_get_ext_tx_set_type`: `tx_size_sqr_up >= TX_32X32`, i.e. this
8723 // function's own `side >= 32`). `None` for the luma call itself
8724 // (`plane_idx == 0`), where the `TxbSet`'s own symbol (or the true
8725 // `DCT_DCT` default at 32-point+) already resolves it without help.
8726 inherited_luma_tx_type: Option<TxType>,
8727) -> Result<(Vec<i32>, TxType)> {
8728 let skip_ctx = if plane_idx == 0 {
8729 0
8730 } else {
8731 usize::from(around.0) + usize::from(around.1)
8732 };
8733 let mut coding = cdfs.txb(set, tx_mode);
8734 let default_tx_type = match inherited_luma_tx_type {
8735 Some(t) if side < 32 => t,
8736 _ => TxType::DctDct,
8737 };
8738 let (grid, tx_type) = read_coeffs(
8739 dec,
8740 &mut coding,
8741 scan,
8742 skip_ctx,
8743 dc_sign_ctx(around.2),
8744 default_tx_type,
8745 None,
8746 )?;
8747 let (dc_delta, ac_delta) = plane_q_delta(plane_idx);
8748 let residual = dequant_and_inverse_typed(&grid, side, bit_depth(), block_q_idx(), dc_delta, ac_delta, tx_type);
8749 plane.reconstruct_mc(x, y, side, prediction, &residual);
8750 Ok((grid, tx_type))
8751}
8752
8753/// Spec 5.11.25's `single_ref_p1`..`p6` tree (reachable only once `comp_mode`
8754/// is known `SINGLE_REFERENCE` -- `decode_stream` refuses any frame with
8755/// `reference_select` set before this is ever called, so that read is never
8756/// needed here). `above_ref`/`left_ref` are `-1` for an intra/unavailable
8757/// neighbour, else the `1..=7` reference that neighbour coded (lane-av1refs).
8758fn read_single_ref(
8759 dec: &mut SymbolDecoder,
8760 cdfs: &mut Cdfs,
8761 above_ref: i8,
8762 above_ref1: Option<i8>,
8763 left_ref: i8,
8764 left_ref1: Option<i8>,
8765) -> i8 {
8766 let above = (above_ref > 0).then_some(above_ref);
8767 let left = (left_ref > 0).then_some(left_ref);
8768 let p1 = dec.symbol(&mut cdfs.single_ref[single_ref_p1_ctx(above, above_ref1, left, left_ref1)][0]);
8769 let ref_frame = if p1 == 1 {
8770 let p2 = dec.symbol(&mut cdfs.single_ref[single_ref_p2_ctx(above, above_ref1, left, left_ref1)][1]);
8771 if p2 == 1 {
8772 ALTREF_FRAME
8773 } else {
8774 let p6 = dec.symbol(&mut cdfs.single_ref[single_ref_p6_ctx(above, above_ref1, left, left_ref1)][5]);
8775 if p6 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
8776 }
8777 } else {
8778 let p3 = dec.symbol(&mut cdfs.single_ref[single_ref_p3_ctx(above, above_ref1, left, left_ref1)][2]);
8779 if p3 == 1 {
8780 let p5 = dec.symbol(&mut cdfs.single_ref[single_ref_p5_ctx(above, above_ref1, left, left_ref1)][4]);
8781 if p5 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
8782 } else {
8783 let p4 = dec.symbol(&mut cdfs.single_ref[single_ref_p4_ctx(above, above_ref1, left, left_ref1)][3]);
8784 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
8785 }
8786 };
8787 if ref_frame != LAST_FRAME {
8788 NON_LAST_REF_HITS.with(|c| c.set(c.get() + 1));
8789 let c = match ref_frame {
8790 LAST2_FRAME => &LAST2_HITS,
8791 LAST3_FRAME => &LAST3_HITS,
8792 GOLDEN_FRAME => &GOLDEN_HITS,
8793 BWDREF_FRAME => &BWDREF_HITS,
8794 ALTREF2_FRAME => &ALTREF2_HITS,
8795 ALTREF_FRAME => &ALTREF_HITS,
8796 _ => unreachable!("read_single_ref only ever returns LAST_FRAME..=ALTREF_FRAME"),
8797 };
8798 c.with(|v| v.set(v.get() + 1));
8799 }
8800 ref_frame
8801}
8802
8803/// Spec 5.11.25's `comp_mode` (lane-av1comp): whether an inter block reads
8804/// `SINGLE_REFERENCE` or `COMPOUND_REFERENCE`, only reached once a frame's
8805/// `reference_select` header bit lets a block choose per-block instead of
8806/// fixing the mode. `above`/`left` are `None` for an intra/unavailable
8807/// neighbour, [`NeighbourRef`] for a coded one -- [`reference_mode_ctx`]'s
8808/// own doc. Called from [`decode_inter_block`] once its own `reference_select`
8809/// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
8810/// way with a coarser (`LAST_FRAME`-only) neighbour shape.
8811/// Resolves a compound reference's own planes -- the same `ref_frame ==
8812/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
8813/// [`decode_inter_block`]'s single-ref path already does, factored out so
8814/// the compound path can call it twice (lane-av1comp).
8815fn ref_planes<'a>(
8816 ref_frame: i8,
8817 ref_y: &'a PlaneBuf,
8818 ref_u: &'a PlaneBuf,
8819 ref_v: &'a PlaneBuf,
8820 other_refs: &'a RefSlots,
8821) -> Result<(&'a PlaneBuf, &'a PlaneBuf, &'a PlaneBuf)> {
8822 if ref_frame == LAST_FRAME {
8823 Ok((ref_y, ref_u, ref_v))
8824 } else {
8825 match other_refs[ref_frame as usize] {
8826 Some((ry, ru, rv)) => Ok((ry, ru, rv)),
8827 None => Err(unsupported(
8828 "a reference frame selected with no picture at this frame's own \
8829 ref_frame_idx slot for it",
8830 )),
8831 }
8832 }
8833}
8834
8835/// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
8836/// directly above this block's own column span, one bordering block at a
8837/// time (stepping by that neighbour's own `MiInfo::size`, which is always
8838/// `<= 16` since no block this decoder ever codes exceeds 64x64), collecting
8839/// every *inter* neighbour found (an intra or unset cell is skipped, one mi
8840/// unit at a time, and does not itself count as a step). `max_neighbors`
8841/// caller-bounds the scan: `1` for the eligibility check (any hit at all),
8842/// `av1_build_obmc_inter_prediction`'s own `max_neighbor_obmc` table for the
8843/// real blend pass. Round 1 corner-cut: libaom's own "4-wide block, treat as
8844/// half of a chroma pair" merge (`obmc.h`'s `mi_step == 1` special case) is
8845/// not ported -- no block this decoder codes is narrower than 8px, so it
8846/// never fires here regardless of what a neighbour's own decoder was.
8847fn overlappable_above(
8848 grid: &MiGrid,
8849 mi_row: usize,
8850 mi_col: usize,
8851 bw4: usize,
8852 mi_cols: usize,
8853 max_neighbors: usize,
8854) -> Vec<(usize, usize, MiInfo)> {
8855 let mut out = Vec::new();
8856 if mi_row == 0 {
8857 return out;
8858 }
8859 let end_col = (mi_col + bw4).min(mi_cols);
8860 let mut col = mi_col;
8861 while col < end_col && out.len() < max_neighbors {
8862 let cell = grid.get(mi_row - 1, col);
8863 let step = cell.map_or(1, |c| c.size).max(1);
8864 if let Some(info) = cell {
8865 if info.is_inter {
8866 out.push((col - mi_col, step.min(end_col - col), *info));
8867 }
8868 }
8869 col += step;
8870 }
8871 out
8872}
8873
8874/// `foreach_overlappable_nb_left`'s left-column mirror of
8875/// [`overlappable_above`] -- see its doc for the shared corner-cut.
8876fn overlappable_left(
8877 grid: &MiGrid,
8878 mi_row: usize,
8879 mi_col: usize,
8880 bh4: usize,
8881 mi_rows: usize,
8882 max_neighbors: usize,
8883) -> Vec<(usize, usize, MiInfo)> {
8884 let mut out = Vec::new();
8885 if mi_col == 0 {
8886 return out;
8887 }
8888 let end_row = (mi_row + bh4).min(mi_rows);
8889 let mut row = mi_row;
8890 while row < end_row && out.len() < max_neighbors {
8891 let cell = grid.get(row, mi_col - 1);
8892 // Vertical walk steps by the neighbour's HEIGHT -- a 32x16 strip's
8893 // width (8) would swallow the strip below it.
8894 let step = cell.map_or(1, |c| c.size_h).max(1);
8895 if let Some(info) = cell {
8896 if info.is_inter {
8897 out.push((row - mi_row, step.min(end_row - row), *info));
8898 }
8899 }
8900 row += step;
8901 }
8902 out
8903}
8904
8905/// `has_top_right` (`av1/common/mvref_common.c`), reduced to the
8906/// square-block, fixed-64px-superblock case this decoder ever reaches: no
8907/// rectangular partition (`VERT`/`HORZ`/`_4`/`VERT_A`) ever produces an
8908/// inter leaf here (`xd->width == xd->height` always), so libaom's own
8909/// rect-partition branches (`xd->width < xd->height`, `xd->width >
8910/// xd->height`, `PARTITION_VERT_A`) never fire and are dropped. `bs` is the
8911/// block's own side in 4x4 (`mi`) units.
8912fn has_top_right(mi_row: usize, mi_col: usize, bs: usize) -> bool {
8913 let sb_mi_size = SB_MI as usize;
8914 let mask_row = mi_row & (sb_mi_size - 1);
8915 let mask_col = mi_col & (sb_mi_size - 1);
8916 if bs > sb_mi_size {
8917 return false;
8918 }
8919 let mut has_tr = !((mask_row & bs != 0) && (mask_col & bs != 0));
8920 let mut b = bs;
8921 while b < sb_mi_size {
8922 if mask_col & b != 0 {
8923 if (mask_col & (2 * b) != 0) && (mask_row & (2 * b) != 0) {
8924 has_tr = false;
8925 break;
8926 }
8927 } else {
8928 break;
8929 }
8930 b <<= 1;
8931 }
8932 has_tr
8933}
8934
8935/// `av1_findSamples` (`mvref_common.c`), full port: the up to
8936/// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
8937/// samples (`record_samples`) that share this block's own single reference
8938/// frame and are themselves single-ref -- `mbmi->num_proj_ref` is
8939/// `.len()` of the returned vec. `bw4` is the block's own side in 4x4 units
8940/// (square, so also `bh4`; a real block's `xd->width`/`xd->height` in
8941/// libaom are also mi units of that same square side here). Each sample's
8942/// own `bw`/`bh` (fed to [`crate::warp::record_sample`]'s offset formula)
8943/// come from the *neighbour* cell's own coded size, not this block's.
8944#[allow(clippy::too_many_arguments)]
8945fn find_samples(
8946 grid: &MiGrid,
8947 mi_row: usize,
8948 mi_col: usize,
8949 bw4: usize,
8950 bh4: usize,
8951 mi_cols: usize,
8952 mi_rows: usize,
8953 ref_frame: i8,
8954) -> Vec<crate::warp::Sample> {
8955 const MAX: usize = crate::warp::LEAST_SQUARES_SAMPLES_MAX;
8956 let up_available = mi_row > 0;
8957 let left_available = mi_col > 0;
8958 let mut samples = Vec::with_capacity(MAX);
8959 let single_ref_match = |info: &MiInfo| info.ref_frame == ref_frame && info.ref_frame1.is_none();
8960 let mut do_tl = true;
8961 let mut do_tr = true;
8962 let rec = |info: &MiInfo, row_offset: i32, sign_r: i32, col_offset: i32, sign_c: i32| {
8963 let nb_bw = (info.size * 4) as i32;
8964 // lane-rect r2: the neighbour's own true height -- a rect strip
8965 // neighbour donates its sample at ITS center (aom pts y=-72 for a
8966 // 32x16 above strip; the square assumption put it at -136).
8967 let nb_bh = (info.size_h * 4) as i32;
8968 crate::warp::record_sample(nb_bw, nb_bh, info.mv, row_offset, sign_r, col_offset, sign_c)
8969 };
8970
8971 'outer: {
8972 if up_available {
8973 let above = grid.get(mi_row - 1, mi_col);
8974 let superblock_width = above.map_or(1, |c| c.size).max(1);
8975 if bw4 <= superblock_width {
8976 let col_offset = -((mi_col % superblock_width) as isize);
8977 if col_offset < 0 {
8978 do_tl = false;
8979 }
8980 if col_offset + superblock_width as isize > bw4 as isize {
8981 do_tr = false;
8982 }
8983 if let Some(info) = above {
8984 if single_ref_match(info) {
8985 samples.push(rec(info, 0, -1, col_offset as i32, 1));
8986 if samples.len() >= MAX {
8987 break 'outer;
8988 }
8989 }
8990 }
8991 } else {
8992 let mut i = 0usize;
8993 let limit = bw4.min(mi_cols.saturating_sub(mi_col));
8994 while i < limit {
8995 let cell = grid.get(mi_row - 1, mi_col + i);
8996 let sw = cell.map_or(1, |c| c.size).max(1);
8997 if let Some(info) = cell {
8998 if single_ref_match(info) {
8999 samples.push(rec(info, 0, -1, i as i32, 1));
9000 if samples.len() >= MAX {
9001 break 'outer;
9002 }
9003 }
9004 }
9005 i += sw;
9006 }
9007 }
9008 }
9009
9010 if left_available {
9011 let left = grid.get(mi_row, mi_col - 1);
9012 let superblock_height = left.map_or(1, |c| c.size_h).max(1);
9013 if bh4 <= superblock_height {
9014 let row_offset = -((mi_row % superblock_height) as isize);
9015 if row_offset < 0 {
9016 do_tl = false;
9017 }
9018 if let Some(info) = left {
9019 if single_ref_match(info) {
9020 samples.push(rec(info, row_offset as i32, 1, 0, -1));
9021 if samples.len() >= MAX {
9022 break 'outer;
9023 }
9024 }
9025 }
9026 } else {
9027 let mut i = 0usize;
9028 let limit = bh4.min(mi_rows.saturating_sub(mi_row));
9029 while i < limit {
9030 let cell = grid.get(mi_row + i, mi_col - 1);
9031 let sh = cell.map_or(1, |c| c.size_h).max(1);
9032 if let Some(info) = cell {
9033 if single_ref_match(info) {
9034 samples.push(rec(info, i as i32, 1, 0, -1));
9035 if samples.len() >= MAX {
9036 break 'outer;
9037 }
9038 }
9039 }
9040 i += sh;
9041 }
9042 }
9043 }
9044
9045 if do_tl && left_available && up_available {
9046 if let Some(info) = grid.get(mi_row - 1, mi_col - 1) {
9047 if single_ref_match(info) {
9048 samples.push(rec(info, 0, -1, 0, -1));
9049 if samples.len() >= MAX {
9050 break 'outer;
9051 }
9052 }
9053 }
9054 }
9055
9056 if do_tr && has_top_right(mi_row, mi_col, bw4) {
9057 let tr_col = mi_col + bw4;
9058 if mi_row > 0 && tr_col < mi_cols {
9059 if let Some(info) = grid.get(mi_row - 1, tr_col) {
9060 if single_ref_match(info) {
9061 samples.push(rec(info, 0, -1, bw4 as i32, 1));
9062 }
9063 }
9064 }
9065 }
9066 }
9067 samples
9068}
9069
9070/// `mbmi->num_proj_ref`: [`find_samples`]'s own count, all that
9071/// `motion_mode_allowed` needs to pick the 3-symbol `motion_mode_cdf` over
9072/// the 2-symbol `obmc_cdf` (spec 5.11.24).
9073#[allow(clippy::too_many_arguments)]
9074fn num_proj_ref(
9075 grid: &MiGrid,
9076 mi_row: usize,
9077 mi_col: usize,
9078 bw4: usize,
9079 bh4: usize,
9080 mi_cols: usize,
9081 mi_rows: usize,
9082 ref_frame: i8,
9083) -> u8 {
9084 find_samples(grid, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows, ref_frame).len() as u8
9085}
9086
9087/// `av1_get_obmc_mask` (`reconinter.c`): the per-position blend weight
9088/// (`AOM_BLEND_A64` numerator, out of 64) for the neighbour's own
9089/// contribution's *complement* -- i.e. `dst = (mask*orig + (64-mask)*nbr +
9090/// 32) >> 6`, low near the shared border (heavier neighbour weight) rising
9091/// to 64 (no neighbour contribution) away from it. Only the lengths this
9092/// decoder's own overlap sizes ever produce (luma 8/16/32, chroma 4/8/16)
9093/// are transcribed.
9094fn obmc_mask(len: usize) -> &'static [u8] {
9095 const M4: [u8; 4] = [39, 50, 59, 64];
9096 const M8: [u8; 8] = [36, 42, 48, 53, 57, 61, 64, 64];
9097 const M16: [u8; 16] = [
9098 34, 37, 40, 43, 46, 49, 52, 54, 56, 58, 60, 61, 64, 64, 64, 64,
9099 ];
9100 const M32: [u8; 32] = [
9101 33, 35, 36, 38, 40, 41, 43, 44, 45, 47, 48, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 60,
9102 61, 62, 64, 64, 64, 64, 64, 64, 64, 64,
9103 ];
9104 match len {
9105 4 => &M4,
9106 8 => &M8,
9107 16 => &M16,
9108 32 => &M32,
9109 _ => unreachable!("obmc overlap length outside this decoder's own block-size range"),
9110 }
9111}
9112
9113/// A bordering block's own resolved interp filter kernel, `(h, v)` --
9114/// mirrors [`resolve_interp_filter`]'s own return order from its stored
9115/// `[u8; 2]` (`Neighbours::above_filter`/`left_filter`, `[sym0, sym1]` =
9116/// `[v_sym, h_sym]`). Never calls `from_switchable_symbol` on the `[3, 3]`
9117/// sentinel: that value is only ever stored for an intra neighbour (already
9118/// excluded by [`overlappable_above`]/[`overlappable_left`]'s `is_inter`
9119/// gate) or when `interp_fixed` is `Some` for the whole frame, handled here
9120/// first.
9121fn neighbour_filter(
9122 interp_fixed: Option<mc::InterpFilterKind>,
9123 sym: [u8; 2],
9124) -> (mc::InterpFilterKind, mc::InterpFilterKind) {
9125 if let Some(kind) = interp_fixed {
9126 return (kind, kind);
9127 }
9128 (
9129 mc::InterpFilterKind::from_switchable_symbol(sym[1] as usize),
9130 mc::InterpFilterKind::from_switchable_symbol(sym[0] as usize),
9131 )
9132}
9133
9134/// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
9135/// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
9136/// under `av1_setup_build_prediction_by_{above,left}_pred`).
9137#[allow(clippy::too_many_arguments)]
9138fn obmc_neighbour_pred(
9139 refplane: &PlaneBuf,
9140 x: usize,
9141 y: usize,
9142 mv: (i32, i32),
9143 w: usize,
9144 h: usize,
9145 luma: bool,
9146 h_kind: mc::InterpFilterKind,
9147 v_kind: mc::InterpFilterKind,
9148) -> Vec<u16> {
9149 let mut out = vec![0u16; w * h];
9150 mc::predict_with_filters(
9151 &refplane.data,
9152 refplane.width,
9153 refplane.true_width,
9154 refplane.true_height,
9155 mv_to_q4(x, mv.1, luma),
9156 mv_to_q4(y, mv.0, luma),
9157 w,
9158 h,
9159 h_kind,
9160 v_kind,
9161 &mut out,
9162 );
9163 out
9164}
9165
9166/// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
9167/// row (the above-neighbour pass, `aom_blend_a64_vmask`).
9168/// `ii_weights1d` (reconinter.c:524): the interintra smooth-mask falloff.
9169const II_WEIGHTS_1D: [u8; 128] = [
9170 60, 58, 56, 54, 52, 50, 48, 47, 45, 44, 42, 41, 39, 38, 37, 35, 34, 33, 32,
9171 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 22, 21, 20, 19, 19, 18, 18, 17, 16,
9172 16, 15, 15, 14, 14, 13, 13, 12, 12, 12, 11, 11, 10, 10, 10, 9, 9, 9, 8,
9173 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 4, 4,
9174 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2,
9175 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
9176 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
9177];
9178
9179/// lane-interintra r1: non-wedge interintra prediction for one plane
9180/// (reconinter.c `av1_build_interintra_predictor` + `combine_interintra` +
9181/// `build_smooth_interintra_mask`). Builds the intra predictor for the
9182/// block's II mode (DC/V/H/SMOOTH, angle 0, no filter-intra) from `plane`'s
9183/// own decoded edges at `(x, y)`, then blends it over the inter prediction
9184/// in `pred`: `comp = (mask*intra + (64-mask)*inter + 32) >> 6`
9185/// (`aom_blend_a64_mask`, intra as src0). `ii_size_scales[plane_bsize]`
9186/// reduces to `128 / side` for the square plane sizes this decoder reaches.
9187/// lane-wii r2: `wedge == Some(..)` replaces the mode mask with the wedge
9188/// codebook mask (fixed sign 0; luma stride, 2x2 box-averaged for chroma).
9189fn interintra_blend(
9190 plane: &PlaneBuf,
9191 x: usize,
9192 y: usize,
9193 side: usize,
9194 ii_mode: u8,
9195 wedge: Option<(&'static [u8], usize)>,
9196 pred: &mut [u16],
9197) {
9198 // `interintra_to_intra_mode`: II_DC/II_V/II_H/II_SMOOTH.
9199 let intra_mode = match ii_mode {
9200 0 => crate::intra::DC_PRED,
9201 1 => crate::intra::V_PRED,
9202 2 => crate::intra::H_PRED,
9203 _ => crate::intra::SMOOTH_PRED,
9204 };
9205 let (above, left, corner) = plane.edges(
9206 x,
9207 y,
9208 side,
9209 crate::encode::Reach {
9210 above_right: false,
9211 below_left: false,
9212 },
9213 );
9214 let mut intra = vec![0u16; side * side];
9215 // Edge filtering never applies here: V/H at delta 0 are plain edge
9216 // copies (angle 90/180 skip the directional walk), DC/SMOOTH carry no
9217 // angle at all.
9218 predict(
9219 intra_mode,
9220 0,
9221 above.as_deref(),
9222 left.as_deref(),
9223 corner,
9224 side,
9225 side,
9226 false,
9227 false,
9228 &mut intra,
9229 );
9230 let scale = 128 / side;
9231 for i in 0..side {
9232 for j in 0..side {
9233 let m = u32::from(match wedge {
9234 // lane-wii r2: wedge-interintra mask (aom_blend_a64_mask
9235 // over the wedge codebook, intra as src0, fixed sign 0).
9236 // Luma plane: mask rows are luma-resolution, ms == side.
9237 // 4:2:0 chroma: 2x2 box average (reconinter.c sub8x8 --
9238 // subw == subh == 1).
9239 Some((mask, ms)) if ms == side => mask[i * side + j],
9240 Some((mask, ms)) => {
9241 let t = 2 * i * ms + 2 * j;
9242 ((u32::from(mask[t])
9243 + u32::from(mask[t + 1])
9244 + u32::from(mask[t + ms])
9245 + u32::from(mask[t + ms + 1])
9246 + 2)
9247 >> 2) as u8
9248 }
9249 None => match ii_mode {
9250 0 => 32,
9251 1 => II_WEIGHTS_1D[i * scale],
9252 2 => II_WEIGHTS_1D[j * scale],
9253 _ => II_WEIGHTS_1D[i.min(j) * scale],
9254 },
9255 });
9256 let idx = i * side + j;
9257 pred[idx] =
9258 ((m * u32::from(intra[idx]) + (64 - m) * u32::from(pred[idx]) + 32) >> 6) as u16;
9259 }
9260 }
9261}
9262
9263fn obmc_blend_v(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
9264 let mask = obmc_mask(h);
9265 for row in 0..h {
9266 let m = u32::from(mask[row]);
9267 for col in 0..w {
9268 let d = &mut dst[(oy + row) * stride + ox + col];
9269 let t = u32::from(tmp[row * w + col]);
9270 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
9271 }
9272 }
9273}
9274
9275/// Blends `tmp` into `dst` at `(ox, oy)`, mask varying by column (the
9276/// left-neighbour pass, `aom_blend_a64_hmask`).
9277fn obmc_blend_h(dst: &mut [u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize, tmp: &[u16]) {
9278 let mask = obmc_mask(w);
9279 for row in 0..h {
9280 for col in 0..w {
9281 let m = u32::from(mask[col]);
9282 let d = &mut dst[(oy + row) * stride + ox + col];
9283 let t = u32::from(tmp[row * w + col]);
9284 *d = ((m * u32::from(*d) + (64 - m) * t + 32) >> 6) as u16;
9285 }
9286 }
9287}
9288
9289/// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
9290/// the overlap strip against each bordering above/left inter neighbour's own
9291/// mv/ref/filter and blends it into this block's just-built single-reference
9292/// prediction, luma then both 4:2:0 chroma planes -- above pass first, then
9293/// left, each reading only the *original* prediction this function was
9294/// handed (never the other pass's own output), matching libaom's own
9295/// independence between the two. `max_neighbor_obmc`'s own cap table
9296/// (`{0,1,2,3,4,4}` indexed by `mi_size_wide_log2`/`_high_log2`, this
9297/// decoder's own square blocks always index the same value both ways) bounds
9298/// how many bordering blocks actually get blended, separate from the
9299/// eligibility scan's own unbounded ("any at all") walk.
9300#[allow(clippy::too_many_arguments)]
9301fn obmc_blend(
9302 grid: &MiGrid,
9303 neighbours: &Neighbours,
9304 mi_row: usize,
9305 mi_col: usize,
9306 bw4: usize,
9307 bh4: usize,
9308 mi_rows: usize,
9309 mi_cols: usize,
9310 side: usize,
9311 write_w: usize,
9312 write_h: usize,
9313 chroma_side: usize,
9314 px: usize,
9315 py: usize,
9316 cpx: usize,
9317 cpy: usize,
9318 ref_y: &PlaneBuf,
9319 ref_u: &PlaneBuf,
9320 ref_v: &PlaneBuf,
9321 other_refs: &RefSlots,
9322 interp_fixed: Option<mc::InterpFilterKind>,
9323 pred_y: &mut [u16],
9324 pred_u: &mut [u16],
9325 pred_v: &mut [u16],
9326) -> Result<()> {
9327 // lane-rect r2 (libaom av1_build_obmc_inter_prediction): each pass has
9328 // its OWN neighbour cap (width-log2 for above, height-log2 for left) and
9329 // overlap (bh/2 rows above, bw/2 cols left) -- one square `side` was
9330 // right only for square blocks.
9331 let max_nb = |n4: usize| match n4 {
9332 1..=4 => 2,
9333 5..=8 => 3,
9334 _ => 4,
9335 };
9336 let overlap_above = write_h / 2;
9337 let overlap_left = write_w / 2;
9338
9339 for (off4, span4, nb) in overlappable_above(grid, mi_row, mi_col, bw4, mi_cols, max_nb(bw4))
9340 {
9341 // `Neighbours::above_filter` is indexed in `SUB`(16px)-wide columns
9342 // (this decoder's own outer block-loop granularity), one step
9343 // coarser than the mi(4px) units `overlappable_above` walks in --
9344 // divide back down to that column.
9345 let (h_kind, v_kind) = neighbour_filter(
9346 interp_fixed,
9347 neighbours.above_filter[(mi_col + off4) / SUB_MI as usize],
9348 );
9349 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
9350 let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4);
9351 let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind);
9352 obmc_blend_v(pred_y, side, ox, 0, bw, bh, &tmp_y);
9353 let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2);
9354 let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind);
9355 obmc_blend_v(pred_u, chroma_side, cox, 0, cbw, cbh, &tmp_u);
9356 let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind);
9357 obmc_blend_v(pred_v, chroma_side, cox, 0, cbw, cbh, &tmp_v);
9358 }
9359
9360 for (off4, span4, nb) in overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4)) {
9361 let (h_kind, v_kind) = neighbour_filter(
9362 interp_fixed,
9363 neighbours.left_filter[(mi_row + off4) / SUB_MI as usize],
9364 );
9365 let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
9366 let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4);
9367 let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind);
9368 obmc_blend_h(pred_y, side, 0, oy, bw, bh, &tmp_y);
9369 let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2);
9370 let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind);
9371 obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, cbh, &tmp_u);
9372 let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind);
9373 obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, cbh, &tmp_v);
9374 }
9375 Ok(())
9376}
9377
9378/// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
9379/// the square block sizes this decoder ever decodes (32/16/8, all
9380/// `min(w,h) >= 8`, `is_comp_ref_allowed` true): `COMPOUND_DIFFWTD` is then
9381/// always `is_interinter_compound_used`, so the function is always `true`
9382/// for `side` -- kept as a named call (rather than inlined `true`) so a
9383/// future sub-8 block size does not silently misdecode a real stream.
9384fn is_any_masked_compound_used_here(side: usize) -> bool {
9385 side.min(side) >= 8
9386}
9387
9388/// Whether a compound reference pair is unidirectional (both references on
9389/// the same temporal side of the current frame) -- `has_uni_comp_refs`
9390/// (libaom `av1_reference_frame_utils.h`/`pred_common.c`'s own definition:
9391/// a pair is `UNIDIR_COMP_REFERENCE` exactly when neither reference is
9392/// backward-while-the-other-is-forward, i.e. `is_backward(ref0) ==
9393/// is_backward(ref1)`). Used to build a real
9394/// [`crate::mvstack::NeighbourRef::uni`] once `ref1` is known, matching
9395/// [`crate::mvstack::comp_reference_type_ctx`]'s own `is_backward` calls.
9396fn is_uni_comp_ref(ref0: i8, ref1: i8) -> bool {
9397 let backward = |r: i8| (BWDREF_FRAME..=ALTREF_FRAME).contains(&r);
9398 backward(ref0) == backward(ref1)
9399}
9400
9401/// `get_comp_group_idx_context` (libaom `pred_common.h`): sums the
9402/// above/left neighbour contributions [`Neighbours::record_inter`]/
9403/// [`Neighbours::record_compound_ctx`] already precomputed, clamped to 5.
9404fn get_comp_group_idx_context(neighbours: &Neighbours, at: (usize, usize), side: usize) -> usize {
9405 let _ = side;
9406 let (r, c) = at;
9407 (neighbours.above_comp_group_idx[c] as usize + neighbours.left_comp_group_idx[r] as usize)
9408 .min(5)
9409}
9410
9411/// `get_comp_index_context` (libaom `pred_common.h`): the above/left
9412/// neighbour bits plus `3 * (fwd == bck)`, where `fwd`/`bck` are this
9413/// block's own two references' distances from the current frame (spec
9414/// 7.11.3.15's `get_relative_dist`, same convention
9415/// [`crate::compound::dist_wtd_comp_weight_assign`] uses).
9416#[allow(clippy::too_many_arguments)]
9417fn get_comp_index_context(
9418 neighbours: &Neighbours,
9419 at: (usize, usize),
9420 side: usize,
9421 order_hint_bits: u32,
9422 cur_order_hint: u32,
9423 ref0_order_hint: u32,
9424 ref1_order_hint: u32,
9425) -> usize {
9426 let _ = side;
9427 let (r, c) = at;
9428 let fwd =
9429 crate::motion_field::get_relative_dist(order_hint_bits, ref1_order_hint, cur_order_hint)
9430 .abs();
9431 let bck =
9432 crate::motion_field::get_relative_dist(order_hint_bits, cur_order_hint, ref0_order_hint)
9433 .abs();
9434 let offset = usize::from(fwd == bck);
9435 neighbours.above_compound_idx[c] as usize
9436 + neighbours.left_compound_idx[r] as usize
9437 + 3 * offset
9438}
9439
9440fn read_comp_mode(
9441 dec: &mut SymbolDecoder,
9442 cdfs: &mut Cdfs,
9443 above: Option<NeighbourRef>,
9444 left: Option<NeighbourRef>,
9445) -> bool {
9446 let ctx = reference_mode_ctx(above, left);
9447 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
9448 if compound {
9449 COMP_MODE_HITS.with(|c| c.set(c.get() + 1));
9450 }
9451 compound
9452}
9453
9454/// Spec 5.11.25's `comp_reference_type` + the `uni_comp_ref`/`comp_ref`/
9455/// `comp_bwdref` trees (libaom `decodemv.c`'s `read_ref_frames` compound
9456/// arm), reached once [`read_comp_mode`] has already returned
9457/// `COMPOUND_REFERENCE`. Returns `(RefFrame[0], RefFrame[1])`.
9458/// `above`/`left` are [`comp_reference_type_ctx`]'s own `NeighbourRef`
9459/// convention; `above_ref`/`left_ref` are the scalar `1..=7`/`-1`
9460/// convention [`read_single_ref`] already uses, for every downstream binary
9461/// decision. libaom `pred_common.c`'s own compound context functions
9462/// (`av1_get_pred_context_uni_comp_ref_p[1|2]`, `comp_ref_p[1|2]`,
9463/// `comp_bwdref_p[1]`) turned out to be exactly [`single_ref_p1_ctx`]..
9464/// [`single_ref_p6_ctx`]/[`uni_comp_ref_p1_ctx`] under a different name
9465/// (same vote-the-neighbours-above-left shape, same forward/backward and
9466/// LAST/LAST2/LAST3/GOLDEN groupings) -- lane-av1comp audited each one
9467/// against the C source rather than porting six near-duplicate functions.
9468/// Its caller today only needs the symbols consumed, correctly, to keep the
9469/// arithmetic decoder's own state in sync before refusing the block by name
9470/// -- the returned pair is not yet threaded into any motion-compensation
9471/// path.
9472fn read_compound_ref_frames(
9473 dec: &mut SymbolDecoder,
9474 cdfs: &mut Cdfs,
9475 above: Option<NeighbourRef>,
9476 left: Option<NeighbourRef>,
9477 above_ref: i8,
9478 left_ref: i8,
9479) -> (i8, i8) {
9480 let a = (above_ref > 0).then_some(above_ref);
9481 let l = (left_ref > 0).then_some(left_ref);
9482 // libaom `av1_collect_neighbors_ref_counts` counts BOTH of a compound
9483 // neighbour's references, not just its first -- `a1`/`l1` carry that
9484 // second reference through to every vote below (lane-av1blend r6: a
9485 // missing `a1`/`l1` here was decoding `compound_idx` off the wrong CDF
9486 // row for a block sitting under a skip_mode-forced compound neighbour).
9487 let a1 = above.and_then(|n| n.ref1);
9488 let l1 = left.and_then(|n| n.ref1);
9489 let type_ctx = comp_reference_type_ctx(above, left);
9490 let unidir = dec.symbol(&mut cdfs.comp_ref_type[type_ctx]) == 0;
9491 if unidir {
9492 // uni_comp_ref (p0): forward vs. backward -- av1_get_pred_context_-
9493 // uni_comp_ref_p is single_ref_p1's own forward/backward vote.
9494 let bit = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p1_ctx(a, a1, l, l1)][0]);
9495 if bit == 1 {
9496 (BWDREF_FRAME, ALTREF_FRAME)
9497 } else {
9498 let p1 = dec.symbol(&mut cdfs.uni_comp_ref[uni_comp_ref_p1_ctx(a, a1, l, l1)][1]);
9499 if p1 == 1 {
9500 // uni_comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
9501 let p2 = dec.symbol(&mut cdfs.uni_comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
9502 if p2 == 1 {
9503 (LAST_FRAME, GOLDEN_FRAME)
9504 } else {
9505 (LAST_FRAME, LAST3_FRAME)
9506 }
9507 } else {
9508 (LAST_FRAME, LAST2_FRAME)
9509 }
9510 }
9511 } else {
9512 // comp_ref (p0): LAST/LAST2 vs. LAST3/GOLDEN, same vote as single_ref_p3.
9513 let bit0 = dec.symbol(&mut cdfs.comp_ref[single_ref_p3_ctx(a, a1, l, l1)][0]);
9514 let ref0 = if bit0 == 0 {
9515 // comp_ref_p1: LAST vs. LAST2, same vote as single_ref_p4.
9516 let p1 = dec.symbol(&mut cdfs.comp_ref[single_ref_p4_ctx(a, a1, l, l1)][1]);
9517 if p1 == 1 { LAST2_FRAME } else { LAST_FRAME }
9518 } else {
9519 // comp_ref_p2: LAST3 vs. GOLDEN, same vote as single_ref_p5.
9520 let p2 = dec.symbol(&mut cdfs.comp_ref[single_ref_p5_ctx(a, a1, l, l1)][2]);
9521 if p2 == 1 { GOLDEN_FRAME } else { LAST3_FRAME }
9522 };
9523 // comp_bwdref (p0): BWDREF/ALTREF2 vs. ALTREF, same vote as single_ref_p2.
9524 let bit1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p2_ctx(a, a1, l, l1)][0]);
9525 let ref1 = if bit1 == 0 {
9526 // comp_bwdref_p1: BWDREF vs. ALTREF2, same vote as single_ref_p6.
9527 let p1 = dec.symbol(&mut cdfs.comp_bwdref[single_ref_p6_ctx(a, a1, l, l1)][1]);
9528 if p1 == 1 { ALTREF2_FRAME } else { BWDREF_FRAME }
9529 } else {
9530 ALTREF_FRAME
9531 };
9532 (ref0, ref1)
9533 }
9534}
9535
9536/// Spec 5.11.24's `compound_mode` (lane-av1comp): which of the eight
9537/// `INTER_COMPOUND_MODES` (`NEAREST_NEARESTMV`..`NEW_NEWMV`, returned as
9538/// `0..=7`) a `COMPOUND_REFERENCE` block takes, reached once
9539/// [`read_comp_mode`] has already returned `COMPOUND_REFERENCE`. `ctx` is
9540/// libaom's `av1_mode_context_analyzer`'s compound branch --
9541/// `compound_mode_ctx_map[ref_mv_ctx >> 1][min(new_mv_ctx, COMP_NEWMV_CTXS
9542/// - 1)]` (`mvref_common.h`) -- folded from [`crate::mvstack::
9543/// find_mv_stack_compound`]'s own `new_mv_ctx`/`ref_mv_ctx`. The read symbol
9544/// is not yet turned into an assigned MV pair or motion-compensated --
9545/// lane-av1comp.
9546fn read_inter_compound_mode(
9547 dec: &mut SymbolDecoder,
9548 cdfs: &mut Cdfs,
9549 new_mv_ctx: usize,
9550 ref_mv_ctx: usize,
9551) -> u8 {
9552 let ctx = cdf::COMPOUND_MODE_CTX_MAP[ref_mv_ctx >> 1][new_mv_ctx.min(4)];
9553 COMPOUND_MODE_HITS.with(|c| c.set(c.get() + 1));
9554 dec.symbol(&mut cdfs.inter_compound_mode[ctx]) as u8
9555}
9556
9557/// spec 7.10.2.10 `assign_mv`'s compound branch, plus the compound half of
9558/// `read_drl_idx` (spec 5.11.24) it depends on -- `mode` is
9559/// [`read_inter_compound_mode`]'s own `0..=7` (`NEAREST_NEARESTMV`..
9560/// `NEW_NEWMV`, libaom `enums.h` order). Every `GLOBAL_GLOBALMV` side reads
9561/// as `(0, 0)` since [`crate::stream::decode_stream`] already refuses any
9562/// non-`IDENTITY` global motion model before a tile is ever decoded.
9563///
9564/// Ported straight from libaom `decodemv.c`'s `read_drl_idx` (the
9565/// `NEW_NEWMV`/`have_nearmv_in_inter_mode` branches) and `assign_mv`/its
9566/// caller's `ref_mv[]`/`nearmv[]` setup: the `NEAR_NEWMV`/`NEW_NEARMV`
9567/// `1 + ref_mv_idx` special case is folded into `new_idx` below, matching
9568/// `read_drl_idx`'s own comment about "offsetting the NEARESTMV mode".
9569fn assign_compound_mv(
9570 dec: &mut SymbolDecoder,
9571 cdfs: &mut Cdfs,
9572 comp_stack: &crate::mvstack::CompoundMvStack,
9573 mode: u8,
9574 allow_high_precision_mv: bool,
9575 force_integer_mv: bool,
9576 // lane-gm r2: `gm_get_motion_vector(ref0)`/`(ref1)` at this block's own
9577 // position, spec 7.10.2.10's `GLOBAL_GLOBALMV` assignment.
9578 global_mv: ((i32, i32), (i32, i32)),
9579) -> ((i32, i32), (i32, i32)) {
9580 const NEAREST_NEARESTMV: u8 = 0;
9581 const NEAR_NEARMV: u8 = 1;
9582 const NEAREST_NEWMV: u8 = 2;
9583 const NEW_NEARESTMV: u8 = 3;
9584 const NEAR_NEWMV: u8 = 4;
9585 const NEW_NEARMV: u8 = 5;
9586 const GLOBAL_GLOBALMV: u8 = 6;
9587 const NEW_NEWMV: u8 = 7;
9588
9589 let mut ref_mv_idx = 0usize;
9590 if mode == NEW_NEWMV {
9591 let mut idx = 0usize;
9592 while idx < 2 && comp_stack.entries.len() > idx + 1 {
9593 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
9594 break;
9595 }
9596 idx += 1;
9597 }
9598 ref_mv_idx = idx;
9599 } else if matches!(mode, NEAR_NEARMV | NEAR_NEWMV | NEW_NEARMV) {
9600 let mut idx = 1usize;
9601 while idx < 3 && comp_stack.entries.len() > idx + 1 {
9602 if dec.symbol(&mut cdfs.drl_mode[comp_stack.drl_ctx[idx]]) == 0 {
9603 break;
9604 }
9605 idx += 1;
9606 }
9607 ref_mv_idx = idx - 1;
9608 }
9609
9610 let near = comp_stack
9611 .entries
9612 .get(ref_mv_idx + 1)
9613 .map_or(comp_stack.near_mv, |e| (e.mv0, e.mv1));
9614 let new_idx = if matches!(mode, NEAR_NEWMV | NEW_NEARMV) {
9615 ref_mv_idx + 1
9616 } else {
9617 ref_mv_idx
9618 };
9619 let new_pred = comp_stack
9620 .entries
9621 .get(new_idx)
9622 .map_or(comp_stack.nearest_mv, |e| (e.mv0, e.mv1));
9623
9624 let read_new = |dec: &mut SymbolDecoder, cdfs: &mut Cdfs, base: (i32, i32)| {
9625 read_mv(
9626 dec,
9627 &mut cdfs.mv_comp,
9628 &mut cdfs.mv_joint,
9629 base,
9630 allow_high_precision_mv,
9631 force_integer_mv,
9632 )
9633 };
9634
9635 match mode {
9636 NEAREST_NEARESTMV => comp_stack.nearest_mv,
9637 NEAR_NEARMV => near,
9638 NEAREST_NEWMV => (comp_stack.nearest_mv.0, read_new(dec, cdfs, new_pred.1)),
9639 NEW_NEARESTMV => (read_new(dec, cdfs, new_pred.0), comp_stack.nearest_mv.1),
9640 NEAR_NEWMV => (near.0, read_new(dec, cdfs, new_pred.1)),
9641 NEW_NEARMV => (read_new(dec, cdfs, new_pred.0), near.1),
9642 GLOBAL_GLOBALMV => global_mv,
9643 _ => (
9644 read_new(dec, cdfs, new_pred.0),
9645 read_new(dec, cdfs, new_pred.1),
9646 ),
9647 }
9648}
9649
9650/// Derives this query block's own [`crate::mvstack::GmMvTable`] -- one
9651/// `gm_get_motion_vector` (spec 7.10.2.1) result per reference frame, at
9652/// THIS block's own `(mi_row, mi_col, bw4, bh4)` (mvstack.rs's own doc: the
9653/// table is always computed at the *querying* block's position, never a
9654/// donating neighbour's).
9655fn build_gm_mv_table(
9656 global_motion: &[ec_av1_syntax::WarpParams; 7],
9657 mi_row: usize,
9658 mi_col: usize,
9659 bw4: usize,
9660 bh4: usize,
9661 allow_high_precision_mv: bool,
9662 force_integer_mv: bool,
9663) -> crate::mvstack::GmMvTable {
9664 std::array::from_fn(|i| {
9665 let gm = &global_motion[i];
9666 crate::warp::gm_get_motion_vector(
9667 gm.model,
9668 &gm.params,
9669 mi_row,
9670 mi_col,
9671 bw4,
9672 bh4,
9673 allow_high_precision_mv,
9674 force_integer_mv,
9675 )
9676 })
9677}
9678
9679/// Decodes one square inter-frame block (32x32 whole or 16x16 leaf): skip,
9680/// `is_inter`, then either the single-reference/MV-stack/motion-vector chain
9681/// and motion-compensated reconstruction, or the inter frame's own intra
9682/// path (`Y_MODE` by size group, not `KF_Y_MODE` by neighbour), mirroring
9683/// [`crate::tile`]'s `sb_coeff_inter_frame_tile`'s whole-block branch and its
9684/// private `write_inter_frame_leaf` -- both share this one function here,
9685/// parameterised by `side`/the transform sets/scan tables/size group they
9686/// each use.
9687///
9688/// # Errors
9689/// Returns an error when a symbol names anything this decoder does not
9690/// reconstruct: a reference other than `LAST_FRAME`, `GLOBALMV` (round 3;
9691/// `NEARESTMV`/`NEARMV`/`NEWMV` are all reconstructed), or an intra
9692/// mode/tx-type outside what [`read_intra_mode`]/[`read_coeffs`] already
9693/// refuse.
9694#[allow(clippy::too_many_arguments)]
9695fn decode_inter_block(
9696 dec: &mut SymbolDecoder,
9697 cdfs: &mut Cdfs,
9698 neighbours: &mut Neighbours,
9699 grid: &mut MiGrid,
9700 at: (usize, usize),
9701 side: usize,
9702 mi_cols: u32,
9703 mi_rows: u32,
9704 y: &mut PlaneBuf,
9705 u: &mut PlaneBuf,
9706 v: &mut PlaneBuf,
9707 ref_y: &PlaneBuf,
9708 ref_u: &PlaneBuf,
9709 ref_v: &PlaneBuf,
9710 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
9711 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
9712 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
9713 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
9714 // slot's still empty (an error-resilient stream, or too early in the
9715 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
9716 other_refs: &RefSlots,
9717 sign_bias_table: &SignBiasTable,
9718 // lane-gm r2: this frame header's own `global_motion` table (spec
9719 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
9720 // -- feeds `warp::gm_get_motion_vector` for `GLOBALMV`/`GLOBAL_GLOBALMV`
9721 // assignment and the mv-stack's neighbour substitution.
9722 global_motion: &[ec_av1_syntax::WarpParams; 7],
9723 base_q_idx: u8,
9724 luma_set_intra: TxbSet,
9725 luma_set_inter: TxbSet,
9726 chroma_set: TxbSet,
9727 luma_tx: usize,
9728 chroma_tx: usize,
9729 scan_luma: &[u16],
9730 scan_chroma: &[u16],
9731 size_group: usize,
9732 allow_high_precision_mv: bool,
9733 force_integer_mv: bool,
9734 interp_fixed: Option<mc::InterpFilterKind>,
9735 enable_dual_filter: bool,
9736 tpl_frame: Option<&TplFrameArgs>,
9737 // lane-av1comp: this frame header's own `reference_select` bit -- `false`
9738 // means every block is `SINGLE_REFERENCE` by construction and `comp_mode`
9739 // is never read (spec 5.11.25); `true` reads `comp_mode` per block and
9740 // refuses (rather than silently misdecoding) the ones that pick
9741 // `COMPOUND_REFERENCE`, since two-reference motion compensation is not
9742 // wired yet.
9743 reference_select: bool,
9744 // lane-av1comp: `seq_params`' own masked-compound/distance-weighted-
9745 // compound enable bits, gating `comp_group_idx`/`compound_idx`
9746 // (spec 5.11.25) -- always present (unlike `tpl_frame`), since the
9747 // compound blend weights need this frame's own order hint regardless
9748 // of `use_ref_frame_mvs`.
9749 enable_masked_compound: bool,
9750 // lane-sb128 r4: this sequence header's own `enable_interintra_compound`
9751 // bit (spec 5.11.24's `interintra` read, libaom `decodemv.c`
9752 // read_inter_block_mode_info ~1490-1510) -- read right after `assign_mv`
9753 // and before `read_motion_mode` on the single-ref path below, gated by
9754 // `is_interintra_allowed` (single-ref, `BLOCK_8X8..=BLOCK_32X32`, and
9755 // every mode this single-ref branch can produce is already in
9756 // `SINGLE_INTER_MODE_START..END`); `interintra == 1` is a named refusal
9757 // (inter+intra blended prediction unimplemented) rather than a
9758 // mis-decode.
9759 enable_interintra_compound: bool,
9760 enable_jnt_comp: bool,
9761 order_hint_bits: u32,
9762 order_hint: u32,
9763 ref_order_hints: [u32; 7],
9764 // lane-av1comp round 14: this frame header's own `skip_mode_present` bit
9765 // and `skip_mode_frame` reference pair (spec 5.9.22, `frame.rs`'s
9766 // `read_skip_mode_params`, already 1-based `MV_REFERENCE_FRAME`) --
9767 // `skip_mode` (spec 5.11.23 `read_skip_mode`) is read *before* `skip`
9768 // when this is `true` (every block this decoder reaches is >= 8x8, so
9769 // `is_comp_ref_allowed` never gates it further); a `true` result forces
9770 // `skip_txfm`, `is_inter`, `NEAREST_NEARESTMV` of this pair with no mode/
9771 // DRL symbol read, and a plain average blend with no `comp_group_idx`/
9772 // `compound_idx` read (libaom `decodemv.c` 1604-1619, 1382-1384, 1509).
9773 skip_mode_present: bool,
9774 skip_mode_frame: [u8; 2],
9775 // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/
9776 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`).
9777 switchable_motion_mode: bool,
9778 allow_warped_motion: bool,
9779 // lane-warp r5: set by the HORZ_B arm -- the 32x16 top strip is decoded
9780 // as a square 32x32 block, which over-reads a residual unless coded
9781 // `skip`; a non-skip strip must refuse cleanly instead of desyncing.
9782 reject_residual: bool,
9783 // lane-partitions r1: the strip's own true width/height in pixels --
9784 // `side` keeps governing every syntax/CDF/prediction-buffer decision
9785 // (matching `HORZ_B`'s already-accepted square-context corner-cut), but
9786 // the final pixel write and this block's own neighbour-context stamp
9787 // (`record*`/`fill_*_grid`) use `write_w`/`write_h` instead, so a
9788 // PARTITION_HORZ/VERT strip only claims its own true footprint. `side`
9789 // for every existing (square) caller.
9790 write_w: usize,
9791 write_h: usize,
9792 // lane-screen r2: this frame header's own `allow_screen_content_tools`
9793 // bit, threaded to the intra-sub-block branch below -- libaom's
9794 // `read_intra_block_mode_info` (decodemv.c:1065-1107, the inter-frame
9795 // counterpart of `read_intra_frame_mode_info`) reads `y_mode_cdf`
9796 // (never `kf_y_mode_cdf`) and has NO `use_intrabc` call at all (that
9797 // symbol is intra-frame-only, spec `av1_read_mode_info` dispatches on
9798 // `frame_is_intra_only`), but it still calls `read_palette_mode_info`
9799 // under the same `av1_allow_palette` gate as the key-frame path.
9800 allow_screen_content_tools: bool,
9801 // lane-superres r9: this frame's own coded luma width (spec 7.11.3.3) --
9802 // compared against each reference's stored picture width to decide
9803 // whether a scaled-MC path (`mc::predict_scaled`) or the ordinary
9804 // stride-1 one (`mc::predict_with_filters`) applies per reference, and to
9805 // refuse (rather than mis-decode) the warp/OBMC/interintra/compound
9806 // combinations that don't implement scaled MC yet.
9807 frame_width: usize,
9808) -> Result<()> {
9809 let (r, c) = at;
9810 let (px, py) = (c * SUB, r * SUB);
9811 let (cpx, cpy) = (px / 2, py / 2);
9812 let chroma_side = side / 2;
9813 let (write_chroma_w, write_chroma_h) = (write_w / 2, write_h / 2);
9814
9815 if std::env::var_os("EC_AV1_TELL").is_some() {
9816 eprintln!(
9817 "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}",
9818 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
9819 );
9820 }
9821 let skip_mode_ctx =
9822 usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);
9823 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read
9824 // MSAC tell so it can be diffed against an equivalent hook in libaom's
9825 // own `read_skip_mode`/`av1_get_skip_mode_context`.
9826 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
9827 eprintln!(
9828 "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}",
9829 dec.debug_bitpos()
9830 );
9831 }
9832 // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before
9833 // `skip_mode`/`skip`, `inter_segment_id(0)` after them.
9834 let (seg_mi_r, seg_mi_c) = (r * SUB_MI as usize, c * SUB_MI as usize);
9835 let (seg_w_mi, seg_h_mi) = (write_w / 4, write_h / 4);
9836 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, false, true);
9837 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
9838 if std::env::var_os("EC_AV1_SKIPMODE_DUMP").is_some() {
9839 eprintln!(
9840 "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}",
9841 dec.debug_bitpos()
9842 );
9843 }
9844 if skip_mode {
9845 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
9846 }
9847
9848 let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]);
9849 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
9850 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false);
9851 maybe_read_cdef_idx(dec, r * SUB_MI as usize, c * SUB_MI as usize, skip);
9852 maybe_read_delta_q(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
9853 maybe_read_delta_lf(dec, cdfs, r * SUB_MI as usize, c * SUB_MI as usize, side == 64, skip);
9854 // lane-warp r5: see `reject_residual` -- a square-block decode of a
9855 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
9856 // motion_mode/warp symbol), so gate here before any further read.
9857 if reject_residual && !skip {
9858 return Err(unsupported(
9859 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
9860 ));
9861 }
9862
9863 let (has_above, has_left) = (
9864 r > neighbours.tile_row0_mi / (SUB / MI),
9865 c > neighbours.tile_col0_mi / (SUB / MI),
9866 );
9867 let (above_inter, left_inter) = (neighbours.above_inter[c], neighbours.left_inter[r]);
9868 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
9869 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
9870 if std::env::var_os("EC_AV1_TELL").is_some() {
9871 eprintln!(
9872 "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}",
9873 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
9874 );
9875 }
9876
9877 let mode_for_tx;
9878 let uv_predict_mode;
9879 let (luma_grid, u_grid, v_grid);
9880 let block_filter;
9881 let ref_frame_for_lf;
9882 let globalmv_for_lf;
9883 // lane-av1comp: `Some((comp_group_idx, compound_idx))` only for a real
9884 // `COMPOUND_REFERENCE` block -- applied to `neighbours` *after* the
9885 // common `record_inter` call below (which would otherwise stamp the
9886 // single-ref ALTREF-special-case default over it).
9887 let mut compound_ctx: Option<(i8, u8, u8)> = None;
9888 if is_inter {
9889 let above_nbr = has_above.then(|| NeighbourRef {
9890 is_inter: above_inter,
9891 ref0: if above_inter {
9892 neighbours.above_ref[c]
9893 } else {
9894 0
9895 },
9896 ref1: neighbours.above_ref1[c],
9897 uni: neighbours.above_ref1[c]
9898 .is_some_and(|r1| is_uni_comp_ref(neighbours.above_ref[c], r1)),
9899 });
9900 let left_nbr = has_left.then(|| NeighbourRef {
9901 is_inter: left_inter,
9902 ref0: if left_inter {
9903 neighbours.left_ref[r]
9904 } else {
9905 0
9906 },
9907 ref1: neighbours.left_ref1[r],
9908 uni: neighbours.left_ref1[r]
9909 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[r], r1)),
9910 });
9911 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
9912 eprintln!(
9913 "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}",
9914 dec.debug_bitpos()
9915 );
9916 }
9917 let is_compound =
9918 skip_mode || (reference_select && read_comp_mode(dec, cdfs, above_nbr, left_nbr));
9919 if is_compound {
9920 let (ref0, ref1) = if skip_mode {
9921 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
9922 } else {
9923 read_compound_ref_frames(
9924 dec,
9925 cdfs,
9926 above_nbr,
9927 left_nbr,
9928 neighbours.above_ref[c],
9929 neighbours.left_ref[r],
9930 )
9931 };
9932 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
9933 // lane-rect r2: true footprint, mirroring the single-ref path below.
9934 let bw4 = write_w / 4;
9935 let bh4 = write_h / 4;
9936 // spec 7.10.2.8, doubled per side (`CompoundTplArgs`): same
9937 // `use_ref_frame_mvs` gating as the single-ref `tpl` build
9938 // below, just one `get_relative_dist` per reference.
9939 let comp_tpl = tpl_frame.map(|t| crate::mvstack::CompoundTplArgs {
9940 field: t.field,
9941 cur_offset_0: crate::motion_field::get_relative_dist(
9942 t.order_hint_bits,
9943 t.order_hint,
9944 t.ref_order_hints[(ref0 - LAST_FRAME) as usize],
9945 ),
9946 cur_offset_1: crate::motion_field::get_relative_dist(
9947 t.order_hint_bits,
9948 t.order_hint,
9949 t.ref_order_hints[(ref1 - LAST_FRAME) as usize],
9950 ),
9951 allow_high_precision_mv,
9952 });
9953 let gm_table = build_gm_mv_table(
9954 global_motion,
9955 mi_row,
9956 mi_col,
9957 bw4,
9958 bh4,
9959 allow_high_precision_mv,
9960 force_integer_mv,
9961 );
9962 let comp_stack = crate::mvstack::find_mv_stack_compound(
9963 grid,
9964 mi_row,
9965 mi_col,
9966 bw4,
9967 bh4,
9968 (ref0, ref1),
9969 mi_cols as usize,
9970 mi_rows as usize,
9971 sign_bias_table,
9972 &gm_table,
9973 comp_tpl,
9974 );
9975 let compound_mode = if skip_mode {
9976 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
9977 } else {
9978 read_inter_compound_mode(dec, cdfs, comp_stack.new_mv_ctx, comp_stack.ref_mv_ctx)
9979 };
9980 let (mv0, mv1) = assign_compound_mv(
9981 dec,
9982 cdfs,
9983 &comp_stack,
9984 compound_mode,
9985 allow_high_precision_mv,
9986 force_integer_mv,
9987 (gm_table[(ref0 - LAST_FRAME) as usize], gm_table[(ref1 - LAST_FRAME) as usize]),
9988 );
9989 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
9990 // spec `is_nontrans_global_motion`: ALL active refs' models must
9991 // be non-TRANSLATION (IDENTITY counts) for the compound block's
9992 // interp-filter read to be suppressed.
9993 let gm_nontrans = is_globalmv
9994 && global_motion[(ref0 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation
9995 && global_motion[(ref1 - LAST_FRAME) as usize].model != ec_av1_syntax::WarpModel::Translation;
9996 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
9997 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
9998 // spec `get_ref_filter_type`: matches when EITHER of the
9999 // neighbour's two references equals this block's own ref0 --
10000 // `above_ref1`/`left_ref1` is the neighbour's real second
10001 // reference (`record_compound_ctx`) when it was itself a
10002 // compound block; checking `above_ref`/`left_ref` alone drops a
10003 // real filter match down to the "no neighbour" sentinel
10004 // whenever the shared reference sits in the neighbour's SECOND
10005 // slot (lane-av1idx r2).
10006 let above_filter_ctx = if neighbours.above_ref[c] == ref0
10007 || neighbours.above_ref1[c] == Some(ref0)
10008 {
10009 neighbours.above_filter[c]
10010 } else {
10011 [3, 3]
10012 };
10013 let left_filter_ctx = if neighbours.left_ref[r] == ref0
10014 || neighbours.left_ref1[r] == Some(ref0)
10015 {
10016 neighbours.left_filter[r]
10017 } else {
10018 [3, 3]
10019 };
10020 globalmv_for_lf = is_globalmv;
10021 ref_frame_for_lf = ref0;
10022 mode_for_tx = 0;
10023 uv_predict_mode = DC_PRED;
10024 // lane-rect r2: `grid` (mvstack.rs's own MiGrid, distinct from
10025 // `neighbours`) must be stamped with the block's true footprint
10026 // too -- a square `bw4`x`bw4` stamp here claims a rect strip's
10027 // NEXT strip's own rows/cols before it decodes, corrupting
10028 // every later mvstack scan that reads this cell back.
10029 for dr in 0..bh4 {
10030 for dc in 0..bw4 {
10031 grid.set(
10032 mi_row + dr,
10033 mi_col + dc,
10034 MiInfo {
10035 is_inter: true,
10036 ref_frame: ref0,
10037 ref_frame1: Some(ref1),
10038 mv1: Some(mv1),
10039 mv: mv0,
10040 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
10041 size: bw4,
10042 size_h: bh4,
10043 // libaom `is_global_mv_block`: per-ref-slot, mode
10044 // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's
10045 // own gm model > TRANSLATION (IDENTITY excluded
10046 // too -- the two-predicate trap, distinct from
10047 // `gm_nontrans` above which allows IDENTITY).
10048 is_global_mv0: is_globalmv
10049 && bw4.min(bh4) >= 2
10050 && global_motion[(ref0 - LAST_FRAME) as usize].model as u8 > 1,
10051 is_global_mv1: is_globalmv
10052 && bw4.min(bh4) >= 2
10053 && global_motion[(ref1 - LAST_FRAME) as usize].model as u8 > 1,
10054 },
10055 );
10056 }
10057 }
10058 // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when
10059 // masked compound / distance-weighted compound are actually
10060 // enabled for this stream -- `is_any_masked_compound_used_here`
10061 // is `true` for every block size this decoder ever reaches
10062 // (`min(side,side) >= 8`, `COMPOUND_DIFFWTD` always eligible
10063 // there), so the gate reduces to the sequence header bit; kept
10064 // as an explicit call so a future smaller block size is not
10065 // silently wrong (libaom `reconinter.h::is_any_masked_compound_used`).
10066 let group_ctx = get_comp_group_idx_context(neighbours, at, side);
10067 let comp_group_idx = if !skip_mode
10068 && enable_masked_compound
10069 && is_any_masked_compound_used_here(side)
10070 {
10071 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
10072 } else {
10073 0
10074 };
10075 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a
10076 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)
10077 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set
10078 // when `comp_group_idx == 1`.
10079 let mut diffwtd_mask_type: Option<u8> = None;
10080 let mut wedge_mask: Option<&'static [u8]> = None;
10081 if comp_group_idx == 1 {
10082 // lane-maskcomp r1: `read_compound_type` (spec 5.11.25,
10083 // libaom `decodemv.c` 1634-1656). `is_interinter_compound_used
10084 // (COMPOUND_WEDGE, bsize)` (`av1_is_wedge_used`,
10085 // `av1_wedge_params_lookup`) is true for every square bsize
10086 // this leaf reaches (8x8/16x16/32x32 all have
10087 // `wedge_types > 0`), so `compound_type` always reads a real
10088 // symbol here -- no alphabet collapse to worry about at this
10089 // block-size family.
10090 let wedge_bsize = match side {
10091 8 => 3,
10092 16 => 6,
10093 32 => 9,
10094 _ => unreachable!("decode_inter_block leaf side is 8/16/32"),
10095 };
10096 let compound_type = dec.symbol(&mut cdfs.compound_type[wedge_bsize]);
10097 if compound_type == 0 {
10098 // COMPOUND_WEDGE: lane-wedge r3, codebook checksum-
10099 // verified vs independent C dump (wedge.rs).
10100 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
10101 let wedge_sign = dec.literal(1);
10102 WEDGE_HITS.with(|c| c.set(c.get() + 1));
10103 wedge_mask = Some(
10104 crate::wedge::wedge_masks()
10105 .codebook(side)
10106 .mask(wedge_sign as usize, wedge_index as usize),
10107 );
10108 } else {
10109 // COMPOUND_DIFFWTD: `mask_type`, MAX_DIFFWTD_MASK_BITS==1.
10110 let mask_type = dec.literal(1);
10111 diffwtd_mask_type = Some(mask_type as u8);
10112 }
10113 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
10114 }
10115 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): r16/r17
10116 // called this a `predict_compound_intermediate`/`combine_compound`
10117 // reconstruction defect. r1 FALSIFIED that hypothesis outright:
10118 // unmasking and running the real gates
10119 // (a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly,
10120 // a_real_aomenc_stream_with_compound_references_decodes_pixel_exact)
10121 // shows the plain-average blend is bit-exact *most of the time*
10122 // -- `combine_compound`'s two-shift-in-one round2 was proven
10123 // algebraically identical to libaom's separate
10124 // `>>DIST_PRECISION_BITS`-then-`ROUND_POWER_OF_TWO` sequence
10125 // (av1_dist_wtd_convolve_2d_c, convolve.c:402-415) for every
10126 // input, and a whole-pel zero-MV compound block (mv0=mv1=(0,0),
10127 // the common case a lag-in-frames GOP's hidden altref frames
10128 // hit) reproduces aomdec's own pre-deblock dump byte-for-byte
10129 // for several consecutive frames.
10130 //
10131 // The real defect a live gate run isolated (seed 49,
10132 // `fixtures/av1blend-r1-mismatch.obu`): decode-order frame 0
10133 // (keyframe) and frame 1 (first hidden altref, `ref1 ==
10134 // ALTREF_FRAME`) match aomdec's own pre-deblock dump byte for
10135 // byte; decode-order frame 2 -- same shape, same zero MV, only
10136 // difference `ref1 == BWDREF_FRAME` instead of `ALTREF_FRAME` --
10137 // is the *first* frame to diverge (881/6144 luma+chroma bytes).
10138 // Every later frame up through decode-order 9 also mismatches,
10139 // *including* frame 8, whose four blocks are back to
10140 // `ref1 == ALTREF_FRAME` only -- ruling out "BWDREF_FRAME's MC
10141 // math is wrong" (that block's own math is proven exact) in
10142 // favour of "the picture sitting in some DPB slot is already
10143 // wrong by the time frame 2 reads it, and the corruption
10144 // propagates through refresh_frame_flags into every later
10145 // reference regardless of which named ref a later block picks".
10146 // Frames 10 through 18 (once the GOP's lineage stops tracing
10147 // back through the bad slot) are bit-exact again. This points at
10148 // reference-slot bookkeeping (`ref_slots`/`refresh_frame_flags`
10149 // in `stream.rs`'s `decode_stream`, or `ref_order_hints`/DPB
10150 // indexing feeding `dist_wtd_comp_weight_assign`) around
10151 // BWDREF_FRAME specifically, not at the MC/blend arithmetic in
10152 // mc.rs. Not isolated further within lane-av1blend's budget --
10153 // refuse by name rather than ship a blend that is right only
10154 // sometimes. Ceiling: r13/r14's MC plumbing above this line
10155 // stays -- only the plain-average reconstruct is masked off
10156 // again. Upgrade: instrument `ref_slots`/`refresh_frame_flags`
10157 // per decode-order frame (which slot each `Frame` OBU refreshes,
10158 // and which slot each `ref_frame_idx[BWDREF_FRAME - LAST_FRAME]`
10159 // reads) against aomdec's own `RefCntBuffer` bookkeeping on
10160 // `fixtures/av1blend-r1-mismatch.obu`, starting at decode-order
10161 // frame 2.
10162 //
10163 // r2 (fresh fixture, seed 45, same recipe -- the original r1
10164 // fixture is gitignored and could not be regenerated byte-exact):
10165 // static review of `stream.rs`'s `ref_slots`/`refresh_frame_flags`/
10166 // `cdf_slots` bookkeeping and the `show_existing_frame` refresh
10167 // arm (spec 7.21: only refreshes on a shown KEY frame, which the
10168 // parser already enforces at `frame.rs:791/815` -- `refresh_frame_flags`
10169 // is forced 0 on every non-key `show_existing_frame`) turned up
10170 // nothing wrong; `other_refs`/`ref_planes` slot indexing for
10171 // `BWDREF_FRAME` is spec-correct too. A live unmasked run
10172 // isolated a *different, smaller* shape than r1's: decode-order
10173 // frame 3 (a `ref1 == BWDREF_FRAME`, zero-MV, simple-average
10174 // compound block) is the first to diverge from ffmpeg (worst
10175 // delta 1, luma only, clustered at 32-pixel block edges) even
10176 // though BOTH its compound inputs -- the key frame and
10177 // decode-order frame 2's own picture (`ref1 == ALTREF_FRAME`,
10178 // itself proven bit-exact: it is later re-shown via
10179 // `show_existing_frame` and matches ffmpeg exactly) -- are
10180 // independently pixel-exact, and the blend arithmetic is the
10181 // same proven-exact formula. That rules out "wrong slot"/"stale
10182 // picture" for this fixture: the inputs are right, so the defect
10183 // is in decode-order frame 3's *own* per-block decode (entropy
10184 // desync from compound-CDF adaptation carried across a slot, or
10185 // the compound mode/MV read itself) -- not in `ref_slots`/
10186 // `refresh_frame_flags`. Not isolated further within budget.
10187 // Upgrade: bisect decode-order frame 3's tile decode against a
10188 // synced `EC_TOK`/`EC_PART` trace from the instrumented aomdec
10189 // build (`/tmp/libaom-src/build/decoder-debug/aomdec`) on
10190 // `fixtures/av1blend-r1-mismatch.obu` (seed 45 now, not seed 49)
10191 // -- the pre-deblock dump frame-index alignment between this
10192 // crate and that aomdec build is NOT 1:1 on this fixture (23
10193 // dumps here vs 24 there), so calibrate that first.
10194 // r3 (this round): pre-deblock buffers were bisected byte-for-byte
10195 // against an instrumented aomdec build (frame-index alignment
10196 // recalibrated via content-hash matching rather than the raw
10197 // dump count -- the keyframe never calls a pre-deblock dump at
10198 // all, since only `decode_inter_frame_tile` does, which is the
10199 // whole "23 vs 24" gap, not a real bug).
10200 // Decode-order frame 3 (`fixtures/av1blend-r1-mismatch.obu`,
10201 // seed 45) is still the first divergence: PRE-deblock differs
10202 // from aomdec's own pre-deblock dump by up to 1, on ~20% of
10203 // luma pixels, clustered where its two compound inputs' pixel
10204 // values disagree by more than a couple of levels -- both
10205 // inputs (the keyframe and decode-order frame 2's own picture)
10206 // are independently proven bit-exact (pre- and post-deblock)
10207 // against aomdec, and `decodemv`'s own EC_TRACE (mode/mv/skip)
10208 // matches this decoder's block loop exactly for every block in
10209 // this frame. Solving `aomval = (key*w0 + bwd*w1 + 8) >> 4` for
10210 // every mismatching pixel against `key`/`bwd` (both known-exact)
10211 // picks out `w0=9, w1=7` for the majority (525/846) with zero
10212 // matches for the plain average this decoder actually emits or
10213 // the reversed `w0=7, w1=9` -- i.e. `compound_idx` is being
10214 // decoded as `1` (simple average, spec `COMPOUND_AVERAGE`) when
10215 // the real bitstream encoded `0` (`COMPOUND_DISTWTD`,
10216 // `dist_wtd_comp_weight_assign`'s own weights for this frame's
10217 // order-hint distances 2/3 land on exactly `(9, 7)` -- this
10218 // decoder's own `dist_wtd_comp_weight_assign` was independently
10219 // re-verified against `QUANT_DIST_WEIGHT`/`QUANT_DIST_LOOKUP_TABLE`
10220 // by hand for these distances and gives the same `(9, 7)`).
10221 // `get_comp_index_context` was checked line-for-line against
10222 // libaom's `pred_common.h` (the `fwd`/`bck` distance halves, the
10223 // `above_mi`/`left_mi` `has_second_ref`/`ALTREF_FRAME` fallback,
10224 // the `3 * offset` term) and matches; `Default_Compound_Idx_Cdf`
10225 // (`cdf.rs`'s `COMPOUND_IDX`) matches `entropymode.c`'s
10226 // `default_compound_idx_cdfs` value-for-value; the read is
10227 // gated on `!skip_mode && enable_jnt_comp`, matching libaom's
10228 // `has_second_ref(mbmi) && !mbmi->skip_mode` outer guard plus
10229 // `order_hint_info.enable_dist_wtd_comp` inner guard. The
10230 // remaining 321/846 mismatched pixels do NOT fit `(9, 7)`
10231 // either -- some blocks in this frame plausibly decode a
10232 // genuinely different (correct, context-dependent) compound_idx
10233 // than block (0,0)'s own -- so this is not simply "always wrong
10234 // the same way": table/context/gate are all individually
10235 // verified correct, yet the decoded VALUE at this specific
10236 // symbol is wrong at least once in this frame. Not isolated
10237 // further within budget. Upgrade: instrument `dec.symbol`'s own
10238 // range/bit state (`rng`/`tell`, matching aomdec's own EC_PART
10239 // trace fields) immediately before and after the `compound_idx`
10240 // read specifically, not just the surrounding mode/mv/skip
10241 // trace which does match -- the desync (if any) is local to
10242 // this one read, not a wider stream desync.
10243 //
10244 // r5 (this round): the `resolve_interp_filter` call used to sit
10245 // right here, ahead of `comp_group_idx`/`compound_idx` -- spec
10246 // 5.11.19/libaom `decodemv.c:1575` reads `interp_filter` AFTER
10247 // `read_compound_type`, not before, so that was a genuine
10248 // ordering bug for a Switchable-filter frame (moved below, past
10249 // the `compound_ctx = Some(...)` line). It does NOT explain this
10250 // fixture's own mismatch, though: `av1blend-r1-mismatch.obu`'s
10251 // header carries a *fixed* interpolation filter
10252 // (`interp_fixed = Some(Regular)`, confirmed live via a
10253 // one-off dump), so `resolve_interp_filter` never read a symbol
10254 // in either position -- zero bits moved, decoded values
10255 // unchanged before and after the reorder. Kept anyway: it is a
10256 // real spec-order fix for the next Switchable-filter compound
10257 // stream, independently correct regardless of this fixture.
10258 //
10259 // Also ruled out this round: comparing this crate's own
10260 // `SymbolDecoder::debug_bitpos()` against aomdec's
10261 // `aom_reader_tell()` at the block boundary is NOT a valid
10262 // desync probe -- they are different quantities (raw consumed
10263 // input bits vs. an entropy-cost estimate that advances without
10264 // a literal byte fetch), so equal/unequal bitpos proves nothing
10265 // either way. Do not repeat that comparison; instead trace
10266 // `range`/`value` (this crate) against libaom's own internal
10267 // `dif`/`rng` (needs new instrumentation in both) immediately
10268 // after each read *upstream* of this one in the same block:
10269 // `read_comp_mode`, `read_compound_ref_frames` (comp_ref_type/
10270 // uni_comp_ref/comp_ref/comp_bwdref), `read_inter_compound_mode`,
10271 // and the DRL loop. All of those independently decoded the SAME
10272 // values this crate and aomdec both show (ref0=1, ref1=5, mode
10273 // NEAREST_NEARESTMV, mv=(0,0)) -- but an upstream *context*
10274 // miscomputation can still decode the identical symbol value off
10275 // a slightly different CDF, narrowing `range` by a different
10276 // amount than aomdec without changing the decoded value itself,
10277 // and only surface as a wrong decode a few reads later exactly
10278 // like this. `get_comp_index_context` and the `COMPOUND_IDX`
10279 // table were independently re-verified again this round and are
10280 // still correct; the four candidates above were not re-audited
10281 // this round. Refusing here (rather than shipping a value-exact-
10282 // most-of-the-time blend) until one of them is found wrong.
10283 // r6/r7: found and fixed one real bug (mvstack.rs ref_ctx family
10284 // undercounted compound neighbours in the single_ref_p*/comp_ref*/
10285 // comp_bwdref* context reads -- kept, real fix). Unmasking on
10286 // that fix alone and running the wide gate sweep (many seeds,
10287 // `a_real_aomenc_stream_with_compound_references_decodes_pixel_exact`/
10288 // `a_real_aomenc_stream_with_reference_select_reads_comp_mode_correctly`,
10289 // cq-level=45) still mismatches roughly half the time, at
10290 // different frames each run for the SAME seed -- aomenc's own
10291 // cpu-used=0 RD search is run-to-run nondeterministic (noted
10292 // above), so this is a second, still-unfound compound_idx defect,
10293 // not the one r6/r7 fixed. r6's own residual-mismatch note (321/
10294 // 846 pixels not fitting the (9,7)-vs-plain-average hypothesis
10295 // either) already flagged more than one bug here. Re-masking:
10296 // do not ship a blend that is right only sometimes.
10297 // lane-av1idx r1: fixed one real bug this round
10298 // (`switchable_interp_ctx` never folded in libaom's
10299 // `INTER_FILTER_COMP_OFFSET` for a compound block's own
10300 // interp_filter context -- kept). Pinned
10301 // `fixtures/av1idx-refsel-pin.obu` (seed 61, reference_select
10302 // gate) still mismatches after that fix (decode-order frame 8
10303 // first, small deltas, worst 1-2, propagating through later
10304 // frames via DPB reference) -- a second, still-unfound bug.
10305 // Re-masking: see that fixture + `scratch_isolate_pinned_mismatch`
10306 // (`EC_AV1_PIN=fixtures/av1idx-refsel-pin.obu EC_AV1_PIN_N=20`)
10307 // for the next round's starting point.
10308 // lane-maskcomp r2: `compound_idx` is only read when
10309 // `comp_group_idx == 0` (libaom `decodemv.c:1606`) -- a masked
10310 // (wedge/diffwtd) block never also carries a distance-weighted
10311 // split. This gate was missing before r2 (dead code: the masked
10312 // path always refused earlier, so it never executed with
10313 // `comp_group_idx == 1` in practice).
10314 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
10315 && !skip_mode
10316 && enable_jnt_comp
10317 {
10318 let idx_ctx = get_comp_index_context(
10319 neighbours,
10320 at,
10321 side,
10322 order_hint_bits,
10323 order_hint,
10324 ref_order_hints[(ref0 - LAST_FRAME) as usize],
10325 ref_order_hints[(ref1 - LAST_FRAME) as usize],
10326 );
10327 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
10328 if idx == 1 {
10329 (8, 8, 1u8)
10330 } else {
10331 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
10332 order_hint_bits,
10333 order_hint,
10334 ref_order_hints[(ref0 - LAST_FRAME) as usize],
10335 ref_order_hints[(ref1 - LAST_FRAME) as usize],
10336 );
10337 (fwd, bck, 0u8)
10338 }
10339 } else {
10340 (8, 8, 1u8)
10341 };
10342 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
10343 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
10344 eprintln!(
10345 "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={}",
10346 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
10347 );
10348 }
10349
10350 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
10351 // comes AFTER `read_compound_type` (the `comp_group_idx`/
10352 // `compound_idx` reads just above), not before -- moved here
10353 // (lane-av1blend r5) from its old position ahead of those reads,
10354 // which stole their bits for a Switchable-filter compound block
10355 // and desynced every symbol read after it in the tile.
10356 // `av1_is_interp_needed` is also 0 for `skip_mode` blocks: the
10357 // filter is derived (Regular), never read -- same
10358 // conditional-read contract as the WARPED_CAUSAL suppression on
10359 // the single-ref path below.
10360 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
10361 dec,
10362 cdfs,
10363 interp_fixed,
10364 enable_dual_filter,
10365 gm_nontrans || skip_mode,
10366 above_filter_ctx,
10367 left_filter_ctx,
10368 true,
10369 );
10370 block_filter = resolved_filter;
10371
10372 // lane-superres r9: a scaled reference in a COMPOUND_REFERENCE
10373 // block (either tap) is not wired -- mc::predict_compound_intermediate
10374 // has no scaled counterpart yet -- refuse by name rather than
10375 // silently sample it unscaled.
10376 if py0.width != frame_width || py1.width != frame_width {
10377 return Err(unsupported(
10378 "a compound-reference block with a scaled reference (superres, unimplemented)",
10379 ));
10380 }
10381
10382 let mut inter0_y = vec![0i32; side * side];
10383 mc::predict_compound_intermediate(
10384 &py0.data,
10385 py0.width,
10386 py0.true_width,
10387 py0.true_height,
10388 mv_to_q4(px, mv0.1, true),
10389 mv_to_q4(py, mv0.0, true),
10390 side,
10391 side,
10392 h_filter,
10393 v_filter,
10394 &mut inter0_y,
10395 );
10396 let mut inter1_y = vec![0i32; side * side];
10397 mc::predict_compound_intermediate(
10398 &py1.data,
10399 py1.width,
10400 py1.true_width,
10401 py1.true_height,
10402 mv_to_q4(px, mv1.1, true),
10403 mv_to_q4(py, mv1.0, true),
10404 side,
10405 side,
10406 h_filter,
10407 v_filter,
10408 &mut inter1_y,
10409 );
10410 let mut pred_y = vec![0u16; side * side];
10411 let mut diffwtd_mask_y = Vec::new();
10412 // lane-wedge r3: `mask_y` is the DIFFWTD buffer just computed OR
10413 // the wedge codebook lookup (comp_group_idx==1's two mutually
10414 // exclusive branches) -- same [`mc::blend_masked_compound`] call
10415 // either way, only the mask source differs.
10416 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
10417 diffwtd_mask_y = vec![0u8; side * side];
10418 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
10419 Some(diffwtd_mask_y.as_slice())
10420 } else {
10421 wedge_mask
10422 };
10423 if let Some(mask_y) = mask_y {
10424 mc::blend_masked_compound(
10425 &inter0_y, &inter1_y, mask_y, side, side, side, false, &mut pred_y,
10426 );
10427 } else {
10428 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
10429 }
10430
10431 let mut inter0_u = vec![0i32; chroma_side * chroma_side];
10432 mc::predict_compound_intermediate(
10433 &pu0.data,
10434 pu0.width,
10435 pu0.true_width,
10436 pu0.true_height,
10437 mv_to_q4(cpx, mv0.1, false),
10438 mv_to_q4(cpy, mv0.0, false),
10439 chroma_side,
10440 chroma_side,
10441 h_filter,
10442 v_filter,
10443 &mut inter0_u,
10444 );
10445 let mut inter1_u = vec![0i32; chroma_side * chroma_side];
10446 mc::predict_compound_intermediate(
10447 &pu1.data,
10448 pu1.width,
10449 pu1.true_width,
10450 pu1.true_height,
10451 mv_to_q4(cpx, mv1.1, false),
10452 mv_to_q4(cpy, mv1.0, false),
10453 chroma_side,
10454 chroma_side,
10455 h_filter,
10456 v_filter,
10457 &mut inter1_u,
10458 );
10459 let mut pred_u = vec![0u16; chroma_side * chroma_side];
10460 if let Some(mask_y) = mask_y {
10461 mc::blend_masked_compound(
10462 &inter0_u,
10463 &inter1_u,
10464 mask_y,
10465 side,
10466 chroma_side,
10467 chroma_side,
10468 true,
10469 &mut pred_u,
10470 );
10471 } else {
10472 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
10473 }
10474
10475 let mut inter0_v = vec![0i32; chroma_side * chroma_side];
10476 mc::predict_compound_intermediate(
10477 &pv0.data,
10478 pv0.width,
10479 pv0.true_width,
10480 pv0.true_height,
10481 mv_to_q4(cpx, mv0.1, false),
10482 mv_to_q4(cpy, mv0.0, false),
10483 chroma_side,
10484 chroma_side,
10485 h_filter,
10486 v_filter,
10487 &mut inter0_v,
10488 );
10489 let mut inter1_v = vec![0i32; chroma_side * chroma_side];
10490 mc::predict_compound_intermediate(
10491 &pv1.data,
10492 pv1.width,
10493 pv1.true_width,
10494 pv1.true_height,
10495 mv_to_q4(cpx, mv1.1, false),
10496 mv_to_q4(cpy, mv1.0, false),
10497 chroma_side,
10498 chroma_side,
10499 h_filter,
10500 v_filter,
10501 &mut inter1_v,
10502 );
10503 let mut pred_v = vec![0u16; chroma_side * chroma_side];
10504 if let Some(mask_y) = mask_y {
10505 mc::blend_masked_compound(
10506 &inter0_v,
10507 &inter1_v,
10508 mask_y,
10509 side,
10510 chroma_side,
10511 chroma_side,
10512 true,
10513 &mut pred_v,
10514 );
10515 } else {
10516 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
10517 }
10518
10519 if skip {
10520 y.reconstruct_mc_rect(
10521 px,
10522 py,
10523 side,
10524 write_w,
10525 write_h,
10526 &pred_y,
10527 &vec![0i32; side * side],
10528 );
10529 u.reconstruct_mc_rect(
10530 cpx,
10531 cpy,
10532 chroma_side,
10533 write_chroma_w,
10534 write_chroma_h,
10535 &pred_u,
10536 &vec![0i32; chroma_side * chroma_side],
10537 );
10538 v.reconstruct_mc_rect(
10539 cpx,
10540 cpy,
10541 chroma_side,
10542 write_chroma_w,
10543 write_chroma_h,
10544 &pred_v,
10545 &vec![0i32; chroma_side * chroma_side],
10546 );
10547 luma_grid = vec![0i32; side * side];
10548 u_grid = vec![0i32; chroma_side * chroma_side];
10549 v_grid = vec![0i32; chroma_side * chroma_side];
10550 } else {
10551 let around = neighbours.around(at, side);
10552 let luma_tx_type;
10553 (luma_grid, luma_tx_type) = read_inter_plane(
10554 dec,
10555 cdfs,
10556 luma_set_inter,
10557 scan_luma,
10558 0,
10559 around[0],
10560 mode_for_tx,
10561 y,
10562 px,
10563 py,
10564 side,
10565 base_q_idx,
10566 &pred_y,
10567 None,
10568 )?;
10569 u_grid = read_inter_plane(
10570 dec,
10571 cdfs,
10572 chroma_set,
10573 scan_chroma,
10574 1,
10575 around[1],
10576 mode_for_tx,
10577 u,
10578 cpx,
10579 cpy,
10580 chroma_side,
10581 base_q_idx,
10582 &pred_u,
10583 Some(luma_tx_type),
10584 )?
10585 .0;
10586 v_grid = read_inter_plane(
10587 dec,
10588 cdfs,
10589 chroma_set,
10590 scan_chroma,
10591 2,
10592 around[2],
10593 mode_for_tx,
10594 v,
10595 cpx,
10596 cpy,
10597 chroma_side,
10598 base_q_idx,
10599 &pred_v,
10600 Some(luma_tx_type),
10601 )?
10602 .0;
10603 }
10604 } else {
10605 let ref_frame =
10606 read_single_ref(
10607 dec,
10608 cdfs,
10609 neighbours.above_ref[c],
10610 neighbours.above_ref1[c],
10611 neighbours.left_ref[r],
10612 neighbours.left_ref1[r],
10613 );
10614 ref_frame_for_lf = ref_frame;
10615 if std::env::var_os("EC_AV1_TELL").is_some() {
10616 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
10617 eprintln!(
10618 "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}",
10619 dec.debug_bitpos(), dec.debug_state().0
10620 );
10621 }
10622 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
10623 // stacked defects (lf_level ref/mode-delta forwarding, the
10624 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
10625 // gap that looked like a GOLDEN MC bug by survivor bias -- see the
10626 // ledger) are all closed; GOLDEN_FRAME decodes live via `other_refs`
10627 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
10628 // widens this from GOLDEN alone to every reference `read_single_ref`
10629 // can name.
10630 let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
10631 (ref_y, ref_u, ref_v)
10632 } else {
10633 match other_refs[ref_frame as usize] {
10634 Some((ry, ru, rv)) => (ry, ru, rv),
10635 None => {
10636 return Err(unsupported(
10637 "a reference frame selected with no picture at this frame's own \
10638 ref_frame_idx slot for it",
10639 ));
10640 }
10641 }
10642 };
10643
10644 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
10645 // lane-rect r2: the mv stack must be queried with the block's
10646 // REAL extent (libaom `av1_get_mv_refs` gets bw4/bh4 from
10647 // xd->width/xd->height, not a square guess) -- `write_w`/
10648 // `write_h` already name the true HORZ/VERT/HORZ_B strip
10649 // footprint (r1's plumbing), so derive bw4/bh4 from those
10650 // instead of the old `side`-square (HORZ_B-only) heuristic.
10651 let bw4 = write_w / 4;
10652 let bh4 = write_h / 4;
10653 // spec 7.10.2.8: only reached when the frame header set
10654 // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
10655 // otherwise) -- `cur_offset_0` is this query block's own resolved
10656 // `ref_frame`'s distance from the current frame (spec 7.9.3),
10657 // recomputed per block since different blocks pick different refs.
10658 let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
10659 field: t.field,
10660 cur_offset_0: crate::motion_field::get_relative_dist(
10661 t.order_hint_bits,
10662 t.order_hint,
10663 t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
10664 ),
10665 allow_high_precision_mv,
10666 });
10667 let gm_table = build_gm_mv_table(
10668 global_motion,
10669 mi_row,
10670 mi_col,
10671 bw4,
10672 bh4,
10673 allow_high_precision_mv,
10674 force_integer_mv,
10675 );
10676 let stack = find_mv_stack_with_sign_bias(
10677 grid,
10678 mi_row,
10679 mi_col,
10680 bw4,
10681 bh4,
10682 ref_frame,
10683 mi_cols as usize,
10684 mi_rows as usize,
10685 sign_bias_table,
10686 &gm_table,
10687 tpl,
10688 );
10689 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
10690 let mut is_globalmv = false;
10691 let (mv, is_new_mv) = if !not_new {
10692 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
10693 // read at most two `drl_mode` bits, one per stack entry past the
10694 // first, stopping at the first `0`. The chosen index selects
10695 // which stack entry `read_mv`'s base predictor comes from
10696 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
10697 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
10698 let mut idx = 0usize;
10699 while idx < 2 && stack.entries.len() > idx + 1 {
10700 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
10701 break;
10702 }
10703 idx += 1;
10704 }
10705 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
10706 (
10707 read_mv(
10708 dec,
10709 &mut cdfs.mv_comp,
10710 &mut cdfs.mv_joint,
10711 base_mv,
10712 allow_high_precision_mv,
10713 force_integer_mv,
10714 ),
10715 true,
10716 )
10717 } else {
10718 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
10719 is_globalmv = !not_zero;
10720 let mv = if !not_zero {
10721 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
10722 // computed at this block's own position in `gm_table`.
10723 gm_table[(ref_frame - LAST_FRAME) as usize]
10724 } else {
10725 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
10726 if nearest {
10727 stack.nearest_mv
10728 } else {
10729 // NEARMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting
10730 // at 1): read at most two more `drl_mode` bits, one per stack
10731 // entry past the second, stopping at the first `0`.
10732 // `drl_ctx[idx]` is the context between `entries[idx]` and
10733 // `entries[idx + 1]` (`MvStack::drl_ctx`'s own doc), which is
10734 // exactly the pair this index is choosing between.
10735 let mut idx = 1usize;
10736 while idx < 3 && stack.entries.len() > idx + 1 {
10737 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
10738 break;
10739 }
10740 idx += 1;
10741 }
10742 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
10743 }
10744 };
10745 (mv, false)
10746 };
10747 // lane-gm r2: the two libaom predicates single-ref GLOBALMV
10748 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode
10749 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating
10750 // `motion_mode_eligible`/`MiInfo::is_global_mv0` below) and
10751 // `is_nontrans_global_motion` (reconinter.h:420-425, model !=
10752 // TRANSLATION -- IDENTITY counts here -- gating the interp
10753 // filter suppress below). Do NOT unify these.
10754 let gm_model = global_motion[(ref_frame - LAST_FRAME) as usize].model;
10755 let min_bw_bh4 = bw4.min(bh4);
10756 let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2;
10757 let gm_nontrans =
10758 is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2;
10759 if std::env::var_os("EC_AV1_TELL").is_some() {
10760 eprintln!(
10761 "TELL mi_row={mi_row} mi_col={mi_col} label=post_assign_mv tell={} range={}",
10762 dec.debug_bitpos(), dec.debug_state().0
10763 );
10764 }
10765 // lane-sb128 r4: `interintra` (spec 5.11.24; libaom
10766 // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed
10767 // right after `assign_mv` and before `read_motion_mode` below --
10768 // libaom's own sequential order. `is_interintra_allowed_bsize`
10769 // (`BLOCK_8X8..=BLOCK_32X32`) is the only real gate on this
10770 // single-ref path: `is_interintra_allowed_ref` always holds here
10771 // (single ref, `ref_frame[1]` not yet `INTRA_FRAME`) and
10772 // `is_interintra_allowed_mode` always holds (every mode this
10773 // branch produces -- NEARESTMV/NEARMV/GLOBALMV/NEWMV -- is
10774 // `SINGLE_INTER_MODE_START..END` by construction).
10775 // `size_group_lookup`: BLOCK_16X16 -> 2, BLOCK_32X32 -> 3.
10776 let mut interintra_mode: Option<u8> = None;
10777 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
10778 if enable_interintra_compound && !skip_mode && (side == 16 || side == 32) {
10779 let bsize_group = if side == 16 { 2 } else { 3 };
10780 let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1;
10781 if interintra {
10782 // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode,
10783 // then -- gated on block size ALONE, never the
10784 // `enable_interintra_wedge` seq bit -- the wedge flag
10785 // (`av1_is_wedge_used(bsize)` holds for 16x16/32x32).
10786 let ii = dec.symbol(&mut cdfs.interintra_mode[bsize_group]) as u8;
10787 let wedge_bsize = if side == 16 { 6 } else { 9 };
10788 let wedge = dec.symbol(&mut cdfs.wedge_interintra[wedge_bsize]) == 1;
10789 if wedge {
10790 // lane-wii r2 (spec 5.11.25): `wedge_index` is an
10791 // ADAPTING CDF symbol over the same `wedge_bsize` row;
10792 // NO sign symbol follows -- libaom fixes
10793 // INTERINTRA_WEDGE_SIGN 0 (blockd.h).
10794 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[wedge_bsize]);
10795 WII_HITS.with(|c| c.set(c.get() + 1));
10796 wedge_mask = Some((
10797 crate::wedge::wedge_masks()
10798 .codebook(side)
10799 .mask(0, wedge_index as usize),
10800 side,
10801 ));
10802 } else {
10803 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
10804 }
10805 interintra_mode = Some(ii);
10806 }
10807 }
10808 if std::env::var_os("EC_AV1_TELL").is_some() {
10809 eprintln!(
10810 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interintra tell={} range={}",
10811 dec.debug_bitpos(), dec.debug_state().0
10812 );
10813 }
10814 // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24;
10815 // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528),
10816 // placed right after MV assignment and before the switchable
10817 // interp filter read below (`read_mb_interp_filter`, decodemv.c
10818 // ~1600) -- libaom's own sequential order. `motion_mode_allowed`
10819 // (`reconinter.h`) reduces, for every block this single-ref path
10820 // reaches, to "does an inter neighbour border the above row or
10821 // left column": `is_motion_variation_allowed_bsize` always holds
10822 // (`side` is never below 16px on this path), `ref_frame[1] !=
10823 // INTRA_FRAME` always holds (no interintra reader here),
10824 // `is_motion_variation_allowed_compound` always holds (this is
10825 // the single-ref branch), and `is_global_mv_block` never
10826 // triggers (this decoder's global motion is always `IDENTITY`,
10827 // so its warp `type` is never `> TRANSLATION`). A stream with
10828 // `allow_warped_motion=1` is refused right at an eligible block
10829 // rather than guessed at: `av1_findSamples`/`num_proj_ref` is
10830 // not ported, so this decoder cannot tell a real
10831 // `WARPED_CAUSAL`-eligible block (3-symbol `motion_mode_cdf`)
10832 // from an `OBMC_CAUSAL`-only one (2-symbol `obmc_cdf`) whenever
10833 // the header allows warp -- reading the wrong alphabet desyncs
10834 // the tile.
10835 // An interintra block has `ref_frame[1] == INTRA_FRAME`, which
10836 // fails libaom's `is_motion_variation_allowed_compound`: the
10837 // motion_mode symbol is NOT read (SIMPLE_TRANSLATION implied).
10838 let motion_mode_eligible = switchable_motion_mode
10839 && !skip_mode
10840 && interintra_mode.is_none()
10841 && (!overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).is_empty()
10842 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1)
10843 .is_empty())
10844 // libaom `motion_mode_allowed`: a GLOBALMV block whose model
10845 // is non-IDENTITY-non-TRANSLATION under free (non-integer)
10846 // mv reads no motion_mode/obmc symbol at all -- implicit
10847 // SIMPLE_TRANSLATION.
10848 && !(is_global_mv_block && !force_integer_mv);
10849 let mut obmc_selected = false;
10850 // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL
10851 // *and* the local warp estimate is valid (`!wm_params.invalid`,
10852 // `av1_find_projection`) -- an invalid estimate falls back to
10853 // this block's own translational mv, same as any other block
10854 // (spec `allow_warp`/`reconinter.c` -- global warp is never the
10855 // fallback here since this decoder's global motion is always
10856 // IDENTITY).
10857 let mut warp_params: Option<crate::warp::WarpParams> = None;
10858 // Tracks the SYMBOL value, not projection validity: libaom's
10859 // `av1_is_interp_needed` suppresses the interp-filter read for
10860 // `motion_mode == WARPED_CAUSAL` even when the projection later
10861 // falls back to translation. Its third suppressor,
10862 // `is_nontrans_global_motion`, matches our unconditional
10863 // `is_globalmv` only because this decoder codes global motion as
10864 // IDENTITY (non-TRANSLATION) and never reads switchable filters
10865 // below 8x8 -- porting TRANSLATION global motion must add the
10866 // wmtype check here.
10867 let mut warped_selected = false;
10868 if motion_mode_eligible {
10869 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 ->
10870 // 0/1/2/3; lane-rect r2: a rect strip reads its OWN bsize row
10871 // (libaom `motion_mode_cdf[mbmi->bsize]`: BLOCK_16X32 -> 4,
10872 // BLOCK_32X16 -> 5 in our packed table) -- rect-flake-1's
10873 // strip motion_mode read diverged on the square row.
10874 let bsize_idx = if write_w == write_h {
10875 (write_w.trailing_zeros() - 3) as usize
10876 } else if write_w == 16 {
10877 4
10878 } else {
10879 5
10880 };
10881 // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf`
10882 // instead of the 2-symbol `obmc_cdf` exactly when
10883 // `num_proj_ref >= 1` under `allow_warped_motion`.
10884 let warp_eligible = allow_warped_motion
10885 && num_proj_ref(grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, ref_frame) >= 1;
10886 if warp_eligible {
10887 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);
10888 match mode {
10889 0 => {}
10890 1 => {
10891 obmc_selected = true;
10892 OBMC_HITS.with(|c| c.set(c.get() + 1));
10893 }
10894 _ => {
10895 warped_selected = true;
10896 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
10897 let mut samples = find_samples(
10898 grid,
10899 mi_row,
10900 mi_col,
10901 bw4,
10902 bh4,
10903 mi_cols as usize,
10904 mi_rows as usize,
10905 ref_frame,
10906 );
10907 if std::env::var_os("EC_WARP_DEBUG").is_some() {
10908 eprintln!(
10909 "EC_WARP_DEBUG findSamples mi_row={mi_row} mi_col={mi_col} bsize={side} num_proj_ref={}",
10910 samples.len()
10911 );
10912 for (i, s) in samples.iter().enumerate() {
10913 eprintln!("EC_WARP_DEBUG sample[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
10914 }
10915 }
10916 if samples.len() > 1 {
10917 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
10918 }
10919 warp_params = crate::warp::find_projection(
10920 &samples,
10921 // lane-rect r2: the block's TRUE dims -- a
10922 // 32x16 strip's model center is not a
10923 // 32x32's (aom av1_find_projection bw/bh).
10924 write_w as i32,
10925 write_h as i32,
10926 mv.1,
10927 mv.0,
10928 mi_row as i32,
10929 mi_col as i32,
10930 );
10931 if std::env::var_os("EC_WARP_DEBUG").is_some() {
10932 eprintln!(
10933 "EC_WARP_DEBUG projection mi_row={mi_row} mi_col={mi_col} num_proj_ref(final)={} mv=({},{}) params={:?}",
10934 samples.len(), mv.0, mv.1, warp_params
10935 );
10936 for (i, s) in samples.iter().enumerate() {
10937 eprintln!("EC_WARP_DEBUG sample_used[{i}] pts={:?} pts_inref={:?}", s.pts1, s.pts2);
10938 }
10939 }
10940 }
10941 }
10942 } else {
10943 obmc_selected = dec.symbol(&mut cdfs.obmc[bsize_idx]) == 1;
10944 if obmc_selected {
10945 OBMC_HITS.with(|c| c.set(c.get() + 1));
10946 }
10947 }
10948 }
10949 // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch
10950 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
10951 // libaom's `av1_init_warp_params` runs for every inter
10952 // predictor build, not just a `WARPED_CAUSAL`-selected one. Only
10953 // reachable when `warp_params` is still `None` here: a block
10954 // that read (and got) local `WARPED_CAUSAL` above already has
10955 // `local_warp_allowed && !wm_params.invalid`, which `allow_warp`
10956 // checks FIRST and short-circuits on -- the global branch is an
10957 // `else if`, never layered on top. `is_global_mv_block` already
10958 // encodes `allow_warp`'s size bound (`min(bw4,bh4) >= 2`, i.e.
10959 // >=8px both dims, matching `av1_init_warp_params`'s
10960 // `block_height < 8 || block_width < 8` early return) and, via
10961 // `motion_mode_eligible`'s own suppression above, the
10962 // `force_integer_mv` case never reads a motion_mode symbol at
10963 // all -- checked again here directly since this branch fires
10964 // independent of `motion_mode_eligible`.
10965 let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
10966 if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid {
10967 warp_params = crate::warp::global_warp_params(gm_ref.params);
10968 }
10969 if std::env::var_os("EC_AV1_TELL").is_some() {
10970 eprintln!(
10971 "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",
10972 motion_mode_eligible as u8, dec.debug_bitpos(), dec.debug_state().0
10973 );
10974 }
10975 // spec `get_ref_filter_type`: a neighbour's own filter only feeds
10976 // this block's switchable_interp context when that neighbour coded
10977 // the SAME reference frame this block is about to read -- a
10978 // different-ref neighbour reads as "no neighbour" ([3, 3], the
10979 // sentinel `Neighbours::new` already seeds unset slots with),
10980 // exactly like an intra neighbour. Without this gate, a GOLDEN_FRAME
10981 // block next to a LAST_FRAME one inherits that neighbour's filter
10982 // choice into its own context, corrupting the symbol it reads.
10983 // lane-av1idx r2: also match on the neighbour's SECOND reference
10984 // (`above_ref1`/`left_ref1`, real for a compound neighbour) --
10985 // see the 16x16 leaf's own comment above for the spec citation.
10986 let above_filter_ctx = if neighbours.above_ref[c] == ref_frame
10987 || neighbours.above_ref1[c] == Some(ref_frame)
10988 {
10989 neighbours.above_filter[c]
10990 } else {
10991 [3, 3]
10992 };
10993 let left_filter_ctx = if neighbours.left_ref[r] == ref_frame
10994 || neighbours.left_ref1[r] == Some(ref_frame)
10995 {
10996 neighbours.left_filter[r]
10997 } else {
10998 [3, 3]
10999 };
11000 let (h_filter, v_filter, resolved_filter) = resolve_interp_filter(
11001 dec,
11002 cdfs,
11003 interp_fixed,
11004 enable_dual_filter,
11005 gm_nontrans || warped_selected,
11006 above_filter_ctx,
11007 left_filter_ctx,
11008 false,
11009 );
11010 block_filter = resolved_filter;
11011 globalmv_for_lf = is_globalmv;
11012 if std::env::var_os("EC_AV1_TELL").is_some() {
11013 eprintln!(
11014 "TELL mi_row={mi_row} mi_col={mi_col} label=post_interp_filter tell={} range={}",
11015 dec.debug_bitpos(), dec.debug_state().0
11016 );
11017 }
11018 if std::env::var_os("EC_AV1_TRACE").is_some() {
11019 eprintln!(
11020 "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={}",
11021 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()
11022 );
11023 }
11024 // lane-rect r2: see the compound path's matching comment above --
11025 // `grid` must be stamped with the block's true bh4/bw4 span, not
11026 // a square `bw4`x`bw4` guess.
11027 for dr in 0..bh4 {
11028 for dc in 0..bw4 {
11029 grid.set(
11030 mi_row + dr,
11031 mi_col + dc,
11032 MiInfo {
11033 is_inter: true,
11034 ref_frame,
11035 // An interintra block records ref_frame[1] ==
11036 // INTRA_FRAME (0): warp-sample gathering
11037 // (libaom av1_findSamples, mvref_common.c:1155)
11038 // requires ref_frame[1] == NONE_FRAME, so such a
11039 // neighbour must not donate samples or count in
11040 // num_proj_ref.
11041 ref_frame1: interintra_mode.map(|_| 0),
11042 mv1: None,
11043 mv,
11044 is_new_mv,
11045 size: bw4,
11046 size_h: bh4,
11047 is_global_mv0: is_global_mv_block,
11048 is_global_mv1: false,
11049 },
11050 );
11051 }
11052 }
11053 mode_for_tx = 0;
11054 uv_predict_mode = DC_PRED;
11055
11056 // lane-superres r9: spec 7.11.3.3's x_scale_fp comes from LUMA
11057 // widths only (r8's derivation) and applies unchanged to the
11058 // chroma calls below (their x_q4 is already in the chroma
11059 // plane's own pixel units). `mc::predict_scaled` has no warp/OBMC
11060 // /interintra counterpart -- those three combinations are refused
11061 // by name instead of silently sampling a scaled reference wrong
11062 // (warp_params/obmc_selected/interintra_mode are all resolved by
11063 // this point, every symbol for this block already read).
11064 let luma_scale = mc::scale_factor(py_ref.width, frame_width);
11065 if luma_scale != mc::REF_NO_SCALE
11066 && (warp_params.is_some() || obmc_selected || interintra_mode.is_some())
11067 {
11068 return Err(unsupported(
11069 "warp/OBMC/interintra prediction with a scaled reference (superres, unimplemented)",
11070 ));
11071 }
11072
11073 let mut pred_y = vec![0u16; side * side];
11074 let mut pred_u = vec![0u16; chroma_side * chroma_side];
11075 let mut pred_v = vec![0u16; chroma_side * chroma_side];
11076 if luma_scale == mc::REF_NO_SCALE {
11077 mc::predict_with_filters(
11078 &py_ref.data,
11079 py_ref.width,
11080 py_ref.true_width,
11081 py_ref.true_height,
11082 mv_to_q4(px, mv.1, true),
11083 mv_to_q4(py, mv.0, true),
11084 side,
11085 side,
11086 h_filter,
11087 v_filter,
11088 &mut pred_y,
11089 );
11090 mc::predict_with_filters(
11091 &pu_ref.data,
11092 pu_ref.width,
11093 pu_ref.true_width,
11094 pu_ref.true_height,
11095 mv_to_q4(cpx, mv.1, false),
11096 mv_to_q4(cpy, mv.0, false),
11097 chroma_side,
11098 chroma_side,
11099 h_filter,
11100 v_filter,
11101 &mut pred_u,
11102 );
11103 mc::predict_with_filters(
11104 &pv_ref.data,
11105 pv_ref.width,
11106 pv_ref.true_width,
11107 pv_ref.true_height,
11108 mv_to_q4(cpx, mv.1, false),
11109 mv_to_q4(cpy, mv.0, false),
11110 chroma_side,
11111 chroma_side,
11112 h_filter,
11113 v_filter,
11114 &mut pred_v,
11115 );
11116 } else {
11117 mc::predict_scaled(
11118 &py_ref.data,
11119 py_ref.width,
11120 py_ref.true_width,
11121 py_ref.true_height,
11122 mv_to_q4(px, mv.1, true),
11123 mv_to_q4(py, mv.0, true),
11124 luma_scale,
11125 side,
11126 side,
11127 h_filter,
11128 v_filter,
11129 &mut pred_y,
11130 );
11131 mc::predict_scaled(
11132 &pu_ref.data,
11133 pu_ref.width,
11134 pu_ref.true_width,
11135 pu_ref.true_height,
11136 mv_to_q4(cpx, mv.1, false),
11137 mv_to_q4(cpy, mv.0, false),
11138 luma_scale,
11139 chroma_side,
11140 chroma_side,
11141 h_filter,
11142 v_filter,
11143 &mut pred_u,
11144 );
11145 mc::predict_scaled(
11146 &pv_ref.data,
11147 pv_ref.width,
11148 pv_ref.true_width,
11149 pv_ref.true_height,
11150 mv_to_q4(cpx, mv.1, false),
11151 mv_to_q4(cpy, mv.0, false),
11152 luma_scale,
11153 chroma_side,
11154 chroma_side,
11155 h_filter,
11156 v_filter,
11157 &mut pred_v,
11158 );
11159 }
11160
11161 if let Some(params) = &warp_params {
11162 crate::warp::warp_affine(
11163 params, &py_ref.data, py_ref.true_width as i32, py_ref.true_height as i32,
11164 py_ref.width as i32, &mut pred_y, px as i32, py as i32, side as i32,
11165 side as i32, side as i32, 0, 0,
11166 );
11167 crate::warp::warp_affine(
11168 params, &pu_ref.data, pu_ref.true_width as i32, pu_ref.true_height as i32,
11169 pu_ref.width as i32, &mut pred_u, cpx as i32, cpy as i32, chroma_side as i32,
11170 chroma_side as i32, chroma_side as i32, 1, 1,
11171 );
11172 crate::warp::warp_affine(
11173 params, &pv_ref.data, pv_ref.true_width as i32, pv_ref.true_height as i32,
11174 pv_ref.width as i32, &mut pred_v, cpx as i32, cpy as i32, chroma_side as i32,
11175 chroma_side as i32, chroma_side as i32, 1, 1,
11176 );
11177 }
11178
11179 if obmc_selected {
11180 obmc_blend(
11181 grid,
11182 neighbours,
11183 mi_row,
11184 mi_col,
11185 bw4,
11186 bh4,
11187 mi_rows as usize,
11188 mi_cols as usize,
11189 side,
11190 write_w,
11191 write_h,
11192 chroma_side,
11193 px,
11194 py,
11195 cpx,
11196 cpy,
11197 ref_y,
11198 ref_u,
11199 ref_v,
11200 other_refs,
11201 interp_fixed,
11202 &mut pred_y,
11203 &mut pred_u,
11204 &mut pred_v,
11205 )?;
11206 }
11207
11208 // Mutually exclusive with warp/OBMC (motion_mode is not read for
11209 // an interintra block): blend the intra predictor over the MC
11210 // result, all planes (reconinter.c av1_build_interintra_predictor
11211 // plane loop).
11212 if let Some(ii) = interintra_mode {
11213 interintra_blend(y, px, py, side, ii, wedge_mask, &mut pred_y);
11214 interintra_blend(u, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_u);
11215 interintra_blend(v, cpx, cpy, chroma_side, ii, wedge_mask, &mut pred_v);
11216 }
11217
11218 if skip {
11219 y.reconstruct_mc_rect(
11220 px,
11221 py,
11222 side,
11223 write_w,
11224 write_h,
11225 &pred_y,
11226 &vec![0i32; side * side],
11227 );
11228 u.reconstruct_mc_rect(
11229 cpx,
11230 cpy,
11231 chroma_side,
11232 write_chroma_w,
11233 write_chroma_h,
11234 &pred_u,
11235 &vec![0i32; chroma_side * chroma_side],
11236 );
11237 v.reconstruct_mc_rect(
11238 cpx,
11239 cpy,
11240 chroma_side,
11241 write_chroma_w,
11242 write_chroma_h,
11243 &pred_v,
11244 &vec![0i32; chroma_side * chroma_side],
11245 );
11246 luma_grid = vec![0i32; side * side];
11247 u_grid = vec![0i32; chroma_side * chroma_side];
11248 v_grid = vec![0i32; chroma_side * chroma_side];
11249 } else {
11250 let around = neighbours.around(at, side);
11251 let luma_tx_type;
11252 (luma_grid, luma_tx_type) = read_inter_plane(
11253 dec,
11254 cdfs,
11255 luma_set_inter,
11256 scan_luma,
11257 0,
11258 around[0],
11259 mode_for_tx,
11260 y,
11261 px,
11262 py,
11263 side,
11264 base_q_idx,
11265 &pred_y,
11266 None,
11267 )?;
11268 u_grid = read_inter_plane(
11269 dec,
11270 cdfs,
11271 chroma_set,
11272 scan_chroma,
11273 1,
11274 around[1],
11275 mode_for_tx,
11276 u,
11277 cpx,
11278 cpy,
11279 chroma_side,
11280 base_q_idx,
11281 &pred_u,
11282 Some(luma_tx_type),
11283 )?
11284 .0;
11285 v_grid = read_inter_plane(
11286 dec,
11287 cdfs,
11288 chroma_set,
11289 scan_chroma,
11290 2,
11291 around[2],
11292 mode_for_tx,
11293 v,
11294 cpx,
11295 cpy,
11296 chroma_side,
11297 base_q_idx,
11298 &pred_v,
11299 Some(luma_tx_type),
11300 )?
11301 .0;
11302 }
11303 }
11304 } else {
11305 // lane-partitions r1: intra prediction (`PlaneBuf::reconstruct`) has
11306 // no rectangular counterpart -- an intra-coded HORZ/VERT strip needs
11307 // its own true-width/height edge/predict math, unlike the inter
11308 // skip path above (which only needed a clipped write of an
11309 // already-square-predicted buffer). Named refusal instead of a
11310 // silently wrong square-shaped intra prediction.
11311 if write_w != side || write_h != side {
11312 return Err(unsupported(
11313 "an intra-coded HORZ/VERT strip needs rectangular intra prediction \
11314 this decoder does not code yet",
11315 ));
11316 }
11317 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
11318 if mode >= 13 {
11319 return Err(unsupported(
11320 "an intra mode this decoder does not code (round 2)",
11321 ));
11322 }
11323 if (V_PRED..=D67_PRED).contains(&mode) {
11324 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
11325 if angle != ANGLE_DELTA_ZERO {
11326 return Err(unsupported(
11327 "a nonzero angle delta (this encoder never writes one)",
11328 ));
11329 }
11330 }
11331 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
11332 if (9..=12).contains(&uv_mode) {
11333 SMOOTH_UV_HITS.with(|c| c.set(c.get() + 1));
11334 }
11335 let alpha = if uv_mode == DC_PRED {
11336 None
11337 } else if uv_mode == UV_CFL_PRED {
11338 Some(read_cfl_alphas(dec, cdfs))
11339 } else {
11340 None
11341 };
11342 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for
11343 // the angle-delta question, same as [`read_intra_mode`]'s own copy
11344 // -- `uv_mode` (13) already falls outside `V_PRED..=D67_PRED` so the
11345 // `else` branch below is exact for it either way.
11346 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
11347 DIRECTIONAL_UV_HITS.with(|c| c.set(c.get() + 1));
11348 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
11349 } else {
11350 0
11351 };
11352 uv_predict_mode = if uv_mode == UV_CFL_PRED {
11353 DC_PRED
11354 } else {
11355 uv_mode
11356 };
11357 // lane-chroma r4: same chroma edge-filter-strength neighbour check
11358 // as [`read_intra_mode`]/[`read_intra_mode_rect`] -- the CHROMA
11359 // neighbour's own `uv_mode`, not the luma one.
11360 let smooth_neighbor_uv =
11361 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
11362 // `read_palette_mode_info` (decodemv.c:567, called from
11363 // `read_intra_block_mode_info` right after `xd->cfl.store_y`, same
11364 // gating and same corner-cut as `read_intra_mode`'s own copy above
11365 // -- `palette_mode_ctx`/`palette_uv_mode_ctx` hardcoded 0, provably
11366 // safe since a nonzero neighbour `palette_size` would already have
11367 // refused the decode that produced it.
11368 if allow_screen_content_tools
11369 && let Some(bsize_ctx) = palette_bsize_ctx(side)
11370 {
11371 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][0]) != 0 {
11372 return Err(unsupported(
11373 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
11374 ));
11375 }
11376 if uv_mode == DC_PRED && dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
11377 return Err(unsupported(
11378 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
11379 ));
11380 }
11381 }
11382 mode_for_tx = mode;
11383 block_filter = [3, 3];
11384 ref_frame_for_lf = 0;
11385 globalmv_for_lf = false;
11386 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
11387 for dr in 0..side / 4 {
11388 for dc in 0..side / 4 {
11389 grid.set(
11390 mi_row + dr,
11391 mi_col + dc,
11392 MiInfo {
11393 is_inter: false,
11394 ref_frame: -1,
11395 ref_frame1: None,
11396 mv1: None,
11397 mv: (0, 0),
11398 is_new_mv: false,
11399 size: side / 4,
11400 size_h: side / 4,
11401 is_global_mv0: false,
11402 is_global_mv1: false,
11403 },
11404 );
11405 }
11406 }
11407
11408 let reach = Reach::of(side, px, py, y.width, y.height);
11409 if skip {
11410 y.reconstruct(
11411 px,
11412 py,
11413 side,
11414 mode,
11415 0,
11416 reach,
11417 &vec![0i32; side * side],
11418 None,
11419 None,
11420 false,
11421 );
11422 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
11423 u.reconstruct(
11424 cpx,
11425 cpy,
11426 chroma_side,
11427 uv_predict_mode,
11428 angle_delta_uv,
11429 reach,
11430 &vec![0i32; chroma_side * chroma_side],
11431 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
11432 None,
11433 smooth_neighbor_uv,
11434 );
11435 v.reconstruct(
11436 cpx,
11437 cpy,
11438 chroma_side,
11439 uv_predict_mode,
11440 angle_delta_uv,
11441 reach,
11442 &vec![0i32; chroma_side * chroma_side],
11443 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
11444 None,
11445 smooth_neighbor_uv,
11446 );
11447 luma_grid = vec![0i32; side * side];
11448 u_grid = vec![0i32; chroma_side * chroma_side];
11449 v_grid = vec![0i32; chroma_side * chroma_side];
11450 } else {
11451 let around = neighbours.around(at, side);
11452 luma_grid = read_plane(
11453 dec,
11454 cdfs,
11455 luma_set_intra,
11456 scan_luma,
11457 0,
11458 around[0],
11459 mode,
11460 mode,
11461 0,
11462 reach,
11463 y,
11464 px,
11465 py,
11466 side,
11467 luma_tx,
11468 base_q_idx,
11469 None,
11470 None,
11471 None,
11472 false,
11473 )?;
11474 let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
11475 u_grid = read_plane(
11476 dec,
11477 cdfs,
11478 chroma_set,
11479 scan_chroma,
11480 1,
11481 around[1],
11482 mode,
11483 uv_predict_mode,
11484 angle_delta_uv,
11485 reach,
11486 u,
11487 cpx,
11488 cpy,
11489 chroma_side,
11490 chroma_tx,
11491 base_q_idx,
11492 alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
11493 None,
11494 None,
11495 smooth_neighbor_uv,
11496 )?;
11497 v_grid = read_plane(
11498 dec,
11499 cdfs,
11500 chroma_set,
11501 scan_chroma,
11502 2,
11503 around[2],
11504 mode,
11505 uv_predict_mode,
11506 angle_delta_uv,
11507 reach,
11508 v,
11509 cpx,
11510 cpy,
11511 chroma_side,
11512 chroma_tx,
11513 base_q_idx,
11514 alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
11515 None,
11516 None,
11517 smooth_neighbor_uv,
11518 )?;
11519 }
11520 }
11521 // lane-comppin r9: end-of-block checkpoint -- everything between
11522 // post_assign_mv and here (interintra, motion_mode, interp_filter, then
11523 // every plane's coeffs) is unproven; a range mismatch here vs aomdec's
11524 // equivalent post-content point (added at the matching call site)
11525 // narrows the ladder to this block's own tail instead of the next
11526 // block's partition read.
11527 if std::env::var_os("EC_AV1_TELL").is_some() {
11528 eprintln!(
11529 "TELL mi_row={} mi_col={} label=block_end tell={} range={}",
11530 r * SUB_MI as usize, c * SUB_MI as usize, dec.debug_bitpos(), dec.debug_state().0
11531 );
11532 }
11533 neighbours.record_rect(
11534 at,
11535 write_w,
11536 write_h,
11537 mode_for_tx,
11538 uv_predict_mode,
11539 &[luma_grid, u_grid, v_grid],
11540 );
11541 neighbours.record_inter_rect(
11542 at,
11543 write_w,
11544 write_h,
11545 skip,
11546 is_inter,
11547 ref_frame_for_lf,
11548 block_filter,
11549 skip_mode,
11550 );
11551 if let Some((ref1, group_idx, idx)) = compound_ctx {
11552 neighbours.record_compound_ctx_rect(at, write_w, write_h, ref1, group_idx, idx);
11553 }
11554 neighbours.fill_skip_grid_rect(
11555 (r * (SUB / MI), c * (SUB / MI)),
11556 write_w / MI,
11557 write_h / MI,
11558 skip,
11559 );
11560 neighbours.fill_lf_grid_rect(
11561 (r * (SUB / MI), c * (SUB / MI)),
11562 write_w / MI,
11563 write_h / MI,
11564 // lane-rect r2: the strip's true TX_32X16/TX_16X32 dims -- the
11565 // single-scalar corner-cut deblocked the strip seam with the wrong
11566 // edge length (1-px chroma drift on rect-flake-1 f17+).
11567 write_w as u8,
11568 write_h as u8,
11569 // ref_grid's packed convention (lf_level): sign carries GLOBALMV,
11570 // whose mode_lf_lut row is 0, not the 1 every other inter mode gets.
11571 if globalmv_for_lf {
11572 -ref_frame_for_lf
11573 } else {
11574 ref_frame_for_lf
11575 },
11576 );
11577 Ok(())
11578}
11579
11580/// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block
11581/// (lane-av1inter8), mirroring [`crate::tile::write_inter_frame_leaf8`]'s
11582/// exact symbol order: its own skip flag, intra/inter choice and (when
11583/// inter) `NEARESTMV`/`NEWMV` chain against this leaf's own 2x2-mi mv-stack
11584/// window, or (when intra) `Y_MODE`, then its own luma and two chroma
11585/// transform blocks through [`TxbSet::Luma8Inter`]/[`TxbSet::Chroma4`],
11586/// same as [`decode_leaf8`]'s coefficient layer but with
11587/// motion-compensated prediction instead of intra prediction when inter.
11588/// `outer_at` (in [`SUB`]-grid units) is the enclosing 16x16 slot's
11589/// skip/intra-inter context, overridden by `prev_leaf` exactly as
11590/// [`decode_leaf8`] overrides mode context: `Neighbours`' above/left arrays
11591/// only resolve to [`SUB`] granularity. Hands back this leaf's own skip flag
11592/// and intra/inter choice, for the next leaf or the caller's final
11593/// write-back.
11594#[allow(clippy::too_many_arguments)]
11595fn decode_inter_block8(
11596 dec: &mut SymbolDecoder,
11597 cdfs: &mut Cdfs,
11598 neighbours: &mut Neighbours,
11599 grid: &mut MiGrid,
11600 mi_cols: u32,
11601 mi_rows: u32,
11602 outer_at: (usize, usize),
11603 leaf_mi: (usize, usize),
11604 y: &mut PlaneBuf,
11605 u: &mut PlaneBuf,
11606 v: &mut PlaneBuf,
11607 ref_y: &PlaneBuf,
11608 ref_u: &PlaneBuf,
11609 ref_v: &PlaneBuf,
11610 other_refs: &RefSlots,
11611 base_q_idx: u8,
11612 scan8: &[u16],
11613 scan4: &[u16],
11614 prev_leaf: Option<((usize, usize), bool, bool)>,
11615 allow_high_precision_mv: bool,
11616 force_integer_mv: bool,
11617 // lane-av1comp: see [`decode_inter_block`]'s own doc -- this leaf path
11618 // only ever tracks a coarse `LAST_FRAME`-or-intra neighbour shape (no
11619 // per-leaf `above_ref`/`left_ref` array exists here), so `comp_mode`'s
11620 // context uses that same approximation.
11621 reference_select: bool,
11622 enable_masked_compound: bool,
11623 // lane-sb128 r4: see [`decode_inter_block`]'s own doc -- `BLOCK_8X8` is
11624 // always `is_interintra_allowed_bsize`-eligible, so this leaf's own gate
11625 // drops the `side` check entirely.
11626 enable_interintra_compound: bool,
11627 enable_jnt_comp: bool,
11628 order_hint_bits: u32,
11629 order_hint: u32,
11630 ref_order_hints: [u32; 7],
11631 // lane-av1comp round 14: see [`decode_inter_block`]'s own doc -- this
11632 // leaf has no per-leaf `above_skip_mode`/`left_skip_mode` array either,
11633 // so its `skip_mode` context reuses the same [`SUB`]-grid
11634 // `above_skip_mode[c]`/`left_skip_mode[r]` the enclosing 16x16 slot
11635 // tracks (mirroring `above_skip`/`left_skip`'s own leaf approximation
11636 // just above).
11637 skip_mode_present: bool,
11638 skip_mode_frame: [u8; 2],
11639 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit -- see
11640 // [`decode_inter_frame_tile_with_cdfs`]'s own doc.
11641 reduced_tx_set: bool,
11642 // lane-motionmode round 3: this frame header's own `is_motion_mode_switchable`/
11643 // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`), plus
11644 // the fixed/switchable interp filter kind `obmc_blend`'s own neighbour
11645 // reads need (see [`decode_inter_block`]'s own doc) -- this leaf's own
11646 // prediction is always `Regular` (documented corner-cut, `mc::predict`
11647 // has no filter param), but an OBMC neighbour can be a real 16x16+
11648 // block that DID resolve a switchable filter.
11649 interp_fixed: Option<mc::InterpFilterKind>,
11650 switchable_motion_mode: bool,
11651 allow_warped_motion: bool,
11652 // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a
11653 // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16
11654 // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own
11655 // `compound_ctx` local, just handed back instead of applied here (this
11656 // fn's `neighbours` recording happens once for the whole straddling
11657 // 16x16 block, after every leaf).
11658 // lane-screen r2: see [`decode_inter_block`]'s own copy of this param --
11659 // `BLOCK_8X8` (this leaf's fixed size) is always `av1_allow_palette`-
11660 // eligible (`bsize >= BLOCK_8X8`).
11661 allow_screen_content_tools: bool,
11662) -> Result<(bool, bool, bool, Option<(i8, i8, u8, u8)>)> {
11663 const LAST_FRAME: i8 = 1;
11664 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).
11665 const SIZE_GROUP_8: usize = 1;
11666
11667 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
11668 let (cpx, cpy) = (px / 2, py / 2);
11669 const SIDE: usize = 8;
11670 const CHROMA_SIDE: usize = 4;
11671
11672 let (r, c) = outer_at;
11673 let mut above_skip = neighbours.above_skip[c];
11674 let mut left_skip = neighbours.left_skip[r];
11675 let mut above_inter = neighbours.above_inter[c];
11676 let mut left_inter = neighbours.left_inter[r];
11677 if let Some(((pr, pc), pskip, pinter)) = prev_leaf {
11678 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
11679 above_skip = pskip;
11680 above_inter = pinter;
11681 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
11682 left_skip = pskip;
11683 left_inter = pinter;
11684 }
11685 }
11686 let skip_mode_ctx =
11687 usize::from(neighbours.above_skip_mode[c]) + usize::from(neighbours.left_skip_mode[r]);
11688 // Same two `inter_segment_id` positions as [`decode_inter_block`]; this
11689 // leaf is always `BLOCK_8X8`, i.e. 2x2 mi.
11690 inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, false, true);
11691 let skip_mode = skip_mode_present && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
11692 if skip_mode {
11693 SKIP_MODE_HITS.with(|c| c.set(c.get() + 1));
11694 }
11695
11696 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
11697 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
11698 inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, skip, false);
11699 maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip);
11700 // Always a `BLOCK_8X8` leaf here, never the whole superblock.
11701 maybe_read_delta_q(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
11702 maybe_read_delta_lf(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip);
11703
11704 let (has_above, has_left) = (
11705 leaf_mi.0 > neighbours.tile_row0_mi,
11706 leaf_mi.1 > neighbours.tile_col0_mi,
11707 );
11708 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);
11709 let is_inter = skip_mode || dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
11710
11711 let mode_for_tx;
11712 let (luma_grid, u_grid, v_grid);
11713 let mut compound_ctx8: Option<(i8, i8, u8, u8)> = None;
11714 if is_inter {
11715 if reference_select || skip_mode {
11716 let above_nbr = has_above.then(|| NeighbourRef {
11717 is_inter: above_inter,
11718 ref0: if above_inter { LAST_FRAME } else { 0 },
11719 ref1: None,
11720 uni: false,
11721 });
11722 let left_nbr = has_left.then(|| NeighbourRef {
11723 is_inter: left_inter,
11724 ref0: if left_inter { LAST_FRAME } else { 0 },
11725 ref1: None,
11726 uni: false,
11727 });
11728 if skip_mode || read_comp_mode(dec, cdfs, above_nbr, left_nbr) {
11729 let (ref0, ref1) = if skip_mode {
11730 (skip_mode_frame[0] as i8, skip_mode_frame[1] as i8)
11731 } else {
11732 read_compound_ref_frames(
11733 dec,
11734 cdfs,
11735 above_nbr,
11736 left_nbr,
11737 if has_above && above_inter {
11738 LAST_FRAME
11739 } else {
11740 -1
11741 },
11742 if has_left && left_inter {
11743 LAST_FRAME
11744 } else {
11745 -1
11746 },
11747 )
11748 };
11749 let (mi_row, mi_col) = leaf_mi;
11750 // lane-av1comp: this leaf path has neither a real sign-bias
11751 // table nor `tpl_frame` (see this function's own doc on the
11752 // coarse `LAST_FRAME`-or-intra neighbour approximation
11753 // already in force above), matching the plain `find_mv_stack`
11754 // (no bias, no tpl) the leaf's single-ref arm below already
11755 // uses.
11756 let comp_stack = crate::mvstack::find_mv_stack_compound(
11757 grid,
11758 mi_row,
11759 mi_col,
11760 2,
11761 2,
11762 (ref0, ref1),
11763 mi_cols as usize,
11764 mi_rows as usize,
11765 &NO_SIGN_BIAS,
11766 &crate::mvstack::NO_GM_MV,
11767 None,
11768 );
11769 let compound_mode = if skip_mode {
11770 0 // NEAREST_NEARESTMV, forced -- no mode symbol read
11771 } else {
11772 read_inter_compound_mode(
11773 dec,
11774 cdfs,
11775 comp_stack.new_mv_ctx,
11776 comp_stack.ref_mv_ctx,
11777 )
11778 };
11779 let (mv0, mv1) = assign_compound_mv(
11780 dec,
11781 cdfs,
11782 &comp_stack,
11783 compound_mode,
11784 allow_high_precision_mv,
11785 force_integer_mv,
11786 // leaf8 stays gm-inert (sanctioned partial landing, see
11787 // this fn's own GLOBALMV refusal below).
11788 ((0, 0), (0, 0)),
11789 );
11790
11791 // spec 5.11.25: same gating [`decode_inter_block`]'s own
11792 // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid
11793 // slot -- the only granularity `Neighbours`' comp_group_idx/
11794 // compound_idx arrays track.
11795 let group_ctx = get_comp_group_idx_context(neighbours, outer_at, SIDE);
11796 let comp_group_idx = if !skip_mode
11797 && enable_masked_compound
11798 && is_any_masked_compound_used_here(SIDE)
11799 {
11800 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
11801 } else {
11802 0
11803 };
11804 // lane-maskcomp r2 / lane-wedge r3: see the 16x16/32x32
11805 // leaf's own comment.
11806 let mut diffwtd_mask_type: Option<u8> = None;
11807 let mut wedge_mask: Option<&'static [u8]> = None;
11808 if comp_group_idx == 1 {
11809 // lane-maskcomp r1: see the 16x16 leaf's own comment
11810 // above -- SIDE==8 here, `wedge_bsize` index 3
11811 // (BLOCK_8X8, `wedge_types > 0`).
11812 let compound_type = dec.symbol(&mut cdfs.compound_type[3]);
11813 if compound_type == 0 {
11814 // COMPOUND_WEDGE: lane-wedge r3, see the 16x16/32x32
11815 // leaf's own comment.
11816 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
11817 let wedge_sign = dec.literal(1);
11818 WEDGE_HITS.with(|c| c.set(c.get() + 1));
11819 wedge_mask = Some(
11820 crate::wedge::wedge_masks()
11821 .codebook(SIDE)
11822 .mask(wedge_sign as usize, wedge_index as usize),
11823 );
11824 } else {
11825 let mask_type = dec.literal(1);
11826 diffwtd_mask_type = Some(mask_type as u8);
11827 }
11828 MASKED_COMPOUND_HITS.with(|c| c.set(c.get() + 1));
11829 }
11830 // corner-cut (lane-av1comp r16/r17, lane-av1blend r1): same
11831 // reference-slot defect as the 16x16 leaf's own mask above
11832 // (r1: falsified as an MC/blend math bug, isolated to a DPB
11833 // slot/refresh_frame_flags issue around BWDREF_FRAME) -- see
11834 // that comment.
11835 // r3: same defect as the 16x16 leaf's own mask above -- see
11836 // that comment (compound_idx's decoded value, not the blend
11837 // math or reference-slot bookkeeping). r6/r7: same re-mask
11838 // as the 16x16 leaf above -- one real bug found and fixed
11839 // (mvstack.rs ref_ctx family), a second, still-unfound
11840 // compound_idx defect surfaces on the wide gate sweep.
11841 // lane-av1idx r1: same re-mask as the 16x16 leaf above --
11842 // see that comment.
11843 let (fwd_offset, bck_offset, compound_idx) = if comp_group_idx == 0
11844 && !skip_mode
11845 && enable_jnt_comp
11846 {
11847 let idx_ctx = get_comp_index_context(
11848 neighbours,
11849 outer_at,
11850 SIDE,
11851 order_hint_bits,
11852 order_hint,
11853 ref_order_hints[(ref0 - LAST_FRAME) as usize],
11854 ref_order_hints[(ref1 - LAST_FRAME) as usize],
11855 );
11856 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
11857 if idx == 1 {
11858 (8, 8, 1u8)
11859 } else {
11860 let (fwd, bck) = crate::compound::dist_wtd_comp_weight_assign(
11861 order_hint_bits,
11862 order_hint,
11863 ref_order_hints[(ref0 - LAST_FRAME) as usize],
11864 ref_order_hints[(ref1 - LAST_FRAME) as usize],
11865 );
11866 (fwd, bck, 0u8)
11867 }
11868 } else {
11869 (8, 8, 1u8)
11870 };
11871 compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx));
11872 if std::env::var_os("EC_AV1_COMPIDX_DUMP").is_some() {
11873 eprintln!(
11874 "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={}",
11875 mv0.0, mv0.1, mv1.0, mv1.1, dec.debug_bitpos()
11876 );
11877 }
11878
11879 let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
11880 let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
11881
11882 for dr in 0..2 {
11883 for dc in 0..2 {
11884 grid.set(
11885 mi_row + dr,
11886 mi_col + dc,
11887 MiInfo {
11888 is_inter: true,
11889 ref_frame: ref0,
11890 ref_frame1: Some(ref1),
11891 mv1: Some(mv1),
11892 mv: mv0,
11893 is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7),
11894 size: 2,
11895 size_h: 2,
11896 is_global_mv0: false,
11897 is_global_mv1: false,
11898 },
11899 );
11900 }
11901 }
11902 mode_for_tx = 0;
11903
11904 // lane-av1comp corner-cut, matching this leaf's single-ref
11905 // arm below (`mc::predict`'s own fixed-Regular default):
11906 // `decode_inter_block8` never resolves a switchable filter,
11907 // so both compound taps use `Regular` too.
11908 use mc::InterpFilterKind::Regular;
11909 let mut inter0_y = vec![0i32; SIDE * SIDE];
11910 mc::predict_compound_intermediate(
11911 &py0.data,
11912 py0.width,
11913 py0.true_width,
11914 py0.true_height,
11915 mv_to_q4(px, mv0.1, true),
11916 mv_to_q4(py, mv0.0, true),
11917 SIDE,
11918 SIDE,
11919 Regular,
11920 Regular,
11921 &mut inter0_y,
11922 );
11923 let mut inter1_y = vec![0i32; SIDE * SIDE];
11924 mc::predict_compound_intermediate(
11925 &py1.data,
11926 py1.width,
11927 py1.true_width,
11928 py1.true_height,
11929 mv_to_q4(px, mv1.1, true),
11930 mv_to_q4(py, mv1.0, true),
11931 SIDE,
11932 SIDE,
11933 Regular,
11934 Regular,
11935 &mut inter1_y,
11936 );
11937 let mut pred_y = vec![0u16; SIDE * SIDE];
11938 let mut diffwtd_mask_y = Vec::new();
11939 let mask_y: Option<&[u8]> = if let Some(mask_type) = diffwtd_mask_type {
11940 diffwtd_mask_y = vec![0u8; SIDE * SIDE];
11941 mc::diffwtd_mask(&inter0_y, &inter1_y, mask_type == 1, &mut diffwtd_mask_y);
11942 Some(diffwtd_mask_y.as_slice())
11943 } else {
11944 wedge_mask
11945 };
11946 if let Some(mask_y) = mask_y {
11947 mc::blend_masked_compound(
11948 &inter0_y, &inter1_y, mask_y, SIDE, SIDE, SIDE, false, &mut pred_y,
11949 );
11950 } else {
11951 mc::combine_compound(&inter0_y, &inter1_y, fwd_offset, bck_offset, &mut pred_y);
11952 }
11953
11954 let mut inter0_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
11955 mc::predict_compound_intermediate(
11956 &pu0.data,
11957 pu0.width,
11958 pu0.true_width,
11959 pu0.true_height,
11960 mv_to_q4(cpx, mv0.1, false),
11961 mv_to_q4(cpy, mv0.0, false),
11962 CHROMA_SIDE,
11963 CHROMA_SIDE,
11964 Regular,
11965 Regular,
11966 &mut inter0_u,
11967 );
11968 let mut inter1_u = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
11969 mc::predict_compound_intermediate(
11970 &pu1.data,
11971 pu1.width,
11972 pu1.true_width,
11973 pu1.true_height,
11974 mv_to_q4(cpx, mv1.1, false),
11975 mv_to_q4(cpy, mv1.0, false),
11976 CHROMA_SIDE,
11977 CHROMA_SIDE,
11978 Regular,
11979 Regular,
11980 &mut inter1_u,
11981 );
11982 let mut pred_u = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
11983 if let Some(mask_y) = mask_y {
11984 mc::blend_masked_compound(
11985 &inter0_u,
11986 &inter1_u,
11987 mask_y,
11988 SIDE,
11989 CHROMA_SIDE,
11990 CHROMA_SIDE,
11991 true,
11992 &mut pred_u,
11993 );
11994 } else {
11995 mc::combine_compound(&inter0_u, &inter1_u, fwd_offset, bck_offset, &mut pred_u);
11996 }
11997
11998 let mut inter0_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
11999 mc::predict_compound_intermediate(
12000 &pv0.data,
12001 pv0.width,
12002 pv0.true_width,
12003 pv0.true_height,
12004 mv_to_q4(cpx, mv0.1, false),
12005 mv_to_q4(cpy, mv0.0, false),
12006 CHROMA_SIDE,
12007 CHROMA_SIDE,
12008 Regular,
12009 Regular,
12010 &mut inter0_v,
12011 );
12012 let mut inter1_v = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
12013 mc::predict_compound_intermediate(
12014 &pv1.data,
12015 pv1.width,
12016 pv1.true_width,
12017 pv1.true_height,
12018 mv_to_q4(cpx, mv1.1, false),
12019 mv_to_q4(cpy, mv1.0, false),
12020 CHROMA_SIDE,
12021 CHROMA_SIDE,
12022 Regular,
12023 Regular,
12024 &mut inter1_v,
12025 );
12026 let mut pred_v = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
12027 if let Some(mask_y) = mask_y {
12028 mc::blend_masked_compound(
12029 &inter0_v,
12030 &inter1_v,
12031 mask_y,
12032 SIDE,
12033 CHROMA_SIDE,
12034 CHROMA_SIDE,
12035 true,
12036 &mut pred_v,
12037 );
12038 } else {
12039 mc::combine_compound(&inter0_v, &inter1_v, fwd_offset, bck_offset, &mut pred_v);
12040 }
12041
12042 if skip {
12043 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
12044 u.reconstruct_mc(
12045 cpx,
12046 cpy,
12047 CHROMA_SIDE,
12048 &pred_u,
12049 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
12050 );
12051 v.reconstruct_mc(
12052 cpx,
12053 cpy,
12054 CHROMA_SIDE,
12055 &pred_v,
12056 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
12057 );
12058 luma_grid = vec![0i32; SIDE * SIDE];
12059 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
12060 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
12061 } else {
12062 let around = neighbours.around_mi(leaf_mi, 8);
12063 let luma_tx_type;
12064 (luma_grid, luma_tx_type) = read_inter_plane(
12065 dec,
12066 cdfs,
12067 if reduced_tx_set {
12068 TxbSet::Luma8Inter
12069 } else {
12070 TxbSet::Luma8InterSet1
12071 },
12072 scan8,
12073 0,
12074 around[0],
12075 mode_for_tx,
12076 y,
12077 px,
12078 py,
12079 SIDE,
12080 base_q_idx,
12081 &pred_y,
12082 None,
12083 )?;
12084 u_grid = read_inter_plane(
12085 dec,
12086 cdfs,
12087 TxbSet::Chroma4,
12088 scan4,
12089 1,
12090 around[1],
12091 mode_for_tx,
12092 u,
12093 cpx,
12094 cpy,
12095 CHROMA_SIDE,
12096 base_q_idx,
12097 &pred_u,
12098 Some(luma_tx_type),
12099 )?
12100 .0;
12101 v_grid = read_inter_plane(
12102 dec,
12103 cdfs,
12104 TxbSet::Chroma4,
12105 scan4,
12106 2,
12107 around[2],
12108 mode_for_tx,
12109 v,
12110 cpx,
12111 cpy,
12112 CHROMA_SIDE,
12113 base_q_idx,
12114 &pred_v,
12115 Some(luma_tx_type),
12116 )?
12117 .0;
12118 }
12119 return Ok((skip, is_inter, skip_mode, compound_ctx8));
12120 }
12121 }
12122 let sr_ctx = single_ref_ctx(above_inter || left_inter);
12123 let p1 = dec.symbol(&mut cdfs.single_ref[sr_ctx][0]);
12124 let p3 = dec.symbol(&mut cdfs.single_ref[sr_ctx][2]);
12125 let p4 = dec.symbol(&mut cdfs.single_ref[sr_ctx][3]);
12126 if (p1, p3, p4) != (0, 0, 0) {
12127 return Err(unsupported(
12128 "a reference frame other than LAST_FRAME (round 2)",
12129 ));
12130 }
12131
12132 let (mi_row, mi_col) = leaf_mi;
12133 let stack = find_mv_stack(
12134 grid,
12135 mi_row,
12136 mi_col,
12137 2,
12138 2,
12139 LAST_FRAME,
12140 mi_cols as usize,
12141 mi_rows as usize,
12142 );
12143
12144 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
12145 let (mv, is_new_mv) = if !not_new {
12146 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
12147 // read at most two `drl_mode` bits, one per stack entry past the
12148 // first, stopping at the first `0`. The chosen index selects
12149 // which stack entry `read_mv`'s base predictor comes from
12150 // (spec 7.10.2.10 `assign_mv`'s `PredMv = RefStackMv[RefMvIdx]`)
12151 // -- entry 0 (`stack.pred_mv`) only when the loop never advances.
12152 let mut idx = 0usize;
12153 while idx < 2 && stack.entries.len() > idx + 1 {
12154 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
12155 break;
12156 }
12157 idx += 1;
12158 }
12159 let base_mv = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
12160 (
12161 read_mv(
12162 dec,
12163 &mut cdfs.mv_comp,
12164 &mut cdfs.mv_joint,
12165 base_mv,
12166 allow_high_precision_mv,
12167 force_integer_mv,
12168 ),
12169 true,
12170 )
12171 } else {
12172 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
12173 if !not_zero {
12174 return Err(unsupported("GLOBALMV (round 3)"));
12175 }
12176 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
12177 let mv = if nearest {
12178 stack.nearest_mv
12179 } else {
12180 let mut idx = 1usize;
12181 while idx < 3 && stack.entries.len() > idx + 1 {
12182 if dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[idx]]) == 0 {
12183 break;
12184 }
12185 idx += 1;
12186 }
12187 stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv)
12188 };
12189 (mv, false)
12190 };
12191 // lane-sb128 r4: `interintra` (spec 5.11.24) at the 8x8 leaf too --
12192 // see [`decode_inter_block`]'s own doc; `BLOCK_8X8` is always
12193 // `is_interintra_allowed_bsize`-eligible, single-ref-only branch
12194 // (compound already returned above), GLOBALMV already refused
12195 // (round 3), so the only real gate left is the header enable bit.
12196 let mut interintra_mode: Option<u8> = None;
12197 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
12198 if enable_interintra_compound && !skip_mode {
12199 let interintra = dec.symbol(&mut cdfs.interintra[SIZE_GROUP_8]) == 1;
12200 if interintra {
12201 // lane-interintra r1: same read pair as the 16/32 site;
12202 // wedge cdf row = BLOCK_8X8 (index 3), read on block size
12203 // alone, never the `enable_interintra_wedge` seq bit.
12204 let ii = dec.symbol(&mut cdfs.interintra_mode[SIZE_GROUP_8]) as u8;
12205 let wedge = dec.symbol(&mut cdfs.wedge_interintra[3]) == 1;
12206 if wedge {
12207 // lane-wii r2: same adapting `wedge_index` symbol as the
12208 // 16/32 leaf, fixed sign 0 -- see that site's comment.
12209 let wedge_index = dec.symbol(&mut cdfs.wedge_idx[3]);
12210 WII_HITS.with(|c| c.set(c.get() + 1));
12211 wedge_mask = Some((
12212 crate::wedge::wedge_masks()
12213 .codebook(SIDE)
12214 .mask(0, wedge_index as usize),
12215 SIDE,
12216 ));
12217 } else {
12218 INTERINTRA_HITS.with(|c| c.set(c.get() + 1));
12219 }
12220 interintra_mode = Some(ii);
12221 }
12222 }
12223 // lane-motionmode round 3: `read_motion_mode` (spec 5.11.24) at the
12224 // 8x8 leaf too -- `motion_mode_allowed` still holds here (BLOCK_8X8
12225 // is the spec's own minimum eligible size, single-ref-only branch,
12226 // no interintra reader, `IDENTITY`-only global motion). Mirrors the
12227 // 16x16 leaf's own `decode_inter_block` read (see its doc above) --
12228 // same 2-symbol `obmc_cdf` alphabet, same `allow_warped_motion=1`
12229 // refusal (warp needs `av1_findSamples`, not ported at either leaf).
12230 let motion_mode_eligible = switchable_motion_mode
12231 && !skip_mode
12232 && interintra_mode.is_none()
12233 && (!overlappable_above(grid, mi_row, mi_col, 2, mi_cols as usize, 1).is_empty()
12234 || !overlappable_left(grid, mi_row, mi_col, 2, mi_rows as usize, 1).is_empty());
12235 let mut obmc_selected = false;
12236 if motion_mode_eligible {
12237 // lane-warp round 1: same 3-vs-2-symbol split as the 16x16+ leaf
12238 // (see its own doc) -- this leaf is always `LAST_FRAME`-only
12239 // (grid.set below hardcodes it).
12240 let warp_eligible = allow_warped_motion
12241 && num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, LAST_FRAME) >= 1;
12242 if warp_eligible {
12243 let mode = dec.symbol(&mut cdfs.motion_mode[0]);
12244 match mode {
12245 0 => {}
12246 1 => {
12247 obmc_selected = true;
12248 OBMC_HITS.with(|c| c.set(c.get() + 1));
12249 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
12250 }
12251 _ => {
12252 WARP_SELECTED_HITS.with(|c| c.set(c.get() + 1));
12253 return Err(unsupported(
12254 "an 8x8 leaf that coded WARPED_CAUSAL (motion_mode == 2): \
12255 av1_find_projection/the affine warp filter are not \
12256 ported, only motion_mode_allowed's alphabet choice is",
12257 ));
12258 }
12259 }
12260 } else {
12261 // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> 0/1/2/3.
12262 obmc_selected = dec.symbol(&mut cdfs.obmc[0]) == 1;
12263 if obmc_selected {
12264 OBMC_HITS.with(|c| c.set(c.get() + 1));
12265 OBMC_HITS_8.with(|c| c.set(c.get() + 1));
12266 }
12267 }
12268 }
12269 for dr in 0..2 {
12270 for dc in 0..2 {
12271 grid.set(
12272 mi_row + dr,
12273 mi_col + dc,
12274 MiInfo {
12275 is_inter: true,
12276 ref_frame: LAST_FRAME,
12277 // INTRA_FRAME marker for interintra blocks -- keeps
12278 // them out of warp-sample gathering (see 16/32 site).
12279 ref_frame1: interintra_mode.map(|_| 0),
12280 mv1: None,
12281 mv,
12282 is_new_mv,
12283 size: 2,
12284 size_h: 2,
12285 is_global_mv0: false,
12286 is_global_mv1: false,
12287 },
12288 );
12289 }
12290 }
12291 mode_for_tx = 0;
12292
12293 let mut pred_y = vec![0u16; SIDE * SIDE];
12294 mc::predict(
12295 &ref_y.data,
12296 ref_y.width,
12297 ref_y.true_width,
12298 ref_y.true_height,
12299 mv_to_q4(px, mv.1, true),
12300 mv_to_q4(py, mv.0, true),
12301 SIDE,
12302 SIDE,
12303 &mut pred_y,
12304 );
12305 let mut pred_u = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
12306 mc::predict(
12307 &ref_u.data,
12308 ref_u.width,
12309 ref_u.true_width,
12310 ref_u.true_height,
12311 mv_to_q4(cpx, mv.1, false),
12312 mv_to_q4(cpy, mv.0, false),
12313 CHROMA_SIDE,
12314 CHROMA_SIDE,
12315 &mut pred_u,
12316 );
12317 let mut pred_v = vec![0u16; CHROMA_SIDE * CHROMA_SIDE];
12318 mc::predict(
12319 &ref_v.data,
12320 ref_v.width,
12321 ref_v.true_width,
12322 ref_v.true_height,
12323 mv_to_q4(cpx, mv.1, false),
12324 mv_to_q4(cpy, mv.0, false),
12325 CHROMA_SIDE,
12326 CHROMA_SIDE,
12327 &mut pred_v,
12328 );
12329
12330 if obmc_selected {
12331 obmc_blend(
12332 grid,
12333 neighbours,
12334 mi_row,
12335 mi_col,
12336 2,
12337 2,
12338 mi_rows as usize,
12339 mi_cols as usize,
12340 SIDE,
12341 SIDE,
12342 SIDE,
12343 CHROMA_SIDE,
12344 px,
12345 py,
12346 cpx,
12347 cpy,
12348 ref_y,
12349 ref_u,
12350 ref_v,
12351 other_refs,
12352 interp_fixed,
12353 &mut pred_y,
12354 &mut pred_u,
12355 &mut pred_v,
12356 )?;
12357 }
12358
12359 // Non-wedge interintra blend, mutually exclusive with OBMC (the
12360 // motion_mode symbol is not read for an interintra block).
12361 if let Some(ii) = interintra_mode {
12362 interintra_blend(y, px, py, SIDE, ii, wedge_mask, &mut pred_y);
12363 interintra_blend(u, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_u);
12364 interintra_blend(v, cpx, cpy, CHROMA_SIDE, ii, wedge_mask, &mut pred_v);
12365 }
12366
12367 if skip {
12368 y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]);
12369 u.reconstruct_mc(
12370 cpx,
12371 cpy,
12372 CHROMA_SIDE,
12373 &pred_u,
12374 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
12375 );
12376 v.reconstruct_mc(
12377 cpx,
12378 cpy,
12379 CHROMA_SIDE,
12380 &pred_v,
12381 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
12382 );
12383 luma_grid = vec![0i32; SIDE * SIDE];
12384 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
12385 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
12386 } else {
12387 let around = neighbours.around_mi(leaf_mi, 8);
12388 let luma_tx_type;
12389 (luma_grid, luma_tx_type) = read_inter_plane(
12390 dec,
12391 cdfs,
12392 if reduced_tx_set {
12393 TxbSet::Luma8Inter
12394 } else {
12395 TxbSet::Luma8InterSet1
12396 },
12397 scan8,
12398 0,
12399 around[0],
12400 mode_for_tx,
12401 y,
12402 px,
12403 py,
12404 SIDE,
12405 base_q_idx,
12406 &pred_y,
12407 None,
12408 )?;
12409 u_grid = read_inter_plane(
12410 dec,
12411 cdfs,
12412 TxbSet::Chroma4,
12413 scan4,
12414 1,
12415 around[1],
12416 mode_for_tx,
12417 u,
12418 cpx,
12419 cpy,
12420 CHROMA_SIDE,
12421 base_q_idx,
12422 &pred_u,
12423 Some(luma_tx_type),
12424 )?
12425 .0;
12426 v_grid = read_inter_plane(
12427 dec,
12428 cdfs,
12429 TxbSet::Chroma4,
12430 scan4,
12431 2,
12432 around[2],
12433 mode_for_tx,
12434 v,
12435 cpx,
12436 cpy,
12437 CHROMA_SIDE,
12438 base_q_idx,
12439 &pred_v,
12440 Some(luma_tx_type),
12441 )?
12442 .0;
12443 }
12444 } else {
12445 let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]);
12446 if mode >= 13 {
12447 return Err(unsupported(
12448 "an intra mode this decoder does not code (round 2)",
12449 ));
12450 }
12451 if (V_PRED..=D67_PRED).contains(&mode) {
12452 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
12453 if angle != ANGLE_DELTA_ZERO {
12454 return Err(unsupported(
12455 "a nonzero angle delta (this encoder never writes one)",
12456 ));
12457 }
12458 }
12459 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
12460 if uv_mode != DC_PRED {
12461 return Err(unsupported(
12462 "a non-DC chroma mode on an 8x8 inter-frame leaf (this encoder never writes one)",
12463 ));
12464 }
12465 // lane-screen r2: see [`decode_inter_block`]'s own copy -- `mode`/
12466 // `uv_mode` are both effectively `DC_PRED`-gated already on this
12467 // leaf (a nonzero `mode` still passes, but `uv_mode` is forced
12468 // `DC_PRED` by the refusal just above), same order as libaom's
12469 // `read_palette_mode_info` call right after `xd->cfl.store_y`.
12470 if allow_screen_content_tools {
12471 if mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[0][0]) != 0 {
12472 return Err(unsupported(
12473 "a block that actually uses a palette (Y) -- reconstruction is out of scope",
12474 ));
12475 }
12476 if dec.symbol(&mut cdfs.palette_uv_mode[0]) != 0 {
12477 return Err(unsupported(
12478 "a block that actually uses a palette (UV) -- reconstruction is out of scope",
12479 ));
12480 }
12481 }
12482 mode_for_tx = mode;
12483 let (mi_row, mi_col) = leaf_mi;
12484 for dr in 0..2 {
12485 for dc in 0..2 {
12486 grid.set(
12487 mi_row + dr,
12488 mi_col + dc,
12489 MiInfo {
12490 is_inter: false,
12491 ref_frame: -1,
12492 ref_frame1: None,
12493 mv1: None,
12494 mv: (0, 0),
12495 is_new_mv: false,
12496 size: 2,
12497 size_h: 2,
12498 is_global_mv0: false,
12499 is_global_mv1: false,
12500 },
12501 );
12502 }
12503 }
12504
12505 let reach = Reach::of(SIDE, px, py, y.width, y.height);
12506 if skip {
12507 y.reconstruct(
12508 px,
12509 py,
12510 SIDE,
12511 mode,
12512 0,
12513 reach,
12514 &vec![0i32; SIDE * SIDE],
12515 None,
12516 None,
12517 false,
12518 );
12519 u.reconstruct(
12520 cpx,
12521 cpy,
12522 CHROMA_SIDE,
12523 DC_PRED,
12524 0,
12525 reach,
12526 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
12527 None,
12528 None,
12529 false,
12530 );
12531 v.reconstruct(
12532 cpx,
12533 cpy,
12534 CHROMA_SIDE,
12535 DC_PRED,
12536 0,
12537 reach,
12538 &vec![0i32; CHROMA_SIDE * CHROMA_SIDE],
12539 None,
12540 None,
12541 false,
12542 );
12543 luma_grid = vec![0i32; SIDE * SIDE];
12544 u_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
12545 v_grid = vec![0i32; CHROMA_SIDE * CHROMA_SIDE];
12546 } else {
12547 let around = neighbours.around_mi(leaf_mi, 8);
12548 luma_grid = read_plane(
12549 dec,
12550 cdfs,
12551 TxbSet::Luma8,
12552 scan8,
12553 0,
12554 around[0],
12555 mode,
12556 mode,
12557 0,
12558 reach,
12559 y,
12560 px,
12561 py,
12562 SIDE,
12563 TX8,
12564 base_q_idx,
12565 None,
12566 None,
12567 None,
12568 false,
12569 )?;
12570 u_grid = read_plane(
12571 dec,
12572 cdfs,
12573 TxbSet::Chroma4,
12574 scan4,
12575 1,
12576 around[1],
12577 mode,
12578 DC_PRED,
12579 0,
12580 reach,
12581 u,
12582 cpx,
12583 cpy,
12584 CHROMA_SIDE,
12585 TX4,
12586 base_q_idx,
12587 None,
12588 None,
12589 None,
12590 false,
12591 )?;
12592 v_grid = read_plane(
12593 dec,
12594 cdfs,
12595 TxbSet::Chroma4,
12596 scan4,
12597 2,
12598 around[2],
12599 mode,
12600 DC_PRED,
12601 0,
12602 reach,
12603 v,
12604 cpx,
12605 cpy,
12606 CHROMA_SIDE,
12607 TX4,
12608 base_q_idx,
12609 None,
12610 None,
12611 None,
12612 false,
12613 )?;
12614 }
12615 }
12616 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
12617 neighbours.fill_lf_grid(leaf_mi, 2, 8, if is_inter { LAST_FRAME } else { 0 });
12618 Ok((skip, is_inter, skip_mode, compound_ctx8))
12619}
12620
12621/// Decodes the payload [`crate::tile::sb_coeff_inter_frame_tile`] writes,
12622/// against `reference` (the previous frame's own decoded picture, at this
12623/// frame's true size -- a decoder's single-slot DPB, matching what this
12624/// crate's encoder always predicts from), returning the picture it
12625/// reconstructs to. Mirrors [`decode_key_frame_tile`]'s own contract
12626/// (`mi_cols`/`mi_rows`/`base_q_idx` from the frame header,
12627/// `frame_width`/`frame_height` its true render size).
12628///
12629/// # Errors
12630/// Returns an error under the same conditions [`decode_inter_block`] does,
12631/// or when `reference` is not this frame's own true size, or when the tile
12632/// codes a 16x16 leaf whose own true edge cuts through it (round 2, same
12633/// refusal [`crate::tile`]'s writer gives its encoder).
12634pub fn decode_inter_frame_tile(
12635 data: &[u8],
12636 mi_cols: u32,
12637 mi_rows: u32,
12638 base_q_idx: u8,
12639 frame_width: u32,
12640 frame_height: u32,
12641 reference: &Picture,
12642 other_refs: [Option<&Picture>; 8],
12643 cdef: &CdefParams,
12644 loop_filter: &LoopFilterParams,
12645 allow_high_precision_mv: bool,
12646 force_integer_mv: bool,
12647 interp_fixed: Option<mc::InterpFilterKind>,
12648 enable_dual_filter: bool,
12649 reference_select: bool,
12650) -> Result<Picture> {
12651 let single_tile = TileInfo {
12652 mi_col_starts: vec![0, mi_cols],
12653 mi_row_starts: vec![0, mi_rows],
12654 ..TileInfo::default()
12655 };
12656 decode_inter_frame_tile_with_cdfs(
12657 &[data],
12658 &single_tile,
12659 mi_cols,
12660 mi_rows,
12661 base_q_idx,
12662 crate::quant::QuantDeltas::default(),
12663 frame_width,
12664 frame_height,
12665 reference,
12666 other_refs,
12667 cdef,
12668 loop_filter,
12669 &LoopRestorationParams::default(),
12670 None,
12671 allow_high_precision_mv,
12672 force_integer_mv,
12673 NO_SIGN_BIAS,
12674 [ec_av1_syntax::WarpParams::default(); 7],
12675 interp_fixed,
12676 enable_dual_filter,
12677 0,
12678 0,
12679 [0; 7],
12680 None,
12681 reference_select,
12682 false,
12683 false,
12684 false,
12685 false,
12686 [0; 2],
12687 true,
12688 false,
12689 false,
12690 false,
12691 DeltaParams::default(),
12692 )
12693 .map(|(picture, _, _)| picture)
12694}
12695
12696/// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see
12697/// [`decode_key_frame_tile_with_cdfs`]'s doc for `initial_cdfs`/the returned
12698/// end-of-tile table. An inter frame's own header can name
12699/// `primary_ref_frame == PRIMARY_REF_NONE` too (an error-resilient stream),
12700/// so `None` is a real case here, not only a convenience default.
12701pub(crate) fn decode_inter_frame_tile_with_cdfs(
12702 tiles: &[&[u8]],
12703 tile_info: &TileInfo,
12704 mi_cols: u32,
12705 mi_rows: u32,
12706 base_q_idx: u8,
12707 // lane-sbpart r11: see [`decode_key_frame_tile_with_cdfs`]'s own `deltas`.
12708 deltas: crate::quant::QuantDeltas,
12709 frame_width: u32,
12710 frame_height: u32,
12711 reference: &Picture,
12712 other_refs: [Option<&Picture>; 8],
12713 cdef: &CdefParams,
12714 loop_filter: &LoopFilterParams,
12715 lr: &LoopRestorationParams,
12716 initial_cdfs: Option<Cdfs>,
12717 allow_high_precision_mv: bool,
12718 force_integer_mv: bool,
12719 sign_bias_table: SignBiasTable,
12720 // lane-gm r2: this frame header's own `global_motion` table (spec
12721 // 5.9.24), threaded to every `decode_inter_block` call below.
12722 global_motion: [ec_av1_syntax::WarpParams; 7],
12723 interp_fixed: Option<mc::InterpFilterKind>,
12724 enable_dual_filter: bool,
12725 // lane-av1tmvp: `order_hint`/`order_hint_bits`/`ref_order_hints` are
12726 // always needed (this frame's own saved [`crate::motion_field::MotionField`]
12727 // carries them for a *later* frame's projection, spec 7.9); `tpl_field`
12728 // is `Some` only when this frame's own header set `use_ref_frame_mvs`
12729 // and the caller ([`crate::stream::decode_stream`]) projected one.
12730 order_hint_bits: u32,
12731 order_hint: u32,
12732 ref_order_hints: [u32; 7],
12733 tpl_field: Option<&crate::motion_field::TplField>,
12734 // lane-av1comp: this frame header's own `reference_select` bit, threaded
12735 // to every `decode_inter_block`/`decode_inter_block8` call below.
12736 reference_select: bool,
12737 // lane-av1comp: `seq_params`' own compound-blend enable bits.
12738 enable_masked_compound: bool,
12739 enable_jnt_comp: bool,
12740 // lane-sb128 r3: this sequence header's own `enable_interintra_compound`
12741 // bit, threaded to every `decode_inter_block`/`decode_inter_block8` call
12742 // below (spec 5.11.24's `interintra` read).
12743 enable_interintra_compound: bool,
12744 // lane-av1comp round 14: this frame header's own `skip_mode_present`/
12745 // `skip_mode_frame` (spec 5.9.22), threaded to every `decode_inter_block`/
12746 // `decode_inter_block8` call below.
12747 skip_mode_present: bool,
12748 skip_mode_frame: [u8; 2],
12749 // lane-cdffwd2: this frame header's own `reduced_tx_set` bit, threaded to
12750 // every inter `tx_type` read below (`false` needs the 12-/16-symbol
12751 // `Set1` coefficient tables at 16x16/8x8 rather than the reduced
12752 // 2-symbol ones -- see [`TxbSet::Luma16InterSet1`]/[`TxbSet::Luma8InterSet1`]).
12753 reduced_tx_set: bool,
12754 // lane-motionmode round 1/3: this frame header's own `is_motion_mode_switchable`/
12755 // `allow_warped_motion` bits, threaded to every `decode_inter_block`/
12756 // `decode_inter_block8` call below (spec 5.11.24's `read_motion_mode`).
12757 switchable_motion_mode: bool,
12758 allow_warped_motion: bool,
12759 // lane-screen r2: this frame header's own `allow_screen_content_tools`
12760 // bit, threaded to every `decode_inter_block`/`decode_inter_block8`
12761 // call below -- consumes (never reconstructs) the intra-sub-block
12762 // palette syntax libaom's `read_intra_block_mode_info` reads under the
12763 // same `av1_allow_palette` gate as the key-frame path.
12764 allow_screen_content_tools: bool,
12765 // lane-realworld r5: this frame header's own `delta` (spec 5.9.17/5.9.18),
12766 // same contract as [`decode_key_frame_tile_with_cdfs`]'s own `delta`
12767 // param -- only `q_present`/`q_res` are read.
12768 delta: DeltaParams,
12769) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> {
12770 let tpl_frame = tpl_field.map(|field| TplFrameArgs {
12771 field,
12772 order_hint_bits,
12773 order_hint,
12774 ref_order_hints,
12775 });
12776 if mi_cols == 0 || mi_rows == 0 {
12777 return Err(unsupported("a frame with no mode-info grid"));
12778 }
12779 let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
12780 // lane-superres r10: a width mismatch alone is no longer refused here --
12781 // `mc::predict_scaled` (spec 7.11.3.3, threaded through
12782 // `decode_inter_block`'s single-ref branch) exists precisely for a
12783 // `use_superres` reference at a different width than this frame's own
12784 // true size. Height must still match: AV1 superres never scales height
12785 // (r8's derivation, `mc.rs`'s own doc), and nothing in this decode path
12786 // has a vertical scaling pass.
12787 if reference.height != true_height {
12788 return Err(unsupported(
12789 "a reference picture whose height does not match this frame's own true size",
12790 ));
12791 }
12792 let (cols, rows) = block_grid(mi_cols, mi_rows);
12793 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
12794 CDEF_BITS.with(|c| c.set(cdef.bits));
12795 CDEF_SB_COLS.with(|c| c.set(sb_cols as usize));
12796 CDEF_IDX_GRID.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
12797 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
12798
12799 let ref_y = PlaneBuf {
12800 data: reference.y.iter().map(|&s| s as u16).collect(),
12801 width: reference.width,
12802 height: reference.height,
12803 true_width: reference.width,
12804 true_height: reference.height,
12805 tile_x0: 0,
12806 tile_y0: 0,
12807 tile_x1: reference.width,
12808 tile_y1: reference.height,
12809 };
12810 let ref_u = PlaneBuf {
12811 data: reference.u.iter().map(|&s| s as u16).collect(),
12812 width: reference.width / 2,
12813 height: reference.height / 2,
12814 true_width: reference.width / 2,
12815 true_height: reference.height / 2,
12816 tile_x0: 0,
12817 tile_y0: 0,
12818 tile_x1: reference.width / 2,
12819 tile_y1: reference.height / 2,
12820 };
12821 let ref_v = PlaneBuf {
12822 data: reference.v.iter().map(|&s| s as u16).collect(),
12823 width: reference.width / 2,
12824 height: reference.height / 2,
12825 true_width: reference.width / 2,
12826 true_height: reference.height / 2,
12827 tile_x0: 0,
12828 tile_y0: 0,
12829 tile_x1: reference.width / 2,
12830 tile_y1: reference.height / 2,
12831 };
12832 // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`
12833 // names a live DPB slot for (lane-av1refs: generalised from the old
12834 // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal,
12835 // now per-reference). `decode_inter_block` refuses by name when the
12836 // block it is decoding selects an index that is still `None` here
12837 // (spec 7.9 requires every *active* reference be a compatible size;
12838 // an inactive one this frame never selects is simply left `None`).
12839 let owned_refs: [Option<(PlaneBuf, PlaneBuf, PlaneBuf)>; 8] = std::array::from_fn(|i| {
12840 other_refs[i]
12841 .filter(|g| g.width == reference.width && g.height == reference.height)
12842 .map(|g| {
12843 (
12844 PlaneBuf {
12845 data: g.y.iter().map(|&s| s as u16).collect(),
12846 width: g.width,
12847 height: g.height,
12848 true_width: g.width,
12849 true_height: g.height,
12850 tile_x0: 0,
12851 tile_y0: 0,
12852 tile_x1: g.width,
12853 tile_y1: g.height,
12854 },
12855 PlaneBuf {
12856 data: g.u.iter().map(|&s| s as u16).collect(),
12857 width: g.width / 2,
12858 height: g.height / 2,
12859 true_width: g.width / 2,
12860 true_height: g.height / 2,
12861 tile_x0: 0,
12862 tile_y0: 0,
12863 tile_x1: g.width / 2,
12864 tile_y1: g.height / 2,
12865 },
12866 PlaneBuf {
12867 data: g.v.iter().map(|&s| s as u16).collect(),
12868 width: g.width / 2,
12869 height: g.height / 2,
12870 true_width: g.width / 2,
12871 true_height: g.height / 2,
12872 tile_x0: 0,
12873 tile_y0: 0,
12874 tile_x1: g.width / 2,
12875 tile_y1: g.height / 2,
12876 },
12877 )
12878 })
12879 });
12880 let ref_slots: RefSlots =
12881 std::array::from_fn(|i| owned_refs[i].as_ref().map(|(a, b, c)| (a, b, c)));
12882
12883 let mut y = PlaneBuf {
12884 data: vec![0u16; width * height],
12885 width,
12886 height,
12887 true_width,
12888 true_height,
12889 tile_x0: 0,
12890 tile_y0: 0,
12891 tile_x1: width,
12892 tile_y1: height,
12893 };
12894 let mut u = PlaneBuf {
12895 data: vec![0u16; width * height / 4],
12896 width: width / 2,
12897 height: height / 2,
12898 true_width: true_width / 2,
12899 true_height: true_height / 2,
12900 tile_x0: 0,
12901 tile_y0: 0,
12902 tile_x1: width / 2,
12903 tile_y1: height / 2,
12904 };
12905 let mut v = PlaneBuf {
12906 data: vec![0u16; width * height / 4],
12907 width: width / 2,
12908 height: height / 2,
12909 true_width: true_width / 2,
12910 true_height: true_height / 2,
12911 tile_x0: 0,
12912 tile_y0: 0,
12913 tile_x1: width / 2,
12914 tile_y1: height / 2,
12915 };
12916
12917 let scan32 = default_scan(TX32);
12918 let scan16 = default_scan(TX16);
12919 let scan8 = default_scan(TX8);
12920 let scan4 = default_scan(TX4);
12921
12922 let base_cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
12923 let mut result_cdfs = base_cdfs.clone();
12924 // spec `decode_tile`: `CurrentQIndex`/`DeltaLF` reset to the frame's own
12925 // `base_q_idx`/zero at the top of every tile, not once per frame (mirrors
12926 // `decode_key_frame_tile_with_cdfs`'s per-tile reset below); the
12927 // delta_q/delta_lf presence/resolution flags themselves are frame-level
12928 // and set once here.
12929 DELTA_Q_PRESENT.with(|c| c.set(delta.q_present));
12930 DELTA_Q_RES.with(|c| c.set(1i32 << delta.q_res));
12931 DELTA_LF_PRESENT.with(|c| c.set(delta.lf_present));
12932 DELTA_LF_RES.with(|c| c.set(1i32 << delta.lf_res));
12933 DELTA_LF_MULTI.with(|c| c.set(delta.lf_multi));
12934 let mut neighbours = Neighbours::new(
12935 cols as usize * 2,
12936 rows as usize * 2,
12937 mi_cols as usize,
12938 mi_rows as usize,
12939 );
12940 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
12941 let mut lr_grid = crate::restoration::RestorationGrid::new(lr, frame_width, frame_height);
12942 let mut lr_reference = [(
12943 crate::restoration::WienerInfo::default(),
12944 crate::restoration::SgrprojInfo::default(),
12945 ); 3];
12946
12947 // lane-tiles r6: mirrors decode_key_frame_tile_with_cdfs's own per-tile
12948 // loop (spec 5.11.2 decode_tile / 7.20 exit_symbol) -- each tile gets
12949 // its own fresh SymbolDecoder over its own byte range and its own fresh
12950 // copy of the frame's initial CDFs; only context_update_tile_id's own
12951 // end-of-tile adapted table becomes the frame's own output.
12952 for (tile_idx, &data) in tiles.iter().enumerate() {
12953 let tile_num = tile_idx as u32;
12954 let (trow, tcol) = (tile_num / tile_info.cols, tile_num % tile_info.cols);
12955 let mi_row0 = tile_info.mi_row_starts[trow as usize];
12956 let mi_row1 = tile_info.mi_row_starts[trow as usize + 1];
12957 let mi_col0 = tile_info.mi_col_starts[tcol as usize];
12958 let mi_col1 = tile_info.mi_col_starts[tcol as usize + 1];
12959 let (sb_r0, sb_r1) = (
12960 (mi_row0 / SB_MI).min(sb_rows),
12961 mi_row1.div_ceil(SB_MI).min(sb_rows),
12962 );
12963 let (sb_c0, sb_c1) = (
12964 (mi_col0 / SB_MI).min(sb_cols),
12965 mi_col1.div_ceil(SB_MI).min(sb_cols),
12966 );
12967 let mut cdfs = base_cdfs.clone();
12968 CURRENT_Q_IDX.with(|c| c.set(i32::from(base_q_idx)));
12969 QUANT_DELTAS.with(|c| c.set(deltas));
12970 CURRENT_DELTA_LF.with(|c| c.set([0; 4]));
12971 let mut dec = SymbolDecoder::new(data);
12972 // lane-comppin r9: tile-entry range, the earliest point comparable
12973 // against aomdec's own `r->ec.rng` right after `aom_reader_init` -- the
12974 // first ladder rung before any symbol (partition or otherwise) is read.
12975 if std::env::var_os("EC_AV1_TELL").is_some() {
12976 eprintln!(
12977 "TELL label=tile_init tell={} range={}",
12978 dec.debug_bitpos(),
12979 dec.debug_state().0
12980 );
12981 }
12982 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize);
12983 y.set_tile_origin(
12984 mi_col0 as usize * 4,
12985 mi_row0 as usize * 4,
12986 (mi_col1 as usize * 4).min(y.width),
12987 (mi_row1 as usize * 4).min(y.height),
12988 );
12989 u.set_tile_origin(
12990 mi_col0 as usize * 2,
12991 mi_row0 as usize * 2,
12992 (mi_col1 as usize * 2).min(u.width),
12993 (mi_row1 as usize * 2).min(u.height),
12994 );
12995 v.set_tile_origin(
12996 mi_col0 as usize * 2,
12997 mi_row0 as usize * 2,
12998 (mi_col1 as usize * 2).min(v.width),
12999 (mi_row1 as usize * 2).min(v.height),
13000 );
13001 // lane-tiles r6: an MV candidate scan (mvstack.rs's grid.get) must
13002 // not reach across a tile boundary any more than intra prediction's
13003 // PlaneBuf reach does -- bounding the shared grid's own read window
13004 // per tile is equivalent to threading tile bounds through every
13005 // find_mv_stack* call site (all four read through this one grid).
13006 grid.set_tile_bounds(
13007 mi_row0 as usize,
13008 mi_col0 as usize,
13009 mi_row1 as usize,
13010 mi_col1 as usize,
13011 );
13012 TILE_HITS.with(|c| c.set(c.get() + 1));
13013
13014 for sb_r in sb_r0..sb_r1 {
13015 neighbours.start_row();
13016 for sb_c in sb_c0..sb_c1 {
13017 crate::restoration::read_lr(
13018 &mut dec,
13019 &mut cdfs,
13020 lr,
13021 &mut lr_grid,
13022 &mut lr_reference,
13023 sb_r * SB_MI,
13024 sb_c * SB_MI,
13025 SB_MI,
13026 );
13027 CDEF_TRANSMITTED.with(|c| c.set(false));
13028 let sb_at = (sb_r as usize * 4, sb_c as usize * 4);
13029 let sb_ctx = neighbours.partition_ctx(sb_at, SB);
13030 let (has_cols, has_rows) = (
13031 sb_c * SB_MI + SB_MI / 2 < mi_cols,
13032 sb_r * SB_MI + SB_MI / 2 < mi_rows,
13033 );
13034 // The straddle cases (one or both halves outside the true
13035 // frame) never carry a real alphabet symbol -- spec forces
13036 // SPLIT there (mirrors the intra key-frame tile's own
13037 // three-way write above). Only the (true, true) case can name
13038 // a non-SPLIT value, and this loop below only ever recurses as
13039 // SPLIT -- so a real non-SPLIT part64 here must refuse by name
13040 // instead of silently decoding as SPLIT and desyncing.
13041 let part64 = match (has_cols, has_rows) {
13042 (true, true) => {
13043 let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]);
13044 if std::env::var_os("EC_AV1_TRACE").is_some() {
13045 eprintln!(
13046 "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={p}",
13047 sb_r * SB_MI,
13048 sb_c * SB_MI
13049 );
13050 }
13051 p
13052 }
13053 (true, false) => {
13054 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE));
13055 PARTITION_SPLIT
13056 }
13057 (false, true) => {
13058 dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE));
13059 PARTITION_SPLIT
13060 }
13061 (false, false) => PARTITION_SPLIT,
13062 };
13063 if part64 != PARTITION_SPLIT {
13064 return Err(unsupported(
13065 "an inter SB-level partition type other than SPLIT (this decoder's \
13066 inter tile path only recurses a superblock as SPLIT)",
13067 ));
13068 }
13069
13070 for quadrant in 0..4 {
13071 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
13072 if r32 >= rows || c32 >= cols {
13073 continue;
13074 }
13075 let at = (r32 as usize * 2, c32 as usize * 2);
13076 let ctx32 = neighbours.partition_ctx(at, BLOCK);
13077 let (has_cols32, has_rows32) = (
13078 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
13079 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
13080 );
13081 let part32 = if has_cols32 && has_rows32 {
13082 if std::env::var_os("EC_AV1_TRACE").is_some() {
13083 eprintln!(
13084 "TRACE part32_pre mi=({},{}) rng={}",
13085 r32 * BLOCK_MI,
13086 c32 * BLOCK_MI,
13087 dec.debug_state().0
13088 );
13089 }
13090 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
13091 if std::env::var_os("EC_AV1_TRACE").is_some() {
13092 eprintln!(
13093 "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p}",
13094 r32 * BLOCK_MI,
13095 c32 * BLOCK_MI
13096 );
13097 }
13098 p
13099 } else {
13100 match (has_cols32, has_rows32) {
13101 (true, false) => {
13102 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], VERT_ALIKE));
13103 }
13104 (false, true) => {
13105 dec.symbol_fixed(&gather(&cdfs.partition_w32[ctx32], HORZ_ALIKE));
13106 }
13107 _ => {}
13108 }
13109 PARTITION_SPLIT
13110 };
13111 match part32 {
13112 PARTITION_NONE => {
13113 decode_inter_block(
13114 &mut dec,
13115 &mut cdfs,
13116 &mut neighbours,
13117 &mut grid,
13118 at,
13119 BLOCK,
13120 mi_cols,
13121 mi_rows,
13122 &mut y,
13123 &mut u,
13124 &mut v,
13125 &ref_y,
13126 &ref_u,
13127 &ref_v,
13128 &ref_slots,
13129 &sign_bias_table,
13130 &global_motion,
13131 base_q_idx,
13132 TxbSet::Luma32,
13133 TxbSet::Luma32Inter,
13134 TxbSet::Chroma16,
13135 TX32,
13136 TX16,
13137 &scan32,
13138 &scan16,
13139 3,
13140 allow_high_precision_mv,
13141 force_integer_mv,
13142 interp_fixed,
13143 enable_dual_filter,
13144 tpl_frame.as_ref(),
13145 reference_select,
13146 enable_masked_compound,
13147 enable_interintra_compound,
13148 enable_jnt_comp,
13149 order_hint_bits,
13150 order_hint,
13151 ref_order_hints,
13152 skip_mode_present,
13153 skip_mode_frame,
13154 switchable_motion_mode,
13155 allow_warped_motion,
13156 false,
13157 BLOCK,
13158 BLOCK,
13159 allow_screen_content_tools,
13160 frame_width as usize,
13161 )?;
13162 }
13163 PARTITION_SPLIT => {
13164 for sub in 0..4 {
13165 let (sr, sc) = (r32 as usize * 2 + sub / 2, c32 as usize * 2 + sub % 2);
13166 if (sr as u32) * SUB_MI >= mi_rows || (sc as u32) * SUB_MI >= mi_cols {
13167 continue;
13168 }
13169 let (has_cols16, has_rows16) = (
13170 has_half(sc as u32 * SUB_MI, SUB_MI, mi_cols),
13171 has_half(sr as u32 * SUB_MI, SUB_MI, mi_rows),
13172 );
13173 if !has_cols16 && !has_rows16 {
13174 return Err(unsupported(
13175 "a 16x16 inter block whose true edge cuts through both \
13176 axes needs a rectangular transform this decoder does \
13177 not code yet",
13178 ));
13179 }
13180 let at16 = (sr, sc);
13181 if has_cols16 && has_rows16 {
13182 let ctx16 = neighbours.partition_ctx(at16, SUB);
13183 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
13184 if part16 != PARTITION_NONE {
13185 return Err(unsupported(
13186 "an inter partition below 16x16 (8x8 and smaller inter blocks are not coded yet)",
13187 ));
13188 }
13189 decode_inter_block(
13190 &mut dec,
13191 &mut cdfs,
13192 &mut neighbours,
13193 &mut grid,
13194 at16,
13195 SUB,
13196 mi_cols,
13197 mi_rows,
13198 &mut y,
13199 &mut u,
13200 &mut v,
13201 &ref_y,
13202 &ref_u,
13203 &ref_v,
13204 &ref_slots,
13205 &sign_bias_table,
13206 &global_motion,
13207 base_q_idx,
13208 TxbSet::Luma16,
13209 if reduced_tx_set {
13210 TxbSet::Luma16Inter
13211 } else {
13212 TxbSet::Luma16InterSet1
13213 },
13214 TxbSet::Chroma8,
13215 TX16,
13216 TX8,
13217 &scan16,
13218 &scan8,
13219 2,
13220 allow_high_precision_mv,
13221 force_integer_mv,
13222 interp_fixed,
13223 enable_dual_filter,
13224 tpl_frame.as_ref(),
13225 reference_select,
13226 enable_masked_compound,
13227 enable_interintra_compound,
13228 enable_jnt_comp,
13229 order_hint_bits,
13230 order_hint,
13231 ref_order_hints,
13232 skip_mode_present,
13233 skip_mode_frame,
13234 switchable_motion_mode,
13235 allow_warped_motion,
13236 false,
13237 SUB,
13238 SUB,
13239 allow_screen_content_tools,
13240 frame_width as usize,
13241 )?;
13242 } else {
13243 let ctx16 = neighbours.partition_ctx(at16, SUB);
13244 if has_cols16 {
13245 dec.symbol_fixed(&gather(
13246 &cdfs.partition_w16[ctx16],
13247 VERT_ALIKE,
13248 ));
13249 } else {
13250 dec.symbol_fixed(&gather(
13251 &cdfs.partition_w16[ctx16],
13252 HORZ_ALIKE,
13253 ));
13254 }
13255 let (mi_row0, mi_col0) = (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
13256 let leaf_positions: Vec<(u32, u32)> = (0..4)
13257 .map(|i| (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2))
13258 .filter(|&(mr, mc)| mr < mi_rows && mc < mi_cols)
13259 .collect();
13260 // lane-superres r9: decode_inter_block8's own
13261 // MC (below) is not threaded for a scaled
13262 // reference (unlike decode_inter_block's 19
13263 // sites) -- refuse the whole 8x8-leaf split
13264 // up front when ANY live reference this leaf
13265 // could pick has a different width than this
13266 // frame, rather than thread frame_width
13267 // through its own single-ref/compound MC
13268 // calls to reach the same block this round.
13269 if ref_y.width != frame_width as usize
13270 || ref_slots.iter().flatten().any(|(py, _, _)| {
13271 py.width != frame_width as usize
13272 })
13273 {
13274 return Err(unsupported(
13275 "an 8x8 partition leaf under a scaled reference (superres, unimplemented)",
13276 ));
13277 }
13278 let mut prev_leaf: Option<((usize, usize), bool, bool)> = None;
13279 let mut last_compound_ctx: Option<(i8, i8, u8, u8)> = None;
13280 let mut last_skip_mode = false;
13281 for (mr, mc) in leaf_positions {
13282 let leaf_mi = (mr as usize, mc as usize);
13283 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
13284 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
13285 if part8 != PARTITION_NONE {
13286 return Err(unsupported(
13287 "a partition below 8x8 (this decoder codes no leaf smaller than 8x8)",
13288 ));
13289 }
13290 let (skip, is_inter, skip_mode_leaf, compound_ctx8) =
13291 decode_inter_block8(
13292 &mut dec,
13293 &mut cdfs,
13294 &mut neighbours,
13295 &mut grid,
13296 mi_cols,
13297 mi_rows,
13298 at16,
13299 leaf_mi,
13300 &mut y,
13301 &mut u,
13302 &mut v,
13303 &ref_y,
13304 &ref_u,
13305 &ref_v,
13306 &ref_slots,
13307 base_q_idx,
13308 &scan8,
13309 &scan4,
13310 prev_leaf,
13311 allow_high_precision_mv,
13312 force_integer_mv,
13313 reference_select,
13314 enable_masked_compound,
13315 enable_interintra_compound,
13316 enable_jnt_comp,
13317 order_hint_bits,
13318 order_hint,
13319 ref_order_hints,
13320 skip_mode_present,
13321 skip_mode_frame,
13322 reduced_tx_set,
13323 interp_fixed,
13324 switchable_motion_mode,
13325 allow_warped_motion,
13326 allow_screen_content_tools,
13327 )?;
13328 prev_leaf = Some((leaf_mi, skip, is_inter));
13329 last_skip_mode = skip_mode_leaf;
13330 if compound_ctx8.is_some() {
13331 last_compound_ctx = compound_ctx8;
13332 }
13333 }
13334 if let Some((_, skip, is_inter)) = prev_leaf {
13335 // corner-cut: `decode_inter_block8`'s
13336 // leaves never read a switchable filter
13337 // (round-3 GLOBALMV refusal already
13338 // bounds them away from the Regular-only
13339 // gap this round closes elsewhere); `[3,
13340 // 3]` is "no info", the same value an
13341 // intra neighbour records. Upgrade:
13342 // thread `interp_fixed`/`enable_dual_filter`
13343 // into `decode_inter_block8` once a
13344 // straddling 8x8 SWITCHABLE stream is on
13345 // hand to pin against.
13346 neighbours.record_inter(
13347 at16,
13348 SUB,
13349 skip,
13350 is_inter,
13351 if is_inter { LAST_FRAME } else { -1 },
13352 [3, 3],
13353 last_skip_mode,
13354 );
13355 if let Some((ref0, ref1, group_idx, idx)) = last_compound_ctx {
13356 neighbours.record_inter(
13357 at16,
13358 SUB,
13359 skip,
13360 is_inter,
13361 ref0,
13362 [3, 3],
13363 last_skip_mode,
13364 );
13365 neighbours
13366 .record_compound_ctx(at16, SUB, ref1, group_idx, idx);
13367 }
13368 }
13369 }
13370 }
13371 }
13372 PARTITION_HORZ_B => {
13373 // lane-warp r5: PARTITION_HORZ_B = 32x32 top strip +
13374 // 16x16 bottom-left + 16x16 bottom-right. aomenc
13375 // carves static regions into it; the strip is
13376 // decoded as a square 32x32 block: for a `skip`
13377 // block the symbol stream is identical to the true
13378 // 32x16 coding (no residual, no motion_mode/warp
13379 // symbol), and the square stamps it leaves over the
13380 // bottom half (neighbour arrays, skip/lf grids) are
13381 // re-stamped by the C/D leaves right after. The
13382 // mi-granular `left_side_mi` rows of a last-block-in-
13383 // tile strip leak 32-vs-16 only until the per-tile
13384 // `Neighbours::new` reset.
13385 EXTENDED_PARTITION_HITS.with(|c| c.set(c.get() + 1));
13386 let at32 = at;
13387 decode_inter_block(
13388 &mut dec,
13389 &mut cdfs,
13390 &mut neighbours,
13391 &mut grid,
13392 at32,
13393 BLOCK,
13394 mi_cols,
13395 mi_rows,
13396 &mut y,
13397 &mut u,
13398 &mut v,
13399 &ref_y,
13400 &ref_u,
13401 &ref_v,
13402 &ref_slots,
13403 &sign_bias_table,
13404 &global_motion,
13405 base_q_idx,
13406 TxbSet::Luma32,
13407 TxbSet::Luma32Inter,
13408 TxbSet::Chroma16,
13409 TX32,
13410 TX16,
13411 &scan32,
13412 &scan16,
13413 3,
13414 allow_high_precision_mv,
13415 force_integer_mv,
13416 interp_fixed,
13417 enable_dual_filter,
13418 tpl_frame.as_ref(),
13419 reference_select,
13420 enable_masked_compound,
13421 enable_interintra_compound,
13422 enable_jnt_comp,
13423 order_hint_bits,
13424 order_hint,
13425 ref_order_hints,
13426 skip_mode_present,
13427 skip_mode_frame,
13428 switchable_motion_mode,
13429 allow_warped_motion,
13430 true,
13431 // lane-rect r2: the top strip's TRUE 32x16
13432 // footprint (was BLOCK,BLOCK -- the same square
13433 // corner-cut rect-flake-1 exposed on HORZ).
13434 BLOCK,
13435 SUB,
13436 allow_screen_content_tools,
13437 frame_width as usize,
13438 )?;
13439 if (r32 * 2 + 1) as u32 * SUB_MI < mi_rows {
13440 decode_inter_block(
13441 &mut dec,
13442 &mut cdfs,
13443 &mut neighbours,
13444 &mut grid,
13445 (r32 as usize * 2 + 1, c32 as usize * 2),
13446 SUB,
13447 mi_cols,
13448 mi_rows,
13449 &mut y,
13450 &mut u,
13451 &mut v,
13452 &ref_y,
13453 &ref_u,
13454 &ref_v,
13455 &ref_slots,
13456 &sign_bias_table,
13457 &global_motion,
13458 base_q_idx,
13459 TxbSet::Luma16,
13460 if reduced_tx_set {
13461 TxbSet::Luma16Inter
13462 } else {
13463 TxbSet::Luma16InterSet1
13464 },
13465 TxbSet::Chroma8,
13466 TX16,
13467 TX8,
13468 &scan16,
13469 &scan8,
13470 2,
13471 allow_high_precision_mv,
13472 force_integer_mv,
13473 interp_fixed,
13474 enable_dual_filter,
13475 tpl_frame.as_ref(),
13476 reference_select,
13477 enable_masked_compound,
13478 enable_interintra_compound,
13479 enable_jnt_comp,
13480 order_hint_bits,
13481 order_hint,
13482 ref_order_hints,
13483 skip_mode_present,
13484 skip_mode_frame,
13485 switchable_motion_mode,
13486 allow_warped_motion,
13487 false,
13488 SUB,
13489 SUB,
13490 allow_screen_content_tools,
13491 frame_width as usize,
13492 )?;
13493 if (c32 * 2 + 1) as u32 * SUB_MI < mi_cols {
13494 decode_inter_block(
13495 &mut dec,
13496 &mut cdfs,
13497 &mut neighbours,
13498 &mut grid,
13499 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
13500 SUB,
13501 mi_cols,
13502 mi_rows,
13503 &mut y,
13504 &mut u,
13505 &mut v,
13506 &ref_y,
13507 &ref_u,
13508 &ref_v,
13509 &ref_slots,
13510 &sign_bias_table,
13511 &global_motion,
13512 base_q_idx,
13513 TxbSet::Luma16,
13514 if reduced_tx_set {
13515 TxbSet::Luma16Inter
13516 } else {
13517 TxbSet::Luma16InterSet1
13518 },
13519 TxbSet::Chroma8,
13520 TX16,
13521 TX8,
13522 &scan16,
13523 &scan8,
13524 2,
13525 allow_high_precision_mv,
13526 force_integer_mv,
13527 interp_fixed,
13528 enable_dual_filter,
13529 tpl_frame.as_ref(),
13530 reference_select,
13531 enable_masked_compound,
13532 enable_interintra_compound,
13533 enable_jnt_comp,
13534 order_hint_bits,
13535 order_hint,
13536 ref_order_hints,
13537 skip_mode_present,
13538 skip_mode_frame,
13539 switchable_motion_mode,
13540 allow_warped_motion,
13541 false,
13542 SUB,
13543 SUB,
13544 allow_screen_content_tools,
13545 frame_width as usize,
13546 )?;
13547 }
13548 }
13549 }
13550 PARTITION_HORZ => {
13551 // lane-rect r2: two true 32x16 strips. Both read at
13552 // `side=BLOCK` (CDF/size-class selection stays square,
13553 // matching HORZ_B's accepted corner-cut) but bw4/bh4
13554 // (mvstack.rs, `motion_mode_eligible`) now derive from
13555 // `write_w`/`write_h`'s true 32x16 footprint -- the
13556 // pin's fix (r1's finding).
13557 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
13558 decode_inter_block(
13559 &mut dec,
13560 &mut cdfs,
13561 &mut neighbours,
13562 &mut grid,
13563 at,
13564 BLOCK,
13565 mi_cols,
13566 mi_rows,
13567 &mut y,
13568 &mut u,
13569 &mut v,
13570 &ref_y,
13571 &ref_u,
13572 &ref_v,
13573 &ref_slots,
13574 &sign_bias_table,
13575 &global_motion,
13576 base_q_idx,
13577 TxbSet::Luma32,
13578 TxbSet::Luma32Inter,
13579 TxbSet::Chroma16,
13580 TX32,
13581 TX16,
13582 &scan32,
13583 &scan16,
13584 3,
13585 allow_high_precision_mv,
13586 force_integer_mv,
13587 interp_fixed,
13588 enable_dual_filter,
13589 tpl_frame.as_ref(),
13590 reference_select,
13591 enable_masked_compound,
13592 enable_interintra_compound,
13593 enable_jnt_comp,
13594 order_hint_bits,
13595 order_hint,
13596 ref_order_hints,
13597 skip_mode_present,
13598 skip_mode_frame,
13599 switchable_motion_mode,
13600 allow_warped_motion,
13601 true,
13602 BLOCK,
13603 SUB,
13604 allow_screen_content_tools,
13605 frame_width as usize,
13606 )?;
13607 decode_inter_block(
13608 &mut dec,
13609 &mut cdfs,
13610 &mut neighbours,
13611 &mut grid,
13612 (r32 as usize * 2 + 1, c32 as usize * 2),
13613 BLOCK,
13614 mi_cols,
13615 mi_rows,
13616 &mut y,
13617 &mut u,
13618 &mut v,
13619 &ref_y,
13620 &ref_u,
13621 &ref_v,
13622 &ref_slots,
13623 &sign_bias_table,
13624 &global_motion,
13625 base_q_idx,
13626 TxbSet::Luma32,
13627 TxbSet::Luma32Inter,
13628 TxbSet::Chroma16,
13629 TX32,
13630 TX16,
13631 &scan32,
13632 &scan16,
13633 3,
13634 allow_high_precision_mv,
13635 force_integer_mv,
13636 interp_fixed,
13637 enable_dual_filter,
13638 tpl_frame.as_ref(),
13639 reference_select,
13640 enable_masked_compound,
13641 enable_interintra_compound,
13642 enable_jnt_comp,
13643 order_hint_bits,
13644 order_hint,
13645 ref_order_hints,
13646 skip_mode_present,
13647 skip_mode_frame,
13648 switchable_motion_mode,
13649 allow_warped_motion,
13650 true,
13651 BLOCK,
13652 SUB,
13653 allow_screen_content_tools,
13654 frame_width as usize,
13655 )?;
13656 }
13657 PARTITION_VERT => {
13658 // lane-rect r2: mirror of PARTITION_HORZ above with
13659 // width/height swapped.
13660 RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1));
13661 decode_inter_block(
13662 &mut dec,
13663 &mut cdfs,
13664 &mut neighbours,
13665 &mut grid,
13666 at,
13667 BLOCK,
13668 mi_cols,
13669 mi_rows,
13670 &mut y,
13671 &mut u,
13672 &mut v,
13673 &ref_y,
13674 &ref_u,
13675 &ref_v,
13676 &ref_slots,
13677 &sign_bias_table,
13678 &global_motion,
13679 base_q_idx,
13680 TxbSet::Luma32,
13681 TxbSet::Luma32Inter,
13682 TxbSet::Chroma16,
13683 TX32,
13684 TX16,
13685 &scan32,
13686 &scan16,
13687 3,
13688 allow_high_precision_mv,
13689 force_integer_mv,
13690 interp_fixed,
13691 enable_dual_filter,
13692 tpl_frame.as_ref(),
13693 reference_select,
13694 enable_masked_compound,
13695 enable_interintra_compound,
13696 enable_jnt_comp,
13697 order_hint_bits,
13698 order_hint,
13699 ref_order_hints,
13700 skip_mode_present,
13701 skip_mode_frame,
13702 switchable_motion_mode,
13703 allow_warped_motion,
13704 true,
13705 SUB,
13706 BLOCK,
13707 allow_screen_content_tools,
13708 frame_width as usize,
13709 )?;
13710 decode_inter_block(
13711 &mut dec,
13712 &mut cdfs,
13713 &mut neighbours,
13714 &mut grid,
13715 (r32 as usize * 2, c32 as usize * 2 + 1),
13716 BLOCK,
13717 mi_cols,
13718 mi_rows,
13719 &mut y,
13720 &mut u,
13721 &mut v,
13722 &ref_y,
13723 &ref_u,
13724 &ref_v,
13725 &ref_slots,
13726 &sign_bias_table,
13727 &global_motion,
13728 base_q_idx,
13729 TxbSet::Luma32,
13730 TxbSet::Luma32Inter,
13731 TxbSet::Chroma16,
13732 TX32,
13733 TX16,
13734 &scan32,
13735 &scan16,
13736 3,
13737 allow_high_precision_mv,
13738 force_integer_mv,
13739 interp_fixed,
13740 enable_dual_filter,
13741 tpl_frame.as_ref(),
13742 reference_select,
13743 enable_masked_compound,
13744 enable_interintra_compound,
13745 enable_jnt_comp,
13746 order_hint_bits,
13747 order_hint,
13748 ref_order_hints,
13749 skip_mode_present,
13750 skip_mode_frame,
13751 switchable_motion_mode,
13752 allow_warped_motion,
13753 true,
13754 SUB,
13755 BLOCK,
13756 allow_screen_content_tools,
13757 frame_width as usize,
13758 )?;
13759 }
13760 PARTITION_HORZ_A => {
13761 // lane-partab r1: two 16x16 squares on top + a true
13762 // 32x16 strip below (libaom decode_partition
13763 // PARTITION_HORZ_A: TL, TR, bottom strip).
13764 PARTAB_HITS.with(|c| c.set(c.get() + 1));
13765 decode_inter_block(
13766 &mut dec,
13767 &mut cdfs,
13768 &mut neighbours,
13769 &mut grid,
13770 at,
13771 SUB,
13772 mi_cols,
13773 mi_rows,
13774 &mut y,
13775 &mut u,
13776 &mut v,
13777 &ref_y,
13778 &ref_u,
13779 &ref_v,
13780 &ref_slots,
13781 &sign_bias_table,
13782 &global_motion,
13783 base_q_idx,
13784 TxbSet::Luma16,
13785 if reduced_tx_set {
13786 TxbSet::Luma16Inter
13787 } else {
13788 TxbSet::Luma16InterSet1
13789 },
13790 TxbSet::Chroma8,
13791 TX16,
13792 TX8,
13793 &scan16,
13794 &scan8,
13795 2,
13796 allow_high_precision_mv,
13797 force_integer_mv,
13798 interp_fixed,
13799 enable_dual_filter,
13800 tpl_frame.as_ref(),
13801 reference_select,
13802 enable_masked_compound,
13803 enable_interintra_compound,
13804 enable_jnt_comp,
13805 order_hint_bits,
13806 order_hint,
13807 ref_order_hints,
13808 skip_mode_present,
13809 skip_mode_frame,
13810 switchable_motion_mode,
13811 allow_warped_motion,
13812 false,
13813 SUB,
13814 SUB,
13815 allow_screen_content_tools,
13816 frame_width as usize,
13817 )?;
13818 decode_inter_block(
13819 &mut dec,
13820 &mut cdfs,
13821 &mut neighbours,
13822 &mut grid,
13823 (r32 as usize * 2, c32 as usize * 2 + 1),
13824 SUB,
13825 mi_cols,
13826 mi_rows,
13827 &mut y,
13828 &mut u,
13829 &mut v,
13830 &ref_y,
13831 &ref_u,
13832 &ref_v,
13833 &ref_slots,
13834 &sign_bias_table,
13835 &global_motion,
13836 base_q_idx,
13837 TxbSet::Luma16,
13838 if reduced_tx_set {
13839 TxbSet::Luma16Inter
13840 } else {
13841 TxbSet::Luma16InterSet1
13842 },
13843 TxbSet::Chroma8,
13844 TX16,
13845 TX8,
13846 &scan16,
13847 &scan8,
13848 2,
13849 allow_high_precision_mv,
13850 force_integer_mv,
13851 interp_fixed,
13852 enable_dual_filter,
13853 tpl_frame.as_ref(),
13854 reference_select,
13855 enable_masked_compound,
13856 enable_interintra_compound,
13857 enable_jnt_comp,
13858 order_hint_bits,
13859 order_hint,
13860 ref_order_hints,
13861 skip_mode_present,
13862 skip_mode_frame,
13863 switchable_motion_mode,
13864 allow_warped_motion,
13865 false,
13866 SUB,
13867 SUB,
13868 allow_screen_content_tools,
13869 frame_width as usize,
13870 )?;
13871 decode_inter_block(
13872 &mut dec,
13873 &mut cdfs,
13874 &mut neighbours,
13875 &mut grid,
13876 (r32 as usize * 2 + 1, c32 as usize * 2),
13877 BLOCK,
13878 mi_cols,
13879 mi_rows,
13880 &mut y,
13881 &mut u,
13882 &mut v,
13883 &ref_y,
13884 &ref_u,
13885 &ref_v,
13886 &ref_slots,
13887 &sign_bias_table,
13888 &global_motion,
13889 base_q_idx,
13890 TxbSet::Luma32,
13891 TxbSet::Luma32Inter,
13892 TxbSet::Chroma16,
13893 TX32,
13894 TX16,
13895 &scan32,
13896 &scan16,
13897 3,
13898 allow_high_precision_mv,
13899 force_integer_mv,
13900 interp_fixed,
13901 enable_dual_filter,
13902 tpl_frame.as_ref(),
13903 reference_select,
13904 enable_masked_compound,
13905 enable_interintra_compound,
13906 enable_jnt_comp,
13907 order_hint_bits,
13908 order_hint,
13909 ref_order_hints,
13910 skip_mode_present,
13911 skip_mode_frame,
13912 switchable_motion_mode,
13913 allow_warped_motion,
13914 true,
13915 BLOCK,
13916 SUB,
13917 allow_screen_content_tools,
13918 frame_width as usize,
13919 )?;
13920 }
13921 PARTITION_VERT_A => {
13922 // lane-partab r1: mirror of PARTITION_HORZ_A with
13923 // width/height swapped (TL, BL, right 16x32 strip).
13924 PARTAB_HITS.with(|c| c.set(c.get() + 1));
13925 decode_inter_block(
13926 &mut dec,
13927 &mut cdfs,
13928 &mut neighbours,
13929 &mut grid,
13930 at,
13931 SUB,
13932 mi_cols,
13933 mi_rows,
13934 &mut y,
13935 &mut u,
13936 &mut v,
13937 &ref_y,
13938 &ref_u,
13939 &ref_v,
13940 &ref_slots,
13941 &sign_bias_table,
13942 &global_motion,
13943 base_q_idx,
13944 TxbSet::Luma16,
13945 if reduced_tx_set {
13946 TxbSet::Luma16Inter
13947 } else {
13948 TxbSet::Luma16InterSet1
13949 },
13950 TxbSet::Chroma8,
13951 TX16,
13952 TX8,
13953 &scan16,
13954 &scan8,
13955 2,
13956 allow_high_precision_mv,
13957 force_integer_mv,
13958 interp_fixed,
13959 enable_dual_filter,
13960 tpl_frame.as_ref(),
13961 reference_select,
13962 enable_masked_compound,
13963 enable_interintra_compound,
13964 enable_jnt_comp,
13965 order_hint_bits,
13966 order_hint,
13967 ref_order_hints,
13968 skip_mode_present,
13969 skip_mode_frame,
13970 switchable_motion_mode,
13971 allow_warped_motion,
13972 false,
13973 SUB,
13974 SUB,
13975 allow_screen_content_tools,
13976 frame_width as usize,
13977 )?;
13978 decode_inter_block(
13979 &mut dec,
13980 &mut cdfs,
13981 &mut neighbours,
13982 &mut grid,
13983 (r32 as usize * 2 + 1, c32 as usize * 2),
13984 SUB,
13985 mi_cols,
13986 mi_rows,
13987 &mut y,
13988 &mut u,
13989 &mut v,
13990 &ref_y,
13991 &ref_u,
13992 &ref_v,
13993 &ref_slots,
13994 &sign_bias_table,
13995 &global_motion,
13996 base_q_idx,
13997 TxbSet::Luma16,
13998 if reduced_tx_set {
13999 TxbSet::Luma16Inter
14000 } else {
14001 TxbSet::Luma16InterSet1
14002 },
14003 TxbSet::Chroma8,
14004 TX16,
14005 TX8,
14006 &scan16,
14007 &scan8,
14008 2,
14009 allow_high_precision_mv,
14010 force_integer_mv,
14011 interp_fixed,
14012 enable_dual_filter,
14013 tpl_frame.as_ref(),
14014 reference_select,
14015 enable_masked_compound,
14016 enable_interintra_compound,
14017 enable_jnt_comp,
14018 order_hint_bits,
14019 order_hint,
14020 ref_order_hints,
14021 skip_mode_present,
14022 skip_mode_frame,
14023 switchable_motion_mode,
14024 allow_warped_motion,
14025 false,
14026 SUB,
14027 SUB,
14028 allow_screen_content_tools,
14029 frame_width as usize,
14030 )?;
14031 decode_inter_block(
14032 &mut dec,
14033 &mut cdfs,
14034 &mut neighbours,
14035 &mut grid,
14036 (r32 as usize * 2, c32 as usize * 2 + 1),
14037 BLOCK,
14038 mi_cols,
14039 mi_rows,
14040 &mut y,
14041 &mut u,
14042 &mut v,
14043 &ref_y,
14044 &ref_u,
14045 &ref_v,
14046 &ref_slots,
14047 &sign_bias_table,
14048 &global_motion,
14049 base_q_idx,
14050 TxbSet::Luma32,
14051 TxbSet::Luma32Inter,
14052 TxbSet::Chroma16,
14053 TX32,
14054 TX16,
14055 &scan32,
14056 &scan16,
14057 3,
14058 allow_high_precision_mv,
14059 force_integer_mv,
14060 interp_fixed,
14061 enable_dual_filter,
14062 tpl_frame.as_ref(),
14063 reference_select,
14064 enable_masked_compound,
14065 enable_interintra_compound,
14066 enable_jnt_comp,
14067 order_hint_bits,
14068 order_hint,
14069 ref_order_hints,
14070 skip_mode_present,
14071 skip_mode_frame,
14072 switchable_motion_mode,
14073 allow_warped_motion,
14074 true,
14075 SUB,
14076 BLOCK,
14077 allow_screen_content_tools,
14078 frame_width as usize,
14079 )?;
14080 }
14081 PARTITION_VERT_B => {
14082 // lane-partab r1: true 16x32 strip on the left + two
14083 // 16x16 squares on the right (libaom decode_partition
14084 // PARTITION_VERT_B: left strip, TR, BR).
14085 PARTAB_HITS.with(|c| c.set(c.get() + 1));
14086 decode_inter_block(
14087 &mut dec,
14088 &mut cdfs,
14089 &mut neighbours,
14090 &mut grid,
14091 at,
14092 BLOCK,
14093 mi_cols,
14094 mi_rows,
14095 &mut y,
14096 &mut u,
14097 &mut v,
14098 &ref_y,
14099 &ref_u,
14100 &ref_v,
14101 &ref_slots,
14102 &sign_bias_table,
14103 &global_motion,
14104 base_q_idx,
14105 TxbSet::Luma32,
14106 TxbSet::Luma32Inter,
14107 TxbSet::Chroma16,
14108 TX32,
14109 TX16,
14110 &scan32,
14111 &scan16,
14112 3,
14113 allow_high_precision_mv,
14114 force_integer_mv,
14115 interp_fixed,
14116 enable_dual_filter,
14117 tpl_frame.as_ref(),
14118 reference_select,
14119 enable_masked_compound,
14120 enable_interintra_compound,
14121 enable_jnt_comp,
14122 order_hint_bits,
14123 order_hint,
14124 ref_order_hints,
14125 skip_mode_present,
14126 skip_mode_frame,
14127 switchable_motion_mode,
14128 allow_warped_motion,
14129 true,
14130 SUB,
14131 BLOCK,
14132 allow_screen_content_tools,
14133 frame_width as usize,
14134 )?;
14135 decode_inter_block(
14136 &mut dec,
14137 &mut cdfs,
14138 &mut neighbours,
14139 &mut grid,
14140 (r32 as usize * 2, c32 as usize * 2 + 1),
14141 SUB,
14142 mi_cols,
14143 mi_rows,
14144 &mut y,
14145 &mut u,
14146 &mut v,
14147 &ref_y,
14148 &ref_u,
14149 &ref_v,
14150 &ref_slots,
14151 &sign_bias_table,
14152 &global_motion,
14153 base_q_idx,
14154 TxbSet::Luma16,
14155 if reduced_tx_set {
14156 TxbSet::Luma16Inter
14157 } else {
14158 TxbSet::Luma16InterSet1
14159 },
14160 TxbSet::Chroma8,
14161 TX16,
14162 TX8,
14163 &scan16,
14164 &scan8,
14165 2,
14166 allow_high_precision_mv,
14167 force_integer_mv,
14168 interp_fixed,
14169 enable_dual_filter,
14170 tpl_frame.as_ref(),
14171 reference_select,
14172 enable_masked_compound,
14173 enable_interintra_compound,
14174 enable_jnt_comp,
14175 order_hint_bits,
14176 order_hint,
14177 ref_order_hints,
14178 skip_mode_present,
14179 skip_mode_frame,
14180 switchable_motion_mode,
14181 allow_warped_motion,
14182 false,
14183 SUB,
14184 SUB,
14185 allow_screen_content_tools,
14186 frame_width as usize,
14187 )?;
14188 decode_inter_block(
14189 &mut dec,
14190 &mut cdfs,
14191 &mut neighbours,
14192 &mut grid,
14193 (r32 as usize * 2 + 1, c32 as usize * 2 + 1),
14194 SUB,
14195 mi_cols,
14196 mi_rows,
14197 &mut y,
14198 &mut u,
14199 &mut v,
14200 &ref_y,
14201 &ref_u,
14202 &ref_v,
14203 &ref_slots,
14204 &sign_bias_table,
14205 &global_motion,
14206 base_q_idx,
14207 TxbSet::Luma16,
14208 if reduced_tx_set {
14209 TxbSet::Luma16Inter
14210 } else {
14211 TxbSet::Luma16InterSet1
14212 },
14213 TxbSet::Chroma8,
14214 TX16,
14215 TX8,
14216 &scan16,
14217 &scan8,
14218 2,
14219 allow_high_precision_mv,
14220 force_integer_mv,
14221 interp_fixed,
14222 enable_dual_filter,
14223 tpl_frame.as_ref(),
14224 reference_select,
14225 enable_masked_compound,
14226 enable_interintra_compound,
14227 enable_jnt_comp,
14228 order_hint_bits,
14229 order_hint,
14230 ref_order_hints,
14231 skip_mode_present,
14232 skip_mode_frame,
14233 switchable_motion_mode,
14234 allow_warped_motion,
14235 false,
14236 SUB,
14237 SUB,
14238 allow_screen_content_tools,
14239 frame_width as usize,
14240 )?;
14241 }
14242 _ => {
14243 return Err(unsupported(format!(
14244 "an INTER 32x32 partition type this decoder does not code (value={part32})"
14245 )));
14246 }
14247 }
14248 }
14249 }
14250 }
14251
14252 if tile_num == tile_info.context_update_tile_id {
14253 result_cdfs = cdfs;
14254 }
14255 }
14256
14257 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
14258 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
14259 // that isolate whether a decode-order frame's mismatch already exists
14260 // in reconstruction (this dump) vs is introduced by the loop filter
14261 // (EC_AV1_DECODE_ORDER_DUMP's post-filter dump).
14262 if let Ok(path) = std::env::var("EC_AV1_PREFILT_DUMP") {
14263 use std::io::Write;
14264 let idx = PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
14265 if let Ok(mut f) = std::fs::File::create(format!("{path}.f{idx}")) {
14266 let narrow = |p: &PlaneBuf| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
14267 let _ = f.write_all(&narrow(&y));
14268 let _ = f.write_all(&narrow(&u));
14269 let _ = f.write_all(&narrow(&v));
14270 }
14271 } else {
14272 PREFILT_PICTURE_IDX.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
14273 }
14274 apply_deblock(
14275 &mut y,
14276 &mut u,
14277 &mut v,
14278 loop_filter,
14279 &neighbours,
14280 frame_width as usize,
14281 frame_height as usize,
14282 );
14283 let (deblocked_y, deblocked_u, deblocked_v) = (y.clone(), u.clone(), v.clone());
14284 // lane-tiny r4: post-deblock / post-CDEF dumps mirroring aomdec's own
14285 // EC_AV1_POSTDEBLOCK_DUMP (decodeframe.c ~5404) -- with the pre-filter
14286 // dump above these bisect WHICH filter stage introduced a mismatch.
14287 dump_stage("EC_AV1_POSTDEBLOCK_DUMP", &y, &u, &v);
14288 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
14289 dump_stage("EC_AV1_POSTCDEF_DUMP", &y, &u, &v);
14290 apply_loop_restoration(&mut y, &mut u, &mut v, &deblocked_y, &deblocked_u, &deblocked_v, lr, &lr_grid);
14291
14292 let motion_field = build_motion_field(
14293 &grid,
14294 mi_cols as usize,
14295 mi_rows as usize,
14296 order_hint,
14297 ref_order_hints,
14298 );
14299
14300 let (fw, fh) = (frame_width as usize, frame_height as usize);
14301 if fw == width && fh == height {
14302 LAST_FRAME_WIDE_MARGIN.with(|m| *m.borrow_mut() = None);
14303 return Ok((
14304 Picture {
14305 width,
14306 height,
14307 y: y.data,
14308 u: u.data,
14309 v: v.data,
14310 },
14311 result_cdfs,
14312 motion_field,
14313 ));
14314 }
14315 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u16> {
14316 let mut out = Vec::with_capacity(w * h);
14317 for row in 0..h {
14318 out.extend(plane.data[row * plane.width..][..w].iter().copied());
14319 }
14320 out
14321 };
14322 // lane-superres r10 (fixed r9): same real-margin stash as
14323 // `decode_key_frame_tile_with_cdfs` (see that function's comment) -- the
14324 // real reconstructed extent is the mi-aligned `true_width`/`true_height`
14325 // (`mi_cols`/`mi_rows` * 4), NOT the superblock-padded `width`/`height`
14326 // this branch was reading before: columns `[true_width, width)` were
14327 // never actually coded (the last partial superblock stops at
14328 // `true_width`), so stashing out to `width` handed the chroma upscale's
14329 // right-edge replicate a slice of uninitialized/stale buffer one column
14330 // early -- the same shorten-vs-replicate shape as `av1-truesize`. The
14331 // key-frame branch above already used `true_width`/`true_height`; this
14332 // just matches it.
14333 LAST_FRAME_WIDE_MARGIN.with(|m| {
14334 *m.borrow_mut() = if true_width > fw || true_height > fh {
14335 Some(Picture {
14336 width: true_width,
14337 height: true_height,
14338 y: crop(&y, true_width, true_height),
14339 u: crop(&u, true_width.div_ceil(2), true_height.div_ceil(2)),
14340 v: crop(&v, true_width.div_ceil(2), true_height.div_ceil(2)),
14341 })
14342 } else {
14343 None
14344 }
14345 });
14346 Ok((
14347 Picture {
14348 width: fw,
14349 height: fh,
14350 y: crop(&y, fw, fh),
14351 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
14352 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
14353 },
14354 result_cdfs,
14355 motion_field,
14356 ))
14357}
14358
14359#[cfg(test)]
14360mod tests {
14361 use super::*;
14362
14363 // `crate::tile`'s `flat_key_frame_tile`/`dc_key_frame_tile_levels`/
14364 // `split_dc_key_frame_tile` are not exercised here: they are synthetic
14365 // single-purpose writers with their own skip-context rule (keyed to
14366 // superblock position, not the neighbour-tracked one every real block
14367 // uses), never reached by `encode_key_frame_with_modes` — decoding them
14368 // would need a second, throwaway context convention next to the real
14369 // one below. `sb_coeff_key_frame_tile`, what the real encoder writes, is
14370 // this decoder's one target, and the round-trip test below is against
14371 // that path with real quantised residual, not a synthetic all-DC frame.
14372
14373 /// `is_uni_comp_ref` (lane-av1comp): a pair is unidirectional exactly
14374 /// when both references sit on the same temporal side -- the three
14375 /// `uni_comp_ref` bitstream pairs (LAST/LAST2, LAST/LAST3, LAST/GOLDEN)
14376 /// all read `true`, a forward/backward mix (LAST/BWDREF) reads `false`,
14377 /// and a same-side non-`uni_comp_ref` pair (BWDREF/ALTREF) still reads
14378 /// `true` (spec `has_uni_comp_refs` is symmetric in the reference set,
14379 /// not just the three enumerated syntax pairs).
14380 #[test]
14381 fn is_uni_comp_ref_matches_forward_backward_sides() {
14382 assert!(is_uni_comp_ref(LAST_FRAME, LAST2_FRAME));
14383 assert!(is_uni_comp_ref(LAST_FRAME, LAST3_FRAME));
14384 assert!(is_uni_comp_ref(LAST_FRAME, GOLDEN_FRAME));
14385 assert!(is_uni_comp_ref(BWDREF_FRAME, ALTREF_FRAME));
14386 assert!(!is_uni_comp_ref(LAST_FRAME, BWDREF_FRAME));
14387 assert!(!is_uni_comp_ref(GOLDEN_FRAME, ALTREF_FRAME));
14388 }
14389
14390 /// [`Neighbours::record_compound_ctx`] stamps `above_ref1`/`left_ref1`
14391 /// with the real second reference (lane-av1comp round 12: previously
14392 /// always cleared to `None` by `record_inter`, so the next block's own
14393 /// `NeighbourRef::uni` -- and `comp_reference_type_ctx` downstream of it
14394 /// -- could never see a real compound neighbour).
14395 #[test]
14396 fn record_compound_ctx_stamps_ref1_for_the_next_block_to_read() {
14397 let mut n = Neighbours::new(4, 4, 16, 16);
14398 n.record_inter((0, 0), SUB, false, true, LAST_FRAME, [3, 3], false);
14399 assert_eq!(n.above_ref1[0], None, "record_inter alone never sets ref1");
14400 n.record_compound_ctx((0, 0), SUB, ALTREF_FRAME, 0, 1);
14401 assert_eq!(n.above_ref1[0], Some(ALTREF_FRAME));
14402 assert_eq!(n.left_ref1[0], Some(ALTREF_FRAME));
14403 assert!(!is_uni_comp_ref(LAST_FRAME, n.above_ref1[0].unwrap()));
14404 }
14405
14406 /// [`cdf::COMPOUND_MODE_CTX_MAP`] folded by hand against libaom's
14407 /// `av1_mode_context_analyzer` compound branch (`mvref_common.h`):
14408 /// `comp_ctx = compound_mode_ctx_map[refmv_ctx >> 1][min(newmv_ctx, 4)]`
14409 /// -- a few corner and interior points, not the whole 6x6 grid.
14410 #[test]
14411 fn compound_mode_ctx_map_matches_libaom_corners() {
14412 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][0], 0);
14413 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[0][4], 1);
14414 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][0], 1);
14415 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[1][3], 4);
14416 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][2], 5);
14417 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[2][4], 7);
14418 // `ref_mv_ctx` up to 5 (`>> 1` = 2, the map's last row) and
14419 // `new_mv_ctx` up to 5 (clamped to 4, `COMP_NEWMV_CTXS - 1`) are
14420 // exactly the ranges `find_mv_stack_compound` produces.
14421 assert_eq!(cdf::COMPOUND_MODE_CTX_MAP[5 >> 1][5usize.min(4)], 7);
14422 }
14423
14424 #[test]
14425 fn a_frame_with_no_mode_info_grid_is_refused() {
14426 assert!(
14427 decode_key_frame_tile(
14428 &[0u8; 4],
14429 0,
14430 32,
14431 32,
14432 0,
14433 128,
14434 false,
14435 &CdefParams::default(),
14436 &LoopFilterParams::default(),
14437 false,
14438 true,
14439 false,
14440 false,
14441 )
14442 .is_err()
14443 );
14444 }
14445
14446 /// Encodes and decodes one picture with `modes`, asserting the decoder's
14447 /// planes are byte-exact against the encoder's own reconstruction.
14448 fn round_trips(w: usize, h: usize, modes: &[u8]) {
14449 use crate::encode::{Encoded, Picture as Pic};
14450 let mut source = vec![0u16; w * h];
14451 for row in 0..h {
14452 for col in 0..w {
14453 source[row * w + col] = ((row * 3 + col * 5) % 251) as u16;
14454 }
14455 }
14456 let picture = Pic {
14457 width: w,
14458 height: h,
14459 y: source,
14460 u: vec![128; w * h / 4],
14461 v: vec![128; w * h / 4],
14462 };
14463 let Encoded {
14464 tile,
14465 reconstruction,
14466 mi_cols,
14467 mi_rows,
14468 base_q_idx,
14469 ..
14470 }: Encoded = crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, modes).unwrap();
14471 let decoded = decode_key_frame_tile(
14472 &tile,
14473 mi_cols,
14474 mi_rows,
14475 base_q_idx,
14476 w as u32,
14477 h as u32,
14478 false,
14479 &CdefParams::default(),
14480 &LoopFilterParams::default(),
14481 false,
14482 true,
14483 false,
14484 false,
14485 )
14486 .unwrap();
14487 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
14488 assert_eq!(decoded.height, h, "{w}x{h}: decoded height");
14489 assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch");
14490 assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch");
14491 assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch");
14492 }
14493
14494 #[test]
14495 fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {
14496 for (w, h) in [(128usize, 128usize), (192, 128)] {
14497 round_trips(w, h, &[DC_PRED as u8]);
14498 }
14499 }
14500
14501 /// Every one of the thirteen key-frame intra modes, at their base angle,
14502 /// on real (non-flat) content: the mode search picks whichever wins each
14503 /// block, so this exercises the directional edge/reach plumbing this
14504 /// decoder round adds, not just `DC_PRED`.
14505 #[test]
14506 fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() {
14507 for (w, h) in [(128usize, 128usize), (192, 128)] {
14508 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
14509 }
14510 }
14511
14512 /// Sizes not a whole number of 64x64 superblocks (nor even of 32x32
14513 /// blocks, for 854x480): the gathered-CDF partial-superblock/32x32 path
14514 /// this decoder round adds.
14515 #[test]
14516 fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
14517 for (w, h) in [(854usize, 480usize), (216, 96)] {
14518 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
14519 }
14520 }
14521
14522 /// mod-32==8 sizes (lane-av1-rect): the true frame edge falls inside a
14523 /// 16x16 block itself, forcing the encoder's 8x8-leaf straddle path
14524 /// ([`crate::tile::write_leaf8`]) regardless of the RD-cost guard, since
14525 /// no whole 16x16/32x32 legally covers the true edge here -- this decoder
14526 /// round's leaf8 read path (`decode_leaf8`, gathered `partition_w16` split
14527 /// bit, `partition_w8` leaves).
14528 #[test]
14529 fn leaf8_straddle_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
14530 for (w, h) in [(40usize, 32usize), (640, 360)] {
14531 round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
14532 }
14533 }
14534
14535 /// A skipped block codes no residual syntax at all (spec 5.11.34):
14536 /// straight prediction on every plane. The real key-frame writer never
14537 /// emits `skip = 1` ([`crate::tile::write_intra_mode`] hardcodes it to
14538 /// `0`), so this constructs the exact symbol sequence a writer that did
14539 /// emit it would produce, by hand, and asserts the decoded reconstruction
14540 /// is pure DC prediction (mid-grey, with no neighbours) rather than
14541 /// refusing.
14542 #[test]
14543 fn a_skipped_block_decodes_to_pure_prediction() {
14544 use crate::msac::SymbolEncoder;
14545 let mut cdfs = Cdfs::new(q_ctx_of(40));
14546 let mut enc = SymbolEncoder::new();
14547 // One whole, unsplit 64x64 superblock, coded skip = true.
14548 enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[0]);
14549 enc.symbol(1, &mut cdfs.skip[0]);
14550 enc.symbol(
14551 DC_PRED,
14552 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
14553 );
14554 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
14555 let data = enc.finish();
14556 let decoded = decode_key_frame_tile(
14557 &data,
14558 16,
14559 16,
14560 40,
14561 64,
14562 64,
14563 false,
14564 &CdefParams::default(),
14565 &LoopFilterParams::default(),
14566 false,
14567 true,
14568 false,
14569 false,
14570 )
14571 .unwrap();
14572 assert!(
14573 decoded.y.iter().all(|&s| s == 128),
14574 "a skipped DC_PRED block with no neighbours predicts flat mid-grey"
14575 );
14576 }
14577
14578 /// An inter tile's SB-level `part64` used to be read and thrown away
14579 /// (`let _ = part64;`), recursing as SPLIT unconditionally -- a real
14580 /// non-SPLIT value there silently desynced the whole tile instead of
14581 /// refusing. Hand-writes a single whole superblock's `part64 = HORZ`
14582 /// symbol (never produced by this crate's own encoder, which only ever
14583 /// writes NONE/SPLIT at this level, but a real aomenc-class encoder can)
14584 /// and asserts this decoder refuses by name rather than decoding garbage.
14585 #[test]
14586 fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() {
14587 use crate::msac::SymbolEncoder;
14588 let mut cdfs = Cdfs::new(q_ctx_of(40));
14589 let mut enc = SymbolEncoder::new();
14590 enc.symbol(PARTITION_HORZ, &mut cdfs.partition_w64[0]);
14591 let data = enc.finish();
14592 let reference = crate::encode::Picture::grey(64, 64);
14593 let err = decode_inter_frame_tile(
14594 &data,
14595 16,
14596 16,
14597 40,
14598 64,
14599 64,
14600 &reference,
14601 [None; 8],
14602 &CdefParams::default(),
14603 &LoopFilterParams::default(),
14604 false,
14605 false,
14606 Some(mc::InterpFilterKind::Regular),
14607 false,
14608 false,
14609 )
14610 .unwrap_err();
14611 let msg = err.to_string();
14612 assert!(
14613 msg.contains("SPLIT"),
14614 "expected the named inter-SB-partition refusal, got: {msg}"
14615 );
14616 }
14617
14618 // ffmpeg cross-oracle: an independent decoder (not this crate's own
14619 // encoder-side reconstruction) agrees with what this module decodes,
14620 // duplicating `crate::encode`'s own `#[cfg(test)]` helpers of the same
14621 // name (that module is another lane's territory this round, and the
14622 // helpers are `#[cfg(test)]`-private to it).
14623 use std::io::Write;
14624 use std::process::{Command, Stdio};
14625
14626 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
14627 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
14628 /// aomenc gate decodes its stream through ffmpeg and is meaningless
14629 /// without it -- turns it into a hard failure. Without this the require
14630 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
14631 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
14632 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
14633 fn have_ffmpeg() -> bool {
14634 let present = Command::new("ffmpeg")
14635 .arg("-version")
14636 .stdout(Stdio::null())
14637 .stderr(Stdio::null())
14638 .status()
14639 .is_ok_and(|s| s.success());
14640 assert!(
14641 present
14642 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
14643 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
14644 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
14645 );
14646 present
14647 }
14648
14649 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
14650 /// frame's planes, at ffmpeg's own (coded, block-padded) size.
14651 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
14652 let mut child = Command::new("ffmpeg")
14653 .args([
14654 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
14655 ])
14656 .stdin(Stdio::piped())
14657 .stdout(Stdio::piped())
14658 .stderr(Stdio::piped())
14659 .spawn()
14660 .expect("ffmpeg failed to start");
14661 child
14662 .stdin
14663 .take()
14664 .expect("ffmpeg stdin")
14665 .write_all(stream)
14666 .expect("writing the stream to ffmpeg");
14667 let out = child.wait_with_output().expect("ffmpeg failed to run");
14668 assert!(
14669 out.status.success(),
14670 "ffmpeg refused the stream: {}",
14671 String::from_utf8_lossy(&out.stderr)
14672 );
14673 let (luma, chroma) = (width * height, width * height / 4);
14674 assert_eq!(
14675 out.stdout.len(),
14676 luma + 2 * chroma,
14677 "expected one 4:2:0 frame"
14678 );
14679 Picture {
14680 width,
14681 height,
14682 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
14683 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
14684 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
14685 }
14686 }
14687
14688 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
14689 fn ffmpeg_decode_sequence(
14690 stream: &[u8],
14691 width: usize,
14692 height: usize,
14693 frames: usize,
14694 ) -> Vec<Picture> {
14695 let mut child = Command::new("ffmpeg")
14696 .args([
14697 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
14698 ])
14699 .stdin(Stdio::piped())
14700 .stdout(Stdio::piped())
14701 .stderr(Stdio::piped())
14702 .spawn()
14703 .expect("ffmpeg failed to start");
14704 child
14705 .stdin
14706 .take()
14707 .expect("ffmpeg stdin")
14708 .write_all(stream)
14709 .expect("writing the stream to ffmpeg");
14710 let out = child.wait_with_output().expect("ffmpeg failed to run");
14711 assert!(
14712 out.status.success(),
14713 "ffmpeg refused the stream: {}",
14714 String::from_utf8_lossy(&out.stderr)
14715 );
14716 let (luma, chroma) = (width * height, width * height / 4);
14717 let frame_bytes = luma + 2 * chroma;
14718 assert_eq!(
14719 out.stdout.len(),
14720 frame_bytes * frames,
14721 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
14722 String::from_utf8_lossy(&out.stderr)
14723 );
14724 (0..frames)
14725 .map(|i| {
14726 let base = i * frame_bytes;
14727 Picture {
14728 width,
14729 height,
14730 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
14731 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
14732 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
14733 }
14734 })
14735 .collect()
14736 }
14737
14738 /// `ffprobe`'s reported coded `width,height` for one OBU stream --
14739 /// duplicating `crate::encode`'s own helper (per-call temp naming: the
14740 /// test binary runs callers on parallel threads, and a shared name lets
14741 /// one test's cleanup race another's still-reading ffprobe --
14742 /// pid-keyed-temp-path class).
14743 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
14744 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
14745 let path = std::env::temp_dir().join(format!(
14746 "ec-av1-decode-probe-{}-{}.obu",
14747 std::process::id(),
14748 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
14749 ));
14750 let _ = std::fs::remove_file(&path);
14751 std::fs::write(&path, stream).expect("writing the probe stream");
14752 let out = Command::new("ffprobe")
14753 .args([
14754 "-v",
14755 "error",
14756 "-f",
14757 "obu",
14758 "-select_streams",
14759 "v:0",
14760 "-show_entries",
14761 "stream=width,height",
14762 "-of",
14763 "csv=p=0",
14764 ])
14765 .arg(&path)
14766 .output()
14767 .expect("ffprobe failed to run");
14768 let _ = std::fs::remove_file(&path);
14769 assert!(
14770 out.status.success(),
14771 "ffprobe refused the stream: {}",
14772 String::from_utf8_lossy(&out.stderr)
14773 );
14774 let text = String::from_utf8_lossy(&out.stdout);
14775 let mut fields = text.trim().split(',');
14776 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
14777 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
14778 (width, height)
14779 }
14780
14781 /// This module's own decoder against an independent one (ffmpeg), not
14782 /// just against this crate's encoder-side reconstruction: both decoders
14783 /// read the identical tile bytes, so agreement here rules out a bug this
14784 /// crate's own writer and reader could otherwise share.
14785 #[test]
14786 fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {
14787 if !have_ffmpeg() {
14788 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg");
14789 return;
14790 }
14791 use crate::encode::encode_key_frame;
14792 for &(width, height) in &[(64usize, 64usize), (216, 96), (40, 32)] {
14793 let picture = round_trip_test_card(width, height);
14794 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
14795 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
14796 let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize);
14797 let ours = decode_key_frame_tile(
14798 &encoded.tile,
14799 encoded.mi_cols,
14800 encoded.mi_rows,
14801 encoded.base_q_idx,
14802 coded_w,
14803 coded_h,
14804 false,
14805 &CdefParams::default(),
14806 &LoopFilterParams::default(),
14807 false,
14808 true,
14809 false,
14810 false,
14811 )
14812 .unwrap();
14813 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
14814 assert_eq!(ours.u, ffmpeg_decoded.u, "{width}x{height}: U vs ffmpeg");
14815 assert_eq!(ours.v, ffmpeg_decoded.v, "{width}x{height}: V vs ffmpeg");
14816 }
14817 }
14818
14819 fn round_trip_test_card(width: usize, height: usize) -> crate::encode::Picture {
14820 let mut picture = crate::encode::Picture::grey(width, height);
14821 for row in 0..height {
14822 for col in 0..width {
14823 picture.y[row * width + col] = ((row * 7 + col * 11) % 251) as u16;
14824 }
14825 }
14826 for row in 0..height / 2 {
14827 for col in 0..width / 2 {
14828 let i = row * width / 2 + col;
14829 picture.u[i] = (100 + (col * 60 / (width / 2).max(1))) as u16;
14830 picture.v[i] = (200 - (row * 80 / (height / 2).max(1))) as u16;
14831 }
14832 }
14833 picture
14834 }
14835
14836 fn panned_test_card(width: usize, height: usize, shift: i64) -> crate::encode::Picture {
14837 let mut picture = crate::encode::Picture::grey(width, height);
14838 for y in 0..height {
14839 for x in 0..width {
14840 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
14841 let gradient = sx * 200.0 / width as f64;
14842 picture.y[y * width + x] = (20.0 + gradient).clamp(0.0, 255.0) as u16;
14843 }
14844 }
14845 for y in 0..height / 2 {
14846 for x in 0..width / 2 {
14847 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
14848 let i = y * width / 2 + x;
14849 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
14850 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
14851 }
14852 }
14853 picture
14854 }
14855
14856 /// A GOP (one key frame plus several inter frames, each panned so its
14857 /// blocks actually take `NEARESTMV`/`NEWMV` rather than an all-skip
14858 /// `(0, 0)` no-op) decodes bit-exact against the encoder's own
14859 /// reconstruction, frame by frame, chaining each decoded frame straight
14860 /// into the next as its reference -- exactly the single-slot DPB
14861 /// [`crate::encode::encode_sequence`] itself threads.
14862 fn gop_round_trips(width: usize, height: usize) {
14863 use crate::encode::encode_sequence;
14864 let pictures: Vec<_> = (0..4)
14865 .map(|i| panned_test_card(width, height, i * 3))
14866 .collect();
14867 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
14868 assert_eq!(encoded.frames.len(), 4);
14869
14870 let key = &encoded.frames[0];
14871 let mut reference = decode_key_frame_tile(
14872 &key.tile,
14873 key.mi_cols,
14874 key.mi_rows,
14875 key.base_q_idx,
14876 width as u32,
14877 height as u32,
14878 false,
14879 &CdefParams::default(),
14880 &LoopFilterParams::default(),
14881 false,
14882 true,
14883 false,
14884 false,
14885 )
14886 .unwrap();
14887 assert_eq!(
14888 reference.y, key.reconstruction.y,
14889 "{width}x{height} frame 0 luma"
14890 );
14891 assert_eq!(
14892 reference.u, key.reconstruction.u,
14893 "{width}x{height} frame 0 U"
14894 );
14895 assert_eq!(
14896 reference.v, key.reconstruction.v,
14897 "{width}x{height} frame 0 V"
14898 );
14899
14900 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
14901 let decoded = decode_inter_frame_tile(
14902 &frame.tile,
14903 frame.mi_cols,
14904 frame.mi_rows,
14905 frame.base_q_idx,
14906 width as u32,
14907 height as u32,
14908 &reference,
14909 [None; 8],
14910 &CdefParams::default(),
14911 &LoopFilterParams::default(),
14912 false,
14913 false,
14914 Some(mc::InterpFilterKind::Regular),
14915 false,
14916 false,
14917 )
14918 .unwrap();
14919 assert_eq!(
14920 decoded.y, frame.reconstruction.y,
14921 "{width}x{height} frame {i} luma"
14922 );
14923 assert_eq!(
14924 decoded.u, frame.reconstruction.u,
14925 "{width}x{height} frame {i} U"
14926 );
14927 assert_eq!(
14928 decoded.v, frame.reconstruction.v,
14929 "{width}x{height} frame {i} V"
14930 );
14931 reference = decoded;
14932 }
14933 }
14934
14935 #[test]
14936 fn a_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
14937 gop_round_trips(128, 64);
14938 }
14939
14940 /// Same claim, at a size that is not a whole number of 32x32 blocks
14941 /// (216x96: 216/32 is not exact), so an inter frame's own 16x16-leaf
14942 /// split path is exercised too.
14943 #[test]
14944 fn an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
14945 gop_round_trips(216, 96);
14946 }
14947
14948 /// The GOP cross-oracle: ffmpeg decodes the whole sequence the same way
14949 /// this module does, frame for frame.
14950 /// A NEARMV block (`not_new`, `not_zero`, `!nearest`) predicts from the
14951 /// MV stack's *second* candidate (`near_mv`), not its first
14952 /// (`nearest_mv`) -- a hand-built symbol stream drives
14953 /// [`decode_inter_block`] directly, since this crate's own encoder never
14954 /// writes NEARMV (round 3: it never chooses the mode).
14955 #[test]
14956 fn a_nearmv_block_predicts_from_the_stacks_second_candidate() {
14957 use crate::msac::SymbolEncoder;
14958 use crate::mvstack::{MiGrid, MiInfo, find_mv_stack, single_ref_ctx};
14959
14960 const LAST_FRAME: i8 = 1;
14961 let (mi_cols, mi_rows) = (12u32, 12u32);
14962 let side = 16usize; // one 16x16 leaf block
14963 let (r, c) = (1usize, 1usize); // `at`, in SUB (16px) units
14964 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
14965 let bw4 = side / 4;
14966
14967 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
14968 let (above_mv, left_mv) = ((4, 4), (8, 8));
14969 let neighbour = |mv| MiInfo {
14970 is_inter: true,
14971 ref_frame: LAST_FRAME,
14972 ref_frame1: None,
14973 mv1: None,
14974 mv,
14975 is_new_mv: false,
14976 size: 1,
14977 size_h: 1,
14978 is_global_mv0: false,
14979 is_global_mv1: false,
14980 };
14981 for col in mi_col..mi_col + bw4 {
14982 grid.set(mi_row - 1, col, neighbour(above_mv));
14983 }
14984 for row in mi_row..mi_row + bw4 {
14985 grid.set(row, mi_col - 1, neighbour(left_mv));
14986 }
14987
14988 let stack = find_mv_stack(
14989 &grid,
14990 mi_row,
14991 mi_col,
14992 bw4,
14993 bw4,
14994 LAST_FRAME,
14995 mi_cols as usize,
14996 mi_rows as usize,
14997 );
14998 // Sanity on the test's own setup, not the code under test: two equal-
14999 // weight candidates keep scan order (above, then left -- module doc).
15000 assert_eq!(stack.entries.len(), 2);
15001 assert_eq!(stack.nearest_mv, above_mv);
15002 assert_eq!(stack.near_mv, left_mv);
15003
15004 let (skip_ctx, ii_ctx, sr_ctx) = (
15005 0usize,
15006 intra_inter_ctx(true, true, false, false),
15007 single_ref_ctx(false),
15008 );
15009
15010 let mut cdfs = Cdfs::new(q_ctx_of(100));
15011 let mut enc = SymbolEncoder::new();
15012 enc.symbol(1, &mut cdfs.skip[skip_ctx]); // skip
15013 enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); // is_inter
15014 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // LAST_FRAME
15015 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]);
15016 enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]);
15017 enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not_new
15018 enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not_zero
15019 enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // !nearest -> NEARMV
15020 let data = enc.finish();
15021
15022 let (width, height) = (64usize, 64usize);
15023 let ref_pattern: Vec<u16> = (0..width * height).map(|i| (i % 251) as u16).collect();
15024 let ref_plane = |scale: usize| PlaneBuf {
15025 data: ref_pattern
15026 .iter()
15027 .step_by(scale.max(1))
15028 .take((width / scale) * (height / scale))
15029 .copied()
15030 .collect(),
15031 width: width / scale,
15032 height: height / scale,
15033 true_width: width / scale,
15034 true_height: height / scale,
15035 tile_x0: 0,
15036 tile_y0: 0,
15037 tile_x1: width / scale,
15038 tile_y1: height / scale,
15039 };
15040 let ref_y = PlaneBuf {
15041 data: ref_pattern.clone(),
15042 width,
15043 height,
15044 true_width: width,
15045 true_height: height,
15046 tile_x0: 0,
15047 tile_y0: 0,
15048 tile_x1: width,
15049 tile_y1: height,
15050 };
15051 let ref_u = ref_plane(2);
15052 let ref_v = ref_plane(2);
15053
15054 let mut y = PlaneBuf {
15055 data: vec![0u16; width * height],
15056 width,
15057 height,
15058 true_width: width,
15059 true_height: height,
15060 tile_x0: 0,
15061 tile_y0: 0,
15062 tile_x1: width,
15063 tile_y1: height,
15064 };
15065 let mut u = PlaneBuf {
15066 data: vec![0u16; (width / 2) * (height / 2)],
15067 width: width / 2,
15068 height: height / 2,
15069 true_width: width / 2,
15070 true_height: height / 2,
15071 tile_x0: 0,
15072 tile_y0: 0,
15073 tile_x1: width / 2,
15074 tile_y1: height / 2,
15075 };
15076 let mut v = PlaneBuf {
15077 data: vec![0u16; (width / 2) * (height / 2)],
15078 width: width / 2,
15079 height: height / 2,
15080 true_width: width / 2,
15081 true_height: height / 2,
15082 tile_x0: 0,
15083 tile_y0: 0,
15084 tile_x1: width / 2,
15085 tile_y1: height / 2,
15086 };
15087
15088 let mut cdfs = Cdfs::new(q_ctx_of(100));
15089 let mut dec = SymbolDecoder::new(&data);
15090 let mut neighbours = Neighbours::new(3, 3, mi_cols as usize, mi_rows as usize);
15091 decode_inter_block(
15092 &mut dec,
15093 &mut cdfs,
15094 &mut neighbours,
15095 &mut grid,
15096 (r, c),
15097 side,
15098 mi_cols,
15099 mi_rows,
15100 &mut y,
15101 &mut u,
15102 &mut v,
15103 &ref_y,
15104 &ref_u,
15105 &ref_v,
15106 &[None; 8],
15107 &NO_SIGN_BIAS,
15108 &[ec_av1_syntax::WarpParams::default(); 7],
15109 100,
15110 TxbSet::Luma16,
15111 TxbSet::Luma16Inter,
15112 TxbSet::Chroma8,
15113 TX16,
15114 TX8,
15115 &[],
15116 &[],
15117 0,
15118 false,
15119 false,
15120 Some(mc::InterpFilterKind::Regular),
15121 false,
15122 None,
15123 false,
15124 false,
15125 false,
15126 false,
15127 0,
15128 0,
15129 [0; 7],
15130 false,
15131 [0; 2],
15132 false,
15133 false,
15134 false,
15135 side,
15136 side,
15137 false,
15138 width,
15139 )
15140 .unwrap();
15141
15142 let (px, py) = (c * SUB, r * SUB);
15143 let mut want_near = vec![0u16; side * side];
15144 crate::mc::predict(
15145 &ref_y.data,
15146 ref_y.width,
15147 ref_y.true_width,
15148 ref_y.true_height,
15149 mv_to_q4(px, left_mv.1, true),
15150 mv_to_q4(py, left_mv.0, true),
15151 side,
15152 side,
15153 &mut want_near,
15154 );
15155 let mut want_nearest = vec![0u16; side * side];
15156 crate::mc::predict(
15157 &ref_y.data,
15158 ref_y.width,
15159 ref_y.true_width,
15160 ref_y.true_height,
15161 mv_to_q4(px, above_mv.1, true),
15162 mv_to_q4(py, above_mv.0, true),
15163 side,
15164 side,
15165 &mut want_nearest,
15166 );
15167 assert_ne!(
15168 want_near, want_nearest,
15169 "test setup: the two candidate MVs must predict differently"
15170 );
15171
15172 let mut got = vec![0u16; side * side];
15173 for row in 0..side {
15174 got[row * side..(row + 1) * side].copy_from_slice(
15175 &y.data[(py + row) * y.width + px..(py + row) * y.width + px + side],
15176 );
15177 }
15178 assert_eq!(
15179 got, want_near,
15180 "NEARMV predicted from the wrong stack entry"
15181 );
15182 }
15183
15184 #[test]
15185 fn ffmpeg_and_this_decoder_agree_on_a_gop() {
15186 if !have_ffmpeg() {
15187 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg");
15188 return;
15189 }
15190 use crate::encode::encode_sequence;
15191 let (width, height) = (128usize, 64usize);
15192 let pictures: Vec<_> = (0..3)
15193 .map(|i| panned_test_card(width, height, i * 3))
15194 .collect();
15195 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
15196 let (coded_w, coded_h) = ffprobe_size(&encoded.stream);
15197 let ffmpeg_frames =
15198 ffmpeg_decode_sequence(&encoded.stream, coded_w as usize, coded_h as usize, 3);
15199
15200 let key = &encoded.frames[0];
15201 let mut reference = decode_key_frame_tile(
15202 &key.tile,
15203 key.mi_cols,
15204 key.mi_rows,
15205 key.base_q_idx,
15206 coded_w,
15207 coded_h,
15208 false,
15209 &CdefParams::default(),
15210 &LoopFilterParams::default(),
15211 false,
15212 true,
15213 false,
15214 false,
15215 )
15216 .unwrap();
15217 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
15218
15219 for (i, frame) in encoded.frames.iter().enumerate().skip(1) {
15220 let decoded = decode_inter_frame_tile(
15221 &frame.tile,
15222 frame.mi_cols,
15223 frame.mi_rows,
15224 frame.base_q_idx,
15225 coded_w,
15226 coded_h,
15227 &reference,
15228 [None; 8],
15229 &CdefParams::default(),
15230 &LoopFilterParams::default(),
15231 false,
15232 false,
15233 Some(mc::InterpFilterKind::Regular),
15234 false,
15235 false,
15236 )
15237 .unwrap();
15238 assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg");
15239 assert_eq!(decoded.u, ffmpeg_frames[i].u, "frame {i} U vs ffmpeg");
15240 assert_eq!(decoded.v, ffmpeg_frames[i].v, "frame {i} V vs ffmpeg");
15241 reference = decoded;
15242 }
15243 }
15244}