forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB70849e0Tahinli2 months ago3122 commits

decode.rs23713 lines, 1.8 MiBHistoryRawDownload
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.
23use crate::hits::{hit, hit_do};
24
25use ec_av1_syntax::{
26 CdefParams, DeltaParams, LoopFilterParams, LoopRestorationParams,
27 SEG_LVL_ALT_LF_Y_V, SEG_LVL_ALT_Q, SegmentationParams, TileInfo,
28};
29use ec_core::{Error, Result};
30
31// lane-av112bit: the 12-bit warp refusals below are inline literals
32// (refusal_inventory.rs extracts them from the decode source); each names the
33// witness gap that keeps the path refused -- warp's reduce bits inherit the
34// 12-bit `conv_params->round_0` (warped_motion.c:295, convolve.h:81..86).
35// lane-av112bitc lifted the compound pair of the same family: the compound
36// combines absorb the CONV_BUF gain drop (`INTER_POST_ROUND - delta`, see
37// `mc::combine_compound`) and the six-frame 12-bit compound witness is
38// byte-exact vs ffmpeg. All sites are PARSE-time: a refused stream never
39// builds a warp predictor.
40
41/// Per-frame decode state, one instance per decoded stream (lane-thread1).
42///
43/// Every field here used to be a `thread_local!` static, which made a decode a
44/// function of the calling THREAD's history rather than of the bitstream alone
45/// -- and made frame-parallel decoding impossible, since a worker thread sees
46/// empty state. The cells keep exactly the interior mutability the statics
47/// had, so every read/write site is byte-identical; what changes is WHERE the
48/// state lives: `stream.rs` owns one `FrameCtx` and threads `&FrameCtx` down
49/// the decode call graph.
50///
51/// `Cell`/`RefCell` make this `!Sync` on purpose: a `FrameCtx` belongs to
52/// exactly one thread's decode, and is never shared between workers.
53/// One frame's in-loop filter intermediates, as [`FrameCtx::capture_stages`]
54/// asks for them: each plane's post-deblock (pre-CDEF) and post-CDEF
55/// (pre-restoration) samples, at the decoder's own plane stride.
56pub(crate) struct FilterStages {
57 /// Post-deblock, pre-CDEF planes (Y, U, V).
58 pub(crate) deblocked: [Vec<u16>; 3],
59 /// Post-CDEF, pre-restoration planes (Y, U, V).
60 pub(crate) cdefed: [Vec<u16>; 3],
61 /// Each plane's stride (and so its width in the buffers above).
62 pub(crate) stride: [usize; 3],
63}
64
65/// Takes whatever the last capturing decode left (see
66/// [`FrameCtx::capture_stages`]).
67#[allow(dead_code)] // read from the encoder's loop restoration search
68pub(crate) fn take_filter_stages(fctx: &FrameCtx) -> Option<FilterStages> {
69 fctx.stages.borrow_mut().take()
70}
71
72pub(crate) struct FrameCtx {
73 /// lane-av1lr: when set, the frame filter chain leaves its post-deblock
74 /// and post-CDEF planes in [`FrameCtx::stages`] for the ENCODER's loop
75 /// restoration search (spec 7.17 reads both: the stripe interior from
76 /// the post-CDEF plane, its 3-row border from the post-deblock one).
77 /// Off for every decode but that search, and off it costs one bool read
78 /// per frame and not a single copy.
79 pub(crate) capture_stages: std::cell::Cell<bool>,
80 pub(crate) stages: std::cell::RefCell<Option<FilterStages>>,
81 pub(crate) sb128_flag: std::cell::Cell<bool>,
82 /// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every
83 /// motion compensation of THIS frame runs, already resolved to a kernel.
84 /// `mc::predict` used to hardwire `Regular`, so the encoder's search,
85 /// trial and recon could only ever build a REGULAR prediction whatever
86 /// the frame header said; it lives here (and is copied by
87 /// [`filter_ctx_copy`]) so a tile-search worker thread reads the same
88 /// kernel the frame header wrote instead of the default.
89 pub(crate) interp_filter: std::cell::Cell<crate::mc::InterpFilterKind>,
90 /// lane-lossless: this frame's `CodedLossless` (spec 5.9.12) -- every
91 /// segment at `qindex == 0` with zero plane deltas. It forces TX_4X4 with
92 /// the Walsh-Hadamard transform on every plane, drops the `tx_type`
93 /// symbol and narrows `is_cfl_allowed` (libaom `read_tx_size`
94 /// (`decodeframe.c`), `read_tx_type` (`decodetxb.c`), `is_cfl_allowed`
95 /// (`blockd.h`)).
96 pub(crate) lossless_flag: std::cell::Cell<bool>,
97 /// lane-av1txr: this frame header's `disable_cdf_update` (spec 5.9.2).
98 /// When set, the tile reader must not adapt any CDF it reads, or its
99 /// tables drift away from the encoder's and the frame desyncs mid-tile
100 /// (libaom: `allow_update_cdf = allow_update_cdf &&
101 /// !cm->features.disable_cdf_update`, `decodeframe.c:2909`).
102 pub(crate) disable_cdf_update: std::cell::Cell<bool>,
103 pub(crate) cdef_bits: std::cell::Cell<u8>,
104 pub(crate) bit_depth: std::cell::Cell<u8>,
105 /// lane-av1mono: the sequence header's `color_config.mono_chrome` (spec
106 /// 5.5.2), i.e. `NumPlanes == 1`. libaom threads this as
107 /// `av1_num_planes(cm)` and every chroma read site is guarded by
108 /// `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`,
109 /// `:1208`) or bounded by `plane < num_planes`; a monochrome frame codes
110 /// NO `uv_mode`/`cfl`/`angle_delta_uv`/`palette_uv` symbol and NO chroma
111 /// coefficients on any block. Set once per frame from the sequence header
112 /// (like [`FrameCtx::bit_depth`]), so a mono frame decoded on a thread
113 /// that last saw a 4:2:0 one never inherits the wrong plane count.
114 pub(crate) mono_chrome: std::cell::Cell<bool>,
115 pub(crate) superres: std::cell::Cell<(u32, u32)>,
116 pub(crate) cdef_transmitted: std::cell::Cell<bool>,
117 pub(crate) cdef_sb_cols: std::cell::Cell<usize>,
118 pub(crate) cdef_idx_grid: std::cell::RefCell<Vec<u8>>,
119 pub(crate) delta_q_present: std::cell::Cell<bool>,
120 pub(crate) delta_q_res: std::cell::Cell<i32>,
121 pub(crate) current_q_idx: std::cell::Cell<i32>,
122 pub(crate) quant_deltas: std::cell::Cell<crate::quant::QuantDeltas>,
123 pub(crate) delta_lf_present: std::cell::Cell<bool>,
124 pub(crate) delta_lf_res: std::cell::Cell<i32>,
125 pub(crate) delta_lf_multi: std::cell::Cell<bool>,
126 pub(crate) current_delta_lf: std::cell::Cell<[i32; 4]>,
127 pub(crate) seg: std::cell::RefCell<SegmentationParams>,
128 pub(crate) seg_ids: std::cell::RefCell<Vec<u8>>,
129 pub(crate) prev_seg_ids: std::cell::RefCell<Vec<u8>>,
130 pub(crate) seg_mi_dims: std::cell::Cell<(usize, usize)>,
131 pub(crate) above_seg_pred: std::cell::RefCell<Vec<u8>>,
132 pub(crate) left_seg_pred: std::cell::RefCell<Vec<u8>>,
133 pub(crate) cur_segment_id: std::cell::Cell<u8>,
134 pub(crate) seg_tile_origin: std::cell::Cell<(usize, usize)>,
135 pub(crate) tx_select_inter: std::cell::Cell<bool>,
136 /// Whether the tile being decoded is an INTRA-ONLY frame's (key/intra-only
137 /// frame). libaom runs `set_txfm_ctxs` for EVERY block of EVERY frame
138 /// (`decodeframe.c` `parse_decode_block`), so an intra-only frame
139 /// maintains the `TXFM_CONTEXT` bands exactly like an inter one; only this
140 /// decoder's inter-side publishing was wired. See
141 /// [`Neighbours::fill_lf_grid_rect`]'s band publish.
142 pub(crate) intra_only: std::cell::Cell<bool>,
143 /// This FRAME's own `tx_mode == TxMode::Select`, set for EVERY frame
144 /// (intra included). [`Self::tx_select_inter`] cannot stand in for it:
145 /// an intrabc block rides an INTRA frame, but libaom still reads its
146 /// var-tx `txfm_partition` tree under the frame's `TxMode::Select`.
147 pub(crate) tx_select_frame: std::cell::Cell<bool>,
148 pub(crate) reduced_tx_set_inter: std::cell::Cell<bool>,
149 pub(crate) enable_filter_intra_inter: std::cell::Cell<bool>,
150 pub(crate) palette_pred: std::cell::RefCell<Option<Vec<u16>>>,
151 pub(crate) intrabc_mi_grid: std::cell::RefCell<Option<(crate::mvstack::MiGrid, usize, usize)>>,
152 pub(crate) intrabc_dv: std::cell::Cell<Option<(i32, i32)>>,
153 pub(crate) luma_tx_type: std::cell::Cell<TxType>,
154 pub(crate) intrabc_chroma_tx: std::cell::Cell<Option<TxType>>,
155 pub(crate) intra_in_inter_mode: std::cell::Cell<Option<(usize, bool)>>,
156 pub(crate) inter_strip_chroma: std::cell::Cell<Option<InterStripChroma>>,
157 pub(crate) inter_last_mc:
158 std::cell::Cell<Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>>,
159 pub(crate) enable_edge_filter: std::cell::Cell<bool>,
160 pub(crate) last_frame_wide_margin: std::cell::RefCell<Option<Picture>>,
161 pub(crate) reach_sb_px: std::cell::Cell<usize>,
162 pub(crate) grain_bit_depth: std::cell::Cell<u32>,
163 /// lane-wave1 step (i): this superblock's recorded pixel writes, see
164 /// [`ReconOp`]. Pushed by parse, replayed by [`flush_recon`].
165 pub(crate) recon_ops: std::cell::RefCell<Vec<ReconOp>>,
166 /// The queue buffer [`flush_recon`] just drained, kept for its capacity
167 /// so a superblock's records do not regrow the vector from nothing.
168 pub(crate) recon_spare: std::cell::RefCell<Vec<ReconOp>>,
169 /// lane-recoparse: the coefficient grids of the recorded ops above, one
170 /// buffer instead of a `Vec` per transform unit -- a recorded unit is
171 /// `(offset, len)` into it ([`Residual::Coeffs`]). Written by parse
172 /// before the op is published, read only by whoever replays that op, and
173 /// handed over WITH the ops at every drain point ([`wave_submit`],
174 /// [`flush_recon`]), so offsets are always relative to the live arena.
175 pub(crate) coeff_arena: std::cell::RefCell<Vec<i32>>,
176 /// [`recon_spare`](Self::recon_spare) for the arena, on the inline drain
177 /// path (a submitted job's arena travels to its worker instead).
178 pub(crate) coeff_spare: std::cell::RefCell<Vec<i32>>,
179 /// [`coeff_arena`](Self::coeff_arena) for the recorded PREDICTIONS
180 /// ([`PredSrc::Owned`]): same lifetime, same drain points.
181 pub(crate) pred_arena: std::cell::RefCell<Vec<u16>>,
182 pub(crate) pred_spare: std::cell::RefCell<Vec<u16>>,
183 /// lane-wave1 step (ii): the tile decoder's own planes, registered by
184 /// [`ReconInline`] while reconstruction runs INLINE (one recon thread).
185 /// `None` while the queue is in use (wavefront workers) and outside a
186 /// tile. See [`push_op`].
187 pub(crate) recon_planes: std::cell::Cell<Option<ReconPlanes>>,
188 /// lane-wave1 step (ii): the superblock wavefront this tile's recorded
189 /// writes are handed to, at more than one reconstruction thread.
190 pub(crate) wave: std::cell::RefCell<Option<std::sync::Arc<WaveState>>>,
191 /// lane-wave5 instrumentation only (`EC_AV1_WAVE_STATS`): when the parse
192 /// thread last handed a superblock to the wavefront.
193 pub(crate) wave_mark: std::cell::Cell<Option<std::time::Instant>>,
194}
195
196impl std::fmt::Debug for FrameCtx {
197 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198 f.write_str("FrameCtx")
199 }
200}
201
202impl FrameCtx {
203 /// A fresh context, every field at the default its thread-local
204 /// predecessor was born with.
205 pub(crate) fn new() -> Self {
206 Self {
207 // A DECODER context is seeded from the stream alone: every real
208 // decode overwrites this from the parsed sequence header
209 // (`set_sb128`, stream.rs). The encoder's own contexts start at
210 // the size this process encodes -- see [`FrameCtx::for_encoder`].
211 sb128_flag: std::cell::Cell::new(false),
212 interp_filter: std::cell::Cell::new(crate::mc::InterpFilterKind::Regular),
213 lossless_flag: std::cell::Cell::new(false),
214 disable_cdf_update: std::cell::Cell::new(false),
215 cdef_bits: std::cell::Cell::new(0),
216 bit_depth: std::cell::Cell::new(8),
217 mono_chrome: std::cell::Cell::new(false),
218 superres: std::cell::Cell::new((0, 8)),
219 cdef_transmitted: std::cell::Cell::new(false),
220 cdef_sb_cols: std::cell::Cell::new(0),
221 capture_stages: std::cell::Cell::new(false),
222 stages: std::cell::RefCell::new(None),
223 cdef_idx_grid: std::cell::RefCell::new(Vec::new()),
224 delta_q_present: std::cell::Cell::new(false),
225 delta_q_res: std::cell::Cell::new(1),
226 current_q_idx: std::cell::Cell::new(0),
227 quant_deltas: std::cell::Cell::new(crate::quant::QuantDeltas {
228 y_dc: 0,
229 u_dc: 0,
230 u_ac: 0,
231 v_dc: 0,
232 v_ac: 0,
233 }),
234 delta_lf_present: std::cell::Cell::new(false),
235 delta_lf_res: std::cell::Cell::new(1),
236 delta_lf_multi: std::cell::Cell::new(false),
237 current_delta_lf: std::cell::Cell::new([0; 4]),
238 seg: std::cell::RefCell::new(SegmentationParams::default()),
239 seg_ids: std::cell::RefCell::new(Vec::new()),
240 prev_seg_ids: std::cell::RefCell::new(Vec::new()),
241 seg_mi_dims: std::cell::Cell::new((0, 0)),
242 above_seg_pred: std::cell::RefCell::new(Vec::new()),
243 left_seg_pred: std::cell::RefCell::new(Vec::new()),
244 cur_segment_id: std::cell::Cell::new(0),
245 seg_tile_origin: std::cell::Cell::new((0, 0)),
246 tx_select_inter: std::cell::Cell::new(false),
247 tx_select_frame: std::cell::Cell::new(false),
248 intra_only: std::cell::Cell::new(false),
249 reduced_tx_set_inter: std::cell::Cell::new(false),
250 enable_filter_intra_inter: std::cell::Cell::new(false),
251 palette_pred: std::cell::RefCell::new(None),
252 intrabc_mi_grid: std::cell::RefCell::new(None),
253 intrabc_dv: std::cell::Cell::new(None),
254 luma_tx_type: std::cell::Cell::new(TxType::DctDct),
255 intrabc_chroma_tx: std::cell::Cell::new(None),
256 intra_in_inter_mode: std::cell::Cell::new(None),
257 inter_strip_chroma: std::cell::Cell::new(None),
258 inter_last_mc: std::cell::Cell::new(None),
259 enable_edge_filter: std::cell::Cell::new(false),
260 last_frame_wide_margin: std::cell::RefCell::new(None),
261 reach_sb_px: std::cell::Cell::new(crate::encode::SUPERBLOCK),
262 grain_bit_depth: std::cell::Cell::new(8),
263 recon_ops: std::cell::RefCell::new(Vec::new()),
264 recon_spare: std::cell::RefCell::new(Vec::new()),
265 coeff_arena: std::cell::RefCell::new(Vec::new()),
266 coeff_spare: std::cell::RefCell::new(Vec::new()),
267 pred_arena: std::cell::RefCell::new(Vec::new()),
268 pred_spare: std::cell::RefCell::new(Vec::new()),
269 recon_planes: std::cell::Cell::new(None),
270 wave: std::cell::RefCell::new(None),
271 wave_mark: std::cell::Cell::new(None),
272 }
273 }
274
275 /// A context for the ENCODER's own trial decodes: it starts at the
276 /// superblock size this process encodes (`crate::encode::sb128_on`) so
277 /// the mode search's `Reach` and the filter search's internal decodes
278 /// agree with the tile writer. A decoder never reads that knob -- doing
279 /// so coupled every decode to the encoder's process-global and raced the
280 /// 128-superblock decode gates against the encoder witness.
281 pub(crate) fn for_encoder() -> Self {
282 let ctx = Self::new();
283 let on = crate::encode::sb128_on();
284 ctx.sb128_flag.set(on);
285 ctx.reach_sb_px.set(if on { 128 } else { crate::encode::SUPERBLOCK });
286 ctx
287 }
288}
289
290/// `LocalKey::with` for a plain value: lets every former `STATIC.with(|c| ..)`
291/// site read `fctx.field.with(|c| ..)` unchanged. `LocalKey`'s own inherent
292/// `with` still wins for the scratch pools and gate counters that stay
293/// thread-local.
294pub(crate) trait WithRef {
295 fn with<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
296 f(self)
297 }
298}
299impl<T: ?Sized> WithRef for T {}
300
301/// A [`FrameCtx`] copy for one of [`crate::par`]'s filter worker threads.
302///
303/// `FrameCtx` is `!Sync` on purpose (a decode's state belongs to one thread),
304/// and the post-decode filter chain reads exactly these fields: the bit depth
305/// (every kernel's clamp and threshold shift), the segmentation table
306/// (`segment_id_at`/`lf_level` in the deblocker), the frame's superres state
307/// and the film-grain bit depth. Everything else keeps [`FrameCtx::new`]'s
308/// default -- a field that turns out to be read after all shows up as a hash
309/// mismatch in
310/// `a_real_stream_filters_identically_with_one_and_four_filter_threads`.
311pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx {
312 let out = FrameCtx::new();
313 out.bit_depth.set(fctx.bit_depth.get());
314 out.mono_chrome.set(fctx.mono_chrome.get());
315 out.interp_filter.set(fctx.interp_filter.get());
316 out.grain_bit_depth.set(fctx.grain_bit_depth.get());
317 out.superres.set(fctx.superres.get());
318 out.seg_mi_dims.set(fctx.seg_mi_dims.get());
319 out.seg.replace(fctx.seg.borrow().clone());
320 out.seg_ids.replace(fctx.seg_ids.borrow().clone());
321 // lane-b128m: the superblock size travels with the copy. A tile SEARCH
322 // worker (`encode::search_tiles`) gets its context from here, so dropping
323 // it made every worker search at 64 while the calling thread searched at
324 // 128 -- the bytes a frame came out as then depended on the tile thread
325 // count under `EC_AV1_SB128`.
326 out.sb128_flag.set(fctx.sb128_flag.get());
327 out.reach_sb_px.set(fctx.reach_sb_px.get());
328 out
329}
330
331use crate::cdf;
332use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
333use crate::encode::{Picture, Reach};
334use crate::intra::predict;
335use crate::mc;
336use crate::msac::SymbolDecoder;
337use crate::mvstack::{
338 ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME, LAST3_FRAME,
339 MiGrid, MiInfo, NO_REF1, NO_SIGN_BIAS, NeighbourRef, SignBiasTable, comp_reference_type_ctx,
340 find_mv_stack_with_sign_bias, mv16, mv32, reference_mode_ctx,
341 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx,
342 single_ref_p6_ctx, uni_comp_ref_p1_ctx,
343};
344use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
345use crate::transform::{TxType, dequant_and_inverse_typed_wh};
346
347const PARTITION_NONE: usize = 0;
348const PARTITION_HORZ: usize = 1;
349const PARTITION_VERT: usize = 2;
350const PARTITION_SPLIT: usize = 3;
351const PARTITION_HORZ_A: usize = 4;
352const PARTITION_HORZ_B: usize = 5;
353const PARTITION_VERT_A: usize = 6;
354const PARTITION_VERT_B: usize = 7;
355const PARTITION_HORZ_4: usize = 8;
356const PARTITION_VERT_4: usize = 9;
357const SB_MI: u32 = 16;
358const BLOCK_MI: u32 = 8;
359
360// lane-sb128 r1: this sequence's `use_128x128_superblock` (spec 5.5.1).
361// Every superblock-granular rule below (`delta_q`/`delta_lf`'s "is this the
362// superblock's own top-left mi?", the loop-restoration read's unit span, the
363// partition tree's own root level) keys off it; `SB_MI` stays the 64x64
364// *quadrant* size a 128 superblock is decoded in, which is also what the CDEF
365// grid is indexed by (libaom `read_cdef` reads one `cdef_idx` per 64x64
366// inside a 128 superblock).
367thread_local! {
368 /// lane-frame80: `EC_TRACE_COEFF_FRAME=<decode idx>` narrows the
369 /// `EC_TRACE_COEFF` rungs to a single frame in DECODE order (a 4K stream
370 /// prints gigabytes otherwise). Unset = every frame, as before.
371 static COEFF_TRACE_FRAME: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
372 static COEFF_TRACE_CUR: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
373}
374
375/// Called by [`crate::stream::decode_stream`] before each frame's tiles with
376/// that frame's DECODE-order index.
377pub fn set_coeff_trace_frame(idx: usize) {
378 COEFF_TRACE_FRAME.with(|c| {
379 if c.get().is_none() {
380 let want = match crate::envflags::var("EC_TRACE_COEFF_FRAME") {
381 Ok(v) => v.parse::<usize>().unwrap_or(usize::MAX),
382 // unset: keep tracing every frame, as before this rung existed
383 Err(_) => usize::MAX - 1,
384 };
385 c.set(Some(want));
386 }
387 });
388 COEFF_TRACE_CUR.with(|c| c.set(idx));
389 if crate::envflags::env_flag!("EC_TRACE_COEFF") {
390 eprintln!("EC_COEFF_FRAME decode_idx={idx}");
391 }
392}
393
394pub(crate) fn coeff_trace_on() -> bool {
395 if !crate::envflags::env_flag!("EC_TRACE_COEFF") {
396 return false;
397 }
398 match COEFF_TRACE_FRAME.with(|c| c.get()) {
399 // no `set_coeff_trace_frame` caller (direct tile-decode tests), or the
400 // env var unset: trace every frame.
401 None => true,
402 Some(w) if w >= usize::MAX - 1 => true,
403 Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w,
404 }
405}
406
407
408/// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
409pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {
410 fctx.sb128_flag.with(|c| c.set(v));
411 crate::encode::set_reach_superblock_px(if v { 128 } else { 64 }, fctx);
412}
413
414/// Sets [`FrameCtx::lossless_flag`] (called once per frame from `stream.rs`).
415pub(crate) fn set_lossless(v: bool, fctx: &crate::decode::FrameCtx) {
416 fctx.lossless_flag.with(|c| c.set(v));
417}
418
419/// This frame's `CodedLossless` -- see [`FrameCtx::lossless_flag`].
420pub(crate) fn lossless(fctx: &crate::decode::FrameCtx) -> bool {
421 fctx.lossless_flag.with(|c| c.get())
422}
423
424/// Sets [`FrameCtx::disable_cdf_update`] (called once per frame from
425/// `stream.rs`).
426pub(crate) fn set_disable_cdf_update(v: bool, fctx: &crate::decode::FrameCtx) {
427 fctx.disable_cdf_update.with(|c| c.set(v));
428}
429
430/// This frame's `disable_cdf_update`, for the tile readers --
431/// [`msac::SymbolDecoder::set_cdf_update`](crate::msac::SymbolDecoder::set_cdf_update).
432pub(crate) fn cdf_update_disabled(fctx: &crate::decode::FrameCtx) -> bool {
433 fctx.disable_cdf_update.with(|c| c.get())
434}
435
436/// The transform side a block of `side` pixels codes: its own (capped at the
437/// caller's own largest) normally, 4 on a lossless frame, where libaom's
438/// `read_tx_size` returns TX_4X4 before it looks at anything else
439/// (`decodeframe.c`: `if (xd->lossless[xd->mi[0]->segment_id]) return
440/// TX_4X4;`).
441pub(crate) fn lossless_tx(px: usize, fctx: &crate::decode::FrameCtx) -> usize {
442 if lossless(fctx) { 4 } else { px }
443}
444
445/// `is_cfl_allowed` (libaom `blockd.h`): CfL is offered on a block up to
446/// 32x32 -- but on a LOSSLESS frame only when the block's CHROMA plane block
447/// is exactly BLOCK_4X4, i.e. (at 4:2:0) a luma block of 8x8 or smaller.
448/// Getting this wrong picks the 14-symbol CFL `uv_mode` alphabet where libaom
449/// picks the 13-symbol one (class `wrong-alphabet-same-value`).
450pub(crate) fn cfl_allowed_px(bw: usize, bh: usize, fctx: &crate::decode::FrameCtx) -> bool {
451 if lossless(fctx) {
452 bw <= 8 && bh <= 8
453 } else {
454 bw <= 32 && bh <= 32
455 }
456}
457
458fn sb128(fctx: &crate::decode::FrameCtx) -> bool {
459 fctx.sb128_flag.with(|c| c.get())
460}
461
462/// This sequence's superblock size in mi units (16 = 64x64, 32 = 128x128).
463pub(crate) fn sb_mi_cur(fctx: &crate::decode::FrameCtx) -> u32 {
464 if sb128(fctx) { SB_MI * 2 } else { SB_MI }
465}
466
467// How many real 128-level partition symbols this decoder has read, and how
468// many superblocks resolved to `PARTITION_SPLIT` (coded or forced) -- the
469// gate's proof a `--sb-size=128` stream exercised the 128 partition root.
470thread_local! {
471 static PART128_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
472 static PART128_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
473 static PART128_GATHERED_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
474}
475
476/// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the
477/// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec
478/// 5.11.4), which this decoder used to read and throw away.
479#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
480pub(crate) fn part128_gathered_symbols() -> usize {
481 PART128_GATHERED_SYMBOLS.with(|c| c.get())
482}
483
484/// Current value of [`PART128_SYMBOLS`].
485#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
486pub(crate) fn part128_symbols() -> usize {
487 PART128_SYMBOLS.with(|c| c.get())
488}
489
490/// Current value of [`PART128_SPLIT_HITS`].
491#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
492pub(crate) fn part128_split_hits() -> usize {
493 PART128_SPLIT_HITS.with(|c| c.get())
494}
495
496/// [`gather`] over an alphabet of any length -- the 128-level partition CDF
497/// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec
498/// `partition_cdf_length`), so its forced-split gather sums 5 elements where
499/// the 64/32 levels sum 6.
500pub(crate) fn gather_of(cdf: &[u16], elements: &[usize]) -> [u16; 3] {
501 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
502 [32768 - split, 32768, 0]
503}
504
505/// [`VERT_ALIKE`]/[`HORZ_ALIKE`] without the 1:4 arms, for the 128 root.
506pub(crate) const VERT_ALIKE128: [usize; 5] = [2, PARTITION_SPLIT, 4, 6, 7];
507pub(crate) const HORZ_ALIKE128: [usize; 5] = [1, PARTITION_SPLIT, 4, 5, 6];
508
509// How many `use_filter_intra` symbols this decoder has read as `1`, across
510// every call on the current thread -- the cheap counter [`filter_intra_hits`] gate
511// tests read (before/after, not the absolute value) to prove a stream
512// actually exercised the filter-intra predictor rather than silently
513// skipping it.
514thread_local! {
515 static FILTER_INTRA_HITS: std::cell::Cell<usize> =
516 const { std::cell::Cell::new(0) };
517}
518
519/// Current value of [`FILTER_INTRA_HITS`].
520#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
521pub(crate) fn filter_intra_hits() -> usize {
522 FILTER_INTRA_HITS.with(|c| c.get())
523}
524
525// lane-fiinter r1: how many of those `use_filter_intra == 1` symbols belonged
526// to an INTRA block inside an INTER frame (`read_intra_block_mode_info`'s own
527// `read_filter_intra_mode_info` call), which no gate exercised before this
528// round -- every inter gate recipe passed `--enable-filter-intra=0`.
529thread_local! {
530 static INTRA_IN_INTER_FILTER_INTRA_HITS: std::cell::Cell<usize> =
531 const { std::cell::Cell::new(0) };
532}
533
534/// Current value of [`INTRA_IN_INTER_FILTER_INTRA_HITS`].
535#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
536pub(crate) fn intra_in_inter_filter_intra_hits() -> usize {
537 INTRA_IN_INTER_FILTER_INTRA_HITS.with(|c| c.get())
538}
539
540// lane-angleinter r1: how many INTRA blocks inside an INTER frame carried a
541// nonzero `angle_delta_y` / `angle_delta_uv` (`read_intra_angle_info`). Both
542// arms refused a nonzero luma delta before this round, and no inter gate
543// enabled `--enable-angle-delta` (aomenc's own default is 1).
544thread_local! {
545 static INTRA_IN_INTER_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> =
546 const { std::cell::Cell::new(0) };
547 static INTRA_IN_INTER_ANGLE_DELTA_UV_HITS: std::cell::Cell<usize> =
548 const { std::cell::Cell::new(0) };
549}
550
551/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_Y_HITS`].
552#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
553pub(crate) fn intra_in_inter_angle_delta_y_hits() -> usize {
554 INTRA_IN_INTER_ANGLE_DELTA_Y_HITS.with(|c| c.get())
555}
556
557/// Current value of [`INTRA_IN_INTER_ANGLE_DELTA_UV_HITS`].
558#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
559pub(crate) fn intra_in_inter_angle_delta_uv_hits() -> usize {
560 INTRA_IN_INTER_ANGLE_DELTA_UV_HITS.with(|c| c.get())
561}
562
563// lane-uv8 r1: the three non-DC chroma mode classes an INTRA 8x8 leaf inside
564// an INTER frame ([`decode_inter_block8`]'s intra arm) can carry -- the arm
565// read `uv_mode` and then refused everything but `DC_PRED`. Counted here and
566// nowhere else so the gate's assert cannot be satisfied by a >=16x16 block.
567thread_local! {
568 static INTRA_IN_INTER8_UV_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
569 static INTRA_IN_INTER8_UV_SMOOTH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
570 static INTRA_IN_INTER8_UV_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
571}
572
573thread_local! {
574 static INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
575}
576
577/// Nonzero luma angle deltas coded by an intra 8x8 leaf inside an inter frame
578/// (lane-leaf8tx r1) -- counted only in [`decode_inter_block8`]'s intra arm.
579#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
580pub(crate) fn intra_in_inter8_angle_delta_y_hits() -> usize {
581 INTRA_IN_INTER8_ANGLE_DELTA_Y_HITS.with(|c| c.get())
582}
583
584/// `(directional, smooth/paeth, CfL)` chroma modes coded by an intra 8x8 leaf
585/// inside an inter frame -- see [`INTRA_IN_INTER8_UV_DIR_HITS`].
586#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
587pub(crate) fn intra_in_inter8_uv_hits() -> (usize, usize, usize) {
588 (
589 INTRA_IN_INTER8_UV_DIR_HITS.with(|c| c.get()),
590 INTRA_IN_INTER8_UV_SMOOTH_HITS.with(|c| c.get()),
591 INTRA_IN_INTER8_UV_CFL_HITS.with(|c| c.get()),
592 )
593}
594
595// lane-realworld r1: this frame's `cdef.bits` (spec 5.9.19), threaded into
596// [`maybe_read_cdef_idx`] the same way [`ENABLE_EDGE_FILTER`] threads a
597// frame-level flag through the recursive block decode -- `0` (the default)
598// makes every call a true no-op, matching every existing gate stream's
599// `cdef_bits == 0` behaviour exactly.
600// lane-realworld r8: the sequence header's `color_config.bit_depth`, set
601// once per `decode_key_frame_tile_with_cdfs`/`decode_inter_frame_tile_with_cdfs`
602// call the same way `CDEF_BITS` is above. `stream.rs`'s own refusal still
603// blocks every non-8-bit stream from reaching a decode call, so this is `8`
604// on every path that runs today -- threading it now (rather than the literal
605// `8`) is stage 1 of widening past that refusal without re-deriving every
606// clamp bound later. `PlaneBuf`'s sample storage stays `u16` regardless of
607// depth (this decoder's own internal choice, matches dav1d/libaom).
608/// `(1 << bit_depth) - 1` — the reconstruction clamp bound for the current
609/// stream's [`BIT_DEPTH`], replacing the crate-wide literal `255`.
610pub(crate) fn sample_max(fctx: &crate::decode::FrameCtx) -> i32 {
611 (1i32 << fctx.bit_depth.with(std::cell::Cell::get)) - 1
612}
613/// The current stream's bit depth, for callers (e.g. dequant) that need the
614/// raw value rather than the derived clamp bound.
615pub(crate) fn bit_depth(fctx: &crate::decode::FrameCtx) -> u8 {
616 fctx.bit_depth.with(std::cell::Cell::get)
617}
618/// Sets [`BIT_DEPTH`] for the current thread, called once per frame from
619/// [`crate::stream`]'s decode loop.
620pub(crate) fn set_bit_depth(bit_depth: u8, fctx: &crate::decode::FrameCtx) {
621 fctx.bit_depth.with(|c| c.set(bit_depth));
622}
623
624/// This stream's `mono_chrome` (see [`FrameCtx::mono_chrome`]): a
625/// monochrome frame has `NumPlanes == 1`, so no block codes any chroma
626/// symbol or chroma coefficient and the output picture is luma only.
627pub(crate) fn mono(fctx: &crate::decode::FrameCtx) -> bool {
628 fctx.mono_chrome.with(std::cell::Cell::get)
629}
630
631/// Sets [`mono`] for the current thread, called once per frame from
632/// [`crate::stream`]'s decode loop like [`set_bit_depth`].
633pub(crate) fn set_mono(mono_chrome: bool, fctx: &crate::decode::FrameCtx) {
634 fctx.mono_chrome.with(|c| c.set(mono_chrome));
635}
636
637 /// This frame's superres state: `(upscaled_width, superres_denom)`, or
638 /// `(0, 8)` when the frame is not scaled. Spec 7.16's upscale runs
639 /// between CDEF and loop restoration, so LOOP RESTORATION -- unit grid,
640 /// `read_lr`'s unit corners and the pixel filters themselves -- works in
641 /// UPSCALED coordinates while deblock and CDEF work in downscaled ones
642 /// (libaom `av1_superres_upscale` in `decodeframe.c`, and
643 /// `av1_loop_restoration_corners_in_sb`'s own `mi_to_num_x`/`denom_x`
644 /// superres arms). Set once per frame from [`crate::stream`]'s decode
645 /// loop, like [`BIT_DEPTH`], and reset to `(0, 8)` on an unscaled frame
646 /// so a later frame never inherits it.
647
648/// Sets [`SUPERRES`] for the current thread. `upscaled_width` is 0 (and
649/// `denom` 8) for a frame that is not superres-scaled.
650pub(crate) fn set_superres(upscaled_width: u32, denom: u32, fctx: &crate::decode::FrameCtx) {
651 fctx.superres.with(|c| c.set((upscaled_width, denom)));
652}
653
654/// `(upscaled_width, superres_denom)` when this frame is superres-scaled
655/// (libaom `av1_superres_scaled`), else `None`.
656pub(crate) fn superres(fctx: &crate::decode::FrameCtx) -> Option<(u32, u32)> {
657 let (w, d) = fctx.superres.with(std::cell::Cell::get);
658 (w > 0 && d != 8).then_some((w, d))
659}
660// Whether this superblock's single CDEF unit (this decoder has no 128x128
661// SB, so the SB IS the CDEF unit) has already had its `cdef_idx` literal
662// read -- reset to `false` at the top of each superblock in the two tile
663// loops, spec `read_cdef`'s `cdef_transmitted[index]`.
664// Number of superblock columns in the current tile's grid, so
665// [`maybe_read_cdef_idx`] can turn an `(mi_r, mi_c)` into a flat index into
666// [`CDEF_IDX_GRID`].
667// One resolved `cdef_idx` per superblock, read by [`apply_cdef`] to select
668// which of the header's `1 << cdef.bits` strength pairs applies to that
669// superblock's samples.
670// How many real (`cdef.bits > 0`) `cdef_idx` literals [`maybe_read_cdef_idx`]
671// has read, across every call on the current thread -- the gate's proof that a
672// `cdef_bits > 0` stream actually reached the new reader rather than every
673// superblock coincidentally being all-skip.
674thread_local! {
675 static CDEF_IDX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
676}
677
678// How many times a warp was suppressed for one PLANE because that plane's own
679// block is narrower or shorter than 8 (`av1_init_warp_params`'s own bail-out,
680// reconinter.c) -- the gate's proof that a stream really carries the shape,
681// since the square `side`/`chroma_side` can be 8 or more while the plane's
682// true block is 4 wide (an 8x16 luma block's 4x8 chroma).
683thread_local! {
684 static WARP_PLANE_SUPPRESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
685}
686
687/// Current value of [`WARP_PLANE_SUPPRESS_HITS`].
688#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
689pub(crate) fn warp_plane_suppress_hits() -> usize {
690 WARP_PLANE_SUPPRESS_HITS.with(|c| c.get())
691}
692
693/// `av1_init_warp_params` (libaom reconinter.c): warp is decided per PLANE and
694/// bails out at `block_width < 8 || block_height < 8`, so the plane's OWN
695/// block dimensions decide it -- never the square `side`/`chroma_side`, which
696/// for a rectangular luma block (8x16, 16x8) or a PARTITION_HORZ/VERT strip is
697/// bigger than the real block in one axis.
698pub(crate) fn warp_plane_allowed(w: usize, h: usize) -> bool {
699 if w >= 8 && h >= 8 {
700 return true;
701 }
702 hit!(WARP_PLANE_SUPPRESS_HITS);
703 false
704}
705
706/// Current value of [`CDEF_IDX_HITS`].
707#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
708pub(crate) fn cdef_idx_hits() -> usize {
709 CDEF_IDX_HITS.with(|c| c.get())
710}
711
712// lane-t900 r6: gate proof for the three r2-r4 root causes that shipped with no
713// counter -- the in-inter tx-depth context (`tx_size_context_txfm_rect`), the
714// non-chroma-reference block that must LEAVE its neighbours' chroma coefficient
715// contexts alone, and the intra-edge filter neighbour pair taken mi-exact
716// instead of from the coarse 16x16 cell.
717thread_local! {
718 static INTRA_IN_INTER_TXCTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
719 static NON_CHROMA_REF_CTX_SKIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
720 static EDGE_FILTER_MI_FIX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
721}
722
723/// Current value of [`INTRA_IN_INTER_TXCTX_HITS`].
724#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
725pub(crate) fn intra_in_inter_txctx_hits() -> usize {
726 INTRA_IN_INTER_TXCTX_HITS.with(|c| c.get())
727}
728
729/// Current value of [`NON_CHROMA_REF_CTX_SKIP_HITS`].
730#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
731pub(crate) fn non_chroma_ref_ctx_skip_hits() -> usize {
732 NON_CHROMA_REF_CTX_SKIP_HITS.with(|c| c.get())
733}
734
735/// Current value of [`EDGE_FILTER_MI_FIX_HITS`].
736#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
737pub(crate) fn edge_filter_mi_fix_hits() -> usize {
738 EDGE_FILTER_MI_FIX_HITS.with(|c| c.get())
739}
740
741// lane-realworld r4: this frame's `delta.q_present` (spec 5.9.17) and its
742// actual step (`1 << delta.q_res`, already the real multiplier, not the raw
743// 2-bit field). `false`/`1` (the defaults) make [`maybe_read_delta_q`] a
744// true no-op, matching every existing gate stream's `delta_q_present == 0`
745// behaviour exactly, the same corner-cut [`CDEF_BITS`] takes above.
746// The running quantizer index (spec `CurrentQIndex`, libaom
747// `xd->current_base_qindex`) -- reset to the frame's own `base_q_idx` at the
748// top of every tile (spec `decode_tile`), carried across superblocks within
749// that tile, and mutated only by [`maybe_read_delta_q`]. Read back at the
750// dequantization call sites instead of the frame-constant `base_q_idx`.
751// This frame's own per-plane DC/AC quantizer-index deltas (lane-sbpart r11,
752// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- frame-constant (not
753// per-superblock like [`CURRENT_Q_IDX`]), set once per frame decode and read
754// back at every dequantization call site keyed on which plane it is doing.
755// How many real `delta_q_present` symbol groups [`maybe_read_delta_q`] has
756// read, across every call on the current thread -- the gate's proof that a
757// `delta_q_present` stream actually reached the new reader.
758thread_local! {
759 static DELTA_Q_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
760}
761
762/// Current value of [`DELTA_Q_HITS`].
763#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
764pub(crate) fn delta_q_hits() -> usize {
765 DELTA_Q_HITS.with(|c| c.get())
766}
767
768/// This frame's [`QUANT_DELTAS`] `(dc, ac)` pair for plane `plane_idx` (0 =
769/// Y, 1 = U, 2 = V) -- luma has no coded `ac` delta (spec 5.9.12 never reads
770/// one), so it is always `0` here.
771fn plane_q_delta(plane_idx: usize, fctx: &crate::decode::FrameCtx) -> (i32, i32) {
772 let d = fctx.quant_deltas.with(|c| c.get());
773 match plane_idx {
774 0 => (d.y_dc, 0),
775 1 => (d.u_dc, d.u_ac),
776 _ => (d.v_dc, d.v_ac),
777 }
778}
779
780/// `read_delta_qindex`/`read_delta_q_params` (spec 5.11.10, libaom
781/// `decodemv.c:85-146,735-770`), called right after [`maybe_read_cdef_idx`]
782/// at every block-decode call site (spec order `skip -> cdef -> delta_q`).
783/// A no-op when `delta_q_present` is unset, or when this block is not at the
784/// superblock's own top-left MI position (`b_row == 0 && b_col == 0` in
785/// libaom, collapsed here to a position check since a partition tree's
786/// top-left leaf is the only block that can ever land there), or when that
787/// leaf both *is* the whole superblock and is `skip` (the one case libaom
788/// itself skips the read, state carrying over unchanged).
789fn maybe_read_delta_q(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool, fctx: &crate::decode::FrameCtx) {
790 if !fctx.delta_q_present.with(|c| c.get()) {
791 return;
792 }
793 let sb_mi = sb_mi_cur(fctx) as usize;
794 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
795 return;
796 }
797 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
798 // computed against the sequence's own superblock size (lane-sb128b r1:
799 // it used to be hardcoded against 64 and disabled under `sb128`, which a
800 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
801 // wrong).
802 if is_whole_sb && skip {
803 return;
804 }
805 let mut abs = dec.symbol(&mut cdfs.delta_q) as i32;
806 const DELTA_Q_SMALL: i32 = 3;
807 if abs >= DELTA_Q_SMALL {
808 let rem_bits = dec.literal(3) + 1;
809 let thr = (1i32 << rem_bits) + 1;
810 abs = dec.literal(rem_bits) as i32 + thr;
811 }
812 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
813 let reduced = if sign_negative { -abs } else { abs };
814 hit!(DELTA_Q_HITS);
815 let res = fctx.delta_q_res.with(|c| c.get());
816 fctx.current_q_idx.with(|c| c.set((c.get() + reduced * res).clamp(1, 255)));
817}
818
819// lane-realworld r5: this frame's `delta.lf_present`/`lf_res`/`lf_multi`
820// (spec 5.9.18) -- same no-op-by-default corner-cut as `DELTA_Q_PRESENT`.
821// The running per-plane/direction loop-filter delta (spec `DeltaLF[i]`,
822// `i` in `0..FRAME_LF_COUNT`) -- reset to `[0; 4]` at the top of every tile,
823// mutated only by [`maybe_read_delta_lf`]. `!delta_lf_multi` mode only ever
824// updates index 0 and every reader treats that as the value for all 4
825// indices (spec `read_delta_lf_params`'s own single-cdf branch).
826// How many real `delta_lf_present` symbol groups [`maybe_read_delta_lf`] has
827// read -- the gate's proof the reader fired, mirroring [`DELTA_Q_HITS`].
828thread_local! {
829 static DELTA_LF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
830}
831
832/// Current value of [`DELTA_LF_HITS`].
833#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
834pub(crate) fn delta_lf_hits() -> usize {
835 DELTA_LF_HITS.with(|c| c.get())
836}
837
838/// `read_delta_lflevel`/`read_delta_lf_params` (spec 5.11.11, libaom
839/// `decodemv.c:99-146,735-770`) -- same shape and same call-site gating as
840/// [`maybe_read_delta_q`] (spec order `delta_q -> delta_lf`), looped over
841/// `FRAME_LF_COUNT = 4` planes/directions when `delta_lf_multi` is set, or
842/// read once into index 0 otherwise.
843fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, is_whole_sb: bool, skip: bool, fctx: &crate::decode::FrameCtx) {
844 if !fctx.delta_lf_present.with(|c| c.get()) {
845 return;
846 }
847 let sb_mi = sb_mi_cur(fctx) as usize;
848 if mi_r % sb_mi != 0 || mi_c % sb_mi != 0 {
849 return;
850 }
851 // `is_whole_sb` is the caller's "this leaf IS the superblock" flag,
852 // computed against the sequence's own superblock size (lane-sb128b r1:
853 // it used to be hardcoded against 64 and disabled under `sb128`, which a
854 // `PARTITION_NONE` 128x128 root -- itself the whole superblock -- makes
855 // wrong).
856 if is_whole_sb && skip {
857 return;
858 }
859 let multi = fctx.delta_lf_multi.with(|c| c.get());
860 let res = fctx.delta_lf_res.with(|c| c.get());
861 let count = if multi { 4 } else { 1 };
862 let mut cur = fctx.current_delta_lf.with(|c| c.get());
863 for i in 0..count {
864 let mut abs = if multi {
865 dec.symbol(&mut cdfs.delta_lf_multi[i]) as i32
866 } else {
867 dec.symbol(&mut cdfs.delta_lf) as i32
868 };
869 const DELTA_LF_SMALL: i32 = 3;
870 if abs >= DELTA_LF_SMALL {
871 let rem_bits = dec.literal(3) + 1;
872 let thr = (1i32 << rem_bits) + 1;
873 abs = dec.literal(rem_bits) as i32 + thr;
874 }
875 let sign_negative = if abs != 0 { dec.literal(1) != 0 } else { true };
876 let reduced = if sign_negative { -abs } else { abs };
877 cur[i] = (cur[i] + reduced * res).clamp(-63, 63);
878 hit!(DELTA_LF_HITS);
879 }
880 fctx.current_delta_lf.with(|c| c.set(cur));
881}
882
883/// `read_cdef` (spec 5.11.56, libaom `decodemv.c:read_cdef`), called right
884/// after `skip` is known at every block-decode call site. A no-op at
885/// `cdef.bits == 0` (0-bit literal, nothing to consume) -- and
886/// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
887/// `allow_intrabc`, so neither needs a separate check here. Reads once per
888/// superblock, at the first non-skip block.
889fn maybe_read_cdef_idx(
890 dec: &mut SymbolDecoder,
891 mi_r: usize,
892 mi_c: usize,
893 // The reading BLOCK's own span in 4x4 mode-info units: a block wider or
894 // taller than one 64x64 CDEF unit is the first non-skip block of EVERY
895 // unit it covers, so its one literal drives all of them (lane-b128r).
896 (w_mi, h_mi): (usize, usize),
897 skip: bool,
898 fctx: &crate::decode::FrameCtx,
899) {
900 let bits = fctx.cdef_bits.with(|c| c.get());
901 if bits == 0 || skip || fctx.cdef_transmitted.with(|c| c.get()) {
902 return;
903 }
904 let idx = dec.literal(u32::from(bits)) as u8;
905 fctx.cdef_transmitted.with(|c| c.set(true));
906 hit!(CDEF_IDX_HITS);
907 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
908 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
909 if sb_cols > 0 {
910 // lane-b128r: libaom's four CDEF units of a 128 superblock all read
911 // their strength off the MB_MODE_INFO of the first non-skip block in
912 // their own unit -- and a block that COVERS several units (the 128
913 // root's own 128x128 block, the only one there is) is that block for
914 // every unit it covers, so one literal drives all four. This grid is
915 // per 64x64 unit, so the read stamps every unit the block covers; one
916 // that is smaller than a unit stamps exactly the cell it always did.
917 let (rows, cols) = (
918 (h_mi / SB_MI as usize).max(1),
919 (w_mi / SB_MI as usize).max(1),
920 );
921 fctx.cdef_idx_grid.with(|g| {
922 let mut g = g.borrow_mut();
923 for dr in 0..rows {
924 for dc in 0..cols {
925 let i = (sb_r + dr) * sb_cols + sb_c + dc;
926 if sb_c + dc < sb_cols && i < g.len() {
927 g[i] = idx;
928 }
929 }
930 }
931 });
932 }
933}
934
935// ---------------------------------------------------------------------------
936// lane-seg: segmentation. Header (spec 5.9.14) is parsed by `ec-av1-syntax`;
937// this block is the per-block `segment_id` reader (spec 5.11.7-5.11.9) plus
938// the two consumers a real stream exercises: the per-segment quantizer index
939// (spec 7.12.2 `get_qindex`) and the per-segment loop-filter level
940// (spec 7.14.4). Shapes follow libaom `decodemv.c:read_segment_id`/
941// `read_intra_segment_id`/`read_inter_segment_id` and
942// `pred_common.h:av1_get_spatial_seg_pred` -- note libaom returns the SPATIAL
943// PREDICTION (not 0) from `read_segment_id` when the block is `skip`, which
944// is what the oracle every gate here compares against actually does.
945thread_local! {
946 /// `CurrentSegmentIds`: this frame's own map, `mi_rows * mi_cols` entries
947 /// with stride `mi_cols` (NOT the padded `Neighbours` grid stride).
948 /// `PrevSegmentIds`: the primary reference frame's saved map, empty when
949 /// this frame has no primary reference (spec `load_previous_segment_ids`).
950 /// `(mi_rows, mi_cols)` for both maps above.
951 /// `AboveSegPredContext` (per mi column) / `LeftSegPredContext` (per mi
952 /// row) -- spec 5.11.9's own `seg_id_predicted` neighbour state, which
953 /// libaom keeps on the neighbouring `mbmi->seg_id_predicted` instead.
954 /// The block currently being decoded -- read back by [`block_q_idx`].
955 /// The tile's own top-left mi position, for `AvailU`/`AvailL`.
956 /// How many real `segment_id` symbols were read, and the set of segment
957 /// ids any block ended up with -- the gate's proof the feature fired.
958 static SEG_ID_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
959 static SEG_IDS_SEEN: std::cell::Cell<u8> = const { std::cell::Cell::new(0) };
960 /// lane-golomb2: the (lowest, highest) quantizer index any block has been
961 /// dequantized with, i.e. `block_q_idx`'s own span. A gate that means to
962 /// exercise `SEG_LVL_ALT_Q` needs a stream where this span is WIDER than
963 /// zero (class `gate-blind-to-feature`): segmentation being enabled says
964 /// nothing about the segments carrying distinct quantizers.
965 static BLOCK_Q_SPAN: std::cell::Cell<(i32, i32)> = const { std::cell::Cell::new((i32::MAX, i32::MIN)) };
966 /// How many `seg_id_predicted` symbols were read (temporal update).
967 static SEG_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
968}
969
970/// Installs this frame's segmentation parameters and allocates its map, with
971/// `prev` the primary reference frame's saved map (spec
972/// `load_previous_segment_ids`; `None` for `PRIMARY_REF_NONE` or an empty
973/// slot). Called once per frame, whether or not segmentation is enabled.
974pub(crate) fn set_segmentation(
975 seg: SegmentationParams,
976 mi_rows: usize,
977 mi_cols: usize,
978 prev: Option<&[u8]>, fctx: &crate::decode::FrameCtx,
979) {
980 if crate::envflags::env_flag!("EC_HDR") {
981 eprintln!(
982 "EC_SEGHDR enabled={} update_map={} temporal={} preskip={} last_active={} data={:?}",
983 seg.enabled, seg.update_map, seg.temporal_update, seg.seg_id_pre_skip, seg.last_active_seg_id, seg.feature_data
984 );
985 }
986 fctx.seg.with(|s| *s.borrow_mut() = seg);
987 fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols)));
988 fctx.seg_ids.with(|m| *m.borrow_mut() = vec![0u8; mi_rows * mi_cols]);
989 fctx.prev_seg_ids.with(|m| {
990 let mut m = m.borrow_mut();
991 m.clear();
992 if let Some(p) = prev {
993 if p.len() == mi_rows * mi_cols {
994 m.extend_from_slice(p);
995 }
996 }
997 });
998 fctx.above_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_cols]);
999 fctx.left_seg_pred.with(|m| *m.borrow_mut() = vec![0u8; mi_rows]);
1000 fctx.cur_segment_id.with(|c| c.set(0));
1001}
1002
1003/// This frame's decoded segment map, to be stored into whichever reference
1004/// slots `refresh_frame_flags` names (spec 7.20's `SavedSegmentIds`).
1005pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec<u8> {
1006 fctx.seg_ids.with(|m| m.borrow().clone())
1007}
1008
1009/// How many `segment_id` symbols have been read (never reset per frame).
1010#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1011pub(crate) fn segment_id_hits() -> usize {
1012 SEG_ID_HITS.with(|c| c.get())
1013}
1014
1015/// How many distinct segment ids any decoded block has carried.
1016#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1017pub(crate) fn segment_ids_seen() -> usize {
1018 SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
1019}
1020
1021/// The lowest and highest quantizer index any decoded block was dequantized
1022/// with (`(i32::MAX, i32::MIN)` when nothing decoded).
1023#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1024pub(crate) fn block_q_span() -> (i32, i32) {
1025 BLOCK_Q_SPAN.with(|c| c.get())
1026}
1027
1028/// How many `seg_id_predicted` symbols have been read (temporal update).
1029#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1030pub(crate) fn segment_pred_hits() -> usize {
1031 SEG_PRED_HITS.with(|c| c.get())
1032}
1033
1034/// Resets the segmentation hit counters (gate setup).
1035#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1036pub(crate) fn reset_segment_hits() {
1037 SEG_ID_HITS.with(|c| c.set(0));
1038 SEG_IDS_SEEN.with(|c| c.set(0));
1039 SEG_PRED_HITS.with(|c| c.set(0));
1040 BLOCK_Q_SPAN.with(|c| c.set((i32::MAX, i32::MIN)));
1041}
1042
1043/// `seg_feature_active_idx(segment_id, feature)` for the frame currently
1044/// being decoded, with its `FeatureData` value.
1045fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option<i32> {
1046 fctx.seg.with(|s| {
1047 let s = s.borrow();
1048 s.feature_active(segment_id, feature)
1049 .then(|| i32::from(s.feature_data[segment_id][feature]))
1050 })
1051}
1052
1053/// `get_qindex(ignoreDeltaQ = 0, segment_id)` (spec 7.12.2, libaom
1054/// `av1_get_qindex`) for the block currently being decoded: the running
1055/// `CurrentQIndex` shifted by this block's segment's `SEG_LVL_ALT_Q` data.
1056/// Every dequant call site reads the block's quantizer through here.
1057fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 {
1058 let base = fctx.current_q_idx.with(|c| c.get());
1059 let seg_id = fctx.cur_segment_id.with(|c| c.get()) as usize;
1060 let q = match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) {
1061 Some(data) => (base + data).clamp(0, 255),
1062 None => base,
1063 };
1064 // lane-d792: which SEGMENT a block's quantizer came out of, beside the
1065 // `EC_DQCOEFF` grid rung -- a dequant that is too low with the levels
1066 // already proven equal is a segment-id defect, not a quantizer one.
1067 if crate::envflags::env_flag!("EC_DQCOEFF") {
1068 eprintln!("OUR_Q base={base} seg={seg_id} q={q}");
1069 }
1070 hit_do!(BLOCK_Q_SPAN.with(|c| {
1071 let (lo, hi) = c.get();
1072 c.set((lo.min(q), hi.max(q)));
1073 }););
1074 q
1075}
1076
1077/// The segment id recorded for one mi cell of the current frame's map.
1078fn segment_id_at(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> u8 {
1079 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1080 if mi_r >= mi_rows || mi_c >= mi_cols {
1081 return 0;
1082 }
1083 fctx.seg_ids.with(|m| m.borrow()[mi_r * mi_cols + mi_c])
1084}
1085
1086/// `set_segment_id`: stamps `id` over every mi cell this block covers.
1087fn write_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, id: u8, fctx: &crate::decode::FrameCtx) {
1088 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1089 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
1090 fctx.seg_ids.with(|m| {
1091 let mut m = m.borrow_mut();
1092 for y in 0..y_mis {
1093 for x in 0..x_mis {
1094 m[(mi_r + y) * mi_cols + mi_c + x] = id;
1095 }
1096 }
1097 });
1098 fctx.cur_segment_id.with(|c| c.set(id));
1099 SEG_IDS_SEEN.with(|c| c.set(c.get() | 1 << id));
1100}
1101
1102/// `get_predicted_segment_id` (libaom `dec_get_segment_id` over
1103/// `last_frame_seg_map`): the minimum previous-frame segment id over the
1104/// block's own mi footprint. `0` when there is no previous map.
1105fn predicted_segment_id(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, fctx: &crate::decode::FrameCtx) -> u8 {
1106 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
1107 fctx.prev_seg_ids.with(|m| {
1108 let m = m.borrow();
1109 if m.is_empty() {
1110 return 0;
1111 }
1112 let (x_mis, y_mis) = (w_mi.min(mi_cols.saturating_sub(mi_c)), h_mi.min(mi_rows.saturating_sub(mi_r)));
1113 let mut id = u8::MAX;
1114 for y in 0..y_mis {
1115 for x in 0..x_mis {
1116 id = id.min(m[(mi_r + y) * mi_cols + mi_c + x]);
1117 }
1118 }
1119 if id == u8::MAX { 0 } else { id }
1120 })
1121}
1122
1123/// `av1_neg_deinterleave` (libaom `decodemv.c:258`).
1124fn neg_deinterleave(diff: i32, reference: i32, max: i32) -> i32 {
1125 if reference == 0 {
1126 return diff;
1127 }
1128 if reference >= max - 1 {
1129 return max - diff - 1;
1130 }
1131 let half = if 2 * reference < max {
1132 diff <= 2 * reference
1133 } else {
1134 diff <= 2 * (max - reference - 1)
1135 };
1136 if half {
1137 return if diff & 1 != 0 {
1138 reference + ((diff + 1) >> 1)
1139 } else {
1140 reference - (diff >> 1)
1141 };
1142 }
1143 if 2 * reference < max { diff } else { max - (diff + 1) }
1144}
1145
1146/// `av1_get_spatial_seg_pred`: `(prediction, cdf_index)` from the current
1147/// frame's already-decoded above/left/above-left neighbours.
1148fn spatial_seg_pred(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> (i32, usize) {
1149 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1150 let (avail_u, avail_l) = (mi_r > row0, mi_c > col0);
1151 let prev_ul = (avail_u && avail_l).then(|| i32::from(segment_id_at(mi_r - 1, mi_c - 1, fctx)));
1152 let prev_u = avail_u.then(|| i32::from(segment_id_at(mi_r - 1, mi_c, fctx)));
1153 let prev_l = avail_l.then(|| i32::from(segment_id_at(mi_r, mi_c - 1, fctx)));
1154 let ctx = match prev_ul {
1155 None => 0,
1156 Some(ul) if Some(ul) == prev_u && Some(ul) == prev_l => 2,
1157 Some(ul) if Some(ul) == prev_u || Some(ul) == prev_l || prev_u == prev_l => 1,
1158 Some(_) => 0,
1159 };
1160 let pred = match (prev_u, prev_l) {
1161 (None, l) => l.unwrap_or(0),
1162 (Some(u), None) => u,
1163 (Some(u), Some(l)) => {
1164 if prev_ul == Some(u) {
1165 u
1166 } else {
1167 l
1168 }
1169 }
1170 };
1171 (pred, ctx)
1172}
1173
1174/// `read_segment_id` (libaom `decodemv.c:280`): the spatially predicted id
1175/// when `skip`, otherwise one `segment_id` symbol de-interleaved against
1176/// that prediction. Does NOT write the map -- callers do.
1177fn read_segment_id(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) -> u8 {
1178 let (pred, ctx) = spatial_seg_pred(mi_r, mi_c, fctx);
1179 if skip {
1180 return pred as u8;
1181 }
1182 let coded = dec.symbol(&mut cdfs.segment_id[ctx]) as i32;
1183 hit!(SEG_ID_HITS);
1184 let last_active = fctx.seg.with(|s| i32::from(s.borrow().last_active_seg_id));
1185 let id = neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active);
1186 // Mirrors the oracle's own `EC_SEG mi_row=.. cdf=.. pred=.. coded=.. id=..`
1187 // (libaom `decodemv.c:read_segment_id`), for a cross-decoder segment diff.
1188 if crate::envflags::env_flag!("EC_TRACE_SEG") {
1189 eprintln!("EC_SEG mi_row={mi_r} mi_col={mi_c} cdf={ctx} pred={pred} coded={coded} id={id} rng={}", dec.debug_state().0);
1190 }
1191 id as u8
1192}
1193
1194/// `read_intra_segment_id` (spec 5.11.7): called twice per intra-frame block
1195/// -- once before `skip` when `SegIdPreSkip`, once after it otherwise (the
1196/// caller decides which by passing `pre_skip`).
1197fn intra_segment_id(
1198 dec: &mut SymbolDecoder,
1199 cdfs: &mut Cdfs,
1200 mi_r: usize,
1201 mi_c: usize,
1202 w_mi: usize,
1203 h_mi: usize,
1204 skip: bool, fctx: &crate::decode::FrameCtx,
1205) {
1206 if !fctx.seg.with(|s| s.borrow().enabled) {
1207 return;
1208 }
1209 let id = read_segment_id(dec, cdfs, mi_r, mi_c, skip, fctx);
1210 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1211}
1212
1213/// Whether this frame's intra blocks read their `segment_id` before `skip`
1214/// (`SegIdPreSkip`); `false` also when segmentation is off.
1215fn seg_id_pre_skip(fctx: &crate::decode::FrameCtx) -> bool {
1216 fctx.seg.with(|s| {
1217 let s = s.borrow();
1218 s.enabled && s.seg_id_pre_skip
1219 })
1220}
1221
1222/// `read_inter_segment_id(preskip)` (spec 5.11.9, libaom `decodemv.c:352`).
1223/// Called at both spec positions of an inter frame's block: `pre_skip = true`
1224/// before `skip_mode`/`skip`, and `pre_skip = false` after them.
1225fn inter_segment_id(
1226 dec: &mut SymbolDecoder,
1227 cdfs: &mut Cdfs,
1228 mi_r: usize,
1229 mi_c: usize,
1230 w_mi: usize,
1231 h_mi: usize,
1232 skip: bool,
1233 pre_skip: bool, fctx: &crate::decode::FrameCtx,
1234) {
1235 let (enabled, update_map, temporal_update, pre_skip_frame) = fctx.seg.with(|s| {
1236 let s = s.borrow();
1237 (s.enabled, s.update_map, s.temporal_update, s.seg_id_pre_skip)
1238 });
1239 if !enabled {
1240 return;
1241 }
1242 if !update_map {
1243 // The map is inherited wholesale from the previous frame.
1244 let id = predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx);
1245 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1246 return;
1247 }
1248 if pre_skip && !pre_skip_frame {
1249 return;
1250 }
1251 if !pre_skip && skip {
1252 // libaom: a skipped block never codes `seg_id_predicted`, and its
1253 // segment id is the spatial prediction.
1254 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, 0, fctx);
1255 let id = read_segment_id(dec, cdfs, mi_r, mi_c, true, fctx);
1256 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1257 return;
1258 }
1259 let id = if temporal_update {
1260 let ctx = seg_pred_ctx(mi_r, mi_c, fctx);
1261 let predicted = dec.symbol(&mut cdfs.segment_pred[ctx]) != 0;
1262 hit!(SEG_PRED_HITS);
1263 stamp_seg_pred(mi_r, mi_c, w_mi, h_mi, u8::from(predicted), fctx);
1264 if predicted {
1265 predicted_segment_id(mi_r, mi_c, w_mi, h_mi, fctx)
1266 } else {
1267 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1268 }
1269 } else {
1270 read_segment_id(dec, cdfs, mi_r, mi_c, false, fctx)
1271 };
1272 write_segment_id(mi_r, mi_c, w_mi, h_mi, id, fctx);
1273}
1274
1275/// `av1_get_pred_context_seg_id`: above + left `seg_id_predicted` flags.
1276fn seg_pred_ctx(mi_r: usize, mi_c: usize, fctx: &crate::decode::FrameCtx) -> usize {
1277 // libaom reads the flag off `above_mbmi`/`left_mbmi`, which are NULL (and
1278 // so contribute 0) outside the tile -- the availability check here is
1279 // what keeps a previous tile's stamps out of this tile's context.
1280 let (row0, col0) = fctx.seg_tile_origin.with(|c| c.get());
1281 let above = if mi_r > row0 {
1282 fctx.above_seg_pred.with(|m| m.borrow().get(mi_c).copied().unwrap_or(0))
1283 } else {
1284 0
1285 };
1286 let left = if mi_c > col0 {
1287 fctx.left_seg_pred.with(|m| m.borrow().get(mi_r).copied().unwrap_or(0))
1288 } else {
1289 0
1290 };
1291 usize::from(above + left)
1292}
1293
1294/// Spec 5.11.9's `AboveSegPredContext`/`LeftSegPredContext` update.
1295fn stamp_seg_pred(mi_r: usize, mi_c: usize, w_mi: usize, h_mi: usize, value: u8, fctx: &crate::decode::FrameCtx) {
1296 fctx.above_seg_pred.with(|m| {
1297 let mut m = m.borrow_mut();
1298 for i in 0..w_mi {
1299 if let Some(cell) = m.get_mut(mi_c + i) {
1300 *cell = value;
1301 }
1302 }
1303 });
1304 fctx.left_seg_pred.with(|m| {
1305 let mut m = m.borrow_mut();
1306 for i in 0..h_mi {
1307 if let Some(cell) = m.get_mut(mi_r + i) {
1308 *cell = value;
1309 }
1310 }
1311 });
1312}
1313
1314// How many key-frame luma blocks resolved `smooth_neighbor` (spec
1315// `get_intra_edge_filter_type`) to `true` -- lane-chroma r2's own before/after
1316// counter, proving a stream actually put a directional block next to a
1317// smooth-predicted neighbour rather than every block reading the (previously
1318// hardcoded `false`) edge-filter strength bucket unchanged.
1319thread_local! {
1320 static SMOOTH_LUMA_HITS: std::cell::Cell<usize> =
1321 const { std::cell::Cell::new(0) };
1322}
1323
1324/// Current value of [`SMOOTH_LUMA_HITS`].
1325#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1326pub(crate) fn smooth_luma_hits() -> usize {
1327 SMOOTH_LUMA_HITS.with(|c| c.get())
1328}
1329
1330thread_local! {
1331 /// lane-band46 r1: how many split-transform units answered their intra
1332 /// reach DIFFERENTLY under libaom's per-unit rules ([`Reach::of_tu`], the
1333 /// palette2 r12 fix) than the standalone-block lookup this decoder used to
1334 /// apply to them (class reach-is-per-transform-unit). Every hit is a
1335 /// transform unit whose above-right / below-left reference samples would
1336 /// be wrong without that fix.
1337 static SPLIT_TU_REACH_FIX_HITS: std::cell::Cell<usize> =
1338 const { std::cell::Cell::new(0) };
1339}
1340
1341/// Current value of [`SPLIT_TU_REACH_FIX_HITS`].
1342#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1343pub(crate) fn split_tu_reach_fix_hits() -> usize {
1344 SPLIT_TU_REACH_FIX_HITS.with(|c| c.get())
1345}
1346
1347/// [`Reach::of_tu`] for one transform unit, counting how often that per-unit
1348/// answer differs from the standalone-block answer the call sites used before
1349/// lane-palette2 r12 -- the counter a gate asserts on to prove a stream really
1350/// exercised the fix. `col_off`/`row_off` are in SAMPLES from the parent
1351/// block's top-left `(px, py)`.
1352#[allow(clippy::too_many_arguments)]
1353fn tu_reach(
1354 bw: usize,
1355 bh: usize,
1356 col_off: usize,
1357 row_off: usize,
1358 tx: usize,
1359 block: Reach,
1360 px: usize,
1361 py: usize,
1362 width: usize,
1363 height: usize, fctx: &crate::decode::FrameCtx,
1364) -> Reach {
1365 let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
1366 let standalone = Reach::of(tx, px + col_off, py + row_off, width, height, fctx);
1367 if fixed != standalone {
1368 hit!(SPLIT_TU_REACH_FIX_HITS);
1369 }
1370 fixed
1371}
1372
1373// How many `uv_mode` reads resolved to `SMOOTH_PRED..=PAETH_PRED` (9..=12),
1374// across every call on the current thread -- lane-chroma r3's own before/after
1375// counter, proving a stream actually exercised chroma's smooth/paeth
1376// predictor (the previously-refused round-2 gap) rather than every block
1377// landing on DC/CFL/directional.
1378thread_local! {
1379 static SMOOTH_UV_HITS: std::cell::Cell<usize> =
1380 const { std::cell::Cell::new(0) };
1381}
1382
1383/// Current value of [`SMOOTH_UV_HITS`].
1384#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1385pub(crate) fn smooth_uv_hits() -> usize {
1386 SMOOTH_UV_HITS.with(|c| c.get())
1387}
1388
1389// How many tiles [`decode_key_frame_tile_with_cdfs`] has actually decoded a
1390// full superblock walk over, across every call on the current thread --
1391// lane-tiles r2's own gate-blind-to-feature guard: a gate over a
1392// multi-tile stream must prove more than one tile actually fired, not just
1393// that the stream carried tile_info.cols > 1.
1394thread_local! {
1395 static TILE_HITS: std::cell::Cell<usize> =
1396 const { std::cell::Cell::new(0) };
1397}
1398/// Current value of [`TILE_HITS`].
1399#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1400pub(crate) fn tile_hits() -> usize {
1401 TILE_HITS.with(|c| c.get())
1402}
1403
1404// How many 4-pixel deblocking edge groups [`edge_params`] has actually
1405// selected for filtering, across every call on the current thread -- the same
1406// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1407// exercised `apply_deblock` rather than every edge landing on level 0.
1408thread_local! {
1409 static DEBLOCK_HITS: std::cell::Cell<usize> =
1410 const { std::cell::Cell::new(0) };
1411}
1412/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
1413/// mirroring stream.rs's `pictures_decoded` so the two dumps index
1414/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
1415static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize =
1416 std::sync::atomic::AtomicUsize::new(0);
1417
1418/// Current value of [`DEBLOCK_HITS`].
1419#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1420pub(crate) fn deblock_hits() -> usize {
1421 DEBLOCK_HITS.with(|c| c.get())
1422}
1423
1424// lane-defon r1: how many COMPOUND_REFERENCE blocks read a
1425// `UNIDIR_COMP_REFERENCE` pair (both references on the same temporal side,
1426// spec 5.11.25 `comp_reference_type == 0`) -- the gate's proof that a
1427// stream built with `--enable-onesided-comp=1` really exercised the
1428// `uni_comp_ref` alphabet rather than only bidirectional pairs.
1429thread_local! {
1430 static UNI_COMP_HITS: std::cell::Cell<usize> =
1431 const { std::cell::Cell::new(0) };
1432}
1433
1434/// Current value of [`UNI_COMP_HITS`].
1435#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1436pub(crate) fn uni_comp_hits() -> usize {
1437 UNI_COMP_HITS.with(|c| c.get())
1438}
1439
1440// lane-defon r1: how many blocks blended through a `COMPOUND_DIFFWTD` mask
1441// (`mc::diffwtd_mask`) -- the narrower half of `MASKED_COMPOUND_HITS`, the
1442// gate's proof that `--enable-diff-wtd-comp=1` reached the difference-weighted
1443// blend and not only the wedge arm.
1444thread_local! {
1445 static DIFFWTD_HITS: std::cell::Cell<usize> =
1446 const { std::cell::Cell::new(0) };
1447}
1448
1449/// Current value of [`DIFFWTD_HITS`].
1450#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1451pub(crate) fn diffwtd_hits() -> usize {
1452 DIFFWTD_HITS.with(|c| c.get())
1453}
1454
1455// lane-mcomp64 r1: how many blocks took the INFERRED `COMPOUND_DIFFWTD` arm --
1456// a block size where `av1_is_wedge_used` is false (64x64 is the only such size
1457// this decoder's square inter path reaches), so no `compound_type` symbol is
1458// coded at all. Strictly narrower than `DIFFWTD_HITS`, which also counts the
1459// coded-symbol DIFFWTD blocks at 8x8/16x16/32x32.
1460thread_local! {
1461 static DIFFWTD_INFERRED_HITS: std::cell::Cell<usize> =
1462 const { std::cell::Cell::new(0) };
1463}
1464
1465/// Current value of [`DIFFWTD_INFERRED_HITS`].
1466#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1467pub(crate) fn diffwtd_inferred_hits() -> usize {
1468 DIFFWTD_INFERRED_HITS.with(|c| c.get())
1469}
1470
1471// lane-defon r1: how many FORWARD KEYFRAMES were decoded -- a KEY frame coded
1472// with `show_frame == 0`, output later by a `show_existing_frame` header
1473// (aomenc `--enable-fwd-kf=1 --fwd-kf-dist=N`). Counted from
1474// `stream::decode_stream`, which is where the frame header is consumed; the
1475// gate's proof that the on-value really reached the bitstream rather than
1476// being dropped by the rate control.
1477thread_local! {
1478 static FWD_KF_HITS: std::cell::Cell<usize> =
1479 const { std::cell::Cell::new(0) };
1480}
1481
1482/// Current value of [`FWD_KF_HITS`].
1483#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1484pub(crate) fn fwd_kf_hits() -> usize {
1485 FWD_KF_HITS.with(|c| c.get())
1486}
1487
1488/// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
1489pub(crate) fn note_fwd_kf() {
1490 hit!(FWD_KF_HITS);
1491}
1492
1493// How many [`read_tx_size`] reads resolved a `tx_depth` strictly less than
1494// the block's own side, across every call on the current thread -- the same
1495// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1496// actually exercised a *split* transform under `TxMode::Select` rather than
1497// every block coincidentally resolving `depth=0` (indistinguishable from
1498// `TxMode::Largest` pixel-wise).
1499thread_local! {
1500 static TX_DEPTH_HITS: std::cell::Cell<usize> =
1501 const { std::cell::Cell::new(0) };
1502}
1503
1504// How many plain SQUARE intra blocks (lane-sqchroma r1) resolved a luma
1505// transform smaller than their own side (`tx_depth != 0`) while coding a
1506// chroma prediction other than `DC_PRED` -- the pair the square path's chroma
1507// only exercises with aomenc's tx-size search left ON (its default), which
1508// every older recipe in this file pins off. Counted at the block, so a stream
1509// where RD happened to give every split-transform block a DC chroma mode
1510// reads as zero rather than silently passing for free.
1511thread_local! {
1512 static SQ_CHROMA_TX_HITS: std::cell::Cell<usize> =
1513 const { std::cell::Cell::new(0) };
1514}
1515
1516/// Current value of [`SQ_CHROMA_TX_HITS`].
1517#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1518pub(crate) fn sq_chroma_tx_hits() -> usize {
1519 SQ_CHROMA_TX_HITS.with(|c| c.get())
1520}
1521
1522/// Current value of [`TX_DEPTH_HITS`].
1523#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1524pub(crate) fn tx_depth_hits() -> usize {
1525 TX_DEPTH_HITS.with(|c| c.get())
1526}
1527
1528// lane-txselect: how many `txfm_split` symbols an inter frame's var-tx tree
1529// read, and how many of those actually took the split, on the current thread
1530// -- the same before/after counter pattern as [`TX_DEPTH_HITS`], proving a
1531// stream exercised spec 5.11.17's `read_var_tx_size` rather than every block
1532// coincidentally coding one whole-block transform.
1533thread_local! {
1534 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1535 static TXFM_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1536 // lane-inter4 r2: rectangular INTER residual coding -- how many rect
1537 // strips coded one whole-block rect transform unit, and how many split
1538 // their rect max transform into square sub-transforms.
1539 static RECT_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1540 static RECT_INTER_TXSPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1541 // lane-r14 r2: luma transform units of an inter strip with a 64-px axis
1542 // (64x32/32x64/64x16/16x64), whose coefficients are coded as the
1543 // truncated low-32 corner.
1544 static RECT64_INTER_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1545 // lane-rectres r1: whole-block luma transform units of a 32x32-level 1:4
1546 // inter strip, `[32x8, 8x32]`.
1547 static RECT32X8_INTER_TU_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1548 // lane-r14 r3: rectangular var-tx LEAVES, [32x16, 16x32].
1549 static VARTX_RECT_LEAF_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1550 // lane-inter16ab r4: rectangular var-tx leaves with a 4-px axis, [8x4, 4x8]
1551 // -- the `sub_tx_size_map[TX_16X4]` split leaves of a 16x16-level 1:4 strip.
1552 static VARTX_RECT_LEAF4_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
1553 // lane-inter4 r3: 16x16-level PARTITION_HORZ / PARTITION_VERT on an inter
1554 // frame -- 16x8 and 8x16 inter leaves.
1555 static INTER_LEAF16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1556 static INTER_LEAF16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1557 // This frame's own `tx_mode == TxMode::Select` and `reduced_tx_set` bits,
1558 // set once per inter tile by [`decode_inter_frame_tile_with_cdfs`] --
1559 // `decode_inter_block` already carries forty parameters and both are
1560 // frame-constant.
1561 // lane-fiinter r1: this sequence header's own `enable_filter_intra` bit,
1562 // frame-constant like the two above and stashed the same way -- an intra
1563 // block inside an inter frame reads `use_filter_intra` under it.
1564}
1565
1566/// Current value of [`TXFM_SPLIT_READS`].
1567#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1568pub(crate) fn txfm_split_reads() -> usize {
1569 TXFM_SPLIT_READS.with(|c| c.get())
1570}
1571
1572/// Current value of [`TXFM_SPLIT_HITS`].
1573#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1574pub(crate) fn txfm_split_hits() -> usize {
1575 TXFM_SPLIT_HITS.with(|c| c.get())
1576}
1577
1578/// Current value of [`INTER_LEAF16_HORZ_HITS`] (lane-inter4 r3).
1579#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1580pub(crate) fn inter_leaf16_horz_hits() -> usize {
1581 INTER_LEAF16_HORZ_HITS.with(|c| c.get())
1582}
1583
1584/// Current value of [`INTER_LEAF16_VERT_HITS`] (lane-inter4 r3).
1585#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1586pub(crate) fn inter_leaf16_vert_hits() -> usize {
1587 INTER_LEAF16_VERT_HITS.with(|c| c.get())
1588}
1589
1590/// Current value of [`RECT_INTER_TU_HITS`] (lane-inter4 r2).
1591pub(crate) fn rect_inter_tu_hits() -> usize {
1592 RECT_INTER_TU_HITS.with(|c| c.get())
1593}
1594
1595/// Current value of [`RECT_INTER_TXSPLIT_HITS`] (lane-inter4 r2).
1596pub(crate) fn rect_inter_txsplit_hits() -> usize {
1597 RECT_INTER_TXSPLIT_HITS.with(|c| c.get())
1598}
1599
1600/// Current value of [`RECT64_INTER_TU_HITS`] (lane-r14 r2).
1601pub(crate) fn rect64_inter_tu_hits() -> usize {
1602 RECT64_INTER_TU_HITS.with(|c| c.get())
1603}
1604
1605/// Current value of [`RECT32X8_INTER_TU_HITS`] (lane-rectres r1): `[32x8, 8x32]`
1606/// whole-block luma units of a 32x32-level 1:4 inter strip.
1607pub(crate) fn rect32x8_inter_tu_hits() -> [usize; 2] {
1608 RECT32X8_INTER_TU_HITS.with(|c| c.get())
1609}
1610
1611/// Current value of [`VARTX_RECT_LEAF_HITS`] (lane-r14 r3): how many
1612/// rectangular var-tx leaf transform units were coded, `[32x16, 16x32]`.
1613pub(crate) fn vartx_rect_leaf_hits() -> [usize; 2] {
1614 VARTX_RECT_LEAF_HITS.with(|c| c.get())
1615}
1616
1617/// Current value of [`VARTX_RECT_LEAF4_HITS`] (lane-inter16ab r4): 8x4/4x8
1618/// split leaves of a 16x4/4x16 strip, `[8x4, 4x8]`.
1619pub(crate) fn vartx_rect_leaf4_hits() -> [usize; 2] {
1620 VARTX_RECT_LEAF4_HITS.with(|c| c.get())
1621}
1622
1623/// Records one rectangular var-tx leaf.
1624fn vartx_rect_leaf_hit(tw: usize, th: usize) {
1625 if crate::envflags::env_flag!("EC_VARTXLEAF") {
1626 eprintln!("EC_VARTXLEAF tw={tw} th={th}");
1627 }
1628 let cell = if tw.min(th) == 4 { &VARTX_RECT_LEAF4_HITS } else { &VARTX_RECT_LEAF_HITS };
1629 cell.with(|c| {
1630 let mut h = c.get();
1631 h[usize::from(th > tw)] += 1;
1632 c.set(h);
1633 });
1634}
1635
1636/// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
1637/// [`ENABLE_FILTER_INTRA_INTER`].
1638pub(crate) fn set_inter_tx_mode(
1639 tx_select: bool,
1640 reduced_tx_set: bool,
1641 enable_filter_intra: bool, fctx: &crate::decode::FrameCtx,
1642) {
1643 fctx.tx_select_inter.with(|c| c.set(tx_select));
1644 fctx.intra_only.with(|c| c.set(false));
1645 fctx.tx_select_frame.with(|c| c.set(tx_select));
1646 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
1647 fctx.enable_filter_intra_inter.with(|c| c.set(enable_filter_intra));
1648}
1649
1650// How many `partition_w16` reads (a 16x16 block's own partition symbol, key
1651// intra-frame path) resolved to `PARTITION_VERT_B` -- lane-rect16 r1: a
1652// plain default-settings aomenc run over lavfi mandelbrot hits this arm on
1653// frame 0's very first non-NONE/SPLIT `partition_w16` symbol (mi=(3,2)), not
1654// the plain HORZ/VERT this lane's charter assumed. Left rect (8x16, real
1655// `decode_block_rect`) + two 8x8 leaves stacked on the right (`decode_leaf8`,
1656// chained via `prev_leaf` exactly like the existing 16x16-SPLIT-into-4x8x8
1657// path above).
1658thread_local! {
1659 static VERT_B_INTRA_HITS: std::cell::Cell<usize> =
1660 const { std::cell::Cell::new(0) };
1661}
1662
1663/// Current value of [`VERT_B_INTRA_HITS`].
1664#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1665pub(crate) fn vert_b_intra_hits() -> usize {
1666 VERT_B_INTRA_HITS.with(|c| c.get())
1667}
1668
1669// lane-ab16 r1: how many 16x16-level AB partitions fired, per arm, in
1670// `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order. Each arm is two
1671// 8x8 squares (`decode_leaf8`) plus one 16x8/8x16 strip (`decode_leaf_rect`,
1672// the non-skip coefficient path lane-rectx proved); the gate hard-asserts
1673// every arm separately so a run where aomenc's RD only picked one cannot
1674// pass as proof of four.
1675thread_local! {
1676 static AB16_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
1677}
1678
1679// [`AB16_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16).
1680thread_local! {
1681 /// 4x4 transform units decoded inside an 8x8 square of a
1682 /// `PARTITION_VERT_A`/`_B` -- the exact call that panicked before
1683 /// [`crate::encode::Reach::of_tu`] (lane-ab16 r2), so the gate can prove
1684 /// a real `--enable-tx-size-search=1` stream reaches it.
1685 static VERT_AB_TX4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1686}
1687
1688#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1689pub(crate) fn vert_ab_tx4_hits() -> usize {
1690 VERT_AB_TX4_HITS.with(std::cell::Cell::get)
1691}
1692
1693#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1694pub(crate) fn ab16_hits_by_arm() -> [usize; 4] {
1695 AB16_HITS.with(std::cell::Cell::get)
1696}
1697
1698fn bump_ab16(arm: usize) {
1699 hit_do! {
1700 AB16_HITS.with(|c| {
1701 let mut v = c.get();
1702 v[arm] += 1;
1703 c.set(v);
1704 });
1705 }
1706}
1707
1708// How many `partition_w16` reads resolved to a plain `PARTITION_HORZ`/
1709// `PARTITION_VERT` (lane-rect16 r2): re-measuring after the VERT_B fix above
1710// showed mandelbrot's real first-hit blocker is this plain arm at mi=(0,7),
1711// not VERT_B (`refusal-names-a-correlate`; the VERT_B write-up's "frame 0's
1712// very first non-NONE/SPLIT symbol" claim was about decode ORDER within one
1713// superblock's z-order recursion, not raster mi position).
1714thread_local! {
1715 static HORZ_VERT_INTRA_HITS: std::cell::Cell<usize> =
1716 const { std::cell::Cell::new(0) };
1717}
1718
1719/// Current value of [`HORZ_VERT_INTRA_HITS`].
1720#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1721pub(crate) fn horz_vert_intra_hits() -> usize {
1722 HORZ_VERT_INTRA_HITS.with(|c| c.get())
1723}
1724
1725// How many blocks were decoded as a frame-edge rect strip -- the single
1726// coded half of a `PARTITION_HORZ`/`PARTITION_VERT` at the true frame edge
1727// (lane-oddh r1), i.e. a block living inside the 8px band of a frame whose
1728// height or width is 8 mod 16 (the user's 3840x1608 film). Intra and inter
1729// paths share the counter.
1730thread_local! {
1731 static EDGE_RECT_STRIP_HITS: std::cell::Cell<usize> =
1732 const { std::cell::Cell::new(0) };
1733}
1734
1735/// Current value of [`EDGE_RECT_STRIP_HITS`].
1736#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
1737pub(crate) fn edge_rect_strip_hits() -> usize {
1738 EDGE_RECT_STRIP_HITS.with(|c| c.get())
1739}
1740
1741// lane-interedge r1: frame-edge half strips on the INTER path, per partition
1742// level (64/32/16) x axis (HORZ at a bottom edge, VERT at a right edge). The
1743// index is `level_idx * 2 + axis` with `level_idx` 0=64, 1=32, 2=16 and
1744// `axis` 0=HORZ (`!has_rows`), 1=VERT (`!has_cols`). Both of the user's films
1745// are height mod 16 == 8, so every inter frame crosses these nodes.
1746thread_local! {
1747 static INTER_EDGE_STRIP_HITS: std::cell::Cell<[usize; 6]> =
1748 const { std::cell::Cell::new([0; 6]) };
1749}
1750
1751/// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`].
1752pub(crate) fn bump_inter_edge_strip(idx: usize) {
1753 hit_do! {
1754 INTER_EDGE_STRIP_HITS.with(|c| {
1755 let mut v = c.get();
1756 v[idx] += 1;
1757 c.set(v);
1758 });
1759 }
1760}
1761
1762// lane-edgeboth r1: how many partition nodes were coded as the BOTH-AXES-CUT
1763// forced split -- libaom `decode_partition` (decodeframe.c):
1764// `else if (!has_rows && !has_cols) partition = PARTITION_SPLIT;`, the one
1765// straddle case that reads NO symbol at all. Indexed by level:
1766// 0 = 16x16, 1 = 32x32, 2 = 64x64, 3 = 128x128; intra and inter share it.
1767thread_local! {
1768 static EDGE_BOTH_CUT_HITS: std::cell::Cell<[usize; 4]> =
1769 const { std::cell::Cell::new([0; 4]) };
1770}
1771
1772fn bump_edge_both_cut(level: usize) {
1773 hit_do! {
1774 EDGE_BOTH_CUT_HITS.with(|c| {
1775 let mut v = c.get();
1776 v[level] += 1;
1777 c.set(v);
1778 });
1779 }
1780}
1781
1782/// Current value of [`INTER_EDGE_STRIP_HITS`] (`[h64, v64, h32, v32, h16, v16]`).
1783pub fn inter_edge_strip_hits() -> [usize; 6] {
1784 INTER_EDGE_STRIP_HITS.with(|c| c.get())
1785}
1786
1787/// Resets [`INTER_EDGE_STRIP_HITS`] -- a refused attempt must not carry hits
1788/// into the next one (class `counter-from-refused-stream`).
1789pub fn reset_inter_edge_strip_hits() {
1790 INTER_EDGE_STRIP_HITS.with(|c| c.set([0; 6]));
1791}
1792
1793/// Current value of [`EDGE_BOTH_CUT_HITS`] (`[16, 32, 64, 128]` levels).
1794#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1795pub(crate) fn edge_both_cut_hits() -> [usize; 4] {
1796 EDGE_BOTH_CUT_HITS.with(|c| c.get())
1797}
1798
1799/// Zeroes [`EDGE_BOTH_CUT_HITS`] so a gate can measure a per-attempt delta.
1800#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1801pub(crate) fn reset_edge_both_cut_hits() {
1802 EDGE_BOTH_CUT_HITS.with(|c| c.set([0; 4]));
1803}
1804
1805// How many HORZ/VERT intra strips resolved a SPLIT luma transform
1806// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) --
1807// the case every rect path here refused by name before, and the first
1808// refusal the user's ReelB extract (600s in) stops at.
1809thread_local! {
1810 static RECT_SPLIT_TX_HITS: std::cell::Cell<usize> =
1811 const { std::cell::Cell::new(0) };
1812}
1813
1814/// Current value of [`RECT_SPLIT_TX_HITS`].
1815#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1816pub(crate) fn rect_split_tx_hits() -> usize {
1817 RECT_SPLIT_TX_HITS.with(|c| c.get())
1818}
1819
1820// The subset of [`RECT_SPLIT_TX_HITS`] that is BOTH superblock-level (one
1821// side 64) AND split past the first depth, i.e. tiled more than one unit in
1822// each axis -- the only shape with a transform unit that has neighbours on
1823// two sides inside its own strip (`row_off > 0 && col_off > 0`), and the one
1824// no gate fired before lane-rectsplit r2 (the shared counter above also
1825// counts 32x32-level and depth-1 strips, so it cannot prove this case).
1826thread_local! {
1827 static RECT_SPLIT_SB_INTERIOR_TU_HITS: std::cell::Cell<usize> =
1828 const { std::cell::Cell::new(0) };
1829}
1830
1831/// Current value of [`RECT_SPLIT_SB_INTERIOR_TU_HITS`].
1832#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1833pub(crate) fn rect_split_sb_interior_tu_hits() -> usize {
1834 RECT_SPLIT_SB_INTERIOR_TU_HITS.with(|c| c.get())
1835}
1836
1837// Per-shape hit counts for the rect chroma transforms lane-rectchroma r1
1838// wired into [`decode_rect_split`] -- the shapes a split-transform strip's
1839// chroma half takes that had no coefficient tables before (index order:
1840// 32x8, 8x32, 8x4, 4x8). One counter per shape because a gate that only
1841// proves the pair it happens to hit cannot catch a transposed scan/context
1842// table (class scan-weights-cross-axis).
1843thread_local! {
1844 static RECT_SPLIT_CHROMA_SHAPE_HITS: std::cell::Cell<[usize; 4]> =
1845 const { std::cell::Cell::new([0; 4]) };
1846}
1847
1848/// Current value of [`RECT_SPLIT_CHROMA_SHAPE_HITS`] (32x8, 8x32, 8x4, 4x8).
1849#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1850pub(crate) fn rect_split_chroma_shape_hits() -> [usize; 4] {
1851 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| c.get())
1852}
1853
1854// How many HORZ/VERT intra strips actually predicted with filter intra
1855// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
1856// ("this decoder predicts square-only") until `predict_filter_intra` took
1857// `bw`x`bh`.
1858thread_local! {
1859 static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
1860 const { std::cell::Cell::new(0) };
1861}
1862
1863/// Current value of [`FILTER_INTRA_RECT_HITS`].
1864#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1865pub(crate) fn filter_intra_rect_hits() -> usize {
1866 FILTER_INTRA_RECT_HITS.with(|c| c.get())
1867}
1868
1869// As [`FILTER_INTRA_RECT_HITS`], counting only the 32x32-level 1:4 strips
1870// (32x8/8x32, lane-fi32x8 r1) -- the shapes whose `use_filter_intra` symbol
1871// was never read at all before that round, so a gate needs to prove the flag
1872// fired at THAT shape and not at a 16x8 one somewhere else in the frame.
1873// Split by ORIENTATION: rows 8 (32x8) and 9 (8x32) of `cdf::FILTER_INTRA`
1874// carry different probabilities (18101 vs 20229), so a transposed pair is
1875// only caught by a gate that sees the flag fire on BOTH shapes (class
1876// scan-weights-cross-axis).
1877thread_local! {
1878 static FILTER_INTRA_RECT4_HORZ_HITS: std::cell::Cell<usize> =
1879 const { std::cell::Cell::new(0) };
1880 static FILTER_INTRA_RECT4_VERT_HITS: std::cell::Cell<usize> =
1881 const { std::cell::Cell::new(0) };
1882}
1883
1884/// Current value of [`FILTER_INTRA_RECT4_HORZ_HITS`] (32x8 strips).
1885#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1886pub(crate) fn filter_intra_rect4_horz_hits() -> usize {
1887 FILTER_INTRA_RECT4_HORZ_HITS.with(|c| c.get())
1888}
1889
1890/// Current value of [`FILTER_INTRA_RECT4_VERT_HITS`] (8x32 strips).
1891#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1892pub(crate) fn filter_intra_rect4_vert_hits() -> usize {
1893 FILTER_INTRA_RECT4_VERT_HITS.with(|c| c.get())
1894}
1895
1896// How many rectangular transform units actually coded coefficients through
1897// [`read_coeffs_rect`] (`all_zero == 0`) -- lane-rect1d's measure that a gate
1898// exercised the rect coefficient reader at all rather than passing on
1899// all-skip blocks.
1900thread_local! {
1901 static RECT_COEFF_TU_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1902 static RECT_CLASS1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1903}
1904
1905/// Current value of [`RECT_COEFF_TU_HITS`].
1906#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1907pub(crate) fn rect_coeff_tu_hits() -> usize {
1908 RECT_COEFF_TU_HITS.with(|c| c.get())
1909}
1910
1911/// Rectangular transform units whose resolved `tx_type` is a 1D class
1912/// (`V_DCT`/`H_DCT`) -- [`TX_CLASS1_HITS`]'s rect-only half, so a gate can
1913/// pin that the 1D-class-on-a-RECT-transform path fired rather than settling
1914/// for the square reader's own 1D types.
1915#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1916pub(crate) fn rect_class1_hits() -> usize {
1917 RECT_CLASS1_HITS.with(|c| c.get())
1918}
1919
1920// As [`FILTER_INTRA_RECT_HITS`], counting only the strips BELOW 16x16
1921// (8x16/16x8 leaves of a 16x16 HORZ/VERT partition, lane-fistrip r1) -- the
1922// shapes whose `use_filter_intra` symbol had no CDF class before this round.
1923// A gate asserting the wider counter would be satisfied by a 32x16 strip and
1924// prove nothing about the new shapes.
1925thread_local! {
1926 static FILTER_INTRA_RECT_SUB16_HITS: std::cell::Cell<usize> =
1927 const { std::cell::Cell::new(0) };
1928}
1929
1930/// Current value of [`FILTER_INTRA_RECT_SUB16_HITS`].
1931#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1932pub(crate) fn filter_intra_rect_sub16_hits() -> usize {
1933 FILTER_INTRA_RECT_SUB16_HITS.with(|c| c.get())
1934}
1935
1936// As [`FILTER_INTRA_RECT_SUB16_HITS`], one partition level further down:
1937// 4x8/8x4 leaves of an 8x8 HORZ/VERT (lane-fi8 r1). A gate on the sub16
1938// counter would be satisfied by a 16x8 strip and prove nothing here.
1939thread_local! {
1940 static FILTER_INTRA_RECT_SUB8_HITS: std::cell::Cell<usize> =
1941 const { std::cell::Cell::new(0) };
1942}
1943
1944/// Current value of [`FILTER_INTRA_RECT_SUB8_HITS`].
1945#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1946pub(crate) fn filter_intra_rect_sub8_hits() -> usize {
1947 FILTER_INTRA_RECT_SUB8_HITS.with(|c| c.get())
1948}
1949
1950// How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
1951// (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
1952// call on the current thread -- the same before/after counter pattern as
1953// [`TX_DEPTH_HITS`], proving a stream actually exercised the class-split
1954// `eob_pt`/1D-neighbour context path rather than every block coincidentally
1955// landing on `DCT_DCT`.
1956thread_local! {
1957 static TX_CLASS1_HITS: std::cell::Cell<usize> =
1958 const { std::cell::Cell::new(0) };
1959}
1960
1961// How many `uv_mode` reads resolved to a directional chroma mode (neither
1962// `DC_PRED` nor `UV_CFL_PRED`), across every call on the current thread -- the same
1963// before/after counter pattern as [`FILTER_INTRA_HITS`], proving a stream
1964// actually exercised chroma's own directional predictor.
1965thread_local! {
1966 static DIRECTIONAL_UV_HITS: std::cell::Cell<usize> =
1967 const { std::cell::Cell::new(0) };
1968}
1969
1970/// Current value of [`DIRECTIONAL_UV_HITS`].
1971#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1972pub(crate) fn directional_uv_hits() -> usize {
1973 DIRECTIONAL_UV_HITS.with(|c| c.get())
1974}
1975
1976// How many `angle_delta`/`angle_delta_uv` symbols this decoder has read as
1977// something other than [`ANGLE_DELTA_ZERO`], across every call in the
1978// process -- the same before/after counter pattern as [`FILTER_INTRA_HITS`],
1979// proving a stream actually exercised a nonzero angle delta.
1980thread_local! {
1981 static ANGLE_DELTA_HITS: std::cell::Cell<usize> =
1982 const { std::cell::Cell::new(0) };
1983}
1984
1985// How many [`read_single_ref`] reads resolved to a reference other than
1986// `LAST_FRAME`, across every call on the current thread -- the same before/after
1987// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
1988// exercised a non-`LAST_FRAME` reference (`GOLDEN_FRAME`, this decoder's
1989// only other supported one so far) rather than every block coincidentally
1990// resolving `LAST_FRAME`.
1991thread_local! {
1992 static NON_LAST_REF_HITS: std::cell::Cell<usize> =
1993 const { std::cell::Cell::new(0) };
1994}
1995
1996/// Current value of [`NON_LAST_REF_HITS`].
1997#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1998pub(crate) fn non_last_ref_hits() -> usize {
1999 NON_LAST_REF_HITS.with(|c| c.get())
2000}
2001
2002// Per-reference [`NON_LAST_REF_HITS`] breakdown (lane-av1refs): one counter
2003// per `MV_REFERENCE_FRAME` past `LAST_FRAME`, so a gate targeting one
2004// specific reference (`LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/`ALTREF2`/`ALTREF`)
2005// can prove THAT reference fired rather than any non-`LAST_FRAME` one --
2006// `NON_LAST_REF_HITS` alone cannot tell a `LAST2_FRAME` gate from a
2007// `GOLDEN_FRAME` draw it did not ask for.
2008thread_local! {
2009 static LAST2_HITS: std::cell::Cell<usize> =
2010 const { std::cell::Cell::new(0) };
2011}
2012thread_local! {
2013 static LAST3_HITS: std::cell::Cell<usize> =
2014 const { std::cell::Cell::new(0) };
2015}
2016thread_local! {
2017 static GOLDEN_HITS: std::cell::Cell<usize> =
2018 const { std::cell::Cell::new(0) };
2019}
2020thread_local! {
2021 static BWDREF_HITS: std::cell::Cell<usize> =
2022 const { std::cell::Cell::new(0) };
2023}
2024thread_local! {
2025 static ALTREF2_HITS: std::cell::Cell<usize> =
2026 const { std::cell::Cell::new(0) };
2027}
2028thread_local! {
2029 static ALTREF_HITS: std::cell::Cell<usize> =
2030 const { std::cell::Cell::new(0) };
2031}
2032
2033// How many [`read_comp_mode`] reads resolved `COMPOUND_REFERENCE` (lane-av1comp)
2034// -- proves a `reference_select` stream actually reached a block that picked
2035// compound, not just that the header bit was set. Every such block is
2036// refused after this fires ([`decode_inter_block`]/[`decode_inter_block8`]),
2037// so this only ever counts attempted reads, never a completed decode.
2038thread_local! {
2039 static COMP_MODE_HITS: std::cell::Cell<usize> =
2040 const { std::cell::Cell::new(0) };
2041}
2042
2043/// Current value of [`COMP_MODE_HITS`].
2044#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2045pub(crate) fn comp_mode_hits() -> usize {
2046 COMP_MODE_HITS.with(|c| c.get())
2047}
2048
2049// How many blocks [`read_intra_mode`] decoded a real (nonzero-size) palette-Y
2050// use for, across every call on the current thread -- the same before/after
2051// counter pattern as [`FILTER_INTRA_HITS`], proving a stream actually
2052// exercised palette reconstruction rather than only reading and refusing the
2053// `palette_y_mode` symbol.
2054thread_local! {
2055 static PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2056}
2057
2058/// Current value of [`PALETTE_HITS`].
2059#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2060pub(crate) fn palette_hits() -> usize {
2061 PALETTE_HITS.with(|c| c.get())
2062}
2063
2064// lane-tiles r12: of those, how many sat at their own TILE's left column --
2065// exactly the blocks whose palette cache/ctx must NOT see the previous tile's
2066// colours (`av1_get_palette_cache`'s `xd->left_mbmi == NULL`). A multi-tile
2067// palette gate that never hits one proves nothing about the tile guard.
2068thread_local! {
2069 static PALETTE_TILE_LEFT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2070}
2071
2072/// Current value of [`PALETTE_TILE_LEFT_HITS`].
2073#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2074pub(crate) fn palette_tile_left_hits() -> usize {
2075 PALETTE_TILE_LEFT_HITS.with(|c| c.get())
2076}
2077
2078// lane-palette2 r1: as [`PALETTE_HITS`], for a real (nonzero-size) chroma
2079// palette use -- proves a stream actually reconstructed UV palette pixels,
2080// not just read and refused the `palette_uv_mode` symbol.
2081thread_local! {
2082 static PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2083}
2084
2085/// Current value of [`PALETTE_UV_HITS`].
2086#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2087pub(crate) fn palette_uv_hits() -> usize {
2088 PALETTE_UV_HITS.with(|c| c.get())
2089}
2090
2091// lane-palette2 r1: how many HORZ/VERT rect intra strips ([`read_intra_mode_rect`])
2092// decoded a real palette-Y use -- proves the rect strip's own palette syntax
2093// (not just the square path's) actually fired.
2094thread_local! {
2095 static PALETTE_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2096}
2097
2098/// Current value of [`PALETTE_RECT_HITS`].
2099#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2100pub(crate) fn palette_rect_hits() -> usize {
2101 PALETTE_RECT_HITS.with(|c| c.get())
2102}
2103
2104// lane-palette2 r6: how many HORZ/VERT rect intra strips ran the
2105// [`palette_bsize_ctx_wh`]-gated code path in [`read_intra_mode_rect`] --
2106// i.e. `allow_screen_content_tools` was set and the strip's `bw`x`bh` was in
2107// range, so `palette_y_mode`/`palette_uv_mode` were actually read (and, per
2108// RD, almost always refused-on-use because the block doesn't end up USING a
2109// palette -- see r5's report). This is the site the removed refusal
2110// ("a HORZ/VERT intra strip in a screen-content frame") used to guard: it
2111// fired here whether or not the block picked a palette, so this is the
2112// counter that proves the case r5's narrower [`PALETTE_RECT_HITS`] almost
2113// never observes.
2114thread_local! {
2115 static RECT_SCREEN_CONTENT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2116}
2117
2118/// Current value of [`RECT_SCREEN_CONTENT_HITS`].
2119#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2120pub(crate) fn rect_screen_content_hits() -> usize {
2121 RECT_SCREEN_CONTENT_HITS.with(|c| c.get())
2122}
2123
2124// lane-palette2 r1: how many palette-Y luma transform UNITS decoded under a
2125// split luma transform (`logical_tx != side`) -- proves the per-TU index-map
2126// windowing actually ran, not just that the whole-block path stayed exact.
2127// Counts units, not blocks (a 64x64 palette block split to 16x16 TUs adds 16);
2128// first actually incremented in r7, when the refusal it guarded was lifted.
2129thread_local! {
2130 static PALETTE_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2131}
2132
2133thread_local! {
2134 /// lane-kf900 r4: rect intra strips that ACTUALLY use a palette -- the
2135 /// 1:4 shapes (32x8/8x32, 16x4/4x16) and the sub-16x16 2:1 leaves
2136 /// (16x8/8x16), the two shapes the lifted refusals named.
2137 static RECT4_PALETTE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2138}
2139
2140/// Current value of [`RECT4_PALETTE_HITS`].
2141#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2142pub(crate) fn rect4_palette_hits() -> usize {
2143 RECT4_PALETTE_HITS.with(|c| c.get())
2144}
2145
2146/// Current value of [`PALETTE_SPLIT_TX_HITS`].
2147#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2148pub(crate) fn palette_split_tx_hits() -> usize {
2149 PALETTE_SPLIT_TX_HITS.with(|c| c.get())
2150}
2151
2152thread_local! {
2153 /// lane-pal8 r1: square 8x8 LEAVES ([`decode_leaf8`]) that actually use a
2154 /// palette (Y or UV) -- the shape every 8-bit `--tune-content=screen`
2155 /// stream stopped on, since aomenc palettes square blocks at 8 bit and
2156 /// `--min-partition-size=8` puts them on this leaf path.
2157 static PALETTE_LEAF8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2158}
2159
2160/// Current value of [`PALETTE_LEAF8_HITS`].
2161#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2162pub(crate) fn palette_leaf8_hits() -> usize {
2163 PALETTE_LEAF8_HITS.with(|c| c.get())
2164}
2165
2166/// Zeroes [`PALETTE_LEAF8_HITS`] (per-attempt gate counting).
2167#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2168pub(crate) fn reset_palette_leaf8_hits() {
2169 PALETTE_LEAF8_HITS.with(|c| c.set(0));
2170}
2171
2172thread_local! {
2173 /// lane-pal8 r1: NON-SKIP palette blocks on a superblock-level (64-level)
2174 /// HORZ/VERT or 1:4 strip ([`decode_block_rect64`]) -- i.e. a palette
2175 /// block that also carries a real, corner-cropped luma transform.
2176 static PALETTE_SB_STRIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2177}
2178
2179/// Current value of [`PALETTE_SB_STRIP_HITS`].
2180#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2181pub(crate) fn palette_sb_strip_hits() -> usize {
2182 PALETTE_SB_STRIP_HITS.with(|c| c.get())
2183}
2184
2185/// Zeroes [`PALETTE_SB_STRIP_HITS`] (per-attempt gate counting).
2186#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2187pub(crate) fn reset_palette_sb_strip_hits() {
2188 PALETTE_SB_STRIP_HITS.with(|c| c.set(0));
2189}
2190
2191// lane-t900 r22: palette blocks reconstructed inside an INTER frame (the
2192// intra-in-inter path, `decode_inter_block`/`decode_inter_block8`) -- counted
2193// apart from [`PALETTE_HITS`] so a witness gate can prove the INTER-frame
2194// capability rather than the key frame's, which every screen stream also
2195// carries.
2196thread_local! {
2197 static INTRA_IN_INTER_PALETTE_Y_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2198 static INTRA_IN_INTER_PALETTE_UV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2199}
2200
2201// lane-t900 r23: as [`INTRA_IN_INTER_PALETTE_Y_HITS`], narrowed to the 8x8
2202// LEAF site ([`decode_inter_block8`]'s intra arm) -- the >=16 site fires the
2203// shared counter too, so only this one proves a gate really reached the leaf
2204// where the refusal used to sit.
2205thread_local! {
2206 static INTER8_PALETTE_HITS: std::cell::Cell<(usize, usize)> =
2207 const { std::cell::Cell::new((0, 0)) };
2208}
2209
2210/// Current values of the 8x8-leaf intra-in-inter palette counters, `(y, uv)`.
2211pub(crate) fn inter8_palette_hits() -> (usize, usize) {
2212 INTER8_PALETTE_HITS.with(std::cell::Cell::get)
2213}
2214
2215/// Current values of the two intra-in-inter palette counters, `(y, uv)`.
2216pub(crate) fn intra_in_inter_palette_hits() -> (usize, usize) {
2217 (
2218 INTRA_IN_INTER_PALETTE_Y_HITS.with(|c| c.get()),
2219 INTRA_IN_INTER_PALETTE_UV_HITS.with(|c| c.get()),
2220 )
2221}
2222
2223// lane-hgkf r2: SKIPPED intra blocks whose `tx_depth` split the luma transform
2224// and which are therefore predicted one transform unit at a time (a skipped
2225// block codes no coefficients, so nothing else in the stream witnesses this
2226// path -- only the pixels do).
2227thread_local! {
2228 static SKIP_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2229}
2230
2231/// Current value of [`SKIP_SPLIT_TX_HITS`] (blocks, not units).
2232pub fn skip_split_tx_hits() -> usize {
2233 SKIP_SPLIT_TX_HITS.with(|c| c.get())
2234}
2235
2236// lane-svt1: SKIPPED square blocks carrying a palette/intrabc prediction whose
2237// `tx_depth` split the luma transform -- the arm that predicted DC off the
2238// block edges before the fix. Like [`SKIP_SPLIT_TX_HITS`] only the pixels
2239// witness this path, so a gate that wants it needs the counter.
2240thread_local! {
2241 static SKIP_SPLIT_TX_OVERRIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2242}
2243
2244/// Current value of [`SKIP_SPLIT_TX_OVERRIDE_HITS`] (blocks).
2245pub fn skip_split_tx_override_hits() -> usize {
2246 SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.get())
2247}
2248
2249/// Zeroes [`SKIP_SPLIT_TX_OVERRIDE_HITS`] before a gate's own decode attempt.
2250pub fn reset_skip_split_tx_override_hits() {
2251 SKIP_SPLIT_TX_OVERRIDE_HITS.with(|c| c.set(0));
2252}
2253
2254// lane-svtinter: palette colour-index maps whose block is cut by the frame's
2255// bottom/right mi edge, so spec 5.11.50's `onscreenWidth`/`onscreenHeight`
2256// really are smaller than the block and FEWER symbols are read than the
2257// block has cells (class map-read-past-frame-edge).
2258thread_local! {
2259 static PALETTE_ONSCREEN_CUT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2260}
2261
2262/// Current value of [`PALETTE_ONSCREEN_CUT_HITS`] (colour-index maps).
2263pub fn palette_onscreen_cut_hits() -> usize {
2264 PALETTE_ONSCREEN_CUT_HITS.with(|c| c.get())
2265}
2266
2267/// Zeroes [`PALETTE_ONSCREEN_CUT_HITS`] before a gate's own decode attempt.
2268pub fn reset_palette_onscreen_cut_hits() {
2269 PALETTE_ONSCREEN_CUT_HITS.with(|c| c.set(0));
2270}
2271
2272/// Zeroes [`SKIP_SPLIT_TX_HITS`] before a gate's own decode attempt.
2273pub fn reset_skip_split_tx_hits() {
2274 SKIP_SPLIT_TX_HITS.with(|c| c.set(0));
2275}
2276
2277// lane-intrainter r1: intra blocks inside an INTER frame whose `tx_depth`
2278// symbol split their luma transform, bucketed by block side (8, 16, 32, 64) --
2279// the gate's proof that the lifted path actually ran, per size.
2280thread_local! {
2281 static INTRA_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 4]> =
2282 const { std::cell::Cell::new([0; 4]) };
2283}
2284
2285/// Current value of [`INTRA_IN_INTER_SPLIT_TX_HITS`], indexed 8/16/32/64.
2286#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2287pub(crate) fn intra_in_inter_split_tx_hits() -> [usize; 4] {
2288 INTRA_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
2289}
2290
2291 /// A just-decoded palette-Y block's own predicted pixels
2292 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
2293 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
2294 /// same off-the-call-stack idiom as [`ENABLE_EDGE_FILTER`] (threading a
2295 /// per-block override through `read_plane`'s two dozen call sites is the
2296 /// alternative this avoids). Always empty again once that call consumes
2297 /// it (`.take()`), so a non-palette block's own `reconstruct` call never
2298 /// sees stale state.
2299
2300
2301/// Arms the pending [`PALETTE_PRED`] override for the next `reconstruct`
2302/// (`set`) / consumes it (`take`). Set and take MUST pair: a buffer armed at a
2303/// site whose reconstruct never runs would be picked up by the NEXT block's
2304/// reconstruct (class [[refusal-hides-a-defect]] / stale thread-local), so
2305/// lane-lossless2: one transform unit's window on a block-sized palette
2306/// prediction buffer. A unit reads its prediction at ITS OWN stride, so
2307/// handing it the whole-block buffer makes every unit reconstruct the block's
2308/// top-left corner (the luma split-transform paths already window; the chroma
2309/// ones did not, which is invisible until a lossless frame codes a palette
2310/// block as 4x4 chroma units).
2311fn palette_window(buf: &[u16], stride: usize, ox: usize, oy: usize, w: usize, h: usize) -> Vec<u16> {
2312 (0..h)
2313 .flat_map(|r| buf[(oy + r) * stride + ox..][..w].iter().copied())
2314 .collect()
2315}
2316
2317/// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
2318#[track_caller]
2319fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {
2320 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2321 let stale = fctx.palette_pred.with(|c| c.borrow().is_some());
2322 eprintln!(
2323 "PALSET len={} stale={stale} at {}",
2324 buf.len(),
2325 std::panic::Location::caller()
2326 );
2327 }
2328 fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
2329}
2330
2331#[track_caller]
2332fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
2333 let got = fctx.palette_pred.with(|c| c.borrow_mut().take());
2334 if crate::envflags::env_flag!("EC_DEBUG_PAL") {
2335 eprintln!(
2336 "PALTAKE len={:?} at {}",
2337 got.as_ref().map(Vec::len),
2338 std::panic::Location::caller()
2339 );
2340 }
2341 got
2342}
2343
2344/// The luma window a `UV_CFL_PRED` chroma block averages its AC signal over
2345/// (lane-wave1 step (i)). Parse records the window; [`flush_recon`] reads the
2346/// pixels, because at parse time this block's own luma is still queued.
2347#[derive(Clone, Copy, Debug)]
2348pub(crate) struct CflSrc {
2349 px: usize,
2350 py: usize,
2351 bw: usize,
2352 bh: usize,
2353 /// Which averager the parse site asked for -- [`cfl_ac_q3_rect`] and
2354 /// [`cfl_ac_q3`] are not the same function at `bw == bh`.
2355 rect: bool,
2356}
2357
2358fn cfl_src(px: usize, py: usize, side: usize) -> CflSrc {
2359 CflSrc { px, py, bw: side, bh: side, rect: false }
2360}
2361
2362fn cfl_src_rect(px: usize, py: usize, bw: usize, bh: usize) -> CflSrc {
2363 CflSrc { px, py, bw, bh, rect: true }
2364}
2365
2366/// lane-wave1 step (i): the pixel-writing half of block decoding, recorded
2367/// instead of executed. Each variant is the resolved argument tuple of the
2368/// `PlaneBuf::reconstruct*` call it replaces, so replaying the queue in push
2369/// order performs exactly the same writes in exactly the same order --
2370/// entropy parsing no longer touches the frame's own planes (except the two
2371/// sites named in [`flush_recon`]'s doc), which is what lets step (ii) run
2372/// the replay on a superblock-row wavefront worker.
2373/// The dequantization + inverse transform of one transform unit, kept as its
2374/// INPUTS so that a recorded write carries the work instead of its result
2375/// (lane-wave3): at `EC_AV1_RECON_THREADS > 1` the transform then runs on the
2376/// recon worker, not on the parsing thread. `stride == 0` means the dense
2377/// `w x h` residual; otherwise it is re-laid into the `stride x stride` grid
2378/// `reconstruct_mc_rect` reads both of its buffers at.
2379#[derive(Clone, Copy)]
2380pub(crate) struct TxParams {
2381 pub(crate) w: usize,
2382 pub(crate) h: usize,
2383 pub(crate) bit_depth: u8,
2384 pub(crate) q_idx: i32,
2385 pub(crate) dc_delta: i32,
2386 pub(crate) ac_delta: i32,
2387 pub(crate) tx_type: TxType,
2388 pub(crate) stride: usize,
2389 /// lane-lossless: this transform unit belongs to a lossless frame, so the
2390 /// residual comes off the 4x4 Walsh-Hadamard
2391 /// ([`crate::transform::dequant_and_inverse_wht4x4`]) instead of the
2392 /// DCT/ADST network (libaom `inv_txfm_add`, `av1/common/idct.c`).
2393 pub(crate) lossless: bool,
2394}
2395
2396impl TxParams {
2397 /// The one copy of the produce-the-residual code: the inline path calls it
2398 /// on the parse thread, the wavefront worker calls it on its own, so both
2399 /// are the same function on the same inputs and byte-identical.
2400 fn run(self, grid: &[i32]) -> Vec<i32> {
2401 let residual = if self.lossless {
2402 debug_assert_eq!((self.w, self.h), (4, 4));
2403 debug_assert_eq!(self.tx_type, TxType::DctDct);
2404 crate::transform::dequant_and_inverse_wht4x4(
2405 grid, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2406 )
2407 } else {
2408 dequant_and_inverse_typed_wh(
2409 grid, self.w, self.h, self.bit_depth, self.q_idx, self.dc_delta, self.ac_delta,
2410 self.tx_type,
2411 )
2412 };
2413 // An all-zero grid transforms to the empty marker, and a strided copy
2414 // of zeros is still zeros: the marker passes straight through.
2415 if residual.is_empty() {
2416 return residual;
2417 }
2418 if self.stride == 0 {
2419 return residual;
2420 }
2421 let mut strided = vec![0i32; self.stride * self.stride];
2422 for row in 0..self.h {
2423 strided[row * self.stride..][..self.w]
2424 .copy_from_slice(&residual[row * self.w..][..self.w]);
2425 }
2426 strided
2427 }
2428}
2429
2430/// A recorded write's residual: already transformed, or the coefficients and
2431/// [`TxParams`] the worker transforms itself.
2432pub(crate) enum Residual {
2433 /// An already-transformed residual in the arena, `(offset, len)`; a zero
2434 /// `len` is the all-zero marker [`dense_residual`] expands.
2435 Done(u32, u32),
2436 /// The coefficients live in the pushing tile's arena
2437 /// ([`crate::decode::FrameCtx::coeff_arena`]); this is their `(offset,
2438 /// len)` in it.
2439 Coeffs(TxParams, u32, u32),
2440}
2441
2442impl Residual {
2443 /// The record for a transform unit whose coefficient grid is all zero:
2444 /// the empty marker, so neither the grid nor the residual is cloned and
2445 /// the worker never runs the transform (60% of the 4K segment's units).
2446 fn coeffs(tx: TxParams, grid: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
2447 if is_zero_grid(grid) {
2448 return Self::Done(0, 0);
2449 }
2450 Self::Coeffs(tx, push_coeffs(grid, fctx), grid.len() as u32)
2451 }
2452
2453 /// A residual the parse thread already transformed, kept in the arena
2454 /// instead of its own `Vec`.
2455 fn done(residual: &[i32], fctx: &crate::decode::FrameCtx) -> Self {
2456 // lane-blockmem: a skipped block hands over [`ZERO_RESIDUAL`] itself,
2457 // which is exactly the all-zero marker -- one pointer compare instead
2458 // of copying up to 64 KB of zeros into the arena per block.
2459 if std::ptr::eq(residual.as_ptr(), ZERO_RESIDUAL.as_ptr()) {
2460 return Self::Done(0, 0);
2461 }
2462 Self::Done(push_coeffs(residual, fctx), residual.len() as u32)
2463 }
2464
2465 /// The residual to reconstruct with; `scratch` is where a transform run
2466 /// on this thread lands, so the caller owns that buffer.
2467 fn resolve<'a>(self, arena: &'a [i32], scratch: &'a mut Vec<i32>) -> &'a [i32] {
2468 match self {
2469 Self::Done(off, len) => &arena[off as usize..][..len as usize],
2470 Self::Coeffs(p, off, len) => {
2471 *scratch = p.run(&arena[off as usize..][..len as usize]);
2472 scratch
2473 }
2474 }
2475 }
2476}
2477
2478/// Appends to the tile's coefficient arena, returning the offset the record
2479/// carries; see [`crate::decode::FrameCtx::coeff_arena`].
2480fn push_coeffs(v: &[i32], fctx: &crate::decode::FrameCtx) -> u32 {
2481 fctx.coeff_arena.with(|a| {
2482 let mut a = a.borrow_mut();
2483 let off = a.len();
2484 a.extend_from_slice(v);
2485 off as u32
2486 })
2487}
2488
2489/// [`push_coeffs`] for a recorded prediction.
2490fn push_pred_samples(v: &[u16], fctx: &crate::decode::FrameCtx) -> u32 {
2491 fctx.pred_arena.with(|a| {
2492 let mut a = a.borrow_mut();
2493 let off = a.len();
2494 a.extend_from_slice(v);
2495 off as u32
2496 })
2497}
2498
2499/// An all-zero residual, for the transform units that code no coefficient:
2500/// [`crate::transform::dequant_and_inverse_typed_wh`] returns those EMPTY,
2501/// and the reconstruction loops below read this instead of a per-unit
2502/// `vec![0; w * h]`. Sized for the largest stride a recorded unit can carry
2503/// (a 128-wide inter block's prediction stride).
2504pub(crate) static ZERO_RESIDUAL: [i32; 128 * 128] = [0; 128 * 128];
2505
2506/// lane-blockscratch: one plane's coefficient levels as the block-tail
2507/// neighbour writes want them. A plane that coded nothing (a skipped block, a
2508/// strip with no chroma, luma under a var-tx split whose units already wrote
2509/// themselves) names the shared [`ZERO_RESIDUAL`] instead of allocating and
2510/// zeroing up to 64 KB of its own per block.
2511#[derive(Clone)]
2512enum Grid {
2513 Zero(usize),
2514 Own(Vec<i32>),
2515}
2516
2517/// lane-blockscratch: the mu-chunk chroma collector, allocated by the first
2518/// unit that writes into it. Only a block wider or taller than 64 px codes its
2519/// chroma per 64x64 chunk; every smaller block used to allocate and zero both
2520/// collectors per block and then drop them untouched.
2521fn mu_units(v: &mut Vec<i32>, n: usize) -> &mut Vec<i32> {
2522 if v.is_empty() {
2523 *v = vec![0i32; n];
2524 }
2525 v
2526}
2527
2528impl std::ops::Deref for Grid {
2529 type Target = [i32];
2530 fn deref(&self) -> &[i32] {
2531 match self {
2532 Grid::Zero(n) => &ZERO_RESIDUAL[..*n],
2533 Grid::Own(v) => v,
2534 }
2535 }
2536}
2537
2538/// Whether a coefficient grid codes nothing: a [`Grid::Zero`] unit IS the
2539/// shared [`ZERO_RESIDUAL`], so one pointer compare answers the 60% of
2540/// transform units that code no coefficient without the scan (lane-coefgrid).
2541pub(crate) fn is_zero_grid(grid: &[i32]) -> bool {
2542 std::ptr::eq(grid.as_ptr(), ZERO_RESIDUAL.as_ptr()) || grid.iter().all(|&c| c == 0)
2543}
2544
2545/// `residual`, or `n` zeros when it is the empty all-zero marker.
2546fn dense_residual(residual: &[i32], n: usize) -> &[i32] {
2547 if residual.is_empty() { &ZERO_RESIDUAL[..n] } else { residual }
2548}
2549
2550/// Where a recorded motion-compensated write reads its prediction from.
2551///
2552/// lane-wave4: a block's whole-block prediction (mc + warp + interintra) is
2553/// the parse thread's single biggest reconstruction cost, so at
2554/// `EC_AV1_RECON_THREADS > 1` it is not built at parse at all: the block
2555/// pushes a [`ReconOp::Pred`] carrying the build as a closure, the worker
2556/// runs it into its own three-plane slot, and every transform unit of that
2557/// block then reads its window out of that slot ([`Pred::Cur`]).
2558#[derive(Clone, Copy)]
2559pub(crate) enum Pred<'a> {
2560 /// A prediction the parse thread already built, at its own stride
2561 /// (`stride == 0` means "the reader's own `stride` argument").
2562 Inline(&'a [u16], usize),
2563 /// The current block's deferred prediction: plane, its stride, and this
2564 /// unit's offset into it.
2565 Cur { plane: usize, stride: usize, off: usize },
2566}
2567
2568impl<'a> Pred<'a> {
2569 /// The same prediction read at an explicit stride.
2570 fn view(self, stride: usize) -> Self {
2571 match self {
2572 Self::Inline(b, _) => Self::Inline(b, stride),
2573 Self::Cur { plane, off, .. } => Self::Cur { plane, stride, off },
2574 }
2575 }
2576 /// The materialised buffer and the stride to read it at (`stride` is the
2577 /// reader's own when this prediction was built dense); `None` for a
2578 /// deferred prediction, which only a recorded op can carry.
2579 fn inline(self, stride: usize) -> Option<(&'a [u16], usize)> {
2580 match self {
2581 Self::Inline(b, s) => Some((b, if s == 0 { stride } else { s })),
2582 Self::Cur { .. } => None,
2583 }
2584 }
2585 /// This prediction's window starting `n` samples in.
2586 fn offset(self, n: usize) -> Self {
2587 match self {
2588 Self::Inline(b, s) => Self::Inline(&b[n..], s),
2589 Self::Cur { plane, stride, off } => Self::Cur { plane, stride, off: off + n },
2590 }
2591 }
2592}
2593
2594/// [`Pred`], resolved into what a recorded op carries.
2595pub(crate) enum PredSrc {
2596 /// A prediction window in the tile's prediction arena, `(offset, len)`.
2597 Owned(u32, u32),
2598 /// A window of the block prediction: its plane, its offset, and the
2599 /// stride it is read at -- which is the block's, not necessarily the
2600 /// op's (a transform unit's residual stays dense, so the worker takes
2601 /// its window out of the block prediction itself).
2602 Cur { plane: usize, off: usize, src: usize },
2603}
2604
2605/// One block's whole-block prediction build, deferred to a recon worker.
2606///
2607/// The closure borrows the tile's reference pictures and its own frame-level
2608/// tables; [`WaveGuard`] joins every worker before the tile decoder returns,
2609/// so those borrows outlive it -- the [`ReconPlanes`] trade-off, stated once
2610/// here for the closure's `'static`/`Send` laundering in [`push_pred`].
2611pub(crate) struct PredBuild(
2612 Box<
2613 dyn FnOnce(
2614 &mut PlaneBuf<'static>,
2615 &mut PlaneBuf<'static>,
2616 &mut PlaneBuf<'static>,
2617 &crate::decode::FrameCtx,
2618 // lane-blockmem: the previous block's three prediction buffers,
2619 // refilled in place -- the build used to return three fresh
2620 // `Vec`s per block and drop these.
2621 &mut [Vec<u16>; 3],
2622 ),
2623 >,
2624);
2625
2626// SAFETY: see [`PredBuild`] -- the captured borrows are read-only reference
2627// pictures and frame tables, and the closure runs on exactly one worker.
2628#[allow(unsafe_code)]
2629unsafe impl Send for PredBuild {}
2630
2631/// `true` when this tile's writes are recorded for the wavefront instead of
2632/// performed at the push site, i.e. when a prediction may be deferred.
2633fn recon_deferred(fctx: &crate::decode::FrameCtx) -> bool {
2634 fctx.recon_planes.with(std::cell::Cell::get).is_none()
2635}
2636
2637/// The previous block's prediction buffer, cleared and zero-filled to `n`
2638/// (lane-blockmem): the same bytes the `vec![0u16; n]` it replaces produced,
2639/// without the per-block allocation and free.
2640fn refill(mut v: Vec<u16>, n: usize) -> Vec<u16> {
2641 // A buffer that has to grow anyway is cheaper allocated zeroed (`calloc`)
2642 // than resized element by element -- which is every block on the inline
2643 // path, where there is no previous buffer to reuse.
2644 if v.capacity() < n {
2645 return vec![0u16; n];
2646 }
2647 v.clear();
2648 v.resize(n, 0);
2649 v
2650}
2651
2652/// Records one block's prediction build for the worker that reconstructs it.
2653#[allow(unsafe_code)]
2654fn push_pred<'a>(
2655 fctx: &crate::decode::FrameCtx,
2656 f: impl FnOnce(
2657 &mut PlaneBuf<'static>,
2658 &mut PlaneBuf<'static>,
2659 &mut PlaneBuf<'static>,
2660 &crate::decode::FrameCtx,
2661 &mut [Vec<u16>; 3],
2662 ) + 'a,
2663) {
2664 type Dyn<'x> = dyn FnOnce(
2665 &mut PlaneBuf<'static>,
2666 &mut PlaneBuf<'static>,
2667 &mut PlaneBuf<'static>,
2668 &crate::decode::FrameCtx,
2669 &mut [Vec<u16>; 3],
2670 ) + 'x;
2671 let boxed: Box<Dyn<'a>> = Box::new(f);
2672 // SAFETY: see [`PredBuild`] -- every worker is joined by [`WaveGuard`]
2673 // before the borrows the closure holds go out of scope.
2674 let boxed: Box<Dyn<'static>> = unsafe { std::mem::transmute(boxed) };
2675 push_op(fctx, ReconOp::Pred(PredBuild(boxed)));
2676}
2677
2678/// One superblock's recorded writes plus the two arenas they index -- the
2679/// unit a wavefront worker takes off the queue (lane-recoparse).
2680pub(crate) struct ReconJob {
2681 ops: Vec<ReconOp>,
2682 coeffs: Vec<i32>,
2683 preds: Vec<u16>,
2684}
2685
2686pub(crate) enum ReconOp {
2687 /// lane-wave4: build this block's prediction into the worker's slot.
2688 Pred(PredBuild),
2689 Intra {
2690 plane: usize,
2691 x: usize,
2692 y: usize,
2693 bw: usize,
2694 bh: usize,
2695 /// `true` when the parse site called `reconstruct_rect` (whose
2696 /// `edges_rect` differs from `edges` even at `bw == bh`).
2697 rect: bool,
2698 mode: usize,
2699 angle_delta: i32,
2700 reach: Reach,
2701 residual: Residual,
2702 cfl: Option<(i32, CflSrc)>,
2703 filter_intra: Option<usize>,
2704 smooth_neighbor: bool,
2705 /// The palette/intrabc prediction override, taken off
2706 /// [`FrameCtx::palette_pred`] at PUSH time (parse order), never read
2707 /// from that slot by the replay.
2708 pred: Option<Vec<u16>>,
2709 },
2710 Mc {
2711 plane: usize,
2712 x: usize,
2713 y: usize,
2714 stride: usize,
2715 w: usize,
2716 h: usize,
2717 prediction: PredSrc,
2718 residual: Residual,
2719 },
2720}
2721
2722/// The three planes of the tile currently being decoded, as raw pointers.
2723///
2724/// corner-cut: at one reconstruction thread a recorded write must cost
2725/// nothing -- deferring it to the end of the superblock is +1.2%
2726/// instructions and +4.5% wall on 4K, because the residual is written at
2727/// parse and read back cache-cold at replay. So the recorded op is performed
2728/// at the push site instead, through the pointers the tile decoder registers
2729/// once ([`ReconInline`]), which is the same thread, the same order and the
2730/// same writes as before lane-wave1 -- but the `&mut PlaneBuf` the parse
2731/// stack still holds aliases them, exactly the [`crate::par::Shared`]
2732/// trade-off (Miri's stacked borrows would flag both). The upgrade path is
2733/// threading the three planes down every `read_plane`/`read_inter_plane`
2734/// call site (~40) so the push site owns the borrow it writes through.
2735#[derive(Clone, Copy)]
2736pub(crate) struct ReconPlanes(
2737 *mut PlaneBuf<'static>,
2738 *mut PlaneBuf<'static>,
2739 *mut PlaneBuf<'static>,
2740);
2741
2742// SAFETY: a `FrameCtx` sent to another thread (a frame worker, or
2743// [`filter_ctx_copy`]) is always one whose guard is not installed, so the
2744// value travelling is `None`; the pointers never leave the tile decoder's
2745// own thread.
2746#[allow(unsafe_code)]
2747unsafe impl Send for ReconPlanes {}
2748// SAFETY: the wavefront's workers share one `ReconPlanes` and write provably
2749// disjoint superblocks of it (see [`WaveState`]) -- the [`crate::par::Shared`]
2750// contract, one superblock per band instead of one row band.
2751#[allow(unsafe_code)]
2752unsafe impl Sync for ReconPlanes {}
2753
2754/// Registers the tile's planes for inline reconstruction and unregisters them
2755/// on every exit from the tile decoder, including the `?` ones -- a stale
2756/// pointer here would outlive the planes, since [`FrameCtx`] outlives the
2757/// tile.
2758pub(crate) struct ReconInline<'a>(&'a crate::decode::FrameCtx);
2759
2760#[allow(unsafe_code)]
2761impl<'a> ReconInline<'a> {
2762 /// Installs the guard for this tile when reconstruction is inline
2763 /// (`EC_AV1_RECON_THREADS == 1`, the default); `None` hands every write
2764 /// to the queue instead, for the wavefront workers to replay.
2765 fn install(
2766 fctx: &'a crate::decode::FrameCtx,
2767 y: &mut PlaneBuf<'static>,
2768 u: &mut PlaneBuf<'static>,
2769 v: &mut PlaneBuf<'static>,
2770 ) -> Option<Self> {
2771 if crate::par::recon_threads() != 1 {
2772 return None;
2773 }
2774 // SAFETY: the planes are locals of the tile decoder and outlive the
2775 // guard, which is dropped on every exit from it (including `?`); see
2776 // [`ReconPlanes`] for the aliasing trade-off.
2777 let planes = ReconPlanes(
2778 std::ptr::from_mut(y),
2779 std::ptr::from_mut(u),
2780 std::ptr::from_mut(v),
2781 );
2782 fctx.recon_planes.with(|c| c.set(Some(planes)));
2783 Some(Self(fctx))
2784 }
2785}
2786
2787impl Drop for ReconInline<'_> {
2788 fn drop(&mut self) {
2789 self.0.recon_planes.with(|c| c.set(None));
2790 }
2791}
2792
2793#[allow(unsafe_code)]
2794fn push_op(fctx: &crate::decode::FrameCtx, op: ReconOp) {
2795 if let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) {
2796 // SAFETY: see [`ReconPlanes`] -- one thread, and the write is the one
2797 // the parse site would have performed itself before lane-wave1.
2798 // The inline path never records coefficients (the transform runs at
2799 // the push site), so the arena is not read here.
2800 unsafe {
2801 exec_op(op, &mut *y, &mut *u, &mut *v, &mut Default::default(), &[], &[], fctx)
2802 };
2803 return;
2804 }
2805 fctx.recon_ops.with(|c| c.borrow_mut().push(op));
2806}
2807
2808/// lane-wave1 step (ii): the superblock-row wavefront a tile's recorded
2809/// writes are reconstructed on when `EC_AV1_RECON_THREADS > 1`.
2810///
2811/// The parser keeps parsing and never touches the planes; each superblock's
2812/// drained `Vec<ReconOp>` becomes one job, keyed by the superblock's own
2813/// `(row, column)` inside the tile (128x128 superblocks are one job for all
2814/// four of their 64x64 visits, since a 128 block writes across quadrants).
2815/// A worker may start job `(r, c)` once `(r - 1, min(c + 1, last_col))` and
2816/// `(r, c - 1)` are complete -- the classic wavefront rule, which covers
2817/// every pixel an intra predictor can read (its edges reach one block right
2818/// along the row above and one block down the column to the left, both
2819/// inside those two neighbours) and every CfL AC read (this block's own
2820/// luma, written by this same job). Jobs are handed out in raster order, so
2821/// the oldest outstanding one always has its dependencies met: no deadlock.
2822///
2823/// Gate counters incremented inside `reconstruct*`/`intra`/`mc` are
2824/// `thread_local!` and miss every worker, which is why the default is 1.
2825pub(crate) struct WaveState {
2826 q: std::sync::Mutex<WaveQueue>,
2827 cv: std::sync::Condvar,
2828 planes: ReconPlanes,
2829 /// The two [`FrameCtx`] fields reconstruction reads (`sample_max` is
2830 /// `bit_depth`'s; everything else a `reconstruct*` needs is in the op).
2831 bit_depth: u8,
2832 enable_edge_filter: bool,
2833 last_col: usize,
2834}
2835
2836struct WaveQueue {
2837 /// Queued jobs per superblock ROW, in column order (lane-wave5). Only a
2838 /// row's front job can ever be runnable -- a job waits on its own left
2839 /// neighbour -- so a worker takes the lowest row whose front job's
2840 /// dependencies are met. Popping the raster-oldest job instead (what
2841 /// this replaced) put every worker on the SAME row, where the wavefront
2842 /// rule serialises them, which is why 4 workers ran the tile at 1.2x.
2843 rows: Vec<std::collections::VecDeque<(usize, ReconJob)>>,
2844 /// Jobs sitting in `rows`, so a worker knows the queue is empty without
2845 /// walking it.
2846 queued: usize,
2847 /// Per superblock row, the last column reconstructed (-1 = none yet).
2848 done: Vec<isize>,
2849 /// Per superblock row, the last column PARSED (submitted, whether or not
2850 /// it recorded any write) and the last column actually pushed as a job
2851 /// (-1 = none). A row is fully reconstructed once it has been parsed to
2852 /// `last_col` and `done` has caught up with `last_push` -- lane-pipefilt
2853 /// reads that to release the row's filters (see [`wave_rows_complete`]).
2854 last_sub: Vec<isize>,
2855 last_push: Vec<isize>,
2856 /// Jobs popped but not finished -- what [`wave_barrier`] waits out.
2857 active: usize,
2858 closed: bool,
2859 /// lane-sballoc: the three per-superblock buffers a finished job hands
2860 /// back, so [`wave_submit`] takes a warm allocation (capacity kept, no
2861 /// first-touch page faults) instead of the `Vec::with_capacity` it used
2862 /// to make per superblock -- 3 allocations and 3 frees per superblock,
2863 /// 4680 per 4K frame. Bounded at `recon_threads + 2` sets, and it lives
2864 /// inside the queue's own mutex, which both sides already take.
2865 free: Vec<JobBufs>,
2866 free_cap: usize,
2867}
2868
2869/// One recycled set of [`ReconJob`] buffers (lane-sballoc).
2870type JobBufs = (Vec<ReconOp>, Vec<i32>, Vec<u16>);
2871
2872impl WaveQueue {
2873 /// The lowest-row queued job whose wavefront dependencies are satisfied,
2874 /// or `None` (with the blocking condition counted when instrumented).
2875 fn take_runnable(
2876 &mut self,
2877 last_col: usize,
2878 stats: bool,
2879 ) -> Option<(usize, usize, ReconJob)> {
2880 let mut blocked: Option<bool> = None;
2881 for r in 0..self.rows.len() {
2882 let Some(front) = self.rows[r].front() else {
2883 continue;
2884 };
2885 let c = front.0;
2886 let above = r == 0 || self.done[r - 1] >= (c + 1).min(last_col) as isize;
2887 let left = c == 0 || self.done[r] >= c as isize - 1;
2888 if above && left {
2889 let (c, job) = self.rows[r].pop_front().expect("front checked above");
2890 self.queued -= 1;
2891 return Some((r, c, job));
2892 }
2893 if blocked.is_none() {
2894 blocked = Some(above);
2895 }
2896 }
2897 if stats {
2898 match blocked {
2899 Some(true) => WS_BLOCK_LEFT.fetch_add(1, Relaxed),
2900 Some(false) => WS_BLOCK_ABOVE.fetch_add(1, Relaxed),
2901 None => 0,
2902 };
2903 }
2904 None
2905 }
2906}
2907
2908/// lane-wave5 instrumentation, on `EC_AV1_WAVE_STATS=1`: where a recon
2909/// worker's time goes (busy replaying, waiting for a dependency, idle on an
2910/// empty queue), how far ahead the parse thread is, and how often the two
2911/// parse-time pixel reads barrier the wavefront. Cumulative for the process,
2912/// dumped by every [`WaveGuard`] drop, so the LAST line of a decode is the
2913/// whole run.
2914const WS_SLOTS: usize = 16;
2915use std::sync::atomic::AtomicU64;
2916use std::sync::atomic::Ordering::Relaxed;
2917static WS_JOBS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2918static WS_OPS: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2919static WS_BUSY: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2920static WS_WAIT: [AtomicU64; WS_SLOTS] = [const { AtomicU64::new(0) }; WS_SLOTS];
2921static WS_BLOCK_ABOVE: AtomicU64 = AtomicU64::new(0);
2922static WS_BLOCK_LEFT: AtomicU64 = AtomicU64::new(0);
2923/// Parse-thread time between two submits, i.e. everything parse still does
2924/// itself (symbol decode plus the predictions not deferred).
2925static WS_PARSE: AtomicU64 = AtomicU64::new(0);
2926/// Parse-thread time spent waiting for the wavefront: at [`wave_barrier`]
2927/// (the intrabc/interintra reads) and at the tile's end.
2928static WS_BARRIER: AtomicU64 = AtomicU64::new(0);
2929static WS_BARRIERS: AtomicU64 = AtomicU64::new(0);
2930static WS_DRAIN: AtomicU64 = AtomicU64::new(0);
2931static WS_TILES: AtomicU64 = AtomicU64::new(0);
2932
2933fn wave_stats() -> bool {
2934 static ON: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
2935 match ON.load(Relaxed) {
2936 0 => {
2937 let on = crate::envflags::var("EC_AV1_WAVE_STATS")
2938 .map(|v| v.trim() == "1")
2939 .unwrap_or(false);
2940 ON.store(1 + u8::from(on), Relaxed);
2941 on
2942 }
2943 n => n == 2,
2944 }
2945}
2946
2947fn wave_stats_dump() {
2948 let ms = |n: u64| n as f64 / 1e6;
2949 let mut s = format!("wave_stats tiles={}", WS_TILES.load(Relaxed));
2950 for i in 0..WS_SLOTS {
2951 let jobs = WS_JOBS[i].load(Relaxed);
2952 if jobs == 0 {
2953 continue;
2954 }
2955 s += &format!(
2956 " | w{i} jobs={jobs} ops/job={:.1} busy={:.0}ms wait={:.0}ms wait/job={:.0}us",
2957 WS_OPS[i].load(Relaxed) as f64 / jobs as f64,
2958 ms(WS_BUSY[i].load(Relaxed)),
2959 ms(WS_WAIT[i].load(Relaxed)),
2960 WS_WAIT[i].load(Relaxed) as f64 / jobs as f64 / 1e3,
2961 );
2962 }
2963 s += &format!(
2964 " | pipe={}/{}",
2965 PIPE_FRAMES.load(Relaxed),
2966 PIPE_FRAMES.load(Relaxed) + PIPE_WHOLE.load(Relaxed),
2967 );
2968 s += &format!(
2969 " | parse={:.0}ms barrier={:.0}ms/{} drain={:.0}ms block_above={} block_left={}",
2970 ms(WS_PARSE.load(Relaxed)),
2971 ms(WS_BARRIER.load(Relaxed)),
2972 WS_BARRIERS.load(Relaxed),
2973 ms(WS_DRAIN.load(Relaxed)),
2974 WS_BLOCK_ABOVE.load(Relaxed),
2975 WS_BLOCK_LEFT.load(Relaxed),
2976 );
2977 eprintln!("{s}");
2978}
2979
2980#[allow(unsafe_code)]
2981fn wave_worker(st: &WaveState, idx: usize) {
2982 let fctx = FrameCtx::new();
2983 fctx.bit_depth.set(st.bit_depth);
2984 fctx.enable_edge_filter.set(st.enable_edge_filter);
2985 let stats = wave_stats();
2986 let slot = idx.min(WS_SLOTS - 1);
2987 loop {
2988 let t0 = std::time::Instant::now();
2989 let mut q = st.q.lock().unwrap();
2990 let (r, c, job) = loop {
2991 if let Some(job) = q.take_runnable(st.last_col, stats) {
2992 break job;
2993 }
2994 if q.closed && q.queued == 0 {
2995 return;
2996 }
2997 q = st.cv.wait(q).unwrap();
2998 };
2999 q.active += 1;
3000 drop(q);
3001 if stats {
3002 WS_WAIT[slot].fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3003 WS_JOBS[slot].fetch_add(1, Relaxed);
3004 WS_OPS[slot].fetch_add(job.ops.len() as u64, Relaxed);
3005 }
3006 let t1 = std::time::Instant::now();
3007 let ReconPlanes(y, u, v) = st.planes;
3008 // SAFETY: this job writes only superblock (r, c)'s own pixels, and
3009 // every superblock that could have written or be reading them is
3010 // complete by the wavefront rule above.
3011 let mut cur: [Vec<u16>; 3] = Default::default();
3012 let ReconJob { mut ops, mut coeffs, mut preds } = job;
3013 unsafe {
3014 for op in ops.drain(..) {
3015 exec_op(op, &mut *y, &mut *u, &mut *v, &mut cur, &coeffs, &preds, &fctx);
3016 }
3017 }
3018 if stats {
3019 WS_BUSY[slot].fetch_add(t1.elapsed().as_nanos() as u64, Relaxed);
3020 }
3021 coeffs.clear();
3022 preds.clear();
3023 let mut q = st.q.lock().unwrap();
3024 // lane-sballoc: hand the three buffers back for the next submit.
3025 if q.free.len() < q.free_cap {
3026 q.free.push((ops, coeffs, preds));
3027 }
3028 q.done[r] = c as isize;
3029 q.active -= 1;
3030 st.cv.notify_all();
3031 }
3032}
3033
3034/// Installs the wavefront for one tile and joins its workers on every exit
3035/// from the tile decoder, including the `?` ones -- the jobs hold raw
3036/// pointers into the tile's planes, so no worker may outlive them.
3037/// (lane-pool1: the workers come from this thread's persistent pool, so a
3038/// tile costs a batch submit rather than `EC_AV1_RECON_THREADS` fresh threads
3039/// with fresh scratch.)
3040pub(crate) struct WaveGuard<'a>(
3041 &'a crate::decode::FrameCtx,
3042 Option<crate::par::Batch<'static>>,
3043);
3044
3045#[allow(unsafe_code)]
3046impl<'a> WaveGuard<'a> {
3047 fn install(
3048 fctx: &'a crate::decode::FrameCtx,
3049 y: &mut PlaneBuf<'static>,
3050 u: &mut PlaneBuf<'static>,
3051 v: &mut PlaneBuf<'static>,
3052 rows: usize,
3053 cols: usize,
3054 ) -> Option<Self> {
3055 let threads = crate::par::recon_threads();
3056 if threads == 1 || rows == 0 || cols == 0 {
3057 return None;
3058 }
3059 let st = std::sync::Arc::new(WaveState {
3060 q: std::sync::Mutex::new(WaveQueue {
3061 rows: (0..rows).map(|_| std::collections::VecDeque::new()).collect(),
3062 queued: 0,
3063 done: vec![-1; rows],
3064 last_sub: vec![-1; rows],
3065 last_push: vec![-1; rows],
3066 active: 0,
3067 closed: false,
3068 free: Vec::new(),
3069 free_cap: threads + 2,
3070 }),
3071 cv: std::sync::Condvar::new(),
3072 // SAFETY: the planes are locals of the tile decoder and outlive
3073 // this guard, which joins every worker in `drop`.
3074 planes: ReconPlanes(
3075 std::ptr::from_mut(y),
3076 std::ptr::from_mut(u),
3077 std::ptr::from_mut(v),
3078 ),
3079 bit_depth: fctx.bit_depth.with(std::cell::Cell::get),
3080 enable_edge_filter: fctx.enable_edge_filter.with(std::cell::Cell::get),
3081 last_col: cols - 1,
3082 });
3083 let batch = crate::par::Batch::new("ec-av1-recon");
3084 for idx in 0..threads {
3085 let st = std::sync::Arc::clone(&st);
3086 batch.submit(move || wave_worker(&st, idx));
3087 }
3088 fctx.wave.with(|w| *w.borrow_mut() = Some(st));
3089 fctx.wave_mark.with(|c| c.set(Some(std::time::Instant::now())));
3090 Some(Self(fctx, Some(batch)))
3091 }
3092}
3093
3094impl Drop for WaveGuard<'_> {
3095 fn drop(&mut self) {
3096 let st = self.0.wave.with(|w| w.borrow_mut().take());
3097 if let Some(st) = st {
3098 st.q.lock().unwrap().closed = true;
3099 st.cv.notify_all();
3100 }
3101 let t0 = std::time::Instant::now();
3102 // Dropping the batch waits every worker out, as the joins did.
3103 drop(self.1.take());
3104 if wave_stats() {
3105 WS_DRAIN.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3106 WS_TILES.fetch_add(1, Relaxed);
3107 wave_stats_dump();
3108 }
3109 }
3110}
3111
3112/// An empty buffer for the next superblock: the recycled one when it is at
3113/// least as big as the superblock just parsed, else a fresh sized one
3114/// (lane-sballoc; `v` is always empty).
3115fn reuse<T>(mut v: Vec<T>, cap: usize) -> Vec<T> {
3116 if v.capacity() < cap {
3117 v.reserve_exact(cap - v.len());
3118 }
3119 v
3120}
3121
3122/// Hands superblock `(r, c)`'s recorded writes to the wavefront. `false`
3123/// when there is no wavefront (one reconstruction thread), in which case the
3124/// caller replays them itself.
3125fn wave_submit(fctx: &crate::decode::FrameCtx, r: usize, c: usize) -> bool {
3126 let st = fctx.wave.with(|w| w.borrow().clone());
3127 let Some(st) = st else { return false };
3128 // lane-blockmem: the op list is replaced sized for the next superblock,
3129 // exactly as the two arenas below are -- taking it left a zero-capacity
3130 // `Vec` that regrew (and memmoved every recorded op) from nothing on
3131 // every superblock.
3132 // lane-sballoc: the replacement comes from the finished jobs' free list
3133 // when there is one (warm capacity, already faulted in); only the first
3134 // superblocks of a tile allocate.
3135 let mut q = st.q.lock().unwrap();
3136 let (sops, scoeffs, spreds) = q.free.pop().unwrap_or_default();
3137 let ops = fctx.recon_ops.with(|c| {
3138 let mut c = c.borrow_mut();
3139 let cap = c.len();
3140 std::mem::replace(&mut *c, reuse(sops, cap))
3141 });
3142 // The job owns its coefficients: the arena is replaced by an empty one
3143 // sized for the next superblock, so parse never regrows from nothing and
3144 // the worker frees this buffer once, instead of once per unit.
3145 let coeffs = fctx.coeff_arena.with(|c| {
3146 let mut c = c.borrow_mut();
3147 let cap = c.len();
3148 std::mem::replace(&mut *c, reuse(scoeffs, cap))
3149 });
3150 let preds = fctx.pred_arena.with(|c| {
3151 let mut c = c.borrow_mut();
3152 let cap = c.len();
3153 std::mem::replace(&mut *c, reuse(spreds, cap))
3154 });
3155 {
3156 if (c as isize) > q.last_sub[r] {
3157 q.last_sub[r] = c as isize;
3158 }
3159 if !ops.is_empty() {
3160 q.rows[r].push_back((c, ReconJob { ops, coeffs, preds }));
3161 q.queued += 1;
3162 q.last_push[r] = c as isize;
3163 }
3164 drop(q);
3165 st.cv.notify_all();
3166 }
3167 if wave_stats() {
3168 let now = std::time::Instant::now();
3169 if let Some(t) = fctx.wave_mark.with(|c| c.replace(Some(now))) {
3170 WS_PARSE.fetch_add((now - t).as_nanos() as u64, Relaxed);
3171 }
3172 }
3173 true
3174}
3175
3176/// Waits until every submitted job is reconstructed, so the parser may read
3177/// the planes itself (the intrabc source fetch and the interintra intra
3178/// predictor -- see [`flush_recon`]).
3179fn wave_barrier(fctx: &crate::decode::FrameCtx) {
3180 let st = fctx.wave.with(|w| w.borrow().clone());
3181 let Some(st) = st else { return };
3182 let stats = wave_stats();
3183 let t0 = std::time::Instant::now();
3184 let mut q = st.q.lock().unwrap();
3185 while q.queued > 0 || q.active > 0 {
3186 q = st.cv.wait(q).unwrap();
3187 }
3188 drop(q);
3189 if stats {
3190 WS_BARRIER.fetch_add(t0.elapsed().as_nanos() as u64, Relaxed);
3191 WS_BARRIERS.fetch_add(1, Relaxed);
3192 }
3193}
3194
3195/// Performs an intra write at its push site when the tile registered its
3196/// planes for inline reconstruction ([`ReconPlanes`]); `false` when the
3197/// caller must record it for the wavefront workers instead.
3198#[allow(unsafe_code)]
3199#[allow(clippy::too_many_arguments)]
3200fn inline_intra(
3201 plane: usize,
3202 x: usize,
3203 oy: usize,
3204 bw: usize,
3205 bh: usize,
3206 rect: bool,
3207 mode: usize,
3208 angle_delta: i32,
3209 reach: Reach,
3210 residual: &[i32],
3211 cfl: Option<(i32, CflSrc)>,
3212 filter_intra: Option<usize>,
3213 smooth_neighbor: bool,
3214 fctx: &crate::decode::FrameCtx,
3215) -> bool {
3216 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3217 return false;
3218 };
3219 let pred = take_palette_pred(fctx);
3220 // SAFETY: see [`ReconPlanes`].
3221 unsafe {
3222 exec_intra(
3223 &mut *y, &mut *u, &mut *v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach,
3224 residual, cfl, filter_intra, smooth_neighbor, pred, fctx,
3225 );
3226 }
3227 true
3228}
3229
3230/// [`inline_intra`] for a motion-compensated write.
3231#[allow(unsafe_code)]
3232#[allow(clippy::too_many_arguments)]
3233fn inline_mc(
3234 plane: usize,
3235 x: usize,
3236 oy: usize,
3237 stride: usize,
3238 w: usize,
3239 h: usize,
3240 prediction: &[u16],
3241 residual: &[i32],
3242 fctx: &crate::decode::FrameCtx,
3243) -> bool {
3244 let Some(ReconPlanes(y, u, v)) = fctx.recon_planes.with(std::cell::Cell::get) else {
3245 return false;
3246 };
3247 // SAFETY: see [`ReconPlanes`].
3248 unsafe {
3249 exec_mc(&mut *y, &mut *u, &mut *v, plane, x, oy, stride, w, h, prediction, residual, fctx);
3250 }
3251 true
3252}
3253
3254/// [`PlaneBuf::reconstruct`], recorded (lane-wave1 step (i)).
3255#[allow(clippy::too_many_arguments)]
3256fn push_intra(
3257 plane: usize,
3258 x: usize,
3259 y: usize,
3260 side: usize,
3261 mode: usize,
3262 angle_delta: i32,
3263 reach: Reach,
3264 residual: &[i32],
3265 cfl: Option<(i32, CflSrc)>,
3266 filter_intra: Option<usize>,
3267 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
3268) {
3269 if inline_intra(
3270 plane, x, y, side, side, false, mode, angle_delta, reach, residual, cfl, filter_intra,
3271 smooth_neighbor, fctx,
3272 ) {
3273 return;
3274 }
3275 let pred = take_palette_pred(fctx);
3276 push_op(fctx, ReconOp::Intra {
3277 plane, x, y, bw: side, bh: side, rect: false, mode, angle_delta, reach,
3278 residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred,
3279 });
3280}
3281
3282/// [`PlaneBuf::reconstruct_rect`], recorded (lane-wave1 step (i)).
3283#[allow(clippy::too_many_arguments)]
3284fn push_intra_rect(
3285 plane: usize,
3286 x: usize,
3287 y: usize,
3288 bw: usize,
3289 bh: usize,
3290 mode: usize,
3291 angle_delta: i32,
3292 reach: Reach,
3293 residual: &[i32],
3294 cfl: Option<(i32, CflSrc)>,
3295 filter_intra: Option<usize>,
3296 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
3297) {
3298 if inline_intra(
3299 plane, x, y, bw, bh, true, mode, angle_delta, reach, residual, cfl, filter_intra,
3300 smooth_neighbor, fctx,
3301 ) {
3302 return;
3303 }
3304 let pred = take_palette_pred(fctx);
3305 push_op(fctx, ReconOp::Intra {
3306 plane, x, y, bw, bh, rect: true, mode, angle_delta, reach,
3307 residual: Residual::done(residual, fctx), cfl, filter_intra, smooth_neighbor, pred,
3308 });
3309}
3310
3311/// [`PlaneBuf::reconstruct_mc_rect`] at `stride == w == h == side`, recorded.
3312fn push_mc(
3313 plane: usize,
3314 x: usize,
3315 y: usize,
3316 side: usize,
3317 prediction: Pred<'_>,
3318 residual: &[i32], fctx: &crate::decode::FrameCtx,
3319) {
3320 push_mc_rect(plane, x, y, side, side, side, prediction, residual, fctx);
3321}
3322
3323/// [`PlaneBuf::reconstruct_mc_rect`], recorded (lane-wave1 step (i)).
3324#[allow(clippy::too_many_arguments)]
3325fn push_mc_rect(
3326 plane: usize,
3327 x: usize,
3328 y: usize,
3329 stride: usize,
3330 w: usize,
3331 h: usize,
3332 prediction: Pred<'_>,
3333 residual: &[i32], fctx: &crate::decode::FrameCtx,
3334) {
3335 let (src, stride) = match prediction.inline(stride) {
3336 Some(v) => v,
3337 None => {
3338 let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() };
3339 push_op(fctx, ReconOp::Mc {
3340 plane, x, y, stride: ss, w, h,
3341 prediction: PredSrc::Cur { plane: sp, off, src: ss },
3342 residual: Residual::done(residual, fctx),
3343 });
3344 return;
3345 }
3346 };
3347 if inline_mc(plane, x, y, stride, w, h, src, residual, fctx) {
3348 return;
3349 }
3350 push_op(fctx, ReconOp::Mc {
3351 plane, x, y, stride, w, h,
3352 // The whole window `reconstruct_mc_rect` reads at `stride`, not
3353 // `w * h`: the record keeps exactly what `src.to_vec()` carried.
3354 prediction: PredSrc::Owned(push_pred_samples(src, fctx), src.len() as u32),
3355 residual: Residual::done(residual, fctx),
3356 });
3357}
3358
3359/// [`push_intra_rect`] carrying the transform's INPUTS: at one reconstruction
3360/// thread the transform runs here, exactly as before; on the wavefront it
3361/// travels with the op and runs on the worker (lane-wave3).
3362#[allow(clippy::too_many_arguments)]
3363fn push_intra_tx(
3364 plane: usize,
3365 x: usize,
3366 y: usize,
3367 bw: usize,
3368 bh: usize,
3369 rect: bool,
3370 mode: usize,
3371 angle_delta: i32,
3372 reach: Reach,
3373 tx: TxParams,
3374 grid: &[i32],
3375 cfl: Option<(i32, CflSrc)>,
3376 filter_intra: Option<usize>,
3377 smooth_neighbor: bool,
3378 fctx: &crate::decode::FrameCtx,
3379) {
3380 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
3381 inline_intra(
3382 plane, x, y, bw, bh, rect, mode, angle_delta, reach, &tx.run(grid), cfl, filter_intra,
3383 smooth_neighbor, fctx,
3384 );
3385 return;
3386 }
3387 let pred = take_palette_pred(fctx);
3388 push_op(fctx, ReconOp::Intra {
3389 plane, x, y, bw, bh, rect, mode, angle_delta, reach,
3390 residual: Residual::coeffs(tx, grid, fctx), cfl, filter_intra, smooth_neighbor, pred,
3391 });
3392}
3393
3394/// [`push_mc_rect`] carrying the transform's inputs -- see [`push_intra_tx`].
3395#[allow(clippy::too_many_arguments)]
3396fn push_mc_rect_tx(
3397 plane: usize,
3398 x: usize,
3399 y: usize,
3400 stride: usize,
3401 w: usize,
3402 h: usize,
3403 prediction: Pred<'_>,
3404 tx: TxParams,
3405 grid: &[i32],
3406 fctx: &crate::decode::FrameCtx,
3407) {
3408 // lane-wave4: a deferred prediction is not there to be windowed -- the
3409 // op carries its offset into the block's prediction instead, and the
3410 // residual is laid out at that same stride (`reconstruct_mc_rect` reads
3411 // both buffers at one stride).
3412 let (prediction, stride) = match prediction.inline(stride) {
3413 Some(v) => v,
3414 None => {
3415 let Pred::Cur { plane: sp, stride: ss, off } = prediction else { unreachable!() };
3416 let mut tx = tx;
3417 tx.stride = 0;
3418 push_op(fctx, ReconOp::Mc {
3419 plane, x, y, stride: w, w, h,
3420 prediction: PredSrc::Cur { plane: sp, off, src: ss },
3421 residual: Residual::coeffs(tx, grid, fctx),
3422 });
3423 return;
3424 }
3425 };
3426 if fctx.recon_planes.with(std::cell::Cell::get).is_some() {
3427 // `reconstruct_mc_rect` reads the prediction and the residual at ONE
3428 // stride, so a prediction handed over at the block's stride (a var-tx
3429 // unit's window, lane-wave4) has to be densified for a dense residual
3430 // -- which is exactly what the recorded path below does.
3431 let residual = tx.run(grid);
3432 let res_stride = if tx.stride == 0 { w } else { tx.stride };
3433 let window;
3434 let prediction = if stride == res_stride {
3435 prediction
3436 } else {
3437 debug_assert_eq!(res_stride, w);
3438 let mut win = Vec::with_capacity(w * h);
3439 for row in 0..h {
3440 win.extend_from_slice(&prediction[row * stride..][..w]);
3441 }
3442 window = win;
3443 &window[..]
3444 };
3445 inline_mc(plane, x, y, res_stride, w, h, prediction, &residual, fctx);
3446 return;
3447 }
3448 // `reconstruct_mc_rect` reads exactly rows `0..h`, columns `0..w` of the
3449 // two buffers at `stride`, so the record carries that window densely
3450 // rather than the whole block's prediction: a 4x4 unit of a 64x64 block
3451 // copied 64*64 samples on the PARSING thread before. The residual is then
3452 // produced dense too (`TxParams::stride = 0`), which is the same numbers
3453 // in the same places at stride `w`.
3454 let off = fctx.pred_arena.with(|a| {
3455 let mut a = a.borrow_mut();
3456 let off = a.len();
3457 for row in 0..h {
3458 a.extend_from_slice(&prediction[row * stride..][..w]);
3459 }
3460 off as u32
3461 });
3462 let mut tx = tx;
3463 tx.stride = 0;
3464 push_op(fctx, ReconOp::Mc {
3465 plane, x, y, stride: w, w, h, prediction: PredSrc::Owned(off, (w * h) as u32),
3466 residual: Residual::coeffs(tx, grid, fctx),
3467 });
3468}
3469
3470/// Replays every recorded [`ReconOp`] into the frame's planes, in push order,
3471/// and empties the queue (lane-wave1 step (i)).
3472///
3473/// Called at the top of each superblock visit and at the end of each tile, so
3474/// a whole superblock's parsing runs with no plane access at all; the two
3475/// parse-time pixel READS that survive -- the intrabc source fetch and the
3476/// interintra intra predictor -- flush ahead of themselves instead, which
3477/// keeps them byte-exact and names exactly what step (ii) still has to move.
3478fn flush_recon(
3479 fctx: &crate::decode::FrameCtx,
3480 y: &mut PlaneBuf<'static>,
3481 u: &mut PlaneBuf<'static>,
3482 v: &mut PlaneBuf<'static>,
3483) {
3484 // lane-wave1 step (ii): a parse-time pixel READ needs every worker's
3485 // writes in place, not just this superblock's queue.
3486 wave_barrier(fctx);
3487 let mut ops = fctx.recon_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3488 fctx.recon_ops.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut ops));
3489 let mut coeffs = fctx.coeff_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3490 fctx.coeff_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut coeffs));
3491 let mut preds = fctx.pred_spare.with(|c| std::mem::take(&mut *c.borrow_mut()));
3492 fctx.pred_arena.with(|c| std::mem::swap(&mut *c.borrow_mut(), &mut preds));
3493 let mut cur: [Vec<u16>; 3] = Default::default();
3494 for op in ops.drain(..) {
3495 exec_op(op, y, u, v, &mut cur, &coeffs, &preds, fctx);
3496 }
3497 coeffs.clear();
3498 preds.clear();
3499 fctx.recon_spare.with(|c| *c.borrow_mut() = ops);
3500 fctx.coeff_spare.with(|c| *c.borrow_mut() = coeffs);
3501 fctx.pred_spare.with(|c| *c.borrow_mut() = preds);
3502}
3503
3504/// Performs one recorded write: the body [`flush_recon`] replays, and the
3505/// body [`push_op`] runs immediately when reconstruction is inline.
3506fn exec_op(
3507 op: ReconOp,
3508 y: &mut PlaneBuf<'static>,
3509 u: &mut PlaneBuf<'static>,
3510 v: &mut PlaneBuf<'static>,
3511 cur: &mut [Vec<u16>; 3],
3512 coeffs: &[i32],
3513 preds: &[u16],
3514 fctx: &crate::decode::FrameCtx,
3515) {
3516 // lane-nbpub instrument: `EC_AV1_NORECON=1` drops every recorded pixel
3517 // write, leaving the entropy parse and the per-mi neighbour bookkeeping
3518 // alone. It makes the encoder's own streams garbage, so it is a
3519 // MEASUREMENT rung only -- what it measures is how much of the encoder's
3520 // first decode of its own tiles (`par::S_FIRST`) is reconstruction and
3521 // how much is parse. Answer at 3840x1608 (4 frames, 4x2 tiles, 8 tile
3522 // threads): 150 ms -> 141 ms, i.e. the reconstruction is 6% of that
3523 // stage and the parse plus the neighbour grids are the other 94%. That
3524 // is why handing the decoder the encoder's own reconstruction cannot
3525 // shrink the stage: only publishing the per-mi neighbour state the
3526 // filters read (and so never parsing at all) can.
3527 if crate::envflags::env_flag!("EC_AV1_NORECON") {
3528 return;
3529 }
3530 let mut scratch = Vec::new();
3531 match op {
3532 ReconOp::Pred(b) => (b.0)(y, u, v, fctx, cur),
3533 ReconOp::Intra {
3534 plane, x, y: oy, bw, bh, rect, mode, angle_delta, reach, residual, cfl,
3535 filter_intra, smooth_neighbor, pred,
3536 } => exec_intra(
3537 y, u, v, plane, x, oy, bw, bh, rect, mode, angle_delta, reach,
3538 residual.resolve(coeffs, &mut scratch),
3539 cfl, filter_intra, smooth_neighbor, pred, fctx,
3540 ),
3541 ReconOp::Mc { plane, x, y: oy, stride, w, h, prediction, residual } => {
3542 let residual = residual.resolve(coeffs, &mut scratch);
3543 match prediction {
3544 PredSrc::Owned(off, len) => {
3545 let p = &preds[off as usize..][..len as usize];
3546 exec_mc(y, u, v, plane, x, oy, stride, w, h, p, residual, fctx);
3547 }
3548 PredSrc::Cur { plane: sp, off, src } => {
3549 let block = std::mem::take(&mut cur[sp]);
3550 if src == stride {
3551 exec_mc(y, u, v, plane, x, oy, stride, w, h, &block[off..], residual, fctx);
3552 } else {
3553 // A transform unit's residual is dense, so its window
3554 // of the block prediction is taken out dense too --
3555 // the copy the parsing thread used to make, made here.
3556 let mut window = Vec::with_capacity(w * h);
3557 for row in 0..h {
3558 window.extend_from_slice(&block[off + row * src..][..w]);
3559 }
3560 exec_mc(y, u, v, plane, x, oy, stride, w, h, &window, residual, fctx);
3561 }
3562 cur[sp] = block;
3563 }
3564 }
3565 }
3566 }
3567}
3568
3569/// [`ReconOp::Intra`] performed. Its arguments are borrowed, so the inline
3570/// path ([`push_op`]'s registered planes) reaches it without ever building
3571/// the record -- which is what keeps one reconstruction thread at the cost of
3572/// the pre-lane-wave1 decoder.
3573#[allow(clippy::too_many_arguments)]
3574fn exec_intra(
3575 y: &mut PlaneBuf<'static>,
3576 u: &mut PlaneBuf<'static>,
3577 v: &mut PlaneBuf<'static>,
3578 plane: usize,
3579 x: usize,
3580 oy: usize,
3581 bw: usize,
3582 bh: usize,
3583 rect: bool,
3584 mode: usize,
3585 angle_delta: i32,
3586 reach: Reach,
3587 residual: &[i32],
3588 cfl: Option<(i32, CflSrc)>,
3589 filter_intra: Option<usize>,
3590 smooth_neighbor: bool,
3591 pred: Option<Vec<u16>>,
3592 fctx: &crate::decode::FrameCtx,
3593) {
3594 // The CfL AC signal is read HERE, off the luma that has already been
3595 // written for this block -- at parse time it would have been the previous
3596 // frame's samples.
3597 let ac = cfl.map(|(alpha, src)| {
3598 let sig = if src.rect {
3599 cfl_ac_q3_rect(&*y, src.px, src.py, src.bw, src.bh)
3600 } else {
3601 cfl_ac_q3(&*y, src.px, src.py, src.bw)
3602 };
3603 (alpha, sig)
3604 });
3605 let cfl = ac.as_ref().map(|(a, sig)| (*a, sig.as_slice()));
3606 let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v };
3607 if rect {
3608 target.reconstruct_rect(
3609 x, oy, bw, bh, mode, angle_delta, reach, residual, cfl, filter_intra,
3610 smooth_neighbor, pred, fctx,
3611 );
3612 } else {
3613 target.reconstruct(
3614 x, oy, bw, mode, angle_delta, reach, residual, cfl, filter_intra,
3615 smooth_neighbor, pred, fctx,
3616 );
3617 }
3618}
3619
3620/// [`ReconOp::Mc`] performed -- see [`exec_intra`].
3621#[allow(clippy::too_many_arguments)]
3622fn exec_mc(
3623 y: &mut PlaneBuf<'static>,
3624 u: &mut PlaneBuf<'static>,
3625 v: &mut PlaneBuf<'static>,
3626 plane: usize,
3627 x: usize,
3628 oy: usize,
3629 stride: usize,
3630 w: usize,
3631 h: usize,
3632 prediction: &[u16],
3633 residual: &[i32],
3634 fctx: &crate::decode::FrameCtx,
3635) {
3636 let target: &mut PlaneBuf<'static> = match plane { 0 => &mut *y, 1 => &mut *u, _ => &mut *v };
3637 target.reconstruct_mc_rect(x, oy, stride, w, h, prediction, residual, fctx);
3638}
3639
3640thread_local! {
3641 /// The current frame's `mi` grid, kept only while a frame header set
3642 /// `allow_intrabc` -- an intrabc block's DV predictor is the ordinary
3643 /// MV stack ([`crate::mvstack::find_mv_stack`]) built against
3644 /// `INTRA_FRAME`, which needs the neighbour state a key frame otherwise
3645 /// never keeps. `(grid, mi_cols, mi_rows)`; `None` on every frame that
3646 /// does not allow intrabc (so nothing is paid for it).
3647 ///
3648 /// corner-cut: only [`decode_block`] (the square path) records into it,
3649 /// so a frame mixing intrabc with rect/sub-8x8 leaves would predict off
3650 /// an incomplete grid. Ceiling: the DV *value* (never the parse) would
3651 /// be wrong there; upgrade = record from the rect/leaf paths too.
3652 /// The block vector [`read_intra_mode`] just decoded, handed to
3653 /// [`decode_block`] off the call stack (same idiom as [`PALETTE_PRED`],
3654 /// which the alternative -- a tenth tuple member through every caller --
3655 /// already avoids). Always `.take()`n by the block that reads it.
3656 /// How many blocks read `use_intrabc == 1` and took the DV path -- the
3657 /// gate's hit counter. Bumped on the READ, before the rect-strip refusal
3658 /// returns too, so it counts reads, not reconstructions (a refused block
3659 /// is never reconstructed).
3660 static INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3661}
3662 // The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
3663 // an intrabc block's chroma reads can inherit it (see
3664 // [`INTRABC_CHROMA_TX`]). Written on every luma read; only ever read
3665 // through that one arming site.
3666 // libaom `av1_get_tx_type` (`blockd.h:1350`): for `PLANE_TYPE_UV` it
3667 // branches on `is_inter_block(mbmi)` -- which `is_intrabc_block` also
3668 // satisfies (`blockd.h:373`) -- and takes the *colocated luma
3669 // transform's coded* `tx_type` (`mbmi->txk_type[...]`), never
3670 // `intra_mode_to_tx_type` of the chroma mode. `Some` only across an
3671 // intrabc block's two chroma [`read_plane`] calls; the type decides the
3672 // `TX_CLASS`, hence the scan order, `eob_multi_ctx` and every nz context
3673 // -- getting it wrong desyncs the chroma coefficients, it is not a
3674 // reconstruction-only detail.
3675
3676/// Whether this frame's header set `allow_intrabc` -- [`INTRABC_MI_GRID`] is
3677/// `Some` exactly then (set once per frame in `decode_frame`), so the flag
3678/// needs no separate plumbing to reach the rect-strip mode reader.
3679fn allow_intrabc_frame(fctx: &crate::decode::FrameCtx) -> bool {
3680 fctx.intrabc_mi_grid.with(|g| g.borrow().is_some())
3681}
3682
3683thread_local! {
3684 /// How many rect intra strips READ the `use_intrabc` symbol (i.e. how many
3685 /// times the fix below was exercised) -- the rect-strip gate's hit counter,
3686 /// distinct from [`INTRABC_HITS`] which counts blocks that USE intrabc.
3687 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3688}
3689
3690/// Current value of [`RECT_INTRABC_READS`].
3691pub(crate) fn rect_intrabc_reads() -> usize {
3692 RECT_INTRABC_READS.with(|c| c.get())
3693}
3694
3695/// Zeroes [`RECT_INTRABC_READS`] (gate tests call this before a decode).
3696#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3697pub(crate) fn reset_rect_intrabc_reads() {
3698 RECT_INTRABC_READS.with(|c| c.set(0));
3699}
3700
3701thread_local! {
3702 /// Blocks that USED intrabc at an 8x8 LEAF (`decode_leaf8`) specifically
3703 /// -- the shape lane-kf900 r7 fixed; [`INTRABC_HITS`] counts every shape.
3704 static LEAF8_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3705}
3706
3707/// Current value of [`LEAF8_INTRABC_HITS`].
3708pub(crate) fn leaf8_intrabc_hits() -> usize {
3709 LEAF8_INTRABC_HITS.with(|c| c.get())
3710}
3711
3712/// Zeroes [`LEAF8_INTRABC_HITS`] (gate tests call this before a decode).
3713#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3714pub(crate) fn reset_leaf8_intrabc_hits() {
3715 LEAF8_INTRABC_HITS.with(|c| c.set(0));
3716}
3717
3718/// Current value of [`INTRABC_HITS`].
3719#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3720pub(crate) fn intrabc_hits() -> usize {
3721 INTRABC_HITS.with(|c| c.get())
3722}
3723
3724thread_local! {
3725 /// An intrabc block that IS a sub-8x8 group's CHROMA REFERENCE and is
3726 /// SKIPPED: the route that arms [`INTRABC_CHROMA_TX`] and then reads no
3727 /// chroma coefficient at all, so the slot used to stay armed into the NEXT
3728 /// block's chroma read. Both group shapes (4x4 split, 4x8/8x4 rect) count
3729 /// here. A non-zero value is what makes the disarm below load-bearing.
3730 static SKIPPED_INTRABC_CHROMA_ARM_HITS: std::cell::Cell<usize> =
3731 const { std::cell::Cell::new(0) };
3732}
3733
3734/// Current value of [`SKIPPED_INTRABC_CHROMA_ARM_HITS`].
3735#[allow(dead_code)] // read only from the `#[cfg(test)]` gates and the probe
3736pub(crate) fn skipped_intrabc_chroma_arm_hits() -> usize {
3737 SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.get())
3738}
3739
3740/// Zeroes [`SKIPPED_INTRABC_CHROMA_ARM_HITS`] (gate tests call this before a
3741/// decode).
3742#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3743pub(crate) fn reset_skipped_intrabc_chroma_arm_hits() {
3744 SKIPPED_INTRABC_CHROMA_ARM_HITS.with(|c| c.set(0));
3745}
3746
3747/// Zeroes [`INTRABC_HITS`] (gate tests call this before a decode).
3748#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3749pub(crate) fn reset_intrabc_hits() {
3750 INTRABC_HITS.with(|c| c.set(0));
3751}
3752
3753thread_local! {
3754 /// lane-t900 r32: intrabc blocks whose transform size came off the INTER
3755 /// var-tx partition tree (unskipped, `TX_MODE_SELECT`) -- the capability
3756 /// that replaced the refusal "an intrabc block under TxMode::Select".
3757 static INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3758 /// lane-av1txr: as above for a `BLOCK_4X8`/`BLOCK_8X4` intrabc leaf --
3759 /// libaom's `block_signals_txsize` is `bsize > BLOCK_4X4`, so these leaves
3760 /// signal a transform size where a plain `BLOCK_4X4` does not. Reading no
3761 /// symbol here desynced `warped.obu` at the very next block.
3762 static RECT_INTRABC_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3763 /// lane-av1-intrabc: rect INTRABC blocks whose reconstruction
3764 /// [`decode_intrabc_rect`] ran -- the engagement counter the rect-strip
3765 /// gates assert on (a refused block bumps [`INTRABC_HITS`] but never
3766 /// this one).
3767 static INTRABC_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3768 /// Of those, how many read the INTER var-tx tree (unskipped, TX_MODE_SELECT).
3769 static INTRABC_RECT_VARTX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3770 /// lane-av1-intrabc r4: rect INTRABC blocks whose reconstruction
3771 /// [`decode_intrabc_rect`] ran with `skip == 0` (a real residual read),
3772 /// split by the strip's orientation -- `bw > bh` is a HORZ strip,
3773 /// `bh > bw` a VERT one. The reviewer's unblock condition needs a CODED
3774 /// witness in BOTH orientations, and the existing `INTRABC_RECT_HITS`
3775 /// counts neither orientation nor the skip flag, so an arm that flipped
3776 /// to an all-skip stream (no residual reader at all) would stay green.
3777 static INTRABC_RECT_CODED_HITS: std::cell::Cell<[usize; 2]> =
3778 const { std::cell::Cell::new([0, 0]) };
3779 /// lane-av1-intrabc r5: the `skip == 1` twin of [`INTRABC_RECT_CODED_HITS`]
3780 /// -- rect INTRABC blocks reconstructed as a bare prediction copy, split
3781 /// by orientation. The r5 panic (residual stride `bw * bh` underrunning
3782 /// `reconstruct_mc_rect`'s `row * side + w` index on a VERT strip) was
3783 /// invisible to every gate because they only counted CODED strips.
3784 static INTRABC_RECT_SKIPPED_HITS: std::cell::Cell<[usize; 2]> =
3785 const { std::cell::Cell::new([0, 0]) };
3786}
3787
3788/// lane-av1-intrabc r4: coded (`skip == 0`) rect intrabc blocks reconstructed,
3789/// as `[horz, vert]` -- see [`INTRABC_RECT_CODED_HITS`].
3790#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3791pub fn intrabc_rect_coded_hits() -> [usize; 2] {
3792 INTRABC_RECT_CODED_HITS.with(std::cell::Cell::get)
3793}
3794
3795/// lane-av1-intrabc r5: skipped (`skip == 1`) rect intrabc blocks
3796/// reconstructed, as `[horz, vert]` -- see [`INTRABC_RECT_SKIPPED_HITS`].
3797#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3798pub fn intrabc_rect_skipped_hits() -> [usize; 2] {
3799 INTRABC_RECT_SKIPPED_HITS.with(std::cell::Cell::get)
3800}
3801
3802/// Current value of [`INTRABC_RECT_HITS`].
3803#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3804pub fn intrabc_rect_hits() -> usize {
3805 INTRABC_RECT_HITS.with(|c| c.get())
3806}
3807
3808/// Zeroes [`INTRABC_RECT_HITS`]/[`INTRABC_RECT_VARTX_HITS`].
3809#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3810pub(crate) fn reset_intrabc_rect_hits() {
3811 INTRABC_RECT_HITS.with(|c| c.set(0));
3812 INTRABC_RECT_VARTX_HITS.with(|c| c.set(0));
3813 INTRABC_RECT_CODED_HITS.with(|c| c.set([0, 0]));
3814 INTRABC_RECT_SKIPPED_HITS.with(|c| c.set([0, 0]));
3815}
3816
3817/// Current value of [`INTRABC_RECT_VARTX_HITS`].
3818#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3819pub fn intrabc_rect_vartx_hits() -> usize {
3820 INTRABC_RECT_VARTX_HITS.with(|c| c.get())
3821}
3822
3823/// Current value of [`INTRABC_VARTX_HITS`].
3824#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3825pub(crate) fn intrabc_vartx_hits() -> usize {
3826 INTRABC_VARTX_HITS.with(|c| c.get())
3827}
3828
3829/// Zeroes [`INTRABC_VARTX_HITS`] (gate tests call this before a decode).
3830#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3831pub(crate) fn reset_intrabc_vartx_hits() {
3832 INTRABC_VARTX_HITS.with(|c| c.set(0));
3833}
3834
3835/// Current value of [`RECT_INTRABC_VARTX_HITS`].
3836#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3837pub fn rect_intrabc_vartx_hits() -> usize {
3838 RECT_INTRABC_VARTX_HITS.with(|c| c.get())
3839}
3840
3841/// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
3842/// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
3843/// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
3844/// `INTRA_FRAME` candidate (libaom treats intrabc as `is_inter_block`).
3845fn record_intrabc_mi(mi_r: usize, mi_c: usize, n4: usize, dv: Option<(i32, i32)>, n: &mut Neighbours, fctx: &crate::decode::FrameCtx) {
3846 record_intrabc_mi_rect(mi_r, mi_c, n4, n4, dv, n, fctx);
3847}
3848
3849/// [`record_intrabc_mi`] with a true rectangular footprint: `av1_find_mv_refs`
3850/// takes the block's real `bsize`, so a sub-8x8 `BLOCK_4X8`/`BLOCK_8X4`
3851/// intrabc leaf must publish a 1x2/2x1 mi span, not a square (lane-av1txr).
3852///
3853/// Also stamps libaom's `is_inter_block` verdict for this block into the
3854/// `above_inter`/`left_inter` bands ([`tx_size_context_txfm_rect`]'s override
3855/// term): `is_inter_block` is `is_intrabc_block(mbmi) || ref_frame[0] >
3856/// INTRA_FRAME` (`blockd.h:373`), so an intrabc block is "inter" there and
3857/// `get_tx_size_context` reads its BLOCK size rather than its transform band.
3858/// The `false` half of the stamp is [`Neighbours::fill_lf_grid_rect`]'s, which
3859/// every block runs; this runs after it (class leaked-band otherwise).
3860fn record_intrabc_mi_rect(
3861 mi_r: usize,
3862 mi_c: usize,
3863 n4_w: usize,
3864 n4_h: usize,
3865 dv: Option<(i32, i32)>,
3866 n: &mut Neighbours,
3867 fctx: &crate::decode::FrameCtx,
3868) {
3869 if dv.is_some() {
3870 for i in 0..n4_w {
3871 if let Some(cell) = n.above_inter.get_mut(mi_c + i) {
3872 *cell = true;
3873 }
3874 }
3875 for i in 0..n4_h {
3876 if let Some(cell) = n.left_inter.get_mut(mi_r + i) {
3877 *cell = true;
3878 }
3879 }
3880 }
3881 fctx.intrabc_mi_grid.with(|g| {
3882 let mut g = g.borrow_mut();
3883 let Some((grid, _, _)) = g.as_mut() else {
3884 return;
3885 };
3886 let info = crate::mvstack::MiInfo {
3887 is_inter: dv.is_some(),
3888 ref_frame: 0,
3889 ref_frame1: NO_REF1,
3890 mv: mv16(dv.unwrap_or((0, 0))),
3891 mv1: (0, 0),
3892 is_new_mv: dv.is_some(),
3893 is_global_mv0: false,
3894 is_global_mv1: false,
3895 size: n4_w as u8,
3896 size_h: n4_h as u8,
3897 };
3898 for r in mi_r..mi_r + n4_h {
3899 for c in mi_c..mi_c + n4_w {
3900 grid.set(r, c, info);
3901 }
3902 }
3903 });
3904}
3905
3906// How many blocks decoded `skip_mode == 1` (lane-av1comp round 14) --
3907// proves a real `skip_mode_present` stream actually reached a block that
3908// picked it, not just that the frame header bit was set.
3909thread_local! {
3910 static SKIP_MODE_HITS: std::cell::Cell<usize> =
3911 const { std::cell::Cell::new(0) };
3912}
3913
3914/// Current value of [`SKIP_MODE_HITS`].
3915#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3916pub(crate) fn skip_mode_hits() -> usize {
3917 SKIP_MODE_HITS.with(|c| c.get())
3918}
3919
3920// lane-motionmode: how many blocks actually decoded `obmc_selected == true`
3921// (as opposed to just reaching an eligible `read_motion_mode` symbol read)
3922// -- the gate's own proof that a real aomenc `--enable-obmc=1` stream
3923// reached [`obmc_blend`], not just the header bit.
3924thread_local! {
3925 static OBMC_HITS: std::cell::Cell<usize> =
3926 const { std::cell::Cell::new(0) };
3927}
3928
3929// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
3930// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
3931// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
3932// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
3933// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
3934// decoder used to read with the wrong alphabet, so a gate that asserts this
3935// counter advanced proves the fixed path fired (class
3936// `gate-blind-to-feature`).
3937thread_local! {
3938 static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3939}
3940
3941/// Current value of [`FIMV_ALPHABET_HITS`].
3942pub fn fimv_alphabet_hits() -> usize {
3943 FIMV_ALPHABET_HITS.with(|c| c.get())
3944}
3945
3946// lane-fimv r1: how many frame headers this decoder has decoded with
3947// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
3948// prove the encoder really produced the header state under test rather than
3949// assume it.
3950thread_local! {
3951 static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3952}
3953
3954/// Current value of [`FIMV_FRAME_HITS`].
3955pub fn fimv_frame_hits() -> usize {
3956 FIMV_FRAME_HITS.with(|c| c.get())
3957}
3958
3959/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
3960/// `force_integer_mv` bit is set.
3961pub fn note_force_integer_mv_frame() {
3962 hit!(FIMV_FRAME_HITS);
3963}
3964
3965/// Current value of [`OBMC_HITS`].
3966#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3967pub(crate) fn obmc_hits() -> usize {
3968 OBMC_HITS.with(|c| c.get())
3969}
3970
3971// lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
3972// off the neighbour band -- the positive half of the proof for "an OBMC
3973// neighbour whose switchable interp filter was never recorded". A
3974// fixed-filter frame returns before this point (its neighbours legitimately
3975// carry the `[3, 3]` sentinel), so every bump is a neighbour whose own
3976// `interp_filter` symbols were published by `record_inter_rect_mi`.
3977thread_local! {
3978 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3979}
3980
3981/// Current value of [`OBMC_FILTER_BAND_READS`].
3982#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3983pub(crate) fn obmc_filter_band_reads() -> usize {
3984 OBMC_FILTER_BAND_READS.with(|c| c.get())
3985}
3986
3987// lane-scaledref r1: per-case firing counts for the scaled-reference gate
3988// (class `gate-blind-to-feature`) -- a pixel match under an UNSCALED
3989// reference would pass just as well and prove nothing, so the gate
3990// hard-asserts each combination this round lifts actually occurred:
3991// a compound block with a scaled tap, a warp block whose warp libaom
3992// suppresses because the reference is scaled, an OBMC block, an interintra
3993// block, and an 8x8 leaf.
3994thread_local! {
3995 static SCALED_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3996 static SCALED_WARP_FALLBACK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3997 static SCALED_OBMC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3998 static SCALED_INTERINTRA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3999 static SCALED_BLOCK8_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4000 static SCALED_WARP_SUPPRESSED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4001 static MIXED_SCALE_COMPOUND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4002}
4003
4004/// Current value of [`MIXED_SCALE_COMPOUND_HITS`]: compound blocks with one
4005/// scaled and one unscaled tap.
4006#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4007pub(crate) fn mixed_scale_compound_hits() -> usize {
4008 MIXED_SCALE_COMPOUND_HITS.with(|c| c.get())
4009}
4010
4011/// Current value of [`SCALED_WARP_SUPPRESSED_HITS`]: blocks that would have
4012/// read the 3-symbol `motion_mode_cdf` but read the 2-symbol `obmc_cdf`
4013/// instead because their reference is scaled (libaom `motion_mode_allowed`,
4014/// `blockd.h:1484`).
4015#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4016pub(crate) fn scaled_warp_suppressed_hits() -> usize {
4017 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.get())
4018}
4019
4020/// Current value of [`SCALED_COMPOUND_HITS`].
4021#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4022pub(crate) fn scaled_compound_hits() -> usize {
4023 SCALED_COMPOUND_HITS.with(|c| c.get())
4024}
4025
4026/// Current value of [`SCALED_WARP_FALLBACK_HITS`].
4027pub fn scaled_warp_fallback_hits() -> usize {
4028 SCALED_WARP_FALLBACK_HITS.with(|c| c.get())
4029}
4030
4031/// Current value of [`SCALED_OBMC_HITS`].
4032#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4033pub(crate) fn scaled_obmc_hits() -> usize {
4034 SCALED_OBMC_HITS.with(|c| c.get())
4035}
4036
4037/// Current value of [`SCALED_INTERINTRA_HITS`].
4038#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4039pub(crate) fn scaled_interintra_hits() -> usize {
4040 SCALED_INTERINTRA_HITS.with(|c| c.get())
4041}
4042
4043/// Current value of [`SCALED_BLOCK8_HITS`].
4044#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4045pub(crate) fn scaled_block8_hits() -> usize {
4046 SCALED_BLOCK8_HITS.with(|c| c.get())
4047}
4048
4049// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to
4050// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of
4051// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an
4052// 8x8-leaf OBMC block apart from a 16x16+ one.
4053thread_local! {
4054 static OBMC_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4055}
4056
4057// lane-interp3 r1: how many inter blocks read a SWITCHABLE `interp_filter`
4058// pair whose two directions differ (`enable_dual_filter` only -- with dual
4059// filter off both directions take the single symbol, so this can never fire).
4060// A gate asserting it proves the stream really carries dual-filter blocks.
4061thread_local! {
4062 static DUAL_FILTER_DIFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4063}
4064
4065// lane-interp3 r1: how many COMPOUND 8x8 leaves read their own
4066// `read_mb_interp_filter` symbol(s) -- the read this round added (the leaf
4067// used to skip it entirely, losing a symbol and stamping the `[3, 3]`
4068// no-filter sentinel that made a neighbouring OBMC block panic).
4069thread_local! {
4070 static COMPOUND8_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4071}
4072
4073/// Current value of [`DUAL_FILTER_DIFF_HITS`].
4074#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4075pub(crate) fn dual_filter_diff_hits() -> usize {
4076 DUAL_FILTER_DIFF_HITS.with(|c| c.get())
4077}
4078
4079/// Current value of [`COMPOUND8_FILTER_HITS`].
4080#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4081pub(crate) fn compound8_filter_hits() -> usize {
4082 COMPOUND8_FILTER_HITS.with(|c| c.get())
4083}
4084
4085// lane-warp round 1: how many blocks resolved `motion_mode_allowed` to
4086// `WARPED_CAUSAL`-eligible (3-symbol read, `num_proj_ref >= 1` under
4087// `allow_warped_motion`) AND the symbol actually decoded to `WARPED_CAUSAL`
4088// -- the gate's proof that a fixture really exercises the alphabet this
4089// round changed, even though the block itself still refuses (warp
4090// estimation/filter not ported).
4091thread_local! {
4092 static WARP_SELECTED_HITS: std::cell::Cell<usize> =
4093 const { std::cell::Cell::new(0) };
4094}
4095
4096/// Current value of [`WARP_SELECTED_HITS`].
4097#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4098pub(crate) fn warp_selected_hits() -> usize {
4099 WARP_SELECTED_HITS.with(|c| c.get())
4100}
4101
4102// lane-cwarp r1: how many COMPOUND_REFERENCE blocks had at least one
4103// reference predicted through the per-ref GLOBAL warp (`av1_warp_plane`
4104// into the compound intermediate) rather than translationally -- the
4105// gate's proof that a `GLOBAL_GLOBALMV` block under a ROTZOOM/AFFINE model
4106// really reached [`crate::warp::warp_affine_compound`].
4107thread_local! {
4108 static COMPOUND_WARP_HITS: std::cell::Cell<usize> =
4109 const { std::cell::Cell::new(0) };
4110}
4111
4112/// Current value of [`COMPOUND_WARP_HITS`].
4113#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4114pub(crate) fn compound_warp_hits() -> usize {
4115 COMPOUND_WARP_HITS.with(|c| c.get())
4116}
4117
4118// lane-interp3 r3: the same proof narrowed to the 8x8 LEAF's own compound
4119// arm ([`decode_inter_block8`]) -- that arm predicted both taps
4120// translationally until r3, so a gate needs to tell a warped 8x8 compound
4121// leaf apart from a warped 16x16+ one (both bump [`COMPOUND_WARP_HITS`]).
4122thread_local! {
4123 static COMPOUND_WARP_HITS_8: std::cell::Cell<usize> =
4124 const { std::cell::Cell::new(0) };
4125}
4126
4127/// Current value of [`COMPOUND_WARP_HITS_8`].
4128#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4129pub(crate) fn compound_warp_hits_8() -> usize {
4130 COMPOUND_WARP_HITS_8.with(|c| c.get())
4131}
4132
4133// lane-gmaffine r1: how many blocks built their prediction from a
4134// SIX-parameter (`AFFINE`) global-motion model through
4135// `crate::warp::global_warp_params` -- the gate's proof that a stream really
4136// carried an AFFINE `global_motion_params` AND that a block was predicted
4137// with it, not merely that the header parsed one.
4138thread_local! {
4139 static AFFINE_GM_HITS: std::cell::Cell<usize> =
4140 const { std::cell::Cell::new(0) };
4141}
4142
4143/// Current value of [`AFFINE_GM_HITS`].
4144#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4145pub(crate) fn affine_gm_hits() -> usize {
4146 AFFINE_GM_HITS.with(|c| c.get())
4147}
4148
4149// lane-t900 r9: rect blocks whose warp-sample top-right probe answers
4150// differently at the block's WIDTH than at libaom's
4151// `AOMMAX(xd->width, xd->height)` -- each one is a `num_proj_ref` that could
4152// pick the wrong motion_mode alphabet.
4153thread_local! {
4154 static TR_REACH_LONGER_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4155}
4156
4157/// Current value of [`TR_REACH_LONGER_SIDE_HITS`].
4158pub fn tr_reach_longer_side_hits() -> usize {
4159 TR_REACH_LONGER_SIDE_HITS.with(std::cell::Cell::get)
4160}
4161
4162// lane-t900 r9: libaom `is_nontrans_global_motion` (mvref_common.h) returns 0
4163// for `AOMMIN(mi_size_wide[bsize], mi_size_high[bsize]) < 2`, i.e. any block
4164// with a 4-px side is NEVER "non-translational global" and therefore ALWAYS
4165// reads its interp-filter symbol. Counts the blocks where that guard flips
4166// our answer -- a GLOBALMV/GLOBAL_GLOBALMV block with a non-TRANSLATION model
4167// and a 4-px side, which we used to suppress the interp read on (a pre-mode
4168// entropy desync one symbol wide).
4169thread_local! {
4170 static GM_NONTRANS_SMALL_SIDE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4171}
4172
4173/// Current value of [`GM_NONTRANS_SMALL_SIDE_HITS`].
4174pub fn gm_nontrans_small_side_hits() -> usize {
4175 GM_NONTRANS_SMALL_SIDE_HITS.with(std::cell::Cell::get)
4176}
4177
4178// lane-gmaffine r1: 8x8-leaf-only counters -- how many `BLOCK_8X8` leaves
4179// coded `GLOBALMV` (`GLOBALMV_HITS_8`) and how many built a real
4180// `WARPED_CAUSAL` local-warp prediction there (`WARP_HITS_8`, incremented
4181// only once `find_projection` returned a usable model, unlike
4182// `WARP_SELECTED_HITS` which counts the symbol). Both are the 8x8 gates'
4183// proof that the leaf path itself fired, not the 16x16+ one.
4184thread_local! {
4185 static GLOBALMV_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4186 static WARP_HITS_8: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4187}
4188
4189/// Current value of [`GLOBALMV_HITS_8`].
4190#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4191pub(crate) fn globalmv_hits_8() -> usize {
4192 GLOBALMV_HITS_8.with(|c| c.get())
4193}
4194
4195/// Current value of [`WARP_HITS_8`].
4196#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4197pub(crate) fn warp_hits_8() -> usize {
4198 WARP_HITS_8.with(|c| c.get())
4199}
4200
4201// How many blocks decoded `interintra == 1` with the non-wedge blended
4202// prediction applied (lane-interintra r1) -- the gate's proof that a
4203// stream actually exercised interintra.
4204thread_local! {
4205 static INTERINTRA_HITS: std::cell::Cell<usize> =
4206 const { std::cell::Cell::new(0) };
4207}
4208
4209/// Current value of [`INTERINTRA_HITS`].
4210#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4211pub(crate) fn interintra_hits() -> usize {
4212 INTERINTRA_HITS.with(|c| c.get())
4213}
4214
4215// lane-midcut r1: of those, how many were RECTANGULAR (`write_w != write_h`)
4216// -- the shape `interintra_blend` used to build a square `side x side` intra
4217// predictor for, with `ii_size_scales`/`edges` taken at the square. Every
4218// pre-existing interintra gate passed with that bug, so the rect arm needs
4219// its own counter to stop being vacuous.
4220thread_local! {
4221 static INTERINTRA_RECT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4222}
4223
4224/// Current value of [`INTERINTRA_RECT_HITS`].
4225pub fn interintra_rect_hits() -> usize {
4226 INTERINTRA_RECT_HITS.with(|c| c.get())
4227}
4228
4229// How many blocks decoded `comp_group_idx == 1` (masked COMPOUND_REFERENCE,
4230// wedge or diffwtd) and had `compound_type`/`wedge_idx`/`wedge_sign`/
4231// `mask_type` consumed entropy-exact -- lane-maskcomp r1's proof that a
4232// gate fixture actually exercises this alphabet, even though the block
4233// still refuses (the mask blend itself is unported).
4234thread_local! {
4235 static MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
4236 const { std::cell::Cell::new(0) };
4237}
4238
4239/// Current value of [`MASKED_COMPOUND_HITS`].
4240#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4241pub(crate) fn masked_compound_hits() -> usize {
4242 MASKED_COMPOUND_HITS.with(|c| c.get())
4243}
4244
4245// lane-intersub8 r4/r5: the NON-SQUARE half of `MASKED_COMPOUND_HITS` -- a
4246// masked-compound block whose true footprint is rectangular, i.e. the case
4247// whose `compound_type`/`wedge_idx` CDF row r4 fixed (it used to read the
4248// square envelope's `BLOCK_SIZES_ALL` index). Square blocks cannot show that
4249// defect, so a gate asserting `masked_compound_hits` alone stays vacuous for it.
4250thread_local! {
4251 static RECT_MASKED_COMPOUND_HITS: std::cell::Cell<usize> =
4252 const { std::cell::Cell::new(0) };
4253}
4254
4255/// Current value of [`RECT_MASKED_COMPOUND_HITS`].
4256#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4257pub(crate) fn rect_masked_compound_hits() -> usize {
4258 RECT_MASKED_COMPOUND_HITS.with(|c| c.get())
4259}
4260
4261// How many blocks decoded a real `COMPOUND_WEDGE` block (`comp_group_idx ==
4262// 1`, `compound_type == 0`) -- lane-wedge r3's proof a gate fixture
4263// actually exercised the wedge blend, not just the DIFFWTD half of
4264// `MASKED_COMPOUND_HITS`.
4265thread_local! {
4266 static WEDGE_HITS: std::cell::Cell<usize> =
4267 const { std::cell::Cell::new(0) };
4268}
4269
4270/// Current value of [`WEDGE_HITS`].
4271#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4272pub(crate) fn wedge_hits() -> usize {
4273 WEDGE_HITS.with(|c| c.get())
4274}
4275
4276// How many blocks decoded a real wedge-INTERINTRA block
4277// (`interintra == 1 && use_wedge_interintra == 1`) -- lane-wii r2's proof
4278// a gate fixture exercised the wedge blend (fixed sign 0), not just the
4279// smooth arm counted by `INTERINTRA_HITS`.
4280thread_local! {
4281 static WII_HITS: std::cell::Cell<usize> =
4282 const { std::cell::Cell::new(0) };
4283}
4284
4285/// Current value of [`WII_HITS`].
4286#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4287pub(crate) fn wii_hits() -> usize {
4288 WII_HITS.with(|c| c.get())
4289}
4290
4291// lane-sbrect10 r1: how many INTRA blocks read `uv_mode` off the 13-symbol
4292// NO-CFL alphabet *because their size excludes CFL* (libaom `is_cfl_allowed`:
4293// wide <= 32 && high <= 32). The witness that a gate stream really carries a
4294// 64-axis intra block -- the shape whose 14-symbol read desynced every inter
4295// frame carrying one.
4296thread_local! {
4297 static NOCFL_UV_MODE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4298}
4299
4300/// Current value of [`NOCFL_UV_MODE_HITS`].
4301#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4302pub(crate) fn nocfl_uv_mode_hits() -> usize {
4303 NOCFL_UV_MODE_HITS.with(|c| c.get())
4304}
4305
4306/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
4307/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
4308pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
4309 [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
4310
4311fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
4312 RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
4313}
4314
4315// lane-inter16ab r5: how many COMPOUND_WEDGE / wedge-INTERINTRA blocks used a
4316// RECTANGULAR codebook row (hgtw/hltw), per shape -- the gate's proof that
4317// the rect wedge masks lifted this round actually fired, not just the square
4318// ones already counted by `WEDGE_HITS`/`WII_HITS`.
4319thread_local! {
4320 static RECT_WEDGE_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
4321 static RECT_WII_HITS: std::cell::Cell<[usize; 6]> = const { std::cell::Cell::new([0; 6]) };
4322}
4323
4324/// Current value of [`RECT_WEDGE_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
4325pub(crate) fn rect_wedge_hits() -> [usize; 6] {
4326 RECT_WEDGE_HITS.with(|c| c.get())
4327}
4328
4329/// Current value of [`RECT_WII_HITS`], indexed by [`RECT_WEDGE_SHAPES`].
4330pub(crate) fn rect_wii_hits() -> [usize; 6] {
4331 RECT_WII_HITS.with(|c| c.get())
4332}
4333
4334// lane-inter4 r4: how many 16x8/8x16 INTER LEAVES actually ran the OBMC
4335// blend -- the gate's proof that `--enable-obmc=1` reached this shape (the
4336// r3 refusal's replacement: prefilt frames are bit-exact vs an instrumented
4337// aomdec, neighbour list included).
4338thread_local! {
4339 static OBMC_RECT_LEAF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4340}
4341
4342/// Current value of [`OBMC_RECT_LEAF_HITS`].
4343pub(crate) fn obmc_rect_leaf_hits() -> usize {
4344 OBMC_RECT_LEAF_HITS.with(|c| c.get())
4345}
4346
4347// lane-obmcrec r1: how many OBMC neighbours were taken from the SECOND half of
4348// a 4-wide/4-tall (1:4 strip) chroma pair -- the case whose interp filter used
4349// to be read from the pair's FIRST mi, which is a different block and, when
4350// that half is intra, carries the `[3, 3]` "no filter" sentinel (the three
4351// 1080p 10-bit film cuts refused there). The gate's proof the shape fired.
4352thread_local! {
4353 static OBMC_PAIR_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4354}
4355
4356/// Current value of [`OBMC_PAIR_FILTER_HITS`].
4357pub(crate) fn obmc_pair_filter_hits() -> usize {
4358 OBMC_PAIR_FILTER_HITS.with(|c| c.get())
4359}
4360
4361// lane-t900 r14: how many OBMC neighbour predictions run PAST the frame edge
4362// -- libaom's `op_mi_size` is `AOMMIN(xd->width|height, mi_step)`, the block's
4363// own side, so a block overhanging the bottom/right still predicts the full
4364// neighbour strip (the destination write is what clips). We used to shrink the
4365// prediction to the visible part, which at 4 chroma rows/cols also swaps the
4366// vertical/horizontal kernel to the 4-tap one. The gate's proof the shape fired.
4367thread_local! {
4368 static OBMC_EDGE_SPAN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4369}
4370
4371/// Current value of [`OBMC_EDGE_SPAN_HITS`].
4372#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4373pub(crate) fn obmc_edge_span_hits() -> usize {
4374 OBMC_EDGE_SPAN_HITS.with(|c| c.get())
4375}
4376
4377/// Current value of [`OBMC_HITS_8`].
4378#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4379pub(crate) fn obmc_hits_8() -> usize {
4380 OBMC_HITS_8.with(|c| c.get())
4381}
4382
4383// lane-rectgate r1: how many 32x32 quadrants actually decoded a
4384// `PARTITION_HORZ_B` split (the one extended/ab partition this decoder's
4385// inter-frame tile loop decodes -- `PARTITION_HORZ`/`VERT`/`HORZ_A`/`VERT_A`/
4386// `VERT_B` all still fall into the generic "a partition type this encoder
4387// never writes" refusal below) -- the gate's proof that a free-partition
4388// aomenc stream actually exercised a non-`NONE`/`SPLIT` partition rather than
4389// coincidentally never selecting one.
4390thread_local! {
4391 static EXTENDED_PARTITION_HITS: std::cell::Cell<usize> =
4392 const { std::cell::Cell::new(0) };
4393}
4394
4395/// Current value of [`EXTENDED_PARTITION_HITS`].
4396#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4397pub(crate) fn extended_partition_hits() -> usize {
4398 EXTENDED_PARTITION_HITS.with(|c| c.get())
4399}
4400
4401// lane-partitions r1: how many 32x32 quadrants decoded a real
4402// `PARTITION_HORZ`/`PARTITION_VERT` (two true rectangular strips, unlike
4403// `PARTITION_HORZ_B`'s square-context stand-in) -- the free-partition
4404// gate's proof this round's arms actually fired.
4405thread_local! {
4406 static RECT_PARTITION_HITS: std::cell::Cell<usize> =
4407 const { std::cell::Cell::new(0) };
4408}
4409
4410/// Current value of [`RECT_PARTITION_HITS`].
4411#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4412pub(crate) fn rect_partition_hits() -> usize {
4413 RECT_PARTITION_HITS.with(|c| c.get())
4414}
4415
4416// lane-inter8 r1: how many superblocks an inter tile coded as a single
4417// whole-SB `PARTITION_NONE` 64x64 inter block (the case aomenc picks for
4418// static content, previously a named refusal).
4419thread_local! {
4420 /// lane-sb128c r1: how many 128x128 `PARTITION_NONE` roots this INTER tile
4421 /// path decoded as one whole block (its gate's own witness).
4422 pub(crate) static INTER_SB128_NONE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4423 /// 128x64 / 64x128 INTER blocks decoded at the 128 root (lane-sb128c r7).
4424 pub(crate) static INTER_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4425 pub(crate) static INTER_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4426}
4427
4428/// Current value of [`INTER_SB128_HORZ_HITS`], for a gate's before/after delta.
4429pub(crate) fn inter_sb128_horz_hits() -> usize {
4430 INTER_SB128_HORZ_HITS.with(std::cell::Cell::get)
4431}
4432
4433/// Current value of [`INTER_SB128_VERT_HITS`], for a gate's before/after delta.
4434pub(crate) fn inter_sb128_vert_hits() -> usize {
4435 INTER_SB128_VERT_HITS.with(std::cell::Cell::get)
4436}
4437
4438/// Current value of [`INTER_SB128_NONE_HITS`], for a gate's before/after delta.
4439pub fn inter_sb128_none_hits() -> usize {
4440 INTER_SB128_NONE_HITS.with(std::cell::Cell::get)
4441}
4442
4443thread_local! {
4444 /// lane-sb128c r3: how many INTRA-coded 128x128 blocks inside an INTER
4445 /// frame this decoder reconstructed (mu-chunk chroma, four TX_64X64 luma
4446 /// units) -- the gate's witness that the lifted refusal's case fired.
4447 pub(crate) static INTRA_128_IN_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4448}
4449
4450/// Current value of [`INTRA_128_IN_INTER_HITS`], for a gate's before/after delta.
4451pub fn intra_128_in_inter_hits() -> usize {
4452 INTRA_128_IN_INTER_HITS.with(std::cell::Cell::get)
4453}
4454
4455thread_local! {
4456 static INTER_SB_NONE_HITS: std::cell::Cell<usize> =
4457 const { std::cell::Cell::new(0) };
4458}
4459
4460/// Current value of [`INTER_SB_NONE_HITS`].
4461#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4462pub(crate) fn inter_sb_none_hits() -> usize {
4463 INTER_SB_NONE_HITS.with(|c| c.get())
4464}
4465
4466// lane-inter8 r1: how many INTERIOR (not frame-edge-straddling) 16x16 inter
4467// blocks coded a real `PARTITION_SPLIT` into four 8x8 leaves -- the straddle
4468// path has always run that loop, so only this counter proves the newly-lifted
4469// alphabet value fired.
4470thread_local! {
4471 static INTER_SUB16_SPLIT_HITS: std::cell::Cell<usize> =
4472 const { std::cell::Cell::new(0) };
4473}
4474
4475/// Current value of [`INTER_SUB16_SPLIT_HITS`].
4476#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4477pub(crate) fn inter_sub16_split_hits() -> usize {
4478 INTER_SUB16_SPLIT_HITS.with(|c| c.get())
4479}
4480
4481// lane-t900 r28: how many 16x16 inter splits reached their four 8x8 leaves
4482// while at least one reference picture was SCALED (superres) -- the counter
4483// behind the lifted "8x8 partition leaf under a scaled reference" refusal.
4484thread_local! {
4485 static SCALED_LEAF8_HITS: std::cell::Cell<usize> =
4486 const { std::cell::Cell::new(0) };
4487}
4488
4489/// Current value of [`SCALED_LEAF8_HITS`].
4490pub fn scaled_leaf8_hits() -> usize {
4491 SCALED_LEAF8_HITS.with(|c| c.get())
4492}
4493
4494// lane-t900 r28: how many sub-8x8 inter blocks (the 4x4 split and the 8x4/4x8
4495// rect pair) were predicted from a SCALED reference -- the counter behind the
4496// lifted "sub-8x8 inter block under a scaled reference" refusal.
4497thread_local! {
4498 static SCALED_SUB8_HITS: std::cell::Cell<usize> =
4499 const { std::cell::Cell::new(0) };
4500}
4501
4502/// Current value of [`SCALED_SUB8_HITS`].
4503pub fn scaled_sub8_hits() -> usize {
4504 SCALED_SUB8_HITS.with(|c| c.get())
4505}
4506
4507// lane-rectwire r2: how many `PARTITION_HORZ`/`VERT` strips actually decoded
4508// real (non-skip) coefficients through [`read_coeffs_rect`] -- proves the
4509// rect coefficient reader itself fired, not just the strip-level partition
4510// symbol [`RECT_PARTITION_HITS`] already counts.
4511thread_local! {
4512 static RECT_COEFF_HITS: std::cell::Cell<usize> =
4513 const { std::cell::Cell::new(0) };
4514}
4515
4516/// Current value of [`RECT_COEFF_HITS`].
4517#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4518pub(crate) fn rect_coeff_hits() -> usize {
4519 RECT_COEFF_HITS.with(|c| c.get())
4520}
4521
4522// lane-rectx r1: how many below-16x16 HORZ/VERT leaves ([`decode_leaf_rect`])
4523// decoded real (non-skip) TX_16X8/TX_8X16 coefficients -- the counter the
4524// charter's real-aomenc gate hard-asserts.
4525thread_local! {
4526 static RECT_LEAF_COEFF_HITS: std::cell::Cell<usize> =
4527 const { std::cell::Cell::new(0) };
4528}
4529
4530/// Current value of [`RECT_LEAF_COEFF_HITS`].
4531#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4532pub(crate) fn rect_leaf_coeff_hits() -> usize {
4533 RECT_LEAF_COEFF_HITS.with(|c| c.get())
4534}
4535
4536// lane-intrarect r1: how many intra-coded HORZ/VERT strips decoded on the
4537// INTER block path ([`decode_intra_rect_in_inter`]), per shape class --
4538// [0] the superblock-level 64x32/32x64, [1] 32x16/16x32, [2] 16x8/8x16.
4539// Every one of them was the named refusal "an intra-coded HORZ/VERT strip
4540// needs rectangular intra prediction" before this round.
4541thread_local! {
4542 static INTRA_RECT_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
4543 const { std::cell::Cell::new([0; 3]) };
4544}
4545
4546/// Current value of [`INTRA_RECT_IN_INTER_HITS`] for one shape class
4547/// (0 = 64x32/32x64, 1 = 32x16/16x32, 2 = 16x8/8x16).
4548#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4549pub(crate) fn intra_rect_strip_in_inter_hits(class: usize) -> usize {
4550 INTRA_RECT_IN_INTER_HITS.with(|c| c.get()[class])
4551}
4552
4553// lane-rect64port r1 (ported by hand from lane-intra64split 5ffbaf3): coded
4554// (non-skip) 64-level HORZ/VERT intra strips whose luma transform is the
4555// un-split TX_64X32/TX_32X64 -- the corner-cropped 32x32 coefficient read of
4556// [`decode_rect_split`], the shape both 10-bit 3840x1608 film cuts stop on.
4557// Split by ORIENTATION (index 0 = 64x32 wide / HORZ, 1 = 32x64 tall / VERT):
4558// a single counter cannot tell an axis swap from a working arm
4559// (class [[scan-weights-cross-axis]]), so the gate asserts both cells.
4560thread_local! {
4561 static RECT64_CORNER_TU_HITS: std::cell::Cell<[usize; 2]> =
4562 const { std::cell::Cell::new([0; 2]) };
4563}
4564
4565/// Current value of [`RECT64_CORNER_TU_HITS`] for one orientation
4566/// (0 = 64x32, 1 = 32x64).
4567pub(crate) fn rect64_corner_tu_hits(orient: usize) -> usize {
4568 RECT64_CORNER_TU_HITS.with(|c| c.get()[orient])
4569}
4570
4571// lane-intrasplit r1: intra HORZ/VERT strips inside an INTER frame whose luma
4572// transform is SPLIT, bucketed by the read `tx_depth` (index 1 and 2; index 0
4573// is never incremented) -- the gate's proof that the lifted path ran per depth.
4574thread_local! {
4575 static INTRA_RECT_IN_INTER_SPLIT_TX_HITS: std::cell::Cell<[usize; 3]> =
4576 const { std::cell::Cell::new([0; 3]) };
4577}
4578
4579// lane-t900 r21: rect intra strips inside an inter frame that read the
4580// screen-content palette syntax (`allow_screen_content_tools` set and the
4581// strip's own shape admitted by `palette_bsize_ctx_wh`) -- the site a blanket
4582// refusal used to guard, so this counter is what keeps its witness gate
4583// non-vacuous.
4584thread_local! {
4585 static INTRA_RECT_IN_INTER_SCREEN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4586}
4587
4588/// Current value of [`INTRA_RECT_IN_INTER_SCREEN_HITS`].
4589#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4590pub(crate) fn intra_rect_in_inter_screen_hits() -> usize {
4591 INTRA_RECT_IN_INTER_SCREEN_HITS.with(std::cell::Cell::get)
4592}
4593
4594/// Resets [`INTRA_RECT_IN_INTER_SCREEN_HITS`] before a decode.
4595#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4596pub(crate) fn reset_intra_rect_in_inter_screen_hits() {
4597 INTRA_RECT_IN_INTER_SCREEN_HITS.with(|c| c.set(0));
4598}
4599
4600/// Current value of [`INTRA_RECT_IN_INTER_SPLIT_TX_HITS`], indexed by tx depth.
4601#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4602pub(crate) fn intra_rect_in_inter_split_tx_hits() -> [usize; 3] {
4603 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(std::cell::Cell::get)
4604}
4605
4606// lane-av1txbands: how many `tx_depth`/`txfm_split` reads the deblock-grid
4607// approximation would have resolved off a DIFFERENT CDF row than the real
4608// `TXFM_CONTEXT` bands do -- the exact blocks this band read fixes, on ANY
4609// frame (lane-midcut r2 had it inter-frame-only). A plain "rect/intra block"
4610// tally is green on the old code too (class gate-blind-to-feature).
4611thread_local! {
4612 static TXCTX_DEBLOCK_DIVERGENCE_HITS: std::cell::Cell<usize> =
4613 const { std::cell::Cell::new(0) };
4614}
4615
4616/// Current value of [`TXCTX_DEBLOCK_DIVERGENCE_HITS`].
4617#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
4618pub(crate) fn txctx_deblock_divergence_hits() -> usize {
4619 TXCTX_DEBLOCK_DIVERGENCE_HITS.with(std::cell::Cell::get)
4620}
4621
4622// lane-intra14 r1: how many intra-coded 1:4 strips decoded on the INTER
4623// block path, per shape -- [0] 64x16, [1] 16x64, [2] 32x8, [3] 8x32. Every
4624// one of them was the named refusal "an intra-coded 1:4 (or other non-2:1)
4625// rect strip on the inter block path" before this round.
4626thread_local! {
4627 static INTRA_RECT4_IN_INTER_HITS: std::cell::Cell<[usize; 4]> =
4628 const { std::cell::Cell::new([0; 4]) };
4629}
4630
4631/// Current value of [`INTRA_RECT4_IN_INTER_HITS`] for one shape
4632/// (0 = 64x16, 1 = 16x64, 2 = 32x8, 3 = 8x32).
4633pub(crate) fn intra_rect4_strip_in_inter_hits(shape: usize) -> usize {
4634 INTRA_RECT4_IN_INTER_HITS.with(|c| c.get()[shape])
4635}
4636
4637// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
4638// through one of the key-frame rect readers ([`decode_block_rect4`],
4639// [`decode_block_rect64`]). `Some((size_group, skip))` tells
4640// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
4641// already read by [`decode_inter_block`] and (b) the luma mode comes off
4642// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
4643// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
4644
4645// lane-rectx r5: how many times a NON-strip `kf_y_mode` reader
4646// ([`decode_block`], [`decode_block_rect`], [`decode_block_rect64`]) took an
4647// above/left mode from the mi-exact map that DIFFERS from its coarse 16x16
4648// slot -- i.e. how often the r5 defect would have picked the wrong CDF row.
4649thread_local! {
4650 static MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
4651 const { std::cell::Cell::new(0) };
4652}
4653
4654/// Current value of [`MODE_MI_OVERRIDE_HITS`].
4655#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4656pub(crate) fn mode_mi_override_hits() -> usize {
4657 MODE_MI_OVERRIDE_HITS.with(|c| c.get())
4658}
4659
4660// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
4661// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
4662// mode from the previous tile, where libaom's `up_available`/`left_available`
4663// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
4664// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
4665// per superblock row in `start_row`, so the luma fallback cannot leak the way
4666// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
4667// the invariant that makes the coarse fallback safe.
4668thread_local! {
4669 static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
4670 const { std::cell::Cell::new(0) };
4671}
4672
4673/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
4674#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4675pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
4676 MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
4677}
4678
4679// lane-cfl r1: how many times a chroma intra-edge filter-type read
4680// (`get_filt_type`, libaom reconintra.c) took an above/left UV mode from the
4681// mi-exact map that DIFFERS from its coarse 16x16 slot -- i.e. how often the
4682// r1 defect would have filtered a chroma edge with the wrong strength.
4683thread_local! {
4684 static UV_MODE_MI_OVERRIDE_HITS: std::cell::Cell<usize> =
4685 const { std::cell::Cell::new(0) };
4686}
4687
4688/// Current value of [`UV_MODE_MI_OVERRIDE_HITS`].
4689#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4690pub(crate) fn uv_mode_mi_override_hits() -> usize {
4691 UV_MODE_MI_OVERRIDE_HITS.with(|c| c.get())
4692}
4693
4694// lane-t900 r12: how many chroma edge-filter-type reads took their above/left
4695// `uv_mode` from the mi GRID where the one-slot-per-column map would have
4696// answered differently -- the sub-8x8 pair case where the pair's own first
4697// half had already overwritten the column slot the chroma-ref half reads.
4698thread_local! {
4699 static UV_MODE_GRID_OVERRIDE_HITS: std::cell::Cell<usize> =
4700 const { std::cell::Cell::new(0) };
4701}
4702
4703/// Current value of [`UV_MODE_GRID_OVERRIDE_HITS`].
4704pub fn uv_mode_grid_override_hits() -> usize {
4705 UV_MODE_GRID_OVERRIDE_HITS.with(|c| c.get())
4706}
4707
4708// lane-t900 r8: how many intra edge-filter-type reads (luma + chroma) the
4709// INTER neighbour stamp saved: the coarse SUB band still held a SMOOTH mode
4710// from an earlier block in that pixel row/column while the mi-exact map --
4711// which an inter block only started writing this round -- correctly says the
4712// neighbour is not smooth (libaom `is_smooth`: an inter neighbour's `mode` is
4713// an INTER mode, and its `uv_mode` "is not set for inter blocks").
4714thread_local! {
4715 static INTER_NEIGHBOUR_NOT_SMOOTH_HITS: std::cell::Cell<usize> =
4716 const { std::cell::Cell::new(0) };
4717}
4718
4719/// Current value of [`INTER_NEIGHBOUR_NOT_SMOOTH_HITS`].
4720#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4721pub(crate) fn inter_neighbour_not_smooth_hits() -> usize {
4722 INTER_NEIGHBOUR_NOT_SMOOTH_HITS.with(|c| c.get())
4723}
4724
4725// lane-mtfix r1: how many times a chroma intra-edge filter-type read was
4726// suppressed at a TILE edge that is not a frame edge -- the above/left
4727// `uv_mode` neighbour of a block on a tile's first mi row/column lives in
4728// another tile, so libaom's `above_mbmi`/`left_mbmi` are NULL there. The
4729// coarse [`SUB`] maps are frame-sized and (`above_uv_mode`) not cleared per
4730// tile, so without the guard in [`Neighbours::smooth_uv_neighbour`] the tile
4731// above would decide this tile's chroma edge filter strength.
4732thread_local! {
4733 static UV_TILE_EDGE_SUPPRESSED_HITS: std::cell::Cell<usize> =
4734 const { std::cell::Cell::new(0) };
4735}
4736
4737/// Current value of [`UV_TILE_EDGE_SUPPRESSED_HITS`].
4738#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4739pub(crate) fn uv_tile_edge_suppressed_hits() -> usize {
4740 UV_TILE_EDGE_SUPPRESSED_HITS.with(|c| c.get())
4741}
4742
4743// lane-cfl r1 gate counters: `UV_CFL_PRED` blocks (every `cfl_alpha_signs`
4744// read) and chroma blocks with a NONZERO `angle_delta_uv` -- the two block
4745// shapes the r1 chroma defect showed up on.
4746thread_local! {
4747 static CFL_BLOCK_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4748 static UV_ANGLE_DELTA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4749}
4750
4751/// Current value of [`CFL_BLOCK_HITS`].
4752#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4753pub(crate) fn cfl_block_hits() -> usize {
4754 CFL_BLOCK_HITS.with(|c| c.get())
4755}
4756
4757/// Current value of [`UV_ANGLE_DELTA_HITS`].
4758#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4759pub(crate) fn uv_angle_delta_hits() -> usize {
4760 UV_ANGLE_DELTA_HITS.with(|c| c.get())
4761}
4762
4763// lane-sbpart r2: how many superblock-level `PARTITION_HORZ`/`PARTITION_VERT`
4764// blocks (two true 64x32/32x64 strips, [`decode_block_rect64`]) fired -- the
4765// gate's proof this round's arms actually reached a real block, not just
4766// that `partition_w64` read one of those two symbol values.
4767thread_local! {
4768 static SB_RECT_HITS: std::cell::Cell<usize> =
4769 const { std::cell::Cell::new(0) };
4770}
4771
4772// Current value of [`SB_RECT_HITS`].
4773// lane-hgkf r1: the frame-edge partition bit, one level each. Slot 0 = a
4774// 64-level gathered edge bit read as HORZ/VERT, 1 = the same bit read as
4775// SPLIT, 2/3 = the 32-level pair. A gate asserting slot 0 or 2 proves the
4776// non-SPLIT edge arm actually decoded (before this round the bit was read and
4777// thrown away, so that arm was unreachable).
4778thread_local! {
4779 static EDGE_PART_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4780}
4781
4782/// Current value of [`EDGE_PART_HITS`].
4783#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4784pub(crate) fn edge_part_hits() -> [usize; 4] {
4785 EDGE_PART_HITS.with(|c| c.get())
4786}
4787
4788/// Reset [`EDGE_PART_HITS`] (a gate counts one stream at a time).
4789#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4790pub(crate) fn reset_edge_part_hits() {
4791 EDGE_PART_HITS.with(|c| c.set([0; 4]));
4792}
4793
4794fn bump_edge_part(slot: usize) {
4795 hit_do! {
4796 EDGE_PART_HITS.with(|c| {
4797 let mut h = c.get();
4798 h[slot] += 1;
4799 c.set(h);
4800 });
4801 }
4802}
4803
4804#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4805pub(crate) fn sb_rect_hits() -> usize {
4806 SB_RECT_HITS.with(|c| c.get())
4807}
4808
4809// lane-golomb r2: the 32x32-level FRAME-EDGE partition. Slot 0/1 = the
4810// gathered edge bit read as 0 (HORZ/VERT) / 1 (SPLIT); slot 2 = a 32-level
4811// PARTITION_HORZ decoded with `has_rows32 == false` (only the top 32x16 half
4812// is coded), slot 3 = a PARTITION_VERT with `has_cols32 == false`. Both tile
4813// paths (intra and inter) feed the same counter.
4814//
4815// lane-golomb r3: slots 4..7 are the same four facts one level up, at the
4816// SUPERBLOCK (64x64) edge -- 4/5 = the gathered 64-level bit read as
4817// HORZ/VERT / SPLIT, 6 = a 64x32 bottom-edge strip decoded with
4818// `has_rows == false`, 7 = a 32x64 right-edge strip. Real aomenc answers a
4819// bottom-edge superblock with the 64-level HORZ (measured: 192x80 flat-band,
4820// every SB of the last row), so the 32-level slots stay 0 on that content and
4821// only these prove the arm fired.
4822thread_local! {
4823 static EDGE32_HITS: std::cell::Cell<[usize; 8]> =
4824 const { std::cell::Cell::new([0; 8]) };
4825}
4826
4827/// Current value of [`EDGE32_HITS`].
4828#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4829pub(crate) fn edge32_hits() -> [usize; 8] {
4830 EDGE32_HITS.with(|c| c.get())
4831}
4832
4833/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
4834/// reads are `if`-conditions, so the counter has to ride the expression.
4835fn bump_edge32_bit(base: usize, bit: usize) -> usize {
4836 bump_edge32(base + bit.min(1));
4837 bit
4838}
4839
4840fn bump_edge32(slot: usize) {
4841 hit_do! {
4842 EDGE32_HITS.with(|c| {
4843 let mut h = c.get();
4844 h[slot] += 1;
4845 c.set(h)
4846 });
4847 }
4848}
4849
4850// lane-part32 r4: how many superblock-level AB blocks (`PARTITION_HORZ_A`/
4851// `_B`/`VERT_A`/`_B` at 64x64 -- two 32x32 squares plus one 64x32/32x64
4852// strip) fired. Real aomenc picks these at 64 even with
4853// `--enable-ab-partitions=0` (lane-sbpart r2's own measurement), so this is
4854// the counter the gate hard-asserts.
4855thread_local! {
4856 static SB_AB_HITS: std::cell::Cell<[usize; 4]> =
4857 const { std::cell::Cell::new([0; 4]) };
4858}
4859
4860/// Current value of [`SB_AB_HITS`], summed over the four arms.
4861#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4862pub(crate) fn sb_ab_hits() -> usize {
4863 SB_AB_HITS.with(|c| c.get().iter().sum())
4864}
4865
4866/// [`SB_AB_HITS`] split per arm, in `PARTITION_HORZ_A`, `_HORZ_B`,
4867/// `_VERT_A`, `_VERT_B` order -- what the gate hard-asserts arm by arm, so a
4868/// run where aomenc's RD only ever picked (say) `HORZ_A` cannot pass off as
4869/// proof of all four.
4870#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4871pub(crate) fn sb_ab_hits_by_arm() -> [usize; 4] {
4872 SB_AB_HITS.with(std::cell::Cell::get)
4873}
4874
4875// lane-tx64x16: the two 1:4 superblock arms, counted per orientation --
4876// `PARTITION_HORZ_4` (four 64x16 strips) and `PARTITION_VERT_4` (four 16x64
4877// strips). Two counters, not one, because a gate that only proved "some 1:4
4878// strip fired" would pass on a stream that never coded the other axis, and
4879// every scan/context table this round added comes in a transposed pair.
4880thread_local! {
4881 static SB_RECT4_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4882 static SB_RECT4_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4883}
4884
4885/// Current value of `SB_RECT4_HORZ_HITS` (64x16 strips decoded).
4886#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4887pub(crate) fn sb_rect4_horz_hits() -> usize {
4888 SB_RECT4_HORZ_HITS.with(|c| c.get())
4889}
4890
4891/// Current value of `SB_RECT4_VERT_HITS` (16x64 strips decoded).
4892#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4893pub(crate) fn sb_rect4_vert_hits() -> usize {
4894 SB_RECT4_VERT_HITS.with(|c| c.get())
4895}
4896
4897// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation --
4898// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32
4899// strips), the arms the ReelB mid-film extract stops at.
4900thread_local! {
4901 static RECT4_32_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4902 static RECT4_32_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4903 /// lane-inter4 r1: the INTER-frame twins of the two counters above --
4904 /// four 32x8 / 8x32 inter strips of a 32x32-level `PARTITION_HORZ_4` /
4905 /// `PARTITION_VERT_4`.
4906 static RECT4_32_HORZ_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4907 static RECT4_32_VERT_INTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4908 /// lane-inter4 r1: superblock-level inter `PARTITION_HORZ`/`PARTITION_VERT`
4909 /// strips (64x32 / 32x64) and their 1:4 pair (64x16 / 16x64).
4910 static INTER_SB_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4911 static INTER_SB_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4912 static INTER_SB_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4913 static INTER_SB_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4914}
4915
4916// How many 32x32-level 1:4 strips actually read coefficients (non-skip):
4917// a gate that only counted strips would pass on an all-skip stream, which
4918// exercises none of the new scan/context tables.
4919thread_local! {
4920 static RECT4_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4921}
4922
4923// lane-rectsplitx r1: 1:4 strips (32x8/8x32/64x16/16x64) decoded through the
4924// per-transform-unit split path, split by tx depth -- depth 1 is a 2:1 RECT
4925// unit (TX_16X8/TX_32X16), depth 2 a square one, and the two INTERLEAVE in
4926// every real stream, so a gate must prove both fired. `SUB16_SPLIT_HITS`
4927// counts the same for a 16x8/8x16 strip below 16x16.
4928thread_local! {
4929 static RECT4_SPLIT_DEPTH1_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4930 static RECT4_SPLIT_DEPTH2_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4931 static SUB16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4932}
4933
4934/// Current values of `RECT4_SPLIT_DEPTH1_HITS` / `RECT4_SPLIT_DEPTH2_HITS`.
4935#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4936pub(crate) fn rect4_split_depth_hits() -> (usize, usize) {
4937 (
4938 RECT4_SPLIT_DEPTH1_HITS.with(|c| c.get()),
4939 RECT4_SPLIT_DEPTH2_HITS.with(|c| c.get()),
4940 )
4941}
4942
4943/// Current value of `SUB16_SPLIT_HITS`.
4944#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4945pub(crate) fn sub16_split_hits() -> usize {
4946 SUB16_SPLIT_HITS.with(|c| c.get())
4947}
4948
4949// lane-frame36 r2: superblock-level strips ([`decode_block_rect64`]) whose
4950// luma transform is SPLIT and which therefore leave through that fn's early
4951// return -- the arm that published no `TXFM_CONTEXT` band until this round.
4952thread_local! {
4953 static RECT64_SPLIT_TXFM_PUBLISH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4954}
4955
4956/// Current value of `RECT64_SPLIT_TXFM_PUBLISH_HITS`.
4957#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4958pub(crate) fn rect64_split_txfm_publish_hits() -> usize {
4959 RECT64_SPLIT_TXFM_PUBLISH_HITS.with(|c| c.get())
4960}
4961
4962/// Current value of `RECT4_COEFF_HITS`.
4963pub(crate) fn rect4_coeff_hits() -> usize {
4964 RECT4_COEFF_HITS.with(|c| c.get())
4965}
4966
4967// lane-sbab r1: how many superblock-level (64x64) AB partitions fired IN AN
4968// INTER frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`,
4969// `_VERT_B` order (the intra-frame counterpart is `SB_AB_HITS`). Each arm is
4970// two 32x32 inter squares plus one true 64x32/32x64 inter strip; the gate
4971// asserts the arms it proves separately so a run whose RD only picked one
4972// cannot pass as proof of the others.
4973thread_local! {
4974 static SB_AB_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4975}
4976
4977/// [`SB_AB_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 64x64 in an
4978/// inter frame).
4979pub fn sb_ab_inter_hits_by_arm() -> [usize; 4] {
4980 SB_AB_INTER_HITS.with(std::cell::Cell::get)
4981}
4982
4983// lane-inter16ab r1: how many 16x16-level AB partitions fired IN AN INTER
4984// frame, per arm, in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B`
4985// order (the intra-frame counterpart is `AB16_HITS`). Each arm is two 8x8
4986// inter leaves (`decode_inter_block8`) plus one true 16x8/8x16 inter strip
4987// (`decode_inter_block` with `write_w`/`write_h`); the gate asserts every
4988// arm separately so a run whose RD only picked one cannot pass as proof of
4989// four.
4990thread_local! {
4991 static AB16_INTER_HITS: std::cell::Cell<[usize; 4]> = const { std::cell::Cell::new([0; 4]) };
4992}
4993
4994/// [`AB16_INTER_HITS`] per arm (HORZ_A, HORZ_B, VERT_A, VERT_B at 16x16 in an
4995/// inter frame).
4996pub fn ab16_inter_hits_by_arm() -> [usize; 4] {
4997 AB16_INTER_HITS.with(std::cell::Cell::get)
4998}
4999
5000// lane-inter16ab r2: the 16x16-level 1:4 pair as INTER blocks -- four 16x4
5001// (`PARTITION_HORZ_4`) or 4x16 (`PARTITION_VERT_4`) strips. `CHROMA_PAIRS`
5002// counts the odd strips that close a 4:2:0 chroma pair
5003// (`is_chroma_reference`, av1_common_int.h:1454: bh == 1 mi => odd mi_row),
5004// `SUB8_PIECES` the pair chroma blocks whose TOP (LEFT) half was built from
5005// the PREVIOUS strip's own mv/ref/filters -- libaom
5006// `build_inter_predictors_sub8x8` (reconinter_template.inc:87-160), reached
5007// through `is_sub8x8_inter` (same file, :54).
5008thread_local! {
5009 static INTER16_HORZ4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5010 static INTER16_VERT4_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5011 static INTER16_CHROMA_PAIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5012 static INTER16_SUB8_PIECE_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5013}
5014
5015// lane-intra16x4: INTRA-coded strips of an inter 16x16-level 1:4 partition --
5016// [0] 16x4, [1] 4x16, [2] the odd (chroma-reference) ones, which carry the
5017// pair's single 8x4 (4x8) chroma unit for BOTH strips.
5018thread_local! {
5019 static INTRA16X4_IN_INTER_HITS: std::cell::Cell<[usize; 3]> =
5020 const { std::cell::Cell::new([0; 3]) };
5021}
5022
5023/// `(intra 16x4 strips, intra 4x16 strips, of which chroma-reference)` decoded
5024/// inside an INTER 16x16-level 1:4 partition (lane-intra16x4).
5025pub fn intra16x4_in_inter_hits() -> (usize, usize, usize) {
5026 let v = INTRA16X4_IN_INTER_HITS.with(std::cell::Cell::get);
5027 (v[0], v[1], v[2])
5028}
5029
5030/// Current values of the inter 16x16-level 1:4 counters: `(16x4 strips, 4x16
5031/// strips, chroma pairs closed, chroma pairs built from two different
5032/// strips' motion vectors)`.
5033pub fn inter16_rect4_counters() -> (usize, usize, usize, usize) {
5034 (
5035 INTER16_HORZ4_HITS.with(std::cell::Cell::get),
5036 INTER16_VERT4_HITS.with(std::cell::Cell::get),
5037 INTER16_CHROMA_PAIR_HITS.with(std::cell::Cell::get),
5038 INTER16_SUB8_PIECE_HITS.with(std::cell::Cell::get),
5039 )
5040}
5041
5042/// One 16x4 / 4x16 inter strip's chroma situation, handed to
5043/// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
5044/// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
5045/// that all mean "an ordinary block, chroma of its own".
5046#[derive(Clone, Copy)]
5047pub(crate) struct InterStripChroma {
5048 /// `is_chroma_reference` for this strip: false on strips 0 and 2, which
5049 /// read and reconstruct NO chroma at all.
5050 has_chroma: bool,
5051 /// `PARTITION_HORZ_4` (16x4 strips) rather than `PARTITION_VERT_4`.
5052 horz: bool,
5053 /// The mi position of the EVEN strip of this pair -- `setup_pred_plane`'s
5054 /// `if (ss_y && (mi_row & 1) && mi_size_high[bsize] == 1) mi_row -= 1`,
5055 /// i.e. the origin of the 8x4 (4x8) chroma transform.
5056 pair_mi: (usize, usize),
5057 /// The previous (even) strip's single-reference MC parameters, `None`
5058 /// when it was intra or compound -- `is_sub8x8_inter` then returns false
5059 /// and the whole chroma block is predicted from THIS strip's mv.
5060 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
5061}
5062
5063 /// The single-reference MC parameters of the inter block that decoded
5064 /// last -- read by the next 1:4 strip to build its pair's chroma.
5065
5066fn bump_ab16_inter(arm: usize) {
5067 hit_do! {
5068 AB16_INTER_HITS.with(|c| {
5069 let mut v = c.get();
5070 v[arm] += 1;
5071 c.set(v);
5072 });
5073 }
5074}
5075
5076// lane-r14: the 16x16-level 1:4 pair -- four 16x4 (`PARTITION_HORZ_4`) or
5077// 4x16 (`PARTITION_VERT_4`) strips, `CHROMA` counting the odd strips that
5078// close a 4:2:0 chroma pair and `COEFF` the strips with a coded residual.
5079thread_local! {
5080 static RECT4_16_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5081 static RECT4_16_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5082 static RECT4_16_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5083 static RECT4_16_COEFF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5084 static RECT4_16_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5085 /// lane-kf1200: pairs whose chroma edge-filter type read from the PAIR's
5086 /// base mi differs from what the strip's own (odd) mi would have said --
5087 /// the shape that made 4 chroma samples of the ReelB `-ss 1200`
5088 /// key frame miss by 1. Zero here means a gate never exercised the fix.
5089 static RECT4_16_UV_PAIR_FILT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5090 /// lane-av1-rect14: lossless 16x4/4x16 chroma pairs walked as two TX_4X4s.
5091 static RECT4_16_LOSSLESS_CHROMA_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5092 /// lane-av1-rect14: intrabc reconstructions of a 16x4/4x16 pair strip.
5093 static RECT4_16_INTRABC_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5094 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
5095 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
5096 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5097 /// lane-av1-loss64: chroma transform units the frame-edge clip skipped
5098 /// (libaom `decode_reconstruct_tx`'s `max_blocks_wide/high` test) in
5099 /// [`decode_block`]'s multi-transform-unit walk -- the units a lossless
5100 /// block overhanging the frame does NOT code.
5101 static CHROMA_EDGE_TU_CLIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5102 /// lane-av1-loss64: skipped lossless intrabc rect strips whose luma
5103 /// entropy bands were zeroed per unit (libaom `av1_reset_entropy_context`,
5104 /// decodeframe.c:1262) instead of leaking the previous occupant's.
5105 static SKIP_LOSSLESS_BAND_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5106}
5107
5108/// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
5109/// that reconstructed as flat DC before lane-kf1200 r2).
5110pub fn skip_cfl_hits() -> usize {
5111 SKIP_CFL_HITS.with(|c| c.get())
5112}
5113
5114/// How many chroma transform units the frame-edge clip skipped in
5115/// [`decode_block`]'s multi-transform-unit walk (lane-av1-loss64). Zero on a
5116/// stream whose lossless blocks never overhang the frame -- a gate asserting
5117/// the clip fired must see this nonzero.
5118pub fn chroma_edge_tu_clip_hits() -> usize {
5119 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.get())
5120}
5121
5122/// How many skipped lossless intrabc rect strips had their luma entropy
5123/// bands zeroed per unit (lane-av1-loss64).
5124pub fn skip_lossless_band_reset_hits() -> usize {
5125 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.get())
5126}
5127
5128/// Gate-side reset for the two lane-av1-loss64 counters above.
5129pub fn reset_loss64_hits() {
5130 CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.set(0));
5131 SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.set(0));
5132}
5133
5134/// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
5135/// from the pair's base mi than the strip's own mi would have given.
5136pub fn rect4_16_uv_pair_filt_hits() -> usize {
5137 RECT4_16_UV_PAIR_FILT_HITS.with(|c| c.get())
5138}
5139
5140/// How many lossless 16x4/4x16 chroma pairs walked two TX_4X4s per plane.
5141pub fn rect4_16_lossless_chroma_hits() -> usize {
5142 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.get())
5143}
5144
5145/// How many 16x4/4x16 strips reconstructed as intra block copy.
5146pub fn rect4_16_intrabc_hits() -> usize {
5147 RECT4_16_INTRABC_HITS.with(|c| c.get())
5148}
5149
5150/// Zero the lane-av1-rect14 pair counters so a gate measures one stream.
5151pub fn reset_rect4_16_pair_hits() {
5152 RECT4_16_LOSSLESS_CHROMA_HITS.with(|c| c.set(0));
5153 RECT4_16_INTRABC_HITS.with(|c| c.set(0));
5154}
5155
5156// lane-reelckf r1: the two chroma defects ReelC's key frames exposed --
5157// CHROMA_SKIP_CFL counts skipped intra blocks whose chroma is `UV_CFL_PRED`
5158// (prediction still runs, libaom `predict_and_reconstruct_intra_block`), and
5159// RECT4_16_CHROMA_DIR counts 1:4 chroma pairs predicted directionally (whose
5160// intra-edge filter type must come from the chroma-reference position).
5161thread_local! {
5162 static CHROMA_SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5163 static RECT4_16_CHROMA_DIR_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5164}
5165
5166/// `(skipped UV_CFL_PRED blocks, directional 1:4 chroma pairs)` -- lane-reelckf.
5167pub fn reelc_chroma_counters() -> (usize, usize) {
5168 (
5169 CHROMA_SKIP_CFL_HITS.with(|c| c.get()),
5170 RECT4_16_CHROMA_DIR_HITS.with(|c| c.get()),
5171 )
5172}
5173
5174/// Current values of the 16x16-level 1:4 counters: `(16x4 strips, 4x16
5175/// strips, chroma-reference strips, strips with a coded residual, strips
5176/// whose luma transform is split)`.
5177pub fn rect4_16_counters() -> (usize, usize, usize, usize, usize) {
5178 (
5179 RECT4_16_HORZ_HITS.with(|c| c.get()),
5180 RECT4_16_VERT_HITS.with(|c| c.get()),
5181 RECT4_16_CHROMA_HITS.with(|c| c.get()),
5182 RECT4_16_COEFF_HITS.with(|c| c.get()),
5183 RECT4_16_SPLIT_HITS.with(|c| c.get()),
5184 )
5185}
5186
5187/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded).
5188pub(crate) fn rect4_32_horz_hits() -> usize {
5189 RECT4_32_HORZ_HITS.with(|c| c.get())
5190}
5191
5192/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded).
5193pub(crate) fn rect4_32_vert_hits() -> usize {
5194 RECT4_32_VERT_HITS.with(|c| c.get())
5195}
5196
5197/// Current value of `RECT4_32_HORZ_INTER_HITS` (32x8 inter strips decoded).
5198pub(crate) fn rect4_32_horz_inter_hits() -> usize {
5199 RECT4_32_HORZ_INTER_HITS.with(|c| c.get())
5200}
5201
5202/// Current value of `RECT4_32_VERT_INTER_HITS` (8x32 inter strips decoded).
5203pub(crate) fn rect4_32_vert_inter_hits() -> usize {
5204 RECT4_32_VERT_INTER_HITS.with(|c| c.get())
5205}
5206
5207/// Current value of `INTER_SB_HORZ_HITS` (64x32 inter strips decoded).
5208pub(crate) fn inter_sb_horz_hits() -> usize {
5209 INTER_SB_HORZ_HITS.with(|c| c.get())
5210}
5211
5212/// Current value of `INTER_SB_VERT_HITS` (32x64 inter strips decoded).
5213pub(crate) fn inter_sb_vert_hits() -> usize {
5214 INTER_SB_VERT_HITS.with(|c| c.get())
5215}
5216
5217/// Current value of `INTER_SB_HORZ4_HITS` (64x16 inter strips decoded).
5218pub(crate) fn inter_sb_horz4_hits() -> usize {
5219 INTER_SB_HORZ4_HITS.with(|c| c.get())
5220}
5221
5222/// Current value of `INTER_SB_VERT4_HITS` (16x64 inter strips decoded).
5223pub(crate) fn inter_sb_vert4_hits() -> usize {
5224 INTER_SB_VERT4_HITS.with(|c| c.get())
5225}
5226
5227// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane
5228// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the
5229// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not
5230// just inert-compiled. Zero forever on a passing gate means that gate's
5231// stream never carries `delta_q_present=1` through a rect64 block.
5232thread_local! {
5233 static RECT64_QIDX_DRIFT_HITS: std::cell::Cell<usize> =
5234 const { std::cell::Cell::new(0) };
5235}
5236
5237/// Current value of [`RECT64_QIDX_DRIFT_HITS`].
5238#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5239pub(crate) fn rect64_qidx_drift_hits() -> usize {
5240 RECT64_QIDX_DRIFT_HITS.with(|c| c.get())
5241}
5242
5243// lane-partab r1: how many 32x32 quadrants decoded an AB partition
5244// (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one
5245// 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the
5246// free-partition gate's proof this round's arms actually fired.
5247thread_local! {
5248 static PARTAB_HITS: std::cell::Cell<usize> =
5249 const { std::cell::Cell::new(0) };
5250}
5251
5252/// Current value of [`PARTAB_HITS`].
5253#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5254pub(crate) fn partab_hits() -> usize {
5255 PARTAB_HITS.with(|c| c.get())
5256}
5257
5258// lane-part32 r1: how many 32x32 quadrants decoded each INTRA AB/4-way arm,
5259// one counter per arm rather than one shared total -- the gate hard-asserts
5260// each of these individually nonzero so a recipe that only ever fires
5261// HORZ_A can't silently stand in for the whole set.
5262thread_local! {
5263 static INTRA_HORZ_A_HITS: std::cell::Cell<usize> =
5264 const { std::cell::Cell::new(0) };
5265 static INTRA_HORZ_B_HITS: std::cell::Cell<usize> =
5266 const { std::cell::Cell::new(0) };
5267 static INTRA_VERT_A_HITS: std::cell::Cell<usize> =
5268 const { std::cell::Cell::new(0) };
5269 static INTRA_VERT_B_HITS: std::cell::Cell<usize> =
5270 const { std::cell::Cell::new(0) };
5271}
5272
5273/// Current value of [`INTRA_HORZ_A_HITS`].
5274#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5275pub(crate) fn intra_horz_a_hits() -> usize {
5276 INTRA_HORZ_A_HITS.with(|c| c.get())
5277}
5278/// Current value of [`INTRA_HORZ_B_HITS`].
5279#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5280pub(crate) fn intra_horz_b_hits() -> usize {
5281 INTRA_HORZ_B_HITS.with(|c| c.get())
5282}
5283/// Current value of [`INTRA_VERT_A_HITS`].
5284#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5285pub(crate) fn intra_vert_a_hits() -> usize {
5286 INTRA_VERT_A_HITS.with(|c| c.get())
5287}
5288/// Current value of [`INTRA_VERT_B_HITS`].
5289#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5290pub(crate) fn intra_vert_b_hits() -> usize {
5291 INTRA_VERT_B_HITS.with(|c| c.get())
5292}
5293
5294// How many [`read_inter_compound_mode`] reads actually happened
5295// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own
5296// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound
5297// mvstack build), not just that `comp_mode` fired. Still refused right
5298// after (no MV assignment or MC wired), so this only counts attempted
5299// reads.
5300thread_local! {
5301 static COMPOUND_MODE_HITS: std::cell::Cell<usize> =
5302 const { std::cell::Cell::new(0) };
5303}
5304
5305/// Current value of [`COMPOUND_MODE_HITS`].
5306#[allow(dead_code)] // reader is test-only (the 12-bit compound witness); dead in non-test builds
5307pub(crate) fn compound_mode_hits() -> usize {
5308 COMPOUND_MODE_HITS.with(|c| c.get())
5309}
5310
5311/// How many query blocks folded in at least one temporal MV candidate
5312/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
5313/// temporal-MV gate's own firing counter (lane-av1tmvp).
5314///
5315/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
5316/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
5317/// this file (`decode_inter_block`) still passes `tpl: None` -- this
5318/// counter compiles and the projection math it counts is unit-tested
5319/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
5320/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
5321/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
5322/// against any real stream today. See the module doc on
5323/// `crate::motion_field` and this crate's ledger for the remaining wiring.
5324#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5325pub(crate) fn tmv_hits() -> usize {
5326 crate::mvstack::tmv_hits()
5327}
5328
5329/// Current value of [`crate::mc::inter_pred_hits`] -- inter predictions
5330/// produced on this thread, the 10-bit inter gate's firing proof.
5331#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5332pub(crate) fn inter_pred_hits() -> usize {
5333 crate::mc::inter_pred_hits()
5334}
5335
5336/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
5337/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
5338/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
5339/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
5340/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
5341/// needs to turn a query block's own resolved `ref_frame` into
5342/// `TplArgs::cur_offset_0` (spec 7.9.3).
5343pub(crate) struct TplFrameArgs<'a> {
5344 pub field: &'a crate::motion_field::TplField,
5345 pub order_hint_bits: u32,
5346 pub order_hint: u32,
5347 /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
5348 /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
5349 /// frame's own `ref_frame_idx` names for each single reference.
5350 pub ref_order_hints: [u32; 7],
5351}
5352
5353/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
5354/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
5355/// decoded `grid`: every 4x4 unit an inter block covers reads the same
5356/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
5357/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
5358/// exact — every block this crate ever codes is at least 8x8, so no 8x8
5359/// cell straddles two different blocks' values.
5360#[allow(unsafe_code)] // lane-mf: `par::Shared` band split, same corner-cut as the filter stages
5361pub(crate) fn build_motion_field(
5362 grid: &MiGrid,
5363 mi_cols: usize,
5364 mi_rows: usize,
5365 order_hint: u32,
5366 order_hint_bits: u32,
5367 ref_order_hints: [u32; 7],
5368 fctx: &FrameCtx,
5369) -> crate::motion_field::MotionField {
5370 let mut field =
5371 crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
5372 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
5373 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
5374 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
5375 // referencing one stores only its OTHER side's mv. With
5376 // `enable_order_hint` off (`order_hint_bits == 0`) every side is 0 and
5377 // nothing is skipped.
5378 // lane-mf: hoisted out of the per-4x4-unit loop -- the answer depends
5379 // only on the reference frame, so it is 7 table lookups per frame instead
5380 // of two per inter unit.
5381 let other_side: [bool; 8] = std::array::from_fn(|rf| {
5382 let i = rf.wrapping_sub(LAST_FRAME as usize);
5383 order_hint_bits != 0
5384 && i < 7
5385 && (crate::motion_field::get_relative_dist(order_hint_bits, ref_order_hints[i], order_hint) > 0
5386 || ref_order_hints[i] == order_hint)
5387 });
5388 // libaom `REFMVS_LIMIT` (`mvref_common.h`): a stored motion field mv is
5389 // capped at 12 bits per component; a longer one is not stored at all.
5390 const REFMVS_LIMIT: i32 = (1 << 12) - 1;
5391 let (cols, rows, cells) = field.cells_mut();
5392 // Fills cell rows `r0..r1`; `out` is exactly those rows' cells, so bands
5393 // never touch each other (an 8x8 cell lives in one cell row, and mi row
5394 // `row` writes cell row `row / 2`).
5395 let fill = |r0: usize, r1: usize, out: &mut [Option<crate::motion_field::SavedMv>]| {
5396 for row in (r0 * 2)..(r1 * 2).min(mi_rows) {
5397 let out = &mut out[(row / 2 - r0) * cols..][..cols];
5398 for col in 0..mi_cols {
5399 let Some(info) = grid.get_frame(row, col) else {
5400 continue;
5401 };
5402 // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
5403 // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
5404 // so an intra block -- or an inter block whose every slot is on the
5405 // other side / over the limit -- wipes what an earlier block wrote
5406 // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
5407 // share a cell).
5408 if !info.is_inter {
5409 out[col / 2] = None;
5410 continue;
5411 }
5412 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
5413 // qualifying one wins -- a compound block stores its second
5414 // reference's mv, never its first (unless the second is on the
5415 // other side or over the limit). Storing slot 0 unconditionally
5416 // put the wrong (mv, ref_frame_offset) pair in every compound
5417 // block's cell, which a later frame's temporal candidate then
5418 // projected with the wrong reference distance.
5419 let mut saved: Option<crate::motion_field::SavedMv> = None;
5420 for (rf, mv) in [
5421 (info.ref_frame, Some(mv32(info.mv))),
5422 (info.ref_frame1.max(0), Some(mv32(info.mv1))),
5423 ] {
5424 let (Some(mv), true) = (mv, rf > 0) else {
5425 continue;
5426 };
5427 if other_side[rf as usize] {
5428 continue;
5429 }
5430 if mv.0.abs() > REFMVS_LIMIT || mv.1.abs() > REFMVS_LIMIT {
5431 continue;
5432 }
5433 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
5434 }
5435 out[col / 2] = saved;
5436 }
5437 }
5438 };
5439 // lane-mf: the whole-frame pass split over the filter pool in cell-row
5440 // bands (same `Shared` corner-cut as the filter stages -- disjointness is
5441 // the band arithmetic above, proved by the 1-vs-16-thread byte-exact gate).
5442 let bands = crate::par::bands(rows, crate::par::filter_threads());
5443 if bands.len() <= 1 {
5444 fill(0, rows, cells);
5445 } else {
5446 let shared = crate::par::Shared::new(cells);
5447 crate::par::run_bands(&bands, fctx, |r0, r1, _| {
5448 // SAFETY: cell rows `r0..r1` are this band's alone.
5449 let cells = unsafe { shared.get() };
5450 fill(r0, r1, &mut cells[r0 * cols..r1 * cols]);
5451 });
5452 }
5453 if crate::envflags::env_flag!("EC_TRACE_TPL") {
5454 eprintln!("EC_TPL_SAVED oh={order_hint}");
5455 for (r, row) in field.occupancy().iter().enumerate() {
5456 eprintln!("EC_TPL_SAVED r{r} {row}");
5457 }
5458 }
5459 field
5460}
5461
5462/// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
5463/// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
5464#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5465pub(crate) fn ref_hits(ref_frame: i8) -> usize {
5466 let c = match ref_frame {
5467 LAST2_FRAME => &LAST2_HITS,
5468 LAST3_FRAME => &LAST3_HITS,
5469 GOLDEN_FRAME => &GOLDEN_HITS,
5470 BWDREF_FRAME => &BWDREF_HITS,
5471 ALTREF2_FRAME => &ALTREF2_HITS,
5472 ALTREF_FRAME => &ALTREF_HITS,
5473 other => panic!("ref_hits: no per-reference counter for ref_frame {other}"),
5474 };
5475 c.with(|v| v.get())
5476}
5477
5478 /// The sequence header's `enable_intra_edge_filter`, set once per
5479 /// [`decode_key_frame_tile_with_cdfs`] call: [`PlaneBuf::reconstruct`]'s
5480 /// own read of it, kept off the call stack (see that function's own doc
5481 /// comment for why) rather than threaded through every `read_plane`/
5482 /// `decode_block`/`decode_leaf8` call between here and there.
5483
5484/// Set [`ENABLE_EDGE_FILTER`] for this thread.
5485///
5486/// `decode_key_frame_tile_with_cdfs` sets it, but `decode_inter_frame_tile`
5487/// never did -- so an inter frame's intra blocks read whatever value the last
5488/// key frame decoded ON THIS THREAD left behind. Inside one stream that is
5489/// harmless (its own key frame sets it first), but a caller that decodes an
5490/// inter frame directly, or a test harness running several streams on one
5491/// thread, inherits a foreign sequence's bit: decode stops being a pure
5492/// function of the bitstream. `decode_stream` now calls this once per stream
5493/// from the sequence header, which covers every frame including inter ones.
5494pub(crate) fn set_enable_edge_filter(value: bool, fctx: &crate::decode::FrameCtx) {
5495 fctx.enable_edge_filter.with(|f| f.set(value));
5496}
5497
5498/// Current value of [`ANGLE_DELTA_HITS`].
5499#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5500pub(crate) fn angle_delta_hits() -> usize {
5501 ANGLE_DELTA_HITS.with(|c| c.get())
5502}
5503
5504/// Current value of [`TX_CLASS1_HITS`].
5505#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5506pub(crate) fn tx_class1_hits() -> usize {
5507 TX_CLASS1_HITS.with(|c| c.get())
5508}
5509
5510// How many `PARTITION_SPLIT` decisions below an 8x8 block (four independent
5511// `BLOCK_4X4` leaves, spec `decode_partition`'s `bSize < BLOCK_8X8` recursion
5512// bottom) this thread's decode actually reconstructed -- the same
5513// before/after counter pattern as [`TX_CLASS1_HITS`], proving a stream
5514// genuinely exercised the sub-8x8 leaf path rather than every attempt
5515// coincidentally landing on `PARTITION_NONE`.
5516thread_local! {
5517 static SUB8_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5518 /// How many 8x8 groups an INTER frame split into four BLOCK_4X4 inter
5519 /// sub-blocks (lane-intersub8).
5520 static SUB8_INTER_SPLIT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5521 /// How many 8x8 groups an INTER frame split into two rectangular sub-8x8
5522 /// inter leaves (lane-intersub8 r3), indexed `[0] = HORZ` (two BLOCK_8X4),
5523 /// `[1] = VERT` (two BLOCK_4X8).
5524 static SUB8_INTER_RECT_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
5525 /// lane-sub8intra: INTRA leaves decoded inside an inter frame's sub-8x8
5526 /// HORZ/VERT partition -- `[0]` 8x4, `[1]` 4x8, `[2]` of those that were
5527 /// the chroma reference (so coded the group's 4x4 chroma intra), `[3]`
5528 /// MIXED groups whose chroma reference is INTER while its sibling is
5529 /// intra (the `is_sub8x8_inter` false path), `[4]` INTRA `BLOCK_4X4`
5530 /// leaves of an inter frame's sub-8x8 `PARTITION_SPLIT` (lane-sub8x4 r2 --
5531 /// the second lifted refusal's own witness; `[0]`/`[1]` count those too,
5532 /// so only this cell separates the split arm from the HORZ/VERT one).
5533 static SUB8_INTRA_RECT_HITS: std::cell::Cell<[usize; 5]> = const { std::cell::Cell::new([0; 5]) };
5534}
5535
5536/// Current value of [`SUB8_INTRA_RECT_HITS`]: `(8x4, 4x8, chroma-reference,
5537/// mixed groups, split 4x4 leaves)`.
5538pub fn sub8_intra_rect_hits() -> (usize, usize, usize, usize, usize) {
5539 SUB8_INTRA_RECT_HITS.with(|c| {
5540 let h = c.get();
5541 (h[0], h[1], h[2], h[3], h[4])
5542 })
5543}
5544
5545/// Current value of [`SUB8_INTER_RECT_HITS`]: `(8x4 groups, 4x8 groups)`.
5546pub fn sub8_inter_rect_hits() -> (usize, usize) {
5547 SUB8_INTER_RECT_HITS.with(|c| {
5548 let h = c.get();
5549 (h[0], h[1])
5550 })
5551}
5552
5553// lane-cdef r1: (a) how many 8x8 CDEF units `apply_cdef` EXCLUDED because all
5554// four of their mi cells are `skip_txfm` (libaom `cdef.c:29-38`
5555// `is_8x8_block_skip` / `av1_cdef_compute_sb_list`'s dlist test), and (b) how
5556// many 8x8 inter leaves (`decode_inter_block8`) wrote that skip band at all.
5557// (b) was 0 for every stream before this round -- the leaf path never touched
5558// the band, so an all-skip 8x8 group kept the PREVIOUS frame's flags and got
5559// filtered where libaom skips it. A gate asserts both are non-zero.
5560thread_local! {
5561 static CDEF_SKIPPED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5562 static INTER8_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5563 // lane-cdef r2: (c) 8x8 CDEF units that are FILTERED and whose extent
5564 // crosses the cropped frame edge -- the only units for which "clamp at
5565 // the crop" and "pad past the mi-rounded extent with CDEF_VERY_LARGE"
5566 // (libaom `cdef.c:249-256`, `cdef_prepare_fb`'s hsize/vsize are
5567 // `nhb << mi_wide_l2` off the MI grid, not the crop) differ. A frame
5568 // whose width or height is not a multiple of 8 is the only shape that
5569 // produces one; the straddling-band gate arms assert it grew.
5570 static CDEF_STRADDLE_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5571 // lane-cdefstrip r1: 8x8 CDEF units visited with an UNWRITTEN skip band
5572 // (see `Neighbours::skip_written`).
5573 static CDEF_UNWRITTEN_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5574 // lane-cdefstrip r1: (d) skip RECTANGULAR blocks (every strip arm: 32x8,
5575 // 8x32, 16x8, 32x16, 64x16, AB/1:4 pieces...) that wrote the CDEF skip
5576 // band, and (e) 8x8 CDEF units whose four mi cells do NOT agree on skip --
5577 // the shape libaom's `is_8x8_block_skip` (`cdef.c:29-38`) exists for: an
5578 // 8-tall strip pair where only one half is skip must still be FILTERED.
5579 static RECT_SKIP_BAND_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5580 static CDEF_MIXED_SKIP_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5581}
5582
5583/// Current value of `RECT_SKIP_BAND_HITS`.
5584pub fn rect_skip_band_hits() -> usize {
5585 RECT_SKIP_BAND_HITS.with(|c| c.get())
5586}
5587
5588/// Current value of `CDEF_MIXED_SKIP_UNITS`.
5589pub fn cdef_mixed_skip_units() -> usize {
5590 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
5591}
5592
5593/// Current value of `CDEF_SKIPPED_UNITS`.
5594#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5595pub(crate) fn cdef_skipped_units() -> usize {
5596 CDEF_SKIPPED_UNITS.with(|c| c.get())
5597}
5598
5599/// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
5600/// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
5601pub fn cdef_unwritten_skip_units() -> usize {
5602 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
5603}
5604
5605/// Current value of `INTER8_SKIP_BAND_HITS`.
5606#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5607pub(crate) fn inter8_skip_band_hits() -> usize {
5608 INTER8_SKIP_BAND_HITS.with(|c| c.get())
5609}
5610
5611/// Current value of `CDEF_STRADDLE_UNITS`.
5612#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5613pub(crate) fn cdef_straddle_units() -> usize {
5614 CDEF_STRADDLE_UNITS.with(|c| c.get())
5615}
5616
5617/// Current value of [`SUB8_SPLIT_HITS`].
5618#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5619pub(crate) fn sub8_split_hits() -> usize {
5620 SUB8_SPLIT_HITS.with(|c| c.get())
5621}
5622
5623/// Current value of [`SUB8_INTER_SPLIT_HITS`].
5624pub fn sub8_inter_split_hits() -> usize {
5625 SUB8_INTER_SPLIT_HITS.with(|c| c.get())
5626}
5627
5628// lane-t900 r7: sub-8x8 inter groups whose one chroma unit inherits a
5629// `tx_type` DIFFERENT from the group's FIRST sub-block -- the only shape that
5630// tells the two rules apart (`av1_get_tx_type` indexes `xd->tx_type_map`,
5631// which `set_mi_offsets` re-points to the CHROMA-REFERENCE sub-block, so the
5632// first sub-block's type is never the one). Reading it off sub-block 0
5633// inverted one 4x4 chroma unit on the wrong basis with the entropy stream
5634// perfectly in sync (no chroma `tx_type` symbol is coded), so a gate can only
5635// see this rule through this counter.
5636thread_local! {
5637 static SUB8_CHROMA_TX_FROM_REF_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5638}
5639
5640/// Current value of `SUB8_CHROMA_TX_FROM_REF_HITS`.
5641pub fn sub8_chroma_tx_from_ref_hits() -> usize {
5642 SUB8_CHROMA_TX_FROM_REF_HITS.with(|c| c.get())
5643}
5644
5645fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
5646 if coeffs && first_sub != chroma_ref {
5647 hit!(SUB8_CHROMA_TX_FROM_REF_HITS);
5648 }
5649}
5650
5651// How many 4x8 / 8x4 leaves (lane-tx4x8's `PARTITION_VERT`/`PARTITION_HORZ`
5652// of an 8x8 block) this thread's decode reconstructed with REAL coefficients
5653// -- a skipped leaf exercises the prediction and the mi bookkeeping but never
5654// the rect transform, the 32-position `eob_pt` or the rect scan, so the gate
5655// asserts on these two rather than a plain leaf count.
5656thread_local! {
5657 static TX4X8_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5658 static TX8X4_CODED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5659 /// Sub-8x8 rect leaves whose `tx_depth` symbol resolved to 1 -- the leaf's
5660 /// two 4x4 transform units, predicted one after the other. A separate
5661 /// counter from [`TX_DEPTH_HITS`] (which every square path also bumps) so
5662 /// the gate can prove THIS path fired.
5663 static RECT8_SPLIT_TX_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5664 /// 16x8/8x16 intra strips whose prediction actually read past the block's
5665 /// own width (above-right) or height (below-left) -- the samples
5666 /// `Reach::of_rect` decides on, and the only ones a wrong `has_tr_*`/
5667 /// `has_bl_*` table row can corrupt (lane-tx4x8 r3).
5668 static RECT_STRIP_REACH_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5669 /// Every 16x8/8x16 intra strip predicted, reaching or not -- the
5670 /// denominator [`RECT_STRIP_REACH_HITS`] is a fraction of.
5671 static RECT_STRIP_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5672}
5673
5674/// Current value of [`RECT8_SPLIT_TX_HITS`].
5675#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5676pub(crate) fn rect8_split_tx_hits() -> usize {
5677 RECT8_SPLIT_TX_HITS.with(|c| c.get())
5678}
5679
5680/// Current value of [`RECT_STRIP_PRED_HITS`].
5681#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5682pub(crate) fn rect_strip_pred_hits() -> usize {
5683 RECT_STRIP_PRED_HITS.with(|c| c.get())
5684}
5685
5686/// Current value of [`RECT_STRIP_REACH_HITS`].
5687#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5688pub(crate) fn rect_strip_reach_hits() -> usize {
5689 RECT_STRIP_REACH_HITS.with(|c| c.get())
5690}
5691
5692/// Current value of [`TX4X8_CODED_HITS`].
5693#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5694pub(crate) fn tx4x8_coded_hits() -> usize {
5695 TX4X8_CODED_HITS.with(|c| c.get())
5696}
5697
5698/// Current value of [`TX8X4_CODED_HITS`].
5699#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5700pub(crate) fn tx8x4_coded_hits() -> usize {
5701 TX8X4_CODED_HITS.with(|c| c.get())
5702}
5703
5704// How many CHROMA coefficient blocks read their `eob_pt` from the class-1
5705// (`TX_CLASS_HORIZ`/`VERT`) row, across every call on the current thread.
5706// Chroma never codes a `tx_type` symbol -- it inherits the colocated luma
5707// type verbatim (`av1_get_tx_type`, `blockd.h:1291`) -- so this fires only on
5708// an inter leaf whose luma picked a 1D type, the path lane-eobc1 wired
5709// (`eob_pt_{16,64,128,256}_chroma_class1`).
5710thread_local! {
5711 static CHROMA_EOB_CLASS1_HITS: std::cell::Cell<usize> =
5712 const { std::cell::Cell::new(0) };
5713}
5714
5715/// Current value of [`CHROMA_EOB_CLASS1_HITS`].
5716#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5717pub(crate) fn chroma_eob_class1_hits() -> usize {
5718 CHROMA_EOB_CLASS1_HITS.with(|c| c.get())
5719}
5720
5721/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
5722/// `tx_type` put this block's `eob_pt` on the class-1 row.
5723fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
5724 if plane_idx > 0 && TxClass::of(tx_type) != TxClass::TwoD {
5725 hit!(CHROMA_EOB_CLASS1_HITS);
5726 }
5727}
5728
5729const SUB_MI: u32 = 4;
5730const MI: usize = 4;
5731const SB: usize = 64;
5732/// The `above_side`/`left_side` value a cell with no decoded neighbour holds
5733/// (tile start, superblock-row start).
5734///
5735/// [`Neighbours::partition_ctx_mi`] reads it as libaom's
5736/// `av1_get_partition_plane_context` reads its own zero-initialised
5737/// `above_partition_context` byte: bit `bsl` clear, i.e. "the neighbour is at
5738/// least as wide as this block". lane-sb128 r1: the old sentinel was `SB`
5739/// (64), which reads identically at every level up to 64x64 but sets the bit
5740/// at the `BLOCK_128X128` root (64 * 2 <= 128) -- the 128-level partition
5741/// symbol was read off CDF row 3 where libaom uses row 0 (aomdec
5742/// `EC_PART mi_row=0 mi_col=0 bsize=15 ctx=16`, i.e. `bsl*4 + 0`).
5743const NO_NEIGHBOUR_SIDE: usize = 128;
5744const BLOCK: usize = 32;
5745const SUB: usize = 16;
5746const TX32: usize = 32;
5747const TX16: usize = 16;
5748const TX8: usize = 8;
5749const TX4: usize = 4;
5750const DC_PRED: usize = 0;
5751/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
5752/// carries an angle delta — [`crate::tile`]'s own private copy of the same
5753/// constant.
5754const V_PRED: usize = 1;
5755const H_PRED: usize = 2;
5756/// `D157_PRED`: `fimode_to_intradir`'s target for `FILTER_D157_PRED` (spec
5757/// `Fimode_To_Intradir`, libaom `blockd.h`).
5758const D157_PRED: usize = 6;
5759/// The last directional mode, `D67_PRED`.
5760const D67_PRED: usize = 8;
5761/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
5762/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
5763/// codes anything else, so this decoder never reads anything else either.
5764const ANGLE_DELTA_ZERO: usize = 3;
5765const NUM_BASE_LEVELS: i32 = 2;
5766const COEFF_BASE_RANGE: i32 = 12;
5767const BR_STEP: i32 = 3;
5768const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
5769
5770/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
5771/// whose probability mass a superblock or block half outside the frame
5772/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
5773/// duplicated here (that module is another lane's territory this round) and
5774/// kept in step with it by the byte-exact round-trip tests below rather than
5775/// by sharing code.
5776const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
5777const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
5778
5779fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
5780 if crate::envflags::env_flag!("EC_AV1_TRACE") {
5781 eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
5782 }
5783}
5784
5785fn element_prob(cdf: &[u16], element: usize) -> u16 {
5786 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
5787}
5788
5789/// The two-symbol CDF a partial superblock/block's forced-split flag is read
5790/// with: the mass of `elements` becomes the probability of the one partition
5791/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
5792/// (the encoder's non-adapting counterpart to this read).
5793fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
5794 let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
5795 [32768 - split, 32768, 0]
5796}
5797
5798fn unsupported(what: impl Into<String>) -> Error {
5799 Error::unsupported("AV1 tile", what.into())
5800}
5801
5802/// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
5803/// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
5804/// same rule.
5805pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
5806 match base_q_idx {
5807 0..=20 => 0,
5808 21..=60 => 1,
5809 61..=120 => 2,
5810 _ => 3,
5811 }
5812}
5813
5814/// `Default_Scan_NxN` (spec 8.4.2), the same anti-diagonal walk
5815/// [`crate::tile`]'s writer generates its scan tables with.
5816fn default_scan(side: usize) -> &'static [u16] {
5817 // One table per transform side (4/8/16/32), built once: this used to be a
5818 // fresh heap allocation plus the whole anti-diagonal walk on every
5819 // transform block read.
5820 static SCANS: std::sync::LazyLock<[Vec<u16>; 4]> = std::sync::LazyLock::new(|| {
5821 [
5822 default_scan_gen(4),
5823 default_scan_gen(8),
5824 default_scan_gen(16),
5825 default_scan_gen(32),
5826 ]
5827 });
5828 assert!(
5829 matches!(side, 4 | 8 | 16 | 32),
5830 "no default scan for a {side}-point transform"
5831 );
5832 &SCANS[side.trailing_zeros() as usize - 2]
5833}
5834
5835fn default_scan_gen(side: usize) -> Vec<u16> {
5836 let mut scan = Vec::with_capacity(side * side);
5837 for d in 0..(2 * side - 1) {
5838 let lo = d.saturating_sub(side - 1);
5839 let hi = d.min(side - 1);
5840 let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
5841 if d % 2 == 0 {
5842 scan.extend(diagonal.rev());
5843 } else {
5844 scan.extend(diagonal);
5845 }
5846 }
5847 scan
5848}
5849
5850/// `Mrow_Scan`/`Mcol_Scan` (spec 8.4.2, libaom `scan.c`): the two
5851/// class-specific scans a `V_DCT`/`H_DCT` transform block reads coefficients
5852/// in, instead of the default zigzag. libaom's own tables are keyed by a
5853/// *column-major* raster (`get_txb_bhl`'s `col = pos / height`) over its
5854/// physically column-major level buffer, but they decompose to the exact
5855/// same (row, col) walk as a flat row-major traversal of *our* row-major
5856/// `grid`/`levels` (`pos = row * side + col`) once you read them that way:
5857/// `Mrow_Scan` visits row 0 across every column, then row 1, ... — precisely
5858/// `0..side*side` in our own indexing — and `Mcol_Scan` is that walk
5859/// transposed (column 0 down every row, then column 1, ...).
5860pub(crate) fn class_scan_table(side: usize, class: TxClass) -> Vec<u16> {
5861 class_scan_table_wh(side, side, class)
5862}
5863
5864/// [`class_scan_table`] widened to `(w, h)` (lane-tx4x8). Checked against
5865/// libaom's own `mrow_scan_4x8`/`mcol_scan_4x8`/`mrow_scan_8x4`/
5866/// `mcol_scan_8x4` (`scan.c`) converted out of their column-major encoding
5867/// by `(p % h) * w + p / h`, the same conversion [`SCAN_16X8`] was
5868/// transcribed with -- `mrow` is the plain row-major raster in our indexing
5869/// and `mcol` its transpose, at rect sizes exactly as at square ones.
5870fn class_scan_table_wh(w: usize, h: usize, class: TxClass) -> Vec<u16> {
5871 match class {
5872 TxClass::Vert => (0..(w * h) as u16).collect(),
5873 TxClass::Horiz => (0..w)
5874 .flat_map(|col| (0..h).map(move |row| (row * w + col) as u16))
5875 .collect(),
5876 TxClass::TwoD => unreachable!("class_scan is only for V_DCT/H_DCT"),
5877 }
5878}
5879
5880fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
5881 match scan_idx {
5882 0 => 0,
5883 i if i <= area / 8 => 1,
5884 i if i <= area / 4 => 2,
5885 _ => 3,
5886 }
5887}
5888
5889/// One cell of [`read_coeffs`]'s level buffer.
5890///
5891/// lane-coef2: the buffer is now PADDED (libaom's `TX_PAD_HOR`/`TX_PAD_VER`,
5892/// `txb_common.h`) -- four zero columns to the right of `side` and four zero
5893/// rows below it, at a fixed `stride = side + 4` -- so the four-away reads
5894/// `base_ctx` makes (`(0, 4)`/`(4, 0)` are its widest offsets) land on real
5895/// zero cells instead of needing the `row >= side || col >= side` edge test
5896/// this used to run five times per coefficient. Nothing writes a padding
5897/// cell, so the values are the same zeros the test returned.
5898#[inline]
5899fn neighbour(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
5900 grid[row * stride + col] as i32
5901}
5902
5903/// spec 5.11.39's three `TxClass`es (`tx_type_to_class`, libaom
5904/// `txb_common.h`): everything but the two lone-axis-identity types this
5905/// decoder reads (`V_DCT`/`H_DCT`) is `TX_CLASS_2D`.
5906#[derive(Clone, Copy, PartialEq, Eq)]
5907pub(crate) enum TxClass {
5908 TwoD,
5909 Horiz,
5910 Vert,
5911}
5912
5913impl TxClass {
5914 pub(crate) fn of(tx_type: TxType) -> Self {
5915 match tx_type {
5916 // `TX_CLASS_VERT`/`TX_CLASS_HORIZ` (`txb_common.h`'s `tx_type_to_class`)
5917 // key on axis alone -- FLIPADST is still ADST for this purpose.
5918 TxType::VDct | TxType::VAdst | TxType::VFlipAdst => Self::Vert,
5919 TxType::HDct | TxType::HAdst | TxType::HFlipAdst => Self::Horiz,
5920 _ => Self::TwoD,
5921 }
5922 }
5923}
5924
5925/// `nz_map_ctx_offset_1d`: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` share one 32-entry
5926/// table (indexed by the position along the transform's *coded* axis --
5927/// `col` for horiz, `row` for vert) that places their contexts past the 2D
5928/// table's own 26 rows (`SIG_COEF_CONTEXTS_2D`), 16 rows total
5929/// (`SIG_COEF_CONTEXTS_1D`) split 26/31/36.
5930pub(crate) fn nz_map_ctx_offset_1d(i: usize) -> usize {
5931 match i {
5932 0 => 26,
5933 1 => 31,
5934 _ => 36,
5935 }
5936}
5937
5938fn base_ctx(
5939 grid: &[u8],
5940 stride: usize,
5941 row: usize,
5942 col: usize,
5943 class: TxClass,
5944 rect_shape: Option<(usize, usize)>,
5945) -> usize {
5946 // libaom's `get_nz_map_ctx_from_stats` only special-cases the DC
5947 // coefficient to ctx 0 for `TX_CLASS_2D` (`(tx_class | coeff_idx) == 0`,
5948 // txb_common.h) -- `V_DCT`/`H_DCT` (class `Horiz`/`Vert`) still run the DC
5949 // position through the full 1D neighbour sum and offset table. Skipping
5950 // that for every class desynced the last (DC) coefficient of a
5951 // `TX_CLASS_HORIZ` block (lane-av1tx4 final round: real ctx 28 read as
5952 // 0, which then read one extra `BR` symbol at the max and forced a
5953 // spurious third Golomb call).
5954 if class == TxClass::TwoD && row == 0 && col == 0 {
5955 return 0;
5956 }
5957 let offsets: [(usize, usize); 5] = match class {
5958 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
5959 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
5960 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
5961 };
5962 let mag: i32 = offsets
5963 .iter()
5964 .map(|&(dr, dc)| neighbour(grid, stride, row + dr, col + dc).min(3))
5965 .sum();
5966 let ctx = ((mag + 1) >> 1).min(4) as usize;
5967 match class {
5968 // libaom's CDF *set* for a truncated 64-wide/tall corner resolves
5969 // through `get_txsize_entropy_ctx` to the square `TX_64X64` (this
5970 // decoder's `TxbSet::Luma64`), but `get_nz_map_ctx_from_stats`
5971 // separately indexes `av1_nz_map_ctx_offset` by the raw, un-adjusted
5972 // `tx_size` -- `TX_32X64`/`TX_64X32` for a superblock-level HORZ/VERT
5973 // strip, which own a genuinely different table from the square one
5974 // (lane-sbpart r8 root cause: `(row=1, col=0)` reads ctx 2 under the
5975 // square table vs the real ctx 13 the rect table gives).
5976 TxClass::TwoD => {
5977 // lane-rectsplit r4: apply libaom's GENERATING RULE
5978 // (`txb_common.h:199-209`) directly instead of indexing the
5979 // transcribed 5x5 tables. `av1_nz_map_ctx_offset[tx_size]` is a
5980 // FLAT array read at `coeff_idx`, and `coeff_idx` is COLUMN-major
5981 // (libaom decomposes it as `col = coeff_idx >> bhl`, `bhl` the
5982 // ADJUSTED height's log2, 5 for both `TX_64X32` and `TX_32X64`),
5983 // so 32 consecutive entries are one COLUMN: the [`cdf`]
5984 // transcriptions are `[col][row]` and this read had them as
5985 // `[row][col]` -- the transpose, i.e. the other shape's rule with
5986 // 11 and 16 swapped. Same values as [`base_ctx_rect`] now, stated
5987 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
5988 // pins the rule against the tables over their whole 5x5 domain.
5989 if let Some((w, h)) = rect_shape {
5990 if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
5991 eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}");
5992 }
5993 if w < h && row < 2 {
5994 return ctx + 11;
5995 }
5996 if w > h && col < 2 {
5997 return ctx + 16;
5998 }
5999 }
6000 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6001 }
6002 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
6003 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
6004 }
6005}
6006
6007/// The five `base_ctx` neighbour taps and the three `br_ctx` ones as FLAT
6008/// offsets into the padded level frame (lane-coefread): the tap pattern is a
6009/// function of the tx class alone, which is fixed for a whole transform unit,
6010/// so resolving it once per unit takes the class match and the `(dr, dc)`
6011/// -> `dr * stride + dc` arithmetic out of the per-coefficient path. Same
6012/// taps as [`base_ctx`]/[`br_ctx`] read, stated once;
6013/// `flat_taps_match_the_row_col_neighbour_reads` pins them against the
6014/// original `(dr, dc)` form.
6015fn flat_taps(stride: usize, class: TxClass) -> ([usize; 5], [usize; 3]) {
6016 match class {
6017 TxClass::TwoD => (
6018 [stride, 1, stride + 1, 2 * stride, 2],
6019 [stride, 1, stride + 1],
6020 ),
6021 TxClass::Horiz => ([stride, 1, 2, 3, 4], [stride, 1, 2]),
6022 TxClass::Vert => (
6023 [stride, 1, 2 * stride, 3 * stride, 4 * stride],
6024 [stride, 1, 2 * stride],
6025 ),
6026 }
6027}
6028
6029/// [`base_ctx`]'s neighbour sum, off flat taps: `((sum of five clamped
6030/// neighbours) + 1) >> 1`, clamped to 4.
6031#[inline(always)]
6032fn base_mag(grid: &[u8], idx: usize, taps: &[usize; 5]) -> usize {
6033 let mut mag = 0u32;
6034 for &t in taps {
6035 mag += u32::from(grid[idx + t]).min(3);
6036 }
6037 (((mag + 1) >> 1) as usize).min(4)
6038}
6039
6040/// [`br_ctx`]'s neighbour sum, off flat taps.
6041#[inline(always)]
6042fn br_mag(grid: &[u8], idx: usize, taps: &[usize; 3]) -> usize {
6043 let mut mag = 0u32;
6044 for &t in taps {
6045 mag += u32::from(grid[idx + t]);
6046 }
6047 (((mag + 1) >> 1) as usize).min(6)
6048}
6049
6050/// lane-coefread: superseded on the decode path by [`br_mag`] plus the
6051/// origin-offset tail the two coefficient readers state inline; kept as the
6052/// `(row, col)` form `flat_taps_match_the_row_col_neighbour_reads` pins the
6053/// flat one against.
6054#[cfg(test)]
6055fn br_ctx(grid: &[u8], stride: usize, row: usize, col: usize, class: TxClass) -> usize {
6056 let extra = match class {
6057 TxClass::TwoD => neighbour(grid, stride, row + 1, col + 1),
6058 TxClass::Horiz => neighbour(grid, stride, row, col + 2),
6059 TxClass::Vert => neighbour(grid, stride, row + 2, col),
6060 };
6061 let mag = neighbour(grid, stride, row + 1, col)
6062 + neighbour(grid, stride, row, col + 1)
6063 + extra;
6064 let mag = (((mag + 1) >> 1).min(6)) as usize;
6065 if row == 0 && col == 0 {
6066 return mag;
6067 }
6068 let near_origin = match class {
6069 TxClass::TwoD => row < 2 && col < 2,
6070 TxClass::Horiz => col == 0,
6071 TxClass::Vert => row == 0,
6072 };
6073 if near_origin { mag + 7 } else { mag + 14 }
6074}
6075
6076/// `Default_Scan_32x16` (spec 8.4.2, libaom `scan.c`'s `default_scan_32x16`):
6077/// transposed from libaom's column-major buffer into this decoder's row-major
6078/// `pos = row * 32 + col` (lane-rectwire, verified as a bijection of `0..512`
6079/// against the real table). Not the square zigzag formula generalized to
6080/// unequal `w`/`h` -- checked and that does NOT reproduce this table.
6081const SCAN_32X16: [u16; 512] = [
6082 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161,
6083 130, 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 256, 225, 194, 163, 132, 101, 70, 39,
6084 8, 288, 257, 226, 195, 164, 133, 102, 71, 40, 9, 320, 289, 258, 227, 196, 165, 134, 103, 72,
6085 41, 10, 352, 321, 290, 259, 228, 197, 166, 135, 104, 73, 42, 11, 384, 353, 322, 291, 260, 229,
6086 198, 167, 136, 105, 74, 43, 12, 416, 385, 354, 323, 292, 261, 230, 199, 168, 137, 106, 75, 44,
6087 13, 448, 417, 386, 355, 324, 293, 262, 231, 200, 169, 138, 107, 76, 45, 14, 480, 449, 418,
6088 387, 356, 325, 294, 263, 232, 201, 170, 139, 108, 77, 46, 15, 481, 450, 419, 388, 357, 326,
6089 295, 264, 233, 202, 171, 140, 109, 78, 47, 16, 482, 451, 420, 389, 358, 327, 296, 265, 234,
6090 203, 172, 141, 110, 79, 48, 17, 483, 452, 421, 390, 359, 328, 297, 266, 235, 204, 173, 142,
6091 111, 80, 49, 18, 484, 453, 422, 391, 360, 329, 298, 267, 236, 205, 174, 143, 112, 81, 50, 19,
6092 485, 454, 423, 392, 361, 330, 299, 268, 237, 206, 175, 144, 113, 82, 51, 20, 486, 455, 424,
6093 393, 362, 331, 300, 269, 238, 207, 176, 145, 114, 83, 52, 21, 487, 456, 425, 394, 363, 332,
6094 301, 270, 239, 208, 177, 146, 115, 84, 53, 22, 488, 457, 426, 395, 364, 333, 302, 271, 240,
6095 209, 178, 147, 116, 85, 54, 23, 489, 458, 427, 396, 365, 334, 303, 272, 241, 210, 179, 148,
6096 117, 86, 55, 24, 490, 459, 428, 397, 366, 335, 304, 273, 242, 211, 180, 149, 118, 87, 56, 25,
6097 491, 460, 429, 398, 367, 336, 305, 274, 243, 212, 181, 150, 119, 88, 57, 26, 492, 461, 430,
6098 399, 368, 337, 306, 275, 244, 213, 182, 151, 120, 89, 58, 27, 493, 462, 431, 400, 369, 338,
6099 307, 276, 245, 214, 183, 152, 121, 90, 59, 28, 494, 463, 432, 401, 370, 339, 308, 277, 246,
6100 215, 184, 153, 122, 91, 60, 29, 495, 464, 433, 402, 371, 340, 309, 278, 247, 216, 185, 154,
6101 123, 92, 61, 30, 496, 465, 434, 403, 372, 341, 310, 279, 248, 217, 186, 155, 124, 93, 62, 31,
6102 497, 466, 435, 404, 373, 342, 311, 280, 249, 218, 187, 156, 125, 94, 63, 498, 467, 436, 405,
6103 374, 343, 312, 281, 250, 219, 188, 157, 126, 95, 499, 468, 437, 406, 375, 344, 313, 282, 251,
6104 220, 189, 158, 127, 500, 469, 438, 407, 376, 345, 314, 283, 252, 221, 190, 159, 501, 470, 439,
6105 408, 377, 346, 315, 284, 253, 222, 191, 502, 471, 440, 409, 378, 347, 316, 285, 254, 223, 503,
6106 472, 441, 410, 379, 348, 317, 286, 255, 504, 473, 442, 411, 380, 349, 318, 287, 505, 474, 443,
6107 412, 381, 350, 319, 506, 475, 444, 413, 382, 351, 507, 476, 445, 414, 383, 508, 477, 446, 415,
6108 509, 478, 447, 510, 479, 511,
6109];
6110
6111/// `Default_Scan_16x32`, this decoder's own row-major transcription (see
6112/// [`SCAN_32X16`]'s doc comment).
6113const SCAN_16X32: [u16; 512] = [
6114 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,
6115 66, 81, 96, 7, 22, 37, 52, 67, 82, 97, 112, 8, 23, 38, 53, 68, 83, 98, 113, 128, 9, 24, 39, 54,
6116 69, 84, 99, 114, 129, 144, 10, 25, 40, 55, 70, 85, 100, 115, 130, 145, 160, 11, 26, 41, 56, 71,
6117 86, 101, 116, 131, 146, 161, 176, 12, 27, 42, 57, 72, 87, 102, 117, 132, 147, 162, 177, 192,
6118 13, 28, 43, 58, 73, 88, 103, 118, 133, 148, 163, 178, 193, 208, 14, 29, 44, 59, 74, 89, 104,
6119 119, 134, 149, 164, 179, 194, 209, 224, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165, 180,
6120 195, 210, 225, 240, 31, 46, 61, 76, 91, 106, 121, 136, 151, 166, 181, 196, 211, 226, 241, 256,
6121 47, 62, 77, 92, 107, 122, 137, 152, 167, 182, 197, 212, 227, 242, 257, 272, 63, 78, 93, 108,
6122 123, 138, 153, 168, 183, 198, 213, 228, 243, 258, 273, 288, 79, 94, 109, 124, 139, 154, 169,
6123 184, 199, 214, 229, 244, 259, 274, 289, 304, 95, 110, 125, 140, 155, 170, 185, 200, 215, 230,
6124 245, 260, 275, 290, 305, 320, 111, 126, 141, 156, 171, 186, 201, 216, 231, 246, 261, 276, 291,
6125 306, 321, 336, 127, 142, 157, 172, 187, 202, 217, 232, 247, 262, 277, 292, 307, 322, 337, 352,
6126 143, 158, 173, 188, 203, 218, 233, 248, 263, 278, 293, 308, 323, 338, 353, 368, 159, 174, 189,
6127 204, 219, 234, 249, 264, 279, 294, 309, 324, 339, 354, 369, 384, 175, 190, 205, 220, 235, 250,
6128 265, 280, 295, 310, 325, 340, 355, 370, 385, 400, 191, 206, 221, 236, 251, 266, 281, 296, 311,
6129 326, 341, 356, 371, 386, 401, 416, 207, 222, 237, 252, 267, 282, 297, 312, 327, 342, 357, 372,
6130 387, 402, 417, 432, 223, 238, 253, 268, 283, 298, 313, 328, 343, 358, 373, 388, 403, 418, 433,
6131 448, 239, 254, 269, 284, 299, 314, 329, 344, 359, 374, 389, 404, 419, 434, 449, 464, 255, 270,
6132 285, 300, 315, 330, 345, 360, 375, 390, 405, 420, 435, 450, 465, 480, 271, 286, 301, 316, 331,
6133 346, 361, 376, 391, 406, 421, 436, 451, 466, 481, 496, 287, 302, 317, 332, 347, 362, 377, 392,
6134 407, 422, 437, 452, 467, 482, 497, 303, 318, 333, 348, 363, 378, 393, 408, 423, 438, 453, 468,
6135 483, 498, 319, 334, 349, 364, 379, 394, 409, 424, 439, 454, 469, 484, 499, 335, 350, 365, 380,
6136 395, 410, 425, 440, 455, 470, 485, 500, 351, 366, 381, 396, 411, 426, 441, 456, 471, 486, 501,
6137 367, 382, 397, 412, 427, 442, 457, 472, 487, 502, 383, 398, 413, 428, 443, 458, 473, 488, 503,
6138 399, 414, 429, 444, 459, 474, 489, 504, 415, 430, 445, 460, 475, 490, 505, 431, 446, 461, 476,
6139 491, 506, 447, 462, 477, 492, 507, 463, 478, 493, 508, 479, 494, 509, 495, 510, 511,
6140];
6141
6142/// `Default_Scan_4x8` (libaom `scan.c`), this decoder's own row-major
6143/// transcription (see [`SCAN_32X16`]'s doc comment for the conversion, which
6144/// was re-verified this lane by regenerating [`SCAN_16X8`]/[`SCAN_8X16`] from
6145/// the same source).
6146const SCAN_4X8: [u16; 32] = [
6147 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22, 25, 28,
6148 23, 26, 29, 27, 30, 31,
6149];
6150
6151/// `Default_Scan_8x4`, same source and conversion as [`SCAN_4X8`].
6152const SCAN_8X4: [u16; 32] = [
6153 0, 8, 1, 16, 9, 2, 24, 17, 10, 3, 25, 18, 11, 4, 26, 19, 12, 5, 27, 20, 13, 6, 28, 21, 14, 7,
6154 29, 22, 15, 30, 23, 31,
6155];
6156
6157/// `Default_Scan_16x8`, this decoder's own row-major transcription (see
6158/// [`SCAN_32X16`]'s doc comment).
6159const SCAN_16X8: [u16; 128] = [
6160 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,
6161 36, 21, 6, 112, 97, 82, 67, 52, 37, 22, 7, 113, 98, 83, 68, 53, 38, 23, 8, 114, 99, 84, 69, 54,
6162 39, 24, 9, 115, 100, 85, 70, 55, 40, 25, 10, 116, 101, 86, 71, 56, 41, 26, 11, 117, 102, 87,
6163 72, 57, 42, 27, 12, 118, 103, 88, 73, 58, 43, 28, 13, 119, 104, 89, 74, 59, 44, 29, 14, 120,
6164 105, 90, 75, 60, 45, 30, 15, 121, 106, 91, 76, 61, 46, 31, 122, 107, 92, 77, 62, 47, 123, 108,
6165 93, 78, 63, 124, 109, 94, 79, 125, 110, 95, 126, 111, 127,
6166];
6167
6168/// `Default_Scan_8x16`, this decoder's own row-major transcription (see
6169/// [`SCAN_32X16`]'s doc comment).
6170const SCAN_8X16: [u16; 128] = [
6171 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,
6172 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
6173 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
6174 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
6175 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 87, 94, 101, 108, 115, 122, 95, 102, 109, 116,
6176 123, 103, 110, 117, 124, 111, 118, 125, 119, 126, 127,
6177];
6178
6179/// `Default_Scan_32x8`, this decoder's own row-major transcription (see
6180/// [`SCAN_32X16`]'s doc comment) -- the chroma plane of a 64x16
6181/// `PARTITION_HORZ_4` superblock strip (lane-tx64x16). libaom stores its
6182/// scans column-major (`p = col * height + row`), so a naive copy of
6183/// `default_scan_32x8` would silently install the TRANSPOSED 8x32 order
6184/// (class reference-layout-not-spec): `default_scan_16x8`'s literal bytes
6185/// are byte-identical to this decoder's [`SCAN_8X16`].
6186const SCAN_32X8: [u16; 256] = [
6187 0, 32, 1, 64, 33, 2, 96, 65, 34, 3, 128, 97, 66, 35, 4, 160, 129, 98, 67, 36, 5, 192, 161, 130,
6188 99, 68, 37, 6, 224, 193, 162, 131, 100, 69, 38, 7, 225, 194, 163, 132, 101, 70, 39, 8, 226, 195,
6189 164, 133, 102, 71, 40, 9, 227, 196, 165, 134, 103, 72, 41, 10, 228, 197, 166, 135, 104, 73, 42,
6190 11, 229, 198, 167, 136, 105, 74, 43, 12, 230, 199, 168, 137, 106, 75, 44, 13, 231, 200, 169,
6191 138, 107, 76, 45, 14, 232, 201, 170, 139, 108, 77, 46, 15, 233, 202, 171, 140, 109, 78, 47, 16,
6192 234, 203, 172, 141, 110, 79, 48, 17, 235, 204, 173, 142, 111, 80, 49, 18, 236, 205, 174, 143,
6193 112, 81, 50, 19, 237, 206, 175, 144, 113, 82, 51, 20, 238, 207, 176, 145, 114, 83, 52, 21, 239,
6194 208, 177, 146, 115, 84, 53, 22, 240, 209, 178, 147, 116, 85, 54, 23, 241, 210, 179, 148, 117,
6195 86, 55, 24, 242, 211, 180, 149, 118, 87, 56, 25, 243, 212, 181, 150, 119, 88, 57, 26, 244, 213,
6196 182, 151, 120, 89, 58, 27, 245, 214, 183, 152, 121, 90, 59, 28, 246, 215, 184, 153, 122, 91,
6197 60, 29, 247, 216, 185, 154, 123, 92, 61, 30, 248, 217, 186, 155, 124, 93, 62, 31, 249, 218, 187,
6198 156, 125, 94, 63, 250, 219, 188, 157, 126, 95, 251, 220, 189, 158, 127, 252, 221, 190, 159, 253,
6199 222, 191, 254, 223, 255,
6200];
6201/// `Default_Scan_8x32`, [`SCAN_32X8`]'s transpose (the chroma plane of a
6202/// 16x64 `PARTITION_VERT_4` strip).
6203const SCAN_8X32: [u16; 256] = [
6204 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,
6205 41, 48, 7, 14, 21, 28, 35, 42, 49, 56, 15, 22, 29, 36, 43, 50, 57, 64, 23, 30, 37, 44, 51, 58,
6206 65, 72, 31, 38, 45, 52, 59, 66, 73, 80, 39, 46, 53, 60, 67, 74, 81, 88, 47, 54, 61, 68, 75, 82,
6207 89, 96, 55, 62, 69, 76, 83, 90, 97, 104, 63, 70, 77, 84, 91, 98, 105, 112, 71, 78, 85, 92, 99,
6208 106, 113, 120, 79, 86, 93, 100, 107, 114, 121, 128, 87, 94, 101, 108, 115, 122, 129, 136, 95,
6209 102, 109, 116, 123, 130, 137, 144, 103, 110, 117, 124, 131, 138, 145, 152, 111, 118, 125, 132,
6210 139, 146, 153, 160, 119, 126, 133, 140, 147, 154, 161, 168, 127, 134, 141, 148, 155, 162, 169,
6211 176, 135, 142, 149, 156, 163, 170, 177, 184, 143, 150, 157, 164, 171, 178, 185, 192, 151, 158,
6212 165, 172, 179, 186, 193, 200, 159, 166, 173, 180, 187, 194, 201, 208, 167, 174, 181, 188, 195,
6213 202, 209, 216, 175, 182, 189, 196, 203, 210, 217, 224, 183, 190, 197, 204, 211, 218, 225, 232,
6214 191, 198, 205, 212, 219, 226, 233, 240, 199, 206, 213, 220, 227, 234, 241, 248, 207, 214, 221,
6215 228, 235, 242, 249, 215, 222, 229, 236, 243, 250, 223, 230, 237, 244, 251, 231, 238, 245, 252,
6216 239, 246, 253, 247, 254, 255,
6217];
6218/// `Default_Scan_16x4`, this decoder's own row-major transcription of
6219/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA
6220/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level
6221/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with
6222/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing
6223/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two
6224/// were emitted -- a naive copy installs the transpose (class
6225/// reference-layout-not-spec).
6226const SCAN_16X4: [u16; 64] = [
6227 0, 16, 1, 32, 17, 2, 48, 33, 18, 3, 49, 34, 19, 4, 50, 35, 20, 5, 51, 36, 21, 6, 52, 37, 22, 7,
6228 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13,
6229 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63,
6230];
6231/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an
6232/// 8x32 `PARTITION_VERT_4` strip).
6233const SCAN_4X16: [u16; 64] = [
6234 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22, 25, 28,
6235 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52,
6236 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63,
6237];
6238
6239/// [`neighbour`]'s rect form (lane-rectwire): same lane-coef2 padding
6240/// (`stride = w + 4`, four spare rows), so the edge test is the zeros the
6241/// padding already holds.
6242#[inline]
6243fn neighbour_rect(grid: &[u8], stride: usize, row: usize, col: usize) -> i32 {
6244 grid[row * stride + col] as i32
6245}
6246
6247/// [`base_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire):
6248/// the rect generalization is libaom's own comment in
6249/// `get_nz_map_ctx_from_stats` (`txb_common.h:189-224`), reduces to the exact
6250/// same [`cdf::NZ_MAP_CTX_OFFSET_32`] table when `w == h`. Never called for
6251/// `V_DCT`/`H_DCT` -- geometrically impossible at the two size pairs
6252/// [`decode_block_rect`] codes (see that function's own doc comment).
6253fn base_ctx_rect(
6254 grid: &[u8],
6255 stride: usize,
6256 w: usize,
6257 h: usize,
6258 row: usize,
6259 col: usize,
6260 class: TxClass,
6261) -> usize {
6262 // Same `(tx_class | coeff_idx) == 0` guard [`base_ctx`] documents: only
6263 // the 2D class short-circuits the DC position.
6264 if class == TxClass::TwoD && row == 0 && col == 0 {
6265 return 0;
6266 }
6267 let offsets: [(usize, usize); 5] = match class {
6268 TxClass::TwoD => [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)],
6269 TxClass::Horiz => [(1, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
6270 TxClass::Vert => [(1, 0), (0, 1), (2, 0), (3, 0), (4, 0)],
6271 };
6272 let mag: i32 = offsets
6273 .iter()
6274 .map(|&(dr, dc)| neighbour_rect(grid, stride, row + dr, col + dc).min(3))
6275 .sum();
6276 let ctx = ((mag + 1) >> 1).min(4) as usize;
6277 match class {
6278 TxClass::TwoD => {
6279 if w < h && row < 2 {
6280 return ctx + 11;
6281 }
6282 if w > h && col < 2 {
6283 return ctx + 16;
6284 }
6285 ctx + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6286 }
6287 // Shape-independent in libaom too (`get_nz_map_ctx_from_stats`'s
6288 // `TX_CLASS_HORIZ`/`VERT` arms index `nz_map_ctx_offset_1d` by the
6289 // position along one axis only).
6290 TxClass::Horiz => ctx + nz_map_ctx_offset_1d(col.min(31)),
6291 TxClass::Vert => ctx + nz_map_ctx_offset_1d(row.min(31)),
6292 }
6293}
6294
6295/// [`br_ctx`]'s `TxClass::TwoD` arm widened to `(w, h)` (lane-rectwire): the
6296/// neighbour-offset math itself is shape-independent, only the boundary
6297/// clamp needs the real bound in each axis.
6298/// lane-coefread: superseded by [`br_mag`] on the rect decode path too --
6299/// its body was character-for-character [`br_ctx`]'s, which
6300/// `flat_taps_match_the_row_col_neighbour_reads` now asserts.
6301#[cfg(test)]
6302fn br_ctx_rect(
6303 grid: &[u8],
6304 stride: usize,
6305 row: usize,
6306 col: usize,
6307 class: TxClass,
6308) -> usize {
6309 let extra = match class {
6310 TxClass::TwoD => neighbour_rect(grid, stride, row + 1, col + 1),
6311 TxClass::Horiz => neighbour_rect(grid, stride, row, col + 2),
6312 TxClass::Vert => neighbour_rect(grid, stride, row + 2, col),
6313 };
6314 let mag = neighbour_rect(grid, stride, row + 1, col)
6315 + neighbour_rect(grid, stride, row, col + 1)
6316 + extra;
6317 let mag = (((mag + 1) >> 1).min(6)) as usize;
6318 if row == 0 && col == 0 {
6319 return mag;
6320 }
6321 let near_origin = match class {
6322 TxClass::TwoD => row < 2 && col < 2,
6323 TxClass::Horiz => col == 0,
6324 TxClass::Vert => row == 0,
6325 };
6326 if near_origin { mag + 7 } else { mag + 14 }
6327}
6328
6329fn dc_vote(dc: Option<bool>) -> i32 {
6330 match dc {
6331 None => 0,
6332 Some(true) => -1,
6333 Some(false) => 1,
6334 }
6335}
6336
6337fn dc_sign_ctx(vote: i32) -> usize {
6338 match vote.signum() {
6339 0 => 0,
6340 -1 => 1,
6341 _ => 2,
6342 }
6343}
6344
6345/// The `tx_type` a CDF symbol names, given the width of the row it was read
6346/// from.
6347///
6348/// The row's own width names its set (spec `Tx_Type_Intra_Inv_Set*` /
6349/// `Tx_Type_Inter_Inv_Set*`): 17 slots (16 symbols) is `EXT_TX_SET_ALL16`, 13
6350/// (12) `EXT_TX_SET_DTT9_IDTX_1DDCT`, 8 (7) `TX_SET_INTRA_1`, and everything
6351/// narrower the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` order, whose two
6352/// members are a prefix of the five.
6353///
6354/// One function rather than a `match` at each reader, so
6355/// [`crate::refusal_inventory`]'s enumeration of every (width, symbol) pair
6356/// tests the mapping the readers actually use.
6357pub(crate) fn tx_type_from_symbol(cdf_len: usize, t: usize) -> Option<TxType> {
6358 match cdf_len {
6359 17 => TxType::from_symbol_all16(t),
6360 13 => TxType::from_symbol_set2_12(t),
6361 8 => TxType::from_symbol_set1(t),
6362 _ => TxType::from_symbol(t),
6363 }
6364}
6365
6366/// [`tx_type_from_symbol`] inverted: which symbol of a `cdf_len`-wide
6367/// `tx_type` CDF names `tx_type`, or `None` when that set does not hold it
6368/// (class `table-and-reader-move-together` -- the writer picks its symbol
6369/// through the reader's own map, so the two cannot drift).
6370pub(crate) fn tx_type_symbol(cdf_len: usize, tx_type: TxType) -> Option<usize> {
6371 (0..cdf_len.saturating_sub(1)).find(|&t| tx_type_from_symbol(cdf_len, t) == Some(tx_type))
6372}
6373
6374/// The remainder of a level the base and base-range syntax could not reach
6375/// (spec 5.11.40): its bit length in unary, then that many of its own bits,
6376/// most significant first — the exact inverse of [`crate::tile::write_golomb`].
6377pub(crate) fn read_golomb(dec: &mut SymbolDecoder) -> Result<u32> {
6378 // THIS CAP IS libaom's OWN, TO THE BIT -- do not "widen" it (lane-golomb2
6379 // re-read the source: `av1/decoder/decodetxb.c:22-43` counts the same
6380 // prefix and calls the 21st zero bit `AOM_CODEC_CORRUPT_FRAME`, "Invalid
6381 // length in read_golomb"; spec 5.11.40 BREAKS at `length == 20` and 5.11.39
6382 // masks the level with `0xFFFFF`, so no conformant stream carries a longer
6383 // tail). `refusal_inventory::read_golomb_reads_every_value_a_conformant_
6384 // stream_can_carry` enumerates that whole value domain.
6385 //
6386 // So this refusal never names a reader gap: it is always the SYMPTOM of an
6387 // earlier desync (class `refusal-hides-a-defect`), and every historical
6388 // instance was closed by fixing that desync -- lane-dgolomb's
6389 // `force_integer_mv`, lane-dkey's palette, lane-t900 r12's `uv_mode_grid`.
6390 // Raising the cap only trades a clean refusal for silent corruption:
6391 // lane-scaledref r1 tried it (commit ee1f980, reverted in 314ee08) and
6392 // turned `a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`
6393 // from a refusal into a frame-0 LUMA MISMATCH.
6394 let mut length = 1u32;
6395 while dec.literal(1) == 0 {
6396 length += 1;
6397 if length > 20 {
6398 return Err(unsupported("a Golomb tail longer than this decoder reads"));
6399 }
6400 }
6401 let mut x = 1u32;
6402 for _ in 1..length {
6403 x = (x << 1) | dec.literal(1);
6404 }
6405 Ok(x - 1)
6406}
6407
6408/// `decode_symbol`'s end-of-block position (spec 5.11.39): the inverse of
6409/// [`crate::tile`]'s `write_eob`.
6410fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) -> usize {
6411 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
6412 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
6413
6414 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
6415 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
6416 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
6417 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
6418 // `eob_multi_ctx`). Missing that split desynced the very first
6419 // `V_DCT`/`H_DCT` TU this decoder ever produced (lane-av1tx4 r5, caught
6420 // against a real aomdec trace).
6421 let eob_pt: &mut [u16] = match (class, coding.eob_pt_class1.as_deref_mut()) {
6422 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
6423 (_, Some(class1)) => class1,
6424 };
6425 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6426 let (range, value) = dec.debug_state();
6427 eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
6428 }
6429 let group = dec.symbol(eob_pt) + 1;
6430 if trace {
6431 eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
6432 }
6433 let bits = OFFSET_BITS[group];
6434 let mut offset = 0u32;
6435 if bits > 0 {
6436 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
6437 if trace {
6438 eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
6439 }
6440 offset = top << (bits - 1);
6441 if bits > 1 {
6442 offset |= dec.literal(bits - 1);
6443 }
6444 }
6445 GROUP_START[group] + offset as usize
6446}
6447
6448/// One transform block's levels, the inverse of [`crate::tile`]'s
6449/// `write_coeffs`, returned as a `side * side` grid in raster order, along
6450/// with the transform type that grid was coded under (`DCT_DCT` when the
6451/// block's `TxbSet` carries no `tx_type` symbol at all, e.g. 32-point and
6452/// 64-point transforms, which never code anything else).
6453///
6454/// # Errors
6455/// Returns an error if the `tx_type` symbol decodes to a value outside its
6456/// CDF's own set (a corrupt or unsupported bitstream) — every value the
6457/// intra `Tx_Type_Intra_Inv_Set2` and inter `Tx_Type_Inter_Inv_Set3` CDFs can
6458/// produce dispatches to a real inverse transform.
6459/// `Intra_Mode_To_Tx_Type` (spec 9.3): chroma's transform type is never its
6460/// own coded symbol -- `TxbSet::Chroma*`'s `tx_type` slot is always `None`
6461/// (a chroma block shares no CDF row with `Luma16`'s mode-indexed one) -- so
6462/// libaom's own `intra_mode_to_tx_type` (`blockd.h`) derives it purely from
6463/// the plane's own predicted mode instead. Every entry this table can
6464/// produce is a member of both `TX_SET_INTRA_1` and `_2` (spec 9.3's two
6465/// intra sets differ only in `IDTX`/`V_DCT`/`H_DCT`, none of which this
6466/// table ever names), so unlike the CDF-coded luma path there is no
6467/// ext-tx-set membership check to fall back from here.
6468pub(crate) fn default_intra_tx_type(mode: u8) -> TxType {
6469 use crate::intra::{
6470 D45_PRED, D67_PRED, D113_PRED, D135_PRED, D157_PRED, D203_PRED, DC_PRED, H_PRED,
6471 PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, SMOOTH_V_PRED, V_PRED,
6472 };
6473 match mode {
6474 DC_PRED | D45_PRED => TxType::DctDct,
6475 V_PRED | D113_PRED | D67_PRED | SMOOTH_V_PRED => TxType::AdstDct,
6476 H_PRED | D157_PRED | D203_PRED | SMOOTH_H_PRED => TxType::DctAdst,
6477 D135_PRED | SMOOTH_PRED | PAETH_PRED => TxType::AdstAdst,
6478 other => panic!("intra mode {other} has no Intra_Mode_To_Tx_Type entry"),
6479 }
6480}
6481
6482/// `is_smooth` (libaom `reconintra.c`): true for `SMOOTH_PRED..=SMOOTH_H_PRED`
6483/// (9..=11) — deliberately excludes `PAETH_PRED` (12), which the spec's own
6484/// `get_intra_edge_filter_type`/libaom `get_filt_type` never treat as smooth.
6485fn is_smooth_mode(mode: usize) -> bool {
6486 (crate::intra::SMOOTH_PRED as usize..=crate::intra::SMOOTH_H_PRED as usize).contains(&mode)
6487}
6488
6489/// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each.
6490/// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so
6491/// nine of them inside the base/sign loops pinned nine sets of values in the
6492/// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill
6493/// traffic). Out of line, the loop keeps its values in registers and the
6494/// trace output is character-for-character what it was.
6495#[cold]
6496#[inline(never)]
6497fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
6498 eprintln!("TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
6499}
6500
6501#[cold]
6502#[inline(never)]
6503fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
6504 eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
6505}
6506
6507#[cold]
6508#[inline(never)]
6509fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) {
6510 eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}");
6511}
6512
6513#[cold]
6514#[inline(never)]
6515fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) {
6516 let (rng, _) = dec.debug_state();
6517 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}");
6518}
6519
6520#[cold]
6521#[inline(never)]
6522fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) {
6523 let (rng, _) = dec.debug_state();
6524 eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}");
6525}
6526
6527#[cold]
6528#[inline(never)]
6529fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) {
6530 let (rng, _) = dec.debug_state();
6531 eprintln!("EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}", negative as i32);
6532}
6533
6534#[cold]
6535#[inline(never)]
6536fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) {
6537 let (rng, _) = dec.debug_state();
6538 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
6539}
6540
6541#[cold]
6542#[inline(never)]
6543fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) {
6544 let (rng, _) = dec.debug_state();
6545 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
6546}
6547
6548fn read_coeffs(
6549 dec: &mut SymbolDecoder,
6550 coding: &mut TxbTables,
6551 scan: &[u16],
6552 skip_ctx: usize,
6553 sign_ctx: usize,
6554 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
6555 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
6556 // nothing at all; `DctDct` for every luma call and every chroma call at
6557 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
6558 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
6559 default_tx_type: TxType,
6560 // `Some((w, h))` with `w != h` when this read is a superblock-level
6561 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
6562 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
6563 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
6564 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
6565 // caller's block genuinely is `side` x `side`.
6566 rect_shape: Option<(usize, usize)>,
6567) -> Result<(Grid, TxType)> {
6568 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
6569 let side = coding.side;
6570 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6571 let (range, value) = dec.debug_state();
6572 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
6573 }
6574 let dbg_txbskip = if coeff_trace_on() {
6575 coding.txb_skip[skip_ctx]
6576 } else {
6577 [0; 3]
6578 };
6579 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
6580 if coeff_trace_on() {
6581 let (rng, _) = dec.debug_state();
6582 eprintln!(
6583 "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} dcctx={sign_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng}",
6584 coding.side,
6585 all_zero as i32
6586 );
6587 }
6588 if crate::envflags::env_flag!("EC_AV1_TELL") {
6589 eprintln!(
6590 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
6591 all_zero as u8, dec.debug_bitpos(), dec.debug_state().0
6592 );
6593 }
6594 if trace {
6595 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
6596 }
6597 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6598 let (range, value) = dec.debug_state();
6599 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
6600 }
6601 if all_zero {
6602 // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the
6603 // shared zero grid instead of allocating and zeroing its own.
6604 return Ok((Grid::Zero(side * side), TxType::DctDct));
6605 }
6606 let mut grid = vec![0i32; side * side];
6607 let mut tx_type = default_tx_type;
6608 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
6609 // The CDF row's own width names its set (lane-cdffwd2: extended
6610 // past the original two-way intra split once wider `reduced_tx_set
6611 // == 0` inter sets joined the table): 17 slots (16 symbols) is
6612 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
6613 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
6614 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
6615 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
6616 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
6617 let len = tx_type_cdf.len();
6618 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
6619 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
6620 }
6621 let t = dec.symbol(tx_type_cdf);
6622 crate::census::tx_type(len, t);
6623 if coeff_trace_on() {
6624 let (rng, _) = dec.debug_state();
6625 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
6626 }
6627 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
6628 let (range, value) = dec.debug_state();
6629 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
6630 }
6631 if trace {
6632 eprintln!("TRACE tx_type value={t} len={len}");
6633 }
6634 tx_type = tx_type_from_symbol(len, t)
6635 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
6636 }
6637
6638 let class = TxClass::of(tx_type);
6639 if class != TxClass::TwoD {
6640 hit!(TX_CLASS1_HITS);
6641 hit!(RECT_CLASS1_HITS);
6642 }
6643 let eob = read_eob(dec, coding, class);
6644 if trace {
6645 eprintln!("TRACE eob value={eob}");
6646 }
6647 let ec_trace_coeff = coeff_trace_on();
6648 if ec_trace_coeff {
6649 let (rng, _) = dec.debug_state();
6650 let cls = match class { TxClass::TwoD => "2d", TxClass::Horiz => "horiz", TxClass::Vert => "vert" };
6651 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
6652 }
6653 let class_scan;
6654 let scan: &[u16] = if class == TxClass::TwoD {
6655 scan
6656 } else {
6657 class_scan = class_scan_table(side, class);
6658 &class_scan
6659 };
6660 // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per-
6661 // coefficient `pos / side`, `pos % side` was a hardware divide where a
6662 // shift and a mask say the same thing, and the level buffer fits a fixed
6663 // 32x32 frame of stack instead of a heap allocation per transform block.
6664 debug_assert!(side.is_power_of_two() && side <= 32);
6665 let sh = side.trailing_zeros();
6666 let col_mask = side - 1;
6667 // lane-coef2: padded like libaom's own level buffer (see [`neighbour`]):
6668 // `stride = side + 4` columns and four spare rows, so the widest read
6669 // `base_ctx` makes -- `(row + 4, col)` / `(row, col + 4)` with
6670 // `row, col <= side - 1` -- stays inside `(side + 4) * (side + 4)`, at
6671 // most `36 * 36`. Only `col < side`, `row < side` cells are ever written.
6672 let stride = side + 4;
6673 let mut levels_buf = [0u8; 36 * 36];
6674 let levels = &mut levels_buf[..stride * stride];
6675 // lane-coefread: the sign pass used to re-walk `scan[..eob]`, redo the
6676 // `pos >> sh` / `& mask` decomposition and load the level back out of the
6677 // padded frame just to skip the zeros. The base pass already knows both,
6678 // so it records `(scan_idx << 4) | level` for each NON-ZERO coefficient
6679 // (`scan_idx < 1024`, `level <= 15` -- both loops assert it), and the sign
6680 // pass walks that list in reverse (the base pass runs in reverse scan
6681 // order, so reversing it is forward scan order: the same coefficients, in
6682 // the same order, with the same `c` the trace prints).
6683 let mut nz_buf = [0u16; 1024];
6684 let mut nz_n = 0usize;
6685 let (base_taps, br_taps) = flat_taps(stride, class);
6686 for scan_idx in (0..eob).rev() {
6687 let pos = scan[scan_idx] as usize;
6688 let (row, col) = (pos >> sh, pos & col_mask);
6689 let idx = row * stride + col;
6690 let level = if scan_idx == eob - 1 {
6691 let ctx = eob_coeff_ctx(scan_idx, side * side);
6692 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
6693 if trace {
6694 trace_base_eob(scan_idx, pos, row, col, ctx, v);
6695 }
6696 v
6697 } else {
6698 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {
6699 if row == 0 && col == 0 {
6700 0
6701 } else {
6702 base_mag(levels, idx, &base_taps)
6703 + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6704 }
6705 } else {
6706 base_ctx(levels, stride, row, col, class, rect_shape)
6707 };
6708 let v = dec.symbol(&mut coding.base[ctx]) as i32;
6709 if ec_trace_coeff {
6710 // `pos` in libaom's column-major `coeff_idx` convention, so
6711 // the ladder lines up with instrumented `aomdec`.
6712 coeff_step_base(dec, scan_idx, col * side + row, ctx, v);
6713 }
6714 if trace {
6715 trace_base(scan_idx, pos, row, col, ctx, v);
6716 }
6717 v
6718 };
6719 let level = if level > NUM_BASE_LEVELS {
6720 let ctx = {
6721 let mag = br_mag(levels, idx, &br_taps);
6722 if row == 0 && col == 0 {
6723 mag
6724 } else {
6725 let near_origin = match class {
6726 TxClass::TwoD => row < 2 && col < 2,
6727 TxClass::Horiz => col == 0,
6728 TxClass::Vert => row == 0,
6729 };
6730 if near_origin { mag + 7 } else { mag + 14 }
6731 }
6732 };
6733 let mut level = level;
6734 let mut sent = 0;
6735 loop {
6736 let k = dec.symbol(&mut coding.br[ctx]) as i32;
6737 if ec_trace_coeff {
6738 // lane-leaf8tx r3: the `br` rung was missing from THIS
6739 // path's trace, so the cross-decoder range ladder was
6740 // blind to every base-range symbol and mis-reported the
6741 // first divergence (class [[gate-blind-to-feature]]).
6742 coeff_step_br(dec, scan_idx, col * side + row, ctx, k);
6743 }
6744 if trace {
6745 trace_br(scan_idx, pos, row, col, ctx, k);
6746 }
6747 level += k;
6748 sent += BR_STEP;
6749 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
6750 break;
6751 }
6752 }
6753 level
6754 } else {
6755 level
6756 };
6757 if ec_trace_coeff && scan_idx == eob - 1 {
6758 coeff_step_base_eob_level(dec, level);
6759 }
6760 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus
6761 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is
6762 // added in the sign pass below, straight into `grid`), so the context
6763 // frame is bytes -- the five-tap sum in [`base_ctx`]/[`br_ctx`] is a
6764 // byte gather (lane-coefbuf).
6765 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
6766 levels[idx] = level as u8;
6767 if level != 0 {
6768 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
6769 nz_n += 1;
6770 }
6771 }
6772 if ec_trace_coeff {
6773 let (rng, _) = dec.debug_state();
6774 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
6775 }
6776
6777 for &packed in nz_buf[..nz_n].iter().rev() {
6778 let c = (packed >> 4) as usize;
6779 let pos = scan[c] as usize;
6780 let level = (packed & 15) as i32;
6781 let negative = if pos == 0 {
6782 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
6783 if trace {
6784 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
6785 }
6786 v
6787 } else {
6788 dec.literal(1) == 1
6789 };
6790 if ec_trace_coeff {
6791 coeff_step_sign(dec, c, negative);
6792 }
6793 let level = if level > MAX_BR_LEVEL {
6794 let g = read_golomb(dec)?;
6795 if trace {
6796 eprintln!("TRACE golomb pos={pos} value={g}");
6797 }
6798 level + g as i32
6799 } else {
6800 level
6801 };
6802 if ec_trace_coeff {
6803 coeff_step_post_golomb(dec, c, level);
6804 }
6805 grid[pos] = if negative { -level } else { level };
6806 }
6807 Ok((Grid::Own(grid), tx_type))
6808}
6809
6810/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
6811/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
6812/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
6813/// can ever produce, since every `tx_type` this decoder's rect sets can read
6814/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
6815/// rather than guess-decode if a non-2D class ever shows up here, since
6816/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
6817/// form for those.
6818
6819fn read_coeffs_rect(
6820 dec: &mut SymbolDecoder,
6821 coding: &mut TxbTables,
6822 scan: &[u16],
6823 w: usize,
6824 h: usize,
6825 skip_ctx: usize,
6826 sign_ctx: usize,
6827 default_tx_type: TxType,
6828) -> Result<(Grid, TxType)> {
6829 let rect_trace = coeff_trace_on();
6830 let entry_rng = dec.debug_state().0;
6831 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
6832 if rect_trace {
6833 eprintln!(
6834 "EC_COEFF_STEP tag=all_zero plane=0 ctx={skip_ctx} entry={entry_rng} all_zero={} rng={}",
6835 all_zero as i32,
6836 dec.debug_state().0
6837 );
6838 }
6839 if all_zero {
6840 return Ok((Grid::Zero(w * h), TxType::DctDct));
6841 }
6842 let mut grid = vec![0i32; w * h];
6843 hit!(RECT_COEFF_TU_HITS);
6844 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
6845 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
6846 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
6847 // context offsets -- both of which now have rect forms
6848 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
6849 // The rect sets that carry no symbol at all still pass `None` here.
6850 let mut tx_type = default_tx_type;
6851 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
6852 let len = tx_type_cdf.len();
6853 let t = dec.symbol(tx_type_cdf);
6854 crate::census::tx_type(len, t);
6855 tx_type = tx_type_from_symbol(len, t)
6856 .ok_or_else(|| unsupported(format!("a tx_type symbol outside its CDF's own set: {t}")))?;
6857 if rect_trace {
6858 eprintln!("EC_COEFF_STEP tag=tx_type plane=0 rng={}", dec.debug_state().0);
6859 }
6860 }
6861 let class = TxClass::of(tx_type);
6862 if class != TxClass::TwoD {
6863 hit!(TX_CLASS1_HITS);
6864 }
6865 let eob = read_eob(dec, coding, class);
6866 if rect_trace {
6867 eprintln!("EC_COEFF_STEP tag=eob eob={eob} rng={}", dec.debug_state().0);
6868 }
6869 let class_scan;
6870 let scan: &[u16] = if class == TxClass::TwoD {
6871 scan
6872 } else {
6873 class_scan = class_scan_table_wh(w, h, class);
6874 &class_scan
6875 };
6876 // lane-coef2: a heap `vec![0i32; w * h]` per rect transform unit became a
6877 // stack frame sized to the unit -- same reasoning as [`read_coeffs`]:
6878 // `neighbour_rect` returns 0 outside `(w, h)` and every write is
6879 // `levels[pos]` with `pos < w * h`. `w` is a power of two at every AV1
6880 // rect size, so the per-coefficient `pos / w`, `pos % w` is a shift and a
6881 // mask rather than a hardware divide.
6882 let stride = w + 4;
6883 let n = stride * (h + 4);
6884 debug_assert!(w.is_power_of_two() && n <= 36 * 36);
6885 let (mut b96, mut b256, mut b768);
6886 // Byte levels, same `0..=15` bound [`read_coeffs`] states.
6887 let levels: &mut [u8] = if n <= 96 {
6888 b96 = [0u8; 96];
6889 &mut b96[..n]
6890 } else if n <= 256 {
6891 b256 = [0u8; 256];
6892 &mut b256[..n]
6893 } else {
6894 b768 = [0u8; 768];
6895 &mut b768[..n]
6896 };
6897 let wsh = w.trailing_zeros();
6898 let wmask = w - 1;
6899 // lane-coefread: the non-zero list [`read_coeffs`] documents.
6900 let mut nz_buf = [0u16; 1024];
6901 let mut nz_n = 0usize;
6902 let (base_taps, br_taps) = flat_taps(stride, class);
6903 let (wlt, wgt) = (w < h, w > h);
6904 for scan_idx in (0..eob).rev() {
6905 let pos = scan[scan_idx] as usize;
6906 let (row, col) = (pos >> wsh, pos & wmask);
6907 let idx = row * stride + col;
6908 // libaom's column-major `coeff_idx`, for ladder comparison.
6909 let _apos = col * h + row;
6910 let level = if scan_idx == eob - 1 {
6911 let ctx = eob_coeff_ctx(scan_idx, w * h);
6912 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
6913 if rect_trace {
6914 eprintln!(
6915 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
6916 dec.debug_state().0
6917 );
6918 }
6919 v
6920 } else {
6921 let ctx = if class == TxClass::TwoD {
6922 if row == 0 && col == 0 {
6923 0
6924 } else {
6925 let m = base_mag(levels, idx, &base_taps);
6926 if wlt && row < 2 {
6927 m + 11
6928 } else if wgt && col < 2 {
6929 m + 16
6930 } else {
6931 m + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
6932 }
6933 }
6934 } else {
6935 base_ctx_rect(levels, stride, w, h, row, col, class)
6936 };
6937 let v = dec.symbol(&mut coding.base[ctx]) as i32;
6938 if rect_trace {
6939 eprintln!(
6940 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
6941 dec.debug_state().0
6942 );
6943 }
6944 v
6945 };
6946 let level = if level > NUM_BASE_LEVELS {
6947 let ctx = {
6948 let mag = br_mag(levels, idx, &br_taps);
6949 if row == 0 && col == 0 {
6950 mag
6951 } else {
6952 let near_origin = match class {
6953 TxClass::TwoD => row < 2 && col < 2,
6954 TxClass::Horiz => col == 0,
6955 TxClass::Vert => row == 0,
6956 };
6957 if near_origin { mag + 7 } else { mag + 14 }
6958 }
6959 };
6960 let mut level = level;
6961 let mut sent = 0;
6962 loop {
6963 let k = dec.symbol(&mut coding.br[ctx]) as i32;
6964 if rect_trace {
6965 eprintln!(
6966 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
6967 dec.debug_state().0
6968 );
6969 }
6970 level += k;
6971 sent += BR_STEP;
6972 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
6973 break;
6974 }
6975 }
6976 level
6977 } else {
6978 level
6979 };
6980 debug_assert!(level >= 0 && level <= 15, "level {level} past the u8 frame");
6981 levels[idx] = level as u8;
6982 if level != 0 {
6983 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
6984 nz_n += 1;
6985 }
6986 if rect_trace {
6987 let (rng, _) = dec.debug_state();
6988 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={pos} level={level} rng={rng}");
6989 }
6990 }
6991 if rect_trace {
6992 let (rng, _) = dec.debug_state();
6993 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
6994 }
6995 for &packed in nz_buf[..nz_n].iter().rev() {
6996 let pos = scan[(packed >> 4) as usize] as usize;
6997 let level = (packed & 15) as i32;
6998 let negative = if pos == 0 {
6999 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
7000 } else {
7001 dec.literal(1) == 1
7002 };
7003 if rect_trace {
7004 let (rng, _) = dec.debug_state();
7005 eprintln!("EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}", u8::from(negative));
7006 }
7007 let level = if level > MAX_BR_LEVEL {
7008 let g = read_golomb(dec)?;
7009 level + g as i32
7010 } else {
7011 level
7012 };
7013 grid[pos] = if negative { -level } else { level };
7014 }
7015 // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the
7016 // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose
7017 // grids differ is a reader defect, one whose grids agree is a transform
7018 // defect.
7019 if crate::envflags::env_flag!("EC_DQCOEFF") {
7020 let nz: Vec<String> = grid
7021 .iter()
7022 .enumerate()
7023 .filter(|&(_, &v)| v != 0)
7024 .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w))
7025 .collect();
7026 eprintln!("OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}", nz.join(","));
7027 }
7028 Ok((Grid::Own(grid), tx_type))
7029}
7030
7031/// [`read_coeffs_rect`] for a CHROMA plane, carrying the monochrome gate the
7032/// [`read_plane`] family already has.
7033///
7034/// A monochrome frame has `NumPlanes == 1`, so libaom's coefficient loop
7035/// (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) never reaches a
7036/// chroma plane: no u/v coefficient symbol is coded, and consuming one moves
7037/// the arithmetic decoder off the stream for the rest of the tile. [`read_plane`]
7038/// enforces that for every strip that reads its chroma through it, but the rect
7039/// strip paths ([`decode_block_rect`], [`decode_leaf_rect`],
7040/// [`decode_block_rect4`], [`decode_rect4_16_strip`], [`decode_block_rect64`])
7041/// call `read_coeffs_rect` on planes 1/2 DIRECTLY, so each of those sites takes
7042/// this gate instead (class `reader-gate-not-on-every-path`). One un-gated
7043/// chroma read desyncs at the FIRST rect leaf of the frame and every later
7044/// symbol -- and therefore every later pixel -- is decoded from the wrong
7045/// place, without ever tripping a refusal (the desynced values stay inside
7046/// every coded alphabet).
7047fn read_chroma_coeffs_rect(
7048 dec: &mut SymbolDecoder,
7049 coding: &mut TxbTables,
7050 scan: &[u16],
7051 w: usize,
7052 h: usize,
7053 skip_ctx: usize,
7054 sign_ctx: usize,
7055 default_tx_type: TxType,
7056 fctx: &crate::decode::FrameCtx,
7057) -> Result<(Grid, TxType)> {
7058 if mono(fctx) {
7059 return Ok((Grid::Zero(w * h), TxType::DctDct));
7060 }
7061 read_coeffs_rect(dec, coding, scan, w, h, skip_ctx, sign_ctx, default_tx_type)
7062}
7063
7064/// What one coded block leaves behind for the blocks that read it as a
7065/// neighbour: whether it coded anything at all, and the sign of its DC —
7066/// [`crate::tile`]'s own private `Neighbour`.
7067#[derive(Clone, Copy, Default)]
7068struct Neighbour {
7069 /// The transform unit's cumulative coefficient level (spec `cul_level`,
7070 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
7071 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
7072 /// boolean (`level != 0`) is enough for every context this decoder read
7073 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
7074 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
7075 /// needs the actual magnitude tier of its above/left neighbours, not
7076 /// just whether they coded anything.
7077 level: u8,
7078 dc: Option<bool>,
7079}
7080
7081/// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the
7082/// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the
7083/// grid is dropped, never a panic. One `memset` per grid row instead of a
7084/// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers
7085/// is contiguous, so this writes exactly the cells the cell loop did,
7086/// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the
7087/// next row.
7088#[inline]
7089fn fill_span<T: Copy>(dst: &mut [T], start: usize, n: usize, v: T) {
7090 let end = (start + n).min(dst.len());
7091 if start < end {
7092 dst[start..end].fill(v);
7093 }
7094}
7095
7096fn neighbour_state(grid: &[i32]) -> Neighbour {
7097 // lane-coefgrid: the shared zero grid sums to zero by construction; this
7098 // sum has no early exit, so the 60% of units that code nothing used to
7099 // walk their whole grid here.
7100 if is_zero_grid(grid) {
7101 return Neighbour::default();
7102 }
7103 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
7104 Neighbour {
7105 level: cul.min(7) as u8,
7106 dc: (grid[0] != 0).then_some(grid[0] < 0),
7107 }
7108}
7109
7110/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
7111/// transform unit smaller than the block it sits in): `top`/`left` are the
7112/// above/left neighbours' magnitude tiers, each already clamped to 4.
7113pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [
7114 [1, 2, 2, 2, 3],
7115 [2, 4, 4, 4, 5],
7116 [2, 4, 4, 4, 5],
7117 [2, 4, 4, 4, 5],
7118 [3, 5, 5, 5, 6],
7119];
7120
7121/// The `skip` flag, its written-instrument bit, and the covering coded
7122/// block's origin and dims, packed into ONE 8-byte cell (lane-publish): the
7123/// four maps are written together by `Neighbours::fill_skip_grid_rect` and by
7124/// nothing else, so a block's row is one fill instead of four, and the
7125/// deblocker's `pu_edge` reads origin and dims off one cache line.
7126#[derive(Clone, Copy)]
7127struct BlkCell {
7128 skip: bool,
7129 written: bool,
7130 org: [u16; 2],
7131 dim: [u8; 2],
7132}
7133
7134/// The neighbour state a block's contexts are read from — a duplicate of
7135/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
7136/// territory this round), kept at the same two granularities the real writer
7137/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
7138/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
7139/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
7140/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
7141/// chroma transform straddling the true, odd-sized frame edge see its
7142/// neighbour's state clamped at its own subsampled edge rather than luma's.
7143#[derive(Clone)]
7144struct Neighbours {
7145 above: Vec<[Neighbour; 3]>,
7146 left: Vec<[Neighbour; 3]>,
7147 above_mode: Vec<usize>,
7148 left_mode: Vec<usize>,
7149 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
7150 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
7151 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
7152 /// luma one -- the same block can (and often does) code a different
7153 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
7154 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
7155 /// within-block neighbour finer than this grid) is luma-only -- a known,
7156 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
7157 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
7158 above_uv_mode: Vec<usize>,
7159 left_uv_mode: Vec<usize>,
7160 above_side: Vec<usize>,
7161 left_side: Vec<usize>,
7162 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
7163 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
7164 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
7165 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
7166 /// array cannot tell the second leaf's partition symbol that the first
7167 /// one was coded at 8x8.
7168 /// lane-publish2: `u8` (a block side is at most 128 px, and so is
7169 /// [`NO_NEIGHBOUR_SIDE`]) -- every block stamps these per mi.
7170 above_side_mi: Vec<u8>,
7171 left_side_mi: Vec<u8>,
7172 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
7173 /// / row, with the mi position it was written at
7174 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
7175 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
7176 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
7177 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
7178 /// leaf whose neighbour is another split group needs that group's leaf 3
7179 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
7180 /// and read only by [`decode_leaf_split4`]; the position guard makes it
7181 /// fall back to the coarse slot whenever the real neighbour was a block
7182 /// of 8x8 or larger (whose one mode is correct for every row it spans).
7183 /// lane-publish2: `(mi position, mode)` narrowed from `(usize, usize)` to
7184 /// `(u16, u8)` -- every block stamps these mi-granular maps, and 16 bytes
7185 /// per mi per side of publish traffic was pure width. `u16::MAX` is the
7186 /// "never written" sentinel (an mi index cannot reach it: AV1's largest
7187 /// frame is 65536 px = 16384 mi).
7188 sub8_mode_col: Vec<(u16, u8)>,
7189 sub8_mode_row: Vec<(u16, u8)>,
7190 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
7191 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
7192 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
7193 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
7194 /// the leaf above writes the same row slot the block to the left owns.
7195 uv_mode_col: Vec<(u16, u8)>,
7196 uv_mode_row: Vec<(u16, u8)>,
7197 /// Every mi cell's own `uv_mode`, the mi grid libaom's
7198 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
7199 /// blockd.h). lane-t900 r12: the one-slot-per-column
7200 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
7201 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
7202 /// overwrote the row the pair's chroma-ref half then wanted to read --
7203 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
7204 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
7205 uv_mode_grid: Vec<u8>,
7206 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
7207 /// every other band here).
7208 uv_grid_cols: usize,
7209 /// Whether the block above/left of this column/row was coded `skip` --
7210 /// an inter frame's own `skip` context (spec `SkipContext`), which the
7211 /// key-frame writer never tracks (its skip context is always zero); a
7212 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
7213 /// `left_skip`.
7214 above_skip: Vec<bool>,
7215 left_skip: Vec<bool>,
7216 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
7217 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
7218 /// pixels last written over each unit by `set_txfm_ctxs`/
7219 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
7220 /// symbol reads its context from (lane-txselect, spec 5.11.17).
7221 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
7222 /// array is exactly libaom's per-superblock-row reset, since each mi row
7223 /// is only ever visited inside one superblock row.
7224 above_txfm: Vec<u8>,
7225 left_txfm: Vec<u8>,
7226 /// Whether the block above/left of this column/row coded `skip_mode`
7227 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
7228 /// lane-av1comp round 14.
7229 above_skip_mode: Vec<bool>,
7230 left_skip_mode: Vec<bool>,
7231 /// Whether the block above/left was coded inter -- the `is_inter`
7232 /// context (spec `av1_get_intra_inter_context`), a duplicate of
7233 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
7234 above_inter: Vec<bool>,
7235 left_inter: Vec<bool>,
7236 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
7237 /// alphabet) the block above/left of this column/row coded, or `-1` for
7238 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
7239 /// functions (`mvstack::ref_ctx` family) need the real reference, not
7240 /// just "was it inter" (lane-av1refs: every inter block used to be
7241 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
7242 /// enough).
7243 above_ref: Vec<i8>,
7244 left_ref: Vec<i8>,
7245 /// The block above/left's *second* reference frame when it was coded
7246 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
7247 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
7248 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
7249 /// `i8`, once a compound `read_ref_frames` lands.
7250 /// lane-publish2 audit: the "always `None` today" note this doc used to
7251 /// carry is long stale -- compound blocks do occur, and
7252 /// [`Self::record_compound_ctx_rect_mi`] stamps the real second reference
7253 /// over their span right after [`Self::record_inter_rect_mi`]'s reset.
7254 /// The array IS read: `single_ref_p*`/`comp_ref` contexts and every
7255 /// [`crate::mvstack::NeighbourRef`] construction (class
7256 /// [[branch-dropped-as-unreachable]] -- the note, not the code, was wrong).
7257 above_ref1: Vec<Option<i8>>,
7258 left_ref1: Vec<Option<i8>>,
7259 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
7260 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
7261 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
7262 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
7263 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
7264 above_comp_group_idx: Vec<u8>,
7265 left_comp_group_idx: Vec<u8>,
7266 above_compound_idx: Vec<u8>,
7267 left_compound_idx: Vec<u8>,
7268 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
7269 /// `3` = "no info": an intra neighbour or the frame's own border) of the
7270 /// block above/left of this column/row -- spec
7271 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
7272 above_filter: Vec<[u8; 2]>,
7273 left_filter: Vec<[u8; 2]>,
7274 mi_cols: usize,
7275 mi_rows: usize,
7276 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
7277 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
7278 /// 7.15) never filters an 8x8 luma block whose covering coded block read
7279 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
7280 /// grain [`Self::record_mi`] already writes at), read back at 8x8
7281 /// granularity by [`apply_cdef`] since `skip` is constant across every
7282 /// mi cell one coded block covers.
7283 /// The four per-mi maps [`Neighbours::blk_grid`] packs, in one cell.
7284 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
7285 /// the `skip` bit at this mi cell during this frame. A fresh
7286 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
7287 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
7288 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
7289 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
7290 /// unobservable from the pixels alone. Counted by
7291 /// [`cdef_unwritten_skip_units`].
7292 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
7293 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
7294 /// which re-enables the loop filter at a prediction boundary between two
7295 /// skipped inter blocks (lane-mergefix r4). Written by
7296 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
7297 /// Per-4x4-mi `(width, height)` in mi units of the coded block covering
7298 /// that cell -- the other half of `pu_edge`: libaom tests the edge
7299 /// coordinate against the block's size in the FILTERED plane's own
7300 /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b).
7301 blk_grid: Vec<BlkCell>,
7302 skip_grid_cols_mi: usize,
7303 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
7304 /// never splits a coded block's transform below its own size (round 2:
7305 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
7306 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
7307 /// edge-length lookup (`apply_deblock`).
7308 tx_grid: Vec<u8>,
7309 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
7310 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
7311 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
7312 tx_h_grid: Vec<u8>,
7313 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
7314 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
7315 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
7316 /// does NOT follow luma's `tx_depth` split, so deriving it as
7317 /// `tx_grid / 2` invented chroma transform edges the deblocker then
7318 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
7319 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
7320 /// every caller routes through.
7321 uv_tx_grid: Vec<u8>,
7322 uv_tx_h_grid: Vec<u8>,
7323 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
7324 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
7325 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
7326 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
7327 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
7328 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
7329 /// reference onto `LAST_FRAME`'s own delta).
7330 ref_grid: Vec<i8>,
7331 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
7332 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
7333 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
7334 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
7335 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
7336 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
7337 /// to know which mode produced the value.
7338 delta_lf_grid: Vec<[i8; 4]>,
7339 /// The block above/left's own palette-Y size (0 = not a palette block)
7340 /// and its base colours -- `av1_get_palette_mode_ctx`/
7341 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
7342 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
7343 above_palette_size: Vec<u8>,
7344 left_palette_size: Vec<u8>,
7345 above_palette_colors: Vec<[u16; 8]>,
7346 left_palette_colors: Vec<[u16; 8]>,
7347 /// As the four fields above, for the neighbour's own chroma (U-channel
7348 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
7349 /// palette size/colours (lane-palette2 r1).
7350 above_palette_uv_size: Vec<u8>,
7351 left_palette_uv_size: Vec<u8>,
7352 above_palette_uv_colors: Vec<[u16; 8]>,
7353 left_palette_uv_colors: Vec<[u16; 8]>,
7354 /// This tile's own top-left corner, in 4x4 mode-info units (spec
7355 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
7356 /// neighbour" check compares against this instead of literal `0`, since a
7357 /// block at the tile's own top/left edge has no usable neighbour even
7358 /// though a decoded block sits there in the picture (spec `decode_tile`'s
7359 /// per-tile `clear_above_context`/`left_available`/`up_available`).
7360 /// `0` for a single-tile frame, matching every existing caller exactly.
7361 tile_row0_mi: usize,
7362 tile_col0_mi: usize,
7363}
7364
7365#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7366impl Neighbours {
7367 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
7368 /// true (unpadded) size in 4x4 mode-info units.
7369 fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize, fctx: &crate::decode::FrameCtx) -> Self {
7370 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
7371 // neighbour state over the whole 64-row extent, past the frame's last
7372 // mi row (mi_rows 198, block rows 192..208). libaom's own context
7373 // buffers are superblock-aligned for exactly that reason
7374 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
7375 // side arrays to a superblock multiple and leave those cells unread --
7376 // every availability check uses the true `mi_rows`/`mi_cols` below.
7377 let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
7378 let (cols, rows) = (
7379 cols.next_multiple_of(sb_sub),
7380 rows.next_multiple_of(sb_sub),
7381 );
7382 Self {
7383 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
7384 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
7385 above_mode: vec![DC_PRED; cols],
7386 left_mode: vec![DC_PRED; rows],
7387 above_uv_mode: vec![DC_PRED; cols],
7388 left_uv_mode: vec![DC_PRED; rows],
7389 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
7390 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
7391 above_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; cols * (SUB / MI)],
7392 left_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; rows * (SUB / MI)],
7393 sub8_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
7394 sub8_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
7395 uv_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
7396 uv_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
7397 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
7398 uv_grid_cols: cols * (SUB / MI),
7399 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
7400 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
7401 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
7402 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
7403 // 16x16 block beside it, which a SUB-grid slot cannot name
7404 // (class context-read-from-one-cell).
7405 above_skip: vec![false; cols * (SUB / MI)],
7406 left_skip: vec![false; rows * (SUB / MI)],
7407 above_skip_mode: vec![false; cols * (SUB / MI)],
7408 left_skip_mode: vec![false; rows * (SUB / MI)],
7409 above_inter: vec![false; cols * (SUB / MI)],
7410 left_inter: vec![false; rows * (SUB / MI)],
7411 above_ref: vec![-1; cols * (SUB / MI)],
7412 left_ref: vec![-1; rows * (SUB / MI)],
7413 above_ref1: vec![None; cols * (SUB / MI)],
7414 left_ref1: vec![None; rows * (SUB / MI)],
7415 above_comp_group_idx: vec![0; cols * (SUB / MI)],
7416 left_comp_group_idx: vec![0; rows * (SUB / MI)],
7417 above_compound_idx: vec![0; cols * (SUB / MI)],
7418 left_compound_idx: vec![0; rows * (SUB / MI)],
7419 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
7420 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
7421 mi_cols,
7422 mi_rows,
7423 blk_grid: vec![
7424 BlkCell { skip: false, written: false, org: [0; 2], dim: [1; 2] };
7425 cols * (SUB / MI) * rows * (SUB / MI)
7426 ],
7427 skip_grid_cols_mi: cols * (SUB / MI),
7428 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
7429 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
7430 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
7431 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
7432 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
7433 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
7434 above_palette_size: vec![0; cols * (SUB / MI)],
7435 left_palette_size: vec![0; rows * (SUB / MI)],
7436 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
7437 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
7438 above_palette_uv_size: vec![0; cols * (SUB / MI)],
7439 left_palette_uv_size: vec![0; rows * (SUB / MI)],
7440 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
7441 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
7442 tile_row0_mi: 0,
7443 tile_col0_mi: 0,
7444 }
7445 }
7446
7447 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
7448 /// tile's own column span (`col1_mi` exclusive), plus recording
7449 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
7450 /// availability check below. Left context resets every superblock row
7451 /// regardless of tile ([`Self::start_row`], already called once per SB
7452 /// row by every caller) so it needs no tile-specific reset here.
7453 fn start_tile(&mut self, row0_mi: usize, col0_mi: usize, col1_mi: usize, fctx: &crate::decode::FrameCtx) {
7454 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
7455 // are tile-relative, same as every other neighbour lookup here.
7456 fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
7457 self.tile_row0_mi = row0_mi;
7458 self.tile_col0_mi = col0_mi;
7459 let end = col1_mi.min(self.above.len());
7460 for i in col0_mi.min(end)..end {
7461 self.above[i] = Default::default();
7462 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE as u8;
7463 }
7464 let (sc0, sc1) = (
7465 col0_mi / (SUB / MI),
7466 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
7467 );
7468 for i in sc0.min(sc1)..sc1 {
7469 self.above_mode[i] = DC_PRED;
7470 self.above_side[i] = NO_NEIGHBOUR_SIDE;
7471 }
7472 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
7473 // the tile's own mi column span directly.
7474 let mend = col1_mi.min(self.above_skip.len());
7475 for i in col0_mi.min(mend)..mend {
7476 self.above_skip[i] = false;
7477 self.above_skip_mode[i] = false;
7478 self.above_inter[i] = false;
7479 self.above_ref[i] = -1;
7480 self.above_ref1[i] = None;
7481 self.above_comp_group_idx[i] = 0;
7482 self.above_compound_idx[i] = 0;
7483 self.above_filter[i] = [3u8; 2];
7484 }
7485 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
7486 // stale `(row, mode)` from the tile to the LEFT names an mi row this
7487 // tile's first block would read as its own above neighbour.
7488 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
7489 for i in col0_mi.min(mcol_end)..mcol_end {
7490 self.sub8_mode_col[i] = (u16::MAX, 0);
7491 self.uv_mode_col[i] = (u16::MAX, 0);
7492 }
7493 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
7494 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
7495 // not zero) -- without it a second tile column reads the first one's
7496 // resolved transform sizes as its own above context.
7497 let tend = col1_mi.min(self.above_txfm.len());
7498 for i in col0_mi.min(tend)..tend {
7499 self.above_txfm[i] = TXFM_CTX_INIT;
7500 }
7501 }
7502
7503 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
7504 /// for a non-palette block, clearing any stale neighbour state) into every
7505 /// [`SUB`]-grid cell it covers on both the above and left edges --
7506 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
7507 /// call sites are all square blocks).
7508 fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
7509 self.record_palette_y_rect((at.0 * (SUB / MI), at.1 * (SUB / MI)), side, side, size, colors);
7510 }
7511
7512 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
7513 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
7514 /// [`Self::record`]): a true rect strip's above/left neighbour spans
7515 /// differ.
7516 fn record_palette_y_rect(
7517 &mut self,
7518 mi: (usize, usize),
7519 w: usize,
7520 h: usize,
7521 size: usize,
7522 colors: [u16; 8],
7523 ) {
7524 let (r, c) = mi;
7525 if crate::envflags::env_flag!("EC_PALPUB") {
7526 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
7527 }
7528 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
7529 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
7530 // cell immediately left of the block, not its 16px [`SUB`] cell. The
7531 // old SUB grid let a 16x8 strip pair share one slot, so the second
7532 // strip of mi(0,8) read the FIRST strip's palette size and the colour
7533 // cache came out one entry short (class [[context-read-from-one-cell]]).
7534 for cell in 0..(w / MI).max(1) {
7535 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
7536 *e = size as u8;
7537 // lane-publish2: spec 5.11.46 `get_palette_cache` reads a
7538 // neighbour's colours only where its palette size > 0, so a
7539 // non-palette block need not stamp 16 bytes of zeroes here.
7540 if size > 0 {
7541 self.above_palette_colors[c + cell] = colors;
7542 }
7543 }
7544 }
7545 for cell in 0..(h / MI).max(1) {
7546 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
7547 *e = size as u8;
7548 if size > 0 {
7549 self.left_palette_colors[r + cell] = colors;
7550 }
7551 }
7552 }
7553 }
7554
7555 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
7556 /// neighbours that are themselves a palette-Y block, plus
7557 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
7558 /// cache (pred_common.c:73).
7559 ///
7560 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
7561 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
7562 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
7563 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
7564 /// the ctx too made every superblock in the frame's second SB row read
7565 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
7566 /// palette block decoded as "no palette" and the tile desynced from
7567 /// there (class [[cdf-row-held-constant]]).
7568 fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
7569 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
7570 }
7571
7572 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
7573 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
7574 /// drops the above neighbour on a 64-px superblock boundary
7575 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
7576 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
7577 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
7578 /// every strip in an SB's top cell row, which libaom does not do.
7579 fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
7580 let (r, c) = mi;
7581 let above_ok = r % 16 != 0;
7582 // `xd->above_mbmi` exists for every row but the tile's own first.
7583 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
7584 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
7585 (usize::from(self.above_palette_size[c]), self.above_palette_colors[c])
7586 } else {
7587 (0, [0u16; 8])
7588 };
7589 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
7590 // is NULL whenever the block sits at its TILE's own left column
7591 // (`left_available`), not the frame's -- without this guard a second
7592 // tile column reads the previous tile's palette colours into its cache
7593 // and its `palette_y_mode` ctx.
7594 let left_ok = c > self.tile_col0_mi;
7595 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
7596 (usize::from(self.left_palette_size[r]), self.left_palette_colors[r])
7597 } else {
7598 (0, [0u16; 8])
7599 };
7600 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
7601 let mut cache = Vec::with_capacity(16);
7602 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
7603 if cache.last() != Some(&v) {
7604 cache.push(v);
7605 }
7606 };
7607 let (mut ai, mut li) = (0usize, 0usize);
7608 while ai < above_n && li < left_n {
7609 let (va, vl) = (above_colors[ai], left_colors[li]);
7610 if vl < va {
7611 push_dedup(&mut cache, vl);
7612 li += 1;
7613 } else {
7614 push_dedup(&mut cache, va);
7615 ai += 1;
7616 if vl == va {
7617 li += 1;
7618 }
7619 }
7620 }
7621 while ai < above_n {
7622 push_dedup(&mut cache, above_colors[ai]);
7623 ai += 1;
7624 }
7625 while li < left_n {
7626 push_dedup(&mut cache, left_colors[li]);
7627 li += 1;
7628 }
7629 (ctx, cache)
7630 }
7631
7632 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
7633 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
7634 /// same way (lane-palette2 r1).
7635 fn record_palette_uv(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
7636 self.record_palette_uv_rect(
7637 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
7638 side,
7639 side,
7640 size,
7641 colors,
7642 );
7643 }
7644
7645 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
7646 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
7647 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
7648 /// luma resolution regardless of which plane the recorded state is for).
7649 fn record_palette_uv_rect(
7650 &mut self,
7651 mi: (usize, usize),
7652 w: usize,
7653 h: usize,
7654 size: usize,
7655 colors: [u16; 8],
7656 ) {
7657 let (r, c) = mi;
7658 // mi granularity, see [`Self::record_palette_y_rect`].
7659 for cell in 0..(w / MI).max(1) {
7660 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
7661 *e = size as u8;
7662 if size > 0 {
7663 self.above_palette_uv_colors[c + cell] = colors;
7664 }
7665 }
7666 }
7667 for cell in 0..(h / MI).max(1) {
7668 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
7669 *e = size as u8;
7670 if size > 0 {
7671 self.left_palette_uv_colors[r + cell] = colors;
7672 }
7673 }
7674 }
7675 }
7676
7677 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
7678 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
7679 /// no neighbour lookup at all (it is this block's own just-decided Y
7680 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
7681 /// so only the cache is wanted here.
7682 fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
7683 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
7684 }
7685
7686 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
7687 /// [`Self::palette_ctx_and_cache_mi`].
7688 fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
7689 let (r, c) = mi;
7690 let above_ok = r % 16 != 0;
7691 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
7692 (usize::from(self.above_palette_uv_size[c]), self.above_palette_uv_colors[c])
7693 } else {
7694 (0, [0u16; 8])
7695 };
7696 // Same tile-relative left availability as the luma cache above.
7697 let left_ok = c > self.tile_col0_mi;
7698 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
7699 (usize::from(self.left_palette_uv_size[r]), self.left_palette_uv_colors[r])
7700 } else {
7701 (0, [0u16; 8])
7702 };
7703 let mut cache = Vec::with_capacity(16);
7704 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
7705 if cache.last() != Some(&v) {
7706 cache.push(v);
7707 }
7708 };
7709 let (mut ai, mut li) = (0usize, 0usize);
7710 while ai < above_n && li < left_n {
7711 let (va, vl) = (above_colors[ai], left_colors[li]);
7712 if vl < va {
7713 push_dedup(&mut cache, vl);
7714 li += 1;
7715 } else {
7716 push_dedup(&mut cache, va);
7717 ai += 1;
7718 if vl == va {
7719 li += 1;
7720 }
7721 }
7722 }
7723 while ai < above_n {
7724 push_dedup(&mut cache, above_colors[ai]);
7725 ai += 1;
7726 }
7727 while li < left_n {
7728 push_dedup(&mut cache, left_colors[li]);
7729 li += 1;
7730 }
7731 cache
7732 }
7733
7734 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
7735 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
7736 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
7737 /// units as [`Self::fill_skip_grid`].
7738 fn fill_lf_grid(&mut self, at_mi: (usize, usize), side_mi: usize, tx_px: u8, ref_frame: i8, fctx: &crate::decode::FrameCtx) {
7739 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
7740 }
7741
7742 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
7743 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
7744 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
7745 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
7746 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
7747 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
7748 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
7749 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
7750 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
7751 /// block's published transform extent to its own size is exactly that
7752 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
7753 /// that needs it is the 128 root, whose chroma extent (64) is the one
7754 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
7755 /// never suppressed (libaom's `is_inter_block` term), so this is called
7756 /// only from the skipped-inter branch.
7757 fn suppress_internal_lf_edges(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize) {
7758 let (mi_r, mi_c) = at_mi;
7759 let (uv_w, uv_h) = ((w_mi * MI / 2).max(4) as u8, (h_mi * MI / 2).max(4) as u8);
7760 for rr in 0..h_mi {
7761 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7762 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w);
7763 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h);
7764 }
7765 }
7766
7767 fn fill_lf_grid_rect(
7768 &mut self,
7769 at_mi: (usize, usize),
7770 w_mi: usize,
7771 h_mi: usize,
7772 tx_px: u8,
7773 tx_h_px: u8,
7774 ref_frame: i8, fctx: &crate::decode::FrameCtx,
7775 ) {
7776 let (mi_r, mi_c) = at_mi;
7777 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
7778 // half its luma one (min 4 px, the smallest transform), capped at
7779 // TX_32X32 -- independent of this block's luma `tx_depth`.
7780 let uv_tx_w = ((w_mi * MI / 2).max(4).min(32)) as u8;
7781 let uv_tx_h = ((h_mi * MI / 2).max(4).min(32)) as u8;
7782 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
7783 eprintln!("EC_LFGRID mi_row={mi_r} mi_col={mi_c} w_mi={w_mi} h_mi={h_mi} tx_px={tx_px} tx_h_px={tx_h_px}");
7784 }
7785 crate::census::tx(tx_px, tx_h_px);
7786 let cur = fctx.current_delta_lf.with(|c| c.get());
7787 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
7788 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
7789 } else {
7790 [cur[0].clamp(-63, 63) as i8; 4]
7791 };
7792 for rr in 0..h_mi {
7793 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7794 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
7795 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
7796 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w);
7797 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h);
7798 fill_span(&mut self.ref_grid, start, w_mi, ref_frame);
7799 fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot);
7800 }
7801 if fctx.intra_only.with(std::cell::Cell::get) {
7802 // libaom's `parse_decode_block` runs `set_txfm_ctxs(mbmi->tx_size,
7803 // xd->width, xd->height, mbmi->skip_txfm && is_inter_block(mbmi),
7804 // xd)` for EVERY block, an intra-only frame's included, and
7805 // `get_tx_size_context` / `txfm_partition_context` read those two
7806 // `TXFM_CONTEXT` bands. This grid carries the same transform size
7807 // over the same footprint, so the publish is this write: the
7808 // `skip && is_inter` term is 0 for every intra-only block that is
7809 // not an intrabc one, and the bodies that can code an intrabc
7810 // block publish their own (the term is then the BLOCK size, a value
7811 // this grid cannot express -- see `decode_block`/`decode_leaf8`).
7812 // Inter frames publish at their own sites and are excluded here
7813 // because their skipped-block term needs the block size too.
7814 txfm_partition_update_rect(
7815 self,
7816 at_mi,
7817 (tx_px as usize, tx_h_px as usize),
7818 (w_mi * MI, h_mi * MI),
7819 );
7820 // libaom `is_inter_block` counts an INTRABC block (`blockd.h:373`),
7821 // so `get_tx_size_context` reads an intrabc NEIGHBOUR's block size
7822 // instead of its transform band. Every block stamps its own cells
7823 // here; the intrabc bodies re-stamp theirs `true` afterwards
7824 // (`record_intrabc_inter_bands`).
7825 for i in 0..w_mi {
7826 if let Some(cell) = self.above_inter.get_mut(mi_c + i) {
7827 *cell = false;
7828 }
7829 }
7830 for i in 0..h_mi {
7831 if let Some(cell) = self.left_inter.get_mut(mi_r + i) {
7832 *cell = false;
7833 }
7834 }
7835 }
7836 // lane-av1-intrabc r4: publish this coded block's own mi footprint
7837 // into the intrabc MV grid's block-COVERAGE map -- every coded block,
7838 // not just the intrabc ones. A later intrabc block's DV predictor is
7839 // built by libaom's own row/col scans over `xd->mi[]`, which holds an
7840 // `MB_MODE_INFO` for EVERY block and steps by
7841 // `mi_size_wide/height[candidate->bsize]`; without this footprint a
7842 // non-intrabc neighbour reads as uncovered and the scan advances it
7843 // by one cell instead of by its real width.
7844 fctx.intrabc_mi_grid.with(|g| {
7845 if let Some((grid, _, _)) = g.borrow_mut().as_mut() {
7846 grid.cover_rect(mi_r, mi_c, w_mi, h_mi);
7847 }
7848 });
7849 }
7850
7851 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
7852 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
7853 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
7854 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
7855 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
7856 /// dims from the LEAF span and so invented chroma transform edges the
7857 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
7858 /// are already correct from the block's own fill over the same span.
7859 fn fill_lf_grid_leaf_luma(
7860 &mut self,
7861 at_mi: (usize, usize),
7862 w_mi: usize,
7863 h_mi: usize,
7864 tx_px: u8,
7865 tx_h_px: u8,
7866 ) {
7867 let (mi_r, mi_c) = at_mi;
7868 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
7869 eprintln!("EC_LFLEAF mi_row={mi_r} mi_col={mi_c} w_mi={w_mi} h_mi={h_mi} tx_px={tx_px} tx_h_px={tx_h_px}");
7870 }
7871 for rr in 0..h_mi {
7872 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7873 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
7874 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
7875 }
7876 }
7877
7878 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
7879 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
7880 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
7881 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
7882 fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
7883 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
7884 }
7885
7886 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
7887 fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
7888 let (mi_r, mi_c) = at_mi;
7889 if skip && w_mi != h_mi {
7890 hit!(RECT_SKIP_BAND_HITS);
7891 }
7892 // lane-census: an INTRA frame's blocks never reach the inter
7893 // publisher, and this one is what every coded block writes.
7894 crate::census::block_intra_frame(w_mi, h_mi, skip);
7895 for rr in 0..h_mi {
7896 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
7897 fill_span(
7898 &mut self.blk_grid,
7899 start,
7900 w_mi,
7901 BlkCell {
7902 skip,
7903 written: true,
7904 org: [mi_r as u16, mi_c as u16],
7905 dim: [w_mi as u8, h_mi as u8],
7906 },
7907 );
7908 }
7909 }
7910
7911 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
7912 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
7913 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
7914 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
7915 /// straddle the region with a mix of skip/non-skip blocks).
7916 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
7917 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
7918 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
7919 /// filtered edge's two sides are each exactly one coded block wide.
7920 fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
7921 self.blk_grid
7922 .get(mi_r * self.skip_grid_cols_mi + mi_c)
7923 .is_some_and(|c| c.skip)
7924 }
7925
7926 /// The `skip_txfm` context of a block whose top-left mi cell is
7927 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
7928 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
7929 /// with an absent neighbour contributing 0. The mi grid is per tile, so
7930 /// row/column 0 is a tile edge and has no neighbour on that axis.
7931 fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
7932 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
7933 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
7934 }
7935
7936 fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
7937 (0..2).all(|rr| {
7938 (0..2).all(|cc| {
7939 self.blk_grid
7940 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
7941 .is_some_and(|c| c.skip)
7942 })
7943 })
7944 }
7945
7946 fn start_row(&mut self) {
7947 self.left.iter_mut().for_each(|l| *l = Default::default());
7948 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
7949 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
7950 self.left_side.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE);
7951 self.left_side_mi.iter_mut().for_each(|s| *s = NO_NEIGHBOUR_SIDE as u8);
7952 self.left_skip.iter_mut().for_each(|s| *s = false);
7953 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
7954 self.left_inter.iter_mut().for_each(|i| *i = false);
7955 self.left_ref.iter_mut().for_each(|r| *r = -1);
7956 self.left_ref1.iter_mut().for_each(|r| *r = None);
7957 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
7958 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
7959 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
7960 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
7961 // context (a tile/SB-row boundary has no left neighbour).
7962 self.sub8_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
7963 self.uv_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
7964 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
7965 // are per-mi maps like every other one here, so they reset with the
7966 // row too -- the left guard above is what actually stops a cross-tile
7967 // read, this keeps a stale colour out of the arrays at all.
7968 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
7969 self.left_palette_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
7970 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
7971 self.left_palette_uv_colors.iter_mut().for_each(|c| *c = [0u16; 8]);
7972 // lane-mergefix r2: `av1_zero_left_context` memsets
7973 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
7974 // every superblock row of every tile -- the var-tx left context does
7975 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
7976 // previous tile column's last block otherwise).
7977 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
7978 }
7979
7980 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
7981 /// block that reads it as a neighbour -- [`crate::tile`]'s
7982 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
7983 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
7984 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
7985 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
7986 /// the real value, not just `is_inter`).
7987 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
7988 fn record_inter(
7989 &mut self,
7990 at: (usize, usize),
7991 side: usize,
7992 skip: bool,
7993 is_inter: bool,
7994 ref_frame: i8,
7995 filter: [u8; 2],
7996 skip_mode: bool,
7997 ) {
7998 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
7999 }
8000
8001 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
8002 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
8003 /// r1: a true rectangular strip's above-context span (its own width) and
8004 /// left-context span (its own height) differ, unlike every caller before
8005 /// this round (class neighbour-votes-all-its-fields).
8006 #[allow(clippy::too_many_arguments)]
8007 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
8008 fn record_inter_rect(
8009 &mut self,
8010 at: (usize, usize),
8011 w_sub: usize,
8012 h_sub: usize,
8013 skip: bool,
8014 is_inter: bool,
8015 ref_frame: i8,
8016 filter: [u8; 2],
8017 skip_mode: bool,
8018 ) {
8019 let (r, c) = at;
8020 self.record_inter_rect_mi(
8021 (r * (SUB / MI), c * (SUB / MI)),
8022 w_sub / MI,
8023 h_sub / MI,
8024 skip,
8025 is_inter,
8026 ref_frame,
8027 filter,
8028 skip_mode,
8029 );
8030 }
8031
8032 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
8033 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
8034 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
8035 /// routes through the wrapper above.
8036 #[allow(clippy::too_many_arguments)]
8037 fn record_inter_rect_mi(
8038 &mut self,
8039 at_mi: (usize, usize),
8040 w_mi: usize,
8041 h_mi: usize,
8042 skip: bool,
8043 is_inter: bool,
8044 ref_frame: i8,
8045 filter: [u8; 2],
8046 skip_mode: bool,
8047 ) {
8048 let (r, c) = at_mi;
8049 crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip);
8050 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
8051 // writes for a whole block class): an INTER block left the luma mode
8052 // map untouched, so a later intra block's `get_intra_edge_filter_type`
8053 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
8054 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
8055 // block in that pixel row -- the directional edge filter then ran at
8056 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
8057 // which for an inter block is an INTER mode (>= NEARESTMV) and is
8058 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
8059 // already stamped it).
8060 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
8061 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
8062 // uv map must read DC_PRED over an inter block's cells too.
8063 if is_inter {
8064 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
8065 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
8066 }
8067 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
8068 self.above_skip[c..c + w_mi].fill(skip);
8069 self.above_skip_mode[c..c + w_mi].fill(skip_mode);
8070 self.above_inter[c..c + w_mi].fill(is_inter);
8071 self.above_ref[c..c + w_mi].fill(ref_frame);
8072 // The single-ref default: `record_compound_ctx_rect_mi` overwrites
8073 // this with the block's real second reference for a compound block,
8074 // called right after this one (lane-publish2 audit).
8075 self.above_ref1[c..c + w_mi].fill(None);
8076 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
8077 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
8078 // as `3`/`1` even though this block has no second reference.
8079 // `record_compound_ctx` overwrites this with the real bit for an
8080 // actual compound block's cells, called right after this one.
8081 self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 });
8082 self.above_compound_idx[c..c + w_mi].fill(u8::from(altref));
8083 self.above_filter[c..c + w_mi].fill(filter);
8084 self.left_skip[r..r + h_mi].fill(skip);
8085 self.left_skip_mode[r..r + h_mi].fill(skip_mode);
8086 self.left_inter[r..r + h_mi].fill(is_inter);
8087 self.left_ref[r..r + h_mi].fill(ref_frame);
8088 self.left_ref1[r..r + h_mi].fill(None);
8089 self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 });
8090 self.left_compound_idx[r..r + h_mi].fill(u8::from(altref));
8091 self.left_filter[r..r + h_mi].fill(filter);
8092 }
8093
8094 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
8095 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
8096 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
8097 /// `get_comp_index_context`) -- called right after `record_inter` for
8098 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
8099 /// stamps `above_ref1`/`left_ref1` with the block's real second
8100 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
8101 /// this is the one caller that actually knows it) -- so the next block's
8102 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
8103 /// neighbour instead of `record_inter`'s single-ref default.
8104 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
8105 fn record_compound_ctx(
8106 &mut self,
8107 at: (usize, usize),
8108 side: usize,
8109 ref1: i8,
8110 comp_group_idx: u8,
8111 compound_idx: u8,
8112 ) {
8113 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
8114 }
8115
8116 /// [`Self::record_compound_ctx`] with independent above/left extents,
8117 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
8118 #[allow(clippy::too_many_arguments)]
8119 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
8120 fn record_compound_ctx_rect(
8121 &mut self,
8122 at: (usize, usize),
8123 w_sub: usize,
8124 h_sub: usize,
8125 ref1: i8,
8126 comp_group_idx: u8,
8127 compound_idx: u8,
8128 ) {
8129 let (r, c) = at;
8130 self.record_compound_ctx_rect_mi(
8131 (r * (SUB / MI), c * (SUB / MI)),
8132 w_sub / MI,
8133 h_sub / MI,
8134 ref1,
8135 comp_group_idx,
8136 compound_idx,
8137 );
8138 }
8139
8140 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
8141 /// [`Self::record_inter_rect_mi`]).
8142 fn record_compound_ctx_rect_mi(
8143 &mut self,
8144 at_mi: (usize, usize),
8145 w_mi: usize,
8146 h_mi: usize,
8147 ref1: i8,
8148 comp_group_idx: u8,
8149 compound_idx: u8,
8150 ) {
8151 let (r, c) = at_mi;
8152 crate::census::compound();
8153 for cell in 0..w_mi {
8154 self.above_ref1[c + cell] = Some(ref1);
8155 self.above_comp_group_idx[c + cell] = comp_group_idx;
8156 self.above_compound_idx[c + cell] = compound_idx;
8157 }
8158 for cell in 0..h_mi {
8159 self.left_ref1[r + cell] = Some(ref1);
8160 self.left_comp_group_idx[r + cell] = comp_group_idx;
8161 self.left_compound_idx[r + cell] = compound_idx;
8162 }
8163 }
8164
8165 /// The context of a block's partition symbol: delegates to the mi-precise
8166 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
8167 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
8168 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
8169 /// only touches the finer mi arrays -- leaves them stale for the *next*
8170 /// sibling's own partition symbol.
8171 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
8172 let (r, c) = at;
8173 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
8174 }
8175
8176 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
8177 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
8178 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
8179 /// than the enclosing 16x16 slot's stale, shared state.
8180 fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
8181 2 * usize::from(usize::from(self.left_side_mi[mi_r]) * 2 <= side)
8182 + usize::from(usize::from(self.above_side_mi[mi_c]) * 2 <= side)
8183 }
8184
8185 /// The gathered coded/DC-sign state of the blocks above and to the left
8186 /// of a block `side` samples across, per plane.
8187 fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
8188 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
8189 }
8190
8191 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
8192 /// units, for the same reason [`Self::record_mi`] does.
8193 fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
8194 let side_mi = side / MI;
8195 // One pass over the cells accumulating all three planes, not one pass
8196 // per plane: the three planes of a cell live in the same
8197 // `[Neighbour; 3]` (6 bytes), so the per-plane form loaded the same
8198 // cache lines three times (lane-publish).
8199 let mut out = [(false, false, 0i32); 3];
8200 for cell in 0..side_mi {
8201 let above = &self.above[mi_c + cell];
8202 let left = &self.left[mi_r + cell];
8203 for (plane, o) in out.iter_mut().enumerate() {
8204 o.0 |= above[plane].level != 0;
8205 o.1 |= left[plane].level != 0;
8206 o.2 += dc_vote(above[plane].dc) + dc_vote(left[plane].dc);
8207 }
8208 }
8209 out
8210 }
8211
8212 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
8213 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
8214 /// extent pattern for a true rectangular strip's own coefficient context.
8215 fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
8216 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
8217 }
8218
8219 /// [`Self::around_rect`] taking the block's position directly in 4x4
8220 /// mode-info units, mirroring [`Self::around_mi`].
8221 fn around_mi_rect(&self, (mi_r, mi_c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
8222 let (w_mi, h_mi) = (w / MI, h / MI);
8223 // [`Self::around_mi`]'s single pass, with the two extents split.
8224 let mut out = [(false, false, 0i32); 3];
8225 for cell in 0..w_mi {
8226 let above = &self.above[mi_c + cell];
8227 for (plane, o) in out.iter_mut().enumerate() {
8228 o.0 |= above[plane].level != 0;
8229 o.2 += dc_vote(above[plane].dc);
8230 }
8231 }
8232 for cell in 0..h_mi {
8233 let left = &self.left[mi_r + cell];
8234 for (plane, o) in out.iter_mut().enumerate() {
8235 o.1 |= left[plane].level != 0;
8236 o.2 += dc_vote(left[plane].dc);
8237 }
8238 }
8239 if crate::envflags::env_flag!("EC_DCDUMP") {
8240 for (plane, o) in out.iter().enumerate() {
8241 let vote = o.2;
8242 let ab: Vec<String> = (0..w_mi)
8243 .map(|k| format!("{:?}/{}", self.above[mi_c + k][plane].dc, self.above[mi_c + k][plane].level))
8244 .collect();
8245 let lf: Vec<String> = (0..h_mi)
8246 .map(|k| format!("{:?}/{}", self.left[mi_r + k][plane].dc, self.left[mi_r + k][plane].level))
8247 .collect();
8248 eprintln!("EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]", ab.join(","), lf.join(","));
8249 }
8250 }
8251 out
8252 }
8253
8254 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
8255 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
8256 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
8257 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
8258 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
8259 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
8260 /// is always 0, spec's `plane_bsize == tx_size` branch).
8261 fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
8262 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
8263 }
8264
8265 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
8266 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
8267 /// context over `tx_size_wide` and the left one over `tx_size_high`.
8268 fn luma_skip_ctx_rect(
8269 &self,
8270 (mi_r, mi_c): (usize, usize),
8271 w_mi: usize,
8272 h_mi: usize,
8273 ) -> usize {
8274 let side_mi = w_mi;
8275 let mut top = 0u8;
8276 let mut left = 0u8;
8277 for cell in 0..w_mi {
8278 top |= self.above[mi_c + cell][0].level;
8279 }
8280 for cell in 0..h_mi {
8281 left |= self.left[mi_r + cell][0].level;
8282 }
8283 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
8284 if crate::envflags::env_flag!("EC_ECDUMP") {
8285 let ab: Vec<String> =
8286 (0..w_mi).map(|k| self.above[mi_c + k][0].level.to_string()).collect();
8287 let lf: Vec<String> =
8288 (0..h_mi).map(|k| self.left[mi_r + k][0].level.to_string()).collect();
8289 eprintln!(
8290 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},]",
8291 ab.join(","), lf.join(",")
8292 );
8293 }
8294 if crate::envflags::env_flag!("EC_AV1_TRACE") {
8295 eprintln!(
8296 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
8297 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
8298 );
8299 }
8300 ctx
8301 }
8302
8303 /// Writes one coded block into every cell it covers, on both grids: the
8304 /// mode/side arrays up to `side`'s own width, and the coefficient-context
8305 /// arrays up to the true frame edge — the units past it are left at their
8306 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
8307 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
8308 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
8309 /// not from this block's own side).
8310 fn record(
8311 &mut self,
8312 at: (usize, usize),
8313 side: usize,
8314 mode: usize,
8315 uv_mode: usize,
8316 grids: &[&[i32]; 3],
8317 ) {
8318 self.record_rect(at, side, side, mode, uv_mode, grids);
8319 }
8320
8321 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
8322 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
8323 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
8324 /// spec's per-edge partition-context rule, so a true rectangular block
8325 /// naturally wants two different values here rather than one.
8326 /// Writes this block's luma `mode` into the mi-granular
8327 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
8328 /// position a *later* neighbour would read it from: the block's LAST mi
8329 /// row for every column it spans (what the block below reads via
8330 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
8331 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
8332 /// read these back, and only when the recorded position is exactly their
8333 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
8334 fn record_mode_mi(
8335 &mut self,
8336 mi_r: usize,
8337 mi_c: usize,
8338 mi_w: usize,
8339 mi_h: usize,
8340 mode: usize,
8341 ) {
8342 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);
8343 let mode = mode as u8;
8344 for cell in 0..mi_w {
8345 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
8346 *slot = (last_r, mode);
8347 }
8348 }
8349 for cell in 0..mi_h {
8350 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
8351 *slot = (last_c, mode);
8352 }
8353 }
8354 }
8355
8356 /// The mi-exact above/left neighbour luma mode for a block whose top-left
8357 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
8358 /// mi position (then the coarse [`SUB`]-grid slot is right by
8359 /// construction). See [`Self::record_mode_mi`].
8360 fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
8361 match self.sub8_mode_col.get(mi_c) {
8362 Some(&(row, m)) if mi_r > self.tile_row0_mi && usize::from(row) == mi_r - 1 => Some(usize::from(m)),
8363 _ => None,
8364 }
8365 }
8366
8367 fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
8368 match self.sub8_mode_row.get(mi_r) {
8369 Some(&(col, m)) if mi_c > self.tile_col0_mi && usize::from(col) == mi_c - 1 => Some(usize::from(m)),
8370 _ => None,
8371 }
8372 }
8373
8374 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
8375 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
8376 fn record_uv_mode_mi(
8377 &mut self,
8378 mi_r: usize,
8379 mi_c: usize,
8380 mi_w: usize,
8381 mi_h: usize,
8382 uv_mode: usize,
8383 ) {
8384 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
8385 fill_span(&mut self.uv_mode_col, mi_c, mi_w, (last_r as u16, uv_mode as u8));
8386 fill_span(&mut self.uv_mode_row, mi_r, mi_h, (last_c as u16, uv_mode as u8));
8387 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
8388 // covers, so the chroma neighbour read below is a plain grid read.
8389 let stride = self.uv_grid_cols;
8390 let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c);
8391 for row in mi_r..=last_r {
8392 fill_span(&mut self.uv_mode_grid, row * stride + mi_c, n, uv_mode as u8);
8393 }
8394 }
8395
8396 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
8397 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
8398 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
8399 /// block has recorded the exact neighbouring mi.
8400 fn smooth_uv_neighbour(&self, mi_r: usize, mi_c: usize, r: usize, c: usize) -> bool {
8401 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
8402 // REFERENCE block, not off the mi that carries the chroma syntax.
8403 // `set_mi_row_col` (`blockd.h`) takes
8404 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
8405 // only then `chroma_above_mbmi = base_mi[-stride]` /
8406 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
8407 // the ODD mi, so without the snap we looked one mi row/column too far
8408 // down/right -- the mi-exact slot never matched and the coarse
8409 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
8410 // 8x4 at (688, 100) = mi (51, 344): libaom's
8411 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
8412 // `UV_SMOOTH_PRED`), ours was 0, which flips
8413 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
8414 // false for type 1, TRUE for type 0) and upsampled an edge libaom
8415 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
8416 // predicting from it (class `context-read-from-one-cell`).
8417 self.smooth_uv_neighbour_unsnapped(mi_r & !1, mi_c & !1, r, c)
8418 }
8419
8420 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
8421 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
8422 /// counter wants this: it measures how often the snap CHANGES the answer,
8423 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
8424 /// decode path uses the snapping form.
8425 fn smooth_uv_neighbour_unsnapped(
8426 &self,
8427 mi_r: usize,
8428 mi_c: usize,
8429 r: usize,
8430 c: usize,
8431 ) -> bool {
8432 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
8433 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
8434 // array that `start_tile` does not clear, so a block on a tile's first
8435 // mi row used to read the uv_mode of the block above it in the tile
8436 // ABOVE and filter its chroma edge at that neighbour's strength
8437 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
8438 // at chroma (120, 32), the top-right tile's first block).
8439 let have_above = mi_r > self.tile_row0_mi;
8440 let have_left = mi_c > self.tile_col0_mi;
8441 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
8442 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
8443 {
8444 hit!(UV_TILE_EDGE_SUPPRESSED_HITS);
8445 }
8446 // The mi grid is libaom's own read; the two maps below stay as the
8447 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
8448 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
8449 (col < self.uv_grid_cols)
8450 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
8451 .flatten()
8452 .filter(|&m| m != u8::MAX)
8453 .map(usize::from)
8454 };
8455 let above = match self.uv_mode_col.get(mi_c) {
8456 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, mi_r - 1, mi_c) => m,
8457 Some(&(row, m)) if have_above && usize::from(row) == mi_r - 1 => usize::from(m),
8458 _ if have_above => self.above_uv_mode[c],
8459 _ => DC_PRED,
8460 };
8461 let left = match self.uv_mode_row.get(mi_r) {
8462 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, mi_r, mi_c - 1) => m,
8463 Some(&(col, m)) if have_left && usize::from(col) == mi_c - 1 => usize::from(m),
8464 _ if have_left => self.left_uv_mode[r],
8465 _ => DC_PRED,
8466 };
8467 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
8468 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m)
8469 }) || have_left && cell(&self.uv_mode_grid, mi_r, mi_c - 1).is_some_and(|m| {
8470 !matches!(self.uv_mode_row.get(mi_r), Some(&(col, cm)) if usize::from(col) == mi_c - 1 && usize::from(cm) == m)
8471 }) {
8472 hit!(UV_MODE_GRID_OVERRIDE_HITS);
8473 }
8474 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
8475 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
8476 // have been filtered at the wrong strength by the coarse map alone.
8477 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
8478 hit!(UV_MODE_MI_OVERRIDE_HITS);
8479 }
8480 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
8481 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
8482 {
8483 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
8484 }
8485 is_smooth_mode(above) || is_smooth_mode(left)
8486 }
8487
8488 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
8489 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
8490 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
8491 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
8492 /// holding an OLDER, larger block's mode -- it only ever recorded into the
8493 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
8494 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
8495 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
8496 /// a different CDF for the same mode value).
8497 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
8498 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
8499 /// only when `up_available` and `left_mbmi` only when `left_available`;
8500 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
8501 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
8502 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
8503 /// strip's mode as its "left neighbour" (measured on the band fixture at
8504 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
8505 fn modes_above_left_mi(
8506 &self,
8507 mi_r: usize,
8508 mi_c: usize,
8509 fallback: (usize, usize),
8510 ) -> (usize, usize) {
8511 let above = if mi_r > self.tile_row0_mi {
8512 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
8513 } else {
8514 DC_PRED
8515 };
8516 let left = if mi_c > self.tile_col0_mi {
8517 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
8518 } else {
8519 DC_PRED
8520 };
8521 (above, left)
8522 }
8523
8524 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
8525 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
8526 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
8527 /// per superblock row and never per tile, so the first block column of
8528 /// tile 2..N read the previous tile's mode as its left neighbour, and the
8529 /// above band survives across a tile ROW boundary the same way lane-mtfix's
8530 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
8531 /// `up_available`/`left_available` and uses DC_PRED otherwise
8532 /// ([`Self::modes_above_left_mi`]).
8533 fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
8534 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
8535 let (above, left) =
8536 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
8537 if above != self.above_mode[c] || left != self.left_mode[r] {
8538 hit!(MODE_MI_OVERRIDE_HITS);
8539 }
8540 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
8541 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
8542 {
8543 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
8544 }
8545 // A neighbour the coarse band offered where the tile edge makes it
8546 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
8547 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
8548 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
8549 {
8550 hit!(MODE_TILE_EDGE_COARSE_LEAKS);
8551 }
8552 (above, left)
8553 }
8554
8555 fn record_rect(
8556 &mut self,
8557 at: (usize, usize),
8558 w: usize,
8559 h: usize,
8560 mode: usize,
8561 uv_mode: usize,
8562 grids: &[&[i32]; 3],
8563 ) {
8564 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
8565 }
8566
8567 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
8568 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
8569 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
8570 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
8571 /// the [`SUB`]-unit path does).
8572 fn record_rect_mi(
8573 &mut self,
8574 at_mi: (usize, usize),
8575 w: usize,
8576 h: usize,
8577 mode: usize,
8578 uv_mode: usize,
8579 grids: &[&[i32]; 3],
8580 ) {
8581 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
8582 // lane-inter4 r2: a strip whose own footprint runs past the frame's
8583 // last 16-px column/row stamps only the cells that exist (libaom's
8584 // arrays are padded past the frame and those cells are never read).
8585 for cell in 0..w / SUB {
8586 if c + cell >= self.above_mode.len() {
8587 break;
8588 }
8589 self.above_mode[c + cell] = mode;
8590 self.above_uv_mode[c + cell] = uv_mode;
8591 self.above_side[c + cell] = w;
8592 }
8593 for cell in 0..h / SUB {
8594 if r + cell >= self.left_mode.len() {
8595 break;
8596 }
8597 self.left_mode[r + cell] = mode;
8598 self.left_uv_mode[r + cell] = uv_mode;
8599 self.left_side[r + cell] = h;
8600 }
8601 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
8602 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
8603 self.record_mi_rect(at_mi, w, h, grids);
8604 }
8605
8606 /// The coefficient-context half of [`Self::record`], taking the block's
8607 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
8608 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
8609 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
8610 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[&[i32]; 3]) {
8611 self.record_mi_rect(at_mi, side, side, grids);
8612 }
8613
8614 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
8615 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
8616 fn record_mi_rect(
8617 &mut self,
8618 at_mi: (usize, usize),
8619 w: usize,
8620 h: usize,
8621 grids: &[&[i32]; 3],
8622 ) {
8623 let (mi_r, mi_c) = at_mi;
8624 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));
8625 let (w_mi, h_mi) = (w / MI, h / MI);
8626 if crate::envflags::env_flag!("EC_ECPUB") {
8627 eprintln!("EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}", states[0].level);
8628 }
8629 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
8630 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
8631 // A chroma 4x4 unit straddling the true luma edge is still whole in
8632 // chroma's own halved grid, so libaom rounds the luma bound up to the
8633 // plane's own 4x4 unit before clamping a subsampled plane
8634 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
8635 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8636 let bound_h = [
8637 self.mi_rows,
8638 round_up_even(self.mi_rows),
8639 round_up_even(self.mi_rows),
8640 ];
8641 let bound_w = [
8642 self.mi_cols,
8643 round_up_even(self.mi_cols),
8644 round_up_even(self.mi_cols),
8645 ];
8646 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
8647 // past the padded side arrays (mi_rows 198, block rows 192..208);
8648 // libaom's own arrays are superblock-sized, so those cells simply
8649 // have no reader -- [`fill_span`] drops them, as the `break` did.
8650 // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane
8651 // predicate is three contiguous runs: all planes, chroma only, none
8652 // (lane-mi).
8653 let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r));
8654 let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r));
8655 let uv_only = [Neighbour::default(), states[1], states[2]];
8656 fill_span(&mut self.left, mi_r, luma_h, states);
8657 fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only);
8658 fill_span(
8659 &mut self.left,
8660 mi_r + chroma_h,
8661 h_mi - chroma_h,
8662 [Neighbour::default(); 3],
8663 );
8664 let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c));
8665 let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c));
8666 let uv_only_w = [Neighbour::default(), states[1], states[2]];
8667 fill_span(&mut self.above, mi_c, luma_w, states);
8668 fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w);
8669 fill_span(
8670 &mut self.above,
8671 mi_c + chroma_w,
8672 w_mi - chroma_w,
8673 [Neighbour::default(); 3],
8674 );
8675 }
8676
8677 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
8678 /// inside a coded block whose luma transform is smaller than its own
8679 /// side (`TxMode::Select`): the real per-transform-unit coefficient
8680 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
8681 /// coarse per-block `tx_grid`/`fill_lf_grid` state
8682 /// [`Self::record_split_luma`] still writes once for the whole block.
8683 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
8684 /// the caller's own [`Self::record_split_luma`] call sets those once,
8685 /// at the block's own true side, not this TU's.
8686 fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
8687 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
8688 }
8689
8690 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
8691 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
8692 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
8693 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
8694 /// coefficient-context arrays are indexed by luma mi, the convention
8695 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
8696 /// clamp included.
8697 fn record_mi_chroma(
8698 &mut self,
8699 (mi_r, mi_c): (usize, usize),
8700 w_px: usize,
8701 h_px: usize,
8702 plane: usize,
8703 grid: &[i32],
8704 ) {
8705 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8706 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
8707 let state = neighbour_state(grid);
8708 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
8709 self.left[mi_r + cell][plane] = state;
8710 }
8711 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
8712 self.above[mi_c + cell][plane] = state;
8713 }
8714 }
8715
8716 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
8717 /// r1): the above context spans the unit's width, the left context its
8718 /// height, which for a square unit is the same loop it always was.
8719 fn record_mi_luma_rect(
8720 &mut self,
8721 (mi_r, mi_c): (usize, usize),
8722 w_px: usize,
8723 h_px: usize,
8724 grid: &[i32],
8725 ) {
8726 let state = neighbour_state(grid);
8727 if crate::envflags::env_flag!("EC_ECPUB") {
8728 eprintln!("EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}", state.level);
8729 }
8730 for cell in 0..h_px / MI {
8731 if mi_r + cell < self.mi_rows {
8732 self.left[mi_r + cell][0] = state;
8733 }
8734 }
8735 for cell in 0..w_px / MI {
8736 if mi_c + cell < self.mi_cols {
8737 self.above[mi_c + cell][0] = state;
8738 }
8739 }
8740 }
8741
8742 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
8743 /// block whose luma was decoded as several transform units through
8744 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
8745 /// whole-block luma write -- everything [`Self::record`] does except
8746 /// plane 0, which is already correct per-TU by the time this runs.
8747 fn record_split_luma(
8748 &mut self,
8749 at: (usize, usize),
8750 side: usize,
8751 mode: usize,
8752 uv_mode: usize,
8753 chroma_grids: [&[i32]; 2],
8754 ) {
8755 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
8756 }
8757
8758 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
8759 /// extents in pixels (lane-rectsplit r1), the same relationship
8760 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
8761 /// luma transform split into several square units needs exactly this
8762 /// bookkeeping, at its own true rectangular extents.
8763 fn record_split_luma_rect(
8764 &mut self,
8765 at: (usize, usize),
8766 w: usize,
8767 h: usize,
8768 mode: usize,
8769 uv_mode: usize,
8770 chroma_grids: [&[i32]; 2],
8771 ) {
8772 let (r, c) = at;
8773 self.record_split_luma_rect_mi(
8774 (r * (SUB / MI), c * (SUB / MI)),
8775 w,
8776 h,
8777 mode,
8778 uv_mode,
8779 chroma_grids,
8780 );
8781 }
8782
8783 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
8784 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
8785 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
8786 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
8787 /// convention [`decode_block_rect4`] already established for 1:4 strips.
8788 fn record_split_luma_rect_mi(
8789 &mut self,
8790 at_mi: (usize, usize),
8791 w: usize,
8792 h: usize,
8793 mode: usize,
8794 uv_mode: usize,
8795 chroma_grids: [&[i32]; 2],
8796 ) {
8797 let (mi_r, mi_c) = at_mi;
8798 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
8799 for cell in 0..w.div_ceil(SUB) {
8800 if c + cell >= self.above_mode.len() {
8801 break;
8802 }
8803 self.above_mode[c + cell] = mode;
8804 self.above_uv_mode[c + cell] = uv_mode;
8805 self.above_side[c + cell] = w;
8806 }
8807 for cell in 0..h.div_ceil(SUB) {
8808 if r + cell >= self.left_mode.len() {
8809 break;
8810 }
8811 self.left_mode[r + cell] = mode;
8812 self.left_uv_mode[r + cell] = uv_mode;
8813 self.left_side[r + cell] = h;
8814 }
8815
8816 let (w_mi, h_mi) = (w / MI, h / MI);
8817 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
8818 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
8819 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
8820 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
8821 let round_up_even = |n: usize| n.div_ceil(2) * 2;
8822 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
8823 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
8824 let plane = plane_idx + 1;
8825 let state = neighbour_state(grid);
8826 for cell in 0..h_mi {
8827 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
8828 self.left[mi_r + cell][plane] = state;
8829 }
8830 }
8831 for cell in 0..w_mi {
8832 if cell < w_mi.min(bound_w.saturating_sub(mi_c)) {
8833 self.above[mi_c + cell][plane] = state;
8834 }
8835 }
8836 }
8837 }
8838}
8839
8840/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
8841/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
8842/// exactly — including its skip context, which the real key-frame writer
8843/// always writes at a fixed context of zero (it never tracks a neighbour-based
8844/// one for intra blocks; that is the inter-frame writer's rule instead).
8845/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
8846/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
8847/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
8848/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
8849/// plain DC chroma.
8850/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
8851/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
8852/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
8853/// instead (the defect commit 1a89ed9 fixed at the square sites).
8854pub(crate) fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
8855 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
8856 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
8857}
8858
8859/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
8860/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
8861/// bound (spec `filter_intra_mode_info` never reads a symbol there).
8862pub(crate) fn filter_intra_size_class(side: usize) -> Option<usize> {
8863 match side {
8864 4 => Some(0),
8865 8 => Some(1),
8866 16 => Some(2),
8867 32 => Some(3),
8868 _ => None,
8869 }
8870}
8871
8872/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
8873/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
8874/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
8875/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
8876fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
8877 match (bw, bh) {
8878 (32, 16) => Some(4),
8879 (16, 32) => Some(5),
8880 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
8881 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
8882 // here dropped that symbol on every DC_PRED strip of that size and
8883 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
8884 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
8885 (16, 8) => Some(6),
8886 (8, 16) => Some(7),
8887 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
8888 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
8889 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
8890 (4, 8) => Some(8),
8891 (8, 4) => Some(9),
8892 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
8893 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
8894 // `use_filter_intra` symbol on those strips although aomenc writes
8895 // one for every DC_PRED block of that shape with
8896 // `--enable-filter-intra=1` (its default), silently desyncing the
8897 // tile (class symbol-consumption-gap).
8898 (32, 8) => Some(10),
8899 (8, 32) => Some(11),
8900 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
8901 // strips), rows 17/16 of `default_filter_intra_cdfs`.
8902 (16, 4) => Some(12),
8903 (4, 16) => Some(13),
8904 _ if bw == bh => filter_intra_size_class(bw),
8905 _ => None,
8906 }
8907}
8908
8909/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
8910/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
8911/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
8912/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
8913/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
8914pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> {
8915 palette_bsize_ctx_wh(side, side)
8916}
8917
8918/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
8919/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
8920/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
8921/// for ANY bsize, not just the square ones a hand-picked table happened to
8922/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
8923/// row breaks the moment its indexing field moves off the diagonal, and a
8924/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
8925/// block dimension is a power of two, so `bw*bh` always is too and
8926/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
8927/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
8928fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
8929 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
8930 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
8931 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
8932 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
8933 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
8934 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
8935 if bw > 64 || bh > 64 || bw * bh < 64 {
8936 return None;
8937 }
8938 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
8939}
8940
8941/// A just-decoded palette-Y block's own size, base colours (only the first
8942/// `size` entries are real), and per-pixel colour-index map (`side*side`,
8943/// row-major, each entry `< size`).
8944struct PaletteY {
8945 size: usize,
8946 colors: [u16; 8],
8947 map: Vec<u8>,
8948}
8949
8950/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
8951/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
8952/// shared between U and V, both co-located after 4:2:0 subsampling) plus
8953/// each plane's own base colours.
8954struct PaletteUv {
8955 size: usize,
8956 u_colors: [u16; 8],
8957 v_colors: [u16; 8],
8958 map: Vec<u8>,
8959}
8960
8961/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
8962/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
8963/// `get_unsigned_bits`, which is the same formula): smallest `n` with
8964/// `2^n >= x`, `0` for `x <= 1`.
8965pub(crate) fn ceil_log2(x: u32) -> u32 {
8966 if x < 2 { 0 } else { 32 - (x - 1).leading_zeros() }
8967}
8968
8969/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
8970/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
8971fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
8972 let l = ceil_log2(n as u32);
8973 let m = (1usize << l) - n;
8974 let v = dec.literal(l - 1) as usize;
8975 if v < m {
8976 v
8977 } else {
8978 (v << 1) - m + dec.literal(1) as usize
8979 }
8980}
8981
8982/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
8983/// colours (already-known, from the above/left neighbours) with the
8984/// ascending `transmitted` ones (delta-coded off the wire) back into one
8985/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
8986/// value picks the cached copy first, matching the C `<=`.
8987fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
8988 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
8989 let (mut ci, mut ti) = (0, 0);
8990 while ci < cached.len() && ti < transmitted.len() {
8991 if cached[ci] <= transmitted[ti] {
8992 out.push(cached[ci]);
8993 ci += 1;
8994 } else {
8995 out.push(transmitted[ti]);
8996 ti += 1;
8997 }
8998 }
8999 out.extend_from_slice(&cached[ci..]);
9000 out.extend_from_slice(&transmitted[ti..]);
9001 out
9002}
9003
9004/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
9005/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
9006/// each delta's width, the `range` bound and the clamp) is sized by
9007/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
9008/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
9009/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
9010/// the msac range, so a cross-decoder range ladder stays bit-identical
9011/// through the whole miscount -- only the decoded VALUE differs (class
9012/// `compare-range-not-tell`'s blind spot). (this
9013/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
9014/// (one flag bit each, in cache order), then delta-codes the remainder
9015/// (first value raw, each following delta `>= 1` off a shrinking bit width),
9016/// and merges the two ascending lists back together.
9017fn read_palette_colors_y(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> [u16; 8] {
9018 let mut cached = Vec::with_capacity(n);
9019 for &c in cache {
9020 if cached.len() >= n {
9021 break;
9022 }
9023 if dec.literal(1) == 1 {
9024 cached.push(c);
9025 }
9026 }
9027 let bd = u32::from(bit_depth(fctx));
9028 let max_val = (1i32 << bd) - 1;
9029 let mut colors = [0u16; 8];
9030 let n_cached = cached.len();
9031 if n_cached < n {
9032 let mut transmitted = Vec::with_capacity(n - n_cached);
9033 let first = dec.literal(bd) as u16;
9034 transmitted.push(first);
9035 if n_cached + 1 < n {
9036 let min_bits = bd - 3;
9037 let mut bits = min_bits + dec.literal(2);
9038 let mut range = (1i32 << bd) - i32::from(first) - 1;
9039 for _ in (n_cached + 1)..n {
9040 let delta = dec.literal(bits) as i32 + 1;
9041 let prev = *transmitted.last().unwrap();
9042 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
9043 range -= i32::from(val) - i32::from(prev);
9044 bits = bits.min(ceil_log2(range.max(0) as u32));
9045 transmitted.push(val);
9046 }
9047 }
9048 let merged = merge_colors(&transmitted, &cached);
9049 colors[..n].copy_from_slice(&merged);
9050 } else {
9051 colors[..n].copy_from_slice(&cached[..n]);
9052 }
9053 colors
9054}
9055
9056/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
9057/// `bit_depth` (see [`read_palette_colors_y`]): U reads
9058/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
9059/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
9060/// unbiased by `+1` -- both differences from Y's own reader, matching the C
9061/// side by side). V never uses a cache: a leading bit picks either `n` raw
9062/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
9063/// rather than clamp.
9064fn read_palette_colors_uv(dec: &mut SymbolDecoder, n: usize, cache: &[u16], fctx: &crate::decode::FrameCtx) -> ([u16; 8], [u16; 8]) {
9065 let mut cached = Vec::with_capacity(n);
9066 for &c in cache {
9067 if cached.len() >= n {
9068 break;
9069 }
9070 if dec.literal(1) == 1 {
9071 cached.push(c);
9072 }
9073 }
9074 let bd = u32::from(bit_depth(fctx));
9075 let max_val = 1i32 << bd;
9076 let mut u_colors = [0u16; 8];
9077 let n_cached = cached.len();
9078 if n_cached < n {
9079 let mut transmitted = Vec::with_capacity(n - n_cached);
9080 let first = dec.literal(bd) as u16;
9081 transmitted.push(first);
9082 if n_cached + 1 < n {
9083 let min_bits = bd - 3;
9084 let mut bits = min_bits + dec.literal(2);
9085 let mut range = max_val - i32::from(first);
9086 for _ in (n_cached + 1)..n {
9087 let delta = dec.literal(bits) as i32;
9088 let prev = *transmitted.last().unwrap();
9089 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
9090 range -= i32::from(val) - i32::from(prev);
9091 bits = bits.min(ceil_log2(range.max(0) as u32));
9092 transmitted.push(val);
9093 }
9094 }
9095 let merged = merge_colors(&transmitted, &cached);
9096 u_colors[..n].copy_from_slice(&merged);
9097 } else {
9098 u_colors[..n].copy_from_slice(&cached[..n]);
9099 }
9100 let mut v_colors = [0u16; 8];
9101 if dec.literal(1) == 1 {
9102 let min_bits_v = bd - 4;
9103 let bits = min_bits_v + dec.literal(2);
9104 v_colors[0] = dec.literal(bd) as u16;
9105 for i in 1..n {
9106 let mut delta = dec.literal(bits) as i32;
9107 if delta != 0 && dec.literal(1) == 1 {
9108 delta = -delta;
9109 }
9110 let mut val = i32::from(v_colors[i - 1]) + delta;
9111 if val < 0 {
9112 val += max_val;
9113 }
9114 if val >= max_val {
9115 val -= max_val;
9116 }
9117 v_colors[i] = val as u16;
9118 }
9119 } else {
9120 for i in 0..n {
9121 v_colors[i] = dec.literal(bd) as u16;
9122 }
9123 }
9124 (u_colors, v_colors)
9125}
9126
9127/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
9128/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
9129/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
9130const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
9131
9132/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
9133/// map's own per-pixel context and colour-order permutation, from the
9134/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
9135/// selection sort). `map`'s stride is `side` (this decoder never crops a
9136/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
9137/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
9138/// actual colour index to store.
9139pub(crate) fn palette_color_index_context(
9140 map: &[u8],
9141 side: usize,
9142 row: usize,
9143 col: usize,
9144 n: usize,
9145) -> (usize, [u8; 8]) {
9146 let left = if col >= 1 { Some(map[row * side + col - 1]) } else { None };
9147 let up_left = if col >= 1 && row >= 1 {
9148 Some(map[(row - 1) * side + col - 1])
9149 } else {
9150 None
9151 };
9152 let up = if row >= 1 { Some(map[(row - 1) * side + col]) } else { None };
9153 let mut scores = [0i32; 8];
9154 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
9155 if let Some(v) = neighbour {
9156 scores[v as usize] += weight;
9157 }
9158 }
9159 let mut color_order = [0u8; 8];
9160 for i in 0..8 {
9161 color_order[i] = i as u8;
9162 }
9163 for i in 0..3 {
9164 let mut max = scores[i];
9165 let mut max_idx = i;
9166 for j in (i + 1)..n {
9167 if scores[j] > max {
9168 max = scores[j];
9169 max_idx = j;
9170 }
9171 }
9172 if max_idx != i {
9173 let max_score = scores[max_idx];
9174 let max_color = color_order[max_idx];
9175 for k in (i + 1..=max_idx).rev() {
9176 scores[k] = scores[k - 1];
9177 color_order[k] = color_order[k - 1];
9178 }
9179 scores[i] = max_score;
9180 color_order[i] = max_color;
9181 }
9182 }
9183 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
9184 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
9185 (ctx as usize, color_order)
9186}
9187
9188/// spec 5.11.50 `palette_tokens` / `av1_get_block_dimensions` (blockd.h:1512):
9189/// the ON-SCREEN part of a block at `(mi_r, mi_c)`, in luma pixels. A block
9190/// cut by the frame's bottom or right mi edge codes its colour-index map only
9191/// over this part and replicates it outward -- reading the full `bw x bh` grid
9192/// consumed symbols libaom never wrote and desynced the rest of the tile
9193/// (lane-svtinter; class map-read-past-frame-edge).
9194fn palette_onscreen(
9195 mi_r: usize,
9196 mi_c: usize,
9197 bw: usize,
9198 bh: usize,
9199 fctx: &crate::decode::FrameCtx,
9200) -> (usize, usize) {
9201 // lane-palw: the ENCODER's own in-process reconstruct runs on a
9202 // `FrameCtx::for_encoder`, which never sees `set_segmentation` -- both
9203 // frame encoders publish the header's mi dims onto it themselves
9204 // (`encode.rs`, beside their `true_width`/`true_height`) so that this
9205 // clamp and `tile::write_color_index_map`'s now agree there too.
9206 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
9207 palette_onscreen_dims(mi_r, mi_c, bw, bh, (mi_rows, mi_cols))
9208}
9209
9210/// [`palette_onscreen`] off explicit mi dims, which is how the WRITER reaches
9211/// it (`tile::write_palette_syntax`, armed per frame): the two sides must
9212/// compute the same on-screen extent or the decoder reads a different number
9213/// of symbols than the encoder wrote.
9214pub(crate) fn palette_onscreen_dims(
9215 mi_r: usize,
9216 mi_c: usize,
9217 bw: usize,
9218 bh: usize,
9219 (mi_rows, mi_cols): (usize, usize),
9220) -> (usize, usize) {
9221 (
9222 bw.min(mi_cols.saturating_sub(mi_c) * MI),
9223 bh.min(mi_rows.saturating_sub(mi_r) * MI),
9224 )
9225}
9226
9227/// [`palette_onscreen`] carried into the chroma plane: `>> subsampling` plus
9228/// the SAME sub-8 bump the caller's own `(bw / 2).max(4)` applies to the block
9229/// dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move together
9230/// or a cut 8-wide block reads its chroma map at the wrong width.
9231pub(crate) fn palette_onscreen_uv(
9232 luma: (usize, usize),
9233 on: (usize, usize),
9234 chroma: (usize, usize),
9235) -> (usize, usize) {
9236 (
9237 (on.0 >> 1) + (chroma.0 - (luma.0 >> 1)),
9238 (on.1 >> 1) + (chroma.1 - (luma.1 >> 1)),
9239 )
9240}
9241
9242/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
9243/// map's wavefront decode over a `side x side` grid, read over the on-screen
9244/// `on_side x on_side` corner (see [`palette_onscreen`]).
9245fn decode_color_index_map(
9246 dec: &mut SymbolDecoder,
9247 cdfs: &mut Cdfs,
9248 n: usize,
9249 side: usize,
9250 on: (usize, usize),
9251 uv: bool,
9252) -> Vec<u8> {
9253 decode_color_index_map_wh(dec, cdfs, n, side, side, on, uv)
9254}
9255
9256/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
9257/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
9258/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
9259/// independently rather than one shared `side` -- the square call above is
9260/// just `bw == bh`.
9261fn decode_color_index_map_wh(
9262 dec: &mut SymbolDecoder,
9263 cdfs: &mut Cdfs,
9264 n: usize,
9265 bw: usize,
9266 bh: usize,
9267 // `(onscreenWidth, onscreenHeight)` in this plane's own units.
9268 on: (usize, usize),
9269 uv: bool,
9270) -> Vec<u8> {
9271 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
9272 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
9273 if on_bw < bw || on_bh < bh {
9274 hit!(PALETTE_ONSCREEN_CUT_HITS);
9275 }
9276 let mut map = vec![0u8; bw * bh];
9277 if trace {
9278 let (rng, _) = dec.debug_state();
9279 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
9280 }
9281 map[0] = read_uniform(dec, n) as u8;
9282 if trace {
9283 let (rng, _) = dec.debug_state();
9284 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
9285 }
9286 for i in 1..(on_bw + on_bh - 1) {
9287 let j_hi = i.min(on_bw - 1);
9288 let j_lo = i.saturating_sub(on_bh - 1);
9289 for j in (j_lo..=j_hi).rev() {
9290 let row = i - j;
9291 let col = j;
9292 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
9293 if trace {
9294 let (rng, _) = dec.debug_state();
9295 let row_cdf = if uv {
9296 &cdfs.palette_uv_color_index[n - 2][ctx]
9297 } else {
9298 &cdfs.palette_y_color_index[n - 2][ctx]
9299 };
9300 eprintln!("EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}", row_cdf[0], row_cdf[n]);
9301 }
9302 let symbol = if uv {
9303 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
9304 } else {
9305 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
9306 };
9307 map[row * bw + col] = color_order[symbol];
9308 if trace {
9309 let (rng, _) = dec.debug_state();
9310 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
9311 }
9312 }
9313 }
9314 palette_replicate(&mut map, bw, bh, on);
9315 map
9316}
9317
9318/// `decode_color_map_tokens`'s own two extension loops (detokenize.c:71): the
9319/// last on-screen column then the last on-screen row are replicated over the
9320/// off-screen remainder, so the prediction still covers the whole block. The
9321/// ENCODER runs this over its searched map too (`encode.rs`'s palette arms),
9322/// so the pixels it prices and reconstructs are the ones the on-screen
9323/// symbols it writes really decode to.
9324pub(crate) fn palette_replicate(map: &mut [u8], bw: usize, bh: usize, on: (usize, usize)) {
9325 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
9326 for row in 0..on_bh {
9327 let last = map[row * bw + on_bw - 1];
9328 map[row * bw + on_bw..row * bw + bw].fill(last);
9329 }
9330 for row in on_bh..bh {
9331 map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw);
9332 }
9333}
9334
9335/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
9336/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
9337/// size class comes from [`filter_intra_size_class_rect`] instead of the
9338/// square-only [`filter_intra_size_class`], and the palette read (when
9339/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
9340/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
9341/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
9342/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
9343#[allow(clippy::too_many_arguments)]
9344fn read_intra_mode_rect(
9345 dec: &mut SymbolDecoder,
9346 cdfs: &mut Cdfs,
9347 above_mode: usize,
9348 left_mode: usize,
9349 cfl: bool,
9350 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
9351 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
9352 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
9353 // chroma is coded once, on the closing strip). Every other caller is a
9354 // block big enough to own its chroma and passes `true`.
9355 has_chroma: bool,
9356 bw: usize,
9357 bh: usize,
9358 enable_filter_intra: bool,
9359 skip_ctx: usize,
9360 allow_screen_content_tools: bool,
9361 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
9362 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
9363 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
9364 palette: Option<(usize, &[u16])>,
9365 palette_uv_cache: &[u16],
9366 mi_r: usize,
9367 mi_c: usize, fctx: &crate::decode::FrameCtx,
9368) -> Result<(
9369 bool,
9370 usize,
9371 i32,
9372 usize,
9373 i32,
9374 Option<(i32, i32)>,
9375 Option<usize>,
9376 Option<PaletteY>,
9377 Option<PaletteUv>,
9378 // lane-av1-intrabc: the block vector, `Some` exactly when this block's
9379 // `use_intrabc` symbol came out 1 -- libaom's `read_intrabc_info` returns
9380 // straight out of `read_intra_frame_mode_info` then, so every later field
9381 // of the tuple is at its default (mode/uv_mode DC, no angle, no palette,
9382 // no filter intra). A caller that can reconstruct intrabc at its shape
9383 // takes this and calls [`decode_intrabc_rect`]; one that cannot refuses by
9384 // name with the same string it always did.
9385 Option<(i32, i32)>,
9386)> {
9387 // lane-av1mono: libaom guards every chroma symbol read with
9388 // `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`),
9389 // so a monochrome block codes no `uv_mode`/`cfl`/`angle_delta_uv`/
9390 // `palette_uv` even on a chroma-reference strip. Fold the plane count
9391 // into the same `has_chroma` this reader already gates on.
9392 let has_chroma = has_chroma && !mono(fctx);
9393 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
9394 if ec_istep {
9395 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
9396 // (decodemv.c:818), printed at the same point: before the first
9397 // mode-info symbol of the block, so a cross-decoder range ladder can
9398 // be keyed on the BLOCK, not just on the symbol sequence.
9399 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=rect bw={bw} bh={bh} efi={} cls={:?} rng={}", enable_filter_intra as i32, filter_intra_size_class_rect(bw, bh), dec.debug_state().0);
9400 }
9401 macro_rules! istep {
9402 ($name:literal, $val:expr) => {
9403 if ec_istep {
9404 let (rng, _) = dec.debug_state();
9405 eprintln!(
9406 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
9407 $name, $val
9408 );
9409 }
9410 };
9411 }
9412 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
9413 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
9414 // the one point every rect caller routes through, so no call site can
9415 // offer the 14-symbol CFL alphabet on a 64-axis block (class
9416 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
9417 let cfl = if cfl && bw.max(bh) > 32 {
9418 hit!(NOCFL_UV_MODE_HITS);
9419 false
9420 } else {
9421 cfl
9422 };
9423 // lane-intra14 r1: on the INTER block path everything up to and including
9424 // `is_inter` was already read by [`decode_inter_block`], so this reader
9425 // starts at the mode syntax with the `skip` that caller read.
9426 let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
9427 let skip = if let Some((_, skip)) = inter {
9428 skip
9429 } else {
9430 // Same `intra_segment_id` placement as the square reader above.
9431 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
9432 if seg_id_pre_skip(fctx) {
9433 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
9434 }
9435 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
9436 istep!("skip", skip as i32);
9437 if !seg_id_pre_skip(fctx) {
9438 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
9439 }
9440 maybe_read_cdef_idx(dec, mi_r, mi_c, (bw / MI, bh / MI), skip, fctx);
9441 istep!("cdef", 0);
9442 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
9443 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
9444 // `false`.
9445 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
9446 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
9447 istep!("dq", 0);
9448 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
9449 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
9450 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
9451 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
9452 // rect strips read it exactly like square leaves ([`read_intra_mode`],
9453 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
9454 // decoder at the FIRST symbol of the first rect block of every
9455 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
9456 // block at this shape is out of scope, so the flag is consumed and
9457 // refused by name when it fires.
9458 if allow_intrabc_frame(fctx) {
9459 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
9460 hit!(RECT_INTRABC_READS);
9461 istep!("intrabc", use_intrabc as i32);
9462 if use_intrabc {
9463 hit!(INTRABC_HITS);
9464 // libaom `read_intrabc_info`: the DV read, then an immediate
9465 // return out of the mode-info read -- no `y_mode`, no `uv_mode`,
9466 // no angle deltas, no palette, no filter intra. The caller owns
9467 // the reconstruction at its own shape.
9468 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (bw / MI, bh / MI), fctx);
9469 return Ok((
9470 skip,
9471 DC_PRED,
9472 0,
9473 DC_PRED,
9474 0,
9475 None,
9476 None,
9477 None,
9478 None,
9479 Some(dv),
9480 ));
9481 }
9482 }
9483 skip
9484 };
9485 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
9486 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
9487 // off `kf_y_mode_cdf[above][left]`).
9488 let mode = if let Some((size_group, _)) = inter {
9489 dec.symbol(&mut cdfs.y_mode[size_group])
9490 } else {
9491 let above_ctx = INTRA_MODE_CTX[above_mode];
9492 let left_ctx = INTRA_MODE_CTX[left_mode];
9493 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
9494 };
9495 istep!("mode", mode as i32);
9496 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
9497 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
9498 } else {
9499 0
9500 };
9501 istep!("angle_y", angle_delta_y);
9502 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
9503 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
9504 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
9505 // here, from the block's own size, is the single point every caller routes
9506 // through -- a caller passing `true` for a >32 strip used to pick the
9507 // 14-symbol CFL CDF, same value but a different range (class
9508 // wrong-alphabet-same-value).
9509 let cfl = cfl && cfl_allowed_px(bw, bh, fctx);
9510 let uv_mode = if !has_chroma {
9511 DC_PRED
9512 } else if cfl {
9513 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
9514 } else {
9515 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
9516 };
9517 istep!("uv_mode", uv_mode as i32);
9518 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
9519 Some(read_cfl_alphas(dec, cdfs))
9520 } else {
9521 None
9522 };
9523 if has_chroma && (9..=12).contains(&uv_mode) {
9524 hit!(SMOOTH_UV_HITS);
9525 }
9526 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
9527 hit!(DIRECTIONAL_UV_HITS);
9528 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
9529 } else {
9530 0
9531 };
9532 istep!("angle_uv", angle_delta_uv);
9533 if angle_delta_uv != 0 {
9534 hit!(UV_ANGLE_DELTA_HITS);
9535 }
9536 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
9537 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
9538 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
9539 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
9540 // colours only here, the colour-index maps deferred past `filter_intra`
9541 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
9542 // runs from the caller, after the whole mode-info read).
9543 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
9544 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
9545 if allow_screen_content_tools
9546 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
9547 {
9548 // r6: this is the exact site the removed blanket refusal used to
9549 // guard -- reached for EVERY rect strip in a screen-content frame,
9550 // independent of whether the block ends up using a palette.
9551 hit!(RECT_SCREEN_CONTENT_HITS);
9552 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
9553 let use_palette_y =
9554 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
9555 if use_palette_y {
9556 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
9557 let colors = read_palette_colors_y(dec, n, cache, fctx);
9558 palette_y_pending = Some((n, colors));
9559 }
9560 let palette_uv_mode_ctx = usize::from(use_palette_y);
9561 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
9562 if has_chroma
9563 && uv_mode == DC_PRED
9564 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
9565 {
9566 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
9567 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
9568 palette_uv_pending = Some((n, u_colors, v_colors));
9569 }
9570 }
9571 let mut filter_intra = None;
9572 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9573 let (rng, _) = dec.debug_state();
9574 eprintln!(
9575 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
9576 class={:?} rng={rng}",
9577 enable_filter_intra as i32,
9578 filter_intra_size_class_rect(bw, bh)
9579 );
9580 }
9581 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
9582 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
9583 if mode == DC_PRED
9584 && enable_filter_intra
9585 && palette_y_pending.is_none()
9586 && let Some(class) = filter_intra_size_class_rect(bw, bh)
9587 {
9588 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
9589 if crate::envflags::env_flag!("EC_AV1_TRACE") {
9590 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
9591 }
9592 istep!("use_filter_intra", use_filter_intra as i32);
9593 if use_filter_intra {
9594 hit!(FILTER_INTRA_HITS);
9595 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
9596 istep!("filter_intra_mode", fi_mode as i32);
9597 filter_intra = Some(fi_mode);
9598 }
9599 }
9600 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
9601 // same order as [`read_intra_mode`]'s own square path.
9602 let palette_y = palette_y_pending.map(|(n, colors)| {
9603 let map =
9604 decode_color_index_map_wh(dec, cdfs, n, bw, bh, palette_onscreen(mi_r, mi_c, bw, bh, fctx), false);
9605 hit!(PALETTE_HITS);
9606 hit!(PALETTE_RECT_HITS);
9607 PaletteY { size: n, colors, map }
9608 });
9609 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
9610 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
9611 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
9612 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
9613 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
9614 // chroma palette and desynced the tile from there.
9615 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
9616 let on = palette_onscreen_uv((bw, bh), palette_onscreen(mi_r, mi_c, bw, bh, fctx), (cw, ch));
9617 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
9618 hit!(PALETTE_UV_HITS);
9619 PaletteUv { size: n, u_colors, v_colors, map }
9620 });
9621 Ok((
9622 skip,
9623 mode,
9624 angle_delta_y,
9625 uv_mode,
9626 angle_delta_uv,
9627 alpha,
9628 filter_intra,
9629 palette_y,
9630 palette_uv,
9631 None,
9632 ))
9633}
9634
9635/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
9636/// at the strip's REAL mi position. `av1_get_palette_cache` reads
9637/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
9638/// block, so each strip owns its own rows and columns and no aliasing rule
9639/// is needed (lane-kf900 r6).
9640#[allow(clippy::too_many_arguments)]
9641fn record_strip_palette(
9642 n: &mut Neighbours,
9643 mi: (usize, usize),
9644 bw: usize,
9645 bh: usize,
9646 y_size: usize,
9647 y_colors: [u16; 8],
9648 uv_size: usize,
9649 uv_colors: [u16; 8],
9650) {
9651 let (r, c) = mi;
9652 // lane-t900 r23 rung: every publication of a block's palette state into
9653 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
9654 // path left a stale `left_palette_size` behind when
9655 // `av1_get_palette_mode_ctx` disagrees with libaom's.
9656 if crate::envflags::env_flag!("EC_PALPUB") {
9657 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
9658 }
9659 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
9660 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
9661 // existed because the 16px [`SUB`] cell held one slot for all the strips
9662 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
9663 // real neighbour leaf 1 reads.
9664 {
9665 for cell in 0..(bw / MI).max(1) {
9666 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
9667 *e = y_size as u8;
9668 n.above_palette_uv_size[c + cell] = uv_size as u8;
9669 // lane-publish2, see [`Neighbours::record_palette_y_rect`]:
9670 // colours of a size-0 neighbour are never read.
9671 if y_size > 0 {
9672 n.above_palette_colors[c + cell] = y_colors;
9673 }
9674 if uv_size > 0 {
9675 n.above_palette_uv_colors[c + cell] = uv_colors;
9676 }
9677 }
9678 }
9679 }
9680 {
9681 for cell in 0..(bh / MI).max(1) {
9682 if n.left_palette_size.get(r + cell).is_none() {
9683 break;
9684 }
9685 n.left_palette_size[r + cell] = y_size as u8;
9686 n.left_palette_uv_size[r + cell] = uv_size as u8;
9687 if y_size > 0 {
9688 n.left_palette_colors[r + cell] = y_colors;
9689 }
9690 if uv_size > 0 {
9691 n.left_palette_uv_colors[r + cell] = uv_colors;
9692 }
9693 }
9694 }
9695}
9696
9697/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
9698fn cfl_ac_q3_rect(y: &PlaneBuf<'_>, px: usize, py: usize, bw: usize, bh: usize) -> Vec<i32> {
9699 cfl_ac_q3_at(px, py, bw, bh, |lx, ly| i32::from(y.data[ly * y.width + lx]))
9700}
9701
9702/// Everything a rect strip already read out of the stream before its luma
9703/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
9704/// (nine values that would otherwise be nine more parameters).
9705struct RectStripModes {
9706 skip: bool,
9707 mode: usize,
9708 angle_delta_y: i32,
9709 uv_predict_mode: usize,
9710 angle_delta_uv: i32,
9711 alpha: Option<(i32, i32)>,
9712 filter_intra: Option<usize>,
9713 smooth_neighbor: bool,
9714 smooth_neighbor_uv: bool,
9715 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
9716 /// mapped through the colour table), sliced per transform unit below --
9717 /// palette prediction reads no edge pixels, so a unit's slice of the
9718 /// whole-block map IS its prediction. Without this a palette strip whose
9719 /// transform splits predicted DC and came out flat grey while the entropy
9720 /// stream stayed in sync (the coefficients are read either way).
9721 palette_y: Option<Vec<u16>>,
9722 /// As `palette_y`, for the un-split chroma transform (U, V).
9723 palette_uv: Option<(Vec<u16>, Vec<u16>)>,
9724}
9725
9726/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
9727/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
9728/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
9729/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
9730/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
9731/// TX_32X16`) and only the second reaches a square -- the reason
9732/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
9733/// already square) mis-tiled 1:4 strips.
9734fn depth_to_tx_wh(
9735 bw: usize,
9736 bh: usize,
9737 depth: usize,
9738 fctx: &crate::decode::FrameCtx,
9739) -> (usize, usize) {
9740 // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom
9741 // `read_tx_size`: the lossless early return comes before
9742 // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here.
9743 if lossless(fctx) {
9744 return (4, 4);
9745 }
9746 let (mut w, mut h) = (bw.min(64), bh.min(64));
9747 for _ in 0..depth {
9748 match w.cmp(&h) {
9749 std::cmp::Ordering::Greater => w /= 2,
9750 std::cmp::Ordering::Less => h /= 2,
9751 std::cmp::Ordering::Equal => {
9752 w /= 2;
9753 h /= 2;
9754 }
9755 }
9756 }
9757 (w, h)
9758}
9759
9760/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
9761/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
9762/// rect path here refused by name until now ("per-unit rect prediction is not
9763/// ported").
9764///
9765/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
9766/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
9767/// strip the very first step already lands on a SQUARE transform
9768/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
9769/// every further step halves a square) -- so each unit is square and reads
9770/// through the ordinary square [`read_plane`]. What is genuinely rectangular
9771/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
9772/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
9773/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
9774/// split by luma's depth.
9775///
9776/// Each unit predicts off whatever the earlier units of this same block
9777/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
9778/// inside `av1_foreach_transformed_block`, raster order), which is exactly
9779/// what predicting the whole strip in one shot got wrong.
9780#[allow(clippy::too_many_arguments)]
9781fn decode_rect_split(
9782 dec: &mut SymbolDecoder,
9783 cdfs: &mut Cdfs,
9784 neighbours: &mut Neighbours,
9785 at_mi: (usize, usize),
9786 bw: usize,
9787 bh: usize,
9788 // The transform unit's own width and height in pixels. Square for every
9789 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
9790 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
9791 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
9792 tx_w: usize,
9793 tx_h: usize,
9794 m: &RectStripModes,
9795 y: &mut PlaneBuf<'static>,
9796 u: &mut PlaneBuf<'static>,
9797 v: &mut PlaneBuf<'static>,
9798 base_q_idx: u8,
9799 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
9800) -> Result<()> {
9801 let (mi_r, mi_c) = at_mi;
9802 let (px, py) = (mi_c * MI, mi_r * MI);
9803 let (cpx, cpy) = (px / 2, py / 2);
9804 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
9805 // The chroma transform is picked before any symbol is read, so an
9806 // unsupported chroma shape refuses before this strip desyncs the tile.
9807 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
9808 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
9809 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
9810 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
9811 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
9812 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
9813 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
9814 // squares a rect transform down to a CDF set by
9815 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
9816 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
9817 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
9818 // paths already prove for these same shapes.
9819 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
9820 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
9821 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
9822 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
9823 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
9824 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
9825 _ => None,
9826 };
9827 if !m.skip {
9828 if let Some(i) = match (chroma_w, chroma_h) {
9829 (32, 8) => Some(0),
9830 (8, 32) => Some(1),
9831 (8, 4) => Some(2),
9832 (4, 8) => Some(3),
9833 _ => None,
9834 } {
9835 hit_do! {
9836 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
9837 let mut hits = c.get();
9838 hits[i] += 1;
9839 c.set(hits);
9840 });
9841 }
9842 }
9843 if chroma.is_none() {
9844 // Diagnostic for the next caller that lands here (class
9845 // refusal-names-a-correlate: the message names the tool, not the
9846 // shape); the refusal below keeps its inventory-pinned wording.
9847 eprintln!("EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} chroma={chroma_w}x{chroma_h}");
9848 }
9849 }
9850 // lane-rectsplit r2 (verifier finding): with both callers wired
9851 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
9852 // 64x32/32x64) every shape that reaches here has a table above, so this
9853 // arm is UNREACHABLE today. It stays as the shape guard for the next
9854 // caller -- a new strip size would otherwise hit the `expect` below and
9855 // panic instead of refusing by name -- and so stays in
9856 // `refusal_inventory::REFUSALS`.
9857 if !m.skip && chroma.is_none() {
9858 return Err(unsupported(
9859 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
9860 ));
9861 }
9862 hit!(RECT_SPLIT_TX_HITS);
9863 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
9864 hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS);
9865 }
9866 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
9867 // A square unit reads through the ordinary square [`read_plane`]; a rect
9868 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
9869 // the very tables the unsplit 16x8/32x16 paths use.
9870 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
9871 (w, h) if w == h => None,
9872 (16, 8) | (8, 16) => Some((
9873 if reduced_tx_set {
9874 TxbSet::LumaRect16x8
9875 } else {
9876 TxbSet::LumaRect16x8Set1
9877 },
9878 if tx_w == 16 { &SCAN_16X8[..] } else { &SCAN_8X16[..] },
9879 )),
9880 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
9881 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
9882 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
9883 // strip, read through the `luma_64corner` arm below instead of a rect
9884 // table -- a 64-length axis codes only its low 32 coefficients
9885 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
9886 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
9887 // depth-0 arm already reads on the key-frame path.
9888 //
9889 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
9890 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
9891 // sub-8x8 intra leaves still refused: with those lifted (r2) the
9892 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
9893 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
9894 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
9895 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
9896 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
9897 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
9898 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
9899 (64, 32) | (32, 64) => None,
9900 _ => {
9901 return Err(unsupported(format!(
9902 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
9903 coefficient tables for that shape here)"
9904 )))
9905 }
9906 };
9907 // The `None` above that is NOT the square arm.
9908 let luma_64corner = tx_w != tx_h;
9909 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
9910 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
9911 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
9912 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
9913 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
9914 // per-unit rect walk stay wired above/below; the round that finds that
9915 // defect deletes this refusal and nothing else.
9916 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
9917 let luma_scan = default_scan(tx_w.min(tx_h));
9918 let zero_tu = vec![0i32; tx_w * tx_h];
9919 // The strip's OWN edge availability, the fallback for a transform unit
9920 // whose top-right/bottom-left pixels fall outside the strip.
9921 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
9922 for tu_row in 0..bh / tx_h {
9923 for tu_col in 0..bw / tx_w {
9924 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
9925 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
9926 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
9927 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
9928 // libaom clips `av1_foreach_transformed_block_in_plane` to
9929 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
9930 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
9931 // TOP-LEFT sample falls outside the frame is never coded. We read
9932 // coefficients for those phantom units and desynced the stream at
9933 // the very next symbol.
9934 if tu_px >= y.true_width || tu_py >= y.true_height {
9935 continue;
9936 }
9937 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
9938 // transform unit INSIDE a block, which is a different rule from
9939 // the standalone-block table [`Reach::of`] applies -- and the
9940 // reason a depth-2 superblock strip came out one sample off
9941 // before this: `Reach::of(tx, ..)` answered as if the unit were
9942 // its own block at that superblock position.
9943 // * top-right: if the unit's right neighbour is still inside the
9944 // strip the pixels are already reconstructed (`col_off +
9945 // tx_wide < plane_bw`); otherwise only the strip's own top row
9946 // of units can reach past it, through the block-level answer.
9947 // * bottom-left: a unit that is not in the strip's left column
9948 // has none (`col_off > 0` returns 0); inside the strip
9949 // (`row_off + tx_high < plane_bh`) they are the left
9950 // neighbour's, already reconstructed; the last row falls back
9951 // to the block-level answer.
9952 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
9953 // The unit's own window on the block's palette prediction.
9954 if let Some(buf) = &m.palette_y {
9955 let tu_buf: Vec<u16> = (0..tx_h)
9956 .flat_map(|i| {
9957 let base = (row_off + i) * bw + col_off;
9958 buf[base..base + tx_w].iter().copied()
9959 })
9960 .collect();
9961 set_palette_pred(tu_buf, fctx);
9962 }
9963 if m.skip {
9964 push_intra_rect(0,
9965 tu_px,
9966 tu_py,
9967 tx_w,
9968 tx_h,
9969 m.mode,
9970 m.angle_delta_y,
9971 tu_reach,
9972 &zero_tu,
9973 None,
9974 m.filter_intra,
9975 m.smooth_neighbor, fctx,
9976 );
9977 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
9978 } else if luma_64corner && luma_rect.is_none() {
9979 // The un-split 64-level luma transform: `read_coeffs` on the
9980 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
9981 // and the real rect shape passed through for
9982 // `av1_nz_map_ctx_offset` -- byte for byte
9983 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
9984 // 64-level strip gate already proves. `tx_type` is not coded
9985 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
9986 // the square-up size is TX_64X64), and this unit covers its
9987 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
9988 if crate::envflags::env_flag!("EC_RECT64TU") {
9989 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
9990 }
9991 hit_do! {
9992 RECT64_CORNER_TU_HITS.with(|c| {
9993 let mut v = c.get();
9994 v[usize::from(tx_h > tx_w)] += 1;
9995 c.set(v);
9996 });
9997 }
9998 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
9999 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
10000 let (corner, tu_tx_type) = read_coeffs(
10001 dec,
10002 &mut coding,
10003 default_scan(TX32),
10004 0,
10005 dc_sign_ctx(tu_around.2),
10006 TxType::DctDct,
10007 Some((tx_w, tx_h)),
10008 )?;
10009 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
10010 let mut tu_grid = vec![0i32; tx_w * tx_h];
10011 for row in 0..ch {
10012 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
10013 }
10014 let residual = dequant_and_inverse_typed_wh(
10015 &tu_grid,
10016 tx_w,
10017 tx_h,
10018 crate::decode::bit_depth(fctx),
10019 block_q_idx(fctx),
10020 plane_q_delta(0, fctx).0,
10021 plane_q_delta(0, fctx).1,
10022 tu_tx_type,
10023 );
10024 push_intra_rect(0,
10025 tu_px,
10026 tu_py,
10027 tx_w,
10028 tx_h,
10029 m.mode,
10030 m.angle_delta_y,
10031 tu_reach,
10032 &residual,
10033 None,
10034 m.filter_intra,
10035 m.smooth_neighbor, fctx,
10036 );
10037 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
10038 } else if let Some((rect_set, rect_scan)) = luma_rect {
10039 // The rect-unit twin of the square arm below: same contexts,
10040 // same order, through the rect coefficient reader. The
10041 // `tx_type` CDF row of a filter-intra block is
10042 // `fimode_to_intradir[filter_intra_mode]`, never the block's
10043 // own (always DC_PRED) mode -- [`read_plane`] applies that
10044 // for the square arm, so this one must too.
10045 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
10046 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
10047 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
10048 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
10049 // neighbour-magnitude table is for a unit SMALLER than its
10050 // block. [`decode_block_rect`]'s own unsplit read passes a
10051 // literal 0 for the same reason; this arm applied the table
10052 // unconditionally and desynced every depth-0 rect strip that
10053 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
10054 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
10055 0
10056 } else {
10057 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
10058 };
10059 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
10060 let (tu_grid, tu_tx_type) = read_coeffs_rect(
10061 dec,
10062 &mut coding,
10063 rect_scan,
10064 tx_w,
10065 tx_h,
10066 tu_skip_ctx,
10067 dc_sign_ctx(tu_around.2),
10068 TxType::DctDct,
10069 )?;
10070 let residual = dequant_and_inverse_typed_wh(
10071 &tu_grid,
10072 tx_w,
10073 tx_h,
10074 crate::decode::bit_depth(fctx),
10075 block_q_idx(fctx),
10076 plane_q_delta(0, fctx).0,
10077 plane_q_delta(0, fctx).1,
10078 tu_tx_type,
10079 );
10080 push_intra_rect(0,
10081 tu_px,
10082 tu_py,
10083 tx_w,
10084 tx_h,
10085 m.mode,
10086 m.angle_delta_y,
10087 tu_reach,
10088 &residual,
10089 None,
10090 m.filter_intra,
10091 m.smooth_neighbor, fctx,
10092 );
10093 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
10094 } else {
10095 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
10096 // This unit is smaller than the block it sits in, so
10097 // `txb_skip_ctx` is the neighbour-magnitude table, not the
10098 // lone-TU 0 (spec `get_txb_ctx_general`).
10099 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
10100 let tu_grid = read_plane(
10101 dec,
10102 cdfs,
10103 luma_set,
10104 &luma_scan,
10105 0,
10106 tu_around,
10107 m.mode,
10108 m.mode,
10109 m.angle_delta_y,
10110 tu_reach,
10111 y,
10112 tu_px,
10113 tu_py,
10114 tx_w,
10115 tx_w,
10116 base_q_idx,
10117 None,
10118 m.filter_intra,
10119 Some(tu_skip_ctx),
10120 m.smooth_neighbor, fctx,
10121 )?;
10122 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
10123 }
10124 }
10125 }
10126 // CHROMA: one un-split rect transform for the whole strip.
10127 // lane-lossless2: except on a lossless frame, where it is a raster of 4x4
10128 // units -- each stamps its own neighbour context as it is read, and the
10129 // whole-block `record_split_luma_rect_mi` below would overwrite all of
10130 // them with the LAST unit's state (class `override-slot-on-one-arm`: the
10131 // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are
10132 // collected here and replayed after that record.
10133 let mut ll_chroma_units: Vec<((usize, usize), usize, Grid)> = Vec::new();
10134 let ac = m.alpha.map(|_| cfl_src_rect(px, py, bw, bh));
10135 let reach = block_reach;
10136 let (u_grid, v_grid) = if mono(fctx) {
10137 // lane-av1mono: a monochrome frame codes no chroma coefficients on
10138 // any block (`plane < av1_num_planes == 1`), so the whole chroma
10139 // section -- the skipped-strip pushes, the lossless raster and the
10140 // un-split `read_coeffs_rect` below -- is bypassed.
10141 let zero = Grid::Zero(chroma_w * chroma_h);
10142 (zero.clone(), zero)
10143 } else if m.skip {
10144 let zero = Grid::Zero(chroma_w * chroma_h);
10145 if let Some((ub, _)) = &m.palette_uv {
10146 set_palette_pred(ub.clone(), fctx);
10147 }
10148 push_intra_rect(1,
10149 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
10150 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv, fctx,
10151 );
10152 if let Some((_, vb)) = &m.palette_uv {
10153 set_palette_pred(vb.clone(), fctx);
10154 }
10155 push_intra_rect(2,
10156 cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero,
10157 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, fctx,
10158 );
10159 (zero.clone(), zero)
10160 } else if lossless(fctx) {
10161 // lane-lossless: the strip's chroma plane block is coded as 4x4
10162 // transform units too (libaom `read_tx_size` returns TX_4X4 for every
10163 // plane), PLANE-MAJOR inside the block -- U's units first, then V's
10164 // (`decode_token_recon_block`'s mu-chunk loop, measured against
10165 // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1,
10166 // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10`
10167 // offset (our `+3` row base) whenever the plane block is bigger than
10168 // the transform.
10169 let scan4 = default_scan(4);
10170 let offset = (chroma_w > 4 || chroma_h > 4).then_some(3);
10171 let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4);
10172 let mut last = [Grid::Zero(16), Grid::Zero(16)];
10173 for plane_idx in 1..=2 {
10174 for cu_row in 0..ch_n {
10175 for cu_col in 0..cw_n {
10176 let luma_span = 8;
10177 let cu_mi = (
10178 mi_r + cu_row * (luma_span / MI),
10179 mi_c + cu_col * (luma_span / MI),
10180 );
10181 let cu_around = neighbours.around_mi(cu_mi, luma_span);
10182 let cu_reach = tu_reach(
10183 bw, bh,
10184 cu_col * luma_span, cu_row * luma_span, luma_span,
10185 block_reach, px, py, y.width, y.height, fctx,
10186 );
10187 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
10188 if let Some((ub, vb)) = &m.palette_uv {
10189 let pbuf = if plane_idx == 1 { ub } else { vb };
10190 set_palette_pred(
10191 palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4),
10192 fctx,
10193 );
10194 }
10195 let plane = if plane_idx == 1 { &mut *u } else { &mut *v };
10196 let grid = read_plane(
10197 dec, cdfs, TxbSet::Chroma4, &scan4, plane_idx,
10198 cu_around[plane_idx], m.mode, m.uv_predict_mode,
10199 m.angle_delta_uv, cu_reach, plane, cu_x, cu_y, 4, 4,
10200 base_q_idx,
10201 m.alpha.zip(ac).map(|((au, av), ac)| {
10202 (if plane_idx == 1 { au } else { av }, ac)
10203 }),
10204 None, offset, m.smooth_neighbor_uv, fctx,
10205 )?;
10206 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_idx, &grid);
10207 ll_chroma_units.push((cu_mi, plane_idx, grid.clone()));
10208 last[plane_idx - 1] = grid;
10209 }
10210 }
10211 }
10212 let [ug, vg] = last;
10213 (ug, vg)
10214 } else {
10215 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
10216 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
10217 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
10218 // so only the 16x8/8x16 pair takes the mode-indexed default.
10219 let default_tx = if chroma_w.max(chroma_h) >= 32 {
10220 TxType::DctDct
10221 } else {
10222 default_intra_tx_type(m.uv_predict_mode as u8)
10223 };
10224 let around = neighbours.around_mi_rect(at_mi, bw, bh);
10225 let mut grids: Vec<Grid> = Vec::with_capacity(2);
10226 for plane_idx in 1..=2 {
10227 let skip_ctx =
10228 usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
10229 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
10230 let (levels, tx_type) = read_coeffs_rect(
10231 dec,
10232 &mut coding,
10233 chroma_scan,
10234 chroma_w,
10235 chroma_h,
10236 skip_ctx,
10237 dc_sign_ctx(around[plane_idx].2),
10238 default_tx,
10239 )?;
10240 // The same delta_q proof the unsplit rect64 path records
10241 // (lane-rectsplit r4: lifting the split-transform refusal moved
10242 // superblock strips onto this path, so only counting there would
10243 // leave the delta_q gate's counter silent for them).
10244 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
10245 hit!(RECT64_QIDX_DRIFT_HITS);
10246 }
10247 let residual = dequant_and_inverse_typed_wh(
10248 &levels,
10249 chroma_w,
10250 chroma_h,
10251 crate::decode::bit_depth(fctx),
10252 // lane-d792: the BLOCK's quantizer index, i.e. the frame's
10253 // own index PLUS this block's segment `SEG_LVL_ALT_Q` --
10254 // reading `current_q_idx` here dropped the segment feature
10255 // that every other dequant site applies (class
10256 // `parsed-then-discarded`).
10257 block_q_idx(fctx),
10258 plane_q_delta(plane_idx, fctx).0,
10259 plane_q_delta(plane_idx, fctx).1,
10260 tx_type,
10261 );
10262 let cfl = m
10263 .alpha
10264 .zip(ac)
10265 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
10266 let _plane = if plane_idx == 1 { &mut *u } else { &mut *v };
10267 if let Some((ub, vb)) = &m.palette_uv {
10268 let buf = if plane_idx == 1 { ub } else { vb };
10269 set_palette_pred(buf.clone(), fctx);
10270 }
10271 push_intra_rect(plane_idx,
10272 cpx,
10273 cpy,
10274 chroma_w,
10275 chroma_h,
10276 m.uv_predict_mode,
10277 m.angle_delta_uv,
10278 reach,
10279 &residual,
10280 cfl,
10281 None,
10282 m.smooth_neighbor_uv, fctx,
10283 );
10284 grids.push(levels);
10285 }
10286 let mut it = grids.into_iter();
10287 (it.next().unwrap(), it.next().unwrap())
10288 };
10289 neighbours.record_split_luma_rect_mi(
10290 at_mi,
10291 bw,
10292 bh,
10293 m.mode,
10294 m.uv_predict_mode,
10295 [&u_grid, &v_grid],
10296 );
10297 for (cu_mi, plane, unit) in &ll_chroma_units {
10298 neighbours.record_mi_chroma(*cu_mi, 8, 8, *plane, unit);
10299 }
10300 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
10301 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
10302 if crate::envflags::env_flag!("EC_AV1_TRACE") {
10303 let (rng, _) = dec.debug_state();
10304 eprintln!(
10305 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
10306 tx={tx_w}x{tx_h} rng={rng}"
10307 );
10308 }
10309 Ok(())
10310}
10311
10312/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
10313/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
10314/// because it predicts squares only. Every pixel here goes through the rect
10315/// machinery the key-frame paths already prove: [`decode_rect_split`], which
10316/// at `depth == 0` is the unsplit strip as a single transform unit and
10317/// beyond it the per-unit walk of [`depth_to_tx_wh`].
10318///
10319/// What is genuinely different from [`decode_block_rect`] is the mode
10320/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
10321/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
10322/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
10323/// intra-in-inter arm's own reads at the rect footprint, including its
10324/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
10325/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
10326/// square and this arm) and a nonzero luma angle delta refused by name.
10327///
10328/// The strip's own neighbour records (luma per transform unit, chroma, skip
10329/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
10330/// inter-side bands and the mi map.
10331#[allow(clippy::too_many_arguments)]
10332/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
10333/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
10334/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
10335/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
10336/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
10337/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
10338/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
10339/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
10340/// table here rather than a shift of `bw.min(bh)`.
10341fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
10342 Some(match (bw.min(bh), bw.max(bh)) {
10343 (8, 16) => (1usize, 1usize),
10344 (16, 32) => (2, 2),
10345 (32, 64) => (3, 3),
10346 (8, 32) => (1, 2),
10347 (16, 64) => (2, 3),
10348 _ => return None,
10349 })
10350}
10351
10352/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
10353/// block path"): the shapes that can reach that arm, enumerated against the
10354/// MEASURED domain of the inter block path
10355/// ([`INTER_BLOCK_SHAPES`], the census the gate
10356/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
10357/// fills from three real streams).
10358///
10359/// [`decode_intra_rect_in_inter`] is called from one site, under
10360/// `write_w != side || write_h != side`, and only after two earlier arms have
10361/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
10362/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
10363/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
10364/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
10365/// and each of those has a row, so the refusal names a shape no measured
10366/// stream can present.
10367#[test]
10368fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
10369 let mut checked = 0;
10370 for &(side, w, h) in &INTER_BLOCK_SHAPES {
10371 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
10372 continue;
10373 }
10374 assert!(
10375 intra_in_inter_size_row(w, h).is_some(),
10376 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
10377 the \"no size-group/tx-category row\" refusal"
10378 );
10379 checked += 1;
10380 }
10381 assert_eq!(
10382 checked, 10,
10383 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
10384 lookup, not the 10 this claim was measured over"
10385 );
10386}
10387
10388/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
10389/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
10390/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
10391/// matched before the square arm's `log2` shortcut).
10392///
10393/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
10394/// row here"; the enumeration below is what proves no conformant block can
10395/// reach it.
10396pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
10397 Some(match (write_w, write_h) {
10398 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
10399 // below maps 128 to row 4 (BLOCK_16X32).
10400 (64, 128) => 14,
10401 (128, 64) => 15,
10402 (128, 128) => 16,
10403 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
10404 (16, 32) => 4,
10405 (32, 16) => 5,
10406 (32, 64) => 6,
10407 (64, 32) => 7,
10408 (8, 32) => 8,
10409 (32, 8) => 9,
10410 (16, 64) => 10,
10411 (64, 16) => 11,
10412 // lane-inter4 r3: the 16x16-level rect inter leaves.
10413 (8, 16) => 12,
10414 (16, 8) => 13,
10415 _ => return None,
10416 })
10417}
10418
10419/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
10420/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
10421/// `block_size_wide`/`block_size_high`).
10422#[cfg(test)]
10423const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
10424 (4, 4),
10425 (4, 8),
10426 (8, 4),
10427 (8, 8),
10428 (8, 16),
10429 (16, 8),
10430 (16, 16),
10431 (16, 32),
10432 (32, 16),
10433 (32, 32),
10434 (32, 64),
10435 (64, 32),
10436 (64, 64),
10437 (64, 128),
10438 (128, 64),
10439 (128, 128),
10440 (4, 16),
10441 (16, 4),
10442 (8, 32),
10443 (32, 8),
10444 (16, 64),
10445 (64, 16),
10446];
10447
10448/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
10449/// shape with no CDF row here" names a shape no conformant stream can present.
10450///
10451/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
10452/// whose `write_w.min(write_h) >= 8` clause is libaom's
10453/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
10454/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
10455/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
10456/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
10457/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
10458/// clause rejects before the lookup.
10459#[test]
10460fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
10461 let mut rows = std::collections::BTreeSet::new();
10462 let mut excluded = 0;
10463 for (w, h) in BLOCK_SIZES_ALL_WH {
10464 if w.min(h) < 8 {
10465 excluded += 1;
10466 assert!(
10467 w == 4 || h == 4,
10468 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
10469 );
10470 continue;
10471 }
10472 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
10473 panic!(
10474 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
10475 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
10476 )
10477 });
10478 assert!(
10479 row < 17,
10480 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
10481 );
10482 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
10483 }
10484 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
10485 assert_eq!(
10486 rows.len(),
10487 17,
10488 "17 eligible footprints must fill all 17 rows of the motion_mode table"
10489 );
10490}
10491
10492fn decode_intra_rect_in_inter(
10493 dec: &mut SymbolDecoder,
10494 cdfs: &mut Cdfs,
10495 neighbours: &mut Neighbours,
10496 at: (usize, usize),
10497 bw: usize,
10498 bh: usize,
10499 skip: bool,
10500 allow_screen_content_tools: bool,
10501 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
10502 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
10503 strip16: Option<(bool, bool)>,
10504 y: &mut PlaneBuf<'static>,
10505 u: &mut PlaneBuf<'static>,
10506 v: &mut PlaneBuf<'static>,
10507 base_q_idx: u8, fctx: &crate::decode::FrameCtx,
10508) -> Result<()> {
10509 // `at` is in MI units (the inter path's own unit since lane-inter4);
10510 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
10511 // below are still keyed by.
10512 let (mi_r, mi_c) = at;
10513 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
10514 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
10515 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
10516 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
10517 // finding -- the category is NOT the same for every strip size).
10518 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
10519 // it is refused by name rather than read from the wrong CDF row.
10520 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
10521 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
10522 // tx-depth category is 1 -- but nothing here has to know either, because
10523 // the strip decodes through the very body the KEY FRAME path proves for
10524 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
10525 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
10526 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
10527 // inter-frame difference is the mode-info read, which
10528 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
10529 // `y_mode[0]` plus the `skip` this caller already read.
10530 if let Some((horz, has_chroma)) = strip16 {
10531 // lane-t900 r22: the screen-content refusal here was STALE (class
10532 // stale-premise): [`decode_rect4_16_strip`] takes
10533 // `allow_screen_content_tools` and reads the whole palette syntax
10534 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
10535 // pair) -- the key frame proves that body. Lifted with the 10-bit
10536 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
10537 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
10538 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
10539 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
10540 let res = decode_rect4_16_strip(
10541 dec,
10542 cdfs,
10543 neighbours,
10544 (mi_r, mi_c),
10545 horz,
10546 has_chroma,
10547 // The inter strips of the same partition publish their own
10548 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
10549 // has nothing to add here.
10550 None,
10551 y,
10552 u,
10553 v,
10554 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10555 allow_screen_content_tools,
10556 base_q_idx,
10557 fctx.tx_select_inter.with(std::cell::Cell::get),
10558 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10559 );
10560 fctx.intra_in_inter_mode.with(|c| c.set(None));
10561 let (mode, uv, (tx_w, tx_h)) = res?;
10562 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
10563 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
10564 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
10565 // block of an inter frame, intra ones included, and
10566 // `txfm_partition_update` for the var-tx context. The key-frame body
10567 // writes neither (a key frame has no var-tx tree and its own readers
10568 // use the deblock grid), so the block AFTER this strip read a stale
10569 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
10570 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
10571 // 16x16 row.
10572 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
10573 for i in 0..bw / MI {
10574 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
10575 *cell = tx_w as u8;
10576 }
10577 }
10578 for i in 0..bh / MI {
10579 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
10580 *cell = tx_h as u8;
10581 }
10582 }
10583 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
10584 // coarse 16-px cell holds one entry for the whole 16x16 and the last
10585 // block to write it wins).
10586 neighbours.above_mode[c] = mode;
10587 neighbours.left_mode[r] = mode;
10588 if let Some(uvm) = uv {
10589 neighbours.above_uv_mode[c] = uvm;
10590 neighbours.left_uv_mode[r] = uvm;
10591 }
10592 neighbours.above_side[c] = bw;
10593 neighbours.left_side[r] = bh;
10594 if crate::envflags::env_flag!("EC_INTRA16X4") {
10595 eprintln!(
10596 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
10597 mi_c * MI,
10598 mi_r * MI
10599 );
10600 }
10601 hit_do! {
10602 INTRA16X4_IN_INTER_HITS.with(|h| {
10603 let mut v = h.get();
10604 v[usize::from(!horz)] += 1;
10605 v[2] += usize::from(has_chroma);
10606 h.set(v);
10607 });
10608 }
10609 return Ok(());
10610 }
10611 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
10612 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
10613 // puts BLOCK_128X64/64X128/128X128 in group 3 and
10614 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
10615 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
10616 // block decodes through the very body the KEY FRAME path proves for this
10617 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
10618 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
10619 // `Reach` rule and the frame-edge write clip). The only inter-frame
10620 // differences live inside that body: the mode-info read
10621 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
10622 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
10623 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
10624 // palette (>64) do not exist at this size and are refused by name there.
10625 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
10626 // `intra128_in_inter_witness2.obu` (gate
10627 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
10628 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
10629 // all 15 frames, so the hits are counted out of exact frames (class
10630 // `counter-from-refused-stream`). What r16/r17 could not find, and what
10631 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
10632 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
10633 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
10634 // where the frame EDGE forces it: a partial last superblock row has
10635 // `has_rows128 == false`, so the 128x64 top half is implied, and a
10636 // partial last column implies the 64x128 left half. Put content no
10637 // reference holds (a fresh smooth ramp) in exactly those two bands of an
10638 // inter frame and the encoder codes those forced halves INTRA.
10639 if bw.max(bh) == 128 {
10640 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
10641 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
10642 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
10643 // palette_syntax`), so a 128-root half consumes no palette syntax and
10644 // a screen-content frame's half is syntactically identical to the
10645 // non-screen one this arm already decodes byte-exact.
10646 if coeff_trace_on() {
10647 // lane-t900 r16: which decode-order frame this arm fires in --
10648 // interleaved with the `EC_COEFF_FRAME` markers, this is what
10649 // proves the hit is counted out of a frame that compares exact
10650 // (class `counter-from-refused-stream`).
10651 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
10652 }
10653 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
10654 let res = decode_block_128rect(
10655 dec,
10656 cdfs,
10657 neighbours,
10658 (r, c),
10659 bw,
10660 bh,
10661 y,
10662 u,
10663 v,
10664 base_q_idx,
10665 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10666 allow_screen_content_tools,
10667 fctx.tx_select_inter.with(std::cell::Cell::get),
10668 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10669 );
10670 fctx.intra_in_inter_mode.with(|c| c.set(None));
10671 return res;
10672 }
10673 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
10674 if crate::envflags::env_flag!("EC_OBMCREC") {
10675 eprintln!(
10676 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
10677 );
10678 }
10679 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
10680 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
10681 // can arrive here are enumerated against the measured block-shape
10682 // census ([`INTER_BLOCK_SHAPES`]) by
10683 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
10684 // -- every one of them has a row, so this arm names a shape no stream
10685 // has been able to present.
10686 return Err(unsupported(format!(
10687 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
10688 )));
10689 };
10690 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
10691 // screen-content frame ("palette syntax is consumed for square blocks
10692 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
10693 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
10694 // it, while the 2:1 reader inlined further down now codes the same syntax
10695 // itself. A real `--tune-content=screen` inter stream reached this refusal
10696 // on 8x16 / 16x8 strips (gate
10697 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
10698 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
10699 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
10700 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
10701 // luma/chroma transform tables, the per-unit split walk and the strip's
10702 // own neighbour records). The ONLY difference on an inter frame is the
10703 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
10704 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
10705 // this caller already read. `tx_cat` above is the same category those
10706 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
10707 // `decode_block_rect64`), asserted here so a future shape cannot drift.
10708 if bw.max(bh) == 4 * bw.min(bh) {
10709 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
10710 fctx.intra_in_inter_mode.with(|c| c.set(Some((size_group, skip))));
10711 let res = if bw.max(bh) == 64 {
10712 decode_block_rect64(
10713 dec,
10714 cdfs,
10715 neighbours,
10716 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
10717 bw,
10718 bh,
10719 y,
10720 u,
10721 v,
10722 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10723 allow_screen_content_tools,
10724 base_q_idx,
10725 fctx.tx_select_inter.with(std::cell::Cell::get),
10726 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
10727 )
10728 } else {
10729 decode_block_rect4(
10730 dec,
10731 cdfs,
10732 neighbours,
10733 (mi_r, mi_c),
10734 bw,
10735 bh,
10736 None,
10737 y,
10738 u,
10739 v,
10740 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
10741 allow_screen_content_tools,
10742 base_q_idx,
10743 fctx.tx_select_inter.with(std::cell::Cell::get), fctx,
10744 )
10745 .map(|_| ())
10746 };
10747 fctx.intra_in_inter_mode.with(|c| c.set(None));
10748 res?;
10749 let shape = match (bw, bh) {
10750 (64, 16) => 0,
10751 (16, 64) => 1,
10752 (32, 8) => 2,
10753 _ => 3,
10754 };
10755 hit_do! {
10756 INTRA_RECT4_IN_INTER_HITS.with(|h| {
10757 let mut v = h.get();
10758 v[shape] += 1;
10759 h.set(v);
10760 });
10761 }
10762 return Ok(());
10763 }
10764 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
10765 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
10766 // own, so a cross-decoder bisection could only see the block's first
10767 // coefficient. Same names/format as [`read_tx_size`]'s rung.
10768 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
10769 if step_trace {
10770 eprintln!(
10771 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
10772 dec.debug_state().0
10773 );
10774 }
10775 if mode >= 13 {
10776 return Err(unsupported(
10777 "an intra mode this decoder does not code (round 2)",
10778 ));
10779 }
10780 // lane-angleinter (merged on main for the square intra-in-inter arm):
10781 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
10782 // directional predictor; this arm refused a nonzero one before the merge.
10783 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
10784 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
10785 } else {
10786 0
10787 };
10788 if angle_delta_y != 0 {
10789 hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS);
10790 }
10791 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
10792 // superblock-level strip reads the no-CFL alphabet -- the same split
10793 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
10794 //
10795 // lane-av1mono: a monochrome strip codes no chroma mode/CFL symbol
10796 // (libaom `decodemv.c:933`).
10797 let has_chroma = !mono(fctx);
10798 let cfl_allowed = has_chroma && cfl_allowed_px(bw, bh, fctx);
10799 let uv_mode = if !has_chroma {
10800 DC_PRED
10801 } else if cfl_allowed {
10802 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
10803 } else {
10804 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
10805 };
10806 if step_trace {
10807 eprintln!(
10808 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
10809 u8::from(cfl_allowed),
10810 dec.debug_state().0
10811 );
10812 }
10813 if (9..=12).contains(&uv_mode) {
10814 hit!(SMOOTH_UV_HITS);
10815 }
10816 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
10817 Some(read_cfl_alphas(dec, cdfs))
10818 } else {
10819 None
10820 };
10821 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
10822 DC_PRED
10823 } else {
10824 uv_mode
10825 };
10826 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
10827 hit!(DIRECTIONAL_UV_HITS);
10828 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
10829 } else {
10830 0
10831 };
10832 if angle_delta_uv != 0 {
10833 hit!(UV_ANGLE_DELTA_HITS);
10834 hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS);
10835 }
10836 // `read_palette_mode_info` (spec 5.11.13), in the position
10837 // `read_intra_block_mode_info` writes it: after the chroma mode and
10838 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
10839 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
10840 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
10841 // skipping the syntax here desynced the tile at the strip's own symbol.
10842 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
10843 // context and colour cache at its own mi position, and the two
10844 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
10845 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
10846 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
10847 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
10848 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
10849 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
10850 if allow_screen_content_tools
10851 && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh)
10852 {
10853 hit!(INTRA_RECT_IN_INTER_SCREEN_HITS);
10854 let use_palette_y =
10855 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
10856 if use_palette_y {
10857 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
10858 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
10859 }
10860 // A 2:1 strip of at least 8x8 is always a chroma reference, so
10861 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
10862 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
10863 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602).
10864 let use_palette_uv = has_chroma
10865 && uv_mode == DC_PRED
10866 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
10867 if crate::envflags::env_flag!("EC_PALSYN") {
10868 eprintln!("EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}", use_palette_y as i32, use_palette_uv as i32, dec.debug_state().0);
10869 }
10870 if use_palette_uv {
10871 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
10872 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
10873 palette_uv_pending = Some((n, u_colors, v_colors));
10874 }
10875 }
10876 // lane-fiinter (merged on main for the square intra-in-inter arm):
10877 // `read_filter_intra_mode_info` is the tail of
10878 // `read_intra_block_mode_info`, after the palette syntax (refused whole
10879 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
10880 // 2:1 strips with both sides <= 32 -- their own CDF rows
10881 // ([`filter_intra_size_class_rect`]).
10882 let mut filter_intra = None;
10883 if mode == DC_PRED
10884 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
10885 // `av1_filter_intra_allowed` excludes a palette-Y block.
10886 && palette_y_pending.is_none()
10887 && let Some(class) = filter_intra_size_class_rect(bw, bh)
10888 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
10889 {
10890 hit!(FILTER_INTRA_HITS);
10891 hit!(INTRA_IN_INTER_FILTER_INTRA_HITS);
10892 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
10893 }
10894 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
10895 let palette_y = palette_y_pending.map(|(n, colors)| {
10896 let map =
10897 decode_color_index_map_wh(dec, cdfs, n, bw, bh, palette_onscreen(mi_r, mi_c, bw, bh, fctx), false);
10898 hit!(PALETTE_HITS);
10899 hit!(PALETTE_RECT_HITS);
10900 hit!(INTRA_IN_INTER_PALETTE_Y_HITS);
10901 PaletteY { size: n, colors, map }
10902 });
10903 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
10904 let (cw, ch) = ((bw / 2).max(4), (bh / 2).max(4));
10905 let on = palette_onscreen_uv((bw, bh), palette_onscreen(mi_r, mi_c, bw, bh, fctx), (cw, ch));
10906 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
10907 hit!(PALETTE_UV_HITS);
10908 hit!(INTRA_IN_INTER_PALETTE_UV_HITS);
10909 PaletteUv { size: n, u_colors, v_colors, map }
10910 });
10911 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
10912 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
10913 // chroma ones -- [`decode_block_rect`]'s own pair.
10914 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
10915 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
10916 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
10917 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
10918 // one exactly as [`decode_leaf8`] already does (class
10919 // context-read-from-one-cell).
10920 let coarse_pair = neighbours.modes_above_left(r, c);
10921 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
10922 if (nb_above_mode, nb_left_mode) != coarse_pair {
10923 hit!(EDGE_FILTER_MI_FIX_HITS);
10924 }
10925 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
10926 if smooth_neighbor {
10927 hit!(SMOOTH_LUMA_HITS);
10928 }
10929 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
10930 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) {
10931 // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`].
10932 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
10933 let d = match tx_cat {
10934 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
10935 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
10936 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
10937 };
10938 if step_trace {
10939 eprintln!(
10940 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
10941 dec.debug_state().0
10942 );
10943 }
10944 d
10945 } else {
10946 0
10947 };
10948 if depth != 0 || lossless(fctx) {
10949 hit!(TX_DEPTH_HITS);
10950 // lane-intrasplit r1: a split intra strip in an inter frame walks the
10951 // key frame's own per-TU path ([`decode_rect_split`] below); what was
10952 // wrong when this refusal was written was the depth SYMBOL, not the walk.
10953 hit_do! {
10954 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
10955 let mut v = h.get();
10956 v[depth.min(2)] += 1;
10957 h.set(v);
10958 });
10959 }
10960 }
10961 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
10962 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
10963 // the two are indistinguishable when the diagnostic fires on splits alone.
10964 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
10965 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
10966 }
10967 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
10968 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
10969 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
10970 // of an inter frame, intra ones included -- with the skip term 0 it
10971 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
10972 // and `left_txfm_context` to `tx_size_high` over its height. This strip
10973 // wrote neither, so the next block's var-tx `txfm_partition` context read
10974 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
10975 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
10976 // mi(16,0) and desyncing the tile at that symbol.
10977 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
10978 let modes = RectStripModes {
10979 skip,
10980 mode,
10981 angle_delta_y,
10982 uv_predict_mode,
10983 angle_delta_uv,
10984 alpha,
10985 filter_intra,
10986 smooth_neighbor,
10987 smooth_neighbor_uv,
10988 palette_y: palette_y
10989 .as_ref()
10990 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
10991 palette_uv: palette_uv.as_ref().map(|p| {
10992 (
10993 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
10994 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
10995 )
10996 }),
10997 };
10998 decode_rect_split(
10999 dec,
11000 cdfs,
11001 neighbours,
11002 (mi_r, mi_c),
11003 bw,
11004 bh,
11005 tx_w,
11006 tx_h,
11007 &modes,
11008 y,
11009 u,
11010 v,
11011 base_q_idx,
11012 fctx.reduced_tx_set_inter.with(std::cell::Cell::get), fctx,
11013 )?;
11014 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
11015 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
11016 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
11017 // left column over its height. This arm wrote neither before lane-intrasplit
11018 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
11019 // context across the strip's footprint.
11020 for i in 0..bw / MI {
11021 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
11022 *cell = tx_w as u8;
11023 }
11024 }
11025 for i in 0..bh / MI {
11026 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
11027 *cell = tx_h as u8;
11028 }
11029 }
11030 // The strip's own palette state into the mi-granular neighbour bands, so
11031 // the next block's colour cache and `palette_y_mode` context are libaom's.
11032 record_strip_palette(
11033 neighbours,
11034 (mi_r, mi_c),
11035 bw,
11036 bh,
11037 palette_y.as_ref().map_or(0, |p| p.size),
11038 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
11039 palette_uv.as_ref().map_or(0, |p| p.size),
11040 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
11041 );
11042 let class = match bw.max(bh) {
11043 64 => 0,
11044 32 => 1,
11045 _ => 2,
11046 };
11047 hit_do! {
11048 INTRA_RECT_IN_INTER_HITS.with(|h| {
11049 let mut v = h.get();
11050 v[class] += 1;
11051 h.set(v);
11052 });
11053 }
11054 Ok(())
11055}
11056
11057/// Reconstructs one rectangular INTRABC block, `bw`x`bh` pixels at the real
11058/// mi `(mi_r, mi_c)` (lane-av1-intrabc).
11059///
11060/// libaom treats an intrabc block as INTER for everything except the mode-info
11061/// read itself: `is_inter_block` is `is_intrabc_block(mbmi) || ref > INTRA`
11062/// (`blockd.h:373`), so
11063///
11064/// * `parse_decode_block` reads the transform size through the INTER var-tx
11065/// tree (`read_tx_size_vartx`) -- [`read_block_tx_size_rect`], whose
11066/// `txfm_partition` context comes off the real `TXFM_CONTEXT` bands and
11067/// whose leaves publish their own resolved size back;
11068/// * `predict_inter_block` predicts the WHOLE block once, from the CURRENT
11069/// frame's own pre-loop-filter reconstruction, at the coded block vector
11070/// with the BILINEAR kernel `read_intrabc_info` forces (`decodemv.c:913`);
11071/// * `decode_token_recon_block`'s inter branch then reads one residual per
11072/// transform unit, through the INTER coefficient sets
11073/// ([`read_inter_plane_rect`]/[`read_inter_plane`]) with the chroma plane
11074/// inheriting the colocated luma unit's coded `tx_type`.
11075///
11076/// Text order is libaom's: transform tree, prediction, luma residual, chroma
11077/// residual, bookkeeping. A skipped block codes no residual at all -- the
11078/// prediction is the reconstruction.
11079#[allow(clippy::too_many_arguments)]
11080fn decode_intrabc_rect(
11081 dec: &mut SymbolDecoder,
11082 cdfs: &mut Cdfs,
11083 neighbours: &mut Neighbours,
11084 (mi_r, mi_c): (usize, usize),
11085 (bw, bh): (usize, usize),
11086 skip: bool,
11087 (dv_row, dv_col): (i32, i32),
11088 y: &mut PlaneBuf<'static>,
11089 u: &mut PlaneBuf<'static>,
11090 v: &mut PlaneBuf<'static>,
11091 base_q_idx: u8,
11092 fctx: &crate::decode::FrameCtx,
11093) -> Result<()> {
11094 hit!(INTRABC_RECT_HITS);
11095 // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`.
11096 let idx = usize::from(bh > bw);
11097 if skip {
11098 INTRABC_RECT_SKIPPED_HITS.with(|c| {
11099 let mut seen = c.get();
11100 seen[idx] += 1;
11101 c.set(seen);
11102 });
11103 } else {
11104 INTRABC_RECT_CODED_HITS.with(|c| {
11105 let mut seen = c.get();
11106 seen[idx] += 1;
11107 c.set(seen);
11108 });
11109 }
11110 let (px, py) = (mi_c * MI, mi_r * MI);
11111 let (cpx, cpy) = (px / 2, py / 2);
11112 // `av1_get_max_uv_txsize(bw x bh)`: 4:2:0 halves the footprint and the
11113 // halved shape's own `max_txsize_rect_lookup` entry IS that size for every
11114 // shape this helper is called at, so the uv plane block is ONE unit --
11115 // the same call `decode_token_recon_block`'s own chroma loop makes.
11116 let (cw, ch) = (bw / 2, bh / 2);
11117 // lane-av1-intrabc r2: the square stride the proven INTER path uses
11118 // (`side`). The residual grids, the prediction windows AND
11119 // `TxParams::stride` are all laid out at it -- the block's own width
11120 // panicked `TxParams::run` on every coded VERT strip (8x16/16x32: `h`
11121 // exceeds the stride).
11122 let side = bw.max(bh);
11123 let cside = cw.max(ch);
11124 // `av1_calc_mi_size`'s 8-px-aligned grid: a block hanging over the right
11125 // or bottom frame edge reads no transform-tree symbol for the units
11126 // outside it.
11127 let mi_cols = 2 * y.true_width.div_ceil(8);
11128 let mi_rows = 2 * y.true_height.div_ceil(8);
11129 let leaves = read_block_tx_size_rect(
11130 dec,
11131 cdfs,
11132 neighbours,
11133 (mi_r, mi_c),
11134 (bw, bh),
11135 (mi_cols, mi_rows),
11136 skip, fctx,
11137 )?;
11138 if leaves.is_some() {
11139 hit!(INTRABC_RECT_VARTX_HITS);
11140 }
11141 // The whole-block prediction: `predict_inter_block` runs once, before any
11142 // coefficient is read. `flush_recon` first -- the source is this frame's
11143 // own reconstruction, including the writes this superblock has queued.
11144 flush_recon(fctx, y, u, v);
11145 // `mc::predict_with_filter` writes a DENSE window; the residual machinery
11146 // reads it at the square stride, so re-lay it -- the same step the inter
11147 // path takes for its own square prediction buffer.
11148 let mut pred_y_dense = vec![0u16; bw * bh];
11149 mc::predict_with_filter(
11150 &y.data, y.width, y.true_width, y.true_height,
11151 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
11152 bw, bh, mc::InterpFilterKind::Bilinear, &mut pred_y_dense, fctx,
11153 );
11154 let mut pred_y = vec![0u16; side * side];
11155 for row in 0..bh {
11156 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
11157 }
11158 let mut pred_u_dense = vec![0u16; cw * ch];
11159 mc::predict_with_filter(
11160 &u.data, u.width, u.true_width, u.true_height,
11161 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
11162 cw, ch, mc::InterpFilterKind::Bilinear, &mut pred_u_dense, fctx,
11163 );
11164 let mut pred_u = vec![0u16; cside * cside];
11165 for row in 0..ch {
11166 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
11167 }
11168 let mut pred_v_dense = vec![0u16; cw * ch];
11169 mc::predict_with_filter(
11170 &v.data, v.width, v.true_width, v.true_height,
11171 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
11172 cw, ch, mc::InterpFilterKind::Bilinear, &mut pred_v_dense, fctx,
11173 );
11174 let mut pred_v = vec![0u16; cside * cside];
11175 for row in 0..ch {
11176 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
11177 }
11178 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
11179 let luma_tx_type: TxType;
11180 let (luma_grid, u_grid, v_grid);
11181 if skip {
11182 // No residual syntax at all: the prediction IS the block.
11183 // Residual stride is `side` (and `cside`), not `bw`: reconstruct_mc_rect indexes
11184 // `residual[row * side .. row*side + w]` for row in 0..h, so a skipped VERT strip
11185 // (bh > bw) overruns a `bw * bh` slice. Bug-for-bug with the inter skip arm.
11186 push_mc_rect(0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * side], fctx);
11187 push_mc_rect(1, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_u, cside), &ZERO_RESIDUAL[..cside * cside], fctx);
11188 push_mc_rect(2, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_v, cside), &ZERO_RESIDUAL[..cside * cside], fctx);
11189 if let Some(ls) = leaves.as_ref() {
11190 // lane-av1-loss64, merged: the same reset [`decode_intrabc_owned_rect`]'s
11191 // skip arm performs -- libaom `av1_reset_entropy_context`
11192 // (`if (mbmi->skip_txfm)`, decodeframe.c:1262 -> blockd.c:58): a
11193 // SKIPPED block zeroes its whole entropy-band footprint. This
11194 // helper serves `decode_block_rect4`'s 1:4 strips on this tree,
11195 // so a skipped lossless strip whose `leaves` resolved (every
11196 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
11197 // returns the 4x4 grid before it looks at `skip`) left the
11198 // PREVIOUS occupant's luma bands standing and the NEXT block's
11199 // partition parse diverged from libaom's: the 320x242 lossless
11200 // sb128 gate read a phantom unskipped 8x32 intrabc strip at
11201 // mi(56,66) right after the skipped 8x16 one at mi(48,66).
11202 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
11203 for &(row, col, tw, th) in ls {
11204 neighbours.record_mi_luma_rect(
11205 (mi_r + row, mi_c + col),
11206 tw,
11207 th,
11208 &ZERO_RESIDUAL[..tw * th],
11209 );
11210 }
11211 }
11212 luma_tx_type = TxType::DctDct;
11213 luma_grid = Grid::Zero(side * side);
11214 u_grid = Grid::Zero(cside * cside);
11215 v_grid = Grid::Zero(cside * cside);
11216 } else {
11217 match leaves.as_ref() {
11218 None => {
11219 // One whole-block rectangular transform unit.
11220 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
11221 let (grid, tx_type) = read_inter_plane_rect(
11222 dec,
11223 cdfs,
11224 rect_inter_luma_set(bw, bh, fctx)?,
11225 (bw, bh),
11226 side,
11227 0,
11228 around[0],
11229 0,
11230 y,
11231 px,
11232 py,
11233 Pred::Inline(&pred_y, side),
11234 None,
11235 None, fctx,
11236 )?;
11237 luma_tx_type = tx_type;
11238 luma_grid = embed_grid_stride(&grid, bw, bh, side);
11239 let (ug, _) = read_inter_plane_rect(
11240 dec,
11241 cdfs,
11242 rect_inter_chroma_set(cw, ch)?,
11243 (cw, ch),
11244 cside,
11245 1,
11246 around[1],
11247 0,
11248 u,
11249 cpx,
11250 cpy,
11251 Pred::Inline(&pred_u, cside),
11252 Some(luma_tx_type),
11253 None, fctx,
11254 )?;
11255 u_grid = embed_grid_stride(&ug, cw, ch, cside);
11256 let (vg, _) = read_inter_plane_rect(
11257 dec,
11258 cdfs,
11259 rect_inter_chroma_set(cw, ch)?,
11260 (cw, ch),
11261 cside,
11262 2,
11263 around[2],
11264 0,
11265 v,
11266 cpx,
11267 cpy,
11268 Pred::Inline(&pred_v, cside),
11269 Some(luma_tx_type),
11270 None, fctx,
11271 )?;
11272 v_grid = embed_grid_stride(&vg, cw, ch, cside);
11273 }
11274 Some(leaves) => {
11275 // P2 (lane-av1-intrabc r2): libaom `get_transform_size` applies
11276 // the split override to LUMA only, per leaf -- the step the
11277 // proven inter var-tx path applies right after its own residual
11278 // loop ([`Neighbours::fill_lf_grid_leaf_luma`]). Without it the
11279 // leaf's own transform edges are never filtered.
11280 for &(row, col, tw, th) in leaves.iter() {
11281 neighbours.fill_lf_grid_leaf_luma(
11282 (mi_r + row, mi_c + col),
11283 tw / MI,
11284 th / MI,
11285 tw as u8,
11286 th as u8,
11287 );
11288 }
11289 // One residual per transform unit, in the order the tree coded
11290 // them; each unit reads its own neighbour-magnitude context off
11291 // the units already decoded before it, and every unit adds onto
11292 // its own window of the block's single prediction.
11293 let mut first_tx_type = TxType::DctDct;
11294 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
11295 let tu_mi = (mi_r + row, mi_c + col);
11296 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
11297 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
11298 let (tu_grid, tu_tx_type) = if tw == th {
11299 let scan = default_scan(tw.min(32));
11300 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
11301 read_inter_plane(
11302 dec,
11303 cdfs,
11304 inter_txbset_for(tw, reduced),
11305 scan,
11306 0,
11307 neighbours.around_mi(tu_mi, tw)[0],
11308 0,
11309 y,
11310 tu_px,
11311 tu_py,
11312 tw,
11313 base_q_idx,
11314 tu_pred,
11315 None,
11316 Some(tu_skip_ctx), fctx,
11317 )?
11318 } else {
11319 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
11320 read_inter_plane_rect(
11321 dec,
11322 cdfs,
11323 rect_inter_luma_set(tw, th, fctx)?,
11324 (tw, th),
11325 side,
11326 0,
11327 neighbours.around_mi_rect(tu_mi, tw, th)[0],
11328 0,
11329 y,
11330 tu_px,
11331 tu_py,
11332 tu_pred,
11333 None,
11334 Some(tu_skip_ctx), fctx,
11335 )?
11336 };
11337 if idx == 0 {
11338 first_tx_type = tu_tx_type;
11339 }
11340 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
11341 }
11342 // `av1_get_tx_type`'s chroma lookup lands on the colocated
11343 // LUMA unit, which for a split block is the top-left one.
11344 luma_tx_type = first_tx_type;
11345 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
11346 let (ug, _) = read_inter_plane_rect(
11347 dec,
11348 cdfs,
11349 rect_inter_chroma_set(cw, ch)?,
11350 (cw, ch),
11351 cside,
11352 1,
11353 around[1],
11354 0,
11355 u,
11356 cpx,
11357 cpy,
11358 Pred::Inline(&pred_u, cside),
11359 Some(luma_tx_type),
11360 None, fctx,
11361 )?;
11362 u_grid = embed_grid_stride(&ug, cw, ch, cside);
11363 let (vg, _) = read_inter_plane_rect(
11364 dec,
11365 cdfs,
11366 rect_inter_chroma_set(cw, ch)?,
11367 (cw, ch),
11368 cside,
11369 2,
11370 around[2],
11371 0,
11372 v,
11373 cpx,
11374 cpy,
11375 Pred::Inline(&pred_v, cside),
11376 Some(luma_tx_type),
11377 None, fctx,
11378 )?;
11379 v_grid = embed_grid_stride(&vg, cw, ch, cside);
11380 luma_grid = Grid::Zero(side * side);
11381 }
11382 }
11383 }
11384 let _ = luma_tx_type;
11385 // Bookkeeping. An intrabc block publishes mode `DC_PRED` everywhere the
11386 // next block reads a neighbour mode, its own block size in both `TXFM`
11387 // bands (already done by `read_block_tx_size_rect`), a zeroed palette
11388 // state (a stale entry would feed the next block's colour cache), and its
11389 // DV into the intrabc mi grid the next block's DV predictor reads.
11390 if leaves.is_some() {
11391 neighbours.record_split_luma_rect_mi(
11392 (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, [&u_grid, &v_grid],
11393 );
11394 } else {
11395 neighbours.record_rect_mi(
11396 (mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, &[&luma_grid, &u_grid, &v_grid],
11397 );
11398 }
11399 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
11400 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
11401 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
11402 neighbours.fill_lf_grid_rect(
11403 (mi_r, mi_c),
11404 bw / MI,
11405 bh / MI,
11406 bw.min(64) as u8,
11407 bh.min(64) as u8,
11408 0, fctx,
11409 );
11410 record_intrabc_mi_rect(
11411 mi_r,
11412 mi_c,
11413 bw / MI,
11414 bh / MI,
11415 Some((dv_row, dv_col)),
11416 neighbours,
11417 fctx,
11418 );
11419 Ok(())
11420}
11421
11422/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
11423/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
11424/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
11425/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
11426/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
11427/// has no rectangular-transform coefficient reader, and a chroma plane here
11428/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
11429/// with no depth-based square-tiling escape the way luma's own resolved
11430/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
11431/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
11432#[allow(clippy::too_many_arguments)]
11433fn decode_block_rect(
11434 dec: &mut SymbolDecoder,
11435 cdfs: &mut Cdfs,
11436 neighbours: &mut Neighbours,
11437 at: (usize, usize),
11438 bw: usize,
11439 bh: usize,
11440 y: &mut PlaneBuf<'static>,
11441 u: &mut PlaneBuf<'static>,
11442 v: &mut PlaneBuf<'static>,
11443 enable_filter_intra: bool,
11444 allow_screen_content_tools: bool,
11445 base_q_idx: u8,
11446 tx_select: bool,
11447 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
11448) -> Result<()> {
11449 let (r, c) = at;
11450 let (px, py) = (c * SUB, r * SUB);
11451 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
11452 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
11453 let palette_uv_cache = neighbours.palette_uv_cache(at);
11454 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv, intrabc) =
11455 read_intra_mode_rect(
11456 dec,
11457 cdfs,
11458 nb_above_mode,
11459 nb_left_mode,
11460 true,
11461 true,
11462 bw,
11463 bh,
11464 enable_filter_intra,
11465 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
11466 allow_screen_content_tools,
11467 Some((palette_ctx, &palette_cache)),
11468 &palette_uv_cache,
11469 r * (SUB / MI),
11470 c * (SUB / MI), fctx,
11471 )?;
11472
11473 if let Some((dv_row, dv_col)) = intrabc {
11474 return decode_intrabc_rect(
11475 dec,
11476 cdfs,
11477 neighbours,
11478 (r * (SUB / MI), c * (SUB / MI)),
11479 (bw, bh),
11480 skip,
11481 (dv_row, dv_col),
11482 y,
11483 u,
11484 v,
11485 base_q_idx, fctx,
11486 );
11487 }
11488 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
11489 if smooth_neighbor {
11490 hit!(SMOOTH_LUMA_HITS);
11491 }
11492 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
11493 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
11494 // `uv_mode`, not the luma one.
11495 let smooth_neighbor_uv =
11496 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
11497 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
11498 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
11499 // rectangle just as happily), so a `use_filter_intra` strip at this level
11500 // predicts instead of refusing. The below-16x16 leaf arm
11501 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
11502 if filter_intra.is_some() {
11503 hit!(FILTER_INTRA_RECT_HITS);
11504 }
11505 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
11506 DC_PRED
11507 } else {
11508 uv_mode
11509 };
11510 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
11511 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
11512 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
11513 // one did not, so with `--enable-tx-size-search=0` -- which several gate
11514 // recipes use -- the decoder consumed a symbol the encoder never wrote and
11515 // desynced the tile from that point on. That is why both strips of the
11516 // pinned HORZ quadrant were wrong from their very first pixel, and why our
11517 // range after the read equalled the oracle's range for the whole block.
11518 let depth = if tx_select {
11519 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
11520 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
11521 // intra-only frame publishes them from every block too
11522 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
11523 // 1920x792 128-superblock stream,
11524 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
11525 // `tx_size_cat2` row 1 where libaom reads row 2.
11526 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
11527 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
11528 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
11529 eprintln!(
11530 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
11531 dec.debug_state().0
11532 );
11533 }
11534 d
11535 } else {
11536 0
11537 };
11538 // lane-av1-intrabc r3: this strip's own `set_txfm_ctxs` when the frame
11539 // reads the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
11540 publish_txfm_bands_if_in_inter(
11541 neighbours,
11542 (mi_r, mi_c),
11543 depth_to_tx_wh(bw, bh, depth, fctx),
11544 (bw, bh), fctx,
11545 );
11546 if depth != 0 || lossless(fctx) {
11547 hit!(TX_DEPTH_HITS);
11548 // lane-rectsplit r1: a split transform is predicted and reconstructed
11549 // per transform unit, each unit taking its edges from the previous
11550 // unit's reconstruction inside this same strip (spec 5.11.36) --
11551 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
11552 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
11553 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
11554 eprintln!(
11555 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
11556 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
11557 angle_y={angle_delta_y}"
11558 );
11559 }
11560 let modes = RectStripModes {
11561 skip,
11562 mode,
11563 angle_delta_y,
11564 uv_predict_mode,
11565 angle_delta_uv,
11566 alpha,
11567 filter_intra,
11568 smooth_neighbor,
11569 smooth_neighbor_uv,
11570 palette_y: palette_y
11571 .as_ref()
11572 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
11573 palette_uv: palette_uv.as_ref().map(|p| {
11574 (
11575 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
11576 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
11577 )
11578 }),
11579 };
11580 if palette_y.is_some() || palette_uv.is_some() {
11581 hit!(PALETTE_SPLIT_TX_HITS);
11582 }
11583 decode_rect_split(
11584 dec,
11585 cdfs,
11586 neighbours,
11587 (mi_r, mi_c),
11588 bw,
11589 bh,
11590 tx_w,
11591 tx_h,
11592 &modes,
11593 y,
11594 u,
11595 v,
11596 base_q_idx,
11597 reduced_tx_set, fctx,
11598 )?;
11599 // This early return skips this fn's own tail, so the palette
11600 // neighbour state has to be stamped HERE too: without it a split-tx
11601 // strip left the above/left palette arrays holding a DEAD block's
11602 // colours, and the next block's colour cache
11603 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
11604 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
11605 // and only those pixels were wrong (lane-palette2 r10).
11606 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
11607 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
11608 let (puv_size, puv_colors) =
11609 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
11610 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
11611 hit!(RECT_PARTITION_HITS);
11612 return Ok(());
11613 }
11614 let (tx_w, tx_h) = (bw, bh);
11615 let (cpx, cpy) = (px / 2, py / 2);
11616 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
11617 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
11618 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11619 let (rng, _) = dec.debug_state();
11620 eprintln!(
11621 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
11622 skip={} tx={depth} rng={rng}",
11623 skip as i32
11624 );
11625 }
11626 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
11627 // block's prediction is the reconstructed colour-index map, set fresh
11628 // right before each `reconstruct_rect` call below (lane-palette2 r4).
11629 if let Some(ref pyv) = palette_y {
11630 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
11631 set_palette_pred(buf, fctx);
11632 }
11633 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
11634 (
11635 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
11636 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
11637 )
11638 });
11639 if skip {
11640 push_intra_rect(0,
11641 px,
11642 py,
11643 bw,
11644 bh,
11645 mode,
11646 angle_delta_y,
11647 reach,
11648 &ZERO_RESIDUAL[..bw * bh],
11649 None,
11650 filter_intra,
11651 smooth_neighbor, fctx,
11652 );
11653 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11654 if let Some((ub, _)) = &palette_uv_bufs {
11655 set_palette_pred(ub.clone(), fctx);
11656 }
11657 push_intra_rect(1,
11658 cpx,
11659 cpy,
11660 chroma_w,
11661 chroma_h,
11662 uv_predict_mode,
11663 angle_delta_uv,
11664 reach,
11665 &ZERO_RESIDUAL[..chroma_w * chroma_h],
11666 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
11667 None,
11668 smooth_neighbor_uv, fctx,
11669 );
11670 if let Some((_, vb)) = &palette_uv_bufs {
11671 set_palette_pred(vb.clone(), fctx);
11672 }
11673 push_intra_rect(2,
11674 cpx,
11675 cpy,
11676 chroma_w,
11677 chroma_h,
11678 uv_predict_mode,
11679 angle_delta_uv,
11680 reach,
11681 &ZERO_RESIDUAL[..chroma_w * chroma_h],
11682 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
11683 None,
11684 smooth_neighbor_uv, fctx,
11685 );
11686 neighbours.record_rect(
11687 at,
11688 bw,
11689 bh,
11690 mode,
11691 uv_predict_mode,
11692 &[
11693 &ZERO_RESIDUAL[..bw * bh],
11694 &ZERO_RESIDUAL[..chroma_w * chroma_h],
11695 &ZERO_RESIDUAL[..chroma_w * chroma_h],
11696 ],
11697 );
11698 } else {
11699 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
11700 // reduces both size pairs to their square-up CDF sets
11701 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
11702 // doc comments); the scan order and 2D context tables are the real
11703 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
11704 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 32 {
11705 (&SCAN_32X16, &SCAN_16X8)
11706 } else {
11707 (&SCAN_16X32, &SCAN_8X16)
11708 };
11709 // lane-rectwire r3: real coefficients desync a pixel-exact gate
11710 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
11711 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
11712 // pixel (not a subtle context-table off-by-one), while the sibling
11713 // non-rect quadrants of the same frame match. Range-ladder bisection
11714 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
11715 // but the intra key-frame path has no traced symbol between the
11716 // partition read and the first coefficient block (mode/skip/tx_depth
11717 // reads are all untraced in libaom's decodeframe.c intra path, unlike
11718 // the inter EC_TRACE_MODE this round added), so a same-length range
11719 // comparison wasn't reachable within budget -- see
11720 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
11721 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
11722 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
11723 // libaom and match). lane-rectwire r4: range-ladder against the
11724 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
11725 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
11726 // both confirmed in sync -- rng=58692 on both sides right after
11727 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
11728 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
11729 // immediately after: ours moves rng 58692 -> 43570, which cannot be
11730 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
11731 // its own tx_size read) unless oracle's tx symbol is a near-certainty
11732 // CDF that barely narrows the range -- i.e. this decoder's
11733 // tx-depth ctx or `cdfs.tx_size_cat2` CDF selection for
11734 // a 32x16/16x32 strip is the first diverging symbol, not the
11735 // coefficient-context math r3 already cleared. Not confirmed byte-
11736 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
11737 // `read_tx_size`'s own rng, not attempted this round -- budget), so
11738 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
11739 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
11740 // it unconditionally where both square paths gate on `tx_select`. With
11741 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
11742 // decoder consumed one that was never there.
11743 {
11744 let around = neighbours.around_rect(at, bw, bh);
11745 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
11746 let (luma_levels, luma_tx_type) = read_coeffs_rect(
11747 dec,
11748 &mut luma_coding,
11749 luma_scan,
11750 bw,
11751 bh,
11752 0,
11753 dc_sign_ctx(around[0].2),
11754 TxType::DctDct,
11755 )?;
11756 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11757 let (rng, _) = dec.debug_state();
11758 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
11759 }
11760 let luma_residual = dequant_and_inverse_typed_wh(
11761 &luma_levels,
11762 bw,
11763 bh,
11764 crate::decode::bit_depth(fctx),
11765 block_q_idx(fctx),
11766 plane_q_delta(0, fctx).0,
11767 plane_q_delta(0, fctx).1,
11768 luma_tx_type,
11769 );
11770 push_intra_rect(0,
11771 px,
11772 py,
11773 bw,
11774 bh,
11775 mode,
11776 angle_delta_y,
11777 reach,
11778 &luma_residual,
11779 None,
11780 filter_intra,
11781 smooth_neighbor, fctx,
11782 );
11783 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
11784 if let Some((ub, _)) = &palette_uv_bufs {
11785 set_palette_pred(ub.clone(), fctx);
11786 }
11787 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
11788 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
11789 let mut u_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
11790 let (u_levels, u_tx_type) = read_chroma_coeffs_rect(
11791 dec,
11792 &mut u_coding,
11793 chroma_scan,
11794 chroma_w,
11795 chroma_h,
11796 u_skip_ctx,
11797 dc_sign_ctx(around[1].2),
11798 u_default_tx,
11799 fctx,
11800 )?;
11801 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11802 let (rng, _) = dec.debug_state();
11803 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
11804 }
11805 let u_residual = dequant_and_inverse_typed_wh(
11806 &u_levels,
11807 chroma_w,
11808 chroma_h,
11809 crate::decode::bit_depth(fctx),
11810 block_q_idx(fctx),
11811 plane_q_delta(1, fctx).0,
11812 plane_q_delta(1, fctx).1,
11813 u_tx_type,
11814 );
11815 push_intra_rect(1,
11816 cpx,
11817 cpy,
11818 chroma_w,
11819 chroma_h,
11820 uv_predict_mode,
11821 angle_delta_uv,
11822 reach,
11823 &u_residual,
11824 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
11825 None,
11826 smooth_neighbor_uv, fctx,
11827 );
11828 if let Some((_, vb)) = &palette_uv_bufs {
11829 set_palette_pred(vb.clone(), fctx);
11830 }
11831 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
11832 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
11833 let mut v_coding = cdfs.txb(TxbSet::ChromaRect16x8, uv_predict_mode);
11834 let (v_levels, v_tx_type) = read_chroma_coeffs_rect(
11835 dec,
11836 &mut v_coding,
11837 chroma_scan,
11838 chroma_w,
11839 chroma_h,
11840 v_skip_ctx,
11841 dc_sign_ctx(around[2].2),
11842 v_default_tx,
11843 fctx,
11844 )?;
11845 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11846 let (rng, _) = dec.debug_state();
11847 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
11848 }
11849 let v_residual = dequant_and_inverse_typed_wh(
11850 &v_levels,
11851 chroma_w,
11852 chroma_h,
11853 crate::decode::bit_depth(fctx),
11854 block_q_idx(fctx),
11855 plane_q_delta(2, fctx).0,
11856 plane_q_delta(2, fctx).1,
11857 v_tx_type,
11858 );
11859 push_intra_rect(2,
11860 cpx,
11861 cpy,
11862 chroma_w,
11863 chroma_h,
11864 uv_predict_mode,
11865 angle_delta_uv,
11866 reach,
11867 &v_residual,
11868 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
11869 None,
11870 smooth_neighbor_uv, fctx,
11871 );
11872 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
11873 hit!(RECT_COEFF_HITS);
11874 }
11875 }
11876 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
11877 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
11878 let (puv_size, puv_colors) =
11879 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
11880 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
11881 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
11882 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
11883 hit!(RECT_PARTITION_HITS);
11884 if crate::envflags::env_flag!("EC_AV1_TRACE") {
11885 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
11886 }
11887 Ok(())
11888}
11889
11890/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
11891/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
11892/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
11893/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
11894/// the second strip of a HORZ/VERT split sits offset by half the 16x16
11895/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
11896/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
11897/// previous strip is directly above (same column, `mi_h` rows up) or
11898/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
11899/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
11900/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
11901/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
11902/// this strip's real position, never the coarse `record_rect` (which the
11903/// caller uses once, after both strips, exactly like the `VERT_B` arm next
11904/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
11905/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
11906/// chroma half (`TxbSet::ChromaRect8x4`), the two size classes one level
11907/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
11908#[allow(clippy::too_many_arguments)]
11909fn decode_leaf_rect(
11910 dec: &mut SymbolDecoder,
11911 cdfs: &mut Cdfs,
11912 neighbours: &mut Neighbours,
11913 outer_at: (usize, usize),
11914 leaf_mi: (usize, usize),
11915 bw: usize,
11916 bh: usize,
11917 prev_leaf: Option<((usize, usize), usize)>,
11918 y: &mut PlaneBuf<'static>,
11919 u: &mut PlaneBuf<'static>,
11920 v: &mut PlaneBuf<'static>,
11921 enable_filter_intra: bool,
11922 allow_screen_content_tools: bool,
11923 base_q_idx: u8,
11924 tx_select: bool,
11925 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
11926) -> Result<usize> {
11927 let _ = base_q_idx;
11928 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
11929 eprintln!(
11930 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
11931 dec.debug_state().0
11932 );
11933 }
11934 let (r, c) = outer_at;
11935 let mut above_mode = neighbours.above_mode[c];
11936 let mut left_mode = neighbours.left_mode[r];
11937 let (mi_w, mi_h) = (bw / MI, bh / MI);
11938 if let Some(((pr, pc), pmode)) = prev_leaf {
11939 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
11940 above_mode = pmode;
11941 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
11942 left_mode = pmode;
11943 }
11944 }
11945 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
11946 // cannot hold the modes a split (or a pair of strips) leaves behind, so
11947 // when the map holds the block at exactly this strip's above/left mi it
11948 // is the neighbour libaom's `above_mi`/`left_mi` reads.
11949 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
11950 // availability-correct -- four 16x8 strips share one coarse 16x16
11951 // `left_mode` cell too, so the fallback must not stand in for an absent
11952 // tile-edge neighbour.
11953 let (above_mode, left_mode) =
11954 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
11955 let smooth_neighbor =
11956 is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
11957 if smooth_neighbor {
11958 hit!(SMOOTH_LUMA_HITS);
11959 }
11960 // The palette-Y mode CDF row is picked by the neighbours' palette use
11961 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
11962 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
11963 // a palette narrows the wrong interval and desyncs the tile even when the
11964 // decoded bit is the same. The cell is the 16px-SUB cell containing the
11965 // leaf (the palette neighbour arrays have no finer granularity).
11966 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
11967 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
11968 // exclusion and the neighbour palette lookup itself are mi-granular
11969 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
11970 let pal_at = leaf_mi;
11971 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
11972 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
11973 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv, intrabc) =
11974 read_intra_mode_rect(
11975 dec,
11976 cdfs,
11977 above_mode,
11978 left_mode,
11979 true,
11980 true,
11981 bw,
11982 bh,
11983 enable_filter_intra,
11984 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
11985 allow_screen_content_tools,
11986 Some((palette_ctx, &palette_cache)),
11987 &palette_uv_cache,
11988 leaf_mi.0,
11989 leaf_mi.1, fctx,
11990 )?;
11991
11992 if let Some((dv_row, dv_col)) = intrabc {
11993 decode_intrabc_rect(
11994 dec, cdfs, neighbours, leaf_mi, (bw, bh), skip, (dv_row, dv_col),
11995 y, u, v, base_q_idx, fctx,
11996 )?;
11997 return Ok(DC_PRED);
11998 }
11999 // lane-kf900 r4: palette prediction on this shape, the same colour-index
12000 // map -> base colours buffer [`decode_block_rect`] hands each
12001 // `reconstruct_rect` through [`set_palette_pred`].
12002 if palette_y.is_some() || palette_uv.is_some() {
12003 hit!(RECT4_PALETTE_HITS);
12004 }
12005 let palette_y_buf: Option<Vec<u16>> = palette_y
12006 .as_ref()
12007 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
12008 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
12009 (
12010 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
12011 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
12012 )
12013 });
12014 let (pal_y_size, pal_y_colors) =
12015 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12016 let (pal_uv_size, pal_uv_colors) =
12017 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12018 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
12019 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
12020 }
12021 if filter_intra.is_some() {
12022 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
12023 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
12024 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
12025 // below already makes; this refusal was square-only prose.
12026 hit!(FILTER_INTRA_RECT_HITS);
12027 hit!(FILTER_INTRA_RECT_SUB16_HITS);
12028 }
12029 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
12030 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
12031 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
12032 // a constant `false`.
12033 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
12034 let depth = if tx_select {
12035 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
12036 // every other rect reader now does -- a no-op on a key frame.
12037 let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx);
12038 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
12039 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
12040 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
12041 // count (3), different CDF row: a wrong-table read of a real symbol,
12042 // the class that cost lane-rectsplit r1 its 64x32 depth.
12043 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
12044 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
12045 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
12046 // function also decodes) sit at depth 2, so they read
12047 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
12048 // while `tx_size_cat2` belongs to the 32-level shapes
12049 // ([`decode_block_rect`]). Both tables carry three symbols, so the
12050 // wrong one decodes a plausible depth from the wrong probabilities:
12051 // the range diverges silently at the first such leaf and every later
12052 // symbol in the tile is read from the wrong place (class
12053 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
12054 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
12055 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
12056 eprintln!("EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}", leaf_mi.0, leaf_mi.1, dec.debug_state().0);
12057 }
12058 d
12059 } else {
12060 0
12061 };
12062 // lane-av1-intrabc r3: this leaf's own `set_txfm_ctxs` when the frame reads
12063 // the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
12064 publish_txfm_bands_if_in_inter(
12065 neighbours,
12066 leaf_mi,
12067 depth_to_tx_wh(bw, bh, depth, fctx),
12068 (bw, bh), fctx,
12069 );
12070 if depth != 0 || lossless(fctx) {
12071 // The same per-transform-unit walk the bigger strips take
12072 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
12073 // depth 2), addressed at this leaf's own mi position.
12074 hit!(TX_DEPTH_HITS);
12075 hit!(SUB16_SPLIT_HITS);
12076 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
12077 let modes = RectStripModes {
12078 skip,
12079 mode,
12080 angle_delta_y,
12081 uv_predict_mode,
12082 angle_delta_uv,
12083 alpha,
12084 filter_intra,
12085 smooth_neighbor,
12086 // lane-rectsplitx r3: the split arm hard-coded `false` here while
12087 // the unsplit arm below passes the real neighbour answer -- chroma
12088 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
12089 smooth_neighbor_uv,
12090 palette_y: palette_y_buf.clone(),
12091 palette_uv: palette_uv_bufs.clone(),
12092 };
12093 if palette_y.is_some() || palette_uv.is_some() {
12094 hit!(PALETTE_SPLIT_TX_HITS);
12095 }
12096 decode_rect_split(
12097 dec,
12098 cdfs,
12099 neighbours,
12100 leaf_mi,
12101 bw,
12102 bh,
12103 tx_w,
12104 tx_h,
12105 &modes,
12106 y,
12107 u,
12108 v,
12109 base_q_idx,
12110 reduced_tx_set, fctx,
12111 )?;
12112 record_strip_palette(
12113 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
12114 );
12115 return Ok(mode);
12116 }
12117 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
12118 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
12119 let (cpx, cpy) = (px / 2, py / 2);
12120 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
12121 let (luma_levels, u_levels, v_levels);
12122 if skip {
12123 luma_levels = Grid::Zero(bw * bh);
12124 u_levels = Grid::Zero(chroma_w * chroma_h);
12125 v_levels = Grid::Zero(chroma_w * chroma_h);
12126 if let Some(b) = &palette_y_buf {
12127 set_palette_pred(b.clone(), fctx);
12128 }
12129 push_intra_rect(0,
12130 px, py, bw, bh, mode, angle_delta_y, reach, &luma_levels, None, filter_intra,
12131 smooth_neighbor, fctx,
12132 );
12133 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
12134 if let Some((ub, _)) = &palette_uv_bufs {
12135 set_palette_pred(ub.clone(), fctx);
12136 }
12137 push_intra_rect(1,
12138 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_levels,
12139 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
12140 );
12141 if let Some((_, vb)) = &palette_uv_bufs {
12142 set_palette_pred(vb.clone(), fctx);
12143 }
12144 push_intra_rect(2,
12145 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_levels,
12146 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
12147 );
12148 } else {
12149 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
12150 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
12151 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
12152 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
12153 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
12154 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
12155 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw == 16 {
12156 (&SCAN_16X8, &SCAN_8X4)
12157 } else {
12158 (&SCAN_8X16, &SCAN_4X8)
12159 };
12160 let around = neighbours.around_mi_rect(leaf_mi, bw, bh);
12161 let luma_set = if reduced_tx_set {
12162 TxbSet::LumaRect16x8
12163 } else {
12164 TxbSet::LumaRect16x8Set1
12165 };
12166 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
12167 let (l_levels, luma_tx_type) = read_coeffs_rect(
12168 dec, &mut luma_coding, luma_scan, bw, bh, 0, dc_sign_ctx(around[0].2), TxType::DctDct,
12169 )?;
12170 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
12171 let nz: Vec<(usize, i32)> = l_levels.iter().copied().enumerate().filter(|(_, v)| *v != 0).collect();
12172 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
12173 }
12174 luma_levels = l_levels;
12175 let luma_residual = dequant_and_inverse_typed_wh(
12176 &luma_levels, bw, bh, crate::decode::bit_depth(fctx),
12177 block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type,
12178 );
12179 if let Some(b) = &palette_y_buf {
12180 set_palette_pred(b.clone(), fctx);
12181 }
12182 push_intra_rect(0,
12183 px, py, bw, bh, mode, angle_delta_y, reach, &luma_residual, None, filter_intra,
12184 smooth_neighbor, fctx,
12185 );
12186 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
12187 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
12188 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
12189 let mut u_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
12190 let (u_l, u_tx_type) = read_chroma_coeffs_rect(
12191 dec, &mut u_coding, chroma_scan, chroma_w, chroma_h, u_skip_ctx,
12192 dc_sign_ctx(around[1].2), u_default_tx, fctx,
12193 )?;
12194 u_levels = u_l;
12195 let u_residual = dequant_and_inverse_typed_wh(
12196 &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
12197 block_q_idx(fctx), plane_q_delta(1, fctx).0, plane_q_delta(1, fctx).1, u_tx_type,
12198 );
12199 if let Some((ub, _)) = &palette_uv_bufs {
12200 set_palette_pred(ub.clone(), fctx);
12201 }
12202 push_intra_rect(1,
12203 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &u_residual,
12204 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx,
12205 );
12206 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
12207 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
12208 let mut v_coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
12209 let (v_l, v_tx_type) = read_chroma_coeffs_rect(
12210 dec, &mut v_coding, chroma_scan, chroma_w, chroma_h, v_skip_ctx,
12211 dc_sign_ctx(around[2].2), v_default_tx, fctx,
12212 )?;
12213 v_levels = v_l;
12214 let v_residual = dequant_and_inverse_typed_wh(
12215 &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx),
12216 block_q_idx(fctx), plane_q_delta(2, fctx).0, plane_q_delta(2, fctx).1, v_tx_type,
12217 );
12218 if let Some((_, vb)) = &palette_uv_bufs {
12219 set_palette_pred(vb.clone(), fctx);
12220 }
12221 push_intra_rect(2,
12222 cpx, cpy, chroma_w, chroma_h, uv_predict_mode, angle_delta_uv, reach, &v_residual,
12223 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx,
12224 );
12225 hit!(RECT_LEAF_COEFF_HITS);
12226 }
12227 neighbours.record_mi_rect(leaf_mi, bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
12228 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
12229 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
12230 // The leaf's own palette state (`0` clears, as this site always did
12231 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
12232 // AXIS only until the pair's closing leaf: the coarse cell holds one
12233 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
12234 // real left neighbour leaf 1 reads (lane-kf900 r4).
12235 record_strip_palette(
12236 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
12237 );
12238 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
12239 // rows -- record the whole span, not one cell.
12240 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
12241 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
12242 Ok(mode)
12243}
12244
12245/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` /
12246/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling,
12247/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`]
12248/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an
12249/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous
12250/// strip's mode so this one's mode context sees its true above/left
12251/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention).
12252///
12253/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context
12254/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with
12255/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the
12256/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with
12257/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale --
12258/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2
12259/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`).
12260///
12261/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of
12262/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1
12263/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused
12264/// unexamined.
12265#[allow(clippy::too_many_arguments)]
12266fn decode_block_rect4(
12267 dec: &mut SymbolDecoder,
12268 cdfs: &mut Cdfs,
12269 neighbours: &mut Neighbours,
12270 strip_mi: (usize, usize),
12271 bw: usize,
12272 bh: usize,
12273 prev_strip: Option<((usize, usize), usize)>,
12274 y: &mut PlaneBuf<'static>,
12275 u: &mut PlaneBuf<'static>,
12276 v: &mut PlaneBuf<'static>,
12277 enable_filter_intra: bool,
12278 allow_screen_content_tools: bool,
12279 base_q_idx: u8,
12280 tx_select: bool, fctx: &crate::decode::FrameCtx,
12281) -> Result<(usize, usize)> {
12282 let _ = base_q_idx;
12283 let (mi_r, mi_c) = strip_mi;
12284 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
12285 let (mi_w, mi_h) = (bw / MI, bh / MI);
12286 let mut above_mode = neighbours.above_mode[c];
12287 let mut left_mode = neighbours.left_mode[r];
12288 if let Some(((pr, pc), pmode)) = prev_strip {
12289 if pc == mi_c && mi_r == pr + mi_h {
12290 above_mode = pmode;
12291 } else if pr == mi_r && mi_c == pc + mi_w {
12292 left_mode = pmode;
12293 }
12294 }
12295 // lane-rectsplitx r2, ROOT CAUSE of the 1:4 mismatch: mi-exact +
12296 // availability-correct neighbour modes (see
12297 // [`Neighbours::modes_above_left_mi`]). The coarse 16x16 bands alias every
12298 // 8-px strip of a `HORZ_4`/`VERT_4` onto one cell.
12299 let (above_mode, left_mode) =
12300 neighbours.modes_above_left_mi(mi_r, mi_c, (above_mode, left_mode));
12301 // lane-kf900 r4: this strip's own palette-Y mode ctx and colour cache.
12302 // Passing `None`/`&[]` read `palette_y_mode` off CDF row 0 and every
12303 // `palette_colors_y` cache hit off an EMPTY cache -- right symbol count,
12304 // wrong interval, so a screen-content tile desynced at the first strip
12305 // whose neighbour used a palette (class [[cdf-row-held-constant]]).
12306 let pal_at = (mi_r, mi_c);
12307 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
12308 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
12309 let (
12310 skip,
12311 mode,
12312 angle_delta_y,
12313 uv_mode,
12314 angle_delta_uv,
12315 alpha,
12316 filter_intra,
12317 palette_y,
12318 palette_uv,
12319 intrabc,
12320 ) = read_intra_mode_rect(
12321 dec,
12322 cdfs,
12323 above_mode,
12324 left_mode,
12325 true,
12326 true,
12327 bw,
12328 bh,
12329 enable_filter_intra,
12330 neighbours.skip_txfm_ctx(mi_r, mi_c),
12331 allow_screen_content_tools,
12332 Some((palette_ctx, &palette_cache)),
12333 &palette_uv_cache,
12334 mi_r,
12335 mi_c, fctx,
12336 )?;
12337 if let Some((dv_row, dv_col)) = intrabc {
12338 decode_intrabc_rect(
12339 dec, cdfs, neighbours, strip_mi, (bw, bh), skip, (dv_row, dv_col),
12340 y, u, v, base_q_idx, fctx,
12341 )?;
12342 return Ok((DC_PRED, DC_PRED));
12343 }
12344 // lane-kf900 r4: palette prediction on this shape, exactly as
12345 // [`decode_block_rect`] does one aspect ratio up -- the colour-index map
12346 // mapped through the base colours IS the prediction (it reads no edge
12347 // pixels), handed to each `reconstruct_rect` through [`set_palette_pred`].
12348 if palette_y.is_some() || palette_uv.is_some() {
12349 hit!(RECT4_PALETTE_HITS);
12350 }
12351 let palette_y_buf: Option<Vec<u16>> = palette_y
12352 .as_ref()
12353 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
12354 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
12355 (
12356 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
12357 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
12358 )
12359 });
12360 let (pal_y_size, pal_y_colors) =
12361 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
12362 let (pal_uv_size, pal_uv_colors) =
12363 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
12364 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
12365 if smooth_neighbor {
12366 hit!(SMOOTH_LUMA_HITS);
12367 }
12368 // lane-rectsplitx r2: this strip's REAL mi, not the [`SUB`] cell's
12369 // top-left -- a 1:4 strip starts 8 px into a 16-px cell, so
12370 // `r * (SUB / MI)` names a different mi column and the chroma
12371 // edge-filter strength was read from the wrong neighbour (measured:
12372 // seed 43, the last 8x32 strip at luma (152,32), chroma-only mismatch
12373 // with luma bit-exact).
12374 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
12375 if filter_intra.is_some() {
12376 hit!(FILTER_INTRA_RECT_HITS);
12377 if bw > bh {
12378 hit!(FILTER_INTRA_RECT4_HORZ_HITS);
12379 } else {
12380 hit!(FILTER_INTRA_RECT4_VERT_HITS);
12381 }
12382 }
12383 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
12384 DC_PRED
12385 } else {
12386 uv_mode
12387 };
12388 let depth = if tx_select {
12389 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
12390 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
12391 // intra-only frame publishes them from every block too
12392 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
12393 // 1920x792 128-superblock stream,
12394 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
12395 // `tx_size_cat2` row 1 where libaom reads row 2.
12396 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
12397 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
12398 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
12399 eprintln!(
12400 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
12401 dec.debug_state().0
12402 );
12403 }
12404 d
12405 } else {
12406 0
12407 };
12408 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
12409 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
12410 publish_txfm_bands_if_in_inter(
12411 neighbours,
12412 (mi_r, mi_c),
12413 depth_to_tx_wh(bw, bh, depth, fctx),
12414 (bw, bh), fctx,
12415 );
12416 if depth != 0 || lossless(fctx) {
12417 // lane-rectsplitx r1: the per-transform-unit walk, at this strip's
12418 // real mi position (strips 1 and 3 of a HORZ_4 start 8 px into a
12419 // 16-px [`SUB`] cell). depth 1 is the RECT unit TX_16X8/TX_8X16
12420 // (`sub_tx_size_map[TX_32X8] == TX_16X8`), depth 2 the square TX_8X8;
12421 // both interleave in every real stream.
12422 hit!(TX_DEPTH_HITS);
12423 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
12424 // lane-rectsplitx r2: both depths ship together, as the r1 handoff
12425 // predicted -- depth 1 fires FIRST in every attempt that splits at
12426 // all, so a depth-2-only lift could never be gated. The r1 mismatch
12427 // was never the rect unit: it was the neighbour MODE the strip reads
12428 // (see `modes_above_left_mi`).
12429 let which = if depth == 1 {
12430 &RECT4_SPLIT_DEPTH1_HITS
12431 } else {
12432 &RECT4_SPLIT_DEPTH2_HITS
12433 };
12434 hit_do! { which.with(|c| c.set(c.get() + 1)); }
12435 let modes = RectStripModes {
12436 skip,
12437 mode,
12438 angle_delta_y,
12439 uv_predict_mode,
12440 angle_delta_uv,
12441 alpha,
12442 filter_intra,
12443 smooth_neighbor,
12444 smooth_neighbor_uv,
12445 palette_y: palette_y_buf.clone(),
12446 palette_uv: palette_uv_bufs.clone(),
12447 };
12448 if palette_y.is_some() || palette_uv.is_some() {
12449 hit!(PALETTE_SPLIT_TX_HITS);
12450 }
12451 decode_rect_split(
12452 dec,
12453 cdfs,
12454 neighbours,
12455 (mi_r, mi_c),
12456 bw,
12457 bh,
12458 tx_w,
12459 tx_h,
12460 &modes,
12461 y,
12462 u,
12463 v,
12464 base_q_idx,
12465 false, fctx,
12466 )?;
12467 record_strip_palette(
12468 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
12469 pal_uv_colors,
12470 );
12471 if bw > bh {
12472 hit!(RECT4_32_HORZ_HITS);
12473 } else {
12474 hit!(RECT4_32_VERT_HITS);
12475 }
12476 if !skip {
12477 hit!(RECT4_COEFF_HITS);
12478 }
12479 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
12480 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
12481 // frame, so this 1:4 strip -- which is also the INTER frame's reader
12482 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
12483 // transform size in both TXFM_CONTEXT bands. Without it the next block
12484 // reads the row's stale value.
12485 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
12486 return Ok((mode, uv_predict_mode));
12487 }
12488 // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip
12489 // that is 8 px tall, so each strip stamps every cell it touches and the
12490 // LAST strip wins -- which is the right answer for the block below/right
12491 // of the 32x32, the only reader outside it. Written after this strip's
12492 // own context read above, never before.
12493 for cell in 0..bw.div_ceil(SUB) {
12494 neighbours.above_mode[c + cell] = mode;
12495 neighbours.above_uv_mode[c + cell] = uv_predict_mode;
12496 neighbours.above_side[c + cell] = bw;
12497 }
12498 for cell in 0..bh.div_ceil(SUB) {
12499 neighbours.left_mode[r + cell] = mode;
12500 neighbours.left_uv_mode[r + cell] = uv_predict_mode;
12501 neighbours.left_side[r + cell] = bh;
12502 }
12503 // ...and the mi-EXACT maps the coarse cells alias away, exactly as
12504 // [`decode_leaf_rect`] does (the split arm above records these through
12505 // `record_mi_luma_rect`). Without this an unsplit 32x8 strip left
12506 // `sub8_mode_row` holding the previous block, and the next 32x32's
12507 // strips read a stale `kf_y_mode` row (measured: mi(4,8) on the band
12508 // fixture).
12509 neighbours.record_mode_mi(mi_r, mi_c, mi_w, mi_h, mode);
12510 neighbours.record_uv_mode_mi(mi_r, mi_c, mi_w, mi_h, uv_predict_mode);
12511 let (px, py) = (mi_c * MI, mi_r * MI);
12512 let (cpx, cpy) = (px / 2, py / 2);
12513 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
12514 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
12515 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh {
12516 (&SCAN_32X8, &SCAN_16X4)
12517 } else {
12518 (&SCAN_8X32, &SCAN_4X16)
12519 };
12520 let (luma_levels, u_levels, v_levels) = if skip {
12521 (
12522 vec![0i32; bw * bh],
12523 vec![0i32; chroma_w * chroma_h],
12524 vec![0i32; chroma_w * chroma_h],
12525 )
12526 } else {
12527 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
12528 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode);
12529 let (luma_levels, luma_tx_type) = read_coeffs_rect(
12530 dec,
12531 &mut luma_coding,
12532 luma_scan,
12533 bw,
12534 bh,
12535 0,
12536 dc_sign_ctx(around[0].2),
12537 TxType::DctDct,
12538 )?;
12539 let mut planes = Vec::with_capacity(2);
12540 for plane in 1..3 {
12541 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
12542 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
12543 let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode);
12544 let (levels, tx_type) = read_chroma_coeffs_rect(
12545 dec,
12546 &mut coding,
12547 chroma_scan,
12548 chroma_w,
12549 chroma_h,
12550 skip_ctx,
12551 dc_sign_ctx(around[plane].2),
12552 default_tx,
12553 fctx,
12554 )?;
12555 planes.push((levels, tx_type));
12556 }
12557 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
12558 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
12559 hit!(RECT4_COEFF_HITS);
12560 let luma_residual = dequant_and_inverse_typed_wh(
12561 &luma_levels,
12562 bw,
12563 bh,
12564 crate::decode::bit_depth(fctx),
12565 block_q_idx(fctx),
12566 plane_q_delta(0, fctx).0,
12567 plane_q_delta(0, fctx).1,
12568 luma_tx_type,
12569 );
12570 if let Some(b) = &palette_y_buf {
12571 set_palette_pred(b.clone(), fctx);
12572 }
12573 push_intra_rect(0,
12574 px,
12575 py,
12576 bw,
12577 bh,
12578 mode,
12579 angle_delta_y,
12580 reach,
12581 &luma_residual,
12582 None,
12583 filter_intra,
12584 smooth_neighbor, fctx,
12585 );
12586 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
12587 for (plane, _buf, levels, tx_type) in [
12588 (1usize, &mut *u, &u_levels, u_tx_type),
12589 (2, &mut *v, &v_levels, v_tx_type),
12590 ] {
12591 let residual = dequant_and_inverse_typed_wh(
12592 levels,
12593 chroma_w,
12594 chroma_h,
12595 crate::decode::bit_depth(fctx),
12596 block_q_idx(fctx),
12597 plane_q_delta(plane, fctx).0,
12598 plane_q_delta(plane, fctx).1,
12599 tx_type,
12600 );
12601 if let Some((ub, vb)) = &palette_uv_bufs {
12602 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
12603 }
12604 push_intra_rect(plane,
12605 cpx,
12606 cpy,
12607 chroma_w,
12608 chroma_h,
12609 uv_predict_mode,
12610 angle_delta_uv,
12611 reach,
12612 &residual,
12613 alpha
12614 .zip(ac)
12615 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
12616 None,
12617 smooth_neighbor_uv, fctx,
12618 );
12619 }
12620 neighbours.record_mi_rect(
12621 (mi_r, mi_c),
12622 bw,
12623 bh,
12624 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
12625 );
12626 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
12627 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
12628 record_strip_palette(
12629 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size,
12630 pal_uv_colors,
12631 );
12632 if bw > bh {
12633 hit!(RECT4_32_HORZ_HITS);
12634 } else {
12635 hit!(RECT4_32_VERT_HITS);
12636 }
12637 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
12638 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
12639 // frame, so this 1:4 strip -- which is also the INTER frame's reader
12640 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
12641 // transform size in both TXFM_CONTEXT bands. Without it the next block
12642 // reads the row's stale value.
12643 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
12644 return Ok((mode, uv_predict_mode));
12645 };
12646 if let Some(b) = &palette_y_buf {
12647 set_palette_pred(b.clone(), fctx);
12648 }
12649 push_intra_rect(0,
12650 px,
12651 py,
12652 bw,
12653 bh,
12654 mode,
12655 angle_delta_y,
12656 reach,
12657 &luma_levels,
12658 None,
12659 filter_intra,
12660 smooth_neighbor, fctx,
12661 );
12662 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
12663 if let Some((ub, _)) = &palette_uv_bufs {
12664 set_palette_pred(ub.clone(), fctx);
12665 }
12666 push_intra_rect(1,
12667 cpx,
12668 cpy,
12669 chroma_w,
12670 chroma_h,
12671 uv_predict_mode,
12672 angle_delta_uv,
12673 reach,
12674 &u_levels,
12675 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
12676 None,
12677 smooth_neighbor_uv, fctx,
12678 );
12679 if let Some((_, vb)) = &palette_uv_bufs {
12680 set_palette_pred(vb.clone(), fctx);
12681 }
12682 push_intra_rect(2,
12683 cpx,
12684 cpy,
12685 chroma_w,
12686 chroma_h,
12687 uv_predict_mode,
12688 angle_delta_uv,
12689 reach,
12690 &v_levels,
12691 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12692 None,
12693 smooth_neighbor_uv, fctx,
12694 );
12695 neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
12696 neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip);
12697 neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
12698 record_strip_palette(
12699 neighbours, pal_at, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
12700 );
12701 if bw > bh {
12702 hit!(RECT4_32_HORZ_HITS);
12703 } else {
12704 hit!(RECT4_32_VERT_HITS);
12705 }
12706 // lane-frame36 r2 (same shape as `decode_block_rect64`'s split arm,
12707 // swept this round): `set_txfm_ctxs` runs for EVERY block of an inter
12708 // frame, so this 1:4 strip -- which is also the INTER frame's reader
12709 // for 32x8/8x32 ([`decode_intra_rect4_in_inter`]) -- publishes its
12710 // transform size in both TXFM_CONTEXT bands. Without it the next block
12711 // reads the row's stale value.
12712 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (bw, bh), (bw, bh));
12713 Ok((mode, uv_predict_mode))
12714}
12715
12716/// Decodes the four 16x4 / 4x16 strips of a 16x16-level `PARTITION_HORZ_4` /
12717/// `PARTITION_VERT_4` (lane-r14) -- [`decode_block_rect4`]'s pair one level
12718/// down, and the first shape here whose luma block is a single mi row (or
12719/// column).
12720///
12721/// What is new at this size is CHROMA. `is_chroma_reference`
12722/// (`av1_common_int.h`) is false for a 4:2:0 block one mi tall (wide) on an
12723/// EVEN mi row (column), so strips 0 and 2 read no `uv_mode`/`cfl_alpha`/
12724/// `angle_delta_uv` at all and code no chroma residual; strips 1 and 3 close
12725/// the pair and carry the chroma of the whole 16x8 (8x16) luma pair --
12726/// `setup_pred_plane`'s own `if (subsampling_y && (mi_row & 1) &&
12727/// mi_size_high[bsize] == 1) mi_row -= 1` offset, i.e. an 8x4 (4x8) chroma
12728/// transform at the PAIR's origin, with CfL averaging over the pair's luma.
12729///
12730/// Tables: LUMA `TX_16X4`/`TX_4X16` averages to the 8x8 entropy context
12731/// ((0 + 2 + 1) >> 1 = 1) with 64 coded positions, so its CDF set is
12732/// [`TxbSet::LumaRect16x4`] (`Luma8`'s tables, the `TX_4X4` `tx_type` row);
12733/// scans are [`SCAN_16X4`]/[`SCAN_4X16`]. CHROMA `TX_8X4`/`TX_4X8` is
12734/// [`TxbSet::ChromaRect8x4`] with [`SCAN_8X4`]/[`SCAN_4X8`]. Angle deltas ARE
12735/// coded (`av1_use_angle_delta` compares the BLOCK_SIZES_ALL enum index, and
12736/// BLOCK_16X4 is 17), and so is `use_filter_intra` (both sides <= 32) off this
12737/// shape's own CDF row.
12738///
12739/// A split transform (`tx_depth != 0`, `sub_tx_size_map[TX_16X4] == TX_8X4`)
12740/// refuses by name rather than guess-decode.
12741#[allow(clippy::too_many_arguments)]
12742fn decode_rect4_16(
12743 dec: &mut SymbolDecoder,
12744 cdfs: &mut Cdfs,
12745 neighbours: &mut Neighbours,
12746 at16: (usize, usize),
12747 horz: bool,
12748 y: &mut PlaneBuf<'static>,
12749 u: &mut PlaneBuf<'static>,
12750 v: &mut PlaneBuf<'static>,
12751 enable_filter_intra: bool,
12752 allow_screen_content_tools: bool,
12753 base_q_idx: u8,
12754 tx_select: bool,
12755 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
12756) -> Result<()> {
12757 let (r, c) = at16;
12758 let (mi_row0, mi_col0) = (r * (SUB / MI), c * (SUB / MI));
12759 let (bw, bh) = if horz { (16, 4) } else { (4, 16) };
12760 let (_mi_w, _mi_h) = (bw / MI, bh / MI);
12761 let _scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
12762 let _chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
12763 let mut prev: Option<((usize, usize), usize)> = None;
12764 let mut last_mode = DC_PRED;
12765 let mut last_uv_mode = DC_PRED;
12766 for i in 0..4usize {
12767 let lmi = if horz {
12768 (mi_row0 + i, mi_col0)
12769 } else {
12770 (mi_row0, mi_col0 + i)
12771 };
12772 let has_chroma = i % 2 == 1;
12773 let (mode, uv, _tx) = decode_rect4_16_strip(
12774 dec,
12775 cdfs,
12776 neighbours,
12777 lmi,
12778 horz,
12779 has_chroma,
12780 prev,
12781 y,
12782 u,
12783 v,
12784 enable_filter_intra,
12785 allow_screen_content_tools,
12786 base_q_idx,
12787 tx_select,
12788 reduced_tx_set, fctx,
12789 )?;
12790 if let Some(m) = uv {
12791 last_uv_mode = m;
12792 }
12793 last_mode = mode;
12794 prev = Some((lmi, mode));
12795 }
12796 // The coarse 16-px cell holds one entry for the whole 16x16: the last
12797 // strip is what a block below (right) sees through it, the mi-exact maps
12798 // above answering everything finer.
12799 neighbours.above_mode[c] = last_mode;
12800 neighbours.left_mode[r] = last_mode;
12801 neighbours.above_uv_mode[c] = last_uv_mode;
12802 neighbours.left_uv_mode[r] = last_uv_mode;
12803 neighbours.above_side[c] = bw;
12804 neighbours.left_side[r] = bh;
12805 Ok(())
12806}
12807
12808/// One 16x4 / 4x16 strip of a 16x16-level 1:4 partition, intra-coded --
12809/// [`decode_rect4_16`]'s per-strip body, lifted (lane-intra16x4) so the INTER
12810/// block path can decode a SINGLE intra strip of a partition whose other
12811/// strips are inter. `prev` is the previous strip's `(mi, mode)` (the
12812/// key-frame caller's coarse-cell stand-in; `None` on the inter path, where
12813/// every strip publishes its own mi-exact mode). Returns
12814/// `(y_mode, uv_predict_mode when this strip closes the 4:2:0 chroma pair)`.
12815/// Intrabc reconstruction for a rect strip that OWNS its chroma
12816/// (`bw/2 x bh/2` at the strip origin). 16x4/4x16 is not this shape -- that
12817/// pair goes through [`decode_rect4_16_intrabc`].
12818///
12819/// This is the same control flow as the unmerged lane's `decode_intrabc_rect`
12820/// (predict once, then one residual per transform unit on the INTER sets,
12821/// chroma inherits luma's `tx_type`), written against the helpers that exist
12822/// on this tree so a 2:1 strip no longer hides the 16x4 pair witness. The
12823/// merge with lane-av1-intrabc should keep one of the two bodies; the call
12824/// shape is the same.
12825#[allow(clippy::too_many_arguments)]
12826fn decode_intrabc_owned_rect(
12827 dec: &mut SymbolDecoder,
12828 cdfs: &mut Cdfs,
12829 neighbours: &mut Neighbours,
12830 (mi_r, mi_c): (usize, usize),
12831 (bw, bh): (usize, usize),
12832 skip: bool,
12833 (dv_row, dv_col): (i32, i32),
12834 y: &mut PlaneBuf<'static>,
12835 u: &mut PlaneBuf<'static>,
12836 v: &mut PlaneBuf<'static>,
12837 base_q_idx: u8,
12838 tx_select: bool,
12839 reduced_tx_set: bool,
12840 fctx: &crate::decode::FrameCtx,
12841) -> Result<()> {
12842 let _ = base_q_idx;
12843 let (px, py) = (mi_c * MI, mi_r * MI);
12844 let (cw, ch) = (bw / 2, bh / 2);
12845 let side = bw.max(bh);
12846 let cside = cw.max(ch);
12847 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
12848 let saved_tx = fctx.tx_select_inter.with(std::cell::Cell::get);
12849 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
12850 // `read_block_tx_size_rect` keys on this cell. A key frame forces it
12851 // false; the real bit is the caller's `tx_select`. Restored before return.
12852 fctx.tx_select_inter.with(|c| c.set(tx_select));
12853 let restore = ReducedTxRestore { fctx, saved_reduced, saved_tx };
12854
12855 flush_recon(fctx, y, u, v);
12856 let pred_y = predict_intrabc_window(y, px, py, bw, bh, dv_col, dv_row, true, side, fctx);
12857 let pred_u = predict_intrabc_window(u, px / 2, py / 2, cw, ch, dv_col, dv_row, false, cside, fctx);
12858 let pred_v = predict_intrabc_window(v, px / 2, py / 2, cw, ch, dv_col, dv_row, false, cside, fctx);
12859
12860 let mi_cols = 2 * y.true_width.div_ceil(8);
12861 let mi_rows = 2 * y.true_height.div_ceil(8);
12862 let leaves = read_block_tx_size_rect(
12863 dec, cdfs, neighbours, (mi_r, mi_c), (bw, bh), (mi_cols, mi_rows), skip, fctx,
12864 )?;
12865 let mut luma_tx_type = TxType::DctDct;
12866 let luma_grid;
12867 let u_grid;
12868 let v_grid;
12869 if skip {
12870 // `reconstruct_mc_rect` indexes the residual at the square stride.
12871 // `bw * bh` underruns on a VERT strip (8x16: stride 16, 16 rows, index 136).
12872 push_mc_rect(0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * bh], fctx);
12873 push_mc_rect(1, px / 2, py / 2, cside, cw, ch, Pred::Inline(&pred_u, cside), &ZERO_RESIDUAL[..cside * ch], fctx);
12874 push_mc_rect(2, px / 2, py / 2, cside, cw, ch, Pred::Inline(&pred_v, cside), &ZERO_RESIDUAL[..cside * ch], fctx);
12875 if let Some(ls) = leaves.as_ref() {
12876 // libaom `av1_reset_entropy_context` (`if (mbmi->skip_txfm)`,
12877 // decodeframe.c:1262 -> blockd.c:58): a SKIPPED block zeroes its
12878 // whole entropy-band footprint. The non-skip arm below writes
12879 // those bands per transform unit and the tail's
12880 // `record_split_luma_rect_mi` writes chroma only, so without
12881 // this walk a skipped strip whose `leaves` resolved (every
12882 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
12883 // returns the 4x4 grid before it looks at `skip`) leaked the
12884 // PREVIOUS occupant's luma bands into the next block's
12885 // `txb_skip`/coefficient contexts (lane-av1-loss64: the skipped
12886 // 8x16 intrabc strip at mi(48,66) of the 320x242 lossless sb128
12887 // stream left a stale 7 in left[48] and mi(48,68)'s first
12888 // transform unit read `txb_skip_ctx` 3 where aomdec reads 1).
12889 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
12890 for &(row, col, tw, th) in ls {
12891 neighbours.record_mi_luma_rect(
12892 (mi_r + row, mi_c + col),
12893 tw,
12894 th,
12895 &ZERO_RESIDUAL[..tw * th],
12896 );
12897 }
12898 }
12899 luma_grid = Grid::Zero(side * side);
12900 u_grid = Grid::Zero(cside * cside);
12901 v_grid = Grid::Zero(cside * cside);
12902 } else if let Some(ls) = leaves.as_ref() {
12903 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
12904 let tu_mi = (mi_r + row, mi_c + col);
12905 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
12906 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
12907 let (g, tt) = if tw == th {
12908 read_inter_plane(
12909 dec, cdfs, inter_txbset_for(tw, reduced_tx_set), &default_scan(tw.min(32)),
12910 0, neighbours.around_mi(tu_mi, tw)[0], 0, y, tu_px, tu_py, tw, base_q_idx,
12911 tu_pred, None, Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)), fctx,
12912 )?
12913 } else {
12914 read_inter_plane_rect(
12915 dec, cdfs, rect_inter_luma_set(tw, th, fctx)?, (tw, th), side, 0,
12916 neighbours.around_mi_rect(tu_mi, tw, th)[0], 0, y, tu_px, tu_py, tu_pred,
12917 None, Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)), fctx,
12918 )?
12919 };
12920 if idx == 0 {
12921 luma_tx_type = tt;
12922 }
12923 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
12924 if tw != th {
12925 neighbours.fill_lf_grid_leaf_luma((tu_mi.0, tu_mi.1), tw / MI, th / MI, tw as u8, th as u8);
12926 }
12927 }
12928 luma_grid = Grid::Zero(side * side);
12929 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
12930 let (ug, _) = read_inter_plane_rect(
12931 dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0,
12932 u, px / 2, py / 2, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx,
12933 )?;
12934 let (vg, _) = read_inter_plane_rect(
12935 dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0,
12936 v, px / 2, py / 2, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx,
12937 )?;
12938 u_grid = ug;
12939 v_grid = vg;
12940 } else {
12941 let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
12942 let (g, tt) = read_inter_plane_rect(
12943 dec, cdfs, rect_inter_luma_set(bw, bh, fctx)?, (bw, bh), side, 0, around[0], 0,
12944 y, px, py, Pred::Inline(&pred_y, side), None, None, fctx,
12945 )?;
12946 luma_tx_type = tt;
12947 luma_grid = g;
12948 let (ug, _) = read_inter_plane_rect(
12949 dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0,
12950 u, px / 2, py / 2, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx,
12951 )?;
12952 let (vg, _) = read_inter_plane_rect(
12953 dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0,
12954 v, px / 2, py / 2, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx,
12955 )?;
12956 u_grid = ug;
12957 v_grid = vg;
12958 }
12959 drop(restore);
12960 if leaves.is_some() {
12961 neighbours.record_split_luma_rect_mi((mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, [&u_grid, &v_grid]);
12962 } else {
12963 neighbours.record_rect_mi((mi_r, mi_c), bw, bh, DC_PRED, DC_PRED, &[&luma_grid, &u_grid, &v_grid]);
12964 }
12965 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
12966 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
12967 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
12968 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, bw.min(64) as u8, bh.min(64) as u8, 0, fctx);
12969 record_intrabc_mi_rect(mi_r, mi_c, bw / MI, bh / MI, Some((dv_row, dv_col)), neighbours, fctx);
12970 let _ = luma_tx_type;
12971 Ok(())
12972}
12973
12974fn predict_intrabc_window(
12975 plane: &PlaneBuf<'_>,
12976 px: usize,
12977 py: usize,
12978 w: usize,
12979 h: usize,
12980 dv_col: i32,
12981 dv_row: i32,
12982 luma: bool,
12983 stride: usize,
12984 fctx: &crate::decode::FrameCtx,
12985) -> Vec<u16> {
12986 let mut dense = vec![0u16; w * h];
12987 mc::predict_with_filter(
12988 &plane.data, plane.width, plane.true_width, plane.true_height,
12989 mv_to_q4(px, dv_col, luma), mv_to_q4(py, dv_row, luma),
12990 w, h, mc::InterpFilterKind::Bilinear, &mut dense, fctx,
12991 );
12992 let mut laid = vec![0u16; stride * stride];
12993 for row in 0..h {
12994 laid[row * stride..][..w].copy_from_slice(&dense[row * w..][..w]);
12995 }
12996 laid
12997}
12998
12999struct ReducedTxRestore<'a> {
13000 fctx: &'a crate::decode::FrameCtx,
13001 saved_reduced: bool,
13002 saved_tx: bool,
13003}
13004impl Drop for ReducedTxRestore<'_> {
13005 fn drop(&mut self) {
13006 self.fctx.reduced_tx_set_inter.with(|c| c.set(self.saved_reduced));
13007 self.fctx.tx_select_inter.with(|c| c.set(self.saved_tx));
13008 }
13009}
13010
13011/// Reconstruction of one intrabc 16x4 / 4x16 strip (lane-av1-rect14).
13012///
13013/// A 1:4 strip is a PAIR. Both children share one chroma block, and only the
13014/// odd-mi member codes it (`is_chroma_reference`, `av1_common_int.h:1454`:
13015/// the bottom strip of a `HORZ_4`, the right strip of a `VERT_4`). The chroma
13016/// plane block is `ss_size_lookup[BLOCK_16X4][1][1] == BLOCK_8X4` (and
13017/// `BLOCK_4X8` for `VERT_4`) at the PAIR origin -- `setup_pred_plane`'s
13018/// `mi_row -= 1` when the block is one mi tall on an odd row. Luma is this
13019/// strip's own footprint, copied from this strip's DV. The block is
13020/// `is_inter_block`, so the residual uses the INTER sets and chroma inherits
13021/// the luma unit's coded `tx_type`.
13022///
13023/// Not [`decode_intrabc_rect`]: that helper (lane-av1-intrabc, not on this
13024/// tree) predicts chroma at `bw/2 x bh/2` of the strip itself. At 16x4 that
13025/// is an 8x2 half-pair at the odd strip -- wrong size, wrong origin, and it
13026/// would code chroma on every strip.
13027#[allow(clippy::too_many_arguments)]
13028fn decode_rect4_16_intrabc(
13029 dec: &mut SymbolDecoder,
13030 cdfs: &mut Cdfs,
13031 neighbours: &mut Neighbours,
13032 lmi: (usize, usize),
13033 horz: bool,
13034 has_chroma: bool,
13035 skip: bool,
13036 (dv_row, dv_col): (i32, i32),
13037 y: &mut PlaneBuf<'static>,
13038 u: &mut PlaneBuf<'static>,
13039 v: &mut PlaneBuf<'static>,
13040 base_q_idx: u8,
13041 tx_select: bool,
13042 reduced_tx_set: bool,
13043 fctx: &crate::decode::FrameCtx,
13044) -> Result<(usize, Option<usize>, (usize, usize))> {
13045 let _ = base_q_idx;
13046 hit!(RECT4_16_INTRABC_HITS);
13047 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
13048 let (mi_w, mi_h) = (bw / MI, bh / MI);
13049 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
13050 let side = bw.max(bh);
13051 // `rect_inter_luma_set` reads the frame cell. A key frame's tile decoder
13052 // publishes `reduced_tx_set` into it; set it here too so a caller that
13053 // passed the bit explicitly cannot disagree with the set we read.
13054 let saved_reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
13055 fctx.reduced_tx_set_inter.with(|c| c.set(reduced_tx_set));
13056 let restored = scopeguard_reduced(fctx, saved_reduced);
13057
13058 flush_recon(fctx, y, u, v);
13059 let mut pred_y_dense = vec![0u16; bw * bh];
13060 mc::predict_with_filter(
13061 &y.data, y.width, y.true_width, y.true_height,
13062 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
13063 bw, bh, mc::InterpFilterKind::Bilinear, &mut pred_y_dense, fctx,
13064 );
13065 let mut pred_y = vec![0u16; side * side];
13066 for row in 0..bh {
13067 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
13068 }
13069
13070 let (pw, ph) = if horz { (16usize, 8usize) } else { (8, 16) };
13071 let (cw, ch) = (pw / 2, ph / 2);
13072 let pair_mi = if has_chroma {
13073 if horz { (lmi.0 - 1, lmi.1) } else { (lmi.0, lmi.1 - 1) }
13074 } else {
13075 lmi
13076 };
13077 let (cpx, cpy) = if has_chroma {
13078 (pair_mi.1 * MI / 2, pair_mi.0 * MI / 2)
13079 } else {
13080 (0, 0)
13081 };
13082 let cside = cw.max(ch);
13083 let (pred_u, pred_v) = if has_chroma {
13084 let mut ud = vec![0u16; cw * ch];
13085 mc::predict_with_filter(
13086 &u.data, u.width, u.true_width, u.true_height,
13087 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
13088 cw, ch, mc::InterpFilterKind::Bilinear, &mut ud, fctx,
13089 );
13090 let mut us = vec![0u16; cside * cside];
13091 for row in 0..ch {
13092 us[row * cside..][..cw].copy_from_slice(&ud[row * cw..][..cw]);
13093 }
13094 let mut vd = vec![0u16; cw * ch];
13095 mc::predict_with_filter(
13096 &v.data, v.width, v.true_width, v.true_height,
13097 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
13098 cw, ch, mc::InterpFilterKind::Bilinear, &mut vd, fctx,
13099 );
13100 let mut vs = vec![0u16; cside * cside];
13101 for row in 0..ch {
13102 vs[row * cside..][..cw].copy_from_slice(&vd[row * cw..][..cw]);
13103 }
13104 (us, vs)
13105 } else {
13106 (Vec::new(), Vec::new())
13107 };
13108
13109 // Key-frame `tx_select` is the parameter. `tx_select_inter` is forced
13110 // false for a key frame, so `read_block_tx_size_rect` would skip the
13111 // symbol; read it here against the parameter the intra path already uses.
13112 // A skipped intrabc block predicts the whole footprint once and codes
13113 // no residual (`decode_token_recon_block`'s inter branch). Lossless
13114 // still forces TX_4X4 when the block is coded.
13115 let leaves = if skip || (!lossless(fctx) && !tx_select) {
13116 None
13117 } else if lossless(fctx) {
13118 let mut leaves = Vec::new();
13119 for row in 0..bh / MI {
13120 for col in 0..bw / MI {
13121 leaves.push((row, col, 4usize, 4usize));
13122 }
13123 }
13124 Some(leaves)
13125 } else {
13126 let ctx = txfm_partition_ctx_rect(
13127 neighbours.above_txfm[lmi.1],
13128 neighbours.left_txfm[lmi.0],
13129 side,
13130 bw,
13131 bh,
13132 );
13133 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
13134 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
13135 let (rng, _) = dec.debug_state();
13136 eprintln!(
13137 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
13138 lmi.0, lmi.1, u8::from(split)
13139 );
13140 }
13141 if !split {
13142 None
13143 } else {
13144 let (sub_w, sub_h) = sub_tx_size_map(bw, bh);
13145 let mi_cols = 2 * y.true_width.div_ceil(8);
13146 let mi_rows = 2 * y.true_height.div_ceil(8);
13147 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(lmi.1));
13148 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(lmi.0));
13149 let mut out = Vec::new();
13150 for row in (0..bh / MI).step_by(sub_h / MI) {
13151 for col in (0..bw / MI).step_by(sub_w / MI) {
13152 read_var_tx_size(
13153 dec, cdfs, neighbours, lmi, side, (max_w_mi, max_h_mi),
13154 (sub_w, sub_h), 1, row, col, &mut out,
13155 );
13156 }
13157 }
13158 Some(out)
13159 }
13160 };
13161 let (tx_w, tx_h) = leaves.as_ref().and_then(|ls| ls.first()).map_or((bw, bh), |l| (l.2, l.3));
13162
13163 let mut luma_tx_type = TxType::DctDct;
13164 let luma_grid;
13165 let mut u_grid = Grid::Zero(cw * ch);
13166 let mut v_grid = Grid::Zero(cw * ch);
13167 let chroma_stamped_per_unit;
13168
13169 if skip {
13170 push_mc_rect(
13171 0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * bh], fctx,
13172 );
13173 luma_grid = Grid::Zero(bw * bh);
13174 if has_chroma {
13175 push_mc_rect(
13176 1, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_u, cside),
13177 &ZERO_RESIDUAL[..cside * ch], fctx,
13178 );
13179 push_mc_rect(
13180 2, cpx, cpy, cside, cw, ch, Pred::Inline(&pred_v, cside),
13181 &ZERO_RESIDUAL[..cside * ch], fctx,
13182 );
13183 }
13184 chroma_stamped_per_unit = false;
13185 } else if let Some(ls) = leaves.as_ref() {
13186 if lossless(fctx) {
13187 for &(row, col, _tw, _th) in ls {
13188 let tu_mi = (lmi.0 + row, lmi.1 + col);
13189 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
13190 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
13191 let (g, _) = read_inter_plane(
13192 dec, cdfs,
13193 if reduced_tx_set { TxbSet::Luma4Inter } else { TxbSet::Luma4InterSet1 },
13194 &default_scan(4), 0, neighbours.around_mi(tu_mi, 4)[0], 0,
13195 y, tu_px, tu_py, 4, base_q_idx, tu_pred, None,
13196 Some(neighbours.luma_skip_ctx(tu_mi, 1)), fctx,
13197 )?;
13198 neighbours.record_mi_luma_rect(tu_mi, 4, 4, &g);
13199 }
13200 } else {
13201 for (idx, &(row, col, tw, th)) in ls.iter().enumerate() {
13202 let tu_mi = (lmi.0 + row, lmi.1 + col);
13203 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
13204 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
13205 let (g, tt) = if tw == th {
13206 read_inter_plane(
13207 dec, cdfs, inter_txbset_for(tw, reduced_tx_set),
13208 &default_scan(tw.min(32)), 0, neighbours.around_mi(tu_mi, tw)[0], 0,
13209 y, tu_px, tu_py, tw, base_q_idx, tu_pred, None,
13210 Some(neighbours.luma_skip_ctx(tu_mi, tw / MI)), fctx,
13211 )?
13212 } else {
13213 read_inter_plane_rect(
13214 dec, cdfs, rect_inter_luma_set(tw, th, fctx)?, (tw, th), side, 0,
13215 neighbours.around_mi_rect(tu_mi, tw, th)[0], 0, y, tu_px, tu_py, tu_pred,
13216 None, Some(neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI)), fctx,
13217 )?
13218 };
13219 if idx == 0 {
13220 luma_tx_type = tt;
13221 }
13222 neighbours.record_mi_luma_rect(tu_mi, tw, th, &g);
13223 }
13224 }
13225 luma_grid = Grid::Zero(bw * bh);
13226 chroma_stamped_per_unit = has_chroma && lossless(fctx);
13227 if has_chroma && lossless(fctx) {
13228 let (mut uo, mut vo) = (Vec::new(), Vec::new());
13229 read_inter_chroma_lossless(
13230 dec, cdfs, neighbours, u, v,
13231 Pred::Inline(&pred_u, cside), Pred::Inline(&pred_v, cside),
13232 pair_mi, (cpx, cpy), (0, 0), (cw, ch), (cw, ch), cside, 0, base_q_idx,
13233 &mut uo, &mut vo, fctx,
13234 )?;
13235 u_grid = if uo.is_empty() { Grid::Zero(cw * ch) } else { Grid::Own(uo) };
13236 v_grid = if vo.is_empty() { Grid::Zero(cw * ch) } else { Grid::Own(vo) };
13237 } else if has_chroma {
13238 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
13239 let (ug, _) = read_inter_plane_rect(
13240 dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0,
13241 u, cpx, cpy, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx,
13242 )?;
13243 u_grid = ug;
13244 let (vg, _) = read_inter_plane_rect(
13245 dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0,
13246 v, cpx, cpy, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx,
13247 )?;
13248 v_grid = vg;
13249 }
13250 } else {
13251 let around = neighbours.around_mi_rect(lmi, bw, bh);
13252 let (g, tt) = read_inter_plane_rect(
13253 dec, cdfs, rect_inter_luma_set(bw, bh, fctx)?, (bw, bh), side, 0, around[0], 0,
13254 y, px, py, Pred::Inline(&pred_y, side), None, None, fctx,
13255 )?;
13256 luma_tx_type = tt;
13257 luma_grid = g;
13258 chroma_stamped_per_unit = false;
13259 if has_chroma {
13260 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
13261 let (ug, _) = read_inter_plane_rect(
13262 dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 1, around[1], 0,
13263 u, cpx, cpy, Pred::Inline(&pred_u, cside), Some(luma_tx_type), None, fctx,
13264 )?;
13265 u_grid = ug;
13266 let (vg, _) = read_inter_plane_rect(
13267 dec, cdfs, rect_inter_chroma_set(cw, ch)?, (cw, ch), cside, 2, around[2], 0,
13268 v, cpx, cpy, Pred::Inline(&pred_v, cside), Some(luma_tx_type), None, fctx,
13269 )?;
13270 v_grid = vg;
13271 }
13272 }
13273 drop(restored);
13274
13275 if leaves.is_none() {
13276 neighbours.record_mi_luma_rect(lmi, bw, bh, &luma_grid);
13277 }
13278 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, DC_PRED);
13279 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
13280 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
13281 for cell in 0..mi_w {
13282 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
13283 *slot = bw as u8;
13284 }
13285 }
13286 for cell in 0..mi_h {
13287 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
13288 *slot = bh as u8;
13289 }
13290 }
13291 let mut last_uv = None;
13292 if has_chroma {
13293 hit!(RECT4_16_CHROMA_HITS);
13294 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, DC_PRED);
13295 if !chroma_stamped_per_unit {
13296 let u_state = neighbour_state(&u_grid);
13297 let v_state = neighbour_state(&v_grid);
13298 let round_up_even = |n: usize| n.div_ceil(2) * 2;
13299 let bound_h = round_up_even(neighbours.mi_rows);
13300 let bound_w = round_up_even(neighbours.mi_cols);
13301 for cell in 0..(ph / MI) {
13302 if pair_mi.0 + cell < bound_h
13303 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
13304 {
13305 slot[1] = u_state;
13306 slot[2] = v_state;
13307 }
13308 }
13309 for cell in 0..(pw / MI) {
13310 if pair_mi.1 + cell < bound_w
13311 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
13312 {
13313 slot[1] = u_state;
13314 slot[2] = v_state;
13315 }
13316 }
13317 }
13318 last_uv = Some(DC_PRED);
13319 }
13320 if horz {
13321 hit!(RECT4_16_HORZ_HITS);
13322 } else {
13323 hit!(RECT4_16_VERT_HITS);
13324 }
13325 record_strip_palette(neighbours, lmi, bw, bh, 0, [0u16; 8], 0, [0u16; 8]);
13326 if leaves.is_none() {
13327 // Skip and TX_MODE_LARGEST publish the block size (`set_txfm_ctxs`
13328 // with `skip && is_inter`, or the unsplit unit). A split tree already
13329 // published per leaf inside `read_var_tx_size`.
13330 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
13331 }
13332 record_intrabc_mi_rect(
13333 lmi.0, lmi.1, mi_w, mi_h, Some((dv_row, dv_col)), neighbours, fctx,
13334 );
13335 Ok((DC_PRED, last_uv, (tx_w, tx_h)))
13336}
13337
13338/// Restores `reduced_tx_set_inter` when the intrabc pair reader returns,
13339/// including through `?`.
13340struct ReducedRestore<'a> {
13341 fctx: &'a crate::decode::FrameCtx,
13342 saved: bool,
13343}
13344impl Drop for ReducedRestore<'_> {
13345 fn drop(&mut self) {
13346 self.fctx.reduced_tx_set_inter.with(|c| c.set(self.saved));
13347 }
13348}
13349fn scopeguard_reduced(fctx: &crate::decode::FrameCtx, saved: bool) -> ReducedRestore<'_> {
13350 ReducedRestore { fctx, saved }
13351}
13352
13353#[allow(clippy::too_many_arguments)]
13354fn decode_rect4_16_strip(
13355 dec: &mut SymbolDecoder,
13356 cdfs: &mut Cdfs,
13357 neighbours: &mut Neighbours,
13358 lmi: (usize, usize),
13359 horz: bool,
13360 has_chroma: bool,
13361 prev: Option<((usize, usize), usize)>,
13362 y: &mut PlaneBuf<'static>,
13363 u: &mut PlaneBuf<'static>,
13364 v: &mut PlaneBuf<'static>,
13365 enable_filter_intra: bool,
13366 allow_screen_content_tools: bool,
13367 base_q_idx: u8,
13368 tx_select: bool,
13369 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
13370) -> Result<(usize, Option<usize>, (usize, usize))> {
13371 let (r, c) = (lmi.0 / (SUB / MI), lmi.1 / (SUB / MI));
13372 let (bw, bh) = if horz { (16usize, 4usize) } else { (4, 16) };
13373 let (mi_w, mi_h) = (bw / MI, bh / MI);
13374 let scan: &[u16] = if horz { &SCAN_16X4 } else { &SCAN_4X16 };
13375 let chroma_scan: &[u16] = if horz { &SCAN_8X4 } else { &SCAN_4X8 };
13376 let mut last_uv_mode: Option<usize> = None;
13377 // `decode_block_rect4`'s own neighbour rule: the coarse 16-px cell
13378 // aliases all four strips onto one entry, so the mi-exact map wins and
13379 // the previous strip stands in on the split axis.
13380 let mut above_mode = neighbours.above_mode[c];
13381 let mut left_mode = neighbours.left_mode[r];
13382 if let Some(((pr, pc), pmode)) = prev {
13383 if pc == lmi.1 && lmi.0 == pr + mi_h {
13384 above_mode = pmode;
13385 } else if pr == lmi.0 && lmi.1 == pc + mi_w {
13386 left_mode = pmode;
13387 }
13388 }
13389 let (above_mode, left_mode) =
13390 neighbours.modes_above_left_mi(lmi.0, lmi.1, (above_mode, left_mode));
13391 // lane-kf900 r4: the strip's real palette ctx + colour cache (see
13392 // [`decode_block_rect4`]); `None`/`&[]` here read `palette_y_mode`
13393 // off CDF row 0 and every cache hit off an empty cache.
13394 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(lmi);
13395 let palette_uv_cache = neighbours.palette_uv_cache_mi(lmi);
13396 let (
13397 skip,
13398 mode,
13399 angle_delta_y,
13400 uv_mode,
13401 angle_delta_uv,
13402 alpha,
13403 filter_intra,
13404 palette_y,
13405 palette_uv,
13406 intrabc,
13407 ) = read_intra_mode_rect(
13408 dec,
13409 cdfs,
13410 above_mode,
13411 left_mode,
13412 true,
13413 has_chroma,
13414 bw,
13415 bh,
13416 enable_filter_intra,
13417 neighbours.skip_txfm_ctx(lmi.0, lmi.1),
13418 allow_screen_content_tools,
13419 Some((palette_ctx, &palette_cache)),
13420 &palette_uv_cache,
13421 lmi.0,
13422 lmi.1, fctx,
13423 )?;
13424 if let Some(dv) = intrabc {
13425 return decode_rect4_16_intrabc(
13426 dec, cdfs, neighbours, lmi, horz, has_chroma, skip, dv, y, u, v,
13427 base_q_idx, tx_select, reduced_tx_set, fctx,
13428 );
13429 }
13430 if palette_y.is_some() || palette_uv.is_some() {
13431 hit!(RECT4_PALETTE_HITS);
13432 }
13433 // The colour-index map through the base colours IS the prediction.
13434 // Chroma's map is the PAIR's 8x4 (4x8) block, matching the one
13435 // chroma transform this closing strip codes.
13436 let palette_y_buf: Option<Vec<u16>> = palette_y
13437 .as_ref()
13438 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
13439 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
13440 (
13441 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
13442 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
13443 )
13444 });
13445 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
13446 if smooth_neighbor {
13447 hit!(SMOOTH_LUMA_HITS);
13448 }
13449 if filter_intra.is_some() {
13450 hit!(FILTER_INTRA_RECT_HITS);
13451 }
13452 // `bsize_to_tx_size_cat(BLOCK_16X4)`: `max_txsize_rect_lookup` is
13453 // TX_16X4 and `sub_tx_size_map` reaches TX_4X4 in two steps, so the
13454 // depth symbol is the 3-symbol `tx_size_cat1` -- not the 2-symbol
13455 // `cat0` a 4x8 leaf reads nor the `cat2` a 32x8 strip does.
13456 let depth = if tx_select {
13457 // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands
13458 // (`get_tx_size_context`, libaom `pred_common.h:342`).
13459 let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
13460 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
13461 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
13462 eprintln!(
13463 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
13464 lmi.0,
13465 lmi.1,
13466 dec.debug_state().0
13467 );
13468 }
13469 d
13470 } else {
13471 0
13472 };
13473 if depth != 0 {
13474 hit!(TX_DEPTH_HITS);
13475 hit!(RECT4_16_SPLIT_HITS);
13476 }
13477 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
13478 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
13479 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
13480 neighbours.record_mode_mi(lmi.0, lmi.1, mi_w, mi_h, mode);
13481 if depth != 0 || lossless(fctx) {
13482 // [`decode_rect_split`]'s per-unit walk, inlined because the
13483 // CHROMA of this shape belongs to the strip's 4:2:0 pair, not to
13484 // the strip (that function codes one chroma transform per block).
13485 // depth 1 is the 2:1 rect unit TX_8X4/TX_4X8
13486 // (`sub_tx_size_map[TX_16X4]`), depth 2 the square TX_4X4; each
13487 // unit predicts off the units before it in raster order.
13488 let rect_unit = tx_w != tx_h;
13489 let zero_tu = vec![0i32; tx_w * tx_h];
13490 for tu_row in 0..bh / tx_h {
13491 for tu_col in 0..bw / tx_w {
13492 let tu_mi = (lmi.0 + tu_row * (tx_h / MI), lmi.1 + tu_col * (tx_w / MI));
13493 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
13494 let tu_reach = Reach::of_tu(
13495 bw,
13496 bh,
13497 tu_col * tx_w,
13498 tu_row * tx_h,
13499 tx_w,
13500 tx_h,
13501 reach,
13502 );
13503 if let Some(b) = &palette_y_buf {
13504 let tu_buf: Vec<u16> = (0..tx_h)
13505 .flat_map(|i| {
13506 let base = (tu_row * tx_h + i) * bw + tu_col * tx_w;
13507 b[base..base + tx_w].iter().copied()
13508 })
13509 .collect();
13510 set_palette_pred(tu_buf, fctx);
13511 }
13512 if skip {
13513 push_intra_rect(0,
13514 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &zero_tu,
13515 None, filter_intra, smooth_neighbor, fctx,
13516 );
13517 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
13518 } else if rect_unit {
13519 // `get_txsize_entropy_ctx(TX_8X4)` is the 8x8 class with
13520 // 32 coded positions and the `TX_4X4` `tx_type` row:
13521 // exactly [`TxbSet::LumaRect4x8`].
13522 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
13523 let tu_skip_ctx =
13524 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI);
13525 let set = if reduced_tx_set {
13526 TxbSet::LumaRect4x8
13527 } else {
13528 TxbSet::LumaRect4x8Set1
13529 };
13530 let tu_scan: &[u16] = if tx_w > tx_h { &SCAN_8X4 } else { &SCAN_4X8 };
13531 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
13532 let (tu_grid, tu_tx_type) = read_coeffs_rect(
13533 dec,
13534 &mut coding,
13535 tu_scan,
13536 tx_w,
13537 tx_h,
13538 tu_skip_ctx,
13539 dc_sign_ctx(tu_around.2),
13540 TxType::DctDct,
13541 )?;
13542 let residual = dequant_and_inverse_typed_wh(
13543 &tu_grid,
13544 tx_w,
13545 tx_h,
13546 crate::decode::bit_depth(fctx),
13547 block_q_idx(fctx),
13548 plane_q_delta(0, fctx).0,
13549 plane_q_delta(0, fctx).1,
13550 tu_tx_type,
13551 );
13552 push_intra_rect(0,
13553 tu_px, tu_py, tx_w, tx_h, mode, angle_delta_y, tu_reach, &residual,
13554 None, filter_intra, smooth_neighbor, fctx,
13555 );
13556 if tu_grid.iter().any(|&l| l != 0) {
13557 hit!(RECT4_16_COEFF_HITS);
13558 }
13559 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
13560 } else {
13561 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
13562 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
13563 let tu_grid = read_plane(
13564 dec,
13565 cdfs,
13566 txbset_for(tx_w, reduced_tx_set),
13567 default_scan(tx_w),
13568 0,
13569 tu_around,
13570 mode,
13571 mode,
13572 angle_delta_y,
13573 tu_reach,
13574 y,
13575 tu_px,
13576 tu_py,
13577 tx_w,
13578 tx_w,
13579 base_q_idx,
13580 None,
13581 filter_intra,
13582 Some(tu_skip_ctx),
13583 smooth_neighbor, fctx,
13584 )?;
13585 if tu_grid.iter().any(|&l| l != 0) {
13586 hit!(RECT4_16_COEFF_HITS);
13587 }
13588 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
13589 }
13590 }
13591 }
13592 } else {
13593 let levels = if skip {
13594 let zeros = Grid::Zero(bw * bh);
13595 if let Some(b) = &palette_y_buf {
13596 set_palette_pred(b.clone(), fctx);
13597 }
13598 push_intra_rect(0,
13599 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
13600 smooth_neighbor, fctx,
13601 );
13602 zeros
13603 } else {
13604 // The strip's luma TU *is* the strip (`plane_bsize ==
13605 // txsize_to_bsize[tx_size]`), so `get_txb_ctx` fixes
13606 // `txb_skip_ctx` at 0.
13607 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
13608 let set = if reduced_tx_set {
13609 TxbSet::LumaRect16x4
13610 } else {
13611 TxbSet::LumaRect16x4Set1
13612 };
13613 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
13614 let (levels, tx_type) = read_coeffs_rect(
13615 dec,
13616 &mut coding,
13617 scan,
13618 bw,
13619 bh,
13620 0,
13621 dc_sign_ctx(around.2),
13622 TxType::DctDct,
13623 )?;
13624 let residual = dequant_and_inverse_typed_wh(
13625 &levels,
13626 bw,
13627 bh,
13628 crate::decode::bit_depth(fctx),
13629 block_q_idx(fctx),
13630 plane_q_delta(0, fctx).0,
13631 plane_q_delta(0, fctx).1,
13632 tx_type,
13633 );
13634 if let Some(b) = &palette_y_buf {
13635 set_palette_pred(b.clone(), fctx);
13636 }
13637 push_intra_rect(0,
13638 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
13639 smooth_neighbor, fctx,
13640 );
13641 hit!(RECT4_16_COEFF_HITS);
13642 levels
13643 };
13644 neighbours.record_mi_luma_rect(lmi, bw, bh, &levels);
13645 }
13646 neighbours.fill_skip_grid_rect(lmi, mi_w, mi_h, skip);
13647 neighbours.fill_lf_grid_rect(lmi, mi_w, mi_h, tx_w as u8, tx_h as u8, 0, fctx);
13648 // `update_partition_context` writes `partition_context_lookup[
13649 // BLOCK_16X4]` over the whole 16x16: full width above, a 4-px side on
13650 // the left (mirrored under VERT_4).
13651 for cell in 0..mi_w {
13652 if let Some(slot) = neighbours.above_side_mi.get_mut(lmi.1 + cell) {
13653 *slot = bw as u8;
13654 }
13655 }
13656 for cell in 0..mi_h {
13657 if let Some(slot) = neighbours.left_side_mi.get_mut(lmi.0 + cell) {
13658 *slot = bh as u8;
13659 }
13660 }
13661 if has_chroma {
13662 hit!(RECT4_16_CHROMA_HITS);
13663 let pair_mi = if horz {
13664 (lmi.0 - 1, lmi.1)
13665 } else {
13666 (lmi.0, lmi.1 - 1)
13667 };
13668 let (pw, ph) = if horz { (16, 8) } else { (8, 16) };
13669 let (ppx, ppy) = (pair_mi.1 * MI, pair_mi.0 * MI);
13670 let (cpx, cpy) = (ppx / 2, ppy / 2);
13671 let (cw, ch) = (pw / 2, ph / 2);
13672 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
13673 if (V_PRED..=D67_PRED).contains(&uv_predict_mode) {
13674 hit!(RECT4_16_CHROMA_DIR_HITS);
13675 }
13676 let pair_reach = Reach::of_rect(pw, ph, ppx, ppy, y.width, y.height, fctx);
13677 // lane-kf1200 r1: the chroma edge-filter type reads the neighbours
13678 // of the CHROMA block, which for a 16x4/4x16 pair is `pair_mi`'s
13679 // 16x8/8x16 region -- libaom builds `chroma_above_mbmi`/
13680 // `chroma_left_mbmi` from `mi[-((mi_row & ss_y) * stride + (mi_col
13681 // & ss_x))]` (`set_mi_offsets`, av1/common/blockd.h ~1050), i.e.
13682 // the pair's top-left luma mi, never this leaf's odd row/column.
13683 // Reading `lmi` here named the leaf directly above (a non-chroma
13684 // -reference 4-row block, `uv_mode == UV_DC_PRED`) and so lost a
13685 // SMOOTH neighbour: filt_type 0 instead of 1 turned
13686 // `av1_use_intra_edge_upsample` on (blk_wh 12 <= 16) for a
13687 // directional chroma strip, moving 4 samples by 1.
13688 let smooth_neighbor_uv =
13689 neighbours.smooth_uv_neighbour(pair_mi.0, pair_mi.1, r, c);
13690 if smooth_neighbor_uv != neighbours.smooth_uv_neighbour_unsnapped(lmi.0, lmi.1, r, c)
13691 {
13692 hit!(RECT4_16_UV_PAIR_FILT_HITS);
13693 }
13694 // lane-av1-rect14: a lossless frame forces TX_4X4 on every plane
13695 // (`av1_get_tx_size`, blockd.h:1381). The pair's chroma block is
13696 // 8x4 (HORZ_4) or 4x8 (VERT_4) -- two TX_4X4s, plane-major
13697 // (`decode_token_recon_block`), not one `ChromaRect8x4`. Reading
13698 // the rect here consumed one symbol block too few and desynced
13699 // the next strip's `skip` (measured: lossless sb128 320x240,
13700 // mi(1,20) uv_mode matched, the following skip did not).
13701 let lossless_pair = lossless(fctx);
13702 let (u_levels, v_levels) = if lossless_pair {
13703 hit!(RECT4_16_LOSSLESS_CHROMA_HITS);
13704 if skip {
13705 for plane in 1..3usize {
13706 for rr in 0..ch / 4 {
13707 for cc in 0..cw / 4 {
13708 let (ox, oy) = (cc * 4, rr * 4);
13709 let cu_reach = tu_reach(
13710 pw, ph, ox * 2, oy * 2, 8, pair_reach, ppx, ppy,
13711 y.width, y.height, fctx,
13712 );
13713 if let Some((ub, vb)) = &palette_uv_bufs {
13714 let buf = if plane == 1 { ub } else { vb };
13715 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
13716 }
13717 push_intra(
13718 plane, cpx + ox, cpy + oy, 4, uv_predict_mode,
13719 angle_delta_uv, cu_reach, &ZERO_RESIDUAL[..16], None, None,
13720 smooth_neighbor_uv, fctx,
13721 );
13722 let cu_mi = (pair_mi.0 + oy / 2, pair_mi.1 + ox / 2);
13723 neighbours.record_mi_chroma(
13724 cu_mi, 8, 8, plane, &ZERO_RESIDUAL[..16],
13725 );
13726 }
13727 }
13728 }
13729 (Grid::Zero(cw * ch), Grid::Zero(cw * ch))
13730 } else {
13731 let scan4 = default_scan(4);
13732 // `get_txb_ctx`: offset 10 (our tables store it at +3)
13733 // when the plane block is larger than the transform.
13734 let offset = Some(3usize);
13735 let mut uo = vec![0i32; cw * ch];
13736 let mut vo = vec![0i32; cw * ch];
13737 for plane in 1..3usize {
13738 for rr in 0..ch / 4 {
13739 for cc in 0..cw / 4 {
13740 let (ox, oy) = (cc * 4, rr * 4);
13741 if cpx + ox >= u.true_width || cpy + oy >= u.true_height {
13742 continue;
13743 }
13744 let cu_mi = (pair_mi.0 + oy / 2, pair_mi.1 + ox / 2);
13745 // One luma-mi cell: the chroma entropy arrays
13746 // are subsampled, and our bands replicate that
13747 // one entry over the unit's two cells
13748 // (`read_intra_chroma_lossless`).
13749 let cu_around = neighbours.around_mi(cu_mi, MI);
13750 let cu_reach = tu_reach(
13751 pw, ph, ox * 2, oy * 2, 8, pair_reach, ppx, ppy,
13752 y.width, y.height, fctx,
13753 );
13754 if let Some((ub, vb)) = &palette_uv_bufs {
13755 let buf = if plane == 1 { ub } else { vb };
13756 set_palette_pred(palette_window(buf, cw, ox, oy, 4, 4), fctx);
13757 }
13758 let buf: &mut PlaneBuf<'static> =
13759 if plane == 1 { &mut *u } else { &mut *v };
13760 let cu_grid = read_plane(
13761 dec, cdfs, TxbSet::Chroma4, &scan4, plane,
13762 cu_around[plane], mode, uv_predict_mode, angle_delta_uv,
13763 cu_reach, buf, cpx + ox, cpy + oy, 4, 4, base_q_idx,
13764 None, None, offset, smooth_neighbor_uv, fctx,
13765 )?;
13766 neighbours.record_mi_chroma(cu_mi, 8, 8, plane, &cu_grid);
13767 hit!(CHROMA_SPLIT_TX_HITS);
13768 let dst = if plane == 1 { &mut uo } else { &mut vo };
13769 for row in 0..4 {
13770 let start = (oy + row) * cw + ox;
13771 dst[start..start + 4]
13772 .copy_from_slice(&cu_grid[row * 4..][..4]);
13773 }
13774 }
13775 }
13776 }
13777 (Grid::Own(uo), Grid::Own(vo))
13778 }
13779 } else if skip {
13780 let zeros = Grid::Zero(cw * ch);
13781 // libaom `predict_and_reconstruct_intra_block` (decodeframe.c
13782 // ~1000) predicts EVERY plane and only guards the residual on
13783 // `mbmi->skip_txfm`, so a skipped `UV_CFL_PRED` block is still
13784 // DC + alpha * luma-AC. Dropping the CfL term here left a
13785 // chroma-only bounded box on ReelC's key frames.
13786 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
13787 if alpha.is_some() {
13788 hit!(CHROMA_SKIP_CFL_HITS);
13789 }
13790 for (_buf, plane) in [(&mut *u, 1usize), (&mut *v, 2)] {
13791 if let Some((ub, vb)) = &palette_uv_bufs {
13792 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
13793 }
13794 push_intra_rect(plane,
13795 cpx,
13796 cpy,
13797 cw,
13798 ch,
13799 uv_predict_mode,
13800 angle_delta_uv,
13801 pair_reach,
13802 &zeros,
13803 alpha
13804 .zip(ac)
13805 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
13806 None,
13807 smooth_neighbor_uv, fctx,
13808 );
13809 }
13810 (zeros.clone(), zeros)
13811 } else {
13812 let around = neighbours.around_mi_rect(pair_mi, pw, ph);
13813 let mut planes = Vec::with_capacity(2);
13814 for plane in 1..3 {
13815 let default_tx = default_intra_tx_type(uv_predict_mode as u8);
13816 let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1);
13817 let mut coding = cdfs.txb(TxbSet::ChromaRect8x4, uv_predict_mode);
13818 let (levels, tx_type) = read_chroma_coeffs_rect(
13819 dec,
13820 &mut coding,
13821 chroma_scan,
13822 cw,
13823 ch,
13824 skip_ctx,
13825 dc_sign_ctx(around[plane].2),
13826 default_tx,
13827 fctx,
13828 )?;
13829 planes.push((levels, tx_type));
13830 }
13831 let (v_levels, v_tx_type) = planes.pop().expect("plane 2");
13832 let (u_levels, u_tx_type) = planes.pop().expect("plane 1");
13833 // CfL averages the luma of the WHOLE pair, the region this one
13834 // chroma transform covers.
13835 let ac = alpha.map(|_| cfl_src_rect(ppx, ppy, pw, ph));
13836 for (plane, _buf, levels, tx_type) in [
13837 (1usize, &mut *u, &u_levels, u_tx_type),
13838 (2, &mut *v, &v_levels, v_tx_type),
13839 ] {
13840 let residual = dequant_and_inverse_typed_wh(
13841 levels,
13842 cw,
13843 ch,
13844 crate::decode::bit_depth(fctx),
13845 block_q_idx(fctx),
13846 plane_q_delta(plane, fctx).0,
13847 plane_q_delta(plane, fctx).1,
13848 tx_type,
13849 );
13850 if let Some((ub, vb)) = &palette_uv_bufs {
13851 set_palette_pred(if plane == 1 { ub.clone() } else { vb.clone() }, fctx);
13852 }
13853 push_intra_rect(plane,
13854 cpx,
13855 cpy,
13856 cw,
13857 ch,
13858 uv_predict_mode,
13859 angle_delta_uv,
13860 pair_reach,
13861 &residual,
13862 alpha
13863 .zip(ac)
13864 .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)),
13865 None,
13866 smooth_neighbor_uv, fctx,
13867 );
13868 }
13869 (u_levels, v_levels)
13870 };
13871 neighbours.record_uv_mode_mi(pair_mi.0, pair_mi.1, pw / MI, ph / MI, uv_predict_mode);
13872 // A lossless pair already stamped each TX_4X4 (`record_mi_chroma`).
13873 // The single-state rewrite below is the non-lossless TX_8X4/TX_4X8.
13874 if !lossless_pair {
13875 // The chroma planes' coefficient context, over the PAIR's mi span
13876 // (`decode_leaf_rect8`'s own rule: a subsampled plane's bound is
13877 // the luma one rounded up to its 4x4 unit).
13878 let u_state = neighbour_state(&u_levels);
13879 let v_state = neighbour_state(&v_levels);
13880 let round_up_even = |n: usize| n.div_ceil(2) * 2;
13881 let bound_h = round_up_even(neighbours.mi_rows);
13882 let bound_w = round_up_even(neighbours.mi_cols);
13883 for cell in 0..(ph / MI) {
13884 if pair_mi.0 + cell < bound_h
13885 && let Some(slot) = neighbours.left.get_mut(pair_mi.0 + cell)
13886 {
13887 slot[1] = u_state;
13888 slot[2] = v_state;
13889 }
13890 }
13891 for cell in 0..(pw / MI) {
13892 if pair_mi.1 + cell < bound_w
13893 && let Some(slot) = neighbours.above.get_mut(pair_mi.1 + cell)
13894 {
13895 slot[1] = u_state;
13896 slot[2] = v_state;
13897 }
13898 }
13899 }
13900 last_uv_mode = Some(uv_predict_mode);
13901 }
13902 if horz {
13903 hit!(RECT4_16_HORZ_HITS);
13904 } else {
13905 hit!(RECT4_16_VERT_HITS);
13906 }
13907 let (pal_y_size, pal_y_colors) =
13908 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
13909 let (pal_uv_size, pal_uv_colors) =
13910 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
13911 record_strip_palette(
13912 neighbours, lmi, bw, bh, pal_y_size, pal_y_colors, pal_uv_size, pal_uv_colors,
13913 );
13914 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
13915 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
13916 // frame): the above row records `tx_size_wide` over the block's width and
13917 // the left column `tx_size_high` over its height. This 1:4 strip reader is
13918 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
13919 // and it published neither band -- so the block after a 64x16 strip read
13920 // the row's init value 64 as its left transform height and took
13921 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
13922 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
13923 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
13924 txfm_partition_update_rect(neighbours, lmi, (tx_w, tx_h), (bw, bh));
13925 Ok((mode, last_uv_mode, (tx_w, tx_h)))
13926}
13927
13928
13929/// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/
13930/// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` /
13931/// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike
13932/// that 32x16/16x32 strip, both dimensions here exceed the 32-coefficient
13933/// cap, so LUMA needs the same corner truncation [`decode_block`] already
13934/// does for a plain 64x64 square (spec 5.11.40): `get_txsize_entropy_ctx`
13935/// resolves TX_64X32/TX_32X64 to TX_64X64 regardless of orientation (see
13936/// this function's own charter/report), so both strips read a real 32x32
13937/// corner through [`read_coeffs`] with [`TxbSet::Luma64`]/[`SCAN_32`] and
13938/// embed it top-left of a zeroed `bw`x`bh` grid, mirroring
13939/// [`read_plane`]'s `tx_side != side` branch generalized to non-square.
13940/// CHROMA (TX_32X16/TX_16X32) resolves to TX_32X32 -- a real, *untruncated*
13941/// `bw/2`x`bh/2` transform via [`read_coeffs_rect`] with
13942/// [`TxbSet::ChromaRect32x16`] and the matching [`SCAN_32X16`]/
13943/// [`SCAN_16X32`], same as [`decode_block_rect`]'s own chroma path. Like
13944/// that function, only the single-transform-unit (`tx_depth == 0`) case is
13945/// supported: a split transform refuses by name rather than guess-decode.
13946#[allow(clippy::too_many_arguments)]
13947fn decode_block_rect64(
13948 dec: &mut SymbolDecoder,
13949 cdfs: &mut Cdfs,
13950 neighbours: &mut Neighbours,
13951 at: (usize, usize),
13952 bw: usize,
13953 bh: usize,
13954 y: &mut PlaneBuf<'static>,
13955 u: &mut PlaneBuf<'static>,
13956 v: &mut PlaneBuf<'static>,
13957 enable_filter_intra: bool,
13958 allow_screen_content_tools: bool,
13959 base_q_idx: u8,
13960 tx_select: bool,
13961 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
13962) -> Result<()> {
13963 let (r, c) = at;
13964 let (px, py) = (c * SUB, r * SUB);
13965 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
13966 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
13967 let palette_uv_cache = neighbours.palette_uv_cache(at);
13968 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv, intrabc) =
13969 read_intra_mode_rect(
13970 dec,
13971 cdfs,
13972 nb_above_mode,
13973 nb_left_mode,
13974 // `is_cfl_allowed` (spec 5.11.5) caps CFL at <=32x32; these
13975 // superblock-level HORZ/VERT strips are 64x32/32x64, so unlike
13976 // `decode_block_rect`'s own 32x16/16x32 strips (where `true` is
13977 // correct), CFL must never be offered here -- passing `true`
13978 // read `uv_mode` off the 14-symbol `uv_mode_cfl` CDF instead of
13979 // the real 13-symbol `uv_mode_no_cfl` one and desynced the tile
13980 // from this block's very first symbol (lane-sbpart r3 bisect).
13981 false,
13982 true,
13983 bw,
13984 bh,
13985 enable_filter_intra,
13986 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
13987 allow_screen_content_tools,
13988 Some((palette_ctx, &palette_cache)),
13989 &palette_uv_cache,
13990 r * (SUB / MI),
13991 c * (SUB / MI), fctx,
13992 )?;
13993 if let Some((dv_row, dv_col)) = intrabc {
13994 return decode_intrabc_owned_rect(
13995 dec, cdfs, neighbours, (r * (SUB / MI), c * (SUB / MI)), (bw, bh), skip,
13996 (dv_row, dv_col), y, u, v, base_q_idx, tx_select, reduced_tx_set, fctx,
13997 );
13998 }
13999 if (palette_y.is_some() || palette_uv.is_some()) && !skip {
14000 // lane-t900 r34: a non-skip palette block on a superblock-level strip
14001 // -- counted so its gate cannot go vacuous (this was a refusal until
14002 // r34; see the gate `a_real_aomenc_palette_stream_with_8x8_leaves_
14003 // decodes_pixel_exact`).
14004 hit!(PALETTE_SB_STRIP_HITS);
14005 }
14006 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
14007 if smooth_neighbor {
14008 hit!(SMOOTH_LUMA_HITS);
14009 }
14010 let smooth_neighbor_uv =
14011 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
14012 if filter_intra.is_some() {
14013 // `filter_intra_size_class_rect` already returns `None` for both
14014 // `(64, 32)` and `(32, 64)` (`av1_filter_intra_allowed_bsize` caps at
14015 // 32 on both axes), so this symbol is never read at this level --
14016 // kept only as the same defensive refusal [`decode_block_rect`] has.
14017 return Err(unsupported(
14018 "filter intra on a superblock-level HORZ/VERT strip (never expected -- \
14019 av1_filter_intra_allowed_bsize caps at 32x32)",
14020 ));
14021 }
14022 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
14023 DC_PRED
14024 } else {
14025 uv_mode
14026 };
14027 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
14028 let depth = if tx_select {
14029 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
14030 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
14031 // intra-only frame publishes them from every block too
14032 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
14033 // 1920x792 128-superblock stream,
14034 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
14035 // `tx_size_cat2` row 1 where libaom reads row 2.
14036 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
14037 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
14038 // counts `sub_tx_size_map` steps from the block's own max rect
14039 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
14040 // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four
14041 // steps, so this level's category is 3 (the same one a 64x64 square
14042 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
14043 // here was a wrong-table read of a real symbol.
14044 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
14045 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
14046 eprintln!(
14047 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
14048 dec.debug_state().0
14049 );
14050 }
14051 d
14052 } else {
14053 0
14054 };
14055 // lane-t900 r1: this strip's own `set_txfm_ctxs` when it is an intra
14056 // block of an INTER frame -- see [`publish_txfm_bands_if_in_inter`].
14057 publish_txfm_bands_if_in_inter(
14058 neighbours,
14059 (mi_r, mi_c),
14060 depth_to_tx_wh(bw, bh, depth, fctx),
14061 (bw, bh), fctx,
14062 );
14063 if depth != 0 || lossless(fctx) {
14064 hit!(TX_DEPTH_HITS);
14065 // lane-rectsplit r1/r4: the superblock-level strip splits its
14066 // transform through the very same per-unit path as its 32x32-level
14067 // sibling; [`depth_to_tx_wh`] names the unit, which for a 64x16/16x64
14068 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
14069 // measured the old square formula mis-tiling exactly that strip).
14070 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
14071 if bw.max(bh) / bw.min(bh) == 4 {
14072 let which = if depth == 1 {
14073 &RECT4_SPLIT_DEPTH1_HITS
14074 } else {
14075 &RECT4_SPLIT_DEPTH2_HITS
14076 };
14077 hit_do! { which.with(|c| c.set(c.get() + 1)); }
14078 }
14079 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
14080 eprintln!(
14081 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
14082 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
14083 angle_y={angle_delta_y}"
14084 );
14085 }
14086 let modes = RectStripModes {
14087 skip,
14088 mode,
14089 angle_delta_y,
14090 uv_predict_mode,
14091 angle_delta_uv,
14092 alpha,
14093 filter_intra,
14094 smooth_neighbor,
14095 smooth_neighbor_uv,
14096 palette_y: palette_y
14097 .as_ref()
14098 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
14099 palette_uv: palette_uv.as_ref().map(|p| {
14100 (
14101 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
14102 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
14103 )
14104 }),
14105 };
14106 if palette_y.is_some() || palette_uv.is_some() {
14107 hit!(PALETTE_SPLIT_TX_HITS);
14108 }
14109 decode_rect_split(
14110 dec,
14111 cdfs,
14112 neighbours,
14113 (mi_r, mi_c),
14114 bw,
14115 bh,
14116 tx_w,
14117 tx_h,
14118 &modes,
14119 y,
14120 u,
14121 v,
14122 base_q_idx,
14123 reduced_tx_set, fctx,
14124 )?;
14125 // Same early-return palette stamp as [`decode_block_rect`]'s split arm
14126 // (lane-palette2 r10): this return skips the fn's own tail, so a
14127 // split-tx superblock strip would otherwise leave the above/left
14128 // palette arrays holding a dead block's colours.
14129 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
14130 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
14131 let (puv_size, puv_colors) =
14132 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
14133 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
14134 // lane-frame36 r2: `set_txfm_ctxs` runs for EVERY block and this early
14135 // return skips the fn's own tail, so a SPLIT superblock-level strip
14136 // published no TXFM_CONTEXT band and the next block read the row's init
14137 // value 64 as its left transform height. Measured on the 10-bit
14138 // 3840x1608 stream, decode-order frame 33: after the split 16x64 strip
14139 // at mi(192,140) (`tx_depth=1` -> TX_16X32) the 32x64 block at
14140 // mi(192,144) took `tx_size_cat3` row 2 where libaom takes row 1. The
14141 // bands carry the SPLIT unit's size, not the block's.
14142 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
14143 hit!(RECT64_SPLIT_TXFM_PUBLISH_HITS);
14144 hit!(RECT_PARTITION_HITS);
14145 return Ok(());
14146 }
14147 let (tx_w, tx_h) = (bw, bh);
14148 let (cpx, cpy) = (px / 2, py / 2);
14149 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
14150 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
14151 if let Some(ref pyv) = palette_y {
14152 let buf: Vec<u16> = pyv.map.iter().map(|&idx| pyv.colors[idx as usize]).collect();
14153 set_palette_pred(buf, fctx);
14154 }
14155 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
14156 (
14157 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
14158 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
14159 )
14160 });
14161 if skip {
14162 push_intra_rect(0,
14163 px,
14164 py,
14165 bw,
14166 bh,
14167 mode,
14168 angle_delta_y,
14169 reach,
14170 &ZERO_RESIDUAL[..bw * bh],
14171 None,
14172 filter_intra,
14173 smooth_neighbor, fctx,
14174 );
14175 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
14176 if let Some((ub, _)) = &palette_uv_bufs {
14177 set_palette_pred(ub.clone(), fctx);
14178 }
14179 push_intra_rect(1,
14180 cpx,
14181 cpy,
14182 chroma_w,
14183 chroma_h,
14184 uv_predict_mode,
14185 angle_delta_uv,
14186 reach,
14187 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14188 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14189 None,
14190 smooth_neighbor_uv, fctx,
14191 );
14192 if let Some((_, vb)) = &palette_uv_bufs {
14193 set_palette_pred(vb.clone(), fctx);
14194 }
14195 push_intra_rect(2,
14196 cpx,
14197 cpy,
14198 chroma_w,
14199 chroma_h,
14200 uv_predict_mode,
14201 angle_delta_uv,
14202 reach,
14203 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14204 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14205 None,
14206 smooth_neighbor_uv, fctx,
14207 );
14208 neighbours.record_rect(
14209 at,
14210 bw,
14211 bh,
14212 mode,
14213 uv_predict_mode,
14214 &[
14215 &ZERO_RESIDUAL[..bw * bh],
14216 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14217 &ZERO_RESIDUAL[..chroma_w * chroma_h],
14218 ],
14219 );
14220 } else {
14221 let around = neighbours.around_rect(at, bw, bh);
14222 // LUMA: the coded corner, embedded top-left of the true bw x bh grid
14223 // (see this function's own doc comment). A 64-length axis codes only
14224 // its low 32 coefficients, so the corner is `min(bw, 32)` x
14225 // `min(bh, 32)`: 32x32 under a 64x32/32x64 HORZ/VERT strip, and
14226 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
14227 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
14228 let scan32 = default_scan(TX32);
14229 if coeff_trace_on() {
14230 let (rng, _) = dec.debug_state();
14231 eprintln!("EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}");
14232 }
14233 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
14234 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
14235 read_coeffs(
14236 dec,
14237 &mut luma_coding,
14238 &scan32,
14239 0,
14240 dc_sign_ctx(around[0].2),
14241 TxType::DctDct,
14242 Some((bw, bh)),
14243 )?
14244 } else {
14245 // `av1_get_adjusted_tx_size` (`blockd.h:1361`) maps TX_64X16 ->
14246 // TX_32X16 and TX_16X64 -> TX_16X32, and `av1_scan_orders`
14247 // (`scan.c`) gives both the very same `default_scan_32x16` /
14248 // `default_scan_16x32` the 2:1 sizes use ("Half of the
14249 // coefficients of tx64 at higher frequencies are set to zeros. So
14250 // tx32's scan order is used"). `get_txsize_entropy_ctx` is
14251 // (txsize_sqr + txsize_sqr_up + 1) >> 1 = (TX_16X16 + TX_64X64 +
14252 // 1) >> 1 = TX_32X32 and `txsize_log2_minus4[TX_64X16]` is 5 (a
14253 // 512-position eob group) -- BOTH identical to TX_32X16, so the
14254 // 2:1 CDF set `LumaRect32x16` is bit-exact here and no new table
14255 // is owed. `av1_nz_map_ctx_offset[TX_64X16]` is literally
14256 // `av1_nz_map_ctx_offset_32x16` (`txb_common.c:340`), which is
14257 // what `base_ctx_rect` computes at (32, 16).
14258 let luma_scan: &[u16] = if bw == 64 { &SCAN_32X16 } else { &SCAN_16X32 };
14259 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, mode);
14260 read_coeffs_rect(
14261 dec,
14262 &mut luma_coding,
14263 luma_scan,
14264 luma_cw,
14265 luma_ch,
14266 0,
14267 dc_sign_ctx(around[0].2),
14268 TxType::DctDct,
14269 )?
14270 };
14271 if coeff_trace_on() {
14272 let (rng, _) = dec.debug_state();
14273 eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
14274 }
14275 let mut luma_levels = vec![0i32; bw * bh];
14276 for row in 0..luma_ch {
14277 luma_levels[row * bw..][..luma_cw]
14278 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
14279 }
14280 {
14281 let cur = block_q_idx(fctx);
14282 if cur != i32::from(base_q_idx) {
14283 hit!(RECT64_QIDX_DRIFT_HITS);
14284 }
14285 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14286 eprintln!(
14287 "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
14288 );
14289 }
14290 }
14291 let luma_residual = dequant_and_inverse_typed_wh(
14292 &luma_levels,
14293 bw,
14294 bh,
14295 crate::decode::bit_depth(fctx),
14296 block_q_idx(fctx),
14297 plane_q_delta(0, fctx).0,
14298 plane_q_delta(0, fctx).1,
14299 luma_tx_type,
14300 );
14301 push_intra_rect(0,
14302 px,
14303 py,
14304 bw,
14305 bh,
14306 mode,
14307 angle_delta_y,
14308 reach,
14309 &luma_residual,
14310 None,
14311 filter_intra,
14312 smooth_neighbor, fctx,
14313 );
14314 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
14315 let leftcol: Vec<u16> = if px > 0 {
14316 (py..py + bh).map(|row| y.data[row * y.width + px - 1]).collect()
14317 } else {
14318 vec![]
14319 };
14320 eprintln!(
14321 "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
14322 skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
14323 luma_corner.iter().any(|&v| v != 0),
14324 &y.data[py * y.width + px..][..bw],
14325 leftcol,
14326 );
14327 }
14328 // CHROMA: a real, untruncated chroma_w x chroma_h transform -- no
14329 // corner crop needed (see doc comment).
14330 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
14331 // The chroma plane is never truncated (both axes <= 32 after
14332 // subsampling). Under a 1:4 strip it is a true 32x8/8x32:
14333 // `get_txsize_entropy_ctx(TX_32X8)` = (TX_8X8 + TX_32X32 + 1) >> 1 =
14334 // TX_16X16 and `txsize_log2_minus4[TX_32X8]` = 4 (256 positions),
14335 // both identical to TX_16X16 -- so [`TxbSet::Chroma16`] is the exact
14336 // set, and only the scan is new (lane-tx64x16).
14337 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (bw, bh) {
14338 (64, 16) => (TxbSet::Chroma16, &SCAN_32X8),
14339 (16, 64) => (TxbSet::Chroma16, &SCAN_8X32),
14340 (64, _) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
14341 _ => (TxbSet::ChromaRect32x16, &SCAN_16X32),
14342 };
14343 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
14344 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
14345 if coeff_trace_on() {
14346 let (rng, _) = dec.debug_state();
14347 eprintln!("EC_COEFF plane=1 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
14348 }
14349 let (u_levels, u_tx_type) = read_chroma_coeffs_rect(
14350 dec,
14351 &mut u_coding,
14352 chroma_scan,
14353 chroma_w,
14354 chroma_h,
14355 u_skip_ctx,
14356 dc_sign_ctx(around[1].2),
14357 TxType::DctDct,
14358 fctx,
14359 )?;
14360 if coeff_trace_on() {
14361 let (rng, _) = dec.debug_state();
14362 eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}");
14363 }
14364 {
14365 let cur = block_q_idx(fctx);
14366 if cur != i32::from(base_q_idx) {
14367 hit!(RECT64_QIDX_DRIFT_HITS);
14368 }
14369 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14370 eprintln!(
14371 "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}"
14372 );
14373 }
14374 }
14375 let u_residual = dequant_and_inverse_typed_wh(
14376 &u_levels,
14377 chroma_w,
14378 chroma_h,
14379 crate::decode::bit_depth(fctx),
14380 block_q_idx(fctx),
14381 plane_q_delta(1, fctx).0,
14382 plane_q_delta(1, fctx).1,
14383 u_tx_type,
14384 );
14385 // lane-t900 r34: the UV-palette prediction override, exactly as the
14386 // `skip` arm above installs it. The [`PALETTE_PRED`] slot is a
14387 // set-then-take, so it must be filled again right before each plane's
14388 // own reconstruct; leaving this out of the non-skip arm predicted a
14389 // palette block's chroma off its block edges (measured: testsrc2
14390 // 128x128 10-bit cq55 `--tile-columns=1`, the 32x64 strip at px=96 --
14391 // luma exact, both chroma planes wrong over its whole 16x32).
14392 if let Some((ub, _)) = &palette_uv_bufs {
14393 set_palette_pred(ub.clone(), fctx);
14394 }
14395 push_intra_rect(1,
14396 cpx,
14397 cpy,
14398 chroma_w,
14399 chroma_h,
14400 uv_predict_mode,
14401 angle_delta_uv,
14402 reach,
14403 &u_residual,
14404 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
14405 None,
14406 smooth_neighbor_uv, fctx,
14407 );
14408 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
14409 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
14410 if coeff_trace_on() {
14411 let (rng, _) = dec.debug_state();
14412 eprintln!("EC_COEFF plane=2 row={mi_r} col={mi_c} tx_size=rect32x16 rng={rng}");
14413 }
14414 let (v_levels, v_tx_type) = read_chroma_coeffs_rect(
14415 dec,
14416 &mut v_coding,
14417 chroma_scan,
14418 chroma_w,
14419 chroma_h,
14420 v_skip_ctx,
14421 dc_sign_ctx(around[2].2),
14422 TxType::DctDct,
14423 fctx,
14424 )?;
14425 if coeff_trace_on() {
14426 let (rng, _) = dec.debug_state();
14427 eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}");
14428 }
14429 {
14430 let cur = block_q_idx(fctx);
14431 if cur != i32::from(base_q_idx) {
14432 hit!(RECT64_QIDX_DRIFT_HITS);
14433 }
14434 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14435 eprintln!(
14436 "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}"
14437 );
14438 }
14439 }
14440 let v_residual = dequant_and_inverse_typed_wh(
14441 &v_levels,
14442 chroma_w,
14443 chroma_h,
14444 crate::decode::bit_depth(fctx),
14445 block_q_idx(fctx),
14446 plane_q_delta(2, fctx).0,
14447 plane_q_delta(2, fctx).1,
14448 v_tx_type,
14449 );
14450 if let Some((_, vb)) = &palette_uv_bufs {
14451 set_palette_pred(vb.clone(), fctx);
14452 }
14453 push_intra_rect(2,
14454 cpx,
14455 cpy,
14456 chroma_w,
14457 chroma_h,
14458 uv_predict_mode,
14459 angle_delta_uv,
14460 reach,
14461 &v_residual,
14462 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
14463 None,
14464 smooth_neighbor_uv, fctx,
14465 );
14466 neighbours.record_rect(at, bw, bh, mode, uv_predict_mode, &[&luma_levels[..], &u_levels[..], &v_levels[..]]);
14467 hit!(RECT_COEFF_HITS);
14468 }
14469 let (py_size, py_colors) = palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
14470 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
14471 let (puv_size, puv_colors) =
14472 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
14473 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
14474 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
14475 neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx_w as u8, tx_h as u8, 0, fctx);
14476 // `set_txfm_ctxs(mbmi->tx_size, n4_w, n4_h, skip && is_inter, xd)`
14477 // (libaom `decode_token_recon_block`, run for EVERY block of an inter
14478 // frame): the above row records `tx_size_wide` over the block's width and
14479 // the left column `tx_size_high` over its height. This 1:4 strip reader is
14480 // also the INTER frame's reader for the shape ([`decode_intra_rect4_in_inter`]),
14481 // and it published neither band -- so the block after a 64x16 strip read
14482 // the row's init value 64 as its left transform height and took
14483 // `tx_size_cat3` row 1 where libaom takes row 0 (lane-frame36 r1: the
14484 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
14485 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
14486 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
14487 hit!(SB_RECT_HITS);
14488 match (bw, bh) {
14489 (64, 16) => hit!(SB_RECT4_HORZ_HITS),
14490 (16, 64) => hit!(SB_RECT4_VERT_HITS),
14491 _ => {}
14492 }
14493 if crate::envflags::env_flag!("EC_AV1_TRACE") {
14494 let (rng, _) = dec.debug_state();
14495 eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
14496 }
14497 Ok(())
14498}
14499
14500/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
14501/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
14502/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
14503/// it lands away from zero, for gate tests to prove a real stream fired one.
14504fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
14505 let symbol = dec.symbol(cdf);
14506 if symbol != ANGLE_DELTA_ZERO {
14507 hit!(ANGLE_DELTA_HITS);
14508 }
14509 symbol as i32 - ANGLE_DELTA_ZERO as i32
14510}
14511
14512#[allow(clippy::too_many_arguments)]
14513fn read_intra_mode(
14514 dec: &mut SymbolDecoder,
14515 cdfs: &mut Cdfs,
14516 above_mode: usize,
14517 left_mode: usize,
14518 cfl: bool,
14519 side: usize,
14520 enable_filter_intra: bool,
14521 skip_ctx: usize,
14522 allow_screen_content_tools: bool,
14523 allow_intrabc: bool,
14524 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
14525 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
14526 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
14527 // `None` at the excluded call sites (the 8x8-leaf path), which still read
14528 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
14529 // decoder reads either way -- but refuse by name the moment it fires,
14530 // exactly the old behaviour.
14531 palette: Option<(usize, &[u16])>,
14532 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
14533 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
14534 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
14535 // `use_palette_y`, not a neighbour lookup).
14536 palette_uv_cache: &[u16],
14537 mi_r: usize,
14538 mi_c: usize, fctx: &crate::decode::FrameCtx,
14539) -> Result<(
14540 bool,
14541 usize,
14542 i32,
14543 usize,
14544 i32,
14545 Option<(i32, i32)>,
14546 Option<usize>,
14547 Option<PaletteY>,
14548 Option<PaletteUv>,
14549)> {
14550 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
14551 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
14552 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
14553 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
14554 // line against the instrumented aomdec, not just `tell()`.
14555 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
14556 if ec_istep {
14557 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
14558 // (decodemv.c:818), printed at the same point: before the first
14559 // mode-info symbol of the block, so a cross-decoder range ladder can
14560 // be keyed on the BLOCK, not just on the symbol sequence.
14561 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}", dec.debug_state().0);
14562 }
14563 macro_rules! istep {
14564 ($name:literal, $val:expr) => {
14565 if ec_istep {
14566 let (rng, _) = dec.debug_state();
14567 eprintln!(
14568 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
14569 $name, $val
14570 );
14571 }
14572 };
14573 }
14574 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
14575 // point every square caller routes through (see `read_intra_mode_rect`).
14576 let cfl = if cfl && side > 32 {
14577 hit!(NOCFL_UV_MODE_HITS);
14578 false
14579 } else {
14580 cfl
14581 };
14582 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
14583 // `skip` when `SegIdPreSkip`, and after it otherwise.
14584 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
14585 if seg_id_pre_skip(fctx) {
14586 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
14587 }
14588 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
14589 if trace {
14590 eprintln!("TRACE skip value={} rng={}", skip as i32, dec.debug_state().0);
14591 }
14592 istep!("skip", skip as i32);
14593 if !seg_id_pre_skip(fctx) {
14594 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
14595 }
14596 // spec order (see the comment below on `read_intrabc_info`): `skip`,
14597 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
14598 maybe_read_cdef_idx(dec, mi_r, mi_c, (side / MI, side / MI), skip, fctx);
14599 istep!("cdef", 0);
14600 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
14601 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
14602 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
14603 let whole_sb = side == sb_mi_cur(fctx) as usize * 4;
14604 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
14605 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
14606 istep!("dq", 0);
14607 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
14608 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
14609 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
14610 // intra frame whose header set `allow_intrabc`. Actual intra block copy
14611 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
14612 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
14613 // draws the line at consuming this one flag symbol and refusing by name
14614 // when it fires, so the arithmetic decoder still resyncs for a stream
14615 // that merely allows (but never uses) intrabc.
14616 if allow_intrabc {
14617 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
14618 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
14619 eprintln!("EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}", u8::from(use_intrabc), dec.debug_state().0);
14620 }
14621 if trace {
14622 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
14623 }
14624 if use_intrabc {
14625 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (side / MI, side / MI), fctx);
14626 if trace {
14627 eprintln!("TRACE intrabc dv={dv:?}");
14628 }
14629 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
14630 hit!(INTRABC_HITS);
14631 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
14632 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
14633 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
14634 // `DC_PRED` (which is also what the neighbour mode contexts and
14635 // the loop filter then see).
14636 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
14637 }
14638 }
14639 let above_ctx = INTRA_MODE_CTX[above_mode];
14640 let left_ctx = INTRA_MODE_CTX[left_mode];
14641 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
14642 if trace {
14643 eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
14644 }
14645 istep!("mode", mode as i32);
14646 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
14647 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
14648 if trace {
14649 eprintln!(
14650 "TRACE angle_delta value={}",
14651 delta + ANGLE_DELTA_ZERO as i32
14652 );
14653 }
14654 delta
14655 } else {
14656 0
14657 };
14658 istep!("angle_y", angle_delta_y);
14659 // lane-av1mono: a monochrome block codes no chroma mode/CFL/palette
14660 // symbol at all (libaom `decodemv.c:933`'s `!monochrome && is_chroma_ref`
14661 // guard). Fold `NumPlanes == 1` into the same `has_chroma` this reader
14662 // gates its chroma symbols on.
14663 let has_chroma = !mono(fctx);
14664 let cfl = cfl && has_chroma && cfl_allowed_px(side, side, fctx);
14665 let uv_mode = if !has_chroma {
14666 DC_PRED
14667 } else if cfl {
14668 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
14669 } else {
14670 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
14671 };
14672 if trace {
14673 eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}", dec.debug_state().0);
14674 }
14675 istep!("uv_mode", uv_mode as i32);
14676 let alpha = if cfl && uv_mode == UV_CFL_PRED {
14677 Some(read_cfl_alphas(dec, cdfs))
14678 } else {
14679 None
14680 };
14681 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
14682 // from this lane's directional chroma: a corner block with neither
14683 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
14684 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
14685 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
14686 // bug in that fallback this lane's own scope does not cover. Keep it
14687 // refused here rather than ship a silently-wrong decode.
14688 if (9..=12).contains(&uv_mode) {
14689 hit!(SMOOTH_UV_HITS);
14690 }
14691 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
14692 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
14693 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
14694 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
14695 // the `else` branch below and never reads one either way.
14696 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
14697 hit!(DIRECTIONAL_UV_HITS);
14698 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
14699 } else {
14700 0
14701 };
14702 istep!("angle_uv", angle_delta_uv);
14703 if angle_delta_uv != 0 {
14704 hit!(UV_ANGLE_DELTA_HITS);
14705 }
14706 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
14707 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
14708 // gated by `av1_allow_palette` (blockd.h -- size bound only,
14709 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
14710 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
14711 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
14712 // read the same CDF row whenever every neighbour really is non-palette).
14713 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
14714 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
14715 // neighbour lookup at all), so it is exact even at the excluded call
14716 // sites once Y decodes real syntax there too.
14717 //
14718 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
14719 // inline from `read_palette_mode_info` -- it runs later, from
14720 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
14721 // after the WHOLE mode-info read for the block, including UV palette
14722 // mode_info (`read_palette_mode_info`'s own second half, right below)
14723 // and `read_filter_intra_mode_info`. So this branch now only reads
14724 // mode/size/colours for both planes (deferring the two colour-index-map
14725 // decodes to after `filter_intra`, below) -- r6's range trace pinned
14726 // this exact ordering bug (`compare-range-not-tell`: ranges matched
14727 // bit-for-bit through the Y colours, diverged only at the old inline
14728 // `decode_color_index_map` call).
14729 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
14730 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
14731 if allow_screen_content_tools
14732 && let Some(bsize_ctx) = palette_bsize_ctx(side)
14733 {
14734 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
14735 if mode == DC_PRED {
14736 if trace {
14737 let (rng, _) = dec.debug_state();
14738 eprintln!(
14739 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
14740 );
14741 }
14742 }
14743 let use_palette_y =
14744 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
14745 if mode == DC_PRED && trace {
14746 let (rng, _) = dec.debug_state();
14747 eprintln!("TRACE palette_y_mode value={} rng={rng}", use_palette_y as i32);
14748 }
14749 if use_palette_y {
14750 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
14751 if trace {
14752 let (rng, _) = dec.debug_state();
14753 eprintln!("TRACE palette_y_size n={n} rng={rng}");
14754 }
14755 let colors = read_palette_colors_y(dec, n, cache, fctx);
14756 if trace {
14757 let (rng, _) = dec.debug_state();
14758 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
14759 }
14760 palette_y_pending = Some((n, colors));
14761 }
14762 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
14763 // unconditionally at this bit position whenever `uv_mode ==
14764 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
14765 // scope always reconstructs chroma alongside luma (`decode_block`
14766 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
14767 // is always true here and does not need threading in.
14768 //
14769 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
14770 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602), so a
14771 // monochrome frame reads NO `palette_uv_mode`/`palette_uv_size`
14772 // symbol even at this chroma-owning square block.
14773 let palette_uv_mode_ctx = usize::from(use_palette_y);
14774 if has_chroma
14775 && uv_mode == DC_PRED
14776 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
14777 {
14778 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
14779 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
14780 palette_uv_pending = Some((n, u_colors, v_colors));
14781 }
14782 }
14783 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
14784 // `use_filter_intra` symbol this decoder never read at all until
14785 // lane-av1real r10 -- silently skipping it left every bit past a
14786 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
14787 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
14788 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
14789 // symbol's bits were never consumed).
14790 let mut filter_intra = None;
14791 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
14792 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
14793 // `use_filter_intra` symbol for a Y-palette block, and reading one here
14794 // desynced every screen-content stream from the first palette block on
14795 // (it surfaced as a bogus "partition below 8x8" refusal further down the
14796 // tile).
14797 if mode == DC_PRED
14798 && enable_filter_intra
14799 && palette_y_pending.is_none()
14800 && let Some(class) = filter_intra_size_class(side)
14801 {
14802 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
14803 if trace {
14804 eprintln!(
14805 "TRACE use_filter_intra side={side} rng={} value={}", dec.debug_state().0,
14806 use_filter_intra as i32
14807 );
14808 }
14809 istep!("use_filter_intra", use_filter_intra as i32);
14810 if use_filter_intra {
14811 hit!(FILTER_INTRA_HITS);
14812 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
14813 if trace {
14814 eprintln!("TRACE filter_intra_mode value={fi_mode}");
14815 }
14816 istep!("filter_intra_mode", fi_mode as i32);
14817 filter_intra = Some(fi_mode);
14818 }
14819 }
14820 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
14821 // shared U/V map) -- the same order libaom's own loop visits them in.
14822 let palette_y = palette_y_pending.map(|(n, colors)| {
14823 let map =
14824 decode_color_index_map(dec, cdfs, n, side, palette_onscreen(mi_r, mi_c, side, side, fctx), false);
14825 hit!(PALETTE_HITS);
14826 if trace {
14827 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
14828 }
14829 PaletteY { size: n, colors, map }
14830 });
14831 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
14832 let on = palette_onscreen_uv(
14833 (side, side),
14834 palette_onscreen(mi_r, mi_c, side, side, fctx),
14835 (side / 2, side / 2),
14836 );
14837 let map = decode_color_index_map(dec, cdfs, n, side / 2, on, true);
14838 hit!(PALETTE_UV_HITS);
14839 if trace {
14840 eprintln!(
14841 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
14842 &u_colors[..n],
14843 &v_colors[..n]
14844 );
14845 }
14846 PaletteUv { size: n, u_colors, v_colors, map }
14847 });
14848 Ok((
14849 skip,
14850 mode,
14851 angle_delta_y,
14852 uv_mode,
14853 angle_delta_uv,
14854 alpha,
14855 filter_intra,
14856 palette_y,
14857 palette_uv,
14858 ))
14859}
14860
14861/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
14862/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
14863/// intra modes.
14864const UV_CFL_PRED: usize = 13;
14865
14866/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
14867/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
14868/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
14869/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
14870/// joint sign the same way. Returns each plane's final signed `alpha_q3`
14871/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
14872fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
14873 hit!(CFL_BLOCK_HITS);
14874 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
14875 let sign_u = ((joint_sign + 1) * 11) >> 5;
14876 let sign_v = (joint_sign + 1) - 3 * sign_u;
14877 let alpha_u = if sign_u == 0 {
14878 0
14879 } else {
14880 let ctx_u = (joint_sign + 1 - 3) as usize;
14881 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
14882 if sign_u == 2 { mag } else { -mag }
14883 };
14884 let alpha_v = if sign_v == 0 {
14885 0
14886 } else {
14887 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
14888 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
14889 if sign_v == 2 { mag } else { -mag }
14890 };
14891 (alpha_u, alpha_v)
14892}
14893
14894/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
14895/// the reconstructed luma samples under a `side`-square block, subsampled
14896/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
14897/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
14898/// to give the AC values [`cfl_scaled`] scales by alpha.
14899fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
14900 cfl_ac_q3_at(px, py, side, side, |lx, ly| i32::from(y.data[ly * y.width + lx]))
14901}
14902
14903/// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma
14904/// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder
14905/// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8`
14906/// reconstruction through THIS function rather than a second transcription of
14907/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`.
14908pub(crate) fn cfl_ac_q3_at(
14909 px: usize,
14910 py: usize,
14911 bw: usize,
14912 bh: usize,
14913 sample: impl Fn(usize, usize) -> i32,
14914) -> Vec<i32> {
14915 let (cw, ch) = (bw / 2, bh / 2);
14916 let mut ac = vec![0i32; cw * ch];
14917 let mut sum = 0i32;
14918 for cy in 0..ch {
14919 for cx in 0..cw {
14920 let (lx, ly) = (px + cx * 2, py + cy * 2);
14921 let q3 = (sample(lx, ly)
14922 + sample(lx + 1, ly)
14923 + sample(lx, ly + 1)
14924 + sample(lx + 1, ly + 1))
14925 << 1;
14926 ac[cy * cw + cx] = q3;
14927 sum += q3;
14928 }
14929 }
14930 let num_pel = (cw * ch) as i32;
14931 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
14932 ac.iter_mut().for_each(|v| *v -= avg);
14933 ac
14934}
14935
14936/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
14937/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
14938/// ties away from zero on the shifted-out sign).
14939pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
14940 let v = alpha_q3 * ac_q3;
14941 if v >= 0 {
14942 (v + 32) >> 6
14943 } else {
14944 -((-v + 32) >> 6)
14945 }
14946}
14947
14948/// One plane's reconstruction buffer, `width * height` samples, and the
14949/// prediction/residual reads and writes into it — the decode-side twin of
14950/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
14951/// (own-edge and reach clamps both), passing what it gathers straight to
14952/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
14953/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
14954/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
14955/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
14956/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects) --
14957/// matches aomdec's own `ec_dump16` rung byte for byte (crop dims, u16 LE).
14958/// lane-mc64 r1: the decode-order index the stage dumps below key their file
14959/// name on. `PREFILT_PICTURE_IDX` is bumped once per frame just BEFORE the
14960/// deblock/CDEF stages run, so the frame being dumped here is `idx - 1` --
14961/// without this every frame overwrote `.f0` and a per-frame bisection silently
14962/// compared the LAST decoded frame (ledger, class stale-output-faked-measurement).
14963#[allow(dead_code)] // gate counter accessor with no reader yet; the counter itself is live
14964fn stage_dump_idx() -> usize {
14965 PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst).saturating_sub(1)
14966}
14967
14968fn dump_stage16(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>, fw: usize, fh: usize) {
14969 use std::io::Write;
14970 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
14971 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
14972 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
14973 // not be read out at all.
14974 if let Ok(path) = crate::envflags::var(var)
14975 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
14976 {
14977 for (p, w, h) in [(y, fw, fh), (u, fw.div_ceil(2), fh.div_ceil(2)), (v, fw.div_ceil(2), fh.div_ceil(2))] {
14978 for row in 0..h {
14979 let mut bytes = Vec::with_capacity(w * 2);
14980 for &s in &p.data[row * p.width..][..w] {
14981 bytes.extend_from_slice(&s.to_le_bytes());
14982 }
14983 let _ = f.write_all(&bytes);
14984 }
14985 }
14986 }
14987}
14988
14989/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
14990/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
14991/// every frame overwrote the previous one and only the LAST frame survived,
14992/// which silently defeats any per-frame filter-stage bisection.
14993fn dump_stage_idx(var: &str) -> usize {
14994 use std::collections::HashMap;
14995 use std::sync::{Mutex, OnceLock};
14996 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
14997 let mut m = IDX.get_or_init(|| Mutex::new(HashMap::new())).lock().unwrap();
14998 let e = m.entry(var.to_string()).or_insert(0);
14999 let i = *e;
15000 *e += 1;
15001 i
15002}
15003
15004fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
15005 use std::io::Write;
15006 if let Ok(path) = crate::envflags::var(var)
15007 && let Ok(mut f) = std::fs::File::create(format!("{path}.f{}", dump_stage_idx(var)))
15008 {
15009 for p in [y, u, v] {
15010 let narrow: Vec<u8> = p.data.iter().map(|&s| s as u8).collect();
15011 let _ = f.write_all(&narrow);
15012 }
15013 }
15014}
15015
15016/// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no
15017/// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`,
15018/// at most 4095), so a decode that hashes identically under the flag proves
15019/// the output does not depend on the plane buffer's initial content.
15020const PLANE_SENTINEL: u16 = 0xDEAD;
15021
15022/// A frame plane's own backing store, `n` samples, UNINITIALISED.
15023///
15024/// (lane-picalloc) The SB-padded coding surface is written sample-for-sample
15025/// by the tile walk's reconstruction before anything reads it, so the
15026/// `vec![0u16; n]` this replaces spent ~3% of the frame thread's cycles
15027/// zeroing 25 MB (at 4K) that the very next pass overwrites -- serially, at
15028/// the frame's head, on the critical path. `EC_AV1_PLANE_SENTINEL=1` swaps the
15029/// uninitialised buffer for a [`PLANE_SENTINEL`] fill; the gate hashes both
15030/// ways (see the lane report) and the two agree, which is the proof that no
15031/// unwritten sample reaches the output.
15032fn fresh_plane(n: usize) -> Vec<u16> {
15033 if crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL") {
15034 return vec![PLANE_SENTINEL; n];
15035 }
15036 let mut v: Vec<u16> = Vec::with_capacity(n);
15037 // SAFETY: `u16` has no invalid bit patterns and no `Drop`, and the
15038 // capacity was just reserved, so the vector owns `n` initialised-or-not
15039 // `u16` slots. Every one is written by reconstruction before it is read
15040 // (proven by the sentinel gate above).
15041 #[allow(unsafe_code)]
15042 unsafe {
15043 v.set_len(n);
15044 }
15045 v
15046}
15047
15048#[derive(Clone)]
15049struct PlaneBuf<'a> {
15050 data: std::borrow::Cow<'a, [u16]>,
15051 width: usize,
15052 height: usize,
15053 /// The frame's true, decodable extent in this plane's own units — past
15054 /// this, samples are the padded coding surface's invented tail, never a
15055 /// real decoder's edge or reach reads.
15056 true_width: usize,
15057 true_height: usize,
15058 /// This plane's own tile's top-left pixel origin (spec: intra prediction
15059 /// never reaches across a tile boundary even though an earlier-decoded
15060 /// tile's real pixels sit right there in the shared buffer) — set via
15061 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
15062 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
15063 /// is threaded (the two-tile column-split stage 1 fixture's tile always
15064 /// ends at the frame's own right/bottom edge); a non-last tile's own
15065 /// right/bottom reach bound is still open, tracked in the report.
15066 tile_x0: usize,
15067 tile_y0: usize,
15068 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
15069 /// (exclusive) -- a non-last tile column/row's own reach must stop at
15070 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
15071 /// full padded extent) for the single-tile/last-tile case, matching the
15072 /// old unclipped behaviour exactly.
15073 tile_x1: usize,
15074 tile_y1: usize,
15075}
15076
15077/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
15078/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
15079/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
15080/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
15081/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
15082/// `ALTREF2`/`ALTREF`).
15083
15084impl PlaneBuf<'_> {
15085 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
15086 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
15087 /// are already in this plane's own units (luma pixels for `y`, chroma
15088 /// pixels — halved — for `u`/`v`).
15089 fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
15090 self.tile_x0 = x0;
15091 self.tile_y0 = y0;
15092 self.tile_x1 = x1;
15093 self.tile_y1 = y1;
15094 }
15095
15096 fn edges(
15097 &self,
15098 x: usize,
15099 y: usize,
15100 side: usize,
15101 reach: Reach,
15102 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
15103 let own_across = x + side.min(self.true_width.saturating_sub(x));
15104 let across = if reach.above_right {
15105 own_across + side.min(self.true_width.saturating_sub(own_across))
15106 } else {
15107 own_across
15108 }
15109 .min(self.width)
15110 .min(self.tile_x1);
15111 let own_down = y + side.min(self.true_height.saturating_sub(y));
15112 let down = if reach.below_left {
15113 own_down + side.min(self.true_height.saturating_sub(own_down))
15114 } else {
15115 own_down
15116 }
15117 .min(self.height)
15118 .min(self.tile_y1);
15119 let above = (y > self.tile_y0 && across > x)
15120 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
15121 let left = (x > self.tile_x0 && down > y).then(|| {
15122 (y..down)
15123 .map(|row| self.data[row * self.width + x - 1])
15124 .collect::<Vec<_>>()
15125 });
15126 let corner =
15127 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
15128 (above, left, corner)
15129 }
15130
15131 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
15132 /// the above/left reach each extend by their OWN axis (`bw` across,
15133 /// `bh` down), not one shared `side`.
15134 fn edges_rect(
15135 &self,
15136 x: usize,
15137 y: usize,
15138 bw: usize,
15139 bh: usize,
15140 reach: Reach,
15141 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
15142 let own_across = x + bw.min(self.true_width.saturating_sub(x));
15143 let across = if reach.above_right {
15144 own_across + bw.min(self.true_width.saturating_sub(own_across))
15145 } else {
15146 own_across
15147 }
15148 .min(self.width)
15149 .min(self.tile_x1);
15150 let own_down = y + bh.min(self.true_height.saturating_sub(y));
15151 let down = if reach.below_left {
15152 own_down + bh.min(self.true_height.saturating_sub(own_down))
15153 } else {
15154 own_down
15155 }
15156 .min(self.height)
15157 .min(self.tile_y1);
15158 let above = (y > self.tile_y0 && across > x)
15159 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
15160 let left = (x > self.tile_x0 && down > y).then(|| {
15161 (y..down)
15162 .map(|row| self.data[row * self.width + x - 1])
15163 .collect::<Vec<_>>()
15164 });
15165 let corner =
15166 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
15167 if matches!((bw, bh), (16, 8) | (8, 16)) {
15168 hit!(RECT_STRIP_PRED_HITS);
15169 if across > own_across || down > own_down {
15170 hit!(RECT_STRIP_REACH_HITS);
15171 }
15172 }
15173 (above, left, corner)
15174 }
15175
15176 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
15177 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
15178 /// already-rect-capable `(bw, bh)` pair.
15179 #[allow(clippy::too_many_arguments)]
15180 #[track_caller]
15181 fn reconstruct_rect(
15182 &mut self,
15183 x: usize,
15184 y: usize,
15185 bw: usize,
15186 bh: usize,
15187 mode: usize,
15188 angle_delta: i32,
15189 reach: Reach,
15190 residual: &[i32],
15191 cfl: Option<(i32, &[i32])>,
15192 filter_intra: Option<usize>,
15193 smooth_neighbor: bool,
15194 // lane-wave1 step (i): the palette/intrabc prediction override, taken
15195 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
15196 // than by this replay.
15197 pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx,
15198 ) {
15199 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
15200 // (lane-palette2 r4): a palette block's prediction is the
15201 // reconstructed colour-index map, needing no edge pixels at all.
15202 let prediction = if let Some(buf) = pred {
15203 buf
15204 } else {
15205 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
15206 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
15207 eprintln!(
15208 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
15209 above.as_ref().map(|a| (a.len(), a[0])),
15210 left.as_ref().map(|l| l.len()),
15211 left.as_ref().map(|l| l[0]),
15212 self.tile_x0, self.tile_y0, self.true_width, self.true_height
15213 );
15214 }
15215 let mut prediction = vec![0u16; bw * bh];
15216 if let Some(fi_mode) = filter_intra {
15217 crate::intra::predict_filter_intra(
15218 fi_mode,
15219 above.as_deref(),
15220 left.as_deref(),
15221 corner,
15222 bw,
15223 bh,
15224 &mut prediction, fctx,
15225 );
15226 } else {
15227 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
15228 predict(
15229 mode as u8,
15230 angle_delta,
15231 above.as_deref(),
15232 left.as_deref(),
15233 corner,
15234 bw,
15235 bh,
15236 enable_edge_filter,
15237 smooth_neighbor,
15238 &mut prediction, fctx,
15239 );
15240 }
15241 prediction
15242 };
15243 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
15244 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
15245 if crate::envflags::env_flag!("EC_PRED") {
15246 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
15247 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
15248 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
15249 eprintln!(
15250 "@{} OUR_PRED x={x} y={y} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller(), i32::from(smooth_neighbor)
15251 );
15252 }
15253 let residual = dense_residual(residual, bw * bh);
15254 for row in 0..bh {
15255 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
15256 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
15257 // whose padded width is not superblock aligned hangs past it.
15258 if y + row >= self.height {
15259 break;
15260 }
15261 for col in 0..bw {
15262 if x + col >= self.width {
15263 break;
15264 }
15265 let idx = row * bw + col;
15266 let mut base = i32::from(prediction[idx]);
15267 if let Some((alpha_q3, ac_q3)) = cfl {
15268 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
15269 }
15270 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
15271 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
15272 }
15273 }
15274 // lane-d792: the RECONSTRUCTION rung beside `EC_PRED`'s prediction one
15275 // -- a block whose prediction matches the oracle's but whose written
15276 // samples do not is either a residual defect or a later overwrite, and
15277 // only this print separates the two.
15278 if crate::envflags::env_flag!("EC_PRED") {
15279 let row0: Vec<u16> =
15280 (0..bw.min(8)).map(|c| self.data[y * self.width + x + c]).collect();
15281 let col0: Vec<u16> =
15282 (0..bh.min(8)).map(|r| self.data[(y + r) * self.width + x]).collect();
15283 eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}");
15284 }
15285 }
15286
15287 /// Predicts under `mode` then adds `residual` (side*side, raster),
15288 /// writing the clamped reconstruction back into the plane at `(x, y)`.
15289 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
15290 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
15291 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
15292 /// order (cfl.c).
15293 #[track_caller]
15294 fn reconstruct(
15295 &mut self,
15296 x: usize,
15297 y: usize,
15298 side: usize,
15299 mode: usize,
15300 angle_delta: i32,
15301 reach: Reach,
15302 residual: &[i32],
15303 cfl: Option<(i32, &[i32])>,
15304 filter_intra: Option<usize>,
15305 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
15306 // libaom `get_filt_type`): true when the block's above OR left
15307 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
15308 // Callers pass their own plane's neighbour-mode check
15309 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
15310 // callers until a smooth/paeth `uv_mode` can reach this call at all
15311 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
15312 // keeps `false` exact for chroma without this fn needing to know why.
15313 smooth_neighbor: bool,
15314 // lane-wave1 step (i): the palette/intrabc prediction override, taken
15315 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
15316 // than by this replay.
15317 pred: Option<Vec<u16>>, fctx: &crate::decode::FrameCtx,
15318 ) {
15319 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
15320 // takes priority over `predict()`/`predict_filter_intra` entirely --
15321 // palette prediction needs no edge pixels at all.
15322 let prediction = if let Some(buf) = pred {
15323 buf
15324 } else {
15325 let (above, left, corner) = self.edges(x, y, side, reach);
15326 let mut prediction = vec![0u16; side * side];
15327 if let Some(fi_mode) = filter_intra {
15328 crate::intra::predict_filter_intra(
15329 fi_mode,
15330 above.as_deref(),
15331 left.as_deref(),
15332 corner,
15333 side,
15334 side,
15335 &mut prediction, fctx,
15336 );
15337 } else {
15338 // `enable_intra_edge_filter` is the sequence header's own flag
15339 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
15340 // call, never per-block) -- threading it through every
15341 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
15342 // dozen sites for a value that never changes mid-decode, so it
15343 // rides a thread-local instead (this decoder is single-threaded
15344 // per stream).
15345 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
15346 predict(
15347 mode as u8,
15348 angle_delta,
15349 above.as_deref(),
15350 left.as_deref(),
15351 corner,
15352 side,
15353 side,
15354 enable_edge_filter,
15355 smooth_neighbor,
15356 &mut prediction, fctx,
15357 );
15358 }
15359 prediction
15360 };
15361 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
15362 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
15363 if crate::envflags::env_flag!("EC_PRED") {
15364 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
15365 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
15366 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
15367 eprintln!(
15368 "@{} OUR_PRED x={x} y={y} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}", std::panic::Location::caller(), i32::from(smooth_neighbor)
15369 );
15370 }
15371 let residual = dense_residual(residual, side * side);
15372 for row in 0..side {
15373 // lane-sb128c r8: libaom's frame buffer is superblock
15374 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
15375 // transform unit of a 128x64 block at the BOTTOM frame edge
15376 // can hang past the last padded row (1920x792: a unit at
15377 // y=768 wants 832 rows of an 800-row buffer, which panicked
15378 // the film's key frames). Those samples are outside the
15379 // frame: never output, and no block below ever references
15380 // them.
15381 if y + row >= self.height {
15382 break;
15383 }
15384 for col in 0..side {
15385 if x + col >= self.width {
15386 break;
15387 }
15388 let idx = row * side + col;
15389 let mut base = i32::from(prediction[idx]);
15390 if let Some((alpha_q3, ac_q3)) = cfl {
15391 base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, sample_max(fctx));
15392 }
15393 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
15394 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
15395 }
15396 }
15397 }
15398}
15399
15400/// Reads one plane's transform block, reconstructs it into `plane` at
15401/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
15402#[allow(clippy::too_many_arguments)]
15403fn read_plane(
15404 dec: &mut SymbolDecoder,
15405 cdfs: &mut Cdfs,
15406 set: TxbSet,
15407 scan: &[u16],
15408 plane_idx: usize,
15409 around: (bool, bool, i32),
15410 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
15411 // it for every plane's `txb` lookup (it is what an intra transform type's
15412 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
15413 tx_mode: usize,
15414 predict_mode: usize,
15415 angle_delta: i32,
15416 reach: Reach,
15417 // lane-wave1 step (i): unread -- this reader records its write
15418 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
15419 // stays in the signature so every call site still proves the plane is
15420 // exclusively held while its coefficients are parsed.
15421 _plane: &mut PlaneBuf<'static>,
15422 x: usize,
15423 y: usize,
15424 side: usize,
15425 tx_side: usize,
15426 base_q_idx: u8,
15427 cfl: Option<(i32, CflSrc)>,
15428 filter_intra: Option<usize>,
15429 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
15430 // smaller than its own block (spec `get_txb_ctx_general`'s
15431 // `plane_bsize != tx_size` branch), carrying the already-looked-up
15432 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
15433 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
15434 // formula below.
15435 luma_skip_ctx: Option<usize>,
15436 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
15437 smooth_neighbor: bool, fctx: &crate::decode::FrameCtx,
15438) -> Result<Grid> {
15439 // lane-av1mono: a monochrome frame has `NumPlanes == 1`, so libaom's
15440 // coefficient loop (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`)
15441 // never reaches a chroma plane -- no u/v coefficient symbol is coded and
15442 // no chroma write is recorded. Return the all-zero grid the caller's
15443 // neighbour bookkeeping reads, without consuming a bit.
15444 if plane_idx > 0 && mono(fctx) {
15445 return Ok(Grid::Zero(side * side));
15446 }
15447 let skip_ctx = if plane_idx == 0 {
15448 luma_skip_ctx.unwrap_or(0)
15449 } else {
15450 // libaom `get_txb_ctx`: a chroma unit's context is
15451 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
15452 // plane block is bigger than the transform. Our chroma tables hold the
15453 // offset-7 rows first, so the caller adds 3 for the bigger-block case
15454 // (only a 128x128 block's TX_32X32 chroma units, lane-sb128b r3).
15455 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
15456 };
15457 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
15458 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
15459 // not by the block's ordinary `mode` (which is always DC_PRED whenever
15460 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
15461 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
15462 // filter-intra in AV1).
15463 let tx_mode = if plane_idx == 0 { fi_tx_row(tx_mode, filter_intra) } else { tx_mode };
15464 let mut coding = cdfs.txb(set, tx_mode);
15465 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
15466 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
15467 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
15468 // plane of a lossless block (the residual then goes through the WHT, so
15469 // the type only picks the scan, which is the default one).
15470 if lossless(fctx) {
15471 coding.tx_type = None;
15472 }
15473 // Luma's `default_tx_type` is only a fallback for the sizes whose
15474 // `TxbSet` carries no symbol at all (32-point and up), which the spec
15475 // fixes at `DCT_DCT` regardless of mode; a chroma plane's `tx_type` is
15476 // *never* its own coded symbol (`coding.tx_type` is always `None` for
15477 // every `TxbSet::Chroma*`), so it would take `Intra_Mode_To_Tx_Type` of
15478 // the plane's own predicted mode (`default_intra_tx_type`) -- except
15479 // `av1_get_ext_tx_set_type` (`blockd.h`) resolves chroma at `tx_size_sqr
15480 // >= TX_32X32` to `EXT_TX_SET_DCTONLY`, which forces the result back to
15481 // `DCT_DCT` no matter what the mode-indexed table said (`TxbSet::Chroma8`
15482 // and `Chroma16` never hit this — every value `default_intra_tx_type` can
15483 // produce is already a member of both `TX_SET_INTRA_1`/`_2`, so nothing
15484 // narrows there — only `Chroma32` and up do).
15485 let default_tx_type = if plane_idx == 0 || side >= 32 {
15486 TxType::DctDct
15487 } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
15488 // See [`INTRABC_CHROMA_TX`]: an intrabc block is an inter block for
15489 // `av1_get_tx_type`, so chroma inherits luma's coded type (the
15490 // `side >= 32` arm above is already libaom's `EXT_TX_SET_DCTONLY`
15491 // clamp at `tx_size_sqr_up >= TX_32X32`, matching
15492 // [`read_inter_plane`]'s own `side < 32` guard).
15493 inherited
15494 } else {
15495 default_intra_tx_type(predict_mode as u8)
15496 };
15497 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
15498 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
15499 let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type };
15500 let (grid, tx_type) = read_coeffs(
15501 dec,
15502 &mut coding,
15503 scan,
15504 skip_ctx,
15505 dc_sign_ctx(around.2),
15506 default_tx_type,
15507 None,
15508 )?;
15509 note_chroma_class1(plane_idx, tx_type);
15510 if plane_idx == 0 {
15511 fctx.luma_tx_type.with(|c| c.set(tx_type));
15512 }
15513 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
15514 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
15515 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
15516 // guard also assumes.
15517 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
15518 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
15519 // keyed by that true size, not the coded corner's -- so the corner
15520 // goes into the top-left of a `side`-sized grid, not the reverse.
15521 let levels = extend_corner(grid, tx_side, tx_side, side, side);
15522 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
15523 let tx = TxParams {
15524 w: side, h: side, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta,
15525 ac_delta, tx_type, stride: 0, lossless: lossless(fctx),
15526 };
15527 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15528 let residual = tx.run(&levels);
15529 eprintln!(
15530 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}", &*levels,
15531 );
15532 }
15533 push_intra_tx(
15534 plane_idx,
15535 x,
15536 y,
15537 side,
15538 side,
15539 false,
15540 predict_mode,
15541 angle_delta,
15542 reach,
15543 tx,
15544 &levels,
15545 cfl,
15546 filter_intra,
15547 smooth_neighbor, fctx,
15548 );
15549 // `record`'s neighbour state only reads whether *the coded grid* (not the
15550 // residual) has nonzero entries, so the levels this function already
15551 // built are what it wants back -- both arms of the old `tx_side == side`
15552 // branch returned exactly that, one of them through a full `to_vec` copy
15553 // of the grid per intra transform unit (lane-coefbuf).
15554 Ok(levels)
15555}
15556
15557/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
15558/// three planes, reconstructing them into `y`/`u`/`v` and updating
15559/// `neighbours`.
15560#[allow(clippy::too_many_arguments)]
15561fn decode_block(
15562 dec: &mut SymbolDecoder,
15563 cdfs: &mut Cdfs,
15564 neighbours: &mut Neighbours,
15565 at: (usize, usize),
15566 side: usize,
15567 luma_set: TxbSet,
15568 chroma_set: TxbSet,
15569 luma_tx: usize,
15570 chroma_tx: usize,
15571 scans: (&[u16], &[u16]),
15572 cfl: bool,
15573 y: &mut PlaneBuf<'static>,
15574 u: &mut PlaneBuf<'static>,
15575 v: &mut PlaneBuf<'static>,
15576 base_q_idx: u8,
15577 enable_filter_intra: bool,
15578 allow_screen_content_tools: bool,
15579 allow_intrabc: bool,
15580 scan32: &[u16],
15581 scan16: &[u16],
15582 scan8: &[u16],
15583 scan4: &[u16],
15584 tx_select: bool,
15585 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
15586) -> Result<()> {
15587 // lane-lossless: a lossless frame's transform is TX_4X4 on every plane
15588 // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
15589 // tables/scans are replaced by the 4x4 ones and the block always takes the
15590 // multi-transform-unit path below.
15591 let (luma_set, chroma_set, luma_tx, chroma_tx, scans) = if lossless(fctx) {
15592 (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, (scan4, scan4))
15593 } else {
15594 (luma_set, chroma_set, luma_tx, chroma_tx, scans)
15595 };
15596 let (r, c) = at;
15597 let (px, py) = (c * SUB, r * SUB);
15598 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
15599 let palette_uv_cache = neighbours.palette_uv_cache(at);
15600 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
15601 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
15602 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
15603 read_intra_mode(
15604 dec,
15605 cdfs,
15606 nb_above_mode,
15607 nb_left_mode,
15608 cfl,
15609 side,
15610 enable_filter_intra,
15611 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
15612 allow_screen_content_tools,
15613 allow_intrabc,
15614 Some((palette_ctx, &palette_cache)),
15615 &palette_uv_cache,
15616 r * (SUB / MI),
15617 c * (SUB / MI), fctx,
15618 )?;
15619 if at_tile_left && palette_y.is_some() {
15620 hit!(PALETTE_TILE_LEFT_HITS);
15621 }
15622 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
15623 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
15624 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
15625 // actual chroma-from-luma correlation, same as this decoder always did.
15626 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
15627 DC_PRED
15628 } else {
15629 uv_mode
15630 };
15631 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
15632 if smooth_neighbor {
15633 hit!(SMOOTH_LUMA_HITS);
15634 }
15635 let smooth_neighbor_uv =
15636 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c);
15637 if crate::envflags::env_flag!("EC_AV1_TRACE") {
15638 eprintln!(
15639 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
15640 angle_delta_uv={angle_delta_uv}"
15641 );
15642 }
15643 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
15644 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
15645 // block, skipped or not. `logical_tx` is what the loop filter's edge
15646 // lookup and the next block's own `get_tx_size_context` want (the *nominal*
15647 // transform size -- 64 even for the 64x64 corner-scanned case, spec
15648 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
15649 // which only differs from it at that one corner case.
15650 // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth`
15651 // symbol on `allowSelect = !skip || !is_inter`, and libaom's
15652 // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED
15653 // intrabc block reads NO tx-size symbol at all -- it takes
15654 // `maxRectTxSize` -- while every ordinary skipped intra block does read
15655 // one. Reading it anyway consumed a symbol libaom never wrote and desynced
15656 // the tile from that block on (class `equal-range-means-unread`).
15657 // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition
15658 // tree instead (`read_var_tx_size`), the same syntax the inter block path
15659 // has always read -- libaom's `parse_decode_block` dispatches on
15660 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
15661 // intrabc block as inter.
15662 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
15663 let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip;
15664 let intrabc_leaves = if intrabc_vartx {
15665 let max_tx = side.min(64);
15666 // `max_block_wide`/`max_block_high`: the frame's own mi grid
15667 // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the
15668 // right/bottom edge reads no split symbol for the units outside it.
15669 let mi_cols = 2 * y.true_width.div_ceil(8);
15670 let mi_rows = 2 * y.true_height.div_ceil(8);
15671 let side_mi = side / MI;
15672 let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c));
15673 let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r));
15674 let mut leaves = Vec::new();
15675 for row in (0..side_mi).step_by(max_tx / MI) {
15676 for col in (0..side_mi).step_by(max_tx / MI) {
15677 read_var_tx_size(
15678 dec, cdfs, neighbours, (mi_r, mi_c), side,
15679 (max_w_mi, max_h_mi), (max_tx, max_tx), 0, row, col, &mut leaves,
15680 );
15681 }
15682 }
15683 hit!(INTRABC_VARTX_HITS);
15684 // The luma reconstruct loop below is a UNIFORM grid of one square
15685 // transform (the intra `tx_depth` shape), so a tree that resolved to
15686 // mixed leaf sizes is refused by name rather than reconstructed at the
15687 // wrong stride.
15688 let uniform = leaves
15689 .first()
15690 .is_some_and(|f| leaves.iter().all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3));
15691 if !uniform {
15692 return Err(unsupported(
15693 "an intrabc block whose var-tx tree resolved to mixed leaf transform sizes",
15694 ));
15695 }
15696 Some(leaves[0].2)
15697 } else {
15698 None
15699 };
15700 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves {
15701 (tx, if tx == 64 { 32 } else { tx })
15702 } else if tx_select && !intrabc_skip_tx {
15703 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side);
15704 (resolved, if resolved == 64 { 32 } else { resolved })
15705 } else {
15706 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
15707 // TX_64X64, so a 128x128 block is always FOUR luma transform units
15708 // even with `tx_select` off -- the TU loop below, never the
15709 // single-unit path.
15710 (lossless_tx(side.min(64), fctx), luma_tx)
15711 };
15712 if tx_select && logical_tx < side && uv_mode != DC_PRED {
15713 hit!(SQ_CHROMA_TX_HITS);
15714 }
15715 let luma_set = if tx_select {
15716 txbset_for(logical_tx, reduced_tx_set)
15717 } else {
15718 luma_set
15719 };
15720 let luma_set = if intrabc_dv.is_some() {
15721 inter_txbset_for(logical_tx, reduced_tx_set)
15722 } else {
15723 luma_set
15724 };
15725 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
15726 let reach = Reach::of(side, px, py, y.width, y.height, fctx);
15727 let (cpx, cpy) = (px / 2, py / 2);
15728 let chroma_side = side / 2;
15729 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
15730 // frame's own pre-loop-filter reconstruction (all loop filters are off
15731 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
15732 // block vector, with the BILINEAR kernel libaom forces for intrabc --
15733 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
15734 // odd, which is exactly what the bilinear taps then interpolate.
15735 flush_recon(fctx, y, u, v);
15736 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
15737 let mut yb = vec![0u16; side * side];
15738 mc::predict_with_filter(
15739 &y.data, y.width, y.true_width, y.true_height,
15740 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
15741 side, side, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
15742 );
15743 let mut ub = vec![0u16; chroma_side * chroma_side];
15744 mc::predict_with_filter(
15745 &u.data, u.width, u.true_width, u.true_height,
15746 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
15747 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
15748 );
15749 let mut vb = vec![0u16; chroma_side * chroma_side];
15750 mc::predict_with_filter(
15751 &v.data, v.width, v.true_width, v.true_height,
15752 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
15753 chroma_side, chroma_side, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
15754 );
15755 (yb, ub, vb)
15756 });
15757 // A palette-Y block's own prediction is the reconstructed colour-index
15758 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
15759 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
15760 // parameter through this function's dozen `y.reconstruct`/`read_plane`
15761 // sites. A split luma transform (`tx_select && logical_tx != side`)
15762 // would need the map sliced per-TU -- untested against a real
15763 // `--enable-palette=1` stream this round, so refuse by name rather than
15764 // guess at the slicing (charter's own named-acceptable fallback).
15765 let palette_y_buf: Option<Vec<u16>> = palette_y.as_ref().map(|py| {
15766 py.map
15767 .iter()
15768 .map(|&idx| py.colors[idx as usize])
15769 .collect()
15770 });
15771 // lane-t900 r32: the intrabc luma prediction rides the very same
15772 // whole-block override slot, so the multi-TU loop below windows it per
15773 // transform unit exactly like a palette map -- setting it once up front
15774 // handed the whole `side`x`side` buffer to the FIRST unit and left every
15775 // later one predicting off block edges (the var-tx tree above is what
15776 // first makes `logical_tx < side` reachable for an intrabc block).
15777 let palette_y_buf = match &intrabc_bufs {
15778 Some((yb, _, _)) => Some(yb.clone()),
15779 None => palette_y_buf,
15780 };
15781 // With one luma transform unit the whole `side`x`side` map is the
15782 // prediction; with several (`logical_tx != side`) each unit takes its own
15783 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
15784 // below (lane-palette2 r7) -- setting the full-block buffer here would be
15785 // taken by the FIRST unit and indexed at the wrong stride.
15786 // lane-svt1: a SKIPPED block predicts the whole `side`x`side` in ONE call
15787 // (the `else` arm below -- a palette/intrabc block never takes the per-unit
15788 // `split_tx_skip` walk), so its map must be armed here even when the
15789 // transform is split. Gating the arm on `logical_tx == side` alone left a
15790 // 16x16 palette block with `tx_depth == 1` and `skip == 1` predicting DC
15791 // off its own edges: right symbols, wrong pixels (SVT-AV1 preset-8 screen
15792 // key frame; class override-slot-on-one-arm). Neither prediction is
15793 // edge-derived, so the whole-block buffer at the block's own stride is
15794 // exactly what that single call wants.
15795 // Counted on the SHAPE, not on the arm below, so a gate can tell a stream
15796 // that reaches this block apart from one that never does (class
15797 // gate-blind-to-feature).
15798 if palette_y_buf.is_some() && skip && logical_tx < side {
15799 hit!(SKIP_SPLIT_TX_OVERRIDE_HITS);
15800 }
15801 if let Some(buf) = &palette_y_buf
15802 && (logical_tx == side || skip)
15803 {
15804 set_palette_pred(buf.clone(), fctx);
15805 }
15806 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
15807 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
15808 // plane's own `reconstruct`/`read_plane` call below (never both planes at
15809 // once), since Y's own set-then-take already emptied the slot by the time
15810 // either of these run.
15811 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
15812 (
15813 puv.map.iter().map(|&idx| puv.u_colors[idx as usize]).collect(),
15814 puv.map.iter().map(|&idx| puv.v_colors[idx as usize]).collect(),
15815 )
15816 });
15817 // The chroma half of the intrabc prediction rides the same per-plane
15818 // override slot the UV-palette buffers do (set fresh before each plane's
15819 // own `reconstruct`/`read_plane` call below).
15820 let palette_uv_bufs = match &intrabc_bufs {
15821 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
15822 None => palette_uv_bufs,
15823 };
15824 if skip {
15825 // A skipped block codes no residual syntax at all (spec 5.11.34):
15826 // straight prediction, on every plane.
15827 //
15828 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
15829 // is skipped (only an INTER skip forces the largest transform), and
15830 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
15831 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
15832 // already written left/above of it inside this same block. Predicting
15833 // the whole `side`x`side` at once gives a different (uniformly off by
15834 // ~1) answer, which is exactly the residue this lane was chasing.
15835 // The palette/intrabc override path keeps the single-call shape (its
15836 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
15837 // untested for skip and unreachable in these streams).
15838 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
15839 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
15840 // per-unit prediction is keyed on the transform being smaller than
15841 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
15842 // narrower meaning (a READ split tx depth).
15843 let split_tx_skip =
15844 logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
15845 if split_tx_skip {
15846 if tx_select {
15847 hit!(SKIP_SPLIT_TX_HITS);
15848 }
15849 let n_axis = side / logical_tx;
15850 for tu_row in 0..n_axis {
15851 for tu_col in 0..n_axis {
15852 let tu_px = px + tu_col * logical_tx;
15853 let tu_py = py + tu_row * logical_tx;
15854 if tu_px >= y.true_width || tu_py >= y.true_height {
15855 continue;
15856 }
15857 let tu_reach = tu_reach(
15858 side,
15859 side,
15860 tu_col * logical_tx,
15861 tu_row * logical_tx,
15862 logical_tx,
15863 reach,
15864 px,
15865 py,
15866 y.width,
15867 y.height, fctx,
15868 );
15869 push_intra(0,
15870 tu_px,
15871 tu_py,
15872 logical_tx,
15873 mode,
15874 angle_delta_y,
15875 tu_reach,
15876 &ZERO_RESIDUAL[..logical_tx * logical_tx],
15877 None,
15878 filter_intra,
15879 smooth_neighbor, fctx,
15880 );
15881 }
15882 }
15883 } else {
15884 push_intra(0,
15885 px,
15886 py,
15887 side,
15888 mode,
15889 angle_delta_y,
15890 reach,
15891 &ZERO_RESIDUAL[..side * side],
15892 None,
15893 filter_intra,
15894 smooth_neighbor, fctx,
15895 );
15896 }
15897 let ac = alpha.map(|_| cfl_src(px, py, side));
15898 let cn = (chroma_side / chroma_tx).max(1);
15899 for cu_row in 0..cn {
15900 for cu_col in 0..cn {
15901 let luma_span = chroma_tx * 2;
15902 let cu_r = if cn == 1 {
15903 reach
15904 } else {
15905 tu_reach(
15906 side, side,
15907 cu_col * luma_span, cu_row * luma_span, luma_span,
15908 reach, px, py, y.width, y.height, fctx,
15909 )
15910 };
15911 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
15912 if let Some((ub, _)) = &palette_uv_bufs {
15913 set_palette_pred(ub.clone(), fctx);
15914 }
15915 push_intra(1,
15916 cu_x,
15917 cu_y,
15918 chroma_tx,
15919 uv_predict_mode,
15920 angle_delta_uv,
15921 cu_r,
15922 &ZERO_RESIDUAL[..chroma_tx * chroma_tx],
15923 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
15924 None,
15925 smooth_neighbor_uv, fctx,
15926 );
15927 if let Some((_, vb)) = &palette_uv_bufs {
15928 set_palette_pred(vb.clone(), fctx);
15929 }
15930 push_intra(2,
15931 cu_x,
15932 cu_y,
15933 chroma_tx,
15934 uv_predict_mode,
15935 angle_delta_uv,
15936 cu_r,
15937 &ZERO_RESIDUAL[..chroma_tx * chroma_tx],
15938 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
15939 None,
15940 smooth_neighbor_uv, fctx,
15941 );
15942 }
15943 }
15944 let luma_grid = vec![0i32; side * side];
15945 let u_grid = vec![0i32; chroma_side * chroma_side];
15946 let v_grid = vec![0i32; chroma_side * chroma_side];
15947 neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
15948 } else if logical_tx == side {
15949 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
15950 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
15951 // that arm was redundant -- and wrong at 128, where
15952 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
15953 // block is four units whether or not `tx_select` is on.
15954 // A single luma transform unit -- the old path, unchanged (including
15955 // the 64x64 corner case, `logical_tx == side == 64` with
15956 // `coeff_tx_side == 32`).
15957 let around = neighbours.around(at, side);
15958 let luma_grid = read_plane(
15959 dec,
15960 cdfs,
15961 luma_set,
15962 luma_scan,
15963 0,
15964 around[0],
15965 mode,
15966 mode,
15967 angle_delta_y,
15968 reach,
15969 y,
15970 px,
15971 py,
15972 side,
15973 coeff_tx_side,
15974 base_q_idx,
15975 None,
15976 filter_intra,
15977 None,
15978 smooth_neighbor, fctx,
15979 )?;
15980 let ac = alpha.map(|_| cfl_src(px, py, side));
15981 // Armed for exactly this block's two chroma reads (see
15982 // [`INTRABC_CHROMA_TX`]); the luma call above just set
15983 // [`LUMA_TX_TYPE`] to the type it coded.
15984 if intrabc_dv.is_some() {
15985 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
15986 }
15987 if let Some((ub, _)) = &palette_uv_bufs {
15988 set_palette_pred(ub.clone(), fctx);
15989 }
15990 let u_grid = read_plane(
15991 dec,
15992 cdfs,
15993 chroma_set,
15994 scans.1,
15995 1,
15996 around[1],
15997 mode,
15998 uv_predict_mode,
15999 angle_delta_uv,
16000 reach,
16001 u,
16002 cpx,
16003 cpy,
16004 chroma_side,
16005 chroma_tx,
16006 base_q_idx,
16007 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
16008 None,
16009 None,
16010 smooth_neighbor_uv, fctx,
16011 )?;
16012 if crate::envflags::env_flag!("EC_AV1_TRACE") {
16013 eprintln!(
16014 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
16015 &u.data[cpy * u.width + cpx..][..chroma_side]
16016 );
16017 }
16018 if let Some((_, vb)) = &palette_uv_bufs {
16019 set_palette_pred(vb.clone(), fctx);
16020 }
16021 let v_grid = read_plane(
16022 dec,
16023 cdfs,
16024 chroma_set,
16025 scans.1,
16026 2,
16027 around[2],
16028 mode,
16029 uv_predict_mode,
16030 angle_delta_uv,
16031 reach,
16032 v,
16033 cpx,
16034 cpy,
16035 chroma_side,
16036 chroma_tx,
16037 base_q_idx,
16038 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
16039 None,
16040 None,
16041 smooth_neighbor_uv, fctx,
16042 )?;
16043 fctx.intrabc_chroma_tx.with(|c| c.set(None));
16044 neighbours.record(at, side, mode, uv_predict_mode, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
16045 } else {
16046 // Several luma transform units, raster order (spec
16047 // `transform_block`'s loop): the block's resolved transform is
16048 // genuinely smaller than its own side, so each tile of it predicts
16049 // and codes independently, its own context read fresh off whatever
16050 // the earlier tiles in this same block already wrote -- the same
16051 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
16052 let n_axis = side / logical_tx;
16053 let cn = (chroma_side / chroma_tx).max(1);
16054 // libaom's transform-block loop is over 64x64 luma "mu" chunks
16055 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
16056 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
16057 // before moving to the next one. Below 128 a block is a single chunk,
16058 // so this is byte-for-byte the all-luma-then-all-chroma order that has
16059 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
16060 // and reading all four luma units first desyncs the tile at the second
16061 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
16062 let nchunk = (side / 64).max(1);
16063 // `cn > 1` means the uv plane block is larger than the uv transform,
16064 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
16065 let chroma_ctx_offset = if cn > 1 { Some(3) } else { None };
16066 let tpc = (n_axis / nchunk).max(1);
16067 let cpc = (cn / nchunk).max(1);
16068 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
16069 let mut units: Vec<((usize, usize), usize, Grid, Grid)> = Vec::new();
16070 for ch_row in 0..nchunk {
16071 for ch_col in 0..nchunk {
16072 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
16073 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
16074 let tu_mi = (
16075 mi_r + tu_row * (logical_tx / MI),
16076 mi_c + tu_col * (logical_tx / MI),
16077 );
16078 let tu_px = px + tu_col * logical_tx;
16079 let tu_py = py + tu_row * logical_tx;
16080 // Same libaom clip as `decode_rect_split`'s loop above; a
16081 // square block only hangs off the frame when the frame's mi
16082 // dimensions are odd at the block's own level.
16083 if tu_px >= y.true_width || tu_py >= y.true_height {
16084 continue;
16085 }
16086 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
16087 // A transform unit inside a block is NOT a block at that
16088 // position (lane-palette2 r12): `Reach::of` granted the
16089 // top-right 8x8 unit of a 16x16 D203 block bottom-left
16090 // pixels libaom refuses outright (`col_off > 0`), which is
16091 // the diagonal wedge seed 46 reconstructed wrong.
16092 let tu_reach = tu_reach(
16093 side,
16094 side,
16095 tu_col * logical_tx,
16096 tu_row * logical_tx,
16097 logical_tx,
16098 reach,
16099 px,
16100 py,
16101 y.width,
16102 y.height, fctx,
16103 );
16104 // This transform unit's own bsize (`logical_tx`) is smaller
16105 // than the block it sits in (`side`), so `txb_skip_ctx` is
16106 // the neighbour-magnitude table, not the lone-TU 0 (spec
16107 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
16108 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
16109 if let Some(buf) = &palette_y_buf {
16110 hit!(PALETTE_SPLIT_TX_HITS);
16111 let mut window = vec![0u16; logical_tx * logical_tx];
16112 for row in 0..logical_tx {
16113 let src = (tu_row * logical_tx + row) * side + tu_col * logical_tx;
16114 window[row * logical_tx..][..logical_tx]
16115 .copy_from_slice(&buf[src..][..logical_tx]);
16116 }
16117 set_palette_pred(window, fctx);
16118 }
16119 let tu_grid = read_plane(
16120 dec,
16121 cdfs,
16122 luma_set,
16123 luma_scan,
16124 0,
16125 tu_around,
16126 mode,
16127 mode,
16128 angle_delta_y,
16129 tu_reach,
16130 y,
16131 tu_px,
16132 tu_py,
16133 logical_tx,
16134 // The unit's own COEFFICIENT grid, half its side at
16135 // TX_64X64 (a 64-point transform codes nothing past 32);
16136 // identical to `logical_tx` at every smaller size
16137 // (lane-sb128b r1).
16138 coeff_tx_side,
16139 base_q_idx,
16140 None,
16141 filter_intra,
16142 Some(tu_skip_ctx),
16143 smooth_neighbor, fctx,
16144 )?;
16145 if crate::envflags::env_flag!("EC_AV1_TRACE") {
16146 eprintln!(
16147 "TRACE tu_bitpos mi=({},{}) tell={}",
16148 tu_mi.0,
16149 tu_mi.1,
16150 dec.debug_bitpos()
16151 );
16152 }
16153 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
16154 }
16155 }
16156 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
16157 // this still runs after every luma unit of the block.
16158 let ac = alpha.map(|_| cfl_src(px, py, side));
16159 // The block's uv plane block is `chroma_side` across but its uv
16160 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
16161 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
16162 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
16163 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
16164 // FOUR units (lane-sb128b r2) -- one per mu chunk.
16165 // libaom `decode_token_recon_block` codes a mu chunk PLANE-MAJOR
16166 // (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of
16167 // the chunk, then every V unit. At one unit per plane per chunk --
16168 // every non-lossless case this decoder reaches -- that is the same
16169 // symbol order as the interleaved pair this loop used to read; a
16170 // lossless frame's 4x4 chroma units are the case where it differs
16171 // (lane-lossless2).
16172 let mut u_pass: Vec<Grid> = Vec::new();
16173 for plane_pass in 1..=2usize {
16174 let mut pass_idx = 0usize;
16175 for cu_row in ch_row * cpc..(ch_row + 1) * cpc {
16176 for cu_col in ch_col * cpc..(ch_col + 1) * cpc {
16177 // libaom `decode_reconstruct_tx`'s frame-edge clip
16178 // (decodeframe.c:299, `blk_row >= max_blocks_high || blk_col
16179 // >= max_blocks_wide` returns before ANY symbol is read): a
16180 // transform unit whose 4x4 origin sits outside the frame's mi
16181 // grid is not coded at all. The luma loop above carries the
16182 // same clip; its absence here read `txb_skip` (+coeffs) for
16183 // chroma units libaom never wrote -- the lossless 64x64 block
16184 // at mi(48,0) of a 320x240 frame overhangs the bottom edge by
16185 // 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units, not
16186 // eight (lane-av1-loss64; 48 chroma units per plane in
16187 // aomdec's EC_COEFF census vs the 64 this loop read).
16188 // `max_block_wide/high` (av1_common_int.h:1565): the plane
16189 // block's pixel span (4:2:0 halves the luma span, clamped to
16190 // 4 by `set_plane_n4`) plus the negative overhang
16191 // (`mb_to_*_edge` = `2 * overhang_mi` chroma px), in 4x4
16192 // units.
16193 let span_mi = side / MI;
16194 let over_w_mi =
16195 (2 * y.true_width.div_ceil(8)) as i32 - mi_c as i32 - span_mi as i32;
16196 let over_h_mi =
16197 (2 * y.true_height.div_ceil(8)) as i32 - mi_r as i32 - span_mi as i32;
16198 let plane_px = ((span_mi * 2).max(4)) as i32;
16199 let max_units_w = ((plane_px + 2 * over_w_mi.min(0)) >> 2).max(0) as usize;
16200 let max_units_h = ((plane_px + 2 * over_h_mi.min(0)) >> 2).max(0) as usize;
16201 let unit = chroma_tx / 4; // TU side in 4x4 chroma units
16202 if cu_col * unit >= max_units_w || cu_row * unit >= max_units_h {
16203 hit!(CHROMA_EDGE_TU_CLIP_HITS);
16204 continue;
16205 }
16206 // The chroma context arrays are indexed in LUMA mi, so this
16207 // unit's anchor is its own luma quadrant: `chroma_tx` chroma
16208 // pixels span `2 * chroma_tx` luma ones.
16209 let luma_span = chroma_tx * 2;
16210 let cu_mi = (
16211 mi_r + cu_row * (luma_span / MI),
16212 mi_c + cu_col * (luma_span / MI),
16213 );
16214 let cu_around = neighbours.around_mi(cu_mi, luma_span);
16215 let cu_reach = if cn == 1 {
16216 reach
16217 } else {
16218 tu_reach(
16219 side, side,
16220 cu_col * luma_span, cu_row * luma_span, luma_span,
16221 reach, px, py, y.width, y.height, fctx,
16222 )
16223 };
16224 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx);
16225 if let Some((ub, vb)) = &palette_uv_bufs {
16226 let pbuf = if plane_pass == 1 { ub } else { vb };
16227 set_palette_pred(
16228 palette_window(
16229 pbuf, chroma_side, cu_col * chroma_tx, cu_row * chroma_tx,
16230 chroma_tx, chroma_tx,
16231 ),
16232 fctx,
16233 );
16234 }
16235 let buf: &mut PlaneBuf<'static> =
16236 if plane_pass == 1 { &mut *u } else { &mut *v };
16237 let cu_grid = read_plane(
16238 dec, cdfs, chroma_set, scans.1, plane_pass, cu_around[plane_pass], mode,
16239 uv_predict_mode, angle_delta_uv, cu_reach, buf, cu_x, cu_y,
16240 chroma_tx, chroma_tx, base_q_idx,
16241 alpha.zip(ac).map(|((au, av), ac)| {
16242 (if plane_pass == 1 { au } else { av }, ac)
16243 }),
16244 None, chroma_ctx_offset, smooth_neighbor_uv, fctx,
16245 )?;
16246 if cn > 1 {
16247 hit!(CHROMA_SPLIT_TX_HITS);
16248 // Immediately, so the NEXT unit of this same block reads
16249 // this one's coefficient context (libaom's chroma
16250 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
16251 // 1 from this left neighbour -- measured against aomdec).
16252 // The same writes are replayed after `record_split_luma`
16253 // below, which would otherwise clobber them whole-block.
16254 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_pass, &cu_grid);
16255 }
16256 if plane_pass == 1 {
16257 u_pass.push(cu_grid);
16258 } else {
16259 let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
16260 if cn > 1 {
16261 units.push((cu_mi, luma_span, u_grid.clone(), cu_grid.clone()));
16262 }
16263 last_grids = [u_grid, cu_grid];
16264 }
16265 pass_idx += 1;
16266 }
16267 }
16268 }
16269 }
16270 }
16271 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
16272 // context write; at `cn > 1` the per-unit writes above are what the
16273 // next block reads, so they run after this (last writer wins).
16274 neighbours.record_split_luma(at, side, mode, uv_predict_mode, [&last_grids[0], &last_grids[1]]);
16275 for (cu_mi, luma_span, u_grid, v_grid) in &units {
16276 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 1, u_grid);
16277 neighbours.record_mi_chroma(*cu_mi, *luma_span, *luma_span, 2, v_grid);
16278 }
16279 }
16280 // Unconditional, `size == 0` for a non-palette block: clears any stale
16281 // neighbour palette state the same way [`Neighbours::record`] always
16282 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
16283 // (the split-luma-TU branch above always refuses before reaching here
16284 // when `palette_y` is `Some`, so it is never live for that branch).
16285 let (py_size, py_colors) = palette_y
16286 .as_ref()
16287 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
16288 neighbours.record_palette_y(at, side, py_size, py_colors);
16289 let (puv_size, puv_colors) = palette_uv
16290 .as_ref()
16291 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
16292 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
16293 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
16294 neighbours.fill_lf_grid(
16295 (r * (SUB / MI), c * (SUB / MI)),
16296 side / MI,
16297 logical_tx as u8,
16298 0, fctx,
16299 );
16300 // lane-t900 r32 / lane-av1txbands: libaom runs `set_txfm_ctxs(mbmi->tx_size,
16301 // n4_w, n4_h, skip_txfm && is_inter_block(mbmi), xd)` at the end of EVERY
16302 // `decode_block`. An intra-only frame's blocks also publish their TRANSFORM
16303 // size from [`Neighbours::fill_lf_grid_rect`], but this grid cannot express
16304 // libaom's `skip && is_inter` term -- the one thing that makes a SKIPPED
16305 // intrabc block publish its BLOCK size instead, intrabc being the only
16306 // "inter" block an intra-only frame codes (`blockd.h:373`). So this call
16307 // stays the authority wherever one can appear; with `allow_intrabc` unset
16308 // it writes exactly what the grid already did.
16309 if allow_intrabc {
16310 set_txfm_ctxs(
16311 neighbours,
16312 (mi_r, mi_c),
16313 logical_tx,
16314 side / MI,
16315 side / MI,
16316 skip && intrabc_dv.is_some(),
16317 );
16318 }
16319 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, neighbours, fctx);
16320 Ok(())
16321}
16322
16323thread_local! {
16324 /// lane-sb128c r8: INTRA (key-frame) 128x64 blocks decoded at the 128
16325 /// root's HORZ arm, and 64x128 ones at its VERT arm.
16326 pub(crate) static INTRA_SB128_HORZ_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
16327 pub(crate) static INTRA_SB128_VERT_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
16328 /// Those blocks by resolved intra `tx_depth` (0 = TX_64X64 units,
16329 /// 1 = TX_32X32, 2 = TX_16X16) -- proof the depth symbol is really read.
16330 pub(crate) static INTRA_SB128_DEPTH_HITS: std::cell::Cell<[usize; 3]> = const { std::cell::Cell::new([0; 3]) };
16331 /// lane-inter128intra r1: the same shapes decoded on the INTER block path
16332 /// (an intra-coded PARTITION_HORZ/VERT half of a 128 superblock inside an
16333 /// inter frame) -- (128x64, 64x128).
16334 pub(crate) static INTRA128_IN_INTER_HITS: std::cell::Cell<[usize; 2]> = const { std::cell::Cell::new([0; 2]) };
16335 /// lane-t900 r17: skipped INTER blocks whose `read_block_tx_size` still
16336 /// handed back var-tx leaves, so the per-transform-unit luma publication
16337 /// loop never ran and the block has to clear its own luma coefficient
16338 /// contexts (libaom `av1_reset_entropy_context`). Every 128 root under
16339 /// `TX_MODE_LARGEST` is one; the counter is what keeps that reset's gate
16340 /// non-vacuous.
16341 pub(crate) static SKIP_VARTX_LUMA_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
16342 /// lane-lossless128: an intra 128-axis (BLOCK_128X64/64X128) block decoded
16343 /// on a LOSSLESS frame, where every plane is coded as TX_4X4 units (the
16344 /// frame's `tx_mode` is forced `ONLY_4X4`). Keeps the gate that owns this
16345 /// shape non-vacuous -- a stream that never codes one reads 0.
16346 pub(crate) static INTRA128_LOSSLESS_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
16347}
16348
16349/// [`SKIP_VARTX_LUMA_RESET_HITS`], for a gate's own before/after delta.
16350pub fn skip_vartx_luma_reset_hits() -> usize {
16351 SKIP_VARTX_LUMA_RESET_HITS.with(std::cell::Cell::get)
16352}
16353
16354/// [`INTRA128_LOSSLESS_HITS`], for a gate's own before/after delta.
16355pub(crate) fn intra128_lossless_hits() -> usize {
16356 INTRA128_LOSSLESS_HITS.with(std::cell::Cell::get)
16357}
16358
16359/// [`INTRA128_IN_INTER_HITS`], for a gate's own before/after delta.
16360pub(crate) fn intra128_in_inter_hits() -> [usize; 2] {
16361 INTRA128_IN_INTER_HITS.with(std::cell::Cell::get)
16362}
16363
16364/// [`INTRA_SB128_HORZ_HITS`] / [`INTRA_SB128_VERT_HITS`] /
16365/// [`INTRA_SB128_DEPTH_HITS`], for a gate's own before/after delta.
16366pub(crate) fn intra_sb128_hits() -> (usize, usize, [usize; 3]) {
16367 (
16368 INTRA_SB128_HORZ_HITS.with(std::cell::Cell::get),
16369 INTRA_SB128_VERT_HITS.with(std::cell::Cell::get),
16370 INTRA_SB128_DEPTH_HITS.with(std::cell::Cell::get),
16371 )
16372}
16373
16374/// The 128 root's HORZ/VERT arm on an INTRA frame: ONE 128x64 (HORZ) or
16375/// 64x128 (VERT) intra block (lane-sb128c r8; the inter twin is
16376/// `decode_inter_block`'s own rect path).
16377///
16378/// libaom `decode_block` -> `predict_and_reconstruct_intra_block` per
16379/// transform unit, with the 128-specific geometry:
16380/// * `max_txsize_rect_lookup[BLOCK_128X64]` is TX_64X64, so every luma unit
16381/// is SQUARE and there are at least two of them -- depth 0: 64x64 x2,
16382/// depth 1: 32x32 x8, depth 2: 16x16 x32 (`bsize_to_tx_size_cat` counts
16383/// the `sub_tx_size_map` chain TX_64X64->32->16->8->4, i.e. cat 3, the
16384/// same CDF a 64x64 square block reads).
16385/// * `av1_get_max_uv_txsize` = `av1_get_adjusted_tx_size(
16386/// max_txsize_rect_lookup[BLOCK_64X32])` caps at TX_32X32, so the block's
16387/// 64x32 uv plane block is TWO 32x32 chroma units per plane -- one per
16388/// 64x64 luma "mu" chunk, and `decode_token_recon_block` codes Y, U, V of
16389/// a chunk before moving to the next (the interleave lane-sb128b r3
16390/// measured at the 128x128 NONE root).
16391/// * `get_txb_ctx`: the uv plane block is bigger than the uv transform, so
16392/// chroma `txb_skip_ctx` takes the offset-10 rows (7 + 3).
16393/// No CfL, no filter intra (both cap at 32x32) and no palette
16394/// (`av1_allow_palette` caps at 64x64) exist at this size -- the mode
16395/// reader's own size gates already say so, and the guard below is defensive.
16396///
16397/// lane-lossless128: on a LOSSLESS frame every one of those sizes collapses to
16398/// TX_4X4 -- `read_tx_mode` returns `ONLY_4X4` before the frame codes a tx-size
16399/// symbol and `read_tx_size` returns `TX_4X4` before it looks at anything
16400/// (`decodeframe.c:141`, `:1183`) -- so the block is tiled into 4x4 luma units
16401/// and (because a lossless frame forces `TX_4X4` on CHROMA too) 4x4 chroma
16402/// units, plane-major inside each 64x64 mu chunk exactly as
16403/// `decode_token_recon_block` codes them. Reading the 64-point geometry there
16404/// reconstructs into a `side`-sized plane with a 16-sample residual (the panic
16405/// this lane closed); the geometry and the unit walks below are normalized on
16406/// `lossless_frame`.
16407#[allow(clippy::too_many_arguments)]
16408fn decode_block_128rect(
16409 dec: &mut SymbolDecoder,
16410 cdfs: &mut Cdfs,
16411 neighbours: &mut Neighbours,
16412 at: (usize, usize),
16413 bw: usize,
16414 bh: usize,
16415 y: &mut PlaneBuf<'static>,
16416 u: &mut PlaneBuf<'static>,
16417 v: &mut PlaneBuf<'static>,
16418 base_q_idx: u8,
16419 enable_filter_intra: bool,
16420 allow_screen_content_tools: bool,
16421 tx_select: bool,
16422 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
16423) -> Result<()> {
16424 let (r, c) = at;
16425 let (px, py) = (c * SUB, r * SUB);
16426 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
16427 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
16428 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
16429 let palette_uv_cache = neighbours.palette_uv_cache(at);
16430 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv, intrabc) =
16431 read_intra_mode_rect(
16432 dec,
16433 cdfs,
16434 nb_above_mode,
16435 nb_left_mode,
16436 // `is_cfl_allowed` caps CFL at 32x32: `uv_mode` comes off the
16437 // 13-symbol no-CFL CDF here, never the 14-symbol one.
16438 false,
16439 true,
16440 bw,
16441 bh,
16442 enable_filter_intra,
16443 neighbours.skip_txfm_ctx(mi_r, mi_c),
16444 allow_screen_content_tools,
16445 Some((palette_ctx, &palette_cache)),
16446 &palette_uv_cache,
16447 mi_r,
16448 mi_c, fctx,
16449 )?;
16450 if intrabc.is_some() {
16451 return Err(unsupported(
16452 "intra block copy on a HORZ/VERT/1:4 rect intra strip (reconstruction is not ported at this shape)",
16453 ));
16454 }
16455 if alpha.is_some() || filter_intra.is_some() || palette_y.is_some() || palette_uv.is_some() {
16456 return Err(unsupported(
16457 "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block (every one of \
16458 their size gates caps at 64x64 or below, so none of these symbols exists there)",
16459 ));
16460 }
16461 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
16462 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
16463 if smooth_neighbor {
16464 hit!(SMOOTH_LUMA_HITS);
16465 }
16466 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c);
16467 // spec 5.11.16 `read_tx_size`: read for every intra block, skipped or
16468 // not. `bsize_to_tx_size_cat(BLOCK_128X64)` is 3 (see this fn's doc).
16469 // lane-lossless128: a LOSSLESS frame codes no tx-size symbol at all --
16470 // libaom's `read_tx_mode` returns `ONLY_4X4` for a `coded_lossless` frame
16471 // before the symbol is even considered (`decodeframe.c:141`) and
16472 // `read_tx_size` returns `TX_4X4` before it looks at anything
16473 // (`decodeframe.c:1183`). So `tx_select` is off, every plane is walked as
16474 // TX_4X4 transform units, and no `tx_size_cat3` symbol may be consumed.
16475 let lossless_frame = lossless(fctx);
16476 let in_inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_some();
16477 let depth = if tx_select && !lossless_frame {
16478 // lane-inter128intra r1: `get_tx_size_context` compares the bands
16479 // against `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` --
16480 // TX_64X64 for every 128-axis block, hence the `min(64)`.
16481 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
16482 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
16483 } else {
16484 0
16485 };
16486 if depth != 0 {
16487 hit!(TX_DEPTH_HITS);
16488 }
16489 hit_do! {
16490 INTRA_SB128_DEPTH_HITS.with(|c| {
16491 let mut h = c.get();
16492 h[depth.min(2)] += 1;
16493 c.set(h);
16494 });
16495 }
16496 let logical_tx = if lossless_frame { 4 } else { 64 >> depth };
16497 if lossless_frame {
16498 hit!(INTRA128_LOSSLESS_HITS);
16499 }
16500 // A 64-point transform codes nothing past its low 32 coefficients.
16501 let coeff_tx_side = logical_tx.min(32);
16502 let luma_set = if lossless_frame {
16503 TxbSet::Luma4
16504 } else {
16505 txbset_for(logical_tx, reduced_tx_set)
16506 };
16507 let luma_scan = default_scan(coeff_tx_side);
16508 // `av1_get_max_uv_txsize` caps at TX_32X32 normally; a lossless frame
16509 // forces every plane to TX_4X4 (its own `Chroma4` set and 4x4 scan).
16510 let chroma_tx = if lossless_frame { 4 } else { 32 };
16511 let chroma_set = if lossless_frame {
16512 TxbSet::Chroma4
16513 } else {
16514 TxbSet::Chroma32
16515 };
16516 let chroma_scan = default_scan(chroma_tx);
16517 let (cpx, cpy) = (px / 2, py / 2);
16518 let (chroma_w, chroma_h) = (bw / 2, bh / 2);
16519 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
16520 let (nch_x, nch_y) = (bw / 64, bh / 64);
16521 // The frame's own mi grid (`av1_calc_mi_size`, 8-px aligned): libaom's
16522 // `decode_token_recon_block` clips each vector's walk to
16523 // `max_block_wide/high`, so a chroma unit whose top-left is off the frame
16524 // codes nothing.
16525 let mi_cols = 2 * y.true_width.div_ceil(8);
16526 let mi_rows = 2 * y.true_height.div_ceil(8);
16527 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
16528 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
16529 // Non-lossless: one 32x32 chroma unit per mu chunk, per plane.
16530 debug_assert!(lossless_frame || (chroma_w / chroma_tx, chroma_h / chroma_tx) == (nch_x, nch_y));
16531 let tpc = 64 / logical_tx;
16532 let zero_tu = vec![0i32; logical_tx * logical_tx];
16533 let zero_cu = vec![0i32; chroma_tx * chroma_tx];
16534 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
16535 let mut units: Vec<(usize, (usize, usize), Grid)> = Vec::new();
16536 // The chroma context arrays are indexed in LUMA mi; every chroma unit of
16537 // every chunk shares this luma span (2 chroma pixels per luma unit).
16538 let luma_span = chroma_tx * 2;
16539 for ch_row in 0..nch_y {
16540 for ch_col in 0..nch_x {
16541 for tu_row in ch_row * tpc..(ch_row + 1) * tpc {
16542 for tu_col in ch_col * tpc..(ch_col + 1) * tpc {
16543 let tu_mi = (
16544 mi_r + tu_row * (logical_tx / MI),
16545 mi_c + tu_col * (logical_tx / MI),
16546 );
16547 let (tu_px, tu_py) = (px + tu_col * logical_tx, py + tu_row * logical_tx);
16548 // libaom clips the transform loop to
16549 // `max_blocks_wide/high`: a unit whose top-left sample is
16550 // outside the frame is never coded.
16551 if tu_px >= y.true_width || tu_py >= y.true_height {
16552 continue;
16553 }
16554 // Edge availability of a unit INSIDE a block, with the
16555 // 128 geometry -- `has_top_right` is false for a block
16556 // whose largest side is > 64, which [`Reach::of_rect`]
16557 // already answered for the block and [`tu_reach`] carries
16558 // down to the units on its own top row.
16559 let tu_r = tu_reach(
16560 bw,
16561 bh,
16562 tu_col * logical_tx,
16563 tu_row * logical_tx,
16564 logical_tx,
16565 reach,
16566 px,
16567 py,
16568 y.width,
16569 y.height, fctx,
16570 );
16571 if skip {
16572 push_intra(0,
16573 tu_px, tu_py, logical_tx, mode, angle_delta_y, tu_r, &zero_tu, None,
16574 None, smooth_neighbor, fctx,
16575 );
16576 neighbours.record_mi_luma(tu_mi, logical_tx, &zero_tu);
16577 continue;
16578 }
16579 // The unit is smaller than its block, so `txb_skip_ctx`
16580 // is the neighbour-magnitude table, never the lone-TU 0.
16581 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, logical_tx / MI);
16582 let tu_around = neighbours.around_mi(tu_mi, logical_tx)[0];
16583 let tu_grid = read_plane(
16584 dec,
16585 cdfs,
16586 luma_set,
16587 &luma_scan,
16588 0,
16589 tu_around,
16590 mode,
16591 mode,
16592 angle_delta_y,
16593 tu_r,
16594 y,
16595 tu_px,
16596 tu_py,
16597 logical_tx,
16598 coeff_tx_side,
16599 base_q_idx,
16600 None,
16601 None,
16602 Some(tu_skip_ctx),
16603 smooth_neighbor, fctx,
16604 )?;
16605 neighbours.record_mi_luma(tu_mi, logical_tx, &tu_grid);
16606 }
16607 }
16608 // Transform units per axis inside this mu chunk's 32x32 chroma
16609 // span: one 32x32 unit normally, 8x8 TX_4X4 units when lossless.
16610 let cn = (32 / chroma_tx).max(1);
16611 // libaom's per-chunk `unit_width/height` (plane-mi units of the
16612 // luma mi grid): `min(mu_blocks + col, max_blocks) >> ss`.
16613 let unit_w = ((ch_col + 1) * 16).min(max_w_mi) >> 1;
16614 let unit_h = ((ch_row + 1) * 16).min(max_h_mi) >> 1;
16615 let stepc = (chroma_tx / 4).max(1);
16616 // `decode_token_recon_block` codes a mu chunk PLANE-MAJOR: every U
16617 // unit of the chunk, then every V unit. At one unit per plane per
16618 // chunk (every non-lossless 128-axis block) that is the same
16619 // symbol order the interleaved pair used to read; a lossless
16620 // frame's 4x4 chroma units are where it becomes observable.
16621 for plane_pass in 1..=2usize {
16622 for ci_row in 0..cn {
16623 for ci_col in 0..cn {
16624 if ch_col * 8 + ci_col * stepc >= unit_w
16625 || ch_row * 8 + ci_row * stepc >= unit_h
16626 {
16627 continue;
16628 }
16629 let cu_x = cpx + ch_col * 32 + ci_col * chroma_tx;
16630 let cu_y = cpy + ch_row * 32 + ci_row * chroma_tx;
16631 let cu_mi = (
16632 mi_r + ch_row * 16 + ci_row * (chroma_tx / 2),
16633 mi_c + ch_col * 16 + ci_col * (chroma_tx / 2),
16634 );
16635 let cu_r = tu_reach(
16636 bw,
16637 bh,
16638 ch_col * 64 + ci_col * luma_span,
16639 ch_row * 64 + ci_row * luma_span,
16640 luma_span,
16641 reach,
16642 px,
16643 py,
16644 y.width,
16645 y.height, fctx,
16646 );
16647 if skip {
16648 push_intra(plane_pass,
16649 cu_x, cu_y, chroma_tx, uv_predict_mode, angle_delta_uv, cu_r,
16650 &zero_cu, None, None, smooth_neighbor_uv, fctx,
16651 );
16652 continue;
16653 }
16654 let cu_around = neighbours.around_mi(cu_mi, luma_span);
16655 let buf: &mut PlaneBuf<'static> =
16656 if plane_pass == 1 { &mut *u } else { &mut *v };
16657 let grid = read_plane(
16658 dec, cdfs, chroma_set, &chroma_scan, plane_pass, cu_around[plane_pass],
16659 mode, uv_predict_mode, angle_delta_uv, cu_r, buf, cu_x, cu_y,
16660 chroma_tx, chroma_tx, base_q_idx, None, None, Some(3),
16661 smooth_neighbor_uv, fctx,
16662 )?;
16663 last_grids[plane_pass - 1] = grid.clone();
16664 // Immediately, so the NEXT unit of this same block
16665 // reads this one's coefficient context; replayed after
16666 // `record_split_luma_rect` below, which would otherwise
16667 // clobber them whole-block.
16668 neighbours.record_mi_chroma(cu_mi, luma_span, luma_span, plane_pass, &grid);
16669 units.push((plane_pass, cu_mi, grid));
16670 }
16671 }
16672 }
16673 if !skip {
16674 hit!(CHROMA_SPLIT_TX_HITS);
16675 }
16676 }
16677 }
16678 if skip {
16679 neighbours.record_rect(
16680 at,
16681 bw,
16682 bh,
16683 mode,
16684 uv_predict_mode,
16685 &[
16686 &ZERO_RESIDUAL[..bw * bh],
16687 &ZERO_RESIDUAL[..chroma_w * chroma_h],
16688 &ZERO_RESIDUAL[..chroma_w * chroma_h],
16689 ],
16690 );
16691 } else {
16692 neighbours.record_split_luma_rect(
16693 at,
16694 bw,
16695 bh,
16696 mode,
16697 uv_predict_mode,
16698 [&last_grids[0], &last_grids[1]],
16699 );
16700 for (plane, cu_mi, grid) in &units {
16701 neighbours.record_mi_chroma(*cu_mi, luma_span, luma_span, *plane, grid);
16702 }
16703 }
16704 // No palette exists at this size; the unconditional stamp clears any
16705 // stale neighbour palette state, as every other block path does.
16706 neighbours.record_palette_y_rect(at, bw, bh, 0, [0u16; 8]);
16707 neighbours.record_palette_uv_rect(at, bw, bh, 0, [0u16; 8]);
16708 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
16709 neighbours.fill_lf_grid_rect(
16710 (mi_r, mi_c),
16711 bw / MI,
16712 bh / MI,
16713 logical_tx as u8,
16714 logical_tx as u8,
16715 0, fctx,
16716 );
16717 if in_inter || allow_intrabc_frame(fctx) {
16718 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)`
16719 // (libaom `decodeframe.c` `decode_block`) runs for EVERY block of an
16720 // inter frame, intra ones included: an intra block stamps its
16721 // TRANSFORM size over its own footprint in both TXFM_CONTEXT bands.
16722 // A key frame reads those bands only when it allows intrabc
16723 // ([`read_block_tx_size_rect`]'s var-tx context), and then libaom
16724 // stamps here too -- lane-av1-intrabc r3.
16725 txfm_partition_update_rect(
16726 neighbours,
16727 (mi_r, mi_c),
16728 (logical_tx, logical_tx),
16729 (bw, bh),
16730 );
16731 }
16732 if in_inter {
16733 hit_do! {
16734 INTRA128_IN_INTER_HITS.with(|c| {
16735 let mut h = c.get();
16736 h[usize::from(bw < bh)] += 1;
16737 c.set(h);
16738 });
16739 }
16740 } else if bw > bh {
16741 hit!(INTRA_SB128_HORZ_HITS);
16742 } else {
16743 hit!(INTRA_SB128_VERT_HITS);
16744 }
16745 Ok(())
16746}
16747
16748
16749/// Decodes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect), mirroring
16750/// [`crate::tile::write_leaf8`]: its intra-mode context comes from the
16751/// *enclosing* 16x16 slot's `above_mode`/`left_mode` (`outer_at`, [`SUB`]-grid),
16752/// overridden on whichever axis `prev_leaf` sits along -- the previous leaf's
16753/// just-decoded mode, not the enclosing slot's stale one, is the true
16754/// neighbour there. `leaf_mi` is this leaf's own position in 4x4 mode-info
16755/// units, which is what its coefficient context (finer than [`SUB`]) is read
16756/// at. Returns the mode this leaf decoded, for the caller's own
16757/// `prev_leaf`/final mode-writeback bookkeeping.
16758#[allow(clippy::too_many_arguments)]
16759/// The coarse 16x16 `above_mode`/`left_mode` cells a four-way SPLIT of one
16760/// 16x16 parent leaves behind (lane-rectx r3). The next block DOWN reads
16761/// `above_mode[col]`, and its true above neighbour is the mi directly above
16762/// its own top-left corner -- the parent's BOTTOM-LEFT leaf, not the last one
16763/// decoded; the next block RIGHT reads `left_mode[row]`, whose true left
16764/// neighbour is the parent's TOP-RIGHT leaf. Writing the z-order last leaf
16765/// (bottom-right) into both, as this path did, is right only when all four
16766/// leaves happen to share a mode. `done` may be short at the true frame edge
16767/// (the straddle caller filters positions off the frame), so each side falls
16768/// back to the last leaf actually decoded.
16769fn write_back_split_modes(
16770 neighbours: &mut Neighbours,
16771 done: &[((usize, usize), usize)],
16772 parent_mi: (usize, usize),
16773 slot: (usize, usize),
16774) {
16775 let (sr, sc) = slot;
16776 let Some(&(_, last)) = done.last() else {
16777 return;
16778 };
16779 let find = |mi: (usize, usize)| done.iter().find(|&&(at, _)| at == mi).map(|&(_, m)| m);
16780 neighbours.above_mode[sc] = find((parent_mi.0 + 2, parent_mi.1)).unwrap_or(last);
16781 neighbours.left_mode[sr] = find((parent_mi.0, parent_mi.1 + 2)).unwrap_or(last);
16782}
16783
16784fn decode_leaf8(
16785 dec: &mut SymbolDecoder,
16786 cdfs: &mut Cdfs,
16787 neighbours: &mut Neighbours,
16788 outer_at: (usize, usize),
16789 leaf_mi: (usize, usize),
16790 scans: (&[u16], &[u16]),
16791 prev_leaf: Option<((usize, usize), usize)>,
16792 y: &mut PlaneBuf<'static>,
16793 u: &mut PlaneBuf<'static>,
16794 v: &mut PlaneBuf<'static>,
16795 base_q_idx: u8,
16796 enable_filter_intra: bool,
16797 allow_screen_content_tools: bool,
16798 allow_intrabc: bool,
16799 tx_select: bool,
16800 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
16801) -> Result<usize> {
16802 let (r, c) = outer_at;
16803 // lane-modectx r1: the group's own availability-correct fallback pair, not
16804 // the raw coarse bands (which leak across a tile edge -- see
16805 // `modes_above_left`).
16806 let (mut above_mode, mut left_mode) = neighbours.modes_above_left(r, c);
16807 if let Some(((pr, pc), pmode)) = prev_leaf {
16808 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
16809 above_mode = pmode;
16810 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
16811 left_mode = pmode;
16812 }
16813 }
16814 // The mi-exact neighbour wins over both the coarse 16x16 slot and
16815 // `prev_leaf`: one 16x16 slot cannot hold the two different modes its
16816 // two 8x8 (or four 4x4) columns leave behind, so a leaf whose above/left
16817 // neighbour sits in a split cell read the wrong `kf_y_mode` row.
16818 // lane-rectsplitx r2 swept this arm into
16819 // [`Neighbours::modes_above_left_mi`]: the mi-exact map ALSO has to answer
16820 // "no neighbour" at a tile edge, where the coarse cell holds the block
16821 // above/left of it inside the same 16x16.
16822 let (above_mode, left_mode) =
16823 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
16824 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
16825 // Chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
16826 // (`get_intra_edge_filter_type`, reconintra.c:974), never the luma mode
16827 // this leaf's `smooth_neighbor` is built from -- passing `false` here
16828 // filtered a directional chroma block's edge at the wrong strength
16829 // (lane-sub8 r5: 4 pixels of one 8x8 leaf's chroma, deltas 1..3).
16830 // The `uv_mode` neighbours are mi-exact (`uv_mode_col`/`uv_mode_row`),
16831 // with the coarse [`SUB`] slot as the fallback when no block recorded
16832 // that exact mi cell.
16833 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
16834 if smooth_neighbor {
16835 hit!(SMOOTH_LUMA_HITS);
16836 }
16837 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
16838 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
16839 // `decode_block` caller at 16x16 and up.
16840 // lane-pal8 r1: this leaf's own palette-Y mode ctx and colour cache
16841 // (`av1_get_palette_mode_ctx` / `av1_get_palette_cache`, decodemv.c:567,
16842 // `read_palette_mode_info`), at its REAL mi position -- passing
16843 // `None`/`&[]` read `palette_y_mode` off CDF row 0 and refused by name the
16844 // moment a real 8x8 palette block fired, which is where every 8-bit
16845 // `--tune-content=screen --min-partition-size=8` stream stopped.
16846 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(leaf_mi);
16847 let palette_uv_cache = neighbours.palette_uv_cache_mi(leaf_mi);
16848 let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra, palette_y, palette_uv) =
16849 read_intra_mode(
16850 dec,
16851 cdfs,
16852 above_mode,
16853 left_mode,
16854 true,
16855 8,
16856 enable_filter_intra,
16857 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
16858 allow_screen_content_tools,
16859 allow_intrabc,
16860 Some((palette_ctx, &palette_cache)),
16861 &palette_uv_cache,
16862 leaf_mi.0,
16863 leaf_mi.1, fctx,
16864 )?;
16865 // lane-kf900 r7: an 8x8 leaf consumed `use_intrabc` (and its DV) through
16866 // `read_intra_mode` and then decoded the block as if it were ordinary
16867 // intra. libaom's `is_inter_block` counts an intrabc block
16868 // (`blockd.h:373`), so its luma `tx_type` comes off the INTER ext-tx set
16869 // (`av1_get_ext_tx_set_type(TX_8X8, is_inter=1, 0)` = `EXT_TX_SET_ALL16`,
16870 // a 16-symbol CDF) while we read the 7-symbol `TX_SET_INTRA_1` row: the
16871 // same value with a different interval, so the tile desynced at the very
16872 // next symbol (class `wrong-alphabet-same-value`). Everything below
16873 // mirrors `decode_block`'s own intrabc handling at 16x16 and up.
16874 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
16875 if intrabc_dv.is_some() {
16876 hit!(LEAF8_INTRABC_HITS);
16877 }
16878 // `av1_visit_palette`'s reconstruction (decodeframe.c:1135): the colour
16879 // index map, mapped through the base colours, IS the block's prediction --
16880 // carried to the next `reconstruct`/`read_plane` through the same
16881 // [`PALETTE_PRED`] slot [`decode_block`] uses at 16x16 and up.
16882 let palette_y_buf: Option<Vec<u16>> = palette_y
16883 .as_ref()
16884 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
16885 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
16886 (
16887 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
16888 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
16889 )
16890 });
16891 let (pal_y_size, pal_y_colors) =
16892 palette_y.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.colors));
16893 let (pal_uv_size, pal_uv_colors) =
16894 palette_uv.as_ref().map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
16895 if palette_y.is_some() || palette_uv.is_some() {
16896 hit!(PALETTE_LEAF8_HITS);
16897 }
16898 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
16899 DC_PRED
16900 } else {
16901 uv_mode
16902 };
16903 neighbours.above_uv_mode[c] = uv_predict_mode;
16904 neighbours.left_uv_mode[r] = uv_predict_mode;
16905 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
16906 // `TxMode::Select`'s `tx_depth` at an 8x8 leaf (spec 5.11.16): the only
16907 // depths an 8x8 block offers are `TX8` (depth 0) and `TX4` (depth 1,
16908 // which splits the leaf's own 8x8 prediction into a 2x2 grid of 4x4
16909 // transform units, same raster-order per-TU pattern `decode_block`'s
16910 // multi-TU branch runs).
16911 // ... and an intrabc leaf reads no intra `tx_depth` symbol at all: libaom
16912 // dispatches `read_block_tx_size` on `is_inter_block`, which counts an
16913 // intrabc block, so a SKIPPED one takes the largest transform and an
16914 // UNSKIPPED one reads the inter var-tx tree (lane-t900 r32). At 8x8 that
16915 // tree is one `txfm_split` symbol: TX_8X8, or TX_4X4 over all four mi
16916 // cells (`read_var_tx_size`'s `sub_txs == TX_4X4` early return).
16917 let resolved = if tx_select && intrabc_dv.is_some() && !skip {
16918 let mut leaves = Vec::new();
16919 let mi_cols = 2 * y.true_width.div_ceil(8);
16920 let mi_rows = 2 * y.true_height.div_ceil(8);
16921 read_var_tx_size(
16922 dec,
16923 cdfs,
16924 neighbours,
16925 leaf_mi,
16926 8,
16927 (
16928 2usize.min(mi_cols.saturating_sub(leaf_mi.1)),
16929 2usize.min(mi_rows.saturating_sub(leaf_mi.0)),
16930 ),
16931 (8, 8),
16932 0,
16933 0,
16934 0,
16935 &mut leaves,
16936 );
16937 hit!(INTRABC_VARTX_HITS);
16938 leaves.first().map_or(8, |l| l.2)
16939 } else if tx_select && intrabc_dv.is_none() {
16940 read_tx_size(dec, cdfs, neighbours, leaf_mi, 8)
16941 } else {
16942 // lane-lossless: TX_4X4 on a lossless frame, no symbol
16943 // (libaom `read_tx_size`).
16944 lossless_tx(8, fctx)
16945 };
16946 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
16947 let reach = Reach::of(8, px, py, y.width, y.height, fctx);
16948 let (cpx, cpy) = (px / 2, py / 2);
16949 // spec 7.11.3.4 with `use_intrabc`, same as `decode_block`: predict from
16950 // the CURRENT frame's own pre-loop-filter reconstruction (every loop
16951 // filter is off whenever `allow_intrabc`, frame.rs:194/210/252/272) at
16952 // the full-pel block vector, with the BILINEAR kernel libaom forces.
16953 flush_recon(fctx, y, u, v);
16954 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
16955 let mut yb = vec![0u16; 8 * 8];
16956 mc::predict_with_filter(
16957 &y.data, y.width, y.true_width, y.true_height,
16958 mv_to_q4(px, dv_col, true), mv_to_q4(py, dv_row, true),
16959 8, 8, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
16960 );
16961 let mut ub = vec![0u16; 4 * 4];
16962 mc::predict_with_filter(
16963 &u.data, u.width, u.true_width, u.true_height,
16964 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
16965 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
16966 );
16967 let mut vb = vec![0u16; 4 * 4];
16968 mc::predict_with_filter(
16969 &v.data, v.width, v.true_width, v.true_height,
16970 mv_to_q4(cpx, dv_col, false), mv_to_q4(cpy, dv_row, false),
16971 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
16972 );
16973 (yb, ub, vb)
16974 });
16975 // The per-plane prediction override rides the same [`PALETTE_PRED`] slot
16976 // `decode_block` uses: set fresh right before each plane's own
16977 // `reconstruct`/`read_plane` call (the slot is taken, not copied).
16978 // lane-t900 r32: through `palette_y_buf`, so the 4x4 TU loop below windows
16979 // it per unit (an intrabc leaf whose var-tx tree split to TX_4X4 is the
16980 // first shape that reaches that loop with an override set).
16981 let palette_y_buf = match &intrabc_bufs {
16982 Some((yb, _, _)) => Some(yb.clone()),
16983 None => palette_y_buf,
16984 };
16985 let (luma_grid, u_grid, v_grid);
16986 if skip {
16987 // lane-hgkf r2 (same shape as `decode_block`'s own skip branch): an
16988 // 8x8 leaf whose `tx_depth` resolved to TX_4X4 predicts FOUR 4x4
16989 // transform units, each off the units already written left/above of
16990 // it inside this same leaf -- an intra block's transform size is read
16991 // whether or not it is skipped, and spec 7.11.2 predicts per unit.
16992 // A palette block's prediction is the whole-block index map, never
16993 // per-transform-unit edges ([`decode_block`]'s own `split_tx_skip`
16994 // rule) -- so a palette leaf takes the single 8x8 reconstruct below
16995 // even when `tx_depth` resolved to TX_4X4.
16996 if resolved == 4 && palette_y_buf.is_none() {
16997 hit!(SKIP_SPLIT_TX_HITS);
16998 for tu_row in 0..2 {
16999 for tu_col in 0..2 {
17000 let (tu_px, tu_py) = (px + tu_col * 4, py + tu_row * 4);
17001 if tu_px >= y.true_width || tu_py >= y.true_height {
17002 continue;
17003 }
17004 let tu_reach = tu_reach(
17005 8,
17006 8,
17007 tu_col * 4,
17008 tu_row * 4,
17009 4,
17010 reach,
17011 px,
17012 py,
17013 y.width,
17014 y.height, fctx,
17015 );
17016 push_intra(0,
17017 tu_px,
17018 tu_py,
17019 4,
17020 mode,
17021 angle_delta_y,
17022 tu_reach,
17023 &ZERO_RESIDUAL[..16],
17024 None,
17025 filter_intra,
17026 smooth_neighbor, fctx,
17027 );
17028 }
17029 }
17030 } else {
17031 if let Some(buf) = &palette_y_buf {
17032 set_palette_pred(buf.clone(), fctx);
17033 }
17034 push_intra(0,
17035 px,
17036 py,
17037 8,
17038 mode,
17039 angle_delta_y,
17040 reach,
17041 &ZERO_RESIDUAL[..64],
17042 None,
17043 filter_intra,
17044 smooth_neighbor, fctx,
17045 );
17046 }
17047 let ac = alpha.map(|_| cfl_src(px, py, 8));
17048 if let Some((_, ub, _)) = &intrabc_bufs {
17049 set_palette_pred(ub.clone(), fctx);
17050 } else if let Some((ub, _)) = &palette_uv_bufs {
17051 set_palette_pred(ub.clone(), fctx);
17052 }
17053 push_intra(1,
17054 cpx,
17055 cpy,
17056 4,
17057 uv_predict_mode,
17058 angle_delta_uv,
17059 reach,
17060 &ZERO_RESIDUAL[..16],
17061 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
17062 None,
17063 smooth_neighbor_uv, fctx,
17064 );
17065 if let Some((_, _, vb)) = &intrabc_bufs {
17066 set_palette_pred(vb.clone(), fctx);
17067 } else if let Some((_, vb)) = &palette_uv_bufs {
17068 set_palette_pred(vb.clone(), fctx);
17069 }
17070 push_intra(2,
17071 cpx,
17072 cpy,
17073 4,
17074 uv_predict_mode,
17075 angle_delta_uv,
17076 reach,
17077 &ZERO_RESIDUAL[..16],
17078 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
17079 None,
17080 smooth_neighbor_uv, fctx,
17081 );
17082 luma_grid = Grid::Zero(64);
17083 u_grid = Grid::Zero(16);
17084 v_grid = Grid::Zero(16);
17085 } else if resolved != 4 {
17086 let around = neighbours.around_mi(leaf_mi, 8);
17087 if let Some(buf) = &palette_y_buf {
17088 set_palette_pred(buf.clone(), fctx);
17089 }
17090 luma_grid = read_plane(
17091 dec,
17092 cdfs,
17093 if intrabc_dv.is_some() {
17094 inter_txbset_for(8, reduced_tx_set)
17095 } else if reduced_tx_set {
17096 TxbSet::Luma8
17097 } else {
17098 TxbSet::Luma8Set1
17099 },
17100 scans.0,
17101 0,
17102 around[0],
17103 mode,
17104 mode,
17105 angle_delta_y,
17106 reach,
17107 y,
17108 px,
17109 py,
17110 8,
17111 TX8,
17112 base_q_idx,
17113 None,
17114 filter_intra,
17115 None,
17116 smooth_neighbor, fctx,
17117 )?;
17118 // `av1_get_tx_type` branches `PLANE_TYPE_UV` on `is_inter_block`, so
17119 // an intrabc block's chroma tx_type is the colocated LUMA transform's
17120 // coded type (lane-kf900 r6's own fix, `decode_block`'s line).
17121 if intrabc_dv.is_some() {
17122 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
17123 }
17124 let ac = alpha.map(|_| cfl_src(px, py, 8));
17125 if let Some((_, ub, _)) = &intrabc_bufs {
17126 set_palette_pred(ub.clone(), fctx);
17127 } else if let Some((ub, _)) = &palette_uv_bufs {
17128 set_palette_pred(ub.clone(), fctx);
17129 }
17130 u_grid = read_plane(
17131 dec,
17132 cdfs,
17133 TxbSet::Chroma4,
17134 scans.1,
17135 1,
17136 around[1],
17137 mode,
17138 uv_predict_mode,
17139 angle_delta_uv,
17140 reach,
17141 u,
17142 cpx,
17143 cpy,
17144 4,
17145 TX4,
17146 base_q_idx,
17147 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
17148 None,
17149 None,
17150 smooth_neighbor_uv, fctx,
17151 )?;
17152 if let Some((_, _, vb)) = &intrabc_bufs {
17153 set_palette_pred(vb.clone(), fctx);
17154 } else if let Some((_, vb)) = &palette_uv_bufs {
17155 set_palette_pred(vb.clone(), fctx);
17156 }
17157 v_grid = read_plane(
17158 dec,
17159 cdfs,
17160 TxbSet::Chroma4,
17161 scans.1,
17162 2,
17163 around[2],
17164 mode,
17165 uv_predict_mode,
17166 angle_delta_uv,
17167 reach,
17168 v,
17169 cpx,
17170 cpy,
17171 4,
17172 TX4,
17173 base_q_idx,
17174 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
17175 None,
17176 None,
17177 smooth_neighbor_uv, fctx,
17178 )?;
17179 // Disarm: `INTRABC_CHROMA_TX` is `Some` across exactly this block's
17180 // two chroma reads (`decode_block`'s own tail does the same) -- left
17181 // set, every later chroma block would inherit this luma tx_type,
17182 // which picks the scan and the inverse transform.
17183 fctx.intrabc_chroma_tx.with(|c| c.set(None));
17184 } else {
17185 // `tx_depth` resolved this leaf's luma to `TX4`: a 2x2 raster-order
17186 // grid of 4x4 transform units, each predicted from the leaf's own
17187 // 8x8 `mode` and reading its own fresh context off the earlier
17188 // units in this same leaf (the same per-TU pattern `decode_block`'s
17189 // multi-TU branch runs at bigger blocks).
17190 for tu_row in 0..2 {
17191 for tu_col in 0..2 {
17192 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
17193 let tu_px = px + tu_col * 4;
17194 let tu_py = py + tu_row * 4;
17195 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
17196 if crate::encode::Reach::in_vert_ab() {
17197 hit!(VERT_AB_TX4_HITS);
17198 }
17199 let tu_reach = tu_reach(
17200 8,
17201 8,
17202 tu_col * 4,
17203 tu_row * 4,
17204 4,
17205 reach,
17206 px,
17207 py,
17208 y.width,
17209 y.height, fctx,
17210 );
17211 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
17212 // Each 4x4 unit predicts from its own window of the block's
17213 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
17214 // 16x16 and up) -- the whole-block buffer would be taken by
17215 // the FIRST unit and indexed at the wrong stride.
17216 if let Some(buf) = &palette_y_buf {
17217 hit!(PALETTE_SPLIT_TX_HITS);
17218 let mut window = vec![0u16; 16];
17219 for row in 0..4 {
17220 let src = (tu_row * 4 + row) * 8 + tu_col * 4;
17221 window[row * 4..][..4].copy_from_slice(&buf[src..][..4]);
17222 }
17223 set_palette_pred(window, fctx);
17224 }
17225 let tu_grid = read_plane(
17226 dec,
17227 cdfs,
17228 if intrabc_dv.is_some() {
17229 inter_txbset_for(4, reduced_tx_set)
17230 } else if reduced_tx_set {
17231 TxbSet::Luma4
17232 } else {
17233 TxbSet::Luma4Set1
17234 },
17235 scans.1,
17236 0,
17237 tu_around,
17238 mode,
17239 mode,
17240 angle_delta_y,
17241 tu_reach,
17242 y,
17243 tu_px,
17244 tu_py,
17245 4,
17246 4,
17247 base_q_idx,
17248 None,
17249 filter_intra,
17250 Some(tu_skip_ctx),
17251 smooth_neighbor, fctx,
17252 )?;
17253 if crate::envflags::env_flag!("EC_AV1_TRACE") {
17254 eprintln!(
17255 "TRACE tu_bitpos mi=({},{}) tell={}",
17256 tu_mi.0,
17257 tu_mi.1,
17258 dec.debug_bitpos()
17259 );
17260 }
17261 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
17262 }
17263 }
17264 let ac = alpha.map(|_| cfl_src(px, py, 8));
17265 let chroma_around = neighbours.around_mi(leaf_mi, 8);
17266 if let Some((ub, _)) = &palette_uv_bufs {
17267 set_palette_pred(ub.clone(), fctx);
17268 }
17269 u_grid = read_plane(
17270 dec,
17271 cdfs,
17272 TxbSet::Chroma4,
17273 scans.1,
17274 1,
17275 chroma_around[1],
17276 mode,
17277 uv_predict_mode,
17278 angle_delta_uv,
17279 reach,
17280 u,
17281 cpx,
17282 cpy,
17283 4,
17284 TX4,
17285 base_q_idx,
17286 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
17287 None,
17288 None,
17289 smooth_neighbor_uv, fctx,
17290 )?;
17291 if let Some((_, vb)) = &palette_uv_bufs {
17292 set_palette_pred(vb.clone(), fctx);
17293 }
17294 v_grid = read_plane(
17295 dec,
17296 cdfs,
17297 TxbSet::Chroma4,
17298 scans.1,
17299 2,
17300 chroma_around[2],
17301 mode,
17302 uv_predict_mode,
17303 angle_delta_uv,
17304 reach,
17305 v,
17306 cpx,
17307 cpy,
17308 4,
17309 TX4,
17310 base_q_idx,
17311 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
17312 None,
17313 None,
17314 smooth_neighbor_uv, fctx,
17315 )?;
17316 // `record_split_luma` expects a `record`-style `(r, c)` position in
17317 // `SUB`-grid units and rescales it by `SUB / MI`; `leaf_mi` is
17318 // already in mi units, so calling it here double-scaled the
17319 // position. Plane 0 is already correct per-TU from the
17320 // `record_mi_luma` calls above; this inlines `record_mi`'s tail
17321 // (spec `get_txb_ctx_general`'s neighbour-magnitude bookkeeping) for
17322 // the two chroma planes only, at `leaf_mi` directly, side_mi=2 (this
17323 // leaf's own 8x8 side over `MI`).
17324 let side_mi = 2;
17325 for cell in 0..side_mi {
17326 neighbours.left_side_mi[leaf_mi.0 + cell] = 8;
17327 neighbours.above_side_mi[leaf_mi.1 + cell] = 8;
17328 }
17329 let round_up_even = |n: usize| n.div_ceil(2) * 2;
17330 let bound_h = round_up_even(neighbours.mi_rows);
17331 let bound_w = round_up_even(neighbours.mi_cols);
17332 let u_state = neighbour_state(&u_grid);
17333 let v_state = neighbour_state(&v_grid);
17334 for cell in 0..side_mi {
17335 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
17336 neighbours.left[leaf_mi.0 + cell][1] = u_state;
17337 neighbours.left[leaf_mi.0 + cell][2] = v_state;
17338 }
17339 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
17340 neighbours.above[leaf_mi.1 + cell][1] = u_state;
17341 neighbours.above[leaf_mi.1 + cell][2] = v_state;
17342 }
17343 }
17344 // This leaf's own palette state into the mi-granular above/left bands
17345 // (sizes 0 when it used none, which is what clears a previous block's
17346 // palette out of the next block's ctx and colour cache).
17347 {
17348 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
17349 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
17350 }
17351 neighbours.fill_skip_grid(leaf_mi, 2, skip);
17352 neighbours.fill_lf_grid(leaf_mi, 2, 4, 0, fctx);
17353 // lane-t900 r32: `set_txfm_ctxs` for an 8x8 leaf -- see `decode_block`'s
17354 // own copy; only an intrabc var-tx read consumes these bands on the intra
17355 // path, so the write is armed by `allow_intrabc`.
17356 if allow_intrabc {
17357 set_txfm_ctxs(neighbours, leaf_mi, 4, 2, 2, skip && intrabc_dv.is_some());
17358 }
17359 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
17360 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, neighbours, fctx);
17361 return Ok(mode);
17362 }
17363 neighbours.record_mi(leaf_mi, 8, &[&luma_grid[..], &u_grid[..], &v_grid[..]]);
17364 // This leaf's own palette state into the mi-granular above/left bands
17365 // (sizes 0 when it used none, which is what clears a previous block's
17366 // palette out of the next block's ctx and colour cache).
17367 {
17368 neighbours.record_palette_y_rect(leaf_mi, 8, 8, pal_y_size, pal_y_colors);
17369 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, pal_uv_size, pal_uv_colors);
17370 }
17371 hit!(INTER8_SKIP_BAND_HITS);
17372 neighbours.fill_skip_grid(leaf_mi, 2, skip);
17373 // lane-kf900 r1: the leaf's own RESOLVED transform size, never the literal
17374 // block side. libaom calls `set_txfm_ctxs(mbmi->tx_size, ..., skip_txfm &&
17375 // is_inter_block(mbmi), xd)` (decodemv.c) -- for an INTRA block that skip
17376 // term is always 0, so a skipped 8x8 leaf whose `tx_depth` resolved to
17377 // TX_4X4 still publishes 4 to the next block's `get_tx_size_context`
17378 // (pred_common.h:342). Writing 8 here made the 8x16 strip below the leaf
17379 // read `tx_size_cat1` row 2 where libaom reads row 1 -- same alphabet,
17380 // wrong CDF row, so the msac range diverged mid-frame with no refusal
17381 // (class `wrong-alphabet-same-value`; the ReelB key frame at
17382 // -ss 900, first bad luma sample row 186 col 1803).
17383 neighbours.fill_lf_grid(leaf_mi, 2, resolved as u8, 0, fctx);
17384 // lane-t900 r32 / lane-av1txbands: `set_txfm_ctxs` for an 8x8 leaf -- see
17385 // `decode_block`'s own copy for why this stays beside
17386 // [`Neighbours::fill_lf_grid_rect`]'s publish (the skipped-intrabc
17387 // BLOCK-size term).
17388 if allow_intrabc {
17389 set_txfm_ctxs(neighbours, leaf_mi, resolved, 2, 2, skip && intrabc_dv.is_some());
17390 }
17391 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, mode);
17392 // The DV predictor of a LATER intrabc block is the ordinary `INTRA_FRAME`
17393 // MV stack over this grid (`av1_find_mv_refs`), so an 8x8 leaf has to
17394 // publish its own cells exactly like `decode_block` does.
17395 record_intrabc_mi(leaf_mi.0, leaf_mi.1, 2, intrabc_dv, neighbours, fctx);
17396 Ok(mode)
17397}
17398
17399/// `read_intra_frame_mode_info`'s mode-info read for one `BLOCK_4X4` leaf
17400/// below an 8x8 partition (spec `decode_partition`'s `bSize < BLOCK_8X8`
17401/// bottom, where no partition symbol is read at all -- `decode_block` runs
17402/// directly). No palette (`av1_allow_palette` needs both dims >= 8, spec
17403/// blockd.h) and no `read_tx_size` (a sub-8x8 block's transform is always
17404/// its own bsize, spec 5.11.16). `has_chroma` follows `is_chroma_reference`
17405/// (spec/libaom `av1_common_int.h`): for 4:2:0, only the bottom-right leaf
17406/// of the 2x2 4x4 group carries chroma syntax at all.
17407#[allow(clippy::too_many_arguments)]
17408fn read_intra_mode_sub8(
17409 dec: &mut SymbolDecoder,
17410 cdfs: &mut Cdfs,
17411 above_mode: usize,
17412 left_mode: usize,
17413 has_chroma: bool,
17414 enable_filter_intra: bool,
17415 // [`filter_intra_size_class_rect`] for the LEAF's own shape: 0 for a
17416 // `BLOCK_4X4` split leaf, 8/9 for a 4x8/8x4 rect leaf. Reading the flag
17417 // from the wrong row is the same VALUE with a different interval, so it
17418 // desyncs a block or two later, not here (class `wrong-alphabet-same-value`).
17419 fi_class: usize,
17420 skip_ctx: usize,
17421 allow_intrabc: bool,
17422 mi_r: usize,
17423 mi_c: usize,
17424 // The leaf's own mi footprint for `set_segment_id`: 1x1 for a `BLOCK_4X4`
17425 // split leaf, 2x1/1x2 for an 8x4/4x8 one. Stamping 1x1 for a rect leaf
17426 // left the second mi column at segment 0, which reads back as a
17427 // neighbour's `cdf_index`/prediction two blocks later.
17428 seg_w_mi: usize,
17429 seg_h_mi: usize, fctx: &crate::decode::FrameCtx,
17430) -> Result<(bool, usize, i32, Option<(usize, i32, Option<(i32, i32)>)>, Option<usize>, Option<(i32, i32)>)> {
17431 // lane-av1mono: a monochrome leaf codes no chroma mode (libaom
17432 // `decodemv.c:933`), so fold `NumPlanes == 1` into `has_chroma`.
17433 let has_chroma = has_chroma && !mono(fctx);
17434 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
17435 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
17436 if ec_istep {
17437 eprintln!("EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}", dec.debug_state().0);
17438 }
17439 // Same `EC_ISTEP` ladder the square/rect readers print, so a cross-decoder
17440 // range diff lands on the ELEMENT inside a 4x4 leaf, not just the block.
17441 macro_rules! istep {
17442 ($name:literal, $val:expr) => {
17443 if ec_istep {
17444 eprintln!("EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={}", $name, $val, dec.debug_state().0);
17445 }
17446 };
17447 }
17448 // lane-seg2: same `intra_segment_id` placement as the square and rect
17449 // readers (spec 5.11.6) -- a `BLOCK_4X4` leaf codes its own `segment_id`
17450 // like any other block, over its own 1x1 mi footprint. Dropping it here
17451 // both ate a symbol (the tile desynced at the frame's first sub-8x8
17452 // split) and left `cur_segment_id` on the previous block, so the leaf
17453 // dequantized with a neighbour's `SEG_LVL_ALT_Q`.
17454 if seg_id_pre_skip(fctx) {
17455 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
17456 }
17457 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
17458 if trace {
17459 eprintln!("TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}", skip as i32, dec.debug_state().0);
17460 }
17461 istep!("skip", skip as i32);
17462 if !seg_id_pre_skip(fctx) {
17463 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
17464 }
17465 maybe_read_cdef_idx(dec, mi_r, mi_c, (2, 2), skip, fctx);
17466 istep!("cdef", 0);
17467 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
17468 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
17469 istep!("dq", 0);
17470 if allow_intrabc {
17471 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
17472 if ec_istep {
17473 eprintln!("EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}", u8::from(use_intrabc), dec.debug_state().0);
17474 }
17475 if use_intrabc {
17476 // lane-av1txr: `read_intrabc_info` (spec 5.11.13) reads the block
17477 // vector right after the flag and RETURNS -- no y/uv mode, angle
17478 // delta, palette, CfL or filter-intra syntax follows, and the
17479 // block is reconstructed by the INTER path (libaom's
17480 // `is_inter_block` counts an intrabc block), so the caller takes
17481 // the frame-copy prediction + inter residual.
17482 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (seg_w_mi, seg_h_mi), fctx);
17483 // lane-av1txr: the DV travels back in the RETURN value -- it is
17484 // NOT published through `FrameCtx::intrabc_dv`. That slot is the
17485 // SQUARE paths' handoff (`decode_block`/`decode_leaf8` arm it,
17486 // then `take()` it in the same call), so a sub-8x8 leaf that
17487 // armed it left the vector standing for the NEXT >=8x8 block:
17488 // `warped.obu`'s (38,60) 8x8 intra block took it as its own
17489 // intrabc and read an inter var-tx `txfm_split` where libaom read
17490 // an intra `tx_depth` (class `stale-slot-handoff`).
17491 hit!(INTRABC_HITS);
17492 return Ok((skip, DC_PRED, 0, None, None, Some(dv)));
17493 }
17494 }
17495 let above_ctx = INTRA_MODE_CTX[above_mode];
17496 let left_ctx = INTRA_MODE_CTX[left_mode];
17497 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
17498 istep!("mode", mode);
17499 if trace {
17500 eprintln!("TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}", dec.debug_state().0);
17501 }
17502 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
17503 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
17504 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
17505 // symbol. Reading one consumed a symbol the encoder never wrote and
17506 // desynced the tile at the very next element.
17507 let angle_delta_y = 0;
17508 let chroma = if has_chroma {
17509 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
17510 if trace {
17511 eprintln!("TRACE sub8 uv_mode value={uv_mode} rng={}", dec.debug_state().0);
17512 }
17513 if (9..=12).contains(&uv_mode) {
17514 hit!(SMOOTH_UV_HITS);
17515 }
17516 let alpha = if uv_mode == UV_CFL_PRED {
17517 Some(read_cfl_alphas(dec, cdfs))
17518 } else {
17519 None
17520 };
17521 if (V_PRED..=D67_PRED).contains(&uv_mode) {
17522 hit!(DIRECTIONAL_UV_HITS);
17523 }
17524 // See the luma comment above: no angle delta below 8x8.
17525 let angle_delta_uv = 0;
17526 Some((uv_mode, angle_delta_uv, alpha))
17527 } else {
17528 None
17529 };
17530 let mut filter_intra = None;
17531 if mode == DC_PRED && enable_filter_intra {
17532 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
17533 if trace {
17534 eprintln!("TRACE sub8 use_filter_intra value={}", use_filter_intra as i32);
17535 }
17536 if use_filter_intra {
17537 hit!(FILTER_INTRA_HITS);
17538 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
17539 filter_intra = Some(fi_mode);
17540 }
17541 }
17542 Ok((skip, mode, angle_delta_y, chroma, filter_intra, None))
17543}
17544
17545/// Decodes a `PARTITION_SPLIT` of one 8x8 block into four `BLOCK_4X4` leaves
17546/// (spec `decode_partition`'s recursion bottom), sharing [`decode_leaf8`]'s
17547/// own signature so its caller's `prev_leaf`/`above_mode`/`left_mode`
17548/// bookkeeping needs no change. Each leaf reads its own luma mode info,
17549/// neighboured off the *previously decoded leaf in this same group* on
17550/// whichever axis is adjacent (mirroring [`decode_leaf8`]'s own `prev_leaf`
17551/// pattern, one level deeper); chroma is read and reconstructed exactly
17552/// once, on the last (bottom-right) leaf, at the whole 8x8 group's own 4x4
17553/// chroma unit -- [`read_intra_mode_sub8`]'s doc has the `is_chroma_reference`
17554/// derivation.
17555#[allow(clippy::too_many_arguments)]
17556fn decode_leaf_split4(
17557 dec: &mut SymbolDecoder,
17558 cdfs: &mut Cdfs,
17559 neighbours: &mut Neighbours,
17560 outer_at: (usize, usize),
17561 leaf_mi: (usize, usize),
17562 scan4: &[u16],
17563 prev_leaf: Option<((usize, usize), usize)>,
17564 y: &mut PlaneBuf<'static>,
17565 u: &mut PlaneBuf<'static>,
17566 v: &mut PlaneBuf<'static>,
17567 base_q_idx: u8,
17568 enable_filter_intra: bool,
17569 allow_intrabc: bool,
17570 reduced_tx_set: bool,
17571 // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
17572 // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
17573 // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1))., fctx: &crate::decode::FrameCtx
17574 fctx: &crate::decode::FrameCtx,
17575) -> Result<(usize, usize)> {
17576 hit!(SUB8_SPLIT_HITS);
17577 let (r, c) = outer_at;
17578 let mut above_mode = neighbours.above_mode[c];
17579 let mut left_mode = neighbours.left_mode[r];
17580 if let Some(((pr, pc), pmode)) = prev_leaf {
17581 if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 {
17582 above_mode = pmode;
17583 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 {
17584 left_mode = pmode;
17585 }
17586 }
17587 // See `decode_leaf8`'s own `smooth_neighbor_uv`: the chroma edge-filter
17588 // type is the chroma neighbours' `uv_mode`, mi-exact where recorded.
17589 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
17590 let mut leaf_modes = [0usize; 4];
17591 let mut leaf_skips = [false; 4];
17592 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
17593 // lane-av1txr: the chroma-reference (i==3) leaf's block vector when that
17594 // leaf is an intrabc block -- its prediction/reconstruction below is a
17595 // frame copy at this DV, not an intra one.
17596 let mut last_intrabc: Option<(i32, i32)> = None;
17597 for i in 0..4usize {
17598 let (dr, dc) = (i / 2, i % 2);
17599 let lmi = (leaf_mi.0 + dr, leaf_mi.1 + dc);
17600 // Neighbour modes at real mi granularity: inside the group the
17601 // sibling leaf, outside it the split-leaf map when the adjacent mi
17602 // was itself a 4x4 leaf, else the coarse 16x16 slot (see
17603 // `sub8_mode_col`'s doc).
17604 let leaf_above = if dr == 0 {
17605 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
17606 } else {
17607 leaf_modes[i - 2]
17608 };
17609 let leaf_left = if dc == 0 {
17610 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
17611 } else {
17612 leaf_modes[i - 1]
17613 };
17614 let has_chroma = i == 3;
17615 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
17616 let (skip, mode, angle_delta_y, chroma, filter_intra, intrabc) = read_intra_mode_sub8(
17617 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
17618 filter_intra_size_class(4).expect("BLOCK_4X4 has its own filter_intra row"),
17619 skip_ctx, allow_intrabc, lmi.0, lmi.1, 1, 1, fctx,
17620 )?;
17621 leaf_modes[i] = mode;
17622 leaf_skips[i] = skip;
17623 neighbours.record_mode_mi(lmi.0, lmi.1, 1, 1, mode);
17624 // lane-av1txr: libaom `parse_decode_block`'s `set_txfm_ctxs` for this
17625 // `BLOCK_4X4` leaf -- EVERY block publishes its transform size into
17626 // the TXFM context bands, and an intrabc block's later `txfm_split`
17627 // context is read off them (`txfm_partition_context`). A 4x4 never
17628 // signals a tx size, so it is always TX_4X4 (`set_txfm_ctxs`'s
17629 // `skip && is_inter` branch writes the block's own 4 pixels -- the
17630 // same value).
17631 set_txfm_ctxs(neighbours, lmi, 4, 1, 1, false);
17632 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
17633 if smooth_neighbor {
17634 hit!(SMOOTH_LUMA_HITS);
17635 }
17636 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
17637 let reach = Reach::of(4, px, py, y.width, y.height, fctx);
17638 if let Some(dv) = intrabc {
17639 // lane-av1txr: an intrabc `BLOCK_4X4` leaf -- prediction is the
17640 // CURRENT frame at the block vector (`predict_inter_block`'s
17641 // intrabc arm, spec 7.11.3.4), residual the INTER coefficient set
17642 // (libaom reads `tx_type` off `inter_ext_tx_cdf` for
17643 // `is_inter_block`, which counts intrabc). Published into
17644 // `intrabc_dv` so the group's chroma arm (below, when the
17645 // chroma-reference leaf is the intrabc one) and
17646 // [`record_intrabc_mi`] see it.
17647 flush_recon(fctx, y, u, v);
17648 let mut yb = vec![0u16; 16];
17649 mc::predict_with_filter(
17650 &y.data, y.width, y.true_width, y.true_height,
17651 mv_to_q4(px, dv.1, true), mv_to_q4(py, dv.0, true),
17652 4, 4, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
17653 );
17654 set_palette_pred(yb.clone(), fctx);
17655 if skip {
17656 push_intra(0, px, py, 4, DC_PRED, 0, reach, &ZERO_RESIDUAL[..16], None, None, smooth_neighbor, fctx);
17657 neighbours.record_mi_luma(lmi, 4, &ZERO_RESIDUAL[..16]);
17658 } else {
17659 let tu_around = neighbours.around_mi(lmi, 4)[0];
17660 let tu_grid = read_plane(
17661 dec,
17662 cdfs,
17663 if reduced_tx_set { TxbSet::Luma4Inter } else { TxbSet::Luma4InterSet1 },
17664 scan4,
17665 0,
17666 tu_around,
17667 DC_PRED,
17668 DC_PRED,
17669 0,
17670 reach,
17671 y,
17672 px,
17673 py,
17674 4,
17675 4,
17676 base_q_idx,
17677 None,
17678 None,
17679 None,
17680 smooth_neighbor, fctx,
17681 )?;
17682 neighbours.record_mi_luma(lmi, 4, &tu_grid);
17683 }
17684 neighbours.fill_skip_grid(lmi, 1, skip);
17685 neighbours.fill_lf_grid(lmi, 1, 4, 0, fctx);
17686 record_intrabc_mi(lmi.0, lmi.1, 1, Some(dv), neighbours, fctx);
17687 if has_chroma {
17688 last_uv = Some((DC_PRED, 0, None));
17689 // An intrabc block is an INTER block for `av1_get_tx_type`, so
17690 // the group's chroma inherits the LUMA's coded transform type
17691 // (`xd->tx_type_map` at the co-located luma position) -- the
17692 // luma `read_plane` above just set [`LUMA_TX_TYPE`]. Armed for
17693 // exactly this group's two chroma reads.
17694 fctx.intrabc_chroma_tx.with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
17695 // lane-av1txbands: the group's chroma is the CHROMA-REFERENCE
17696 // leaf's own block -- libaom codes one chroma unit under the
17697 // last sub-block only (`is_chroma_reference`), so its prediction
17698 // is that leaf's `uv_mode` (CfL alpha and all) unless THAT leaf
17699 // is the intrabc one. Arming this from a non-chroma-reference
17700 // leaf's DV made `warped.obu`'s 8x8 group at mi(40,62) copy
17701 // frame bytes at mi(41,62)'s vector where aomdec predicts
17702 // `uv_mode=UV_CFL_PRED`: luma stayed byte-exact and only chroma
17703 // moved (class chroma-keyed-at-a-non-chroma-leaf). Mirrors
17704 // [`decode_leaf_rect8`]'s own placement.
17705 last_intrabc = Some(dv);
17706 }
17707 continue;
17708 }
17709 if skip {
17710 push_intra(0, px, py, 4, mode, angle_delta_y, reach, &ZERO_RESIDUAL[..16], None, filter_intra, smooth_neighbor, fctx);
17711 neighbours.record_mi_luma(lmi, 4, &ZERO_RESIDUAL[..16]);
17712 } else {
17713 let tu_around = neighbours.around_mi(lmi, 4)[0];
17714 // A `BLOCK_4X4` leaf's luma TU *is* the whole block, so libaom's
17715 // `get_txb_ctx` takes its `plane_bsize == txsize_to_bsize[tx_size]`
17716 // branch: `txb_skip_ctx = 0`, never the neighbour-magnitude table
17717 // (`txb_common.h:400`). Reading the table here decoded `all_zero`
17718 // off the wrong CDF on the very first leaf and desynced the tile.
17719 let tu_grid = read_plane(
17720 dec,
17721 cdfs,
17722 if reduced_tx_set { TxbSet::Luma4 } else { TxbSet::Luma4Set1 },
17723 scan4,
17724 0,
17725 tu_around,
17726 mode,
17727 mode,
17728 angle_delta_y,
17729 reach,
17730 y,
17731 px,
17732 py,
17733 4,
17734 4,
17735 base_q_idx,
17736 None,
17737 filter_intra,
17738 None,
17739 smooth_neighbor, fctx,
17740 )?;
17741 neighbours.record_mi_luma(lmi, 4, &tu_grid);
17742 }
17743 neighbours.fill_skip_grid(lmi, 1, skip);
17744 neighbours.fill_lf_grid(lmi, 1, 4, 0, fctx);
17745 if has_chroma {
17746 last_uv = chroma;
17747 }
17748 }
17749 // lane-av1mono: as [`decode_leaf_rect8`] -- a monochrome frame has no
17750 // chroma to reconstruct and no uv_mode was read.
17751 let (u_grid, v_grid): (Grid, Grid) = if mono(fctx) {
17752 (Grid::Zero(16), Grid::Zero(16))
17753 } else {
17754 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
17755 let (cpx, cpy) = (gpx / 2, gpy / 2);
17756 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
17757 let (uv_mode, angle_delta_uv, alpha) =
17758 last_uv.expect("i==3 always sets has_chroma, so chroma is always Some");
17759 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
17760 neighbours.above_uv_mode[c] = uv_predict_mode;
17761 neighbours.left_uv_mode[r] = uv_predict_mode;
17762 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
17763 let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[3] {
17764 // A skipped chroma block still gets its CfL contribution: libaom's
17765 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
17766 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
17767 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
17768 // added -- `skip_txfm` only drops the residual, never the alpha.
17769 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
17770 // merge keeps one fix and feeds both lanes' counters so neither of
17771 // their gates goes vacuous.
17772 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
17773 if alpha.is_some() {
17774 hit!(CHROMA_SKIP_CFL_HITS);
17775 hit!(SKIP_CFL_HITS);
17776 }
17777 push_intra(1, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx);
17778 push_intra(2, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx);
17779 // lane-av1txbands: a SKIPPED chroma-reference leaf reads no chroma
17780 // coefficient, so it never consults the inherited luma transform type
17781 // -- but an intrabc chroma-reference leaf did arm
17782 // [`INTRABC_CHROMA_TX`] above (`has_chroma`), and the two coefficient
17783 // branches below are the only ones that disarm it. Left armed, the slot
17784 // picks the NEXT block's chroma scan and inverse transform (class
17785 // arm-without-clear-on-a-skip-route). Counted so a gate can tell a
17786 // stream that reaches this route from one that never does.
17787 if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() {
17788 hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS);
17789 fctx.intrabc_chroma_tx.with(|c| c.set(None));
17790 }
17791 (Grid::Zero(16), Grid::Zero(16))
17792 } else if let Some(dv) = last_intrabc {
17793 // lane-av1txr: the chroma-reference leaf was an intrabc block, so the
17794 // group's one chroma unit is a frame copy at that DV too (its residual
17795 // still reads the ordinary `Chroma4` coefficient tables -- libaom
17796 // codes a chroma `tx_type` nowhere).
17797 let mut ub = vec![0u16; 16];
17798 mc::predict_with_filter(
17799 &u.data, u.width, u.true_width, u.true_height,
17800 mv_to_q4(cpx, dv.1, false), mv_to_q4(cpy, dv.0, false),
17801 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
17802 );
17803 let mut vb = vec![0u16; 16];
17804 mc::predict_with_filter(
17805 &v.data, v.width, v.true_width, v.true_height,
17806 mv_to_q4(cpx, dv.1, false), mv_to_q4(cpy, dv.0, false),
17807 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
17808 );
17809 let chroma_around = neighbours.around_mi(leaf_mi, 8);
17810 set_palette_pred(ub, fctx);
17811 let ug = read_plane(
17812 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], DC_PRED, DC_PRED,
17813 0, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
17814 None, None, None, smooth_neighbor_uv, fctx,
17815 )?;
17816 set_palette_pred(vb, fctx);
17817 let vg = read_plane(
17818 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], DC_PRED, DC_PRED,
17819 0, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
17820 None, None, None, smooth_neighbor_uv, fctx,
17821 )?;
17822 fctx.intrabc_chroma_tx.with(|c| c.set(None));
17823 (ug, vg)
17824 } else {
17825 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
17826 let chroma_around = neighbours.around_mi(leaf_mi, 8);
17827 let ug = read_plane(
17828 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
17829 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
17830 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
17831 )?;
17832 let vg = read_plane(
17833 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
17834 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
17835 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
17836 )?;
17837 (ug, vg)
17838 };
17839 (u_grid, v_grid)
17840 };
17841 // Chroma neighbour bookkeeping for the whole 8x8 group -- mirrors
17842 // [`decode_leaf8`]'s own tx4-chroma section (`record_split_luma`'s
17843 // rescaling is wrong for an already-mi-unit position, so this inlines
17844 // its tail directly at `leaf_mi`, side_mi=2), EXCEPT for the partition
17845 // context value itself. Unlike `decode_leaf8`'s TX4 branch (still one
17846 // `BLOCK_8X8`, `PARTITION_NONE`, transform depth only), this group is
17847 // genuinely four `BLOCK_4X4` blocks (`PARTITION_SPLIT` at the 8x8
17848 // level, libaom `decode_partition`'s `bsize2`/`subsize` recursion
17849 // bottom). libaom's `update_ext_partition_context` writes
17850 // `partition_context_lookup[subsize]` at the 8x8 slot -- `{30,30}` for
17851 // `BLOCK_8X8` (bit0=0, what `decode_leaf8` already reproduces via
17852 // side_mi=8) but `{31,31}` for `BLOCK_4X4` (bit0=1) here, and
17853 // `partition_ctx_mi`'s `left_side_mi[mi_r]*2 <= side` needs
17854 // `left_side_mi <= 4` to read that bit as 1. Leaving this at 8 (this
17855 // round's bug) makes the very next sibling 8x8's `partition_w8` read
17856 // with the wrong context and desync immediately.
17857 let side_mi = 2;
17858 for cell in 0..side_mi {
17859 neighbours.left_side_mi[leaf_mi.0 + cell] = 4;
17860 neighbours.above_side_mi[leaf_mi.1 + cell] = 4;
17861 }
17862 let round_up_even = |n: usize| n.div_ceil(2) * 2;
17863 let bound_h = round_up_even(neighbours.mi_rows);
17864 let bound_w = round_up_even(neighbours.mi_cols);
17865 let u_state = neighbour_state(&u_grid);
17866 let v_state = neighbour_state(&v_grid);
17867 for cell in 0..side_mi {
17868 if cell < side_mi.min(bound_h.saturating_sub(leaf_mi.0)) {
17869 neighbours.left[leaf_mi.0 + cell][1] = u_state;
17870 neighbours.left[leaf_mi.0 + cell][2] = v_state;
17871 }
17872 if cell < side_mi.min(bound_w.saturating_sub(leaf_mi.1)) {
17873 neighbours.above[leaf_mi.1 + cell][1] = u_state;
17874 neighbours.above[leaf_mi.1 + cell][2] = v_state;
17875 }
17876 }
17877 // lane-dkey: a sub-8x8 leaf can never use palette (`av1_allow_palette`
17878 // needs BLOCK_8X8 and up), and libaom's mi grid says so -- its
17879 // `palette_size` is 0 in every one of these mi cells, so the NEXT block's
17880 // `av1_get_palette_mode_ctx` and colour cache read 0 here. This decoder
17881 // only ever WROTE palette state from the >=8x8 readers, so an 8x8 palette
17882 // block above a 4x4 group left its size/colours standing in the mi-granular
17883 // bands: the block below the group read `palette_y_mode` off CDF row 1
17884 // where libaom reads row 0 (class [[cdf-row-held-constant]]), decoded a
17885 // palette libaom never coded, and then skipped the `use_filter_intra`
17886 // symbol that a palette block has none of -- one symbol short, tile
17887 // desynced. Publishing the group's own zeros is the clear.
17888 neighbours.record_palette_y_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
17889 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
17890 Ok((leaf_modes[2], leaf_modes[1]))
17891}
17892
17893/// Decodes a `PARTITION_VERT`/`PARTITION_HORZ` of one 8x8 block into two
17894/// `BLOCK_4X8`/`BLOCK_8X4` leaves (lane-tx4x8), the last partition shape
17895/// below 8x8 this decoder refused. Mirrors [`decode_leaf_split4`] element for
17896/// element -- same mode reads ([`read_intra_mode_sub8`]: no angle delta, no
17897/// tx-depth symbol below 8x8), same "chroma once, on the last sub-block, at
17898/// the whole 8x8 group's 4x4 unit" rule (`is_chroma_reference` is false for
17899/// every sub-block one mi wide or high but the last) -- differing only where
17900/// the shape does:
17901///
17902/// * the transform is a true `TX_4X8`/`TX_8X4`
17903/// ([`dequant_and_inverse_typed_wh`], whose `abs(rect_type) == 1` scale and
17904/// `av1_inv_txfm_shift_ls` row already cover this size pair);
17905/// * the CDF set is [`TxbSet::LumaRect4x8`] (`get_txsize_entropy_ctx` squares
17906/// up to `TX_8X8`) with a 32-position `eob_pt` and the `TX_4X4` `tx_type`
17907/// row -- see that variant's doc comment;
17908/// * the scan is [`SCAN_4X8`]/[`SCAN_8X4`], or their `mrow`/`mcol` siblings
17909/// ([`class_scan_table_wh`]) when the coded `tx_type` is `V_DCT`/`H_DCT`;
17910/// * `Reach` comes from libaom's own `has_tr_4x8`/`has_bl_8x4` rows
17911/// ([`Reach::of_rect`]);
17912/// * `update_partition_context` writes `partition_context_lookup[BLOCK_4X8]`
17913/// = `{31, 30}` (width 4 above, height 8 left), not the `{31, 31}` a
17914/// `BLOCK_4X4` split writes.
17915///
17916/// Filter intra on one of these leaves is decoded (lane-fi8 r1): the flag is
17917/// read from `BLOCK_4X8`/`BLOCK_8X4`'s own `cdf::FILTER_INTRA` row (classes
17918/// 8/9, NOT `BLOCK_4X4`'s), the predictor is [`crate::intra::predict_filter_intra`]
17919/// over the leaf's true `bw`x`bh` -- per 4x4 transform unit, with that unit's
17920/// own edge, when `tx_depth` splits it -- and the coded `tx_type` row is
17921/// [`fi_tx_row`]'s `fimode_to_intradir`, not the block's raw `DC_PRED`.
17922#[allow(clippy::too_many_arguments)]
17923fn decode_leaf_rect8(
17924 dec: &mut SymbolDecoder,
17925 cdfs: &mut Cdfs,
17926 neighbours: &mut Neighbours,
17927 outer_at: (usize, usize),
17928 leaf_mi: (usize, usize),
17929 vert: bool,
17930 scan4: &[u16],
17931 y: &mut PlaneBuf<'static>,
17932 u: &mut PlaneBuf<'static>,
17933 v: &mut PlaneBuf<'static>,
17934 base_q_idx: u8,
17935 enable_filter_intra: bool,
17936 allow_intrabc: bool,
17937 tx_select: bool,
17938 reduced_tx_set: bool, fctx: &crate::decode::FrameCtx,
17939) -> Result<(usize, usize)> {
17940 let (r, c) = outer_at;
17941 // lane-modectx r1: availability-correct fallback pair (see
17942 // `modes_above_left`), not the raw coarse bands.
17943 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);
17944 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c);
17945 let (bw, bh) = if vert { (4, 8) } else { (8, 4) };
17946 let (w_mi, h_mi) = (bw / MI, bh / MI);
17947 let scan: &[u16] = if vert { &SCAN_4X8 } else { &SCAN_8X4 };
17948 let mut leaf_modes = [0usize; 2];
17949 let mut leaf_skips = [false; 2];
17950 let mut last_uv: Option<(usize, i32, Option<(i32, i32)>)> = None;
17951 // lane-av1txr: as [`decode_leaf_split4`]'s own `last_intrabc`.
17952 let mut last_intrabc: Option<(i32, i32)> = None;
17953 for i in 0..2usize {
17954 let lmi = if vert {
17955 (leaf_mi.0, leaf_mi.1 + i)
17956 } else {
17957 (leaf_mi.0 + i, leaf_mi.1)
17958 };
17959 // Inside the pair the sibling is the neighbour on the split axis;
17960 // outside it the mi-granular map, else the coarse 16x16 slot.
17961 let leaf_above = if !vert && i == 1 {
17962 leaf_modes[0]
17963 } else {
17964 neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode)
17965 };
17966 let leaf_left = if vert && i == 1 {
17967 leaf_modes[0]
17968 } else {
17969 neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode)
17970 };
17971 let has_chroma = i == 1;
17972 let skip_ctx = neighbours.skip_txfm_ctx(lmi.0, lmi.1);
17973 let (skip, mode, angle_delta_y, chroma, filter_intra, intrabc) = read_intra_mode_sub8(
17974 dec, cdfs, leaf_above, leaf_left, has_chroma, enable_filter_intra,
17975 filter_intra_size_class_rect(bw, bh)
17976 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize"),
17977 skip_ctx, allow_intrabc, lmi.0, lmi.1, bw / 4, bh / 4, fctx,
17978 )?;
17979 leaf_modes[i] = mode;
17980 leaf_skips[i] = skip;
17981 neighbours.record_mode_mi(lmi.0, lmi.1, w_mi, h_mi, mode);
17982 let smooth_neighbor = is_smooth_mode(leaf_above) || is_smooth_mode(leaf_left);
17983 if let Some(dv) = intrabc {
17984 // lane-av1txr: an intrabc `BLOCK_4X8`/`BLOCK_8X4` leaf. The
17985 // prediction is a frame copy at the DV and the residual reads the
17986 // INTER `LumaRect8x4` set -- but with `TxMode::Select` the leaf
17987 // reads the INTER var-tx tree, exactly like every other intrabc
17988 // block: libaom's `block_signals_txsize` is `bsize > BLOCK_4X4`
17989 // (`blockd.h:1027`), TRUE at `BLOCK_4X8`/`BLOCK_8X4`, so
17990 // `parse_decode_block` sends an unskipped `inter_block_tx` block
17991 // (intrabc counts, `is_inter_block`) of a signalling bsize into
17992 // `read_tx_size_vartx` over `max_txsize_rect_lookup[BLOCK_4X8] ==
17993 // TX_4X8`; only `BLOCK_4X4` reads no tx symbol at all. Measured on
17994 // `warped.obu` mi (37,62): reading NO symbol here left the
17995 // arithmetic decoder one symbol short and desynced the very next
17996 // block's `skip` (ours 60320 vs aomdec 48630, class
17997 // `symbol-consumption-gap`).
17998 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
17999 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
18000 flush_recon(fctx, y, u, v);
18001 let mut luma_leaves: Vec<(usize, usize, usize, usize)> = Vec::new();
18002 if tx_select && !skip {
18003 // `max_block_wide`/`max_block_high`: the frame's own mi grid,
18004 // so a leaf hanging over the right/bottom edge reads no split
18005 // symbol for the units outside it (as in `decode_block`).
18006 let mi_cols = 2 * y.true_width.div_ceil(8);
18007 let mi_rows = 2 * y.true_height.div_ceil(8);
18008 let max_w_mi = w_mi.min(mi_cols.saturating_sub(lmi.1));
18009 let max_h_mi = h_mi.min(mi_rows.saturating_sub(lmi.0));
18010 read_var_tx_size(
18011 dec,
18012 cdfs,
18013 neighbours,
18014 lmi,
18015 bw.max(bh),
18016 (max_w_mi, max_h_mi),
18017 (bw, bh),
18018 0,
18019 0,
18020 0,
18021 &mut luma_leaves,
18022 );
18023 hit!(RECT_INTRABC_VARTX_HITS);
18024 } else {
18025 luma_leaves.push((0, 0, bw, bh));
18026 // The non-var-tx arm: a SKIPPED intrabc leaf (or a frame
18027 // outside `TxMode::Select`) publishes its own rect transform
18028 // (`set_txfm_ctxs`'s `skip && is_inter` branch writes the
18029 // block's own pixels -- the same size here).
18030 txfm_partition_update_rect(neighbours, lmi, (bw, bh), (bw, bh));
18031 }
18032 // The transform type an intrabc block's CHROMA inherits is the
18033 // `tx_type_map` entry at the chroma unit's co-located luma
18034 // position (`av1_get_tx_type`, `blockd.h:1278`), i.e. the FIRST
18035 // luma unit the tree resolved.
18036 let single = luma_leaves.len() == 1;
18037 let mut chroma_tx = TxType::DctDct;
18038 let mut grid = Grid::Zero(bw * bh);
18039 for (li, &(tu_row, tu_col, tw, th)) in luma_leaves.iter().enumerate() {
18040 let tu_mi = (lmi.0 + tu_row, lmi.1 + tu_col);
18041 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
18042 let tu_reach = if single {
18043 reach
18044 } else {
18045 tu_reach(
18046 bw, bh, tu_px - px, tu_py - py, tw, reach, px, py, y.width, y.height, fctx,
18047 )
18048 };
18049 let mut yb = vec![0u16; tw * th];
18050 mc::predict_with_filter(
18051 &y.data, y.width, y.true_width, y.true_height,
18052 mv_to_q4(tu_px, dv.1, true), mv_to_q4(tu_py, dv.0, true),
18053 tw, th, mc::InterpFilterKind::Bilinear, &mut yb, fctx,
18054 );
18055 set_palette_pred(yb, fctx);
18056 let tu_grid = if skip {
18057 let zeros = Grid::Zero(tw * th);
18058 if (tw, th) == (4, 4) {
18059 push_intra(0, tu_px, tu_py, 4, DC_PRED, 0, tu_reach, &zeros, None, None, smooth_neighbor, fctx);
18060 } else {
18061 push_intra_rect(0, tu_px, tu_py, tw, th, DC_PRED, 0, tu_reach, &zeros, None, None, smooth_neighbor, fctx);
18062 }
18063 zeros
18064 } else {
18065 // A unit smaller than its own block (the var-tx split)
18066 // reads its `txb_skip_ctx` off the neighbours; the
18067 // whole-leaf unit's `plane_bsize == txsize_to_bsize` fixes
18068 // it at 0.
18069 let (set, tu_scan, around, skip_ctx) = if (tw, th) == (4, 4) {
18070 (
18071 inter_txbset_for(4, reduced_tx_set),
18072 scan4,
18073 neighbours.around_mi(tu_mi, 4)[0],
18074 neighbours.luma_skip_ctx(tu_mi, 1),
18075 )
18076 } else {
18077 (
18078 if reduced_tx_set {
18079 TxbSet::LumaRect8x4Inter
18080 } else {
18081 TxbSet::LumaRect8x4InterSet1
18082 },
18083 scan,
18084 neighbours.around_mi_rect(tu_mi, tw, th)[0],
18085 0,
18086 )
18087 };
18088 let mut coding = cdfs.txb(set, DC_PRED);
18089 let (levels, tx_type) = read_coeffs_rect(
18090 dec, &mut coding, tu_scan, tw, th, skip_ctx, dc_sign_ctx(around.2),
18091 TxType::DctDct,
18092 )?;
18093 if li == 0 {
18094 chroma_tx = tx_type;
18095 fctx.luma_tx_type.with(|c| c.set(tx_type));
18096 }
18097 let residual = dequant_and_inverse_typed_wh(
18098 &levels, tw, th, crate::decode::bit_depth(fctx), block_q_idx(fctx),
18099 plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, tx_type,
18100 );
18101 if (tw, th) == (4, 4) {
18102 push_intra(0, tu_px, tu_py, 4, DC_PRED, 0, tu_reach, &residual, None, None, smooth_neighbor, fctx);
18103 } else {
18104 push_intra_rect(0, tu_px, tu_py, tw, th, DC_PRED, 0, tu_reach, &residual, None, None, smooth_neighbor, fctx);
18105 }
18106 levels
18107 };
18108 if single {
18109 grid = tu_grid;
18110 } else {
18111 // Per-unit neighbour state, the same shape the intra rect
18112 // leaf's own split path runs (`decode_leaf8`'s depth-1
18113 // loop): a transform unit inside a block is not a block at
18114 // that position.
18115 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
18116 }
18117 }
18118 if single {
18119 let state = neighbour_state(&grid);
18120 for cell in 0..h_mi {
18121 if lmi.0 + cell < neighbours.mi_rows {
18122 neighbours.left[lmi.0 + cell][0] = state;
18123 }
18124 }
18125 for cell in 0..w_mi {
18126 if lmi.1 + cell < neighbours.mi_cols {
18127 neighbours.above[lmi.1 + cell][0] = state;
18128 }
18129 }
18130 }
18131 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
18132 neighbours.fill_lf_grid_rect(
18133 lmi,
18134 w_mi,
18135 h_mi,
18136 if single { bw as u8 } else { 4 },
18137 if single { bh as u8 } else { 4 },
18138 0,
18139 fctx,
18140 );
18141 // `record_intrabc_mi` publishes a square `n4`x`n4` footprint; a
18142 // 4x8/8x4 leaf needs its true `w_mi`x`h_mi` (lane-av1txr).
18143 record_intrabc_mi_rect(lmi.0, lmi.1, w_mi, h_mi, Some(dv), neighbours, fctx);
18144 if has_chroma {
18145 last_uv = Some((DC_PRED, 0, None));
18146 last_intrabc = Some(dv);
18147 // See [`decode_leaf_split4`]: an intrabc block's chroma
18148 // inherits the luma transform type.
18149 fctx.intrabc_chroma_tx.with(|c| c.set(Some(chroma_tx)));
18150 }
18151 continue;
18152 }
18153 if filter_intra.is_some() {
18154 // lane-fi8 r1: `predict_filter_intra` walks its 4x2 patches over
18155 // a true `bw`x`bh` block, so a 4x8/8x4 leaf predicts through the
18156 // same `reconstruct_rect`/`reconstruct` calls below -- and under
18157 // a split transform, per 4x4 unit with that unit's own edge,
18158 // which is exactly what the depth-1 loop already does.
18159 hit!(FILTER_INTRA_RECT_HITS);
18160 hit!(FILTER_INTRA_RECT_SUB8_HITS);
18161 }
18162 // `TxMode::Select`'s `tx_depth` (spec 5.11.16) exists at a 4x8/8x4
18163 // leaf too, and is read for every intra block, skipped or not. Its
18164 // category is libaom's `bsize_to_tx_size_cat(BLOCK_4X8) == 0` --
18165 // `sub_tx_size_map[TX_4X8] == TX_4X4` is a single step, so it is the
18166 // same 2-symbol `tx_size_cat0` an 8x8 uses, not the 3-symbol
18167 // `tx_size_cat2` the 32x16 strips read -- with the rect context
18168 // (`get_tx_size_context`'s `max_tx_wide`/`max_tx_high` = bw/bh).
18169 // Missing this read consumed one symbol fewer than the encoder wrote
18170 // and desynced the tile at the very first rect leaf (class
18171 // `symbol-consumption-gap`).
18172 let depth = if tx_select {
18173 // lane-av1txbands: the `TXFM_CONTEXT` band read every other rect
18174 // reader already does.
18175 let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
18176 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
18177 } else {
18178 0
18179 };
18180 if depth != 0 {
18181 hit!(TX_DEPTH_HITS);
18182 hit!(RECT8_SPLIT_TX_HITS);
18183 }
18184 if smooth_neighbor {
18185 hit!(SMOOTH_LUMA_HITS);
18186 }
18187 let (px, py) = (lmi.1 * MI, lmi.0 * MI);
18188 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
18189 // `sub_tx_size_map[TX_4X8] == TX_4X4`: depth 1 splits the leaf into
18190 // two 4x4 transform units along its long axis, each predicted from
18191 // the previous unit's reconstruction and reading its own `txb_skip`
18192 // context -- `decode_leaf8`'s own depth-1 loop, two units instead of
18193 // four. The per-TU path writes its own neighbour state, so the
18194 // block-level write below is skipped for it.
18195 let split = depth != 0 || lossless(fctx);
18196 // lane-av1txr: libaom `parse_decode_block`'s `set_txfm_ctxs` for this
18197 // leaf -- the size the `tx_depth` symbol resolved (depth 1 -> TX_4X4,
18198 // else the leaf's own rect transform), published over the leaf's own
18199 // mi span. An intrabc block's `txfm_partition_context` reads these
18200 // bands, and the key-frame sub-8x8 leaves had no write at all:
18201 // `warped.obu` mi (37,62) read a stale 8 where aomdec read 4 (ctx 18
18202 // vs 19) and the tile desynced (class `context-band-not-published`).
18203 let (ctx_tx_w, ctx_tx_h) = if split { (4, 4) } else { (bw, bh) };
18204 txfm_partition_update_rect(neighbours, lmi, (ctx_tx_w, ctx_tx_h), (bw, bh));
18205 if split {
18206 let mut done = 0usize;
18207 for tu in 0..2usize {
18208 let tu_mi = if vert {
18209 (lmi.0 + tu, lmi.1)
18210 } else {
18211 (lmi.0, lmi.1 + tu)
18212 };
18213 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
18214 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
18215 // Same per-TU rule as every other split-transform site
18216 // (lane-palette2 r12): a transform unit inside a block is not
18217 // a block at that position, so its reach comes from the
18218 // block's own row, offset by the unit's position.
18219 let tu_reach = tu_reach(
18220 bw,
18221 bh,
18222 tu_px - px,
18223 tu_py - py,
18224 4,
18225 reach,
18226 px,
18227 py,
18228 y.width,
18229 y.height, fctx,
18230 );
18231 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
18232 if skip {
18233 // A skipped leaf still predicts per transform unit: the
18234 // second 4x4 takes its above/left edge from the first
18235 // one's reconstruction, which is NOT what a single 4x8
18236 // prediction of the same mode produces.
18237 let zeros = vec![0i32; 16];
18238 push_intra(0,
18239 tu_px, tu_py, 4, mode, angle_delta_y, tu_reach, &zeros, None,
18240 filter_intra, smooth_neighbor, fctx,
18241 );
18242 neighbours.record_mi_luma(tu_mi, 4, &zeros);
18243 continue;
18244 }
18245 let tu_grid = read_plane(
18246 dec,
18247 cdfs,
18248 if reduced_tx_set {
18249 TxbSet::Luma4
18250 } else {
18251 TxbSet::Luma4Set1
18252 },
18253 scan4,
18254 0,
18255 tu_around,
18256 mode,
18257 mode,
18258 angle_delta_y,
18259 tu_reach,
18260 y,
18261 tu_px,
18262 tu_py,
18263 4,
18264 TX4,
18265 base_q_idx,
18266 None,
18267 filter_intra,
18268 Some(tu_skip_ctx),
18269 smooth_neighbor, fctx,
18270 )?;
18271 if tu_grid.iter().any(|&l| l != 0) {
18272 done += 1;
18273 }
18274 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
18275 }
18276 if done > 0 {
18277 if vert {
18278 hit!(TX4X8_CODED_HITS);
18279 } else {
18280 hit!(TX8X4_CODED_HITS);
18281 }
18282 }
18283 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
18284 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, 4, 4, 0, fctx);
18285 if has_chroma {
18286 last_uv = chroma;
18287 }
18288 continue;
18289 }
18290 let grid = if skip {
18291 let zeros = Grid::Zero(bw * bh);
18292 push_intra_rect(0,
18293 px, py, bw, bh, mode, angle_delta_y, reach, &zeros, None, filter_intra,
18294 smooth_neighbor, fctx,
18295 );
18296 zeros
18297 } else {
18298 // `plane_bsize == txsize_to_bsize[tx_size]` here too (the leaf's
18299 // luma TU *is* the leaf), so `get_txb_ctx` fixes `txb_skip_ctx`
18300 // at 0 -- see `decode_leaf_split4`'s own note.
18301 let around = neighbours.around_mi_rect(lmi, bw, bh)[0];
18302 let set = if reduced_tx_set {
18303 TxbSet::LumaRect4x8
18304 } else {
18305 TxbSet::LumaRect4x8Set1
18306 };
18307 let mut coding = cdfs.txb(set, fi_tx_row(mode, filter_intra));
18308 let (levels, tx_type) = read_coeffs_rect(
18309 dec,
18310 &mut coding,
18311 scan,
18312 bw,
18313 bh,
18314 0,
18315 dc_sign_ctx(around.2),
18316 TxType::DctDct,
18317 )?;
18318 if levels.iter().any(|&l| l != 0) {
18319 if vert {
18320 hit!(TX4X8_CODED_HITS);
18321 } else {
18322 hit!(TX8X4_CODED_HITS);
18323 }
18324 }
18325 let residual = dequant_and_inverse_typed_wh(
18326 &levels,
18327 bw,
18328 bh,
18329 crate::decode::bit_depth(fctx),
18330 // lane-d792 sweep: the block's segment `SEG_LVL_ALT_Q`, as at
18331 // every other dequant site (class `parsed-then-discarded`).
18332 block_q_idx(fctx),
18333 plane_q_delta(0, fctx).0,
18334 plane_q_delta(0, fctx).1,
18335 tx_type,
18336 );
18337 push_intra_rect(0,
18338 px, py, bw, bh, mode, angle_delta_y, reach, &residual, None, filter_intra,
18339 smooth_neighbor, fctx,
18340 );
18341 levels
18342 };
18343 // Plane 0's per-TU coefficient context over this leaf's own mi span
18344 // (`record_mi_luma`'s rect twin -- the chroma planes are written once
18345 // for the whole 8x8 group below).
18346 let state = neighbour_state(&grid);
18347 for cell in 0..h_mi {
18348 if lmi.0 + cell < neighbours.mi_rows {
18349 neighbours.left[lmi.0 + cell][0] = state;
18350 }
18351 }
18352 for cell in 0..w_mi {
18353 if lmi.1 + cell < neighbours.mi_cols {
18354 neighbours.above[lmi.1 + cell][0] = state;
18355 }
18356 }
18357 neighbours.fill_skip_grid_rect(lmi, w_mi, h_mi, skip);
18358 let (tx_w, tx_h) = if split { (4, 4) } else { (bw as u8, bh as u8) };
18359 neighbours.fill_lf_grid_rect(lmi, w_mi, h_mi, tx_w, tx_h, 0, fctx);
18360 if has_chroma {
18361 last_uv = chroma;
18362 }
18363 }
18364 // lane-av1mono: a monochrome frame codes no chroma at all -- no
18365 // `uv_mode` was read ([`read_intra_mode_sub8`] folds the plane count in),
18366 // so there is no chroma to reconstruct and no chroma coefficient to read.
18367 let (u_grid, v_grid): (Grid, Grid) = if mono(fctx) {
18368 (Grid::Zero(16), Grid::Zero(16))
18369 } else {
18370 let (gpx, gpy) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
18371 let (cpx, cpy) = (gpx / 2, gpy / 2);
18372 let group_reach = Reach::of(8, gpx, gpy, y.width, y.height, fctx);
18373 let (uv_mode, angle_delta_uv, alpha) =
18374 last_uv.expect("i==1 always sets has_chroma, so chroma is always Some");
18375 let uv_predict_mode = if uv_mode == UV_CFL_PRED { DC_PRED } else { uv_mode };
18376 neighbours.above_uv_mode[c] = uv_predict_mode;
18377 neighbours.left_uv_mode[r] = uv_predict_mode;
18378 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, 2, 2, uv_predict_mode);
18379 let (u_grid, v_grid): (Grid, Grid) = if leaf_skips[1] && last_intrabc.is_none() {
18380 // A skipped chroma block still gets its CfL contribution: libaom's
18381 // `predict_and_reconstruct_intra_block` calls `cfl_predict_block`
18382 // from `av1_predict_intra_block_facade` (av1/common/reconintra.c:1719)
18383 // whenever `mbmi->uv_mode == UV_CFL_PRED`, before any residual is
18384 // added -- `skip_txfm` only drops the residual, never the alpha.
18385 // lane-reelckf and lane-kf1200 fixed THIS SAME arm independently; the
18386 // merge keeps one fix and feeds both lanes' counters so neither of
18387 // their gates goes vacuous.
18388 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
18389 if alpha.is_some() {
18390 hit!(CHROMA_SKIP_CFL_HITS);
18391 hit!(SKIP_CFL_HITS);
18392 }
18393 push_intra(1, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, smooth_neighbor_uv, fctx);
18394 push_intra(2, cpx, cpy, 4, uv_predict_mode, angle_delta_uv, group_reach, &ZERO_RESIDUAL[..16], alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, smooth_neighbor_uv, fctx);
18395 // lane-av1txbands: a SKIPPED chroma-reference leaf reads no chroma
18396 // coefficient, so it never consults the inherited luma transform type
18397 // -- but an intrabc chroma-reference leaf did arm
18398 // [`INTRABC_CHROMA_TX`] above (`has_chroma`), and the two coefficient
18399 // branches below are the only ones that disarm it. Left armed, the slot
18400 // picks the NEXT block's chroma scan and inverse transform (class
18401 // arm-without-clear-on-a-skip-route). Counted so a gate can tell a
18402 // stream that reaches this route from one that never does.
18403 if fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_some() {
18404 hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS);
18405 fctx.intrabc_chroma_tx.with(|c| c.set(None));
18406 }
18407 (Grid::Zero(16), Grid::Zero(16))
18408 } else if let Some(dv) = last_intrabc {
18409 // A 4:2:0 `BLOCK_4X8`/`BLOCK_8X4` leaf maps to a clamped chroma
18410 // `BLOCK_4X4` (`get_plane_block_size`, blockd.h:1184; `set_plane_n4`,
18411 // av1_common_int.h:1344). The chroma reference is still the whole
18412 // 8x8 group's 4x4 plane block at `(cpx, cpy)`, so prediction uses the
18413 // group's destination origin, not the odd-mi leaf's nominal 2x4/4x2
18414 // extent. The old route treated a skipped intrabc leaf as skipped
18415 // intra and predicted this block with DC, first differing at
18416 // mi(46,52), U(104,92), while consuming identical symbols.
18417 let chroma_mv_x = mv_to_q4(cpx, dv.1, false);
18418 let chroma_mv_y = mv_to_q4(cpy, dv.0, false);
18419 // `decode_reconstruct_tx` reads no chroma coefficients for a skipped
18420 // intrabc block, but an unskipped one reads the ordinary Chroma4
18421 // tables; chroma inherits no coded tx_type of its own.
18422 let mut ub = vec![0u16; 16];
18423 mc::predict_with_filter(
18424 &u.data, u.width, u.true_width, u.true_height,
18425 chroma_mv_x, chroma_mv_y, 4, 4, mc::InterpFilterKind::Bilinear, &mut ub, fctx,
18426 );
18427 let mut vb = vec![0u16; 16];
18428 mc::predict_with_filter(
18429 &v.data, v.width, v.true_width, v.true_height,
18430 chroma_mv_x, chroma_mv_y, 4, 4, mc::InterpFilterKind::Bilinear, &mut vb, fctx,
18431 );
18432 if leaf_skips[1] {
18433 // `skip_txfm` still reconstructs an intrabc prediction, but
18434 // libaom's `decode_reconstruct_tx` reads NO chroma coefficients.
18435 // The ordinary skipped-intra arm above is therefore not valid for
18436 // an intrabc leaf: use the copied, clamped 4x4 prediction directly.
18437 push_mc_rect(
18438 1, cpx, cpy, 4, 4, 4, Pred::Inline(&ub, 4),
18439 &ZERO_RESIDUAL[..16], fctx,
18440 );
18441 push_mc_rect(
18442 2, cpx, cpy, 4, 4, 4, Pred::Inline(&vb, 4),
18443 &ZERO_RESIDUAL[..16], fctx,
18444 );
18445 hit!(SKIPPED_INTRABC_CHROMA_ARM_HITS);
18446 fctx.intrabc_chroma_tx.with(|c| c.set(None));
18447 (Grid::Zero(16), Grid::Zero(16))
18448 } else {
18449 let chroma_around = neighbours.around_mi(leaf_mi, 8);
18450 set_palette_pred(ub, fctx);
18451 let ug = read_plane(
18452 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], DC_PRED, DC_PRED,
18453 0, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
18454 None, None, None, smooth_neighbor_uv, fctx,
18455 )?;
18456 set_palette_pred(vb, fctx);
18457 let vg = read_plane(
18458 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], DC_PRED, DC_PRED,
18459 0, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
18460 None, None, None, smooth_neighbor_uv, fctx,
18461 )?;
18462 fctx.intrabc_chroma_tx.with(|c| c.set(None));
18463 (ug, vg)
18464 }
18465 } else {
18466 let ac = alpha.map(|_| cfl_src(gpx, gpy, 8));
18467 let chroma_around = neighbours.around_mi(leaf_mi, 8);
18468 let ug = read_plane(
18469 dec, cdfs, TxbSet::Chroma4, scan4, 1, chroma_around[1], uv_mode, uv_predict_mode,
18470 angle_delta_uv, group_reach, u, cpx, cpy, 4, TX4, base_q_idx,
18471 alpha.zip(ac).map(|((au, _), ac)| (au, ac)), None, None, smooth_neighbor_uv, fctx,
18472 )?;
18473 let vg = read_plane(
18474 dec, cdfs, TxbSet::Chroma4, scan4, 2, chroma_around[2], uv_mode, uv_predict_mode,
18475 angle_delta_uv, group_reach, v, cpx, cpy, 4, TX4, base_q_idx,
18476 alpha.zip(ac).map(|((_, av), ac)| (av, ac)), None, None, smooth_neighbor_uv, fctx,
18477 )?;
18478 (ug, vg)
18479 };
18480 (u_grid, v_grid)
18481 };
18482 // `update_partition_context` at the 8x8 level writes
18483 // `partition_context_lookup[subsize]` over the whole 8x8 span: BLOCK_4X8
18484 // is `{31, 30}` (bit0 set on the above half only), BLOCK_8X4 `{30, 31}`
18485 // -- the mirror of `decode_leaf_split4`'s `{31, 31}`, which
18486 // `partition_ctx_mi` reads back off these side values.
18487 for cell in 0..2 {
18488 neighbours.above_side_mi[leaf_mi.1 + cell] = bw as u8;
18489 neighbours.left_side_mi[leaf_mi.0 + cell] = bh as u8;
18490 }
18491 let round_up_even = |n: usize| n.div_ceil(2) * 2;
18492 let bound_h = round_up_even(neighbours.mi_rows);
18493 let bound_w = round_up_even(neighbours.mi_cols);
18494 let u_state = neighbour_state(&u_grid);
18495 let v_state = neighbour_state(&v_grid);
18496 for cell in 0..2usize {
18497 if cell < 2usize.min(bound_h.saturating_sub(leaf_mi.0)) {
18498 neighbours.left[leaf_mi.0 + cell][1] = u_state;
18499 neighbours.left[leaf_mi.0 + cell][2] = v_state;
18500 }
18501 if cell < 2usize.min(bound_w.saturating_sub(leaf_mi.1)) {
18502 neighbours.above[leaf_mi.1 + cell][1] = u_state;
18503 neighbours.above[leaf_mi.1 + cell][2] = v_state;
18504 }
18505 }
18506 // lane-dkey (same clear as `decode_leaf_split4`): a sub-8x8 leaf can never use palette (`av1_allow_palette`
18507 // needs BLOCK_8X8 and up), and libaom's mi grid says so -- its
18508 // `palette_size` is 0 in every one of these mi cells, so the NEXT block's
18509 // `av1_get_palette_mode_ctx` and colour cache read 0 here. This decoder
18510 // only ever WROTE palette state from the >=8x8 readers, so an 8x8 palette
18511 // block above a 4x4 group left its size/colours standing in the mi-granular
18512 // bands: the block below the group read `palette_y_mode` off CDF row 1
18513 // where libaom reads row 0 (class [[cdf-row-held-constant]]), decoded a
18514 // palette libaom never coded, and then skipped the `use_filter_intra`
18515 // symbol that a palette block has none of -- one symbol short, tile
18516 // desynced. Publishing the group's own zeros is the clear.
18517 neighbours.record_palette_y_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
18518 neighbours.record_palette_uv_rect(leaf_mi, 8, 8, 0, [0u16; 8]);
18519 // `(below_mode, right_mode)`: the sub-block a neighbour below sees is the
18520 // bottom one (the second under HORZ, the left one under VERT), the one a
18521 // neighbour to the right sees is the top-right (the second under VERT).
18522 Ok(if vert {
18523 (leaf_modes[0], leaf_modes[1])
18524 } else {
18525 (leaf_modes[1], leaf_modes[0])
18526 })
18527}
18528
18529/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
18530/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
18531/// (mod 8) reuse the same table.
18532const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
18533 [(-1, 1), (-2, 2)],
18534 [(0, 1), (-1, 2)],
18535 [(0, 1), (0, 2)],
18536 [(0, 1), (1, 2)],
18537 [(1, 1), (2, 2)],
18538 [(1, 0), (2, 1)],
18539 [(1, 0), (2, 0)],
18540 [(1, 0), (2, -1)],
18541];
18542/// A neighbour tap outside the frame's true extent -- `constrain` reads this
18543/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
18544const CDEF_VERY_LARGE: i32 = 0x4000;
18545const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
18546const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
18547
18548fn cdef_msb(x: i32) -> i32 {
18549 31 - x.leading_zeros() as i32
18550}
18551
18552/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
18553/// centre sample a filter tap is allowed to contribute.
18554#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
18555fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
18556 if threshold == 0 {
18557 return 0;
18558 }
18559 cdef_constrain_shifted(diff, threshold, cdef_constrain_shift(threshold, damping))
18560}
18561
18562/// `constrain`'s damping shift: a function of the block's threshold and
18563/// damping alone, so the filter loop computes it once per block instead of
18564/// the `leading_zeros` + branch it used to do twice per tap read.
18565fn cdef_constrain_shift(threshold: i32, damping: i32) -> i32 {
18566 (damping - cdef_msb(threshold)).max(0)
18567}
18568
18569/// [`cdef_constrain`]'s body with the shift already resolved; `threshold` is
18570/// non-zero on every call (the caller only filters when its strength is).
18571fn cdef_constrain_shifted(diff: i32, threshold: i32, shift: i32) -> i32 {
18572 let a = diff.abs();
18573 diff.signum() * (threshold - (a >> shift)).clamp(0, a)
18574}
18575
18576/// The widest `CDEF_DIRECTIONS` offset in either axis: every tap a block reads
18577/// lies inside its own samples grown by this much.
18578const CDEF_BORDER: usize = 2;
18579
18580/// Copies one block's whole CDEF footprint -- its `bh` x `bw` samples plus the
18581/// [`CDEF_BORDER`] tap ring -- out of the *unfiltered* plane into `buf` (row
18582/// stride `bw + 2 * CDEF_BORDER`), so the direction search and the tap loops
18583/// index a small contiguous window instead of re-deriving the frame-bounds
18584/// test on every one of a pixel's ~17 tap reads. Out-of-frame positions get
18585/// `CDEF_VERY_LARGE`, exactly as the per-sample closure did.
18586fn cdef_gather(
18587 src: &[u16],
18588 stride: usize,
18589 true_w: usize,
18590 true_h: usize,
18591 ox: usize,
18592 oy: usize,
18593 bw: usize,
18594 bh: usize,
18595 buf: &mut [i16],
18596) {
18597 let bstride = bw + 2 * CDEF_BORDER;
18598 let rows = bh + 2 * CDEF_BORDER;
18599 if oy >= CDEF_BORDER
18600 && ox >= CDEF_BORDER
18601 && oy + bh + CDEF_BORDER <= true_h
18602 && ox + bw + CDEF_BORDER <= true_w
18603 {
18604 // Interior block: every tap is inside the frame, so the whole window
18605 // is `rows` contiguous runs.
18606 for r in 0..rows {
18607 let s0 = (oy - CDEF_BORDER + r) * stride + (ox - CDEF_BORDER);
18608 let src_row = &src[s0..s0 + bstride];
18609 let dst_row = &mut buf[r * bstride..r * bstride + bstride];
18610 for (d, &v) in dst_row.iter_mut().zip(src_row) {
18611 *d = v as i16;
18612 }
18613 }
18614 return;
18615 }
18616 for r in 0..rows {
18617 let ny = oy as isize + r as isize - CDEF_BORDER as isize;
18618 for c in 0..bstride {
18619 let nx = ox as isize + c as isize - CDEF_BORDER as isize;
18620 buf[r * bstride + c] =
18621 if ny < 0 || nx < 0 || ny as usize >= true_h || nx as usize >= true_w {
18622 CDEF_VERY_LARGE as i16
18623 } else {
18624 src[ny as usize * stride + nx as usize] as i16
18625 };
18626 }
18627 }
18628}
18629
18630/// libaom `cdef_find_dir_c`'s eight partial-sum arrays, row at a time: each
18631/// array takes the row, its reverse, its pairwise sums or its total added
18632/// into consecutive slots, so the 512 scalar read-modify-writes on i64 the
18633/// per-sample form did become a handful of lane-wide adds per row. i32 is
18634/// exact here: every partial is a sum of at most eight values in -128..127,
18635/// and slot 15 exists only so an eight-lane store at offset 7 fits.
18636fn cdef_find_dir_partials(win: &[i16], bstride: usize, coeff_shift: i32) -> [[i32; 16]; 8] {
18637 fn add_at<const N: usize>(dst: &mut [i32; 16], off: usize, src: &[i32; N]) {
18638 for (d, &x) in dst[off..off + N].iter_mut().zip(src.iter()) {
18639 *d += x;
18640 }
18641 }
18642 let mut partial = [[0i32; 16]; 8];
18643 for i in 0..8usize {
18644 let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER;
18645 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
18646 // accumulating, same as `constrain`'s threshold shift.
18647 let row: [i32; 8] = core::array::from_fn(|j| (i32::from(win[base + j]) >> coeff_shift) - 128);
18648 let rev: [i32; 8] = core::array::from_fn(|j| row[7 - j]);
18649 let pair: [i32; 4] = core::array::from_fn(|k| row[2 * k] + row[2 * k + 1]);
18650 let rpair: [i32; 4] = core::array::from_fn(|k| pair[3 - k]);
18651 let (p, rest) = partial.split_at_mut(1);
18652 add_at(&mut p[0], i, &row); // partial[0][i + j]
18653 add_at(&mut rest[0], i, &pair); // partial[1][i + j / 2]
18654 rest[1][i] = row.iter().sum(); // partial[2][i]
18655 add_at(&mut rest[2], i, &rpair); // partial[3][3 + i - j / 2]
18656 add_at(&mut rest[3], i, &rev); // partial[4][7 + i - j]
18657 add_at(&mut rest[4], 3 - i / 2, &row); // partial[5][3 - i / 2 + j]
18658 add_at(&mut rest[5], 0, &row); // partial[6][j]
18659 add_at(&mut rest[6], i / 2, &row); // partial[7][i / 2 + j]
18660 }
18661 partial
18662}
18663
18664/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
18665/// direction of an 8x8 luma window and the variance gap between it and its
18666/// orthogonal, reading [`cdef_gather`]'s window (row stride `bstride`, the
18667/// block's own samples starting at `CDEF_BORDER, CDEF_BORDER`).
18668fn cdef_find_dir(win: &[i16], bstride: usize, coeff_shift: i32) -> (usize, i32) {
18669 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
18670 #[cfg(target_arch = "x86_64")]
18671 let partial = if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
18672 // SAFETY: reached only when the CPU reports avx2; the kernel reads
18673 // the same eight rows of eight samples the scalar form does.
18674 #[allow(unsafe_code)]
18675 unsafe {
18676 cdef_simd::find_dir_partials_avx2(win, bstride, coeff_shift)
18677 }
18678 } else {
18679 cdef_find_dir_partials(win, bstride, coeff_shift)
18680 };
18681 #[cfg(not(target_arch = "x86_64"))]
18682 let partial = cdef_find_dir_partials(win, bstride, coeff_shift);
18683 let sq = |a: i32| -> i64 { i64::from(a) * i64::from(a) };
18684 let mut cost = [0i64; 8];
18685 for i in 0..8usize {
18686 cost[2] += sq(partial[2][i]);
18687 cost[6] += sq(partial[6][i]);
18688 }
18689 cost[2] *= DIV_TABLE[8];
18690 cost[6] *= DIV_TABLE[8];
18691 for i in 0..7usize {
18692 cost[0] += (sq(partial[0][i]) + sq(partial[0][14 - i])) * DIV_TABLE[i + 1];
18693 cost[4] += (sq(partial[4][i]) + sq(partial[4][14 - i])) * DIV_TABLE[i + 1];
18694 }
18695 cost[0] += sq(partial[0][7]) * DIV_TABLE[8];
18696 cost[4] += sq(partial[4][7]) * DIV_TABLE[8];
18697 for i in (1..8).step_by(2) {
18698 for j in 0..5usize {
18699 cost[i] += sq(partial[i][3 + j]);
18700 }
18701 cost[i] *= DIV_TABLE[8];
18702 for j in 0..3usize {
18703 cost[i] += (sq(partial[i][j]) + sq(partial[i][10 - j])) * DIV_TABLE[2 * j + 2];
18704 }
18705 }
18706 let mut best_cost = 0i64;
18707 let mut best_dir = 0usize;
18708 for (i, &c) in cost.iter().enumerate() {
18709 if c > best_cost {
18710 best_cost = c;
18711 best_dir = i;
18712 }
18713 }
18714 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
18715 (best_dir, var as i32)
18716}
18717
18718/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
18719/// (high variance gap) gets more deringing than a flat or non-directional
18720/// one, only ever applied to the luma primary strength.
18721fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
18722 if var == 0 {
18723 return 0;
18724 }
18725 let i = if var >> 6 != 0 {
18726 cdef_msb(var >> 6).min(12)
18727 } else {
18728 0
18729 };
18730 (strength * (4 + i) + 8) >> 4
18731}
18732
18733/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
18734/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
18735/// previously-filtered neighbour must never feed this block's own sum).
18736#[allow(clippy::too_many_arguments)]
18737#[allow(unsafe_code)]
18738fn cdef_filter_block(
18739 src: &[i16],
18740 dst: &mut PlaneBuf<'static>,
18741 ox: usize,
18742 oy: usize,
18743 bw: usize,
18744 bh: usize,
18745 pri_strength: i32,
18746 sec_strength: i32,
18747 dir: usize,
18748 pri_damping: i32,
18749 sec_damping: i32,
18750 enable_primary: bool,
18751 enable_secondary: bool,
18752 coeff_shift: i32, fctx: &crate::decode::FrameCtx,
18753) {
18754 let (stride, smax) = (dst.width, sample_max(fctx));
18755 #[cfg(target_arch = "x86_64")]
18756 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 && (bw == 4 || bw == 8) && bh % 2 == 0
18757 {
18758 // SAFETY: reached only when the CPU reports avx2; the kernel reads
18759 // `src`'s whole (bw + 4) x (bh + 4) window and writes exactly the
18760 // `bh` runs of `bw` samples the scalar form writes.
18761 unsafe {
18762 cdef_simd::filter_block_avx2(
18763 src,
18764 dst.data.to_mut(),
18765 stride,
18766 ox,
18767 oy,
18768 bw,
18769 bh,
18770 pri_strength,
18771 sec_strength,
18772 dir,
18773 pri_damping,
18774 sec_damping,
18775 enable_primary,
18776 enable_secondary,
18777 coeff_shift,
18778 smax,
18779 )
18780 };
18781 return;
18782 }
18783 cdef_filter_block_scalar(
18784 src,
18785 dst.data.to_mut(),
18786 stride,
18787 ox,
18788 oy,
18789 bw,
18790 bh,
18791 pri_strength,
18792 sec_strength,
18793 dir,
18794 pri_damping,
18795 sec_damping,
18796 enable_primary,
18797 enable_secondary,
18798 coeff_shift,
18799 smax,
18800 );
18801}
18802
18803/// [`cdef_filter_block`]'s scalar reference: spec 7.15.3 sample by sample,
18804/// the form every non-AVX2 build decodes through and the one
18805/// `cdef_simd_kernel_matches_the_scalar_filter` checks the kernel against.
18806#[allow(clippy::too_many_arguments)]
18807fn cdef_filter_block_scalar(
18808 src: &[i16],
18809 dst: &mut [u16],
18810 stride: usize,
18811 ox: usize,
18812 oy: usize,
18813 bw: usize,
18814 bh: usize,
18815 pri_strength: i32,
18816 sec_strength: i32,
18817 dir: usize,
18818 pri_damping: i32,
18819 sec_damping: i32,
18820 enable_primary: bool,
18821 enable_secondary: bool,
18822 coeff_shift: i32,
18823 smax: i32,
18824) {
18825 let clipping_required = enable_primary && enable_secondary;
18826 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
18827 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
18828 // derivative) carries the bit-depth shift, so the tap-set parity bit
18829 // must be read back above that shift, not off the raw low bit.
18830 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
18831 // Both damping shifts depend only on this block's strengths (spec 7.15.3's
18832 // `constrain`), so they are resolved here rather than per tap read.
18833 let pri_shift = cdef_constrain_shift(pri_strength.max(1), pri_damping);
18834 let sec_shift = cdef_constrain_shift(sec_strength.max(1), sec_damping);
18835 let bstride = bw + 2 * CDEF_BORDER;
18836 // `src` is [`cdef_gather`]'s window: (i, j) in block coordinates, taps
18837 // reaching +-CDEF_BORDER, so every index below is in range by construction.
18838 let at = |i: i32, j: i32| -> i32 {
18839 i32::from(src[(i + CDEF_BORDER as i32) as usize * bstride + (j + CDEF_BORDER as i32) as usize])
18840 };
18841 let (pri_dir, sec_dir0, sec_dir1) =
18842 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
18843 for i in 0..bh {
18844 for j in 0..bw {
18845 let (i32i, i32j) = (i as i32, j as i32);
18846 let x = at(i32i, i32j);
18847 let mut sum = 0i32;
18848 let mut max = x;
18849 let mut min = x;
18850 for k in 0..2usize {
18851 if enable_primary {
18852 let (tr, tc) = pri_dir[k];
18853 let p0 = at(i32i + tr, i32j + tc);
18854 let p1 = at(i32i - tr, i32j - tc);
18855 sum += pri_taps[k] * cdef_constrain_shifted(p0 - x, pri_strength, pri_shift);
18856 sum += pri_taps[k] * cdef_constrain_shifted(p1 - x, pri_strength, pri_shift);
18857 if clipping_required {
18858 if p0 != CDEF_VERY_LARGE {
18859 max = max.max(p0);
18860 }
18861 if p1 != CDEF_VERY_LARGE {
18862 max = max.max(p1);
18863 }
18864 min = min.min(p0).min(p1);
18865 }
18866 }
18867 if enable_secondary {
18868 let (tr0, tc0) = sec_dir0[k];
18869 let (tr1, tc1) = sec_dir1[k];
18870 let s0 = at(i32i + tr0, i32j + tc0);
18871 let s1 = at(i32i - tr0, i32j - tc0);
18872 let s2 = at(i32i + tr1, i32j + tc1);
18873 let s3 = at(i32i - tr1, i32j - tc1);
18874 if clipping_required {
18875 for s in [s0, s1, s2, s3] {
18876 if s != CDEF_VERY_LARGE {
18877 max = max.max(s);
18878 }
18879 }
18880 min = min.min(s0).min(s1).min(s2).min(s3);
18881 }
18882 sum += CDEF_SEC_TAPS[k]
18883 * (cdef_constrain_shifted(s0 - x, sec_strength, sec_shift)
18884 + cdef_constrain_shifted(s1 - x, sec_strength, sec_shift)
18885 + cdef_constrain_shifted(s2 - x, sec_strength, sec_shift)
18886 + cdef_constrain_shifted(s3 - x, sec_strength, sec_shift));
18887 }
18888 }
18889 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
18890 if clipping_required {
18891 y = y.clamp(min, max);
18892 }
18893 dst[(oy + i) * stride + (ox + j)] = y.clamp(0, smax) as u16;
18894 }
18895 }
18896}
18897
18898/// lane-perf7 step 1: [`cdef_filter_block`]'s AVX2 kernel -- the scalar
18899/// filter was 13.1% of a 4K decode's self time. Nothing here is spec logic:
18900/// the same taps, the same `constrain`, the same `min`/`max` clamp with the
18901/// `CDEF_VERY_LARGE` sentinel excluded from the max, the same
18902/// `y + ((8 + sum - (sum < 0)) >> 4)` rounding, done 16 samples (two rows) at
18903/// a time in 16-bit lanes.
18904///
18905/// 16-bit lanes are exact for every value this filter sees: window samples
18906/// are in `[0, CDEF_VERY_LARGE]` (0x4000), so a tap difference fits in
18907/// `i16`, a `constrain` result is bounded by the threshold (at most
18908/// `15 << 4`), and the tap-weighted sum by `24 *` that.
18909#[cfg(target_arch = "x86_64")]
18910#[allow(unsafe_code)]
18911#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
18912mod cdef_simd {
18913 use super::{
18914 cdef_constrain_shift, CDEF_BORDER, CDEF_DIRECTIONS, CDEF_PRI_TAPS, CDEF_SEC_TAPS,
18915 CDEF_VERY_LARGE,
18916 };
18917 use std::arch::x86_64::*;
18918
18919 /// The window's rows `i` and `i + 1` at one tap offset, as one 256-bit
18920 /// register (low half = row `i`).
18921 ///
18922 /// # Safety
18923 /// Requires AVX2; `off + bstride + 8` must be inside `w`.
18924 #[target_feature(enable = "avx2")]
18925 #[inline]
18926 unsafe fn ld2(w: *const i16, off: isize, bstride: isize) -> __m256i {
18927 let lo = _mm_loadu_si128(w.offset(off).cast());
18928 let hi = _mm_loadu_si128(w.offset(off + bstride).cast());
18929 _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1)
18930 }
18931
18932 /// Spec 7.15.3's `constrain`, lane-parallel:
18933 /// `sign(diff) * clamp(threshold - (|diff| >> shift), 0, |diff|)`.
18934 /// `_mm256_sign_epi16` reproduces `signum` exactly, zero included (the
18935 /// clamped magnitude is already 0 where `diff` is).
18936 ///
18937 /// # Safety
18938 /// Requires AVX2.
18939 #[target_feature(enable = "avx2")]
18940 #[inline]
18941 unsafe fn constrain(p: __m256i, x: __m256i, thr: __m256i, shift: __m128i) -> __m256i {
18942 let diff = _mm256_sub_epi16(p, x);
18943 let a = _mm256_abs_epi16(diff);
18944 let t = _mm256_sub_epi16(thr, _mm256_sra_epi16(a, shift));
18945 let t = _mm256_min_epi16(_mm256_max_epi16(t, _mm256_setzero_si256()), a);
18946 _mm256_sign_epi16(t, diff)
18947 }
18948
18949 /// [`super::cdef_find_dir_partials`] in AVX2 (libaom
18950 /// `cdef_find_dir_avx2`'s shape): eight i32 lanes per row instead of the
18951 /// four the auto-vectorised scalar form gets without the feature.
18952 ///
18953 /// # Safety
18954 /// Requires AVX2. `win` must hold [`super::cdef_gather`]'s 8x8 window
18955 /// grown by `CDEF_BORDER` at row stride `bstride`.
18956 #[target_feature(enable = "avx2")]
18957 pub unsafe fn find_dir_partials_avx2(
18958 win: &[i16],
18959 bstride: usize,
18960 coeff_shift: i32,
18961 ) -> [[i32; 16]; 8] {
18962 #[target_feature(enable = "avx2")]
18963 unsafe fn add8(dst: &mut [i32; 16], off: usize, v: __m256i) {
18964 let p = dst.as_mut_ptr().add(off) as *mut __m256i;
18965 _mm256_storeu_si256(p, _mm256_add_epi32(_mm256_loadu_si256(p), v));
18966 }
18967 #[target_feature(enable = "avx2")]
18968 unsafe fn add4(dst: &mut [i32; 16], off: usize, v: __m128i) {
18969 let p = dst.as_mut_ptr().add(off) as *mut __m128i;
18970 _mm_storeu_si128(p, _mm_add_epi32(_mm_loadu_si128(p), v));
18971 }
18972 let mut partial = [[0i32; 16]; 8];
18973 let shift = _mm_cvtsi32_si128(coeff_shift);
18974 let c128 = _mm256_set1_epi32(128);
18975 let revidx = _mm256_setr_epi32(7, 6, 5, 4, 3, 2, 1, 0);
18976 let mut p6 = _mm256_setzero_si256();
18977 for i in 0..8usize {
18978 let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER;
18979 let raw = _mm_loadu_si128(win.as_ptr().add(base) as *const __m128i);
18980 let row = _mm256_sub_epi32(_mm256_sra_epi32(_mm256_cvtepi16_epi32(raw), shift), c128);
18981 let rev = _mm256_permutevar8x32_epi32(row, revidx);
18982 // `hadd(row, row)` is [p0, p1, p0, p1 | p2, p3, p2, p3], so the
18983 // four pairwise sums are the two lanes' low halves joined.
18984 let h = _mm256_hadd_epi32(row, row);
18985 let pair =
18986 _mm_unpacklo_epi64(_mm256_castsi256_si128(h), _mm256_extracti128_si256(h, 1));
18987 let rpair = _mm_shuffle_epi32(pair, 0b00_01_10_11);
18988 let hs = _mm_hadd_epi32(pair, pair);
18989 let total = _mm_cvtsi128_si32(_mm_hadd_epi32(hs, hs));
18990 add8(&mut partial[0], i, row);
18991 add4(&mut partial[1], i, pair);
18992 partial[2][i] = total;
18993 add4(&mut partial[3], i, rpair);
18994 add8(&mut partial[4], i, rev);
18995 add8(&mut partial[5], 3 - i / 2, row);
18996 p6 = _mm256_add_epi32(p6, row);
18997 add8(&mut partial[7], i / 2, row);
18998 }
18999 _mm256_storeu_si256(partial[6].as_mut_ptr() as *mut __m256i, p6);
19000 partial
19001 }
19002
19003 /// [`super::cdef_filter_block_scalar`]'s arithmetic, two rows per
19004 /// iteration. `bw` is 8 (luma) or 4 (4:2:0 chroma) and `bh` matches; for
19005 /// `bw == 4` the upper four lanes of each half are window samples read
19006 /// past the row (never past the buffer -- `w` is padded to 256 entries),
19007 /// computed and then dropped by the 64-bit store.
19008 ///
19009 /// # Safety
19010 /// Requires AVX2. `src` must be [`super::cdef_gather`]'s 256-entry window
19011 /// buffer (the tap loads read up to 152 entries past its start, i.e. past
19012 /// the `(bw + 4) x (bh + 4)` samples themselves) and `dst` the `bh` rows
19013 /// of `bw` samples at `(ox, oy)`.
19014 #[target_feature(enable = "avx2")]
19015 #[allow(clippy::too_many_arguments)]
19016 pub unsafe fn filter_block_avx2(
19017 src: &[i16],
19018 dst: &mut [u16],
19019 stride: usize,
19020 ox: usize,
19021 oy: usize,
19022 bw: usize,
19023 bh: usize,
19024 pri_strength: i32,
19025 sec_strength: i32,
19026 dir: usize,
19027 pri_damping: i32,
19028 sec_damping: i32,
19029 enable_primary: bool,
19030 enable_secondary: bool,
19031 coeff_shift: i32,
19032 smax: i32,
19033 ) {
19034 let bstride = bw + 2 * CDEF_BORDER;
19035 // The caller's window is already `i16` and 256 entries long, so the
19036 // kernel taps it in place: the largest two-row load is
19037 // (bh + 3) * bstride + 8 <= 152 for the 8x8 luma block, 72 for the
19038 // 4x4 chroma one, both inside the buffer's zeroed tail.
19039 let w = src;
19040 let clipping_required = enable_primary && enable_secondary;
19041 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
19042 let pri_shift = _mm_cvtsi32_si128(cdef_constrain_shift(pri_strength.max(1), pri_damping));
19043 let sec_shift = _mm_cvtsi32_si128(cdef_constrain_shift(sec_strength.max(1), sec_damping));
19044 let pri_thr = _mm256_set1_epi16(pri_strength as i16);
19045 let sec_thr = _mm256_set1_epi16(sec_strength as i16);
19046 let very_large = _mm256_set1_epi16(CDEF_VERY_LARGE as i16);
19047 let zero = _mm256_setzero_si256();
19048 let eight = _mm256_set1_epi16(8);
19049 let smaxv = _mm256_set1_epi16(smax as i16);
19050 let (pri_dir, sec_dir0, sec_dir1) =
19051 (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
19052 let wp = w.as_ptr();
19053 let bs = bstride as isize;
19054 let dp = dst.as_mut_ptr();
19055 let mut i = 0usize;
19056 while i < bh {
19057 let base = (i + CDEF_BORDER) as isize * bs + CDEF_BORDER as isize;
19058 let x = ld2(wp, base, bs);
19059 let mut sum = zero;
19060 let mut max = x;
19061 let mut min = x;
19062 for k in 0..2usize {
19063 if enable_primary {
19064 let (tr, tc) = pri_dir[k];
19065 let off = tr as isize * bs + tc as isize;
19066 let p0 = ld2(wp, base + off, bs);
19067 let p1 = ld2(wp, base - off, bs);
19068 let tap = _mm256_set1_epi16(pri_taps[k] as i16);
19069 sum = _mm256_add_epi16(
19070 sum,
19071 _mm256_mullo_epi16(tap, constrain(p0, x, pri_thr, pri_shift)),
19072 );
19073 sum = _mm256_add_epi16(
19074 sum,
19075 _mm256_mullo_epi16(tap, constrain(p1, x, pri_thr, pri_shift)),
19076 );
19077 if clipping_required {
19078 // The sentinel is excluded from the max exactly as the
19079 // scalar `if p != CDEF_VERY_LARGE` does: masking it to
19080 // 0 cannot win a max whose seed `x` is non-negative.
19081 max = _mm256_max_epi16(
19082 max,
19083 _mm256_andnot_si256(_mm256_cmpeq_epi16(p0, very_large), p0),
19084 );
19085 max = _mm256_max_epi16(
19086 max,
19087 _mm256_andnot_si256(_mm256_cmpeq_epi16(p1, very_large), p1),
19088 );
19089 min = _mm256_min_epi16(min, _mm256_min_epi16(p0, p1));
19090 }
19091 }
19092 if enable_secondary {
19093 let (tr0, tc0) = sec_dir0[k];
19094 let (tr1, tc1) = sec_dir1[k];
19095 let off0 = tr0 as isize * bs + tc0 as isize;
19096 let off1 = tr1 as isize * bs + tc1 as isize;
19097 let s0 = ld2(wp, base + off0, bs);
19098 let s1 = ld2(wp, base - off0, bs);
19099 let s2 = ld2(wp, base + off1, bs);
19100 let s3 = ld2(wp, base - off1, bs);
19101 if clipping_required {
19102 for s in [s0, s1, s2, s3] {
19103 max = _mm256_max_epi16(
19104 max,
19105 _mm256_andnot_si256(_mm256_cmpeq_epi16(s, very_large), s),
19106 );
19107 }
19108 min = _mm256_min_epi16(
19109 min,
19110 _mm256_min_epi16(
19111 _mm256_min_epi16(s0, s1),
19112 _mm256_min_epi16(s2, s3),
19113 ),
19114 );
19115 }
19116 let c = _mm256_add_epi16(
19117 _mm256_add_epi16(
19118 constrain(s0, x, sec_thr, sec_shift),
19119 constrain(s1, x, sec_thr, sec_shift),
19120 ),
19121 _mm256_add_epi16(
19122 constrain(s2, x, sec_thr, sec_shift),
19123 constrain(s3, x, sec_thr, sec_shift),
19124 ),
19125 );
19126 sum = _mm256_add_epi16(
19127 sum,
19128 _mm256_mullo_epi16(_mm256_set1_epi16(CDEF_SEC_TAPS[k] as i16), c),
19129 );
19130 }
19131 }
19132 // `-1` where `sum < 0`, i.e. the scalar `- i32::from(sum < 0)`.
19133 let neg = _mm256_cmpgt_epi16(zero, sum);
19134 let mut y = _mm256_add_epi16(
19135 x,
19136 _mm256_srai_epi16(_mm256_add_epi16(_mm256_add_epi16(eight, sum), neg), 4),
19137 );
19138 if clipping_required {
19139 y = _mm256_min_epi16(_mm256_max_epi16(y, min), max);
19140 }
19141 y = _mm256_min_epi16(_mm256_max_epi16(y, zero), smaxv);
19142 let (lo, hi) = (_mm256_castsi256_si128(y), _mm256_extracti128_si256(y, 1));
19143 let o0 = ((oy + i) * stride + ox) as isize;
19144 let o1 = o0 + stride as isize;
19145 if bw == 8 {
19146 _mm_storeu_si128(dp.offset(o0).cast(), lo);
19147 _mm_storeu_si128(dp.offset(o1).cast(), hi);
19148 } else {
19149 _mm_storel_epi64(dp.offset(o0).cast(), lo);
19150 _mm_storel_epi64(dp.offset(o1).cast(), hi);
19151 }
19152 i += 2;
19153 }
19154 }
19155}
19156
19157/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
19158/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
19159/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
19160/// every block's level comes from [`LoopFilterParams::level`] plus the
19161/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
19162/// `get_filter_level`, precomputed per-block here rather than cached in a
19163/// table the way libaom's `av1_loop_filter_frame_init` does).
19164///
19165/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
19166/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
19167fn apply_deblock(
19168 y: &mut PlaneBuf<'static>,
19169 u: &mut PlaneBuf<'static>,
19170 v: &mut PlaneBuf<'static>,
19171 lf: &LoopFilterParams,
19172 n: &Neighbours,
19173 frame_width: usize,
19174 frame_height: usize, fctx: &crate::decode::FrameCtx,
19175) {
19176 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
19177 // mismatch between the raw reconstruction and post-filter output.
19178 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_DEBLOCK") {
19179 return;
19180 }
19181 if lf.level[0] != 0 || lf.level[1] != 0 {
19182 deblock_plane(y, 0, lf, n, frame_width, frame_height, fctx);
19183 }
19184 if lf.level[2] != 0 {
19185 deblock_plane(u, 1, lf, n, frame_width, frame_height, fctx);
19186 }
19187 if lf.level[3] != 0 {
19188 deblock_plane(v, 2, lf, n, frame_width, frame_height, fctx);
19189 }
19190}
19191
19192/// [`apply_deblock`] for ONE pass over ONE band of luma rows
19193/// (`y_lo..y_hi`), the form [`pipe_run`] calls it in. Running the three
19194/// planes' vertical passes and then their three horizontal ones is the same
19195/// output as `apply_deblock`'s plane-at-a-time order: the planes are
19196/// separate buffers and neither pass reads another plane.
19197#[allow(clippy::too_many_arguments)]
19198fn deblock_span(
19199 y: &mut PlaneBuf<'static>,
19200 u: &mut PlaneBuf<'static>,
19201 v: &mut PlaneBuf<'static>,
19202 lf: &LoopFilterParams,
19203 n: &Neighbours,
19204 frame_width: usize,
19205 frame_height: usize,
19206 y_lo: usize,
19207 y_hi: usize,
19208 horz: bool,
19209 fctx: &crate::decode::FrameCtx,
19210) {
19211 if lf.level[0] != 0 || lf.level[1] != 0 {
19212 deblock_plane_span(y, 0, lf, n, frame_width, frame_height, y_lo, y_hi, horz, fctx);
19213 }
19214 if lf.level[2] != 0 {
19215 deblock_plane_span(u, 1, lf, n, frame_width, frame_height, y_lo / 2, y_hi / 2, horz, fctx);
19216 }
19217 if lf.level[3] != 0 {
19218 deblock_plane_span(v, 2, lf, n, frame_width, frame_height, y_lo / 2, y_hi / 2, horz, fctx);
19219 }
19220}
19221
19222/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
19223/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
19224/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
19225/// mi unit under this decoder's assumed 4:2:0 subsampling).
19226///
19227/// lane-t900 r30b: the chroma arm ORs in the subsampling, exactly as
19228/// `set_lpf_parameters` does (`av1_loopfilter.c:245`, `mi_col = scale_horz |
19229/// ((x << scale_horz) >> MI_SIZE_LOG2)`) -- "for sub8x8 block, chroma
19230/// prediction mode is obtained from the bottom/right mi structure of the
19231/// co-located 8x8 luma block, so for chroma plane both mi_row and mi_col
19232/// should be odd". Dropping that `| 1` read the group's TOP-LEFT mi, which
19233/// is the same cell for every block 8x8 and larger and a DIFFERENT coded
19234/// block (different tx size, ref frame, skip flag and delta_lf) as soon as
19235/// the group is split into 4x4 luma blocks (class
19236/// `context-read-from-one-cell`).
19237fn plane_to_mi(chroma: bool, coord: usize) -> usize {
19238 if chroma { (coord / 2) | 1 } else { coord / 4 }
19239}
19240
19241/// This plane's own transform width in pixels at the covering block, spec
19242/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
19243/// width directly; chroma halves it (this decoder's UV transform is always
19244/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
19245/// under 4:2:0 and a block that never splits its own transform).
19246fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
19247 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
19248 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
19249}
19250
19251/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
19252/// edges step and gate by transform height, which differs from width only
19253/// on rect partition strips.
19254fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
19255 let grid = if chroma { &n.uv_tx_h_grid } else { &n.tx_h_grid };
19256 grid.get(mi_r * n.skip_grid_cols_mi + mi_c).copied().unwrap_or(0) as u32
19257}
19258
19259/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
19260/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
19261/// present only when its neighbour exists inside the true frame -- whether
19262/// the block immediately above (at this block's own leftmost mi column) or
19263/// to the left (at its own topmost mi row) coded a transform at least as wide
19264/// (tall) as this block's own `max_txsize_rect_lookup[bsize]`.
19265///
19266/// lane-av1txbands: this reads the real `TXFM_CONTEXT` bands
19267/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`]) for EVERY frame
19268/// now -- libaom maintains them on intra-only frames too (`parse_decode_block`
19269/// runs `set_txfm_ctxs` for every block, and
19270/// [`Neighbours::fill_lf_grid_rect`] publishes them there), except that an
19271/// *inter* neighbour contributes its own BLOCK size rather than its transform
19272/// size -- and libaom's `is_inter_block` counts an INTRABC block
19273/// (`blockd.h:373`), which is what the `above_inter`/`left_inter` bands carry.
19274/// The previous deblock-grid approximation coincided with this only while
19275/// every neighbour coded one whole-block transform, which is exactly what
19276/// `TxMode::Select` ends.
19277///
19278/// The rect form (lane-intrasplit r1): `get_tx_size_context` compares the
19279/// neighbour ABOVE against `tx_size_wide[max_txsize_rect_lookup[bsize]]` and
19280/// the neighbour to the LEFT against `tx_size_high[...]` (libaom
19281/// `pred_common.h:342`), which for a 2:1 strip are two different numbers.
19282fn tx_size_context_txfm_rect(
19283 n: &Neighbours,
19284 (mi_r, mi_c): (usize, usize),
19285 own_w: usize,
19286 own_h: usize, fctx: &crate::decode::FrameCtx,
19287) -> usize {
19288 hit!(INTRA_IN_INTER_TXCTX_HITS);
19289 // `max_txsize_rect_lookup[bsize]` tops out at TX_64X64: no transform is
19290 // wider or taller than 64, so a block with a 128 side resolves against 64
19291 // (lane-sb128b r1).
19292 let (own_w, own_h) = (own_w.min(64), own_h.min(64));
19293 let has_above = mi_r > n.tile_row0_mi;
19294 let has_left = mi_c > n.tile_col0_mi;
19295 let mut above = usize::from(n.above_txfm[mi_c]) >= own_w;
19296 let mut left = usize::from(n.left_txfm[mi_r]) >= own_h;
19297 if has_above && n.above_inter[mi_c] {
19298 above = usize::from(n.above_side_mi[mi_c]) >= own_w;
19299 }
19300 if has_left && n.left_inter[mi_r] {
19301 left = usize::from(n.left_side_mi[mi_r]) >= own_h;
19302 }
19303 if crate::envflags::env_flag!("EC_TXCTX") {
19304 eprintln!(
19305 "EC_TXCTX mi={mi_r},{mi_c} own={own_w}x{own_h} ha={has_above} hl={has_left} \
19306 intra_only={} above_txfm={} left_txfm={} above_inter={} left_inter={} \
19307 above_side={} left_side={} above={above} left={left}",
19308 fctx.intra_only.with(std::cell::Cell::get),
19309 n.above_txfm[mi_c],
19310 n.left_txfm[mi_r],
19311 n.above_inter[mi_c],
19312 n.left_inter[mi_r],
19313 n.above_side_mi[mi_c],
19314 n.left_side_mi[mi_r],
19315 );
19316 }
19317 let ctx = match (has_above, has_left) {
19318 (true, true) => usize::from(above) + usize::from(left),
19319 (true, false) => usize::from(above),
19320 (false, true) => usize::from(left),
19321 (false, false) => 0,
19322 };
19323 {
19324 let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w)
19325 + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h);
19326 if ctx != stale {
19327 hit!(TXCTX_DEBLOCK_DIVERGENCE_HITS);
19328 }
19329 }
19330 ctx
19331}
19332
19333/// lane-intrasplit r3: `above_inter`/`left_inter` are mi-granular bands (they
19334/// are written and read everywhere else with a raw mi index); the SUB-cell
19335/// division this pair used read a cell four blocks away, so the inter-neighbour
19336/// override above fired on the wrong neighbour -- the first divergence of the
19337/// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1,
19338/// at the intra block right of an inter one).
19339fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
19340 let has_above = mi_r > n.tile_row0_mi;
19341 let has_left = mi_c > n.tile_col0_mi;
19342 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
19343 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
19344 // lane-angledelta r1 (class [[context-read-from-one-cell]]): both
19345 // `above_inter`/`left_inter` bands are written per MI unit
19346 // (`record_inter_rect_mi`), so they are read per MI too -- the `/ (SUB /
19347 // MI)` here read the 16-px cell's FIRST mi instead, i.e. a different
19348 // block whenever the neighbour column/row is not the cell's first. A
19349 // 16x16 intra block whose left neighbour is an inter block at mi row 4
19350 // then missed libaom's "an inter neighbour contributes its BLOCK size"
19351 // override and read `tx_size_cat1` row 1 where aomdec reads row 2.
19352 if has_above && n.above_inter[mi_c] {
19353 above = usize::from(n.above_side_mi[mi_c]) >= side;
19354 }
19355 if has_left && n.left_inter[mi_r] {
19356 left = usize::from(n.left_side_mi[mi_r]) >= side;
19357 }
19358 if crate::envflags::env_flag!("EC_TXCTX") {
19359 eprintln!(
19360 "EC_TXCTX mi={mi_r},{mi_c} own={side} ha={has_above} hl={has_left} \
19361 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
19362 above={above} left={left}",
19363 n.above_txfm[mi_c],
19364 n.left_txfm[mi_r],
19365 n.above_inter[mi_c],
19366 n.left_inter[mi_r],
19367 n.above_side_mi[mi_c],
19368 n.left_side_mi[mi_r],
19369 );
19370 }
19371 match (has_above, has_left) {
19372 (true, true) => usize::from(above) + usize::from(left),
19373 (true, false) => usize::from(above),
19374 (false, true) => usize::from(left),
19375 (false, false) => 0,
19376 }
19377}
19378
19379/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
19380/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
19381/// the transform's own side in pixels (`side >> depth`) -- this decoder's
19382/// four square categories (8/16/32/64) each halve at most twice, matching
19383/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
19384fn read_tx_size(
19385 dec: &mut SymbolDecoder,
19386 cdfs: &mut Cdfs,
19387 n: &Neighbours,
19388 at_mi: (usize, usize),
19389 side: usize,
19390) -> usize {
19391 // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` /
19392 // `get_tx_size_context`): a block wider than 64 still tops out at
19393 // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth
19394 // chain 64->32->16->8->4 is the same four steps) and resolves against 64,
19395 // never against its own 128 side (lane-sb128b r1).
19396 let max_tx = side.min(64);
19397 let ctx = tx_size_context_txfm(n, at_mi, max_tx);
19398 let depth = match max_tx {
19399 8 => {
19400 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
19401 }
19402 16 => {
19403 dec.symbol(&mut cdfs.tx_size_cat1[ctx])
19404 }
19405 32 => {
19406 dec.symbol(&mut cdfs.tx_size_cat2[ctx])
19407 }
19408 64 => {
19409 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
19410 }
19411 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),
19412 };
19413 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
19414 let (rng, _) = dec.debug_state();
19415 let (mi_r, mi_c) = at_mi;
19416 eprintln!(
19417 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
19418 );
19419 }
19420 if depth != 0 {
19421 hit!(TX_DEPTH_HITS);
19422 }
19423 max_tx >> depth
19424}
19425
19426/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
19427/// `txfm_split` context -- a category from the block's own largest square
19428/// transform and whether this unit already sits below it, times three, plus
19429/// the two neighbour terms (whether the transform last written above/left of
19430/// this unit is narrower/shorter than the unit itself).
19431#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
19432fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
19433 txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px)
19434}
19435
19436/// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2):
19437/// libaom's `txfm_partition_context` compares the above context against
19438/// `tx_size_wide` and the left one against `tx_size_high`, and takes its
19439/// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one
19440/// side for a square transform, which is why the square form above is a
19441/// special case of this one.
19442pub(crate) fn txfm_partition_ctx_rect(
19443 above_px: u8,
19444 left_px: u8,
19445 blk_max_px: usize,
19446 tx_w: usize,
19447 tx_h: usize,
19448) -> usize {
19449 let above = usize::from(usize::from(above_px) < tx_w);
19450 let left = usize::from(usize::from(left_px) < tx_h);
19451 let tx_px = tx_w.max(tx_h);
19452 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
19453 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
19454 // `log2(px) - 2`.
19455 let max_tx = blk_max_px.min(64);
19456 let max_idx = max_tx.trailing_zeros() as usize - 2;
19457 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
19458 category * 3 + above + left
19459}
19460
19461/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
19462/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
19463/// resolved transform's own size.
19464#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
19465fn txfm_partition_update(
19466 n: &mut Neighbours,
19467 at_mi: (usize, usize),
19468 tx_px: usize,
19469 txb_px: usize,
19470) {
19471 txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px));
19472}
19473
19474/// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2):
19475/// the left column records `tx_size_high` over the parent's own height and
19476/// the above row records `tx_size_wide` over its width.
19477/// libaom `set_txfm_ctxs` + `txfm_partition_update` (`decodeframe.c`, end of
19478/// `decode_token_recon_block`): EVERY block of an inter frame publishes its
19479/// TRANSFORM size into both `TXFM_CONTEXT` bands, intra blocks included. The
19480/// key frame writes neither (its readers use the deblock grid), so the
19481/// key-frame bodies reused by [`decode_intra_rect_in_inter`] have to do it
19482/// themselves when they run inside an inter frame. The 2:1 and 16x4 arms do it
19483/// at the call site (the transform size comes back to them); the 1:4 arms
19484/// ([`decode_block_rect4`] / [`decode_block_rect64`]) keep their size inside,
19485/// so they call this where their own depth resolves. A no-op on a key frame
19486/// ([`INTRA_IN_INTER_MODE`] unset), where those bands are not read at all.
19487///
19488/// lane-t900 r1 root cause: the HORZ_4 32x8 intra strip at mi(0,312) of an
19489/// inter frame left `left_txfm[0]` at a stale 32 where libaom's own
19490/// `set_txfm_ctxs` writes 8, so the intra 8x16 block at mi(0,320) read
19491/// `tx_size_cat1` row 1 instead of row 0 -- same depth VALUE, different CDF,
19492/// range 39156 where the reference has 54736 (class tx-grid-published-block-side
19493/// / early-return-skips-tail).
19494///
19495/// lane-av1-intrabc r3: an `allow_intrabc` KEY frame reads the same bands --
19496/// `read_intra_frame_mode_info` returns early for an intrabc block, so
19497/// [`read_block_tx_size_rect`]'s var-tx tree is the intra path's one
19498/// `txfm_partition_context` reader, and it reads whatever the block ABOVE and
19499/// the block LEFT published. [`decode_block`] has published on such a frame
19500/// since lane-t900 r32; the RECT strips did not, so the band still held the
19501/// value of an older, smaller neighbour -- measured on the 256x192 testsrc2
19502/// cq45 var-tx arm: the coded 16x8 intrabc strip at mi(38,48) read ctx 14
19503/// where libaom reads 13 (`left_ctx` 4 vs the 8 the 16x8 intra strip at
19504/// mi(38,44) should have published), desyncing the tile there.
19505fn publish_txfm_bands_if_in_inter(
19506 n: &mut Neighbours,
19507 at_mi: (usize, usize),
19508 (tx_w, tx_h): (usize, usize),
19509 (bw, bh): (usize, usize), fctx: &crate::decode::FrameCtx,
19510) {
19511 if fctx.intra_in_inter_mode.with(std::cell::Cell::get).is_none()
19512 && !allow_intrabc_frame(fctx)
19513 {
19514 return;
19515 }
19516 let (mi_r, mi_c) = at_mi;
19517 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
19518 for i in 0..bw / MI {
19519 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
19520 *cell = tx_w as u8;
19521 }
19522 }
19523 for i in 0..bh / MI {
19524 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
19525 *cell = tx_h as u8;
19526 }
19527 }
19528}
19529
19530fn txfm_partition_update_rect(
19531 n: &mut Neighbours,
19532 (mi_r, mi_c): (usize, usize),
19533 (tx_w, tx_h): (usize, usize),
19534 (txb_w, txb_h): (usize, usize),
19535) {
19536 if crate::envflags::env_flag!("EC_TXUPD") {
19537 eprintln!("EC_TXUPD rect mi=({},{}) tx=({tx_w},{tx_h}) txb=({txb_w},{txb_h})", mi_r, mi_c);
19538 }
19539 for i in 0..txb_h / MI {
19540 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
19541 *cell = tx_h as u8;
19542 }
19543 }
19544 for i in 0..txb_w / MI {
19545 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
19546 *cell = tx_w as u8;
19547 }
19548 }
19549}
19550
19551/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
19552/// same contexts -- a skipped *inter* block records its own block size rather
19553/// than its transform size.
19554fn set_txfm_ctxs(
19555 n: &mut Neighbours,
19556 (mi_r, mi_c): (usize, usize),
19557 tx_px: usize,
19558 w_mi: usize,
19559 h_mi: usize,
19560 skip_inter: bool,
19561) {
19562 if crate::envflags::env_flag!("EC_TXUPD") {
19563 eprintln!("EC_TXUPD ctxs mi=({mi_r},{mi_c}) tx={tx_px} wh=({w_mi},{h_mi}) skip_inter={skip_inter}");
19564 }
19565 let bw = if skip_inter { w_mi * MI } else { tx_px };
19566 let bh = if skip_inter { h_mi * MI } else { tx_px };
19567 for i in 0..w_mi {
19568 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
19569 *cell = bw as u8;
19570 }
19571 }
19572 for i in 0..h_mi {
19573 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
19574 *cell = bh as u8;
19575 }
19576 }
19577}
19578
19579/// The value libaom initialises both transform contexts to -- NOT zero:
19580/// `av1_zero_above_context` memsets the txfm row to
19581/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
19582/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
19583/// pixels, so an unwritten neighbour reads as the *widest* possible
19584/// transform, not the narrowest.
19585pub(crate) const TXFM_CTX_INIT: u8 = 64;
19586
19587/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
19588/// twice below its own largest transform.
19589const MAX_VARTX_DEPTH: usize = 2;
19590
19591/// libaom `sub_tx_size_map[TX_SIZES_ALL]` (`common_data.c`): the transform
19592/// one `txfm_split` step below `tx_size`. RECTANGULAR for the 1:4 shapes
19593/// (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`) and for the 4:1
19594/// small ones, square everywhere else.
19595fn sub_tx_size_map(tx_w: usize, tx_h: usize) -> (usize, usize) {
19596 match (tx_w, tx_h) {
19597 (4, 4) => (4, 4),
19598 (8, 8) => (4, 4),
19599 (16, 16) => (8, 8),
19600 (32, 32) => (16, 16),
19601 (64, 64) => (32, 32),
19602 (4, 8) | (8, 4) => (4, 4),
19603 (8, 16) | (16, 8) => (8, 8),
19604 (16, 32) | (32, 16) => (16, 16),
19605 (32, 64) | (64, 32) => (32, 32),
19606 (4, 16) => (4, 8),
19607 (16, 4) => (8, 4),
19608 (8, 32) => (8, 16),
19609 (32, 8) => (16, 8),
19610 (16, 64) => (16, 32),
19611 (64, 16) => (32, 16),
19612 _ => unreachable!("not a TX_SIZES_ALL shape: {tx_w}x{tx_h}"),
19613 }
19614}
19615
19616#[test]
19617fn sub_tx_size_map_matches_libaom() {
19618 // libaom `common_data.c` `sub_tx_size_map`, in TX_SIZES_ALL order.
19619 const TABLE: [((usize, usize), (usize, usize)); 19] = [
19620 ((4, 4), (4, 4)), ((8, 8), (4, 4)), ((16, 16), (8, 8)), ((32, 32), (16, 16)),
19621 ((64, 64), (32, 32)), ((4, 8), (4, 4)), ((8, 4), (4, 4)), ((8, 16), (8, 8)),
19622 ((16, 8), (8, 8)), ((16, 32), (16, 16)), ((32, 16), (16, 16)), ((32, 64), (32, 32)),
19623 ((64, 32), (32, 32)), ((4, 16), (4, 8)), ((16, 4), (8, 4)), ((8, 32), (8, 16)),
19624 ((32, 8), (16, 8)), ((16, 64), (16, 32)), ((64, 16), (32, 16)),
19625 ];
19626 for (tx, want) in TABLE {
19627 assert_eq!(sub_tx_size_map(tx.0, tx.1), want, "sub_tx_size_map({tx:?})");
19628 }
19629}
19630
19631/// The domain of var-tx leaf sizes, enumerated against the two refusals that
19632/// name a leaf "larger than 32x32" / "larger than 64x64".
19633///
19634/// [`read_var_tx_size`] emits a leaf in exactly three places, and each one is
19635/// either the unit it was entered with or a `sub_tx_size_map` step below it:
19636/// the depth cap, the `!split` return, and libaom's `sub_txs == TX_4X4` early
19637/// return. So the leaf set reachable from an entry unit is that unit plus the
19638/// chain of `sub_tx_size_map` steps under it, capped at `MAX_VARTX_DEPTH` --
19639/// which this test enumerates, and over which no leaf is ever larger than the
19640/// entry.
19641///
19642/// That closes both refusals:
19643///
19644/// * [`read_block_tx_size_rect`]'s `bw.max(bh) > 64` branch enters every unit
19645/// at TX_64X64 (`max_txsize_rect_lookup[BLOCK_128X64]`), so "larger than
19646/// 64x64" names a leaf the tree cannot produce;
19647/// * [`read_block_tx_size`] enters at `side.min(64)` with a ceiling of 32
19648/// below the 128 root. The only entry that exceeds that ceiling is 64x64,
19649/// reached only when `side == 64`, and then the block is ONE unit whose only
19650/// above-ceiling leaf is the whole 64x64 unit itself -- which is the `single`
19651/// case the refusal is guarded by.
19652#[test]
19653fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() {
19654 // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h).
19655 fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) {
19656 out.push((depth, entry.0, entry.1));
19657 if depth == MAX_VARTX_DEPTH {
19658 return;
19659 }
19660 let sub = sub_tx_size_map(entry.0, entry.1);
19661 if sub == (4, 4) {
19662 out.push((depth + 1, 4, 4));
19663 return;
19664 }
19665 reachable(sub, depth + 1, out);
19666 }
19667
19668 for entry in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64)] {
19669 let mut leaves = Vec::new();
19670 reachable(entry, 0, &mut leaves);
19671 for (depth, w, h) in &leaves {
19672 assert!(
19673 w.max(h) <= &entry.0.max(entry.1),
19674 "a {}x{} unit reaches a {w}x{h} leaf at depth {depth}",
19675 entry.0,
19676 entry.1
19677 );
19678 }
19679 // Above-ceiling leaves of a 64x64 entry: the entry itself, at depth 0.
19680 if entry == (64, 64) {
19681 let above: Vec<&(usize, usize, usize)> =
19682 leaves.iter().filter(|(_, w, h)| w.max(h) > &32).collect();
19683 assert_eq!(above, [&(0usize, 64usize, 64usize)], "64x64 entry, leaves above 32");
19684 }
19685 }
19686
19687 // The entry size and ceiling each caller uses, over the block sides that
19688 // reach them (`read_block_tx_size`'s square path; the 128-root rect path
19689 // enters at a fixed 64).
19690 for side in [8usize, 16, 32, 64, 128] {
19691 let max_tx = side.min(64);
19692 let ceiling = if side > 64 { 64 } else { 32 };
19693 let units = (side / max_tx) * (side / max_tx);
19694 if max_tx <= ceiling {
19695 continue;
19696 }
19697 assert_eq!(
19698 (side, units),
19699 (64, 1),
19700 "a {side}px block enters var-tx at {max_tx} over a ceiling of {ceiling} in \
19701 {units} units -- an above-ceiling leaf there would NOT be the `single` case"
19702 );
19703 }
19704}
19705
19706/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
19707/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
19708/// max-transform-sized unit of an inter block, collecting the resolved leaf
19709/// transform units into `out` as `(row offset, col offset, side)` in mi units
19710/// -- exactly the order `decode_reconstruct_tx` later reads their
19711/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
19712/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
19713/// `max_block_high`).
19714#[allow(clippy::too_many_arguments)]
19715fn read_var_tx_size(
19716 dec: &mut SymbolDecoder,
19717 cdfs: &mut Cdfs,
19718 n: &mut Neighbours,
19719 at_mi: (usize, usize),
19720 blk_max_px: usize,
19721 (max_w_mi, max_h_mi): (usize, usize),
19722 (tx_w, tx_h): (usize, usize),
19723 depth: usize,
19724 blk_row: usize,
19725 blk_col: usize,
19726 out: &mut Vec<(usize, usize, usize, usize)>,
19727) {
19728 if blk_row >= max_h_mi || blk_col >= max_w_mi {
19729 return;
19730 }
19731 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
19732 if depth == MAX_VARTX_DEPTH {
19733 out.push((blk_row, blk_col, tx_w, tx_h));
19734 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
19735 return;
19736 }
19737 let ctx = txfm_partition_ctx_rect(
19738 n.above_txfm[unit.1],
19739 n.left_txfm[unit.0],
19740 blk_max_px,
19741 tx_w,
19742 tx_h,
19743 );
19744 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
19745 hit!(TXFM_SPLIT_READS);
19746 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
19747 let (rng, _) = dec.debug_state();
19748 eprintln!(
19749 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
19750 unit.0,
19751 unit.1,
19752 u8::from(split)
19753 );
19754 }
19755 if !split {
19756 out.push((blk_row, blk_col, tx_w, tx_h));
19757 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
19758 return;
19759 }
19760 hit!(TXFM_SPLIT_HITS);
19761 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
19762 if (sub_w, sub_h) == (4, 4) {
19763 // libaom's `sub_txs == TX_4X4` early return: every mi cell of the
19764 // unit is marked 4x4 (raster order) without recursing.
19765 for row in 0..tx_h / MI {
19766 for col in 0..tx_w / MI {
19767 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
19768 out.push((blk_row + row, blk_col + col, 4, 4));
19769 }
19770 }
19771 }
19772 txfm_partition_update_rect(n, unit, (4, 4), (tx_w, tx_h));
19773 return;
19774 }
19775 for row in (0..tx_h / MI).step_by(sub_h / MI) {
19776 for col in (0..tx_w / MI).step_by(sub_w / MI) {
19777 read_var_tx_size(
19778 dec,
19779 cdfs,
19780 n,
19781 at_mi,
19782 blk_max_px,
19783 (max_w_mi, max_h_mi),
19784 (sub_w, sub_h),
19785 depth + 1,
19786 blk_row + row,
19787 blk_col + col,
19788 out,
19789 );
19790 }
19791 }
19792}
19793
19794/// `read_block_tx_size` (libaom `decodeframe.c` `parse_decode_block`'s tx
19795/// branch): every block of a `TxMode::Select` inter frame codes its transform
19796/// size right after its own mode info -- an inter non-skip block through the
19797/// recursive var-tx tree ([`read_var_tx_size`], whose leaf list this returns),
19798/// every other block through the intra `tx_depth` symbol (a skipped inter
19799/// block codes no symbol at all) plus a `set_txfm_ctxs` write. Returns the
19800/// block's own resolved transform side and the leaf list, the latter only
19801/// when the tree resolved to more than one transform unit.
19802#[allow(clippy::too_many_arguments)]
19803fn read_block_tx_size(
19804 dec: &mut SymbolDecoder,
19805 cdfs: &mut Cdfs,
19806 n: &mut Neighbours,
19807 at_mi: (usize, usize),
19808 side: usize,
19809 (mi_cols, mi_rows): (usize, usize),
19810 is_inter: bool,
19811 skip: bool, fctx: &crate::decode::FrameCtx,
19812) -> Result<(usize, Option<Vec<(usize, usize, usize, usize)>>)> {
19813 // lane-lossless: TX_4X4 over the whole block, and NO var-tx tree -- libaom
19814 // `read_block_tx_size` (`decodeframe.c`) sends a lossless block down the
19815 // `read_tx_size` arm, which returns TX_4X4 before it reads anything.
19816 if lossless(fctx) {
19817 let mut leaves = Vec::new();
19818 for row in 0..side / MI {
19819 for col in 0..side / MI {
19820 leaves.push((row, col, 4, 4));
19821 }
19822 }
19823 return Ok((4, Some(leaves)));
19824 }
19825 if !fctx.tx_select_inter.with(std::cell::Cell::get) {
19826 // lane-sb128c r1: `max_txsize_rect_lookup[BLOCK_128X128]` is TX_64X64,
19827 // so a 128x128 inter block is FOUR luma units even with `tx_mode ==
19828 // TX_MODE_LARGEST` -- the same leaf shape the var-tx tree hands back.
19829 // lane-sb128c r3: intra too -- an INTRA 128x128 block under
19830 // `TX_MODE_LARGEST` also resolves to TX_64X64, i.e. four luma units.
19831 if side > 64 {
19832 let step = 64 / MI;
19833 let mut leaves = Vec::new();
19834 for row in (0..side / MI).step_by(step) {
19835 for col in (0..side / MI).step_by(step) {
19836 leaves.push((row, col, 64, 64));
19837 }
19838 }
19839 return Ok((64, Some(leaves)));
19840 }
19841 return Ok((side, None));
19842 }
19843 let side_mi = side / MI;
19844 if is_inter && !skip {
19845 let max_tx = side.min(64);
19846 let max_w_mi = side_mi.min(mi_cols.saturating_sub(at_mi.1));
19847 let max_h_mi = side_mi.min(mi_rows.saturating_sub(at_mi.0));
19848 let mut leaves = Vec::new();
19849 let step = max_tx / MI;
19850 for row in (0..side_mi).step_by(step) {
19851 for col in (0..side_mi).step_by(step) {
19852 read_var_tx_size(
19853 dec,
19854 cdfs,
19855 n,
19856 at_mi,
19857 side,
19858 (max_w_mi, max_h_mi),
19859 (max_tx, max_tx),
19860 0,
19861 row,
19862 col,
19863 &mut leaves,
19864 );
19865 }
19866 }
19867 let single = leaves.len() == 1 && leaves[0].2 == side && leaves[0].3 == side;
19868 // lane-sb128c r6: below the 128 root the ceiling is main's TX_32X32
19869 // ([`inter_txbset_for`] has no 64-point *inter* table set); a 128x128
19870 // block's own var-tx tree legitimately bottoms out at TX_64X64 leaves,
19871 // which the mu-chunk reader above codes as their 32x32 coded corner.
19872 let leaf_ceiling = if side > 64 { 64 } else { 32 };
19873 if !single && leaves.iter().any(|leaf| leaf.2.max(leaf.3) > leaf_ceiling) {
19874 // Only a block wider than a superblock's own 64x64 max transform
19875 // reaches here; this crate has no 64-point *inter* coefficient
19876 // table set ([`inter_txbset_for`] stops at 32).
19877 return Err(unsupported(
19878 "an inter var-tx tree with a leaf transform larger than 32x32",
19879 ));
19880 }
19881 let resolved = leaves.last().map_or(side, |l| l.2);
19882 return Ok((resolved, (!single).then_some(leaves)));
19883 }
19884 let tx = if is_inter {
19885 side.min(64)
19886 } else {
19887 read_tx_size(
19888 dec,
19889 cdfs,
19890 n,
19891 at_mi,
19892 side,
19893 )
19894 };
19895 set_txfm_ctxs(n, at_mi, tx, side_mi, side_mi, skip && is_inter);
19896 if !is_inter && tx != side {
19897 // lane-intrainter r1: an intra block inside an inter frame whose
19898 // `tx_depth` split its luma transform codes exactly the key-frame
19899 // split path's transform units (`decode_block`'s multi-TU loop),
19900 // raster order over the block. Handed back in the same leaf shape the
19901 // inter var-tx tree uses, so the caller's per-TU luma loop, the
19902 // `record_split_luma` neighbour write-back and the per-TU deblock
19903 // edges are the ones it already runs for a var-tx inter block. A
19904 // caller that has no per-TU intra loop (the 8x8 leaf) refuses on
19905 // seeing `Some` here.
19906 let step = tx / MI;
19907 let mut leaves = Vec::new();
19908 for row in (0..side_mi).step_by(step) {
19909 for col in (0..side_mi).step_by(step) {
19910 leaves.push((row, col, tx, tx));
19911 }
19912 }
19913 hit_do! {
19914 INTRA_IN_INTER_SPLIT_TX_HITS.with(|c| {
19915 let mut h = c.get();
19916 h[(side.trailing_zeros() as usize).saturating_sub(3).min(3)] += 1;
19917 c.set(h);
19918 });
19919 }
19920 return Ok((tx, Some(leaves)));
19921 }
19922 Ok((tx, None))
19923}
19924
19925/// lane-inter4 r2: the shapes whose *rectangular inter* residual this
19926/// decoder codes -- a 2:1 strip whose own max rect transform
19927/// (`max_txsize_rect_lookup[BLOCK_32X16] == TX_32X16`) has both a
19928/// coefficient table set ([`TxbSet::LumaRect32x16Inter`], 512-coefficient
19929/// `eob_pt`) and a `tx_type` alphabet here. 64x32/64x16 strips would need a
19930/// 64-point rect transform, and 16x8/8x16 needs
19931/// `default_inter_ext_tx_cdf[2][TX_8X8]` (the 12-symbol
19932/// `DTT9_IDTX_1DDCT` row at `tx_size_sqr == TX_8X8`, only reachable through a
19933/// rect transform), neither of which exists yet -- both stay refused by name.
19934pub(crate) fn rect_inter_residual_supported(w: usize, h: usize) -> bool {
19935 matches!(
19936 (w, h),
19937 // 2:1 strips whose transform is coded in full (lane-inter4).
19938 (32, 16) | (16, 32) | (16, 8) | (8, 16)
19939 // lane-inter16ab r2: the 16x16-level 1:4 strips. TX_16X4/TX_4X16
19940 // codes all 64 of its positions, and its chroma pair is an 8x4 /
19941 // 4x8 unit (`ss_size_lookup[BLOCK_16X4]` = BLOCK_8X4).
19942 | (16, 4) | (4, 16)
19943 // lane-r14 r2: strips with a 64-px axis. `av1_get_max_eob` codes
19944 // only the low 32 coefficients of a 64-length axis, so these read
19945 // exactly the truncated corner the INTRA superblock-strip path
19946 // already reads (`read_intra_mode_rect`), through
19947 // `av1_get_adjusted_tx_size`'s CDF set. Their `tx_size_sqr_up` is
19948 // `TX_64X64`, so `av1_get_ext_tx_set_type` is `DCT_ONLY` and no
19949 // `tx_type` symbol is coded at all.
19950 | (64, 32) | (32, 64) | (64, 16) | (16, 64)
19951 // lane-inter16ab r4: `sub_tx_size_map[TX_16X4] == TX_8X4`, so a
19952 // split-transform 16x4/4x16 strip has RECTANGULAR 8x4/4x8 leaves.
19953 // Only reachable as a var-tx LEAF -- an 8x4/4x8 inter BLOCK is
19954 // refused earlier ("an inter partition below 8x8").
19955 | (8, 4) | (4, 8)
19956 // lane-sb128c r7: the 128 root's HORZ/VERT halves. These are NOT
19957 // one rectangular transform -- `max_txsize_rect_lookup
19958 // [BLOCK_128X64]` is TX_64X64, so the block tiles into two square
19959 // TX_64X64 units read through the mu-chunk loop, same as the
19960 // 128x128 NONE block's four.
19961 | (128, 64) | (64, 128)
19962 // lane-rectres r1: the 32x32-level 1:4 strips -- THE shape both
19963 // 10-bit film cuts and every measured 1080p offset stop on
19964 // (measured: 6/6 probes refuse at 32x8 or 8x32, nothing else).
19965 // `max_txsize_rect_lookup[BLOCK_32X8] == TX_32X8` codes all 256
19966 // positions, and its chroma pair is a 16x4 / 4x16 unit
19967 // (`ss_size_lookup[BLOCK_32X8]` = BLOCK_16X4).
19968 | (32, 8) | (8, 32)
19969 )
19970}
19971
19972// lane-t900 r20: the `(side, write_w, write_h)` triples the inter block path
19973// actually PRESENTS, as a thread-local bitmask -- the measured domain behind
19974// the "rectangular ... has no ... here" refusals. `side` is the square context
19975// a block reads its CDFs at and `write_w`/`write_h` its true footprint;
19976// `inter_piece!` derives `reject_residual` from exactly that inequality, so
19977// these triples are what decides whether those refusals can fire at all. Bit
19978// 31 is "a triple this table does not list", which is what makes the gate a
19979// census rather than a restatement of its own table.
19980pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [
19981 (16, 16, 16),
19982 (32, 32, 32),
19983 (32, 16, 32),
19984 (32, 32, 16),
19985 (16, 8, 16),
19986 (16, 16, 8),
19987 (32, 8, 32),
19988 (64, 64, 64),
19989 (32, 32, 8),
19990 (64, 16, 64),
19991 (128, 128, 128),
19992 (64, 32, 64),
19993 (64, 64, 32),
19994 (16, 4, 16),
19995 (64, 64, 16),
19996 (16, 16, 4),
19997 (128, 128, 64),
19998 (128, 64, 128),
19999];
20000
20001/// Bit 31 of [`inter_block_shape_mask`]: a `(side, write_w, write_h)` triple
20002/// outside [`INTER_BLOCK_SHAPES`].
20003pub const INTER_BLOCK_SHAPE_UNLISTED: u32 = 1 << 31;
20004
20005thread_local! {
20006 static INTER_BLOCK_SHAPE_MASK: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
20007}
20008
20009/// Which of [`INTER_BLOCK_SHAPES`] this THREAD has decoded (thread-local, so a
20010/// gate reading it sees only the streams it decoded itself).
20011pub fn inter_block_shape_mask() -> u32 {
20012 INTER_BLOCK_SHAPE_MASK.with(std::cell::Cell::get)
20013}
20014
20015/// Records one block's shape. The table is ordered by measured frequency over
20016/// the three witnesses the census gate decodes, so the common square shapes
20017/// leave the scan on their first comparison.
20018fn census_inter_block_shape(side: usize, w: usize, h: usize) {
20019 let bit = match INTER_BLOCK_SHAPES.iter().position(|&s| s == (side, w, h)) {
20020 Some(i) => 1u32 << i,
20021 None => INTER_BLOCK_SHAPE_UNLISTED,
20022 };
20023 let seen = inter_block_shape_mask();
20024 if seen & bit == 0 {
20025 INTER_BLOCK_SHAPE_MASK.with(|c| c.set(seen | bit));
20026 }
20027}
20028
20029/// The luma coefficient/`tx_type` table set of a whole-block rectangular
20030/// INTER transform unit (lane-inter4 r3). `av1_get_ext_tx_set_type` splits
20031/// the two shapes: a 32x16/16x32 unit has `tx_size_sqr_up == TX_32X32`, so
20032/// it reads the 2-symbol `EXT_TX_SET_DCT_IDTX` set regardless of
20033/// `reduced_tx_set`; a 16x8/8x16 unit has `tx_size_sqr_up == TX_16X16` and
20034/// `tx_size_sqr == TX_8X8`, so it reads `EXT_TX_SET_DCT_IDTX` when reduced
20035/// and the 16-symbol `EXT_TX_SET_ALL16` otherwise -- both at the *8x8* CDF
20036/// row (`txsize_sqr_map`), never the 16x16 one.
20037fn rect_inter_luma_set(w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> Result<TxbSet> {
20038 Ok(match (w, h) {
20039 (32, 16) | (16, 32) => TxbSet::LumaRect32x16Inter,
20040 // lane-inter16ab r4: the 8x4/4x8 split leaf of a 16x4/4x16 strip.
20041 // `av1_get_ext_tx_set_type` (blockd.h:1097) at `tx_size_sqr_up ==
20042 // TX_8X8`, `tx_size_sqr == TX_4X4`, inter: DCT_IDTX when reduced,
20043 // ALL16 otherwise -- both at the TX_4X4 row.
20044 (8, 4) | (4, 8) => {
20045 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
20046 TxbSet::LumaRect8x4Inter
20047 } else {
20048 TxbSet::LumaRect8x4InterSet1
20049 }
20050 }
20051 (16, 4) | (4, 16) => {
20052 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
20053 TxbSet::LumaRect16x4Inter
20054 } else {
20055 TxbSet::LumaRect16x4Inter1
20056 }
20057 }
20058 (16, 8) | (8, 16) => {
20059 if fctx.reduced_tx_set_inter.with(std::cell::Cell::get) {
20060 TxbSet::LumaRect16x8Inter
20061 } else {
20062 TxbSet::LumaRect16x8InterSet1
20063 }
20064 }
20065 // lane-r14 r2: `av1_get_adjusted_tx_size` maps TX_64X32/TX_32X64 to
20066 // TX_32X32 and TX_64X16/TX_16X64 to TX_32X16/TX_16X32, and
20067 // `get_txsize_entropy_ctx`/`txsize_log2_minus4` agree with the
20068 // adjusted size, so the existing sets are bit-exact. Neither carries a
20069 // `tx_type` table (DCT_ONLY above), so the intra/inter split is moot.
20070 // lane-rectres r1: `tx_size_sqr_up[TX_32X8] == TX_32X32`, so
20071 // `av1_get_ext_tx_set_type` is `EXT_TX_SET_DCT_IDTX` for inter with or
20072 // without `reduced_tx_set` -- one set, no `REDUCED_TX_SET_INTER`
20073 // branch, read at the `txsize_sqr_map[TX_32X8] == TX_8X8` row.
20074 (32, 8) | (8, 32) => TxbSet::LumaRect32x8Inter,
20075 (64, 32) | (32, 64) => TxbSet::Luma64,
20076 (64, 16) | (16, 64) => TxbSet::LumaRect32x16,
20077 _ => {
20078 return Err(unsupported(
20079 "a rectangular inter luma transform unit whose shape has no coefficient table set here",
20080 ));
20081 }
20082 })
20083}
20084
20085/// The chroma table set of the same block's single rectangular chroma unit
20086/// (`av1_get_max_uv_txsize`): 16x8/8x16 under a 32x16/16x32 strip, 8x4/4x8
20087/// under a 16x8/8x16 one. Neither codes a `tx_type` symbol -- both inherit
20088/// the luma unit's.
20089fn rect_inter_chroma_set(w: usize, h: usize) -> Result<TxbSet> {
20090 Ok(match (w, h) {
20091 (16, 8) | (8, 16) => TxbSet::ChromaRect16x8,
20092 (8, 4) | (4, 8) => TxbSet::ChromaRect8x4,
20093 // lane-r14 r2: chroma of a 64-axis strip -- 32x16/16x32 under a
20094 // 64x32/32x64 one, 32x8/8x32 under a 64x16/16x64 one. Neither chroma
20095 // unit has a 64-px axis, so both are coded in full; `Chroma16` is the
20096 // exact set for TX_32X8/TX_8X32 (`get_txsize_entropy_ctx` = TX_16X16,
20097 // `txsize_log2_minus4` = 4), same as the intra strip path uses.
20098 (32, 16) | (16, 32) => TxbSet::ChromaRect32x16,
20099 (32, 8) | (8, 32) => TxbSet::Chroma16,
20100 // lane-rectres r1: chroma of a 32x8/8x32 strip. `Chroma8` is the exact
20101 // set for TX_16X4/TX_4X16 (`get_txsize_entropy_ctx` = TX_8X8,
20102 // `txsize_log2_minus4` = 2, 64-coefficient `eob_pt`).
20103 (16, 4) | (4, 16) => TxbSet::Chroma8,
20104 _ => {
20105 return Err(unsupported(
20106 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
20107 ));
20108 }
20109 })
20110}
20111
20112/// libaom `size_group_lookup[bsize]` for the block shapes this decoder's
20113/// inter path reaches, from the block's TRUE footprint rather than the
20114/// square `side` corner-cut: 8x8/8x16/16x8 -> 1, 16x16/16x32/32x16 -> 2,
20115/// everything 32 and above -> 3.
20116fn size_group_wh(w: usize, h: usize) -> usize {
20117 // lane-inter4 r4: `size_group_lookup[BLOCK_SIZES_ALL]` (libaom
20118 // `common_data.h:60`) is 0 for every block with a 4-px side
20119 // (4x4/4x8/8x4/4x16/16x4), 1 for min side 8, 2 for 16, 3 above -- the old
20120 // `0..=8 => 1` row gave a sub-8 leaf group 1 where libaom says 0.
20121 match w.min(h) {
20122 0..=4 => 0,
20123 8 => 1,
20124 16 => 2,
20125 _ => 3,
20126 }
20127}
20128
20129#[test]
20130fn size_group_wh_matches_libaom_size_group_lookup() {
20131 // `BLOCK_SIZES_ALL` in libaom's own order, with `size_group_lookup`'s
20132 // transcribed values (common_data.h:60-62).
20133 const TABLE: [((usize, usize), usize); 22] = [
20134 ((4, 4), 0), ((4, 8), 0), ((8, 4), 0), ((8, 8), 1), ((8, 16), 1), ((16, 8), 1),
20135 ((16, 16), 2), ((16, 32), 2), ((32, 16), 2), ((32, 32), 3), ((32, 64), 3),
20136 ((64, 32), 3), ((64, 64), 3), ((64, 128), 3), ((128, 64), 3), ((128, 128), 3),
20137 ((4, 16), 0), ((16, 4), 0), ((8, 32), 1), ((32, 8), 1), ((16, 64), 2), ((64, 16), 2),
20138 ];
20139 for ((w, h), want) in TABLE {
20140 assert_eq!(size_group_wh(w, h), want, "size_group_wh({w}, {h})");
20141 }
20142}
20143
20144/// The default (2D) coefficient scan of a rectangular transform.
20145fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> {
20146 Ok(match (w, h) {
20147 (32, 16) => &SCAN_32X16,
20148 (16, 32) => &SCAN_16X32,
20149 (16, 8) => &SCAN_16X8,
20150 (8, 16) => &SCAN_8X16,
20151 (16, 4) => &SCAN_16X4,
20152 (4, 16) => &SCAN_4X16,
20153 (8, 4) => &SCAN_8X4,
20154 (4, 8) => &SCAN_4X8,
20155 (32, 8) => &SCAN_32X8,
20156 (8, 32) => &SCAN_8X32,
20157 _ => {
20158 return Err(unsupported(
20159 "a rectangular transform unit whose shape has no coefficient scan table here",
20160 ));
20161 }
20162 })
20163}
20164
20165/// lane-t900 r20, refusal D -- the three "a rectangular inter luma/chroma
20166/// transform unit whose shape has no coefficient table set here" / "a
20167/// rectangular transform unit whose shape has no coefficient scan table here"
20168/// arms, enumerated against the MEASURED domain of the inter block path
20169/// ([`INTER_BLOCK_SHAPES`], filled from three real streams by the gate
20170/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`).
20171///
20172/// What each helper is actually handed:
20173///
20174/// * [`rect_inter_luma_set`] -- the block's own footprint (call sites at the
20175/// whole-block residual), and a var-tx LEAF shape. `sub_tx_size_map` is
20176/// square for every rect transform except TX_16X4/TX_4X16, whose leaves are
20177/// TX_8X4/TX_4X8, so the leaf domain adds exactly 8x4 and 4x8.
20178/// * [`rect_inter_chroma_set`] -- `(write_w / 2, write_h / 2)` for a 4:2:0
20179/// block, except a 16x4/4x16 strip, whose chroma is the PAIR's 8x4 / 4x8.
20180/// * [`rect_scan`] -- the `min(w, 32) x min(h, 32)` coded corner of a rect
20181/// unit, and only when that corner is not 32x32 (a square corner goes
20182/// through the square reader with `rect_shape = Some((w, h))`).
20183///
20184/// The 128-px halves take neither: `max_txsize_rect_lookup[BLOCK_128X64]` is
20185/// TX_64X64, so they tile into SQUARE 64x64 luma units through the mu-chunk
20186/// loop, which is why they are skipped below.
20187#[test]
20188fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() {
20189 let fctx = &crate::decode::FrameCtx::new();
20190 let corner_scan = |w: usize, h: usize| {
20191 let (cw, ch) = (w.min(32), h.min(32));
20192 if (cw, ch) == (32, 32) {
20193 return; // the square coefficient reader, not `rect_scan`
20194 }
20195 assert!(
20196 rect_scan(cw, ch).is_ok(),
20197 "a {w}x{h} rect transform codes its {cw}x{ch} corner, which has no scan table"
20198 );
20199 };
20200 let mut checked = 0;
20201 for &(side, w, h) in &INTER_BLOCK_SHAPES {
20202 if (w, h) == (side, side) || w.max(h) > 64 {
20203 continue;
20204 }
20205 assert!(
20206 rect_inter_luma_set(w, h, fctx).is_ok(),
20207 "the inter path decodes {w}x{h} blocks but has no luma coefficient table set for one"
20208 );
20209 corner_scan(w, h);
20210 // 4:2:0 chroma: the pair's 8x4 / 4x8 for a 1:4 strip, the halved
20211 // footprint for every other shape.
20212 let (cw, ch) = match (w, h) {
20213 (16, 4) => (8, 4),
20214 (4, 16) => (4, 8),
20215 _ => (w / 2, h / 2),
20216 };
20217 assert!(
20218 rect_inter_chroma_set(cw, ch).is_ok(),
20219 "a {w}x{h} block's {cw}x{ch} chroma unit has no coefficient table set"
20220 );
20221 corner_scan(cw, ch);
20222 checked += 1;
20223 }
20224 assert_eq!(
20225 checked, 12,
20226 "the block-shape census changed: {checked} rect shapes reach the rect transform \
20227 tables, not the 12 this claim was measured over"
20228 );
20229 // `sub_tx_size_map[TX_16X4] == TX_8X4` -- the only RECTANGULAR var-tx leaf
20230 // shapes, which reach `rect_inter_luma_set` as `(tw, th)`.
20231 for (w, h) in [(8usize, 4usize), (4, 8)] {
20232 assert!(
20233 rect_inter_luma_set(w, h, fctx).is_ok(),
20234 "the {w}x{h} split leaf of a 16x4/4x16 strip has no luma coefficient table set"
20235 );
20236 corner_scan(w, h);
20237 }
20238}
20239
20240/// [`read_block_tx_size`] for a rectangular inter block (lane-inter4 r2):
20241/// spec 5.11.17 / libaom `read_tx_size_vartx` starting from the block's own
20242/// `max_txsize_rect_lookup` entry, which for a 2:1 strip IS rectangular. The
20243/// depth-0 `txfm_partition` symbol reads its context off the rect transform's
20244/// own width/height; a `0` leaves one whole-block rect transform unit
20245/// (`None`), and a `1` splits it into `sub_tx_size_map`'s two SQUARE
20246/// sub-transforms (`sub_tx_size_map[TX_32X16] == TX_16X16`), from which the
20247/// ordinary square [`read_var_tx_size`] recursion continues at depth 1 -- so
20248/// every leaf of a split rect block is square and the existing square leaf
20249/// loop reconstructs it unchanged.
20250#[allow(clippy::too_many_arguments)]
20251fn read_block_tx_size_rect(
20252 dec: &mut SymbolDecoder,
20253 cdfs: &mut Cdfs,
20254 n: &mut Neighbours,
20255 at_mi: (usize, usize),
20256 (bw, bh): (usize, usize),
20257 (mi_cols, mi_rows): (usize, usize),
20258 skip: bool, fctx: &crate::decode::FrameCtx,
20259) -> Result<Option<Vec<(usize, usize, usize, usize)>>> {
20260 if lossless(fctx) {
20261 let mut leaves = Vec::new();
20262 for row in 0..bh / MI {
20263 for col in 0..bw / MI {
20264 leaves.push((row, col, 4, 4));
20265 }
20266 }
20267 return Ok(Some(leaves));
20268 }
20269 if skip {
20270 // `set_txfm_ctxs(.., skip && is_inter)`: a skipped inter block records
20271 // its own BLOCK size -- width above, height left -- not a transform.
20272 txfm_partition_update_rect(n, at_mi, (bw, bh), (bw, bh));
20273 return Ok(None);
20274 }
20275 // `max_txsize_rect_lookup` is the block's own size, capped at 64 -- and
20276 // `rect_inter_residual_supported` has already excluded everything above 32.
20277 // lane-sb128c r7: except at the 128 root. `max_txsize_rect_lookup
20278 // [BLOCK_128X64] == TX_64X64` (libaom `common_data.h`), so a 128x64 block
20279 // is TWO square top-level transform units side by side and a 64x128 one is
20280 // two stacked -- exactly what libaom `read_block_tx_size`
20281 // (decodeframe.c:1140) codes with its `idy/idx` loop over
20282 // `tx_size_high_unit/tx_size_wide_unit[max_tx_size]`. Each unit reads its
20283 // own `txfm_partition` symbol at depth 0.
20284 if bw.max(bh) > 64 {
20285 let tx = 64usize;
20286 let (max_w_mi, max_h_mi) = (
20287 (bw / MI).min(mi_cols.saturating_sub(at_mi.1)),
20288 (bh / MI).min(mi_rows.saturating_sub(at_mi.0)),
20289 );
20290 let mut leaves = Vec::new();
20291 if !fctx.tx_select_frame.with(std::cell::Cell::get) {
20292 for row in (0..bh / MI).step_by(tx / MI) {
20293 for col in (0..bw / MI).step_by(tx / MI) {
20294 leaves.push((row, col, tx, tx));
20295 }
20296 }
20297 for &(row, col, tw, th) in &leaves {
20298 txfm_partition_update_rect(n, (at_mi.0 + row, at_mi.1 + col), (tw, th), (tw, th));
20299 }
20300 return Ok(Some(leaves));
20301 }
20302 for row in (0..bh / MI).step_by(tx / MI) {
20303 for col in (0..bw / MI).step_by(tx / MI) {
20304 read_var_tx_size(
20305 dec,
20306 cdfs,
20307 n,
20308 at_mi,
20309 bw.max(bh),
20310 (max_w_mi, max_h_mi),
20311 (tx, tx),
20312 0,
20313 row,
20314 col,
20315 &mut leaves,
20316 );
20317 }
20318 }
20319 if leaves.iter().any(|l| l.2.max(l.3) > 64) {
20320 return Err(unsupported(
20321 "an inter var-tx tree with a leaf transform larger than 64x64",
20322 ));
20323 }
20324 return Ok(Some(leaves));
20325 }
20326 let (tx_w, tx_h) = (bw, bh);
20327 if !fctx.tx_select_frame.with(std::cell::Cell::get) {
20328 // `TX_MODE_LARGEST`: no symbol at all, the whole block is one
20329 // transform, and `set_txfm_ctxs` records exactly what
20330 // `txfm_partition_update` would for that same unit.
20331 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
20332 hit!(RECT_INTER_TU_HITS);
20333 return Ok(None);
20334 }
20335 let ctx = txfm_partition_ctx_rect(
20336 n.above_txfm[at_mi.1],
20337 n.left_txfm[at_mi.0],
20338 bw.max(bh),
20339 tx_w,
20340 tx_h,
20341 );
20342 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
20343 hit!(TXFM_SPLIT_READS);
20344 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
20345 let (rng, _) = dec.debug_state();
20346 eprintln!(
20347 "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
20348 at_mi.0,
20349 at_mi.1,
20350 u8::from(split)
20351 );
20352 }
20353 if !split {
20354 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
20355 hit!(RECT_INTER_TU_HITS);
20356 return Ok(None);
20357 }
20358 hit!(TXFM_SPLIT_HITS);
20359 hit!(RECT_INTER_TXSPLIT_HITS);
20360 // lane-r14 r3: `sub_tx_size_map` (libaom `common_data.c`) stays
20361 // RECTANGULAR under a 1:4 strip -- `[TX_64X16] == TX_32X16`,
20362 // `[TX_16X64] == TX_16X32` -- so the recursion below is the general
20363 // rect one and its leaves carry their own width and height.
20364 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
20365 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(at_mi.1));
20366 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(at_mi.0));
20367 let mut leaves = Vec::new();
20368 for row in (0..bh / MI).step_by(sub_h / MI) {
20369 for col in (0..bw / MI).step_by(sub_w / MI) {
20370 read_var_tx_size(
20371 dec,
20372 cdfs,
20373 n,
20374 at_mi,
20375 bw.max(bh),
20376 (max_w_mi, max_h_mi),
20377 (sub_w, sub_h),
20378 1,
20379 row,
20380 col,
20381 &mut leaves,
20382 );
20383 }
20384 }
20385 Ok(Some(leaves))
20386}
20387
20388/// [`read_inter_plane`] for a rectangular transform unit (lane-inter4 r2):
20389/// the coefficients are read with the rect coefficient machinery
20390/// ([`read_coeffs_rect`], whose `TxClass` handling covers the 1D `V_*`/`H_*`
20391/// types), inverted with the rect inverse transform
20392/// ([`dequant_and_inverse_typed_wh`], which carries the 2:1 `sqrt2` scale),
20393/// and added onto the top-left `w x h` of the block's own square-strided
20394/// motion-compensated prediction buffer. Returns the *rect* coefficient grid
20395/// and the coded `tx_type`.
20396///
20397/// `txb_skip_ctx` is 0 for luma: this unit covers the whole block, i.e.
20398/// `get_txb_ctx`'s `plane_bsize == txsize_to_bsize[tx_size]` branch.
20399#[allow(clippy::too_many_arguments)]
20400fn read_inter_plane_rect(
20401 dec: &mut SymbolDecoder,
20402 cdfs: &mut Cdfs,
20403 set: TxbSet,
20404 (w, h): (usize, usize),
20405 stride: usize,
20406 plane_idx: usize,
20407 around: (bool, bool, i32),
20408 tx_mode: usize,
20409 // lane-wave1 step (i): unread -- this reader records its write
20410 // ([`push_intra`]/[`push_mc`]) instead of performing it; the borrow
20411 // stays in the signature so every call site still proves the plane is
20412 // exclusively held while its coefficients are parsed.
20413 _plane: &mut PlaneBuf<'static>,
20414 x: usize,
20415 y: usize,
20416 prediction: Pred<'_>,
20417 inherited_luma_tx_type: Option<TxType>,
20418 luma_skip_ctx: Option<usize>, fctx: &crate::decode::FrameCtx,
20419) -> Result<(Grid, TxType)> {
20420 // lane-av1mono: as [`read_plane`] -- a monochrome frame codes no chroma
20421 // coefficients (`plane < av1_num_planes == 1`).
20422 if plane_idx > 0 && mono(fctx) {
20423 return Ok((Grid::Zero(w * h), TxType::DctDct));
20424 }
20425 let skip_ctx = if plane_idx == 0 {
20426 // `get_txb_ctx_general`: 0 only when this unit IS the whole plane
20427 // block; a var-tx leaf passes its own neighbour-table context.
20428 luma_skip_ctx.unwrap_or(0)
20429 } else {
20430 usize::from(around.0) + usize::from(around.1)
20431 };
20432 let mut coding = cdfs.txb(set, tx_mode);
20433 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
20434 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
20435 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
20436 // plane of a lossless block (the residual then goes through the WHT, so
20437 // the type only picks the scan, which is the default one).
20438 if lossless(fctx) {
20439 coding.tx_type = None;
20440 }
20441 // `av1_get_ext_tx_set_type`'s DCT-only clamp is on `tx_size_sqr_up`, i.e.
20442 // the *longer* side of this rect transform.
20443 let default_tx_type = match inherited_luma_tx_type {
20444 Some(t) => reduce_inherited_chroma_tx_type(t, w, h, fctx),
20445 None => TxType::DctDct,
20446 };
20447 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
20448 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
20449 let default_tx_type = if lossless(fctx) { TxType::DctDct } else { default_tx_type };
20450 // lane-r14 r2: a 64-length axis codes only its low 32 coefficients
20451 // (`av1_get_max_eob`), so the coded unit is the `min(w,32) x min(h,32)`
20452 // corner, zero-extended into the true `w x h` grid before the inverse
20453 // transform -- exactly what the intra superblock-strip path does. A
20454 // corner that comes out square (32x32, under a 64x32/32x64 strip) reads
20455 // through the SQUARE coefficient reader with `rect_shape = Some((w, h))`,
20456 // because `av1_nz_map_ctx_offset` is indexed by the real, un-adjusted
20457 // rectangular shape (lane-sbpart r8).
20458 let (cw, ch) = (w.min(32), h.min(32));
20459 if plane_idx == 0 && w.max(h) == 64 {
20460 hit!(RECT64_INTER_TU_HITS);
20461 }
20462 if plane_idx == 0 && (w, h) == (32, 8) || plane_idx == 0 && (w, h) == (8, 32) {
20463 hit_do! {
20464 RECT32X8_INTER_TU_HITS.with(|c| {
20465 let mut v = c.get();
20466 v[usize::from(w == 8)] += 1;
20467 c.set(v);
20468 });
20469 }
20470 }
20471 let (corner, tx_type) = if (cw, ch) == (32, 32) {
20472 let scan32 = default_scan(TX32);
20473 read_coeffs(
20474 dec,
20475 &mut coding,
20476 &scan32,
20477 skip_ctx,
20478 dc_sign_ctx(around.2),
20479 default_tx_type,
20480 Some((w, h)),
20481 )?
20482 } else {
20483 read_coeffs_rect(
20484 dec,
20485 &mut coding,
20486 rect_scan(cw, ch)?,
20487 cw,
20488 ch,
20489 skip_ctx,
20490 dc_sign_ctx(around.2),
20491 default_tx_type,
20492 )?
20493 };
20494 let grid = extend_corner(corner, cw, ch, w, h);
20495 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
20496 if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
20497 eprintln!("OUR_TXTYPE plane={plane_idx} x={x} y={y} w={w} h={h} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}");
20498 }
20499 // `reconstruct_mc_rect` reads both buffers at the square prediction
20500 // stride, so the dense `w x h` residual is re-laid at that stride
20501 // (`TxParams::stride`) after the inverse transform.
20502 let tx = TxParams {
20503 w, h, bit_depth: bit_depth(fctx), q_idx: block_q_idx(fctx), dc_delta, ac_delta, tx_type,
20504 stride, lossless: lossless(fctx),
20505 };
20506 push_mc_rect_tx(plane_idx, x, y, stride, w, h, prediction, tx, &grid, fctx);
20507 Ok((grid, tx_type))
20508}
20509
20510/// The coded `cw x ch` corner of a transform zero-extended into its true
20511/// `w x h` grid (a 64-length axis codes only its low 32 coefficients). A
20512/// corner that coded nothing stays the shared zero grid -- no allocation
20513/// (lane-coefgrid).
20514fn extend_corner(corner: Grid, cw: usize, ch: usize, w: usize, h: usize) -> Grid {
20515 if (cw, ch) == (w, h) {
20516 return corner;
20517 }
20518 if let Grid::Zero(_) = corner {
20519 return Grid::Zero(w * h);
20520 }
20521 let mut full = vec![0i32; w * h];
20522 for row in 0..ch {
20523 full[row * w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
20524 }
20525 Grid::Own(full)
20526}
20527
20528/// [`embed_rect_grid`] that keeps the shared zero marker zero: an all-zero
20529/// transform unit's grid IS `Grid::Zero` (whose deref is the shared
20530/// `ZERO_RESIDUAL`), so re-laying it would read a zero-length slice.
20531fn embed_grid_stride(grid: &Grid, w: usize, h: usize, stride: usize) -> Grid {
20532 if is_zero_grid(grid) {
20533 return Grid::Zero(stride * stride);
20534 }
20535 Grid::Own(embed_rect_grid(grid, w, h, stride))
20536}
20537
20538/// A rect coefficient grid re-laid into the square `stride x stride` grid the
20539/// neighbour/deblock stamps downstream of the residual expect.
20540fn embed_rect_grid(grid: &[i32], w: usize, h: usize, stride: usize) -> Vec<i32> {
20541 let mut full = vec![0i32; stride * stride];
20542 for row in 0..h {
20543 full[row * stride..][..w].copy_from_slice(&grid[row * w..][..w]);
20544 }
20545 full
20546}
20547
20548/// One 8x8 inter leaf's luma residual (lane-txselect): either the whole-8x8
20549/// transform, or -- when [`read_block_tx_size`]'s var-tx tree took the single
20550/// split a `BLOCK_8X8` can take (`split`) -- the four 4x4 transform units in
20551/// raster order, each reading its own coefficient context off the units
20552/// already decoded before it. Returns the block's luma grid (all-zero in the
20553/// split case, whose reconstruction has already happened unit by unit) and
20554/// the `tx_type` chroma inherits: `av1_get_tx_type`'s colocated luma lookup,
20555/// which for a split block lands on the top-left unit.
20556#[allow(clippy::too_many_arguments)]
20557fn read_inter_luma8(
20558 dec: &mut SymbolDecoder,
20559 cdfs: &mut Cdfs,
20560 neighbours: &mut Neighbours,
20561 leaf_mi: (usize, usize),
20562 y: &mut PlaneBuf<'static>,
20563 px: usize,
20564 py: usize,
20565 pred_y: Pred<'_>,
20566 mode_for_tx: usize,
20567 base_q_idx: u8,
20568 scan8: &[u16],
20569 scan4: &[u16],
20570 reduced_tx_set: bool,
20571 split: bool, fctx: &crate::decode::FrameCtx,
20572) -> Result<(Grid, TxType)> {
20573 // lane-lossless: an 8x8 inter block is FOUR 4x4 units (libaom
20574 // `read_block_tx_size`'s lossless TX_4X4), tree or no tree.
20575 let split = split || lossless(fctx);
20576 if !split {
20577 return read_inter_plane(
20578 dec,
20579 cdfs,
20580 if reduced_tx_set {
20581 TxbSet::Luma8Inter
20582 } else {
20583 TxbSet::Luma8InterSet1
20584 },
20585 scan8,
20586 0,
20587 neighbours.around_mi(leaf_mi, 8)[0],
20588 mode_for_tx,
20589 y,
20590 px,
20591 py,
20592 8,
20593 base_q_idx,
20594 pred_y,
20595 None,
20596 None, fctx,
20597 );
20598 }
20599 let mut first = TxType::DctDct;
20600 for tu_row in 0..2 {
20601 for tu_col in 0..2 {
20602 let tu_mi = (leaf_mi.0 + tu_row, leaf_mi.1 + tu_col);
20603 let tu_pred = pred_y.view(8).offset(tu_row * 4 * 8 + tu_col * 4);
20604 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
20605 let (tu_grid, tu_tx_type) = read_inter_plane(
20606 dec,
20607 cdfs,
20608 if reduced_tx_set {
20609 TxbSet::Luma4Inter
20610 } else {
20611 TxbSet::Luma4InterSet1
20612 },
20613 scan4,
20614 0,
20615 neighbours.around_mi(tu_mi, 4)[0],
20616 mode_for_tx,
20617 y,
20618 px + tu_col * 4,
20619 py + tu_row * 4,
20620 4,
20621 base_q_idx,
20622 tu_pred,
20623 None,
20624 Some(tu_skip_ctx), fctx,
20625 )?;
20626 if tu_row == 0 && tu_col == 0 {
20627 first = tu_tx_type;
20628 }
20629 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
20630 }
20631 }
20632 Ok((Grid::Zero(64), first))
20633}
20634
20635/// The [`TxbSet`] one leaf of an inter block's var-tx tree reads its
20636/// coefficient tables from -- the inter counterpart of [`txbset_for`].
20637/// `av1_get_tx_type`'s chroma tail (libaom `av1/common/blockd.h:1291-1305`):
20638/// an inter block's chroma transform inherits the *colocated luma* unit's
20639/// coded `tx_type`, then drops back to `DCT_DCT` unless that type is a member
20640/// of the extended set the CHROMA transform size selects
20641/// (`av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)][tx_type]`,
20642/// `blockd.h:1036`/`1097`). lane-golomb r7: we used to force `DCT_DCT` at
20643/// every chroma side >= 32, but `av1_get_ext_tx_set_type`'s DCT-only rung is
20644/// `tx_size_sqr_up > TX_32X32`; at exactly TX_32X32 an inter block reads
20645/// `EXT_TX_SET_DCT_IDTX`, so a 64x64 inter block whose first luma leaf coded
20646/// `IDTX` inherits IDTX on its 32x32 chroma units. `IDTX` and `DCT_DCT` are
20647/// both `TX_CLASS_2D`, so that mistake left the entropy stream perfectly in
20648/// sync and only corrupted the inverse transform (one 64x64 superblock of
20649/// high-frequency chroma noise, luma bit-exact).
20650pub(crate) fn reduce_inherited_chroma_tx_type(t: TxType, w: usize, h: usize, fctx: &crate::decode::FrameCtx) -> TxType {
20651 reduce_inherited_chroma_tx_type_flagged(t, w, h, fctx.reduced_tx_set_inter.with(std::cell::Cell::get))
20652}
20653
20654/// [`reduce_inherited_chroma_tx_type`] against an explicit `reduced_tx_set`
20655/// bit (lane-intertx): the WRITER calls this with the frame's own header bit
20656/// ([`crate::cdf_state::Cdfs::reduced_tx_set`]) to derive the type an inter
20657/// block's chroma transform is coded with, the same derivation its reader
20658/// makes -- it has no `FrameCtx` in reach and must not silently read one
20659/// whose value can lag the frame being written (class `stale-context-bit`).
20660pub(crate) fn reduce_inherited_chroma_tx_type_flagged(t: TxType, w: usize, h: usize, reduced: bool) -> TxType {
20661 use TxType::*;
20662 let sqr_up = w.max(h);
20663 let sqr = w.min(h);
20664 // `av1_get_ext_tx_set_type(tx_size, is_inter = 1, reduced)`.
20665 let allowed: &[TxType] = if sqr_up > 32 {
20666 // EXT_TX_SET_DCTONLY
20667 &[DctDct]
20668 } else if sqr_up == 32 || reduced {
20669 // EXT_TX_SET_DCT_IDTX
20670 &[DctDct, Idtx]
20671 } else if sqr == 16 {
20672 // EXT_TX_SET_DTT9_IDTX_1DDCT -- TX_TYPES 0..=11, i.e. everything but
20673 // the four 1D ADST/FLIPADST types.
20674 &[
20675 DctDct, AdstDct, DctAdst, AdstAdst, FlipAdstDct, DctFlipAdst, FlipAdstFlipAdst,
20676 AdstFlipAdst, FlipAdstAdst, Idtx, VDct, HDct,
20677 ]
20678 } else {
20679 // EXT_TX_SET_ALL16
20680 return t;
20681 };
20682 if allowed.contains(&t) { t } else { DctDct }
20683}
20684
20685/// The [`TxbSet`] a resolved luma transform side reads its coefficient tables
20686/// from for a block libaom's `is_inter_block` calls inter -- which an intrabc
20687/// block is (`blockd.h:373`), so its `tx_type` comes off the inter `ext_tx`
20688/// sets, never the mode-indexed intra ones ([`txbset_for`]).
20689///
20690/// 64 is only ever the 64x64-block, depth-0, corner-scanned case
20691/// ([`TxbSet::Luma64`]); every other resolved side maps to its own matching
20692/// set. `get_tx_set` (spec 5.11.48) only splits on `reduced_tx_set` at
20693/// `TX_8X8`/`TX_4X4`: an intra `TX_16X16` always reads `TX_SET_INTRA_2`
20694/// regardless of the flag (`av1_get_ext_tx_set_type`'s
20695/// `tx_size_sqr == TX_16X16` branch ignores `use_reduced_set` once it is past
20696/// the `TX_32X32`/reduced-set checks), so only the 8x8 and 4x4 cases have a
20697/// second table ([`TxbSet::Luma8Inter`]/[`TxbSet::Luma4Inter`]).
20698///
20699/// lane-av1txr: the intrabc leaf sites used to call a near-duplicate
20700/// `txbset_for_inter` whose `4` fell through to `Luma64` -- 32x32-class tables
20701/// (a 1024-entry grid) handed to a 4x4 dequant, which panicked at
20702/// `transform.rs`'s `inverse_transform_2d_typed_wh` the first time an intrabc
20703/// 4x4 TU coded a non-zero coefficient (`allintra0`/cpu-used=0). The
20704/// duplicate is gone; every inter-table site goes through this one mapping.
20705fn inter_txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
20706 match tx_px {
20707 // lane-sb128c r1: a 128x128 inter block's own luma unit
20708 // (`max_txsize_rect_lookup[BLOCK_128X128] == TX_64X64`).
20709 // `av1_get_ext_tx_set_type` is `DCT_ONLY` at `tx_size_sqr_up ==
20710 // TX_64X64`, so no `tx_type` symbol is coded and the intra/inter sets
20711 // coincide -- exactly the set the whole-64x64 inter block already uses.
20712 64 => TxbSet::Luma64,
20713 32 => TxbSet::Luma32Inter,
20714 16 if reduced_tx_set => TxbSet::Luma16Inter,
20715 16 => TxbSet::Luma16InterSet1,
20716 8 if reduced_tx_set => TxbSet::Luma8Inter,
20717 8 => TxbSet::Luma8InterSet1,
20718 4 if reduced_tx_set => TxbSet::Luma4Inter,
20719 4 => TxbSet::Luma4InterSet1,
20720 _ => unreachable!("a var-tx leaf is never wider than a 64x64 block's 32x32 sub-transform"),
20721 }
20722}
20723
20724/// The luma coefficient scan table for a resolved transform side -- 32/16/8/4,
20725/// the only four sizes a `TxMode::Select` block's coded coefficient grid
20726/// ([`read_tx_size`]'s resolved side, or 32 at the 64x64 corner case) can be.
20727fn scan_for<'a>(
20728 tx_px: usize,
20729 scan32: &'a [u16],
20730 scan16: &'a [u16],
20731 scan8: &'a [u16],
20732 scan4: &'a [u16],
20733) -> &'a [u16] {
20734 match tx_px {
20735 32 => scan32,
20736 16 => scan16,
20737 8 => scan8,
20738 4 => scan4,
20739 _ => unreachable!("read_tx_size never resolves the coefficient grid to anything else"),
20740 }
20741}
20742
20743
20744fn txbset_for(tx_px: usize, reduced_tx_set: bool) -> TxbSet {
20745 match tx_px {
20746 64 => TxbSet::Luma64,
20747 32 => TxbSet::Luma32,
20748 16 => TxbSet::Luma16,
20749 8 if reduced_tx_set => TxbSet::Luma8,
20750 8 => TxbSet::Luma8Set1,
20751 4 if reduced_tx_set => TxbSet::Luma4,
20752 4 => TxbSet::Luma4Set1,
20753 _ => unreachable!("read_tx_size never resolves a block's own side to anything else"),
20754 }
20755}
20756
20757/// `tx_size_wide_unit_log2`/`tx_size_high_unit_log2`: `log2(px / 4)`, the
20758/// index [`tx_dim_to_filter_length`] and the chroma 4-vs-6 choice key on.
20759fn unit_log2(px: u32) -> i32 {
20760 if px == 0 {
20761 0
20762 } else {
20763 px.trailing_zeros() as i32 - 2
20764 }
20765}
20766
20767/// spec 7.14.4's `get_filter_level`: `ref_deltas` is indexed by the block's
20768/// reference frame, `mode_deltas` by `mode_lf_lut[mode]` -- `0` for
20769/// `GLOBALMV`, `1` for `NEARESTMV`/`NEARMV`/`NEWMV` (intra gets no mode
20770/// delta). `ref_frame` here is [`Neighbours::ref_grid`]'s packed cell:
20771/// magnitude = reference (`0` = intra), sign = `GLOBALMV` (lane-av1golden2:
20772/// the flat `mode_deltas[1]` this used before was a `LAST_FRAME`-reachable
20773/// wrong delta on every `GLOBALMV` block, masked while any `GOLDEN_FRAME`
20774/// block anywhere aborted the whole stream's decode before comparison).
20775fn lf_level(
20776 lf: &LoopFilterParams,
20777 plane_idx: usize,
20778 dir: usize,
20779 ref_frame: i8,
20780 delta_lf: i32,
20781 segment_id: u8, fctx: &crate::decode::FrameCtx,
20782) -> i32 {
20783 let base = i32::from(if plane_idx == 0 {
20784 lf.level[dir]
20785 } else if plane_idx == 1 {
20786 lf.level[2]
20787 } else {
20788 lf.level[3]
20789 });
20790 // spec 7.14.4: the per-superblock `DeltaLF` term applies before the
20791 // ref/mode delta scaling below, and regardless of `delta_enabled`
20792 // (that flag only gates `ref_deltas`/`mode_deltas`).
20793 let base = (base + delta_lf).clamp(0, 63);
20794 // lane-seg, spec 7.14.4 / libaom `av1_loop_filter_frame_init`: this
20795 // block's segment's own `SEG_LVL_ALT_LF_*` delta applies after the
20796 // per-superblock `DeltaLF` term and before the ref/mode deltas below.
20797 // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4)
20798 // for chroma.
20799 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
20800 // lane-perf9: `segment_id` is `0` and this lookup is skipped entirely
20801 // when the frame codes no segmentation (`seg_lf_active`), which is what
20802 // spares the deblock loop two thread-local reads per 4x4 edge.
20803 let base = match seg_feature(usize::from(segment_id), feature, fctx) {
20804 Some(data) => (base + data).clamp(0, 63),
20805 None => base,
20806 };
20807 if !lf.delta_enabled {
20808 return base;
20809 }
20810 let scale = 1i32 << (base >> 5);
20811 let is_inter = ref_frame != 0;
20812 let is_globalmv = ref_frame < 0;
20813 let ref_idx = ref_frame.unsigned_abs() as usize;
20814 let mut lvl = base + i32::from(lf.ref_deltas[ref_idx]) * scale;
20815 if is_inter {
20816 lvl += i32::from(lf.mode_deltas[usize::from(!is_globalmv)]) * scale;
20817 }
20818 lvl.clamp(0, 63)
20819}
20820
20821thread_local! {
20822 /// lane-pipefilt: [`EdgeCtx`]'s level LUT, memoised per thread. The table
20823 /// is a pure function of the frame's [`LoopFilterParams`], the plane, the
20824 /// pass and segment 0's own `SEG_LVL_ALT_LF_*` datum (the only thing
20825 /// [`lf_level`] reads out of the `FrameCtx` at `segment_id = 0`), so one
20826 /// build per plane and pass serves the whole frame. The pipeline builds
20827 /// an `EdgeCtx` per superblock-row band rather than per frame, which
20828 /// turned 20 builds a frame into ~680 -- 960 `lf_level` calls each.
20829 static LVL_CACHE: std::cell::RefCell<
20830 Vec<((usize, usize, LoopFilterParams, Option<i32>), [[u8; 15]; 64])>,
20831 > = const { std::cell::RefCell::new(Vec::new()) };
20832}
20833
20834/// `lf_level` over the whole `(base level, ref frame)` domain -- see
20835/// [`LVL_CACHE`]. `lf_level`'s own first step is
20836/// `(base0 + delta_lf).clamp(0, 63)`, so passing `b - base0` pins its base at
20837/// `b` and the rest of the function is a pure function of `(b, ref_frame)`.
20838fn lvl_table(
20839 lf: &LoopFilterParams,
20840 plane_idx: usize,
20841 dir: usize,
20842 base0: i32,
20843 fctx: &crate::decode::FrameCtx,
20844) -> [[u8; 15]; 64] {
20845 let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 };
20846 let key = (plane_idx, dir, *lf, seg_feature(0, feature, fctx));
20847 if let Some(t) = LVL_CACHE.with(|c| {
20848 c.borrow().iter().find(|(k, _)| *k == key).map(|(_, t)| *t)
20849 }) {
20850 return t;
20851 }
20852 let mut lvl = [[0u8; 15]; 64];
20853 for (b, row) in lvl.iter_mut().enumerate() {
20854 for (r, cell) in row.iter_mut().enumerate() {
20855 *cell =
20856 lf_level(lf, plane_idx, dir, (r as i32 - 7) as i8, b as i32 - base0, 0, fctx) as u8;
20857 }
20858 }
20859 LVL_CACHE.with(|c| {
20860 let mut c = c.borrow_mut();
20861 if c.len() >= 8 {
20862 c.remove(0);
20863 }
20864 c.push((key, lvl));
20865 });
20866 lvl
20867}
20868
20869/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
20870/// no-segmentation, no-delta-LF path and to this decoder's own invariant
20871/// that a coded block's transform is always its own full size -- so a TU
20872/// edge is always also a PU edge, and the "both sides skipped, not a PU
20873/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
20874/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
20875/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
20876/// One plane pass's worth of [`edge_params`] constants (lane-deblock2): the
20877/// seven values that used to be re-passed per 4-pixel edge group -- half of
20878/// them on the stack, into an `inline(never)` body -- plus libaom's
20879/// `lfi->lfthr` idea in level form: `av1_loop_filter_frame_init` builds the
20880/// filter level for every `(base level, ref frame)` pair once per frame
20881/// instead of running `av1_get_filter_level`'s delta arithmetic per edge.
20882struct EdgeCtx<'a> {
20883 lf: &'a LoopFilterParams,
20884 n: &'a Neighbours,
20885 fctx: &'a crate::decode::FrameCtx,
20886 plane_idx: usize,
20887 dir: usize,
20888 chroma: bool,
20889 seg_lf_active: bool,
20890 /// `delta_lf_grid`'s column for this plane and direction.
20891 delta_idx: usize,
20892 /// `mode_step` (`set_lpf_parameters`): one mi for luma, `1 << ss` for
20893 /// chroma.
20894 step: usize,
20895 /// This pass's own `lf.level[..]`, the LUT's base.
20896 base0: i32,
20897 /// `lf_level` at `[base level][ref frame + 7]`, with no segment
20898 /// override -- the whole domain, since a level is `0..=63` and a ref
20899 /// frame `-7..=7` (`ref_deltas` holds `TOTAL_REFS_PER_FRAME` = 8
20900 /// entries and is indexed by the ref frame's magnitude).
20901 lvl: [[u8; 15]; 64],
20902}
20903
20904impl<'a> EdgeCtx<'a> {
20905 fn new(
20906 lf: &'a LoopFilterParams,
20907 n: &'a Neighbours,
20908 plane_idx: usize,
20909 dir: usize,
20910 chroma: bool,
20911 seg_lf_active: bool,
20912 fctx: &'a crate::decode::FrameCtx,
20913 ) -> Self {
20914 let base0 = i32::from(if plane_idx == 0 {
20915 lf.level[dir]
20916 } else if plane_idx == 1 {
20917 lf.level[2]
20918 } else {
20919 lf.level[3]
20920 });
20921 let lvl = lvl_table(lf, plane_idx, dir, base0, fctx);
20922 Self {
20923 lf,
20924 n,
20925 fctx,
20926 plane_idx,
20927 dir,
20928 chroma,
20929 seg_lf_active,
20930 delta_idx: if plane_idx == 0 { dir } else { plane_idx + 1 },
20931 step: if chroma { 2 } else { 1 },
20932 base0,
20933 lvl,
20934 }
20935 }
20936
20937 /// Spec 7.14.4's `get_filter_level`, off the table when no segment can
20938 /// override it (which is every frame that codes no segmentation).
20939 #[inline(always)]
20940 fn level(&self, ref_frame: i8, delta_lf: i32, seg: u8) -> i32 {
20941 if self.seg_lf_active {
20942 return lf_level(self.lf, self.plane_idx, self.dir, ref_frame, delta_lf, seg, self.fctx);
20943 }
20944 let b = (self.base0 + delta_lf).clamp(0, 63) as usize;
20945 debug_assert!((-7..=7).contains(&ref_frame));
20946 let r = (i32::from(ref_frame) + 7).clamp(0, 14) as usize;
20947 i32::from(self.lvl[b][r])
20948 }
20949}
20950
20951/// Spec 7.14.2's `set_lpf_parameters`, restricted to the uniform-level,
20952/// no-segmentation, no-delta-LF path and to this decoder's own invariant
20953/// that a coded block's transform is always its own full size -- so a TU
20954/// edge is always also a PU edge, and the "both sides skipped, not a PU
20955/// edge" suppression (which only ever fires at a non-PU-edge TU boundary)
20956/// never applies here, letting this skip the `skip`/`skip_txfm` lookup
20957/// entirely. Returns `None` when this 4-pixel edge group is not filtered.
20958#[inline(always)]
20959fn edge_params(c: &EdgeCtx, x0: usize, y0: usize) -> Option<(u8, i32)> {
20960 let (mi_r, mi_c) = (plane_to_mi(c.chroma, y0), plane_to_mi(c.chroma, x0));
20961 let cur_tx = if c.dir == 0 {
20962 tx_px_at(c.n, c.chroma, mi_r, mi_c)
20963 } else {
20964 tx_h_px_at(c.n, c.chroma, mi_r, mi_c)
20965 };
20966 // lane-deblock: `cur_tx` is a power-of-two pixel size, so the alignment
20967 // test is a mask, not the hardware `divl` this used to emit (10.7% of
20968 // `edge_params`' own samples sat on that divide's result test).
20969 //
20970 // Most 4-pixel edge groups die right here (a 4-aligned coordinate that
20971 // the covering transform does not start at), so this head is inlined
20972 // into the deblock loops and only survivors pay the call and the
20973 // register-spilling prologue of the body below.
20974 if cur_tx == 0 || (if c.dir == 0 { x0 } else { y0 }) & (cur_tx as usize - 1) != 0 {
20975 return None;
20976 }
20977 edge_params_body(c, x0, y0, mi_r, mi_c, cur_tx)
20978}
20979
20980/// [`edge_params`] past its transform-alignment gate.
20981#[inline(never)]
20982fn edge_params_body(
20983 c: &EdgeCtx,
20984 x0: usize,
20985 y0: usize,
20986 mi_r: usize,
20987 mi_c: usize,
20988 cur_tx: u32,
20989) -> Option<(u8, i32)> {
20990 let n = c.n;
20991 let cur_ref = n.ref_grid[mi_r * n.skip_grid_cols_mi + mi_c];
20992 // The previous cell must keep the odd parity `plane_to_mi` just
20993 // established, i.e. the bottom/right mi of the PREVIOUS 8x8 luma group,
20994 // not the other half of this one.
20995 let (pv_mi_r, pv_mi_c) = if c.dir == 0 {
20996 (mi_r, mi_c - c.step)
20997 } else {
20998 (mi_r - c.step, mi_c)
20999 };
21000 let pv_tx = if c.dir == 0 {
21001 tx_px_at(n, c.chroma, pv_mi_r, pv_mi_c)
21002 } else {
21003 tx_h_px_at(n, c.chroma, pv_mi_r, pv_mi_c)
21004 };
21005 let pv_ref = n.ref_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c];
21006 let cur_delta_lf = i32::from(n.delta_lf_grid[mi_r * n.skip_grid_cols_mi + mi_c][c.delta_idx]);
21007 let pv_delta_lf =
21008 i32::from(n.delta_lf_grid[pv_mi_r * n.skip_grid_cols_mi + pv_mi_c][c.delta_idx]);
21009
21010 // spec 7.14.2 / libaom `set_lpf_parameters`: a transform edge between two
21011 // SKIPPED INTER blocks is filtered only when it is also a prediction
21012 // (coded-block) edge -- `!pv_skip || !curr_skipped || pu_edge`. The
21013 // omission of this term (on the stale invariant "a coded block's transform
21014 // is always its own full size", which var-tx broke) had us filtering an
21015 // interior 8-px lattice the reference never touches: on the pinned 192x68
21016 // inter stream frame 1 went from 7244 wrong post-deblock luma px to 0.
21017 // libaom prices `pu_edge` in the PLANE's own pixels against the plane's
21018 // block size (`!(coord & (block_size_wide[get_plane_block_size(bsize)] -
21019 // 1))`), which for chroma bottoms out at 4 px: every 4-aligned chroma
21020 // edge of a sub-8x8 group is a prediction edge, even though the group's
21021 // bottom/right mi does not start there. Comparing mi origins instead is
21022 // the same test only while the block's own origin is aligned to its
21023 // size, which a 4x4 luma block read at the `| 1` mi is not.
21024 let cur_cell = n.blk_grid[mi_r * n.skip_grid_cols_mi + mi_c];
21025 let (cur_org, cur_dim) = (cur_cell.org, cur_cell.dim);
21026 let (org_px, dim_mi) = if c.dir == 0 {
21027 (usize::from(cur_org[1]), usize::from(cur_dim[0]))
21028 } else {
21029 (usize::from(cur_org[0]), usize::from(cur_dim[1]))
21030 };
21031 let pu_edge = if c.chroma {
21032 let plane_dim = (dim_mi * MI / 2).max(4);
21033 (if c.dir == 0 { x0 } else { y0 }) % plane_dim == 0
21034 } else {
21035 plane_to_mi(false, if c.dir == 0 { x0 } else { y0 }) == org_px
21036 };
21037 if !pu_edge
21038 && cur_ref != 0
21039 && pv_ref != 0
21040 && n.skip_at(mi_r, mi_c)
21041 && n.skip_at(pv_mi_r, pv_mi_c)
21042 {
21043 return None;
21044 }
21045 let (cur_seg, pv_seg) = if c.seg_lf_active {
21046 (segment_id_at(mi_r, mi_c, c.fctx), segment_id_at(pv_mi_r, pv_mi_c, c.fctx))
21047 } else {
21048 (0, 0)
21049 };
21050 let cur_level = c.level(cur_ref, cur_delta_lf, cur_seg);
21051 let pv_level = c.level(pv_ref, pv_delta_lf, pv_seg);
21052 if cur_level == 0 && pv_level == 0 {
21053 return None;
21054 }
21055 let dim = unit_log2(cur_tx).min(unit_log2(pv_tx)).clamp(0, 4) as usize;
21056 let len: u8 = if c.chroma {
21057 if dim == 0 { 4 } else { 6 }
21058 } else {
21059 [4, 8, 14, 14, 14][dim]
21060 };
21061 let level = if cur_level != 0 { cur_level } else { pv_level };
21062 hit!(DEBLOCK_HITS);
21063 Some((len, level))
21064}
21065
21066/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
21067fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
21068 let sharpness = i32::from(sharpness);
21069 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
21070 let mut lim = level >> shift;
21071 if sharpness > 0 {
21072 lim = lim.min(9 - sharpness);
21073 }
21074 lim = lim.max(1);
21075 (2 * (level + 2) + lim, lim, level >> 4)
21076}
21077
21078#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
21079fn sclamp(v: i32, fctx: &crate::decode::FrameCtx) -> i32 {
21080 // libaom's `signed_char_clamp_high`: the clamp range scales with
21081 // `128 << (bit_depth - 8)` alongside the centering constant below.
21082 let scale = 1i32 << (bit_depth(fctx) - 8);
21083 v.clamp(-128 * scale, 128 * scale - 1)
21084}
21085
21086fn round_pow2(v: i32, n: u32) -> i32 {
21087 (v + (1 << (n - 1))) >> n
21088}
21089
21090/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
21091/// fallback.
21092fn filter4(mask: bool, thresh: i32, p1: i32, p0: i32, q0: i32, q1: i32, fctx: &crate::decode::FrameCtx) -> [i32; 4] {
21093 if !mask {
21094 return [p1, p0, q0, q1];
21095 }
21096 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
21097 // lane-perf6: `sclamp` re-read the thread-local bit depth on every one of
21098 // this kernel's eight clamps, and this kernel runs per deblocked sample.
21099 // Same bound, resolved once.
21100 let scale = 1i32 << (bit_depth(fctx) - 8);
21101 let sclamp = |v: i32| v.clamp(-128 * scale, 128 * scale - 1);
21102 let centre = 128i32 * scale;
21103 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
21104 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
21105 let filter = sclamp(outer + 3 * (qs0 - ps0));
21106 let filter1 = sclamp(filter + 4) >> 3;
21107 let filter2 = sclamp(filter + 3) >> 3;
21108 let oq0 = sclamp(qs0 - filter1) + centre;
21109 let op0 = sclamp(ps0 + filter2) + centre;
21110 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
21111 let oq1 = sclamp(qs1 - tap) + centre;
21112 let op1 = sclamp(ps1 + tap) + centre;
21113 [op1, op0, oq0, oq1]
21114}
21115
21116/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
21117/// `filter4`'s narrow taps.
21118#[allow(clippy::too_many_arguments)]
21119fn filter6(
21120 mask: bool,
21121 thresh: i32,
21122 flat: bool,
21123 p2: i32,
21124 p1: i32,
21125 p0: i32,
21126 q0: i32,
21127 q1: i32,
21128 q2: i32, fctx: &crate::decode::FrameCtx,
21129) -> [i32; 4] {
21130 if flat && mask {
21131 [
21132 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
21133 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
21134 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
21135 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
21136 ]
21137 } else {
21138 filter4(mask, thresh, p1, p0, q0, q1, fctx)
21139 }
21140}
21141
21142/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
21143#[allow(clippy::too_many_arguments)]
21144fn filter8(
21145 mask: bool,
21146 thresh: i32,
21147 flat: bool,
21148 p3: i32,
21149 p2: i32,
21150 p1: i32,
21151 p0: i32,
21152 q0: i32,
21153 q1: i32,
21154 q2: i32,
21155 q3: i32, fctx: &crate::decode::FrameCtx,
21156) -> [i32; 6] {
21157 if flat && mask {
21158 [
21159 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
21160 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
21161 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
21162 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
21163 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
21164 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
21165 ]
21166 } else {
21167 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1, fctx);
21168 [p2, op1, op0, oq0, oq1, q2]
21169 }
21170}
21171
21172/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
21173/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
21174/// way -- they are only ever taps here, never written).
21175#[allow(clippy::too_many_arguments)]
21176fn filter14(
21177 mask: bool,
21178 thresh: i32,
21179 flat: bool,
21180 flat2: bool,
21181 p6: i32,
21182 p5: i32,
21183 p4: i32,
21184 p3: i32,
21185 p2: i32,
21186 p1: i32,
21187 p0: i32,
21188 q0: i32,
21189 q1: i32,
21190 q2: i32,
21191 q3: i32,
21192 q4: i32,
21193 q5: i32,
21194 q6: i32, fctx: &crate::decode::FrameCtx,
21195) -> [i32; 12] {
21196 if flat2 && flat && mask {
21197 [
21198 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
21199 round_pow2(
21200 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
21201 4,
21202 ),
21203 round_pow2(
21204 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
21205 4,
21206 ),
21207 round_pow2(
21208 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
21209 4,
21210 ),
21211 round_pow2(
21212 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
21213 4,
21214 ),
21215 round_pow2(
21216 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
21217 4,
21218 ),
21219 round_pow2(
21220 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
21221 4,
21222 ),
21223 round_pow2(
21224 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
21225 4,
21226 ),
21227 round_pow2(
21228 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
21229 4,
21230 ),
21231 round_pow2(
21232 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
21233 4,
21234 ),
21235 round_pow2(
21236 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
21237 4,
21238 ),
21239 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
21240 ]
21241 } else {
21242 let [op2, op1, op0, oq0, oq1, oq2] =
21243 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
21244 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
21245 }
21246}
21247
21248/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
21249/// the first (`q0`) sample past the edge, `outer_stride` advances to the
21250/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
21251/// the next along the edge's own filtering direction.
21252#[allow(clippy::too_many_arguments)]
21253fn filter_edge(
21254 data: &mut [u16],
21255 base: usize,
21256 outer_stride: isize,
21257 tap_stride: isize,
21258 len: u8,
21259 level: i32,
21260 sharpness: u8, fctx: &crate::decode::FrameCtx,
21261) {
21262 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
21263 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
21264 // every 8-bit threshold (including the flat masks' fixed `1`) is
21265 // compared against a raw pixel difference on the stream's own bit-depth
21266 // scale, so each is shifted left by `bit_depth - 8` before use.
21267 let shift = bit_depth(fctx) - 8;
21268 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
21269 let flat_thresh = 1i32 << shift;
21270 let smax = sample_max(fctx);
21271 for i in 0..4isize {
21272 let center = (base as isize + i * outer_stride) as usize;
21273 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
21274 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
21275 match len {
21276 4 => {
21277 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
21278 let mask = (p1 - p0).abs() <= limit
21279 && (q1 - q0).abs() <= limit
21280 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
21281 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1, fctx);
21282 data[idx(-2)] = op1.clamp(0, smax) as u16;
21283 data[idx(-1)] = op0.clamp(0, smax) as u16;
21284 data[idx(0)] = oq0.clamp(0, smax) as u16;
21285 data[idx(1)] = oq1.clamp(0, smax) as u16;
21286 }
21287 6 => {
21288 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
21289 let mask = (p2 - p1).abs() <= limit
21290 && (p1 - p0).abs() <= limit
21291 && (q1 - q0).abs() <= limit
21292 && (q2 - q1).abs() <= limit
21293 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
21294 let flat = (p1 - p0).abs() <= flat_thresh
21295 && (q1 - q0).abs() <= flat_thresh
21296 && (p2 - p0).abs() <= flat_thresh
21297 && (q2 - q0).abs() <= flat_thresh;
21298 let [op1, op0, oq0, oq1] = filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2, fctx);
21299 data[idx(-2)] = op1.clamp(0, smax) as u16;
21300 data[idx(-1)] = op0.clamp(0, smax) as u16;
21301 data[idx(0)] = oq0.clamp(0, smax) as u16;
21302 data[idx(1)] = oq1.clamp(0, smax) as u16;
21303 }
21304 8 => {
21305 let (p3, p2, p1, p0, q0, q1, q2, q3) =
21306 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
21307 let mask = (p3 - p2).abs() <= limit
21308 && (p2 - p1).abs() <= limit
21309 && (p1 - p0).abs() <= limit
21310 && (q1 - q0).abs() <= limit
21311 && (q2 - q1).abs() <= limit
21312 && (q3 - q2).abs() <= limit
21313 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
21314 let flat = (p1 - p0).abs() <= flat_thresh
21315 && (q1 - q0).abs() <= flat_thresh
21316 && (p2 - p0).abs() <= flat_thresh
21317 && (q2 - q0).abs() <= flat_thresh
21318 && (p3 - p0).abs() <= flat_thresh
21319 && (q3 - q0).abs() <= flat_thresh;
21320 let [op2, op1, op0, oq0, oq1, oq2] =
21321 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
21322 data[idx(-3)] = op2.clamp(0, smax) as u16;
21323 data[idx(-2)] = op1.clamp(0, smax) as u16;
21324 data[idx(-1)] = op0.clamp(0, smax) as u16;
21325 data[idx(0)] = oq0.clamp(0, smax) as u16;
21326 data[idx(1)] = oq1.clamp(0, smax) as u16;
21327 data[idx(2)] = oq2.clamp(0, smax) as u16;
21328 }
21329 _ => {
21330 let (p6, p5, p4, p3, p2, p1, p0) =
21331 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
21332 let (q0, q1, q2, q3, q4, q5, q6) =
21333 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
21334 let mask = (p3 - p2).abs() <= limit
21335 && (p2 - p1).abs() <= limit
21336 && (p1 - p0).abs() <= limit
21337 && (q1 - q0).abs() <= limit
21338 && (q2 - q1).abs() <= limit
21339 && (q3 - q2).abs() <= limit
21340 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
21341 let flat = (p1 - p0).abs() <= flat_thresh
21342 && (q1 - q0).abs() <= flat_thresh
21343 && (p2 - p0).abs() <= flat_thresh
21344 && (q2 - q0).abs() <= flat_thresh
21345 && (p3 - p0).abs() <= flat_thresh
21346 && (q3 - q0).abs() <= flat_thresh;
21347 let flat2 = (p4 - p0).abs() <= flat_thresh
21348 && (q4 - q0).abs() <= flat_thresh
21349 && (p5 - p0).abs() <= flat_thresh
21350 && (q5 - q0).abs() <= flat_thresh
21351 && (p6 - p0).abs() <= flat_thresh
21352 && (q6 - q0).abs() <= flat_thresh;
21353 let out = filter14(
21354 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
21355 q6, fctx,
21356 );
21357 for (k, v) in (-6..=5isize).zip(out) {
21358 data[idx(k)] = v.clamp(0, smax) as u16;
21359 }
21360 }
21361 }
21362 }
21363}
21364
21365/// lane-perf8: [`filter_edge`]'s AVX2 kernel -- the scalar loop was 8.0% of a
21366/// 4K decode's self time, spent almost entirely on the per-tap strided
21367/// addressing (`perf annotate`'s hot lines are `leaq`/`movzwl` pairs, not the
21368/// arithmetic). Nothing here is spec logic: the same masks, the same
21369/// `filter4`/`filter6`/`filter8`/`filter14` weighted sums and the same
21370/// rounding, done for 16 edge lines at once.
21371///
21372/// 16-bit lanes are exact for every value these filters see. Samples are in
21373/// `[0, 4095]`, so a difference and the `blimit` term (`2 * |p0 - q0| +
21374/// |p1 - q1| / 2 <= 10237`) fit `i16`; `filter4` works in the centred domain
21375/// where every intermediate is clamped to `+-128 << (bit_depth - 8)`; and the
21376/// wide kernels' weights each total 8 or 16, so their sums (at most
21377/// `16 * 4095 + 8 = 65528`) fit `u16` -- hence `_mm256_srli_epi16` for their
21378/// rounding shift, which is the unsigned shift the scalar's non-negative sum
21379/// takes.
21380#[cfg(target_arch = "x86_64")]
21381#[allow(unsafe_code)]
21382#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
21383mod deblock_simd {
21384 use std::arch::x86_64::*;
21385
21386 /// `a <= b` lane-wise, as a full-width mask.
21387 ///
21388 /// # Safety
21389 /// Requires AVX2.
21390 #[target_feature(enable = "avx2")]
21391 #[inline]
21392 unsafe fn le(a: __m256i, b: __m256i) -> __m256i {
21393 _mm256_cmpeq_epi16(_mm256_max_epi16(a, b), b)
21394 }
21395
21396 /// `|a - b|` lane-wise.
21397 ///
21398 /// # Safety
21399 /// Requires AVX2.
21400 #[target_feature(enable = "avx2")]
21401 #[inline]
21402 unsafe fn ad(a: __m256i, b: __m256i) -> __m256i {
21403 _mm256_abs_epi16(_mm256_sub_epi16(a, b))
21404 }
21405
21406 /// `signed_char_clamp_high`, lane-wise.
21407 ///
21408 /// # Safety
21409 /// Requires AVX2.
21410 #[target_feature(enable = "avx2")]
21411 #[inline]
21412 unsafe fn sclamp(v: __m256i, lo: __m256i, hi: __m256i) -> __m256i {
21413 _mm256_min_epi16(_mm256_max_epi16(v, lo), hi)
21414 }
21415
21416 /// 16 rows of 16 `i16` transposed in place (unpack ladder, then the
21417 /// 128-bit lane swap AVX2's in-lane unpacks leave behind).
21418 ///
21419 /// # Safety
21420 /// Requires AVX2.
21421 #[target_feature(enable = "avx2")]
21422 unsafe fn transpose16(t: &mut [__m256i; 16]) {
21423 let mut a = [_mm256_setzero_si256(); 16];
21424 for k in 0..8 {
21425 a[2 * k] = _mm256_unpacklo_epi16(t[2 * k], t[2 * k + 1]);
21426 a[2 * k + 1] = _mm256_unpackhi_epi16(t[2 * k], t[2 * k + 1]);
21427 }
21428 let mut b = [_mm256_setzero_si256(); 16];
21429 for g in 0..4 {
21430 let s = 4 * g;
21431 b[s] = _mm256_unpacklo_epi32(a[s], a[s + 2]);
21432 b[s + 1] = _mm256_unpackhi_epi32(a[s], a[s + 2]);
21433 b[s + 2] = _mm256_unpacklo_epi32(a[s + 1], a[s + 3]);
21434 b[s + 3] = _mm256_unpackhi_epi32(a[s + 1], a[s + 3]);
21435 }
21436 let mut c = [_mm256_setzero_si256(); 16];
21437 for g in 0..2 {
21438 let s = 8 * g;
21439 for j in 0..4 {
21440 c[s + 2 * j] = _mm256_unpacklo_epi64(b[s + j], b[s + j + 4]);
21441 c[s + 2 * j + 1] = _mm256_unpackhi_epi64(b[s + j], b[s + j + 4]);
21442 }
21443 }
21444 for i in 0..8 {
21445 t[i] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x20);
21446 t[i + 8] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x31);
21447 }
21448 }
21449
21450 /// The wide kernels' tap weights, in tap order and with the spec's
21451 /// rounding divisor as the row sum: `filter6` over `p2..q2`, `filter8`
21452 /// over `p3..q3`, `filter14` over `p6..q6`.
21453 const W6: [[i16; 6]; 4] = [
21454 [3, 2, 2, 1, 0, 0],
21455 [1, 2, 2, 2, 1, 0],
21456 [0, 1, 2, 2, 2, 1],
21457 [0, 0, 1, 2, 2, 3],
21458 ];
21459 const W8: [[i16; 8]; 6] = [
21460 [3, 2, 1, 1, 1, 0, 0, 0],
21461 [2, 1, 2, 1, 1, 1, 0, 0],
21462 [1, 1, 1, 2, 1, 1, 1, 0],
21463 [0, 1, 1, 1, 2, 1, 1, 1],
21464 [0, 0, 1, 1, 1, 2, 1, 2],
21465 [0, 0, 0, 1, 1, 1, 2, 3],
21466 ];
21467 #[allow(dead_code)] // superseded by the running-sum rows; kept as the weights' statement
21468 const W14: [[i16; 14]; 12] = [
21469 [7, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
21470 [5, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
21471 [4, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0],
21472 [3, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0],
21473 [2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0],
21474 [1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0],
21475 [0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1],
21476 [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2],
21477 [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 3],
21478 [0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 4],
21479 [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 5],
21480 [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 7],
21481 ];
21482
21483 /// One weighted tap sum, rounded by `shift` (3 for the divide-by-8 rows,
21484 /// 4 for `filter14`'s divide-by-16 ones). The sum is non-negative and
21485 /// below `1 << 16`, so the logical shift is the arithmetic one.
21486 ///
21487 /// # Safety
21488 /// Requires AVX2.
21489 ///
21490 /// lane-deblock: the tap count, the weights and the shift are all const
21491 /// here (they were slice parameters, which left the weight `match` as a
21492 /// runtime branch and a `movzwl` per tap -- `testl`/`je`/`movzwl` were
21493 /// 34% of this kernel's samples, and the spilled tap slices another 17%).
21494 #[target_feature(enable = "avx2")]
21495 #[inline] // rust#145574: `inline(always)` is rejected on a `target_feature` fn
21496 unsafe fn wsum<const N: usize, const SHIFT: i32>(
21497 taps: &[__m256i; N],
21498 w: &[i16; N],
21499 ) -> __m256i {
21500 let mut s = _mm256_setzero_si256();
21501 for i in 0..N {
21502 match w[i] {
21503 0 => {}
21504 1 => s = _mm256_add_epi16(s, taps[i]),
21505 2 => s = _mm256_add_epi16(s, _mm256_add_epi16(taps[i], taps[i])),
21506 k => s = _mm256_add_epi16(s, _mm256_mullo_epi16(taps[i], _mm256_set1_epi16(k))),
21507 }
21508 }
21509 let s = _mm256_add_epi16(s, _mm256_set1_epi16(1 << (SHIFT - 1)));
21510 if SHIFT == 3 {
21511 _mm256_srli_epi16(s, 3)
21512 } else {
21513 _mm256_srli_epi16(s, 4)
21514 }
21515 }
21516
21517 /// [`super::filter_edge`]'s body for 16 lines held as `t[0..16]`, `q0` in
21518 /// `t[8]`; the filtered taps are written back in place. Returns `false`
21519 /// when the filter mask is empty on every one of the 16 lines -- nothing
21520 /// was written and the caller can skip the whole write-back.
21521 ///
21522 /// # Safety
21523 /// Requires AVX2.
21524 ///
21525 /// lane-deblock2: `LEN` is a const parameter, so each edge length gets
21526 /// its own kernel holding only its own taps, and every wide row is
21527 /// clamped straight into `t` instead of into a shared twelve-entry
21528 /// result array (which the register allocator spilled -- 35% of this
21529 /// kernel's samples were `vmovdqa` to the stack).
21530 #[target_feature(enable = "avx2")]
21531 #[allow(clippy::too_many_arguments)]
21532 unsafe fn filter16<const LEN: u8>(
21533 t: &mut [__m256i; 16],
21534 blimit: i32,
21535 limit: i32,
21536 hev_thr: i32,
21537 flat_thresh: i32,
21538 scale: i32,
21539 smax: i32,
21540 ) -> bool {
21541 let lim = _mm256_set1_epi16(limit as i16);
21542 let blim = _mm256_set1_epi16(blimit as i16);
21543 let hthr = _mm256_set1_epi16(hev_thr as i16);
21544 let fthr = _mm256_set1_epi16(flat_thresh as i16);
21545 let zero = _mm256_setzero_si256();
21546 let smaxv = _mm256_set1_epi16(smax as i16);
21547 macro_rules! put {
21548 ($i:expr, $v:expr) => {
21549 t[$i] = _mm256_min_epi16(_mm256_max_epi16($v, zero), smaxv);
21550 };
21551 }
21552 let (p6, p5, p4, p3, p2, p1, p0) = (t[1], t[2], t[3], t[4], t[5], t[6], t[7]);
21553 let (q0, q1, q2, q3, q4, q5, q6) = (t[8], t[9], t[10], t[11], t[12], t[13], t[14]);
21554
21555 // `highbd_filter_mask`: the neighbour steps this kernel's length
21556 // reaches, plus the shared `blimit` term.
21557 let d1 = _mm256_max_epi16(ad(p1, p0), ad(q1, q0));
21558 let mut md = d1;
21559 if LEN >= 6 {
21560 md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p2, p1), ad(q2, q1)));
21561 }
21562 if LEN >= 8 {
21563 md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p3, p2), ad(q3, q2)));
21564 }
21565 let bl = _mm256_add_epi16(
21566 _mm256_slli_epi16(ad(p0, q0), 1),
21567 _mm256_srli_epi16(ad(p1, q1), 1),
21568 );
21569 let mask = _mm256_and_si256(le(md, lim), le(bl, blim));
21570 // lane-deblock2: an empty mask leaves every tap at its loaded value
21571 // (the flat masks are `& mask`, so they are empty too, and the final
21572 // clamp is the identity on samples that came out of the plane), so
21573 // the whole write-back -- including the vertical edge's second
21574 // transpose -- is dead.
21575 if _mm256_testz_si256(mask, mask) != 0 {
21576 return false;
21577 }
21578 let hev = _mm256_cmpgt_epi16(d1, hthr);
21579
21580 // `filter4`, in the centred domain.
21581 let centre = _mm256_set1_epi16((128 * scale) as i16);
21582 let lo = _mm256_set1_epi16((-128 * scale) as i16);
21583 let hi = _mm256_set1_epi16((128 * scale - 1) as i16);
21584 let ps1 = _mm256_sub_epi16(p1, centre);
21585 let ps0 = _mm256_sub_epi16(p0, centre);
21586 let qs0 = _mm256_sub_epi16(q0, centre);
21587 let qs1 = _mm256_sub_epi16(q1, centre);
21588 let outer = _mm256_and_si256(hev, sclamp(_mm256_sub_epi16(ps1, qs1), lo, hi));
21589 let f = sclamp(
21590 _mm256_add_epi16(
21591 outer,
21592 _mm256_mullo_epi16(_mm256_set1_epi16(3), _mm256_sub_epi16(qs0, ps0)),
21593 ),
21594 lo,
21595 hi,
21596 );
21597 let f1 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(4)), lo, hi), 3);
21598 let f2 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(3)), lo, hi), 3);
21599 let tap = _mm256_andnot_si256(
21600 hev,
21601 _mm256_srai_epi16(_mm256_add_epi16(f1, _mm256_set1_epi16(1)), 1),
21602 );
21603 let n_p1 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps1, tap), lo, hi), centre);
21604 let n_p0 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps0, f2), lo, hi), centre);
21605 let n_q0 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs0, f1), lo, hi), centre);
21606 let n_q1 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs1, tap), lo, hi), centre);
21607 let b_p1 = _mm256_blendv_epi8(p1, n_p1, mask);
21608 let b_p0 = _mm256_blendv_epi8(p0, n_p0, mask);
21609 let b_q0 = _mm256_blendv_epi8(q0, n_q0, mask);
21610 let b_q1 = _mm256_blendv_epi8(q1, n_q1, mask);
21611 if LEN == 4 {
21612 put!(6, b_p1);
21613 put!(7, b_p0);
21614 put!(8, b_q0);
21615 put!(9, b_q1);
21616 return true;
21617 }
21618
21619 // `highbd_flat_mask4`, over the same reach as this length's mask.
21620 let mut fl = _mm256_max_epi16(
21621 _mm256_max_epi16(ad(p1, p0), ad(q1, q0)),
21622 _mm256_max_epi16(ad(p2, p0), ad(q2, q0)),
21623 );
21624 if LEN >= 8 {
21625 fl = _mm256_max_epi16(fl, _mm256_max_epi16(ad(p3, p0), ad(q3, q0)));
21626 }
21627 let flat = _mm256_and_si256(le(fl, fthr), mask);
21628 let any_flat = _mm256_testz_si256(flat, flat) == 0;
21629 if LEN == 6 {
21630 if any_flat {
21631 let taps = [p2, p1, p0, q0, q1, q2];
21632 put!(6, _mm256_blendv_epi8(b_p1, wsum::<_, 3>(&taps, &W6[0]), flat));
21633 put!(7, _mm256_blendv_epi8(b_p0, wsum::<_, 3>(&taps, &W6[1]), flat));
21634 put!(8, _mm256_blendv_epi8(b_q0, wsum::<_, 3>(&taps, &W6[2]), flat));
21635 put!(9, _mm256_blendv_epi8(b_q1, wsum::<_, 3>(&taps, &W6[3]), flat));
21636 } else {
21637 put!(6, b_p1);
21638 put!(7, b_p0);
21639 put!(8, b_q0);
21640 put!(9, b_q1);
21641 }
21642 return true;
21643 }
21644
21645 // `filter8`'s six rows over `p2..q2`, the wide kernel's base.
21646 let (o0, o1, o2, o3, o4, o5) = if any_flat {
21647 let taps = [p3, p2, p1, p0, q0, q1, q2, q3];
21648 (
21649 _mm256_blendv_epi8(p2, wsum::<_, 3>(&taps, &W8[0]), flat),
21650 _mm256_blendv_epi8(b_p1, wsum::<_, 3>(&taps, &W8[1]), flat),
21651 _mm256_blendv_epi8(b_p0, wsum::<_, 3>(&taps, &W8[2]), flat),
21652 _mm256_blendv_epi8(b_q0, wsum::<_, 3>(&taps, &W8[3]), flat),
21653 _mm256_blendv_epi8(b_q1, wsum::<_, 3>(&taps, &W8[4]), flat),
21654 _mm256_blendv_epi8(q2, wsum::<_, 3>(&taps, &W8[5]), flat),
21655 )
21656 } else {
21657 (p2, b_p1, b_p0, b_q0, b_q1, q2)
21658 };
21659 macro_rules! put8 {
21660 () => {
21661 put!(5, o0);
21662 put!(6, o1);
21663 put!(7, o2);
21664 put!(8, o3);
21665 put!(9, o4);
21666 put!(10, o5);
21667 };
21668 }
21669 if LEN == 8 {
21670 put8!();
21671 return true;
21672 }
21673
21674 let fl2 = _mm256_max_epi16(
21675 _mm256_max_epi16(
21676 _mm256_max_epi16(ad(p4, p0), ad(q4, q0)),
21677 _mm256_max_epi16(ad(p5, p0), ad(q5, q0)),
21678 ),
21679 _mm256_max_epi16(ad(p6, p0), ad(q6, q0)),
21680 );
21681 let flat2 = _mm256_and_si256(le(fl2, fthr), flat);
21682 if _mm256_testz_si256(flat2, flat2) != 0 {
21683 // No line takes the wide rows: `t[2..5]`/`t[11..14]` keep the
21684 // taps they were loaded with, exactly as the blend would.
21685 put8!();
21686 return true;
21687 }
21688 // lane-deblock: `filter14`'s twelve rows as a RUNNING sum.
21689 // Consecutive `W14` rows differ by three or four taps (row j+1 - row
21690 // j is a constant vector with two negative and two positive
21691 // entries), so each output costs one add, one sub and the rounding
21692 // shift instead of a fresh 14-tap weighted sum -- 168 tap operations
21693 // become 44. Exact: every partial sum is taken mod 2^16 by
21694 // `add/sub_epi16` and every ROW sum is a real `W14` row, at most
21695 // `16 * 4095 + 8 < 2^16`, so the unsigned rounding shift sees the
21696 // true value. `deblock_simd_kernel_matches_the_scalar_filter` pins
21697 // it against `filter_edge` at 8/10/12-bit.
21698 let mut s = _mm256_add_epi16(
21699 _mm256_add_epi16(
21700 _mm256_mullo_epi16(p6, _mm256_set1_epi16(7)),
21701 _mm256_slli_epi16(_mm256_add_epi16(p5, p4), 1),
21702 ),
21703 _mm256_add_epi16(
21704 _mm256_add_epi16(_mm256_add_epi16(p3, p2), _mm256_add_epi16(p1, p0)),
21705 q0,
21706 ),
21707 );
21708 let add2 = |a, b| _mm256_add_epi16(a, b);
21709 macro_rules! row14 {
21710 ($idx:literal, $base:expr) => {
21711 put!(
21712 $idx,
21713 _mm256_blendv_epi8(
21714 $base,
21715 _mm256_srli_epi16(_mm256_add_epi16(s, _mm256_set1_epi16(8)), 4),
21716 flat2,
21717 )
21718 );
21719 };
21720 ($idx:literal, $base:expr, $plus:expr, $minus:expr) => {
21721 s = _mm256_sub_epi16(_mm256_add_epi16(s, $plus), $minus);
21722 row14!($idx, $base);
21723 };
21724 }
21725 row14!(2, p5);
21726 row14!(3, p4, add2(p3, q1), _mm256_slli_epi16(p6, 1));
21727 row14!(4, p3, add2(p2, q2), add2(p6, p5));
21728 row14!(5, o0, add2(p1, q3), add2(p6, p4));
21729 row14!(6, o1, add2(p0, q4), add2(p6, p3));
21730 row14!(7, o2, add2(q0, q5), add2(p6, p2));
21731 row14!(8, o3, add2(q1, q6), add2(p6, p1));
21732 row14!(9, o4, add2(q2, q6), add2(p5, p0));
21733 row14!(10, o5, add2(q3, q6), add2(p4, q0));
21734 row14!(11, q3, add2(q4, q6), add2(p3, q1));
21735 row14!(12, q4, add2(q5, q6), add2(p2, q2));
21736 row14!(13, q5, _mm256_slli_epi16(q6, 1), add2(p1, q3));
21737 true
21738 }
21739
21740 /// 16 edge lines at `base`. `vertical` names the edge: a vertical edge's
21741 /// 16 lines are 16 consecutive rows and its taps are consecutive samples
21742 /// (loaded as a 16x16 tile and transposed), a horizontal edge's are 16
21743 /// consecutive columns with each tap a whole row segment.
21744 ///
21745 /// # Safety
21746 /// Requires AVX2. For a vertical edge `base % stride >= 8`, `base %
21747 /// stride + 8 <= stride` and 16 rows from `base` must be inside `data`;
21748 /// for a horizontal edge `base >= 8 * stride` and `base + 8 * stride`
21749 /// must be inside it.
21750 #[target_feature(enable = "avx2")]
21751 #[allow(clippy::too_many_arguments)]
21752 pub unsafe fn edge16(
21753 data: &mut [u16],
21754 base: usize,
21755 stride: usize,
21756 vertical: bool,
21757 len: u8,
21758 blimit: i32,
21759 limit: i32,
21760 hev_thr: i32,
21761 flat_thresh: i32,
21762 scale: i32,
21763 smax: i32,
21764 ) {
21765 let p = data.as_mut_ptr();
21766 let mut t = [_mm256_setzero_si256(); 16];
21767 // The taps this length reads, as `t` indices.
21768 let (lo, hi) = match len {
21769 4 => (6, 10),
21770 6 => (5, 11),
21771 8 => (4, 12),
21772 _ => (1, 15),
21773 };
21774 if vertical {
21775 for j in 0..16 {
21776 t[j] = _mm256_loadu_si256(p.add(base + j * stride - 8).cast());
21777 }
21778 transpose16(&mut t);
21779 } else {
21780 let top = base - 8 * stride;
21781 for i in lo..hi {
21782 t[i] = _mm256_loadu_si256(p.add(top + i * stride).cast());
21783 }
21784 }
21785 // lane-deblock2: one monomorphised kernel per edge length, and an
21786 // empty filter mask returns without any write-back at all.
21787 let modified = match len {
21788 4 => filter16::<4>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
21789 6 => filter16::<6>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
21790 8 => filter16::<8>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
21791 _ => filter16::<14>(&mut t, blimit, limit, hev_thr, flat_thresh, scale, smax),
21792 };
21793 if !modified {
21794 return;
21795 }
21796 if vertical {
21797 transpose16(&mut t);
21798 for j in 0..16 {
21799 _mm256_storeu_si256(p.add(base + j * stride - 8).cast(), t[j]);
21800 }
21801 } else {
21802 let top = base - 8 * stride;
21803 let (a, b) = match len {
21804 4 | 6 => (6, 10),
21805 8 => (5, 11),
21806 _ => (2, 14),
21807 };
21808 for i in a..b {
21809 _mm256_storeu_si256(p.add(top + i * stride).cast(), t[i]);
21810 }
21811 }
21812 }
21813}
21814
21815/// [`filter_edge`] for 16 adjacent edge lines that share `edge_params`'
21816/// output. Returns `false` when this build or CPU has no kernel, leaving the
21817/// caller on the scalar path.
21818#[allow(unused_variables)]
21819fn filter_edge16(
21820 data: &mut [u16],
21821 base: usize,
21822 stride: usize,
21823 vertical: bool,
21824 len: u8,
21825 level: i32,
21826 sharpness: u8, fctx: &crate::decode::FrameCtx,
21827) -> bool {
21828 #[cfg(target_arch = "x86_64")]
21829 {
21830 if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
21831 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
21832 let shift = bit_depth(fctx) - 8;
21833 // SAFETY: the avx2 arm is reached only when the CPU reports it,
21834 // and `deblock_plane` checks the kernel's edge bounds.
21835 #[allow(unsafe_code)]
21836 unsafe {
21837 deblock_simd::edge16(
21838 data,
21839 base,
21840 stride,
21841 vertical,
21842 len,
21843 blimit << shift,
21844 limit << shift,
21845 hev_thr << shift,
21846 1 << shift,
21847 1 << shift,
21848 sample_max(fctx),
21849 )
21850 };
21851 return true;
21852 }
21853 }
21854 false
21855}
21856
21857/// One plane's worth of spec 7.14: every vertical edge across the plane,
21858/// then every horizontal edge (the order the spec and libaom both use).
21859fn deblock_plane(
21860 plane: &mut PlaneBuf<'static>,
21861 plane_idx: usize,
21862 lf: &LoopFilterParams,
21863 n: &Neighbours,
21864 frame_width: usize,
21865 frame_height: usize, fctx: &crate::decode::FrameCtx,
21866) {
21867 // spec 7.14's order: this plane's whole vertical pass, then its whole
21868 // horizontal one. lane-pipefilt split the two into one row-ranged
21869 // function so the per-superblock-row pipeline can run them a band at a
21870 // time; `0..usize::MAX` is the whole plane, i.e. exactly this call.
21871 deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, false, fctx);
21872 deblock_plane_span(plane, plane_idx, lf, n, frame_width, frame_height, 0, usize::MAX, true, fctx);
21873}
21874
21875/// One pass of [`deblock_plane`] -- vertical edges (`horz == false`) or
21876/// horizontal ones -- restricted to the plane rows `span_lo..span_hi`.
21877///
21878/// A row span is a legal cut of either pass because a band boundary is a
21879/// multiple of 16 rows and every edge's kernel stays inside its own
21880/// 4-sample group's reach; the pipeline's row lags (see [`pipe_run`]) are
21881/// what keep the two passes in spec order across bands.
21882#[allow(clippy::too_many_arguments)]
21883fn deblock_plane_span(
21884 plane: &mut PlaneBuf<'static>,
21885 plane_idx: usize,
21886 lf: &LoopFilterParams,
21887 n: &Neighbours,
21888 frame_width: usize,
21889 frame_height: usize,
21890 span_lo: usize,
21891 span_hi: usize,
21892 horz: bool,
21893 fctx: &crate::decode::FrameCtx,
21894) {
21895 let chroma = plane_idx != 0;
21896 // r7: libaom clips the deblock loop to the CODED frame's own
21897 // width/height, not the mi-aligned `true_width`/`true_height` margin
21898 // (the padding up to the next 8-pixel/superblock boundary that
21899 // reconstruction still fills in but the loop filter never visits).
21900 // Confirmed against the superres gate: with the margin included, the
21901 // last coded mi column's horizontal edges were filtered when libaom's
21902 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
21903 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
21904 // lane-golomb r9: the bound is the MI-ROUNDED frame, not the coded
21905 // frame. libaom's `av1_filter_block_plane_vert/horz` walk the superblock
21906 // and stop at `cm->mi_params.mi_cols`/`mi_rows`, which
21907 // `av1_set_mb_mi` derives from `ALIGN_POWER_OF_TWO(width, 3)` -- the
21908 // 8-pixel-aligned frame, i.e. a 68-wide frame is filtered out to column
21909 // 72 and the vertical edge AT x=68 is a real edge that rewrites the
21910 // in-crop columns 64..67. Clipping at `frame_width` skipped it, which is
21911 // the +-1 straddling-band defect (68x192 cq35, frame 1, 141 luma pixels
21912 // all in columns 64..67; frame 0 survived because that edge carried no
21913 // filter level there). r7's superres measurement is preserved: its frame
21914 // was already 8-aligned, so this bound equals `frame_width` there and
21915 // still excludes the superblock padding up to `true_width`.
21916 let (cw, ch) = if chroma {
21917 (frame_width.div_ceil(2), frame_height.div_ceil(2))
21918 } else {
21919 (frame_width, frame_height)
21920 };
21921 let (tw, th, stride) = (
21922 plane.true_width.min(cw),
21923 plane.true_height.min(ch),
21924 plane.width,
21925 );
21926 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") {
21927 eprintln!("DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}", plane.true_width, plane.true_height);
21928 }
21929 // lane-perf8: both passes iterate the edge's OWN direction innermost, so
21930 // 4 consecutive 4-sample groups (16 lines) can go through one AVX2
21931 // kernel. The swap is order-preserving: a filtered group overlaps only
21932 // groups along the edge it sits on -- the vertical pass's writes at
21933 // `x0` reach columns `x0 - 7 ..= x0 + 5` of its own 4 rows, so the
21934 // dependence is on ascending `x0` within a row, which stays the outer
21935 // loop's order, and rows remain independent (horizontal pass mirrored).
21936 let rows = plane.data.len() / stride.max(1);
21937 let seg_lf_active = fctx.seg.with(|s| s.borrow().enabled);
21938 // lane-filt1: both passes are split across `EC_AV1_FILTER_THREADS`
21939 // bands along the axis whose writes are disjoint. A vertical edge's
21940 // 4-sample groups write columns `x0-7 ..= x0+5` of their OWN 4 rows, so
21941 // row bands never touch each other; a horizontal edge's groups write rows
21942 // `y0-7 ..= y0+6` of their own 4 columns, so column bands never do. Both
21943 // read the mode-info grids immutably. The grouping a band starts with is
21944 // free: every 4-row (4-column) group's output is a pure function of that
21945 // group, whether it goes through `filter_edge16` with three neighbours or
21946 // through `filter_edge` alone. Band boundaries are multiples of 16 so no
21947 // group ever straddles one.
21948 // lane-perf10 merge: the output plane is owned (perf10 made mutable
21949 // plane params PlaneBuf<'static>); force the Cow to Owned ONCE here so
21950 // the bands below never clone it concurrently.
21951 plane.data.to_mut();
21952 let threads = crate::par::filter_threads();
21953 let sp = crate::par::Shared::new(plane);
21954 let (sp_lo, sp_hi) = (span_lo.min(th), span_hi.min(th));
21955 let vbands: Vec<(usize, usize)> = if horz || sp_lo >= sp_hi {
21956 Vec::new()
21957 } else {
21958 crate::par::bands((sp_hi - sp_lo).div_ceil(16), threads)
21959 .into_iter()
21960 .map(|(a, b)| (sp_lo + a * 16, (sp_lo + b * 16).min(sp_hi)))
21961 .collect()
21962 };
21963 crate::par::run_bands(&vbands, fctx, |y_lo, y_hi, fctx| {
21964 // SAFETY: this band writes only rows `y_lo..y_hi` of the plane, which
21965 // no other band touches (see `Shared`'s own corner-cut note).
21966 #[allow(unsafe_code)]
21967 let plane = unsafe { sp.get() };
21968 // lane-deblock2: this band's own level table and pass constants,
21969 // built once per band instead of re-derived per 4-pixel edge.
21970 let vctx = EdgeCtx::new(lf, n, plane_idx, 0, chroma, seg_lf_active, fctx);
21971 let mut x0 = 4usize;
21972 while x0 < tw {
21973 let mut y0 = y_lo;
21974 while y0 < y_hi {
21975 if y0 + 16 <= y_hi && x0 >= 8 && x0 + 8 <= stride {
21976 let ps: [Option<(u8, i32)>; 4] =
21977 std::array::from_fn(|k| edge_params(&vctx, x0, y0 + 4 * k));
21978 if let Some((len, level)) = ps[0] {
21979 if ps.iter().all(|p| *p == ps[0])
21980 && filter_edge16(
21981 plane.data.to_mut(),
21982 y0 * stride + x0,
21983 stride,
21984 true,
21985 len,
21986 level,
21987 lf.sharpness, fctx,
21988 )
21989 {
21990 y0 += 16;
21991 continue;
21992 }
21993 }
21994 for (k, p) in ps.iter().enumerate() {
21995 if let Some((len, level)) = *p {
21996 filter_edge(
21997 plane.data.to_mut(),
21998 (y0 + 4 * k) * stride + x0,
21999 stride as isize,
22000 1,
22001 len,
22002 level,
22003 lf.sharpness, fctx,
22004 );
22005 }
22006 }
22007 y0 += 16;
22008 continue;
22009 }
22010 if let Some((len, level)) = edge_params(&vctx, x0, y0) {
22011 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 {
22012 eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}");
22013 }
22014 filter_edge(
22015 plane.data.to_mut(),
22016 y0 * stride + x0,
22017 stride as isize,
22018 1,
22019 len,
22020 level,
22021 lf.sharpness, fctx,
22022 );
22023 }
22024 y0 += 4;
22025 }
22026 x0 += 4;
22027 }
22028 });
22029 // The horizontal pass runs only after the WHOLE vertical pass of this
22030 // plane (spec 7.14 order), which `run_bands` guarantees by joining.
22031 let hbands: Vec<(usize, usize)> = if !horz || sp_lo >= sp_hi {
22032 Vec::new()
22033 } else {
22034 crate::par::bands(tw.div_ceil(16), threads)
22035 .into_iter()
22036 .map(|(a, b)| (a * 16, (b * 16).min(tw)))
22037 .collect()
22038 };
22039 crate::par::run_bands(&hbands, fctx, |x_lo, x_hi, fctx| {
22040 // SAFETY: this band writes only columns `x_lo..x_hi`.
22041 #[allow(unsafe_code)]
22042 let plane = unsafe { sp.get() };
22043 let hctx = EdgeCtx::new(lf, n, plane_idx, 1, chroma, seg_lf_active, fctx);
22044 let mut y0 = sp_lo.max(4);
22045 while y0 < sp_hi {
22046 let mut x0 = x_lo;
22047 while x0 < x_hi {
22048 if x0 + 16 <= x_hi && y0 >= 8 && y0 + 7 <= rows {
22049 let ps: [Option<(u8, i32)>; 4] =
22050 std::array::from_fn(|k| edge_params(&hctx, x0 + 4 * k, y0));
22051 if let Some((len, level)) = ps[0] {
22052 if ps.iter().all(|p| *p == ps[0])
22053 && filter_edge16(
22054 plane.data.to_mut(),
22055 y0 * stride + x0,
22056 stride,
22057 false,
22058 len,
22059 level,
22060 lf.sharpness, fctx,
22061 )
22062 {
22063 x0 += 16;
22064 continue;
22065 }
22066 }
22067 for (k, p) in ps.iter().enumerate() {
22068 if let Some((len, level)) = *p {
22069 filter_edge(
22070 plane.data.to_mut(),
22071 y0 * stride + x0 + 4 * k,
22072 1,
22073 stride as isize,
22074 len,
22075 level,
22076 lf.sharpness, fctx,
22077 );
22078 }
22079 }
22080 x0 += 16;
22081 continue;
22082 }
22083 if let Some((len, level)) = edge_params(&hctx, x0, y0) {
22084 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE")
22085 && plane_idx == 0
22086 && x0 == 44
22087 {
22088 eprintln!(
22089 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
22090 lf.sharpness
22091 );
22092 }
22093 filter_edge(
22094 plane.data.to_mut(),
22095 y0 * stride + x0,
22096 1,
22097 stride as isize,
22098 len,
22099 level,
22100 lf.sharpness, fctx,
22101 );
22102 }
22103 x0 += 4;
22104 }
22105 y0 += 4;
22106 } });
22107}
22108
22109/// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a
22110/// pre-CDEF snapshot of all three planes, a post-deblock snapshot when loop
22111/// restoration is active, and a fresh LR destination per plane -- freshly
22112/// allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K, so every
22113/// sample written also takes a first-touch page fault. The buffers are handed
22114/// back here instead and refilled in place.
22115///
22116/// lane-memfix: PROCESS-WIDE, not one stash per thread. These buffers do not
22117/// stay on one thread: the frame thread allocates the snapshots and a filter
22118/// worker returns them ([`pipe_run_lr`] swaps the picture's pre-LR planes
22119/// into the pool from whichever worker ran it), so a per-thread pool leaked
22120/// whole-plane buffers into every worker it touched -- 19 MB a set, times
22121/// every pool thread the decode ever created. One shared pool with a hard
22122/// entry cap bounds the retention at [`SCRATCH_CAP`] buffers no matter how
22123/// many threads cycle through it; anything over the cap is freed.
22124static PLANE_SCRATCH: std::sync::Mutex<Vec<Vec<u16>>> = std::sync::Mutex::new(Vec::new());
22125
22126/// Most buffers the shared pool keeps. ~3 whole-plane sets per in-flight 4K
22127/// frame at the shipped `EC_AV1_THREADS` ceiling; the frames actually in
22128/// flight cycle through far fewer.
22129const SCRATCH_CAP: usize = 32;
22130
22131/// Takes a pooled buffer for a caller that wants `n` samples, best-fit by
22132/// CAPACITY so a chroma-sized request does not permanently promote a
22133/// luma-sized allocation (every pooled buffer would drift to the largest
22134/// size otherwise). `None` when the pool is empty.
22135fn scratch_take(n: usize) -> Option<Vec<u16>> {
22136 let mut p = PLANE_SCRATCH.lock().unwrap();
22137 if p.is_empty() {
22138 return None;
22139 }
22140 let fit = p
22141 .iter()
22142 .enumerate()
22143 .filter(|(_, v)| v.capacity() >= n)
22144 .min_by_key(|(_, v)| v.capacity())
22145 .map(|(i, _)| i);
22146 let i = match fit {
22147 Some(i) => i,
22148 // Nothing big enough: grow the largest rather than a small one.
22149 None => p
22150 .iter()
22151 .enumerate()
22152 .max_by_key(|(_, v)| v.capacity())
22153 .map(|(i, _)| i)
22154 .expect("the pool is not empty"),
22155 };
22156 Some(p.swap_remove(i))
22157}
22158
22159/// A pooled buffer holding a copy of `src`.
22160fn scratch_from(src: &[u16]) -> Vec<u16> {
22161 let mut v = scratch_take(src.len()).unwrap_or_default();
22162 v.clear();
22163 v.extend_from_slice(src);
22164 v
22165}
22166
22167/// An empty pooled buffer, for a caller that fills it itself.
22168fn scratch_empty() -> Vec<u16> {
22169 let mut v = scratch_take(0).unwrap_or_default();
22170 v.clear();
22171 v
22172}
22173
22174/// A pooled buffer of exactly `n` samples whose contents are NOT cleared --
22175/// for a caller that writes every element it later reads (lane-copy: the
22176/// post-deblock snapshot writes 4 rows in 64 and reads no other).
22177fn scratch_sized(n: usize) -> Vec<u16> {
22178 let mut v = scratch_take(n).unwrap_or_default();
22179 if v.len() > n {
22180 v.truncate(n);
22181 } else if v.len() < n {
22182 v.resize(n, 0);
22183 }
22184 v
22185}
22186
22187/// A plane's post-deblock snapshot, its samples taken from the pool (every
22188/// other field is `usize`).
22189///
22190/// lane-copy: loop restoration is the only reader, and spec 7.17.2's stripe
22191/// boundary substitution reads the post-deblock plane at just four rows
22192/// around each interior stripe boundary (`row` outside
22193/// `[stripe_v_start, stripe_v_end)` resolves to `stripe_v_start-1`,
22194/// `stripe_v_start-2`, `stripe_v_end` or `stripe_v_end+1` in
22195/// `restoration::lr_src_row`); stripes are `64 >> ss_y` rows offset by
22196/// `RESTORATION_UNIT_OFFSET = 8 >> ss_y`, so the boundaries sit at
22197/// `k*stripe_h - offset`. Copying only those rows turns a full-plane
22198/// memmove per plane per frame into 4 rows in 64 (luma). Every other row of
22199/// the pooled buffer keeps whatever a previous frame left there -- an
22200/// initialised value that no reader ever reaches.
22201fn snap_alloc(p: &PlaneBuf<'_>) -> PlaneBuf<'static> {
22202 PlaneBuf { data: std::borrow::Cow::Owned(scratch_sized(p.data.len())), ..*p }
22203}
22204
22205fn plane_snapshot(p: &PlaneBuf<'_>, ss_y: u32) -> PlaneBuf<'static> {
22206 let mut data = scratch_sized(p.data.len());
22207 let rows = if p.width == 0 { 0 } else { p.data.len() / p.width };
22208 let stripe_h = 64usize >> ss_y;
22209 let offset = 8usize >> ss_y;
22210 let mut b = stripe_h - offset;
22211 while b < rows {
22212 let (lo, hi) = (b - 2, (b + 2).min(rows));
22213 data[lo * p.width..hi * p.width].copy_from_slice(&p.data[lo * p.width..hi * p.width]);
22214 b += stripe_h;
22215 }
22216 PlaneBuf { data: std::borrow::Cow::Owned(data), ..*p }
22217}
22218
22219/// The pre-filter reconstruction of one coded frame, plus the per-block state
22220/// the loop filters read.
22221///
22222/// The encoder's filter search ([`crate::filter_search::pick_filters`])
22223/// decodes the same coded tile under ~25 candidate deblock/CDEF parameter
22224/// sets to score each one, and the entropy decode and reconstruction it
22225/// repeats are identical every time -- both filters run after it, on the
22226/// finished planes. That re-parse was 24% of the encoder's profile. A caller
22227/// arms [`arm_filter_replay`] around ONE decode and then re-runs the filters
22228/// alone through [`replay_filters`]; the result is the same picture the full
22229/// decode would have returned, because it is the same two calls on a copy of
22230/// the same planes.
22231pub(crate) struct FilterReplay {
22232 y: PlaneBuf<'static>,
22233 u: PlaneBuf<'static>,
22234 v: PlaneBuf<'static>,
22235 neighbours: Neighbours,
22236 frame_width: usize,
22237 frame_height: usize,
22238 width: usize,
22239 height: usize,
22240 /// The reconstructed extent (`mi_cols`/`mi_rows` * 4), for the wide-margin
22241 /// stash the cropped return path leaves behind.
22242 true_width: usize,
22243 true_height: usize,
22244 /// lane-av1fpar: plane buffers this replay is done with. Every candidate
22245 /// works on its own copy of three ~6 MB planes, and a fresh `Vec` per
22246 /// copy is a fresh mmap the kernel faults in page by page -- 12.6% of a
22247 /// 1080p frame's wall in allocation, not in filtering. Recycled here
22248 /// instead; the pool holds at most the six planes one candidate has live.
22249 scratch: Vec<Vec<u16>>,
22250 /// lane-av1cap2: the final replay's post-CDEF luma plane and the TRUE
22251 /// post-deblock rows loop restoration substitutes at its stripe
22252 /// borders ([`plane_snapshot`], exactly `restoration::lr_src_row`'s
22253 /// rows) -- what [`replay_restoration`] filters, instead of decoding
22254 /// the re-coded tile a second time.
22255 final_luma: Option<(PlaneBuf<'static>, PlaneBuf<'static>)>,
22256 /// lane-av1speed3: the previous candidate's DESTINATION planes, still
22257 /// holding its post-CDEF samples, and one byte per 8x8 CDEF unit its
22258 /// filter wrote (see [`cdef_band`]). The CDEF half of the search moves
22259 /// no deblocking level, so every candidate of it used to copy the three
22260 /// post-deblock planes (~19 MB at 4K) into fresh destinations. Here the
22261 /// destinations are kept and only the units the last candidate touched
22262 /// are restored -- the same bytes, since a unit nobody wrote still holds
22263 /// the deblocked sample it was copied from.
22264 work: Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
22265 wrote: Vec<u8>,
22266 /// The strengths [`FilterReplay::work`] was filtered under: a plane whose
22267 /// new candidate can only write MORE units than the old one needs no
22268 /// restore at all, since every unit CDEF writes it writes from the
22269 /// post-deblock source alone.
22270 work_cdef: Option<CdefParams>,
22271 /// The last deblocked planes and the levels that produced them.
22272 /// Deblocking depends on nothing else the search moves, and the search
22273 /// fixes the levels before it walks the CDEF strengths, so every
22274 /// candidate after the first of a level pair replays CDEF alone.
22275 deblocked: Option<(LoopFilterParams, PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
22276}
22277
22278thread_local! {
22279 /// Set by [`arm_filter_replay`] for the span of one decode.
22280 static REPLAY_ARMED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
22281 /// What that decode captured, until [`clear_filter_replay`].
22282 static REPLAY: std::cell::RefCell<Option<FilterReplay>> =
22283 const { std::cell::RefCell::new(None) };
22284}
22285
22286/// Capture this thread's next decode's pre-filter frame (see [`FilterReplay`]).
22287pub(crate) fn arm_filter_replay() {
22288 REPLAY_ARMED.set(true);
22289}
22290
22291/// Test-only: force every filter candidate through a full decode, so a gate
22292/// can hold the replay against the decode it stands in for
22293/// (`encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode`).
22294#[cfg(test)]
22295static REPLAY_DISABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
22296
22297#[cfg(test)]
22298pub(crate) fn set_filter_replay_disabled(off: bool) {
22299 REPLAY_DISABLED.store(off, std::sync::atomic::Ordering::Relaxed);
22300}
22301
22302// Test-only: run the capture decode `replay_final` replaced as well, and
22303// hold its picture and its `FilterStages` against the replay's
22304// (`encoder::tests::filter_replay_final_matches_the_capture_decode`).
22305// Thread-local, not a global: the filter stage runs on the frame thread the
22306// test itself drives, and a process-wide flag would put every test encoding
22307// in parallel with this one through the extra decode too.
22308#[cfg(test)]
22309thread_local! {
22310 static VERIFY_FINAL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
22311}
22312
22313#[cfg(test)]
22314pub(crate) fn set_verify_final_replay(on: bool) {
22315 VERIFY_FINAL.set(on);
22316}
22317
22318#[cfg(test)]
22319pub(crate) fn verify_final_replay() -> bool {
22320 VERIFY_FINAL.get()
22321}
22322
22323/// Drop the armed flag and anything captured: the tile it belongs to is done.
22324pub(crate) fn clear_filter_replay() {
22325 REPLAY_ARMED.set(false);
22326 REPLAY.with_borrow_mut(|r| *r = None);
22327}
22328
22329/// The capture itself, called from the decoder's own pre-filter point. Owns
22330/// copies of the planes, since the caller filters them in place.
22331fn capture_filter_replay(
22332 y: &PlaneBuf<'_>,
22333 u: &PlaneBuf<'_>,
22334 v: &PlaneBuf<'_>,
22335 neighbours: &Neighbours,
22336 frame_width: usize,
22337 frame_height: usize,
22338 width: usize,
22339 height: usize,
22340 true_width: usize,
22341 true_height: usize,
22342) {
22343 if !REPLAY_ARMED.replace(false) {
22344 return;
22345 }
22346 let own = |p: &PlaneBuf<'_>| PlaneBuf { data: std::borrow::Cow::Owned(p.data.to_vec()), ..*p };
22347 REPLAY.with_borrow_mut(|slot| {
22348 *slot = Some(FilterReplay {
22349 y: own(y),
22350 u: own(u),
22351 v: own(v),
22352 neighbours: neighbours.clone(),
22353 frame_width,
22354 frame_height,
22355 width,
22356 height,
22357 true_width,
22358 true_height,
22359 scratch: Vec::new(),
22360 work: None,
22361 wrote: Vec::new(),
22362 work_cdef: None,
22363 final_luma: None,
22364 deblocked: None,
22365 });
22366 });
22367}
22368
22369/// Restores, from the post-deblock cache, every sample the previous CDEF
22370/// candidate may have written: for each unit row, the column span between
22371/// its first and last written unit (a superset of the written units, which
22372/// is what makes the copy contiguous -- and never more than the whole-plane
22373/// copy it replaces). `unit` is this plane's CDEF unit side, 8 for luma and
22374/// 4 for 4:2:0 chroma.
22375fn restore_written(
22376 dst: &mut PlaneBuf<'static>,
22377 src: &PlaneBuf<'_>,
22378 wrote: &[u8],
22379 mask: u8,
22380 unit_cols: usize,
22381 unit: usize,
22382) {
22383 let w = dst.width;
22384 if w == 0 || unit_cols == 0 || wrote.is_empty() {
22385 return;
22386 }
22387 let rows = dst.data.len() / w;
22388 let s: &[u16] = &src.data;
22389 let d = dst.data.to_mut();
22390 let band = |d: &mut [u16], wr: &[u8], ur0: usize| {
22391 for (i, row) in wr.chunks(unit_cols).enumerate() {
22392 let Some(c0) = row.iter().position(|&b| b & mask != 0) else {
22393 continue;
22394 };
22395 let c1 = row.iter().rposition(|&b| b & mask != 0).expect("just found one");
22396 let (x0, x1) = ((c0 * unit).min(w), ((c1 + 1) * unit).min(w));
22397 let ur = ur0 + i;
22398 let (y0, y1) = ((ur * unit).min(rows), ((ur + 1) * unit).min(rows));
22399 for r in y0..y1 {
22400 let off = (r - ur0 * unit) * w;
22401 d[off + x0..off + x1].copy_from_slice(&s[r * w + x0..r * w + x1]);
22402 }
22403 }
22404 };
22405 let urows = wrote.len() / unit_cols;
22406 let threads = crate::par::filter_threads().min(urows.max(1));
22407 if threads <= 1 {
22408 band(d, wrote, 0);
22409 return;
22410 }
22411 let per = urows.div_ceil(threads);
22412 let batch = crate::par::Batch::new("ec-av1-filter");
22413 for (i, (dc, wr)) in d.chunks_mut(per * unit * w).zip(wrote.chunks(per * unit_cols)).enumerate()
22414 {
22415 let band = &band;
22416 batch.submit(move || band(dc, wr, i * per));
22417 }
22418}
22419
22420/// One candidate's working copy of a captured plane, off [`FilterReplay`]'s
22421/// own buffer pool: a cleared `Vec` that already has the capacity keeps the
22422/// allocator and the page fault handler out of the filter search.
22423fn pooled(p: &PlaneBuf<'_>, scratch: &mut Vec<Vec<u16>>) -> PlaneBuf<'static> {
22424 let mut buf = scratch.pop().unwrap_or_default();
22425 let src: &[u16] = &p.data;
22426 let threads = crate::par::filter_threads();
22427 if buf.len() != src.len() || threads <= 1 {
22428 buf.clear();
22429 buf.extend_from_slice(src);
22430 } else {
22431 // A recycled buffer is already the right length, so the copy is a
22432 // plain `copy_from_slice` -- and one worth banding: ~6 MB per
22433 // candidate is memory bandwidth, not arithmetic, and the halves are
22434 // disjoint `&mut` slices (no `par::Shared` needed).
22435 let per = src.len().div_ceil(threads);
22436 let batch = crate::par::Batch::new("ec-av1-filter");
22437 for (dst, src) in buf.chunks_mut(per).zip(src.chunks(per)) {
22438 batch.submit(move || dst.copy_from_slice(src));
22439 }
22440 }
22441 PlaneBuf { data: std::borrow::Cow::Owned(buf), ..*p }
22442}
22443
22444/// The filter half of a captured decode, under new parameters: exactly the
22445/// [`apply_deblock`] / [`apply_cdef`] pair the decoder's own tail runs, on a
22446/// copy of the captured planes. `None` when nothing is captured (the caller
22447/// then decodes for real).
22448pub(crate) fn replay_filters(
22449 loop_filter: &LoopFilterParams,
22450 cdef: &CdefParams,
22451 fctx: &FrameCtx,
22452) -> Option<Picture> {
22453 #[cfg(test)]
22454 if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
22455 return None;
22456 }
22457 replay_inner(loop_filter, cdef, None, fctx).map(|(picture, _)| picture)
22458}
22459
22460/// lane-av1cap: the filter stage's LAST replay -- the WINNING parameters,
22461/// under the per-64x64 `cdef_idx` grid the re-coded tile carries. The stage
22462/// used to reach this picture by decoding that re-coded tile a second time
22463/// (10% of a 4K frame's encode), only because the loop-restoration search
22464/// needs the decoder's own post-CDEF plane
22465/// ([`FrameCtx::capture_stages`]). It is the same two kernel calls
22466/// ([`apply_deblock`], [`apply_cdef`]) on the same captured pre-filter
22467/// planes in the same order, so it is the same bytes -- pinned by
22468/// `encoder::tests::filter_replay_final_matches_the_capture_decode`, which
22469/// runs the decode as well and holds picture and stages against it.
22470///
22471/// `want_stages` mirrors `capture_stages`' own `deblocked = None` arm: that
22472/// decode's header says `RESTORE_NONE`, so the decoder took no pre-CDEF
22473/// snapshot and handed the post-CDEF plane over for both stages.
22474pub(crate) fn replay_final(
22475 loop_filter: &LoopFilterParams,
22476 cdef: &CdefParams,
22477 idx_grid: &[u8],
22478 want_stages: bool,
22479 fctx: &FrameCtx,
22480) -> Option<(Picture, Option<FilterStages>)> {
22481 #[cfg(test)]
22482 if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
22483 return None;
22484 }
22485 replay_inner(loop_filter, cdef, Some((idx_grid, want_stages)), fctx)
22486}
22487
22488fn replay_inner(
22489 loop_filter: &LoopFilterParams,
22490 cdef: &CdefParams,
22491 // `Some((cdef_idx grid, capture the filter stages))` for the final
22492 // replay; `None` for a scoring candidate, which always codes `bits == 0`.
22493 final_pass: Option<(&[u8], bool)>,
22494 fctx: &FrameCtx,
22495) -> Option<(Picture, Option<FilterStages>)> {
22496 REPLAY.with_borrow_mut(|slot| {
22497 let r = slot.as_mut()?;
22498 let hit = matches!(&r.deblocked, Some((lf, ..)) if lf == loop_filter);
22499 // Set when the working planes ARE the deblocked planes (see below):
22500 // they go into the cache at the end, and the picture is cropped out
22501 // of them rather than taking their buffers.
22502 let mut share = false;
22503 let cpt = crate::par::timer(crate::par::S_COPY);
22504 let unit_cols = r.neighbours.mi_cols.div_ceil(2);
22505 let unit_rows = r.neighbours.mi_rows.div_ceil(2);
22506 let (mut y, mut u, mut v) = if hit {
22507 let work = r.work.take();
22508 let wrote = std::mem::take(&mut r.wrote);
22509 // `cdef_adjust_strength` is monotone in the strength it is given,
22510 // so a candidate whose primary strength is no lower and whose
22511 // secondary is zero only if the last one's was writes every unit
22512 // the last one wrote -- and writes it from the same post-deblock
22513 // source, so the samples under it need not be put back first.
22514 // Only while both candidates carry ONE strength pair (`bits ==
22515 // 0`, every scoring candidate) and read the same `cdef_idx` grid.
22516 let superset = |cur: (u8, u8), old: (u8, u8)| cur.0 >= old.0 && (cur.1 != 0 || old.1 == 0);
22517 let (skip_y, skip_uv) = match (final_pass, &r.work_cdef) {
22518 (None, Some(old)) if old.bits == 0 && cdef.bits == 0 => (
22519 superset(
22520 (cdef.y_pri_strength[0], cdef.y_sec_strength[0]),
22521 (old.y_pri_strength[0], old.y_sec_strength[0]),
22522 ),
22523 superset(
22524 (cdef.uv_pri_strength[0], cdef.uv_sec_strength[0]),
22525 (old.uv_pri_strength[0], old.uv_sec_strength[0]),
22526 ),
22527 ),
22528 _ => (false, false),
22529 };
22530 let (deblocked, scratch) = (&r.deblocked, &mut r.scratch);
22531 let (_, dy, du, dv) = deblocked.as_ref().expect("just matched");
22532 match work {
22533 Some((mut wy, mut wu, mut wv)) => {
22534 if !skip_y {
22535 restore_written(&mut wy, dy, &wrote, 1, unit_cols, 8);
22536 }
22537 if !skip_uv {
22538 restore_written(&mut wu, du, &wrote, 2, unit_cols, 4);
22539 restore_written(&mut wv, dv, &wrote, 2, unit_cols, 4);
22540 }
22541 (wy, wu, wv)
22542 }
22543 None => (pooled(dy, scratch), pooled(du, scratch), pooled(dv, scratch)),
22544 }
22545 } else {
22546 // The levels moved, so the cached deblocked planes are dead:
22547 // their buffers are this candidate's working copies.
22548 for plane in r.work.take().into_iter().flat_map(|(a, b, c)| [a, b, c]) {
22549 r.scratch.push(plane.data.into_owned());
22550 }
22551 r.work_cdef = None;
22552 if let Some((_, dy, du, dv)) = r.deblocked.take() {
22553 r.scratch.push(dy.data.into_owned());
22554 r.scratch.push(du.data.into_owned());
22555 r.scratch.push(dv.data.into_owned());
22556 }
22557 let (cap_y, cap_u, cap_v, scratch) = (&r.y, &r.u, &r.v, &mut r.scratch);
22558 let (mut y, mut u, mut v) =
22559 (pooled(cap_y, scratch), pooled(cap_u, scratch), pooled(cap_v, scratch));
22560 let _t = crate::par::timer(crate::par::S_DEBLOCK);
22561 apply_deblock(
22562 &mut y,
22563 &mut u,
22564 &mut v,
22565 loop_filter,
22566 &r.neighbours,
22567 r.frame_width,
22568 r.frame_height,
22569 fctx,
22570 );
22571 // lane-av1cap2: an all-zero-strength CDEF writes no sample at
22572 // all ([`cdef_all_zero`]'s own early return), so THESE planes
22573 // are already this candidate's output -- they become the
22574 // deblock cache at the end instead of being copied into it
22575 // here, which is three ~6 MB copies less per candidate that
22576 // moves the levels (the whole deblocking half of the search:
22577 // its CDEF strengths are still (0,0)).
22578 share = cdef_all_zero(cdef);
22579 if !share {
22580 let scratch = &mut r.scratch;
22581 r.deblocked = Some((
22582 *loop_filter,
22583 pooled(&y, scratch),
22584 pooled(&u, scratch),
22585 pooled(&v, scratch),
22586 ));
22587 }
22588 (y, u, v)
22589 };
22590 drop(cpt);
22591 // The winner's `cdef_idx` literals live in the re-coded tile, which
22592 // nothing parses on this path -- hand the grid the encoder already
22593 // chose straight to the filter (`bits == 0` leaves the grid the last
22594 // parse sized, which is what every scoring candidate reads).
22595 if let Some((grid, _)) = final_pass.filter(|(g, _)| !g.is_empty()) {
22596 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = grid.to_vec());
22597 }
22598 let ct = crate::par::timer(crate::par::S_CDEF);
22599 let mut wrote = std::mem::take(&mut r.wrote);
22600 wrote.clear();
22601 wrote.resize(unit_cols * unit_rows, 0);
22602 r.work_cdef = Some(*cdef);
22603 let pre = r.deblocked.as_ref().map(|(_, dy, du, dv)| {
22604 (dy.data.as_ref(), du.data.as_ref(), dv.data.as_ref())
22605 });
22606 apply_cdef(
22607 &mut y, &mut u, &mut v, cdef, &r.neighbours, (r.frame_width, r.frame_height), fctx,
22608 pre,
22609 Some(&mut wrote),
22610 );
22611 drop(ct);
22612 if final_pass.is_some_and(|(_, want)| want) {
22613 // The loop-restoration search runs on the stages above (where
22614 // post-CDEF stands in for post-deblock, as the capture decode
22615 // had it); the FILTER this frame ends up applying reads the
22616 // real post-deblock rows, which is what the decoder does.
22617 let snapshot = if share {
22618 // Nothing filtered these planes after the deblock, so they
22619 // are the post-deblock picture themselves.
22620 Some(plane_snapshot(&y, 0))
22621 } else {
22622 r.deblocked.as_ref().map(|(_, dy, ..)| plane_snapshot(dy, 0))
22623 };
22624 let scratch = &mut r.scratch;
22625 r.final_luma = snapshot.map(|d| (pooled(&y, scratch), d));
22626 }
22627 let stages = final_pass.and_then(|(_, want)| {
22628 want.then(|| FilterStages {
22629 deblocked: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
22630 cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
22631 stride: [y.width, u.width, v.width],
22632 })
22633 });
22634 // The capture only happens on the shape whose tail is the two
22635 // filter calls and the crop (no superres, no loop restoration), so
22636 // what is left is that crop -- byte for byte the cropped return path
22637 // of the decode this replaces, wide-margin stash included.
22638 //
22639 // lane-av1fpar: the crop is why this arm exists at all. The capture
22640 // used to demand `frame == plane` dimensions, which no editor size
22641 // meets (1080 and 1608 both pad to a superblock row), so every
22642 // candidate of every frame at those sizes fell through to a full
22643 // re-decode -- 57% of a 1080p frame's wall.
22644 let (fw, fh) = (r.frame_width, r.frame_height);
22645 if fw == r.width && fh == r.height {
22646 fctx.last_frame_wide_margin.with(|m| *m.borrow_mut() = None);
22647 r.wrote = Vec::new();
22648 r.work_cdef = None;
22649 if share {
22650 let picture = Picture {
22651 width: r.width,
22652 height: r.height,
22653 y: y.data.to_vec(),
22654 u: u.data.to_vec(),
22655 v: v.data.to_vec(),
22656 };
22657 r.deblocked = Some((*loop_filter, y, u, v));
22658 return Some((picture, stages));
22659 }
22660 return Some((
22661 Picture {
22662 width: r.width,
22663 height: r.height,
22664 y: y.data.into_owned(),
22665 u: u.data.into_owned(),
22666 v: v.data.into_owned(),
22667 },
22668 stages,
22669 ));
22670 }
22671 let crop = |plane: &PlaneBuf<'_>, w: usize, h: usize| -> Vec<u16> {
22672 let mut out = Vec::with_capacity(w * h);
22673 for row in 0..h {
22674 out.extend(plane.data[row * plane.width..][..w].iter().copied());
22675 }
22676 out
22677 };
22678 let (tw, th) = (r.true_width, r.true_height);
22679 fctx.last_frame_wide_margin.with(|m| {
22680 *m.borrow_mut() = (tw > fw || th > fh).then(|| Picture {
22681 width: tw,
22682 height: th,
22683 y: crop(&y, tw, th),
22684 u: crop(&u, tw.div_ceil(2), th.div_ceil(2)),
22685 v: crop(&v, tw.div_ceil(2), th.div_ceil(2)),
22686 });
22687 });
22688 let out = Picture {
22689 width: fw,
22690 height: fh,
22691 y: crop(&y, fw, fh),
22692 u: crop(&u, fw.div_ceil(2), fh.div_ceil(2)),
22693 v: crop(&v, fw.div_ceil(2), fh.div_ceil(2)),
22694 };
22695 // The working planes outlive the crop: either they ARE the
22696 // deblocked planes this candidate's successors reuse, or they go
22697 // back to the pool.
22698 if share {
22699 r.wrote = Vec::new();
22700 r.work_cdef = None;
22701 r.deblocked = Some((*loop_filter, y, u, v));
22702 } else {
22703 // lane-av1speed3: kept whole (post-CDEF samples and all) for the
22704 // next candidate, together with the map of what CDEF wrote.
22705 r.wrote = wrote;
22706 r.work = Some((y, u, v));
22707 }
22708 Some((out, stages))
22709 })
22710}
22711
22712/// lane-av1cap2: the loop-restoration half of the final replay. Once the
22713/// units are chosen the tile is coded a second time to carry them, and that
22714/// re-coded tile used to be DECODED to reach the restored reference frame
22715/// (5.6% of a 4K frame's encode). Loop restoration reads nothing of that
22716/// tile but the per-unit filters the encoder just picked: it is the
22717/// decoder's own [`crate::restoration::apply_loop_restoration_plane`] on
22718/// the post-CDEF plane the final replay produced, with the TRUE
22719/// post-deblock stripe-border rows -- the same call the decoder's
22720/// `apply_loop_restoration` makes, on the same input. Only luma moves: the
22721/// encoder never writes a chroma restoration type other than
22722/// `RESTORE_NONE`, whose kernel hands its input straight back.
22723///
22724/// Returns the cropped luma plane and refreshes the wide-margin stash's own
22725/// luma (restoration writes strictly inside `frame_width x frame_height`,
22726/// so the margin columns past it stand). `None` when nothing was captured
22727/// -- the caller then decodes for real.
22728pub(crate) fn replay_restoration(
22729 lr: &LoopRestorationParams,
22730 units: &[Option<crate::restoration::WienerInfo>],
22731 fctx: &FrameCtx,
22732) -> Option<Vec<u16>> {
22733 #[cfg(test)]
22734 if REPLAY_DISABLED.load(std::sync::atomic::Ordering::Relaxed) {
22735 return None;
22736 }
22737 REPLAY.with_borrow_mut(|slot| {
22738 let r = slot.as_mut()?;
22739 let (cdefed, deblocked) = r.final_luma.as_ref()?;
22740 let (fw, fh) = (r.frame_width, r.frame_height);
22741 let mut grid = crate::restoration::RestorationGrid::new(lr, fw as u32, fh as u32);
22742 let (horz, vert) = (grid.horz_units[0], grid.vert_units[0]);
22743 if horz == 0 || units.len() != horz * vert {
22744 return None;
22745 }
22746 for (i, filter) in units.iter().enumerate() {
22747 if let Some(info) = filter {
22748 grid.set(0, i / horz, i % horz, crate::restoration::UnitFilter::Wiener(*info));
22749 }
22750 }
22751 let stride = cdefed.width;
22752 let mut out = scratch_empty();
22753 crate::restoration::apply_loop_restoration_plane(
22754 &cdefed.data,
22755 &deblocked.data,
22756 stride,
22757 fw,
22758 fh,
22759 0,
22760 lr.frame_restoration_type[0],
22761 lr.loop_restoration_size[0],
22762 &grid,
22763 0,
22764 &mut out,
22765 None,
22766 fctx,
22767 );
22768 fctx.last_frame_wide_margin.with(|m| {
22769 if let Some(p) = m.borrow_mut().as_mut() {
22770 let tw = p.width;
22771 for row in 0..p.height.min(fh) {
22772 let n = tw.min(fw);
22773 p.y[row * tw..][..n].copy_from_slice(&out[row * stride..][..n]);
22774 }
22775 }
22776 });
22777 let mut y = Vec::with_capacity(fw * fh);
22778 for row in 0..fh {
22779 y.extend(out[row * stride..][..fw].iter().copied());
22780 }
22781 scratch_return(out);
22782 Some(y)
22783 })
22784}
22785
22786/// The output crop, taking the plane by value: a frame whose width is
22787/// already superblock-aligned (only its height is padded) has a padded
22788/// buffer whose stride equals the visible width, so the crop is a pure
22789/// truncation of the buffer we already own -- no full-plane copy at all
22790/// (lane-copy: three ~6 MB memmoves per 4K frame on the frame thread's
22791/// serial tail). Any other shape falls back to the row-by-row copy.
22792fn crop_owned(plane: PlaneBuf<'_>, w: usize, h: usize) -> Vec<u16> {
22793 let stride = plane.width;
22794 let mut data = plane.data.into_owned();
22795 if stride == w {
22796 data.truncate(w * h);
22797 return data;
22798 }
22799 let mut out = Vec::with_capacity(w * h);
22800 for row in 0..h {
22801 out.extend(data[row * stride..][..w].iter().copied());
22802 }
22803 out
22804}
22805
22806/// Hands a buffer back to the pool; the capacity is what is worth keeping.
22807/// Over [`SCRATCH_CAP`] the buffer is dropped (freed) instead -- the cap is
22808/// what keeps a pool shared by every thread from being an unbounded stash.
22809fn scratch_return(v: Vec<u16>) {
22810 let mut p = PLANE_SCRATCH.lock().unwrap();
22811 if p.len() < SCRATCH_CAP {
22812 p.push(v);
22813 }
22814}
22815
22816/// One CDEF mi-row band, as a real function rather than the body of the
22817/// `run_bands` closure: inside the closure the destination planes are
22818/// `&mut` references derived from a `par::Shared` raw pointer in the same
22819/// scope as the `src_*` snapshot reads, so LLVM cannot tell the two apart and
22820/// re-loads through them on every tap. Reference parameters restore `noalias`
22821/// (lane-perf11 (a): -x% instructions at one filter thread).
22822#[allow(clippy::too_many_arguments)]
22823fn cdef_band(
22824 r_lo: usize,
22825 r_hi: usize,
22826 y: &mut PlaneBuf<'static>,
22827 u: &mut PlaneBuf<'static>,
22828 v: &mut PlaneBuf<'static>,
22829 src_y: &[u16],
22830 src_u: &[u16],
22831 src_v: &[u16],
22832 cdef: &CdefParams,
22833 skip_grid: &Neighbours,
22834 idx_grid: &[u8],
22835 sb_cols: usize,
22836 coeff_shift: i32,
22837 damping: i32,
22838 damping_uv: i32,
22839 (frame_w, frame_h): (usize, usize),
22840 fctx: &crate::decode::FrameCtx,
22841 // lane-av1speed3: one byte per 8x8 CDEF unit of the WHOLE frame (stride
22842 // `mi_cols.div_ceil(2)`), set for every unit this band actually filters.
22843 // Bit 0 = this unit's LUMA square was filtered, bit 1 = its chroma ones.
22844 // `cdef_adjust_strength` zeroes a unit's primary strength off its own
22845 // variance, so which units a candidate writes is not a function of its
22846 // strengths alone -- the encoder's filter replay reuses one destination
22847 // plane across candidates and needs the map to restore it.
22848 mut wrote: Option<&mut [u8]>,
22849) {
22850 let unit_cols = skip_grid.mi_cols.div_ceil(2);
22851 let strength_idx = |mi_r: usize, mi_c: usize| -> usize {
22852 if sb_cols == 0 {
22853 return 0;
22854 }
22855 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
22856 idx_grid.get(sb_r * sb_cols + sb_c).copied().unwrap_or(0) as usize
22857 };
22858 // One scratch window per plane kind, reused by every unit (8x8 luma and
22859 // 4x4 chroma, each grown by the [`CDEF_BORDER`] tap ring).
22860 // 256 entries, not the (bw + 4) x (bh + 4) samples themselves: the
22861 // AVX2 kernel taps the window in place with two-row loads that reach
22862 // past the last sample, and the tail stays zero for every unit.
22863 let mut win_y = [0i16; 256];
22864 let mut win_uv = [0i16; 256];
22865 let mut mi_r = r_lo;
22866 while mi_r < r_hi {
22867 let mut mi_c = 0usize;
22868 while mi_c < skip_grid.mi_cols {
22869 if skip_grid.is_skip_txfm(mi_r, mi_c) {
22870 hit!(CDEF_SKIPPED_UNITS);
22871 }
22872 if !skip_grid.is_skip_txfm(mi_r, mi_c) {
22873 let sidx = strength_idx(mi_r, mi_c);
22874 let (ox, oy) = (mi_c * 4, mi_r * 4);
22875 // Nothing to do for this unit at all: the direction search is
22876 // only ever consumed through a strength, so a unit whose four
22877 // strengths are zero never needs its 8x8 window gathered.
22878 if cdef.y_pri_strength[sidx] == 0
22879 && cdef.y_sec_strength[sidx] == 0
22880 && cdef.uv_pri_strength[sidx] == 0
22881 && cdef.uv_sec_strength[sidx] == 0
22882 {
22883 mi_c += 2;
22884 continue;
22885 }
22886 let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height);
22887 cdef_gather(src_y, y_stride, y_true_w, y_true_h, ox, oy, 8, 8, &mut win_y);
22888 // lane-cdef r1: the direction search reads the SAME padded
22889 // block the taps do -- libaom runs `cdef_find_dir` on the
22890 // prepared filter block (`cdef_block.c:296-320` over
22891 // `cdef_prepare_fb`'s buffer, `cdef.c:249-256`), whose columns
22892 // and rows past the mi-rounded frame extent are CDEF_VERY_LARGE.
22893 // Clamping to the last real sample instead made every straddling
22894 // edge 8x8 (odd `mi_cols`/`mi_rows`) pick a different var, hence
22895 // a different `adjust_strength`, hence a +-1 band at the crop edge.
22896 let (dir, var) = cdef_find_dir(&win_y, 8 + 2 * CDEF_BORDER, coeff_shift);
22897
22898 // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0`
22899 // -- each plane zeroes the shared direction when *its own*
22900 // frame-level primary strength is 0, independent of the
22901 // per-block adjusted `t` and of the other plane's strength.
22902 let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift;
22903 let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift;
22904 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
22905 let t = cdef_adjust_strength(y_pri_strength, var);
22906 // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit.
22907 if crate::envflags::env_flag!("EC_AV1_CDEF_DBG") {
22908 eprintln!(
22909 "EC_CDEF mi_r={mi_r} mi_c={mi_c} x={ox} y={oy} sidx={sidx} dir={dir} var={var} t={t} pri={y_pri_strength} sec={y_sec_strength} damp={damping}"
22910 );
22911 }
22912 let enable_primary = t != 0;
22913 let enable_secondary = y_sec_strength != 0;
22914 if (ox + 8 > frame_w || oy + 8 > frame_h)
22915 && (enable_primary
22916 || enable_secondary
22917 || cdef.uv_pri_strength[sidx] != 0
22918 || cdef.uv_sec_strength[sidx] != 0)
22919 {
22920 hit!(CDEF_STRADDLE_UNITS);
22921 }
22922 if enable_primary || enable_secondary {
22923 cdef_filter_block(
22924 &win_y,
22925 y,
22926 ox,
22927 oy,
22928 8,
22929 8,
22930 t,
22931 y_sec_strength,
22932 y_dir,
22933 damping,
22934 damping,
22935 enable_primary,
22936 enable_secondary,
22937 coeff_shift, fctx,
22938 );
22939 }
22940
22941 let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift;
22942 let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift;
22943 let uv_dir = if t_uv != 0 { dir } else { 0 };
22944 let enable_primary_uv = t_uv != 0;
22945 let enable_secondary_uv = uv_sec_strength != 0;
22946 if let Some(w) = wrote.as_deref_mut() {
22947 let mark = u8::from(enable_primary || enable_secondary)
22948 | (u8::from(enable_primary_uv || enable_secondary_uv) << 1);
22949 w[(mi_r / 2) * unit_cols + mi_c / 2] = mark;
22950 }
22951 if enable_primary_uv || enable_secondary_uv {
22952 let (cox, coy) = (ox / 2, oy / 2);
22953 for (plane, src_p) in [(&mut *u, src_u), (&mut *v, src_v)] {
22954 let (tw, th) = (plane.true_width, plane.true_height);
22955 let stride = plane.width;
22956 cdef_gather(src_p, stride, tw, th, cox, coy, 4, 4, &mut win_uv);
22957 cdef_filter_block(
22958 &win_uv,
22959 plane,
22960 cox,
22961 coy,
22962 4,
22963 4,
22964 t_uv,
22965 uv_sec_strength,
22966 uv_dir,
22967 damping_uv,
22968 damping_uv,
22969 enable_primary_uv,
22970 enable_secondary_uv,
22971 coeff_shift, fctx,
22972 );
22973 }
22974 }
22975 }
22976 mi_c += 2;
22977 }
22978 mi_r += 2;
22979 }
22980}
22981
22982
22983// --- lane-pipefilt: the per-superblock-row loop filter pipeline ----------
22984//
22985// DEPENDENCY SHAPE (derived from this decoder's own whole-frame pass order:
22986// every plane's vertical deblock edges, then every plane's horizontal ones,
22987// then CDEF, then -- unpipelined -- superres and loop restoration).
22988// A band is 64 luma rows, one superblock row (a 128 superblock is two).
22989//
22990// * recon: intra prediction of band r+1 reads the UNFILTERED bottom rows of
22991// band r, so no filter may touch band r before band r+1 is reconstructed.
22992// Hence V(r) waits for `ready >= r + 2`.
22993// * V(r) (vertical edges whose 4-sample groups live in band r's rows) then
22994// H(r-1) (horizontal edges at `y` in band r-1, including the one at its
22995// own top boundary): the edge at `y = r*64` reads/writes 6-7 rows either
22996// side of the band boundary, so H(r-1)'s last edge reaches into band r,
22997// which the whole-frame order has already vertical-filtered -- V(r)
22998// before H(r-1) reproduces exactly that.
22999// * post-deblock finality: band j's own bottom rows are still rewritten by
23000// H(j+1)'s first edge, so band j's post-deblock snapshot (`snap`) may
23001// only be taken after H(j+1).
23002// * CDEF(j) reads the post-deblock picture 2-3 rows across its 64x64
23003// boundaries, i.e. bands j-1..j+1, so it runs after snap(j+1).
23004//
23005// One iteration k therefore runs V(k), H(k-1), snap(k-2), CDEF(k-3), and the
23006// loop runs k in `0..nbands+3` so the tail drains. Loop restoration (and the
23007// superres upscale, which is a whole-frame refusal for this path) stay in the
23008// frame thread's tail; the snapshot the pipeline built is what LR reads.
23009struct PipeQ {
23010 /// Bands whose reconstruction the frame thread has released.
23011 ready: usize,
23012 abort: bool,
23013}
23014
23015pub(crate) struct PipeSync {
23016 m: std::sync::Mutex<PipeQ>,
23017 cv: std::sync::Condvar,
23018}
23019
23020impl PipeSync {
23021 fn new() -> Self {
23022 Self {
23023 m: std::sync::Mutex::new(PipeQ { ready: 0, abort: false }),
23024 cv: std::sync::Condvar::new(),
23025 }
23026 }
23027 fn note(&self, ready: usize) {
23028 let mut q = self.m.lock().unwrap();
23029 if ready > q.ready {
23030 q.ready = ready;
23031 self.cv.notify_all();
23032 }
23033 }
23034 /// Releases every remaining band (`abort` = the tile decoder is bailing
23035 /// out, so the worker returns instead of finishing the frame).
23036 fn close(&self, all: usize, abort: bool) {
23037 let mut q = self.m.lock().unwrap();
23038 q.ready = q.ready.max(all);
23039 q.abort |= abort;
23040 self.cv.notify_all();
23041 }
23042 /// `false` when the frame was aborted.
23043 fn wait_for(&self, want: usize) -> bool {
23044 let mut q = self.m.lock().unwrap();
23045 while q.ready < want && !q.abort {
23046 q = self.cv.wait(q).unwrap();
23047 }
23048 !q.abort
23049 }
23050}
23051
23052/// Band `j`'s rows of `src` copied into the pipeline's post-deblock
23053/// snapshot. `full` mirrors [`apply_cdef`]'s whole-plane pre-CDEF copy;
23054/// otherwise only the four rows around each stripe boundary that loop
23055/// restoration reads are taken, exactly [`plane_snapshot`]'s rows.
23056fn snap_band(dst: &mut [u16], src: &PlaneBuf<'_>, ss_y: u32, y_lo: usize, y_hi: usize, full: bool) {
23057 let w = src.width;
23058 if w == 0 {
23059 return;
23060 }
23061 let rows = src.data.len() / w;
23062 let (lo, hi) = (y_lo.min(rows), y_hi.min(rows));
23063 if lo >= hi {
23064 return;
23065 }
23066 if full {
23067 dst[lo * w..hi * w].copy_from_slice(&src.data[lo * w..hi * w]);
23068 return;
23069 }
23070 let stripe_h = 64usize >> ss_y;
23071 let offset = 8usize >> ss_y;
23072 let mut b = stripe_h - offset;
23073 while b < rows {
23074 let (a, e) = ((b - 2).max(lo), (b + 2).min(rows).min(hi));
23075 if a < e {
23076 dst[a * w..e * w].copy_from_slice(&src.data[a * w..e * w]);
23077 }
23078 b += stripe_h;
23079 }
23080}
23081
23082/// Everything the pipeline worker needs that is not a plane or a grid.
23083struct PipeCfg<'a> {
23084 lf: &'a LoopFilterParams,
23085 cdef: &'a CdefParams,
23086 /// `(cdef_idx_grid.as_ptr(), len)` -- the frame thread keeps filling the
23087 /// entries of the superblock rows the pipeline has not reached; the Vec
23088 /// itself is sized once per frame, so the pointer stays valid.
23089 idx_grid: (*const u8, usize),
23090 sb_cols: usize,
23091 frame_w: usize,
23092 frame_h: usize,
23093 nbands: usize,
23094 cdef_on: bool,
23095 snap_on: bool,
23096}
23097
23098// SAFETY: the `*const u8` is a read-only view of a Vec that is allocated once
23099// per frame and only ever written at indices the pipeline is three bands
23100// behind (see this module's dependency note).
23101#[allow(unsafe_code)]
23102unsafe impl Send for PipeCfg<'_> {}
23103
23104#[allow(unsafe_code)]
23105#[allow(clippy::too_many_arguments)]
23106fn pipe_run(
23107 sync: &PipeSync,
23108 sy: crate::par::Shared<'_, PlaneBuf<'static>>,
23109 su: crate::par::Shared<'_, PlaneBuf<'static>>,
23110 sv: crate::par::Shared<'_, PlaneBuf<'static>>,
23111 sn: crate::par::Shared<'_, Neighbours>,
23112 cfg: PipeCfg<'_>,
23113 snap: &mut Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
23114 lr_sync: Option<&PipeSync>,
23115 fctx: &crate::decode::FrameCtx,
23116) {
23117 // SAFETY: the frame thread parses (and reconstructs) bands the pipeline
23118 // is at least two behind, and the two ranges never meet -- see the
23119 // dependency note above and `Shared`'s own corner-cut.
23120 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
23121 let n: &Neighbours = unsafe { sn.get() };
23122 let idx_grid = unsafe { std::slice::from_raw_parts(cfg.idx_grid.0, cfg.idx_grid.1) };
23123 let coeff_shift = i32::from(bit_depth(fctx)) - 8;
23124 let damping = i32::from(cfg.cdef.damping) + coeff_shift;
23125 let damping_uv = (damping - 1).max(0);
23126 let (fw, fh) = (cfg.frame_w, cfg.frame_h);
23127 let nb = cfg.nbands;
23128 for k in 0..nb + 3 {
23129 if !sync.wait_for((k + 2).min(nb)) {
23130 if let Some(ls) = lr_sync {
23131 ls.close(nb, true);
23132 }
23133 return;
23134 }
23135 if k < nb {
23136 deblock_span(y, u, v, cfg.lf, n, fw, fh, k * 64, (k + 1) * 64, false, fctx);
23137 }
23138 if k >= 1 && k - 1 < nb {
23139 deblock_span(y, u, v, cfg.lf, n, fw, fh, (k - 1) * 64, k * 64, true, fctx);
23140 }
23141 if cfg.snap_on && k >= 2 && k - 2 < nb {
23142 let j = k - 2;
23143 if let Some((sy2, su2, sv2)) = snap.as_mut() {
23144 snap_band(sy2.data.to_mut(), y, 0, j * 64, (j + 1) * 64, cfg.cdef_on);
23145 snap_band(su2.data.to_mut(), u, 1, j * 32, (j + 1) * 32, cfg.cdef_on);
23146 snap_band(sv2.data.to_mut(), v, 1, j * 32, (j + 1) * 32, cfg.cdef_on);
23147 }
23148 }
23149 if cfg.cdef_on && k >= 3 && k - 3 < nb {
23150 let j = k - 3;
23151 if let Some((sy2, su2, sv2)) = snap.as_ref() {
23152 cdef_rows(
23153 y, u, v, &sy2.data, &su2.data, &sv2.data, cfg.cdef, n, idx_grid, cfg.sb_cols,
23154 coeff_shift, damping, damping_uv, (fw, fh), j * 16, (j + 1) * 16, fctx,
23155 None,
23156 );
23157 }
23158 }
23159 // lane-pipefilt2: CDEF bands `0..=k-3` are now complete -- release
23160 // them to the loop restoration worker.
23161 if let Some(ls) = lr_sync {
23162 ls.note(k.saturating_sub(2));
23163 }
23164 }
23165 if let Some(ls) = lr_sync {
23166 ls.close(nb, false);
23167 }
23168}
23169
23170/// The pipeline's loop restoration worker, a second task alongside
23171/// [`pipe_run`]: restoration-unit row `r` writes `out` rows
23172/// `v_start..v_end`, reads post-CDEF rows only inside that span and the
23173/// post-deblock snapshot at most two rows past `v_end` (see
23174/// `restoration::lr_src_row`), so it is ready as soon as CDEF band
23175/// `(v_end - 1) / 64` is done -- `pipe_run` runs that band at its own
23176/// iteration `band + 3` and the snapshot band one iteration earlier, so the
23177/// snapshot condition `(v_end + 1) / 64 <= band + 1` is implied, the two row
23178/// indices being at most one band apart. Running it as its own worker (not
23179/// as a fourth step inside `pipe_run`'s loop) keeps it OFF the deblock/CDEF
23180/// critical path: serialised into that loop it measured ~1% slower than the
23181/// whole-frame form, which at least ran its RU rows across the filter pool.
23182#[allow(unsafe_code)]
23183fn pipe_run_lr(
23184 sync: &PipeSync,
23185 sy: crate::par::Shared<'_, PlaneBuf<'static>>,
23186 su: crate::par::Shared<'_, PlaneBuf<'static>>,
23187 sv: crate::par::Shared<'_, PlaneBuf<'static>>,
23188 snap: crate::par::Shared<'_, Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>>,
23189 cfg: LrCfg<'_>,
23190 fctx: &crate::decode::FrameCtx,
23191) {
23192 // SAFETY: this worker only reads bands `pipe_run` has finished filtering
23193 // and writes its own `out` buffers; the final swap happens after the
23194 // last CDEF band, which is `pipe_run`'s last plane write.
23195 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
23196 let snap = unsafe { snap.get() };
23197 let grid = unsafe { &*cfg.lr_grid };
23198 let (fw, fh) = (cfg.frame_w, cfg.frame_h);
23199 let dims = [
23200 (fw, fh, 0u32, y.width, y.data.len()),
23201 (fw.div_ceil(2), fh.div_ceil(2), 1, u.width, u.data.len()),
23202 (fw.div_ceil(2), fh.div_ceil(2), 1, v.width, v.data.len()),
23203 ];
23204 let mut planes: Vec<LrPlane> = Vec::new();
23205 for (p, &(pw, ph, ss, stride, len)) in dims.iter().enumerate() {
23206 let rows = crate::restoration::lr_unit_rows(
23207 ph,
23208 cfg.lr.loop_restoration_size[p],
23209 ss,
23210 cfg.lr.frame_restoration_type[p],
23211 );
23212 if rows.is_empty() {
23213 continue;
23214 }
23215 planes.push(LrPlane { p, out: scratch_sized(len), rows, next: 0, pw, ph, ss, stride });
23216 }
23217 for band in 0..cfg.nbands {
23218 if !sync.wait_for(band + 1) {
23219 return;
23220 }
23221 let Some((sy2, su2, sv2)) = snap.as_ref() else { return };
23222 for lp in &mut planes {
23223 let stripe = 64usize >> lp.ss;
23224 let r_lo = lp.next;
23225 while lp.next < lp.rows.len() && (lp.rows[lp.next].1 as usize - 1) / stripe <= band {
23226 lp.next += 1;
23227 }
23228 if lp.next == r_lo {
23229 continue;
23230 }
23231 let (src, deb) = match lp.p {
23232 0 => (&y.data, &sy2.data),
23233 1 => (&u.data, &su2.data),
23234 _ => (&v.data, &sv2.data),
23235 };
23236 crate::restoration::apply_loop_restoration_plane(
23237 src,
23238 deb,
23239 lp.stride,
23240 lp.pw,
23241 lp.ph,
23242 lp.ss,
23243 cfg.lr.frame_restoration_type[lp.p],
23244 cfg.lr.loop_restoration_size[lp.p],
23245 grid,
23246 lp.p,
23247 &mut lp.out,
23248 Some((r_lo, lp.next)),
23249 fctx,
23250 );
23251 }
23252 }
23253 // The RU rows partition `0..plane_h`; the mi-rounded rows below it are
23254 // untouched by restoration and copied here, then the restored plane
23255 // takes the picture's place (the whole-frame path's own final swap).
23256 for mut lp in planes {
23257 let buf: &mut PlaneBuf<'static> = match lp.p {
23258 0 => &mut *y,
23259 1 => &mut *u,
23260 _ => &mut *v,
23261 };
23262 let tail = lp.ph * lp.stride;
23263 if tail < buf.data.len() {
23264 lp.out[tail..].copy_from_slice(&buf.data[tail..]);
23265 }
23266 scratch_return(
23267 std::mem::replace(&mut buf.data, std::borrow::Cow::Owned(lp.out)).into_owned(),
23268 );
23269 }
23270}
23271
23272/// Everything [`pipe_run_lr`] needs beyond the planes.
23273struct LrCfg<'a> {
23274 lr: &'a LoopRestorationParams,
23275 /// Sized once per frame by `RestorationGrid::new`; the parse thread is
23276 /// many bands ahead of every unit this worker reads.
23277 lr_grid: *const crate::restoration::RestorationGrid,
23278 frame_w: usize,
23279 frame_h: usize,
23280 nbands: usize,
23281}
23282
23283// SAFETY: as `PipeCfg`'s -- a read-only view of a per-frame allocation.
23284#[allow(unsafe_code)]
23285unsafe impl Send for LrCfg<'_> {}
23286
23287/// One plane's pipelined loop restoration state (see [`pipe_run`]).
23288struct LrPlane {
23289 p: usize,
23290 /// The restored plane, built band by band and swapped in at the end.
23291 out: Vec<u16>,
23292 rows: Vec<(u32, u32)>,
23293 /// The first RU row not yet restored.
23294 next: usize,
23295 pw: usize,
23296 ph: usize,
23297 ss: u32,
23298 stride: usize,
23299}
23300
23301/// The pipeline's handle on the frame thread: [`PipeGuard::note`] releases
23302/// bands as reconstruction completes, [`PipeGuard::finish`] drains it, and
23303/// `Drop` aborts it on any `?` out of the tile decoder (the worker holds raw
23304/// pointers into the frame's planes, so it may not outlive them).
23305struct PipeGuard<'a> {
23306 sync: std::sync::Arc<PipeSync>,
23307 batch: Option<crate::par::Batch<'a>>,
23308 nbands: usize,
23309 /// The loop restoration worker's own gate, aborted with the first one.
23310 lr_sync: Option<std::sync::Arc<PipeSync>>,
23311}
23312
23313impl PipeGuard<'_> {
23314 fn note(&self, bands: usize) {
23315 self.sync.note(bands);
23316 }
23317 fn finish(&mut self) {
23318 self.sync.close(self.nbands, false);
23319 // Dropping the batch waits the worker out.
23320 self.batch.take();
23321 }
23322}
23323
23324impl Drop for PipeGuard<'_> {
23325 fn drop(&mut self) {
23326 self.sync.close(self.nbands, true);
23327 if let Some(ls) = &self.lr_sync {
23328 ls.close(self.nbands, true);
23329 }
23330 }
23331}
23332
23333/// Leading superblock rows of the live tile's wavefront that are fully
23334/// reconstructed: parsed out to the last column and with every job that
23335/// carried a write finished. 0 when reconstruction is inline (no wavefront),
23336/// where the caller uses the parse position instead.
23337fn wave_rows_complete(fctx: &crate::decode::FrameCtx) -> usize {
23338 let st = fctx.wave.with(|w| w.borrow().clone());
23339 let Some(st) = st else { return 0 };
23340 let q = st.q.lock().unwrap();
23341 let mut n = 0;
23342 while n < q.rows.len() {
23343 if q.last_sub[n] < st.last_col as isize || q.done[n] < q.last_push[n] {
23344 break;
23345 }
23346 n += 1;
23347 }
23348 n
23349}
23350
23351/// Frames whose loop filters ran pipelined, and frames that took the
23352/// whole-frame path instead (`EC_AV1_WAVE_STATS`).
23353static PIPE_FRAMES: AtomicU64 = AtomicU64::new(0);
23354static PIPE_WHOLE: AtomicU64 = AtomicU64::new(0);
23355
23356/// Whether this frame's filters may run per superblock row. Everything that
23357/// reads the picture out of band order, or the pipeline's own inputs out of
23358/// row order, keeps the whole-frame path: superres (a between-CDEF-and-LR
23359/// whole-plane resample), segmentation (the deblocker reads `seg_ids`, which
23360/// the parse thread is still filling), delta_lf, more than one tile COLUMN (a
23361/// frame row is only complete after the last tile column's own parse), and
23362/// every pixel-dump / stage-skip debug flag, whose whole point is the
23363/// unpipelined stage boundary. The pipeline also stays off unless some
23364/// threading is on -- at (1, 1) the filters would run on a worker thread for
23365/// nothing and the crate's `thread_local!` gate counters would miss them.
23366fn pipe_filters_ok(fctx: &crate::decode::FrameCtx, tile_cols: u32, lf_present: bool) -> bool {
23367 if crate::envflags::var("EC_AV1_PIPE_FILTERS").map(|v| v.trim() == "0").unwrap_or(false) {
23368 return false;
23369 }
23370 if crate::par::filter_threads() == 1 && crate::par::recon_threads() == 1 {
23371 return false;
23372 }
23373 if tile_cols != 1 || lf_present || superres(fctx).is_some() {
23374 return false;
23375 }
23376 if fctx.seg.with(|s| s.borrow().enabled) {
23377 return false;
23378 }
23379 !(crate::envflags::is_set("EC_AV1_PREFILT_DUMP")
23380 || crate::envflags::is_set("EC_AV1_PREFILT_DUMP16")
23381 || crate::envflags::is_set("EC_AV1_PREFILT_WIDE_DUMP")
23382 || crate::envflags::is_set("EC_AV1_POSTDEBLOCK_DUMP")
23383 || crate::envflags::is_set("EC_AV1_POSTDEBLOCK_DUMP16")
23384 || crate::envflags::is_set("EC_AV1_POSTCDEF_DUMP")
23385 || crate::envflags::is_set("EC_AV1_POSTCDEF_DUMP16")
23386 || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_DEBLOCK")
23387 || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_CDEF")
23388 || crate::envflags::is_set("EC_AV1_DEBUG_SKIP_LR")
23389 || crate::envflags::is_set("EC_AV1_DEBUG_CDEF_BAND")
23390 || crate::envflags::is_set("EC_AV1_DEBLOCK_TRACE")
23391 || crate::envflags::is_set("EC_AV1_DEBLOCK_TRACE_V"))
23392}
23393
23394/// lane-cdefstrip r1 instrument, run for every frame BEFORE either of
23395/// [`apply_cdef`]'s early returns (lane-pipefilt: the pipelined path
23396/// never enters `apply_cdef`, so it calls this itself).
23397fn cdef_scan_counters(skip_grid: &Neighbours) {
23398 let _ = skip_grid;
23399 hit_do! {
23400 let mut r = 0usize;
23401 while r < skip_grid.mi_rows {
23402 let mut c = 0usize;
23403 while c < skip_grid.mi_cols {
23404 if (0..2).any(|rr| {
23405 (0..2).any(|cc| {
23406 !skip_grid
23407 .blk_grid
23408 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
23409 .map_or(true, |x| x.written)
23410 })
23411 }) {
23412 hit!(CDEF_UNWRITTEN_SKIP_UNITS);
23413 if crate::envflags::env_flag!("EC_AV1_DEBUG_CDEF_BAND") {
23414 eprintln!("cdef band unwritten at mi ({r},{c}) px ({},{})", r * 4, c * 4);
23415 }
23416 }
23417 let cell = |rr: usize, cc: usize| {
23418 skip_grid
23419 .blk_grid
23420 .get((r + rr) * skip_grid.skip_grid_cols_mi + (c + cc))
23421 .is_some_and(|x| x.skip)
23422 };
23423 let first = cell(0, 0);
23424 if (0..2).any(|rr| (0..2).any(|cc| cell(rr, cc) != first)) {
23425 hit!(CDEF_MIXED_SKIP_UNITS);
23426 }
23427 c += 2;
23428 }
23429 r += 2;
23430 }
23431 }
23432}
23433
23434/// `true` when this frame's CDEF cannot change a sample: `bits == 0` still
23435/// means "no filtering at all" whenever the single (index 0) strength pair
23436/// is all-zero, the fast path every existing gate stream takes.
23437fn cdef_all_zero(cdef: &CdefParams) -> bool {
23438 cdef.bits == 0
23439 && cdef.y_pri_strength[0] == 0
23440 && cdef.y_sec_strength[0] == 0
23441 && cdef.uv_pri_strength[0] == 0
23442 && cdef.uv_sec_strength[0] == 0
23443}
23444
23445/// [`apply_cdef`]'s band loop over the mi rows `r_lo0..r_hi0` only (the
23446/// whole frame when `0..mi_rows`, which is what `apply_cdef` passes).
23447/// `src_*` are the PRE-CDEF planes every unit reads; the writes are this
23448/// row range's own pixels.
23449#[allow(clippy::too_many_arguments)]
23450fn cdef_rows(
23451 y: &mut PlaneBuf<'static>,
23452 u: &mut PlaneBuf<'static>,
23453 v: &mut PlaneBuf<'static>,
23454 src_y: &[u16],
23455 src_u: &[u16],
23456 src_v: &[u16],
23457 cdef: &CdefParams,
23458 skip_grid: &Neighbours,
23459 idx_grid: &[u8],
23460 sb_cols: usize,
23461 coeff_shift: i32,
23462 damping: i32,
23463 damping_uv: i32,
23464 (frame_w, frame_h): (usize, usize),
23465 r_lo0: usize,
23466 r_hi0: usize, fctx: &crate::decode::FrameCtx,
23467 // See [`cdef_band`]. Shared because the bands below write disjoint unit
23468 // ROWS of it, exactly as they write disjoint plane rows.
23469 wrote: Option<crate::par::Shared<'_, [u8]>>,
23470) {
23471 let mi_rows = skip_grid.mi_rows;
23472 let (lo, hi) = (r_lo0.min(mi_rows), r_hi0.min(mi_rows));
23473 if lo >= hi {
23474 return;
23475 }
23476 let (sy, su, sv) = (
23477 crate::par::Shared::new(y),
23478 crate::par::Shared::new(u),
23479 crate::par::Shared::new(v),
23480 );
23481 let cbands: Vec<(usize, usize)> = crate::par::bands((hi - lo).div_ceil(2), crate::par::filter_threads())
23482 .into_iter()
23483 .map(|(a, b)| (lo + a * 2, (lo + b * 2).min(hi)))
23484 .collect();
23485 crate::par::run_bands(&cbands, fctx, |r_lo, r_hi, fctx| {
23486 // SAFETY: this band writes only the plane rows its own mi rows cover,
23487 // disjoint from every other band's (see `Shared`).
23488 #[allow(unsafe_code)]
23489 let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
23490 // SAFETY: this band marks only the unit rows its own mi rows cover,
23491 // disjoint from every other band's (see `Shared`).
23492 #[allow(unsafe_code)]
23493 let wr = wrote.as_ref().map(|w| unsafe { w.get() });
23494 cdef_band(
23495 r_lo,
23496 r_hi,
23497 y,
23498 u,
23499 v,
23500 src_y,
23501 src_u,
23502 src_v,
23503 cdef,
23504 skip_grid,
23505 idx_grid,
23506 sb_cols,
23507 coeff_shift,
23508 damping,
23509 damping_uv,
23510 (frame_w, frame_h),
23511 fctx,
23512 wr,
23513 );
23514 });
23515}
23516
23517fn apply_cdef(
23518 y: &mut PlaneBuf<'static>,
23519 u: &mut PlaneBuf<'static>,
23520 v: &mut PlaneBuf<'static>,
23521 cdef: &CdefParams,
23522 skip_grid: &Neighbours,
23523 // This frame header's own CROPPED luma size, for the straddling-unit
23524 // counter only -- CDEF itself walks the mi-rounded plane.
23525 (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx,
23526 // lane-av1cap: every CDEF unit reads the PRE-CDEF planes, so the filter
23527 // starts by copying all three (~19 MB at 4K). The encoder's filter
23528 // replay already holds an untouched copy of exactly those planes -- its
23529 // post-deblock cache, which is where the working planes were copied FROM
23530 // -- so it hands them straight in and the copy does not happen. `None`
23531 // (every decode) copies as before.
23532 src: Option<(&[u16], &[u16], &[u16])>,
23533 // See [`cdef_band`]: `Some` only from the encoder's filter replay, which
23534 // clears and sizes it (`mi_cols.div_ceil(2) * mi_rows.div_ceil(2)`)
23535 // before the call.
23536 mut wrote: Option<&mut [u8]>,
23537) {
23538 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
23539 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") {
23540 return;
23541 }
23542 cdef_scan_counters(skip_grid);
23543 // `cdef.bits == 0` still means "no filtering at all" whenever the single
23544 // (index 0) strength pair is all-zero -- the fast path every existing
23545 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
23546 // at every index, but that is rare enough not to special-case; the
23547 // per-superblock lookup below degrades to the same index-0 read anyway
23548 // when [`CDEF_IDX_GRID`] was never populated (`bits == 0`).
23549 if cdef_all_zero(cdef) {
23550 return;
23551 }
23552 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
23553 // One entry per superblock (a few hundred at 4K), so this clone is not
23554 // one of the per-frame copies lane-perf6 pooled below.
23555 let idx_grid = fctx.cdef_idx_grid.with(|g| g.borrow().clone());
23556 let owned = src.is_none();
23557 let (src_y, src_u, src_v) = match src {
23558 Some((a, b, c)) => (std::borrow::Cow::Borrowed(a), std::borrow::Cow::Borrowed(b), std::borrow::Cow::Borrowed(c)),
23559 None => (
23560 std::borrow::Cow::Owned(scratch_from(&y.data)),
23561 std::borrow::Cow::Owned(scratch_from(&u.data)),
23562 std::borrow::Cow::Owned(scratch_from(&v.data)),
23563 ),
23564 };
23565 // libaom `av1_cdef_filter_fb`: `pri_strength = level << coeff_shift`,
23566 // `sec_strength <<= coeff_shift`, `damping += coeff_shift - (pli != 0)`.
23567 let coeff_shift = i32::from(bit_depth(fctx)) - 8;
23568 let damping = i32::from(cdef.damping) + coeff_shift;
23569 let damping_uv = (damping - 1).max(0);
23570 // lane-filt1: every CDEF unit reads ONLY the pre-CDEF snapshots
23571 // (`src_y`/`src_u`/`src_v`, immutable here) and writes its own 8x8 luma /
23572 // 4x4 chroma square, so units are independent. Bands are mi ROW bands (2
23573 // mi = 8 luma rows, 4 chroma rows), which makes each band's writes a
23574 // disjoint row range of all three planes.
23575 cdef_rows(
23576 y, u, v, &src_y, &src_u, &src_v, cdef, skip_grid, &idx_grid, sb_cols, coeff_shift,
23577 damping, damping_uv, (frame_w, frame_h), 0, skip_grid.mi_rows, fctx,
23578 wrote.as_deref_mut().map(crate::par::Shared::new),
23579 );
23580 if owned {
23581 scratch_return(src_y.into_owned());
23582 scratch_return(src_u.into_owned());
23583 scratch_return(src_v.into_owned());
23584 }
23585}
23586
23587/// [`FrameCtx::capture_stages`]'s write side, called between CDEF and loop
23588/// restoration on both tile paths: hands the encoder's restoration search the
23589/// two pictures spec 7.17 filters from. `deblocked` is the decoder's own
23590/// stripe-boundary snapshot ([`plane_snapshot`], only the rows LR reads), so
23591/// a capture is worth three plane copies and nothing else -- and when the
23592/// capture flag is off (every decode but that search) it is worth a bool.
23593fn capture_stages(
23594 y: &PlaneBuf<'_>,
23595 u: &PlaneBuf<'_>,
23596 v: &PlaneBuf<'_>,
23597 deblocked: Option<&(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
23598 fctx: &FrameCtx,
23599) {
23600 if !fctx.capture_stages.get() {
23601 return;
23602 }
23603 // Without an active restoration type the decoder took no pre-CDEF
23604 // snapshot; the post-CDEF plane then stands in for it, which is exact
23605 // everywhere but LR's own 3-row stripe borders (the encoder's search
23606 // always asks with a type set, so this is the defensive arm).
23607 let db = |i: usize, p: &PlaneBuf<'_>| match deblocked {
23608 Some((a, b, c)) => [a, b, c][i].data.to_vec(),
23609 None => p.data.to_vec(),
23610 };
23611 *fctx.stages.borrow_mut() = Some(FilterStages {
23612 deblocked: [db(0, y), db(1, u), db(2, v)],
23613 cdefed: [y.data.to_vec(), u.data.to_vec(), v.data.to_vec()],
23614 stride: [y.width, u.width, v.width],
23615 });
23616}
23617
23618/// Spec 7.17: loop restoration, run after [`apply_cdef`] (a sibling lane's
23619/// ordering note: libaom also runs `superres_post_decode` between the two,
23620/// but this decoder never implements super-resolution, so there is nothing
23621/// to interleave). `deblocked_*` is each plane's post-deblock, pre-CDEF
23622/// buffer (the caller clones it before calling [`apply_cdef`]) -- loop
23623/// restoration's stripe-boundary rows read from it instead of the
23624/// CDEF-filtered plane, per `restoration.rs`'s own `lr_sample` doc comment.
23625#[allow(clippy::too_many_arguments)]
23626fn apply_loop_restoration(
23627 y: &mut PlaneBuf<'static>,
23628 u: &mut PlaneBuf<'static>,
23629 v: &mut PlaneBuf<'static>,
23630 deblocked_y: &PlaneBuf<'_>,
23631 deblocked_u: &PlaneBuf<'_>,
23632 deblocked_v: &PlaneBuf<'_>,
23633 lr: &LoopRestorationParams,
23634 grid: &crate::restoration::RestorationGrid,
23635 // lane-golomb r8: this frame header's own (cropped) luma size. Loop
23636 // restoration is the ONE post-decode filter that does NOT run over the
23637 // mi-rounded plane: libaom's `av1_loop_restoration_filter_frame` sizes
23638 // every plane with `av1_get_upsampled_plane_size` -- `plane_w =
23639 // ROUND_POWER_OF_TWO(cm->superres_upscaled_width, ss_x)`, `plane_h =
23640 // ROUND_POWER_OF_TWO(cm->height, ss_y)` (`av1/common/restoration.c:47`)
23641 // -- and asserts it equals the buffer's CROP width
23642 // (`restoration.c:1106`), then `av1_extend_frame(..., plane_w, plane_h,
23643 // ...)` (`restoration.c:1109`) replicates the right/bottom border from
23644 // that cropped edge before any unit is filtered. Deblock and CDEF DO
23645 // walk the mi grid, which is why passing `true_width`/`true_height`
23646 // here went unnoticed until a frame whose size is not a multiple of 8
23647 // (68 -> mi-rounded 72): the LR taps at the last four real columns then
23648 // read this decoder's own decoded samples at columns 68..71 where
23649 // libaom reads column 67 replicated -- +-1 over the straddling band
23650 // (class av1-truesize-lane: true frame size vs mi-rounded).
23651 (frame_w, frame_h): (usize, usize), fctx: &crate::decode::FrameCtx,
23652) {
23653 // lane-svt1 debug rung, env-gated: see `apply_cdef`/`apply_deblock`'s siblings.
23654 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_LR") {
23655 return;
23656 }
23657 let mut out = scratch_empty();
23658 crate::restoration::apply_loop_restoration_plane(
23659 &y.data,
23660 &deblocked_y.data,
23661 y.width,
23662 frame_w,
23663 frame_h,
23664 0,
23665 lr.frame_restoration_type[0],
23666 lr.loop_restoration_size[0],
23667 grid,
23668 0,
23669 &mut out, None, fctx,
23670 );
23671 scratch_return(std::mem::replace(&mut y.data, std::borrow::Cow::Owned(out)).into_owned());
23672 let mut out = scratch_empty();
23673 crate::restoration::apply_loop_restoration_plane(
23674 &u.data,
23675 &deblocked_u.data,
23676 u.width,
23677 frame_w.div_ceil(2),
23678 frame_h.div_ceil(2),
23679 1,
23680 lr.frame_restoration_type[1],
23681 lr.loop_restoration_size[1],
23682 grid,
23683 1,
23684 &mut out, None, fctx,
23685 );
23686 scratch_return(std::mem::replace(&mut u.data, std::borrow::Cow::Owned(out)).into_owned());
23687 let mut out = scratch_empty();
23688 crate::restoration::apply_loop_restoration_plane(
23689 &v.data,
23690 &deblocked_v.data,
23691 v.width,
23692 frame_w.div_ceil(2),
23693 frame_h.div_ceil(2),
23694 1,
23695 lr.frame_restoration_type[2],
23696 lr.loop_restoration_size[2],
23697 grid,
23698 2,
23699 &mut out, None, fctx,
23700 );
23701 scratch_return(std::mem::replace(&mut v.data, std::borrow::Cow::Owned(out)).into_owned());
23702}
23703
23704/// Decodes the payload [`crate::tile::sb_coeff_key_frame_tile`] writes,
23705/// returning the picture it reconstructs to.
23706///
23707/// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
23708/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
23709/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
23710/// `compute_image_size` derives one from the other, but not losslessly: a
23711/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
23712/// what the reconstruction is cropped to on the way out, mirroring
23713/// [`crate::encod

Showing the first 1 MiB of this file. View raw.