forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

block.rs3459 lines, 154.1 KiBHistoryRawDownload
1//! Block decoder: intra mode and angle readers, CFL, the plane reader and decode_block. //! av1split: moved out of `decode/mod.rs`; the items are unchanged apart from visibility. (D17)
2
3use super::*;
4
5#[allow(clippy::too_many_arguments)]
6pub(super) fn read_intra_mode(
7 dec: &mut SymbolDecoder,
8 cdfs: &mut Cdfs,
9 above_mode: usize,
10 left_mode: usize,
11 cfl: bool,
12 side: usize,
13 enable_filter_intra: bool,
14 skip_ctx: usize,
15 allow_screen_content_tools: bool,
16 allow_intrabc: bool,
17 // `Some((palette_mode_ctx, color_cache))` at the call sites this lane's
18 // scope actually reconstructs a palette-Y block for (`av1_get_palette_mode_ctx`
19 // and `av1_get_palette_cache`'s neighbour lookup, [`Neighbours::palette_ctx_and_cache`]);
20 // `None` at the excluded call sites (the 8x8-leaf path), which still read
21 // the `palette_y_mode` symbol at ctx 0 -- matching the bits a real
22 // decoder reads either way -- but refuse by name the moment it fires,
23 // exactly the old behaviour.
24 palette: Option<(usize, &[u16])>,
25 // The U-channel colour cache for a chroma palette read ([`Neighbours::palette_uv_cache`]),
26 // `&[]` at the excluded call sites -- same corner-cut as `palette` above,
27 // no `mode_ctx` needed (`palette_uv_mode_ctx` is this block's own just-read
28 // `use_palette_y`, not a neighbour lookup).
29 palette_uv_cache: &[u16],
30 mi_r: usize,
31 mi_c: usize,
32 fctx: &crate::decode::FrameCtx,
33) -> Result<(
34 bool,
35 usize,
36 i32,
37 usize,
38 i32,
39 Option<(i32, i32)>,
40 Option<usize>,
41 Option<PaletteY>,
42 Option<PaletteUv>,
43)> {
44 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
45 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
46 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
47 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
48 // line against the instrumented aomdec, not just `tell()`.
49 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
50 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
51 if ec_istep {
52 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
53 // (decodemv.c:818), printed at the same point: before the first
54 // mode-info symbol of the block, so a cross-decoder range ladder can
55 // be keyed on the BLOCK, not just on the symbol sequence.
56 eprintln!(
57 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}",
58 dec.debug_state().0
59 );
60 }
61 macro_rules! istep {
62 ($name:literal, $val:expr) => {
63 if ec_istep {
64 let (rng, _) = dec.debug_state();
65 eprintln!(
66 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
67 $name, $val
68 );
69 }
70 };
71 }
72 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
73 // point every square caller routes through (see `read_intra_mode_rect`).
74 let cfl = if cfl && side > 32 {
75 hit!(NOCFL_UV_MODE_HITS);
76 false
77 } else {
78 cfl
79 };
80 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
81 // `skip` when `SegIdPreSkip`, and after it otherwise.
82 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
83 if seg_id_pre_skip(fctx) {
84 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
85 }
86 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
87 if trace {
88 eprintln!(
89 "TRACE skip value={} rng={}",
90 skip as i32,
91 dec.debug_state().0
92 );
93 }
94 istep!("skip", skip as i32);
95 if !seg_id_pre_skip(fctx) {
96 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
97 }
98 // spec order (see the comment below on `read_intrabc_info`): `skip`,
99 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
100 maybe_read_cdef_idx(dec, mi_r, mi_c, (side / MI, side / MI), skip, fctx);
101 istep!("cdef", 0);
102 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
103 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
104 // superblock and skips `delta_q` exactly like a 64 one under a 64 root.
105 let whole_sb = side == sb_mi_cur(fctx) as usize * 4;
106 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
107 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, whole_sb, skip, fctx);
108 istep!("dq", 0);
109 // `read_intrabc_info` (spec 5.11.13, libaom decodemv.c:693, called at
110 // :811 right after `skip_txfm`/`segment_id`/`cdef`/`delta_q` and before
111 // `mbmi->mode` is ever read): a `use_intrabc` symbol only present on an
112 // intra frame whose header set `allow_intrabc`. Actual intra block copy
113 // needs `assign_dv`'s own motion-vector-prediction machinery (`av1_find_mv_refs`,
114 // `av1_find_ref_dv`) this decoder does not carry -- lane-screen scope
115 // draws the line at consuming this one flag symbol and refusing by name
116 // when it fires, so the arithmetic decoder still resyncs for a stream
117 // that merely allows (but never uses) intrabc.
118 if allow_intrabc {
119 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
120 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
121 eprintln!(
122 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}",
123 u8::from(use_intrabc),
124 dec.debug_state().0
125 );
126 }
127 if trace {
128 eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
129 }
130 if use_intrabc {
131 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (side / MI, side / MI), fctx);
132 if trace {
133 eprintln!("TRACE intrabc dv={dv:?}");
134 }
135 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
136 hit!(INTRABC_HITS);
137 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
138 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
139 // CFL or filter-intra syntax follows. `YMode`/`UVMode` are forced
140 // `DC_PRED` (which is also what the neighbour mode contexts and
141 // the loop filter then see).
142 return Ok((skip, DC_PRED, 0, DC_PRED, 0, None, None, None, None));
143 }
144 }
145 let above_ctx = INTRA_MODE_CTX[above_mode];
146 let left_ctx = INTRA_MODE_CTX[left_mode];
147 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
148 if trace {
149 eprintln!(
150 "TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}",
151 dec.debug_state().0
152 );
153 }
154 istep!("mode", mode as i32);
155 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
156 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
157 if trace {
158 eprintln!(
159 "TRACE angle_delta value={}",
160 delta + ANGLE_DELTA_ZERO as i32
161 );
162 }
163 delta
164 } else {
165 0
166 };
167 istep!("angle_y", angle_delta_y);
168 // lane-av1mono: a monochrome block codes no chroma mode/CFL/palette
169 // symbol at all (libaom `decodemv.c:933`'s `!monochrome && is_chroma_ref`
170 // guard). Fold `NumPlanes == 1` into the same `has_chroma` this reader
171 // gates its chroma symbols on.
172 let has_chroma = !mono(fctx);
173 let cfl = cfl && has_chroma && cfl_allowed_px(side, side, fctx);
174 let uv_mode = if !has_chroma {
175 DC_PRED
176 } else if cfl {
177 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
178 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
179 } else {
180 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
181 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
182 };
183 if trace {
184 eprintln!(
185 "TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}",
186 dec.debug_state().0
187 );
188 }
189 istep!("uv_mode", uv_mode as i32);
190 let alpha = if cfl && uv_mode == UV_CFL_PRED {
191 Some(read_cfl_alphas(dec, cdfs))
192 } else {
193 None
194 };
195 // `SMOOTH_PRED..PAETH_PRED` (9..=12) chroma is a separate round-2 gap
196 // from this lane's directional chroma: a corner block with neither
197 // `above` nor `left` (both `Edges::build`'s no-neighbour fallback,
198 // 127/129) fed `SMOOTH_PRED` produces the wrong pixel there (worst delta
199 // 78 against ffmpeg, traced 2026-08-27) -- an existing, un-lane-touched
200 // bug in that fallback this lane's own scope does not cover. Keep it
201 // refused here rather than ship a silently-wrong decode.
202 if (9..=12).contains(&uv_mode) {
203 hit!(SMOOTH_UV_HITS);
204 }
205 // `get_uv_mode` (spec 9.3): `UV_CFL_PRED` predicts as `DC_PRED` for the
206 // angle-delta question -- libaom's own `read_intra_frame_mode_info` reads
207 // `angle_delta_uv` off `get_uv_mode(uv_mode)`, never off `uv_mode` raw,
208 // so a CFL block (uv_mode==13, outside `V_PRED..=D67_PRED`) already takes
209 // the `else` branch below and never reads one either way.
210 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
211 hit!(DIRECTIONAL_UV_HITS);
212 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
213 } else {
214 0
215 };
216 istep!("angle_uv", angle_delta_uv);
217 if angle_delta_uv != 0 {
218 hit!(UV_ANGLE_DELTA_HITS);
219 }
220 // `read_palette_mode_info` (spec 5.11.13, libaom decodemv.c:567, called
221 // at :840 right after `xd->cfl.store_y` and before `read_filter_intra_mode_info`):
222 // gated by `av1_allow_palette` (blockd.h -- size bound only,
223 // [`palette_bsize_ctx`]). `palette_mode_ctx` comes from the caller
224 // (`palette` param, `None` refuses unconditionally at ctx 0 -- the old
225 // behaviour, bit-identical since a hardcoded ctx-0 read and a real one
226 // read the same CDF row whenever every neighbour really is non-palette).
227 // `palette_uv_mode_ctx` is this block's own just-decided Y palette use,
228 // per `read_palette_mode_info`'s own `pmi->palette_size[0] > 0` (not a
229 // neighbour lookup at all), so it is exact even at the excluded call
230 // sites once Y decodes real syntax there too.
231 //
232 // lane-palette r7: libaom's `decode_color_map_tokens` is NOT called
233 // inline from `read_palette_mode_info` -- it runs later, from
234 // `parse_decode_block` (`decodeframe.c:1135`, `av1_visit_palette`),
235 // after the WHOLE mode-info read for the block, including UV palette
236 // mode_info (`read_palette_mode_info`'s own second half, right below)
237 // and `read_filter_intra_mode_info`. So this branch now only reads
238 // mode/size/colours for both planes (deferring the two colour-index-map
239 // decodes to after `filter_intra`, below) -- r6's range trace pinned
240 // this exact ordering bug (`compare-range-not-tell`: ranges matched
241 // bit-for-bit through the Y colours, diverged only at the old inline
242 // `decode_color_index_map` call).
243 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
244 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
245 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx(side) {
246 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
247 if mode == DC_PRED && trace {
248 let (rng, _) = dec.debug_state();
249 eprintln!(
250 "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
251 );
252 }
253 let use_palette_y =
254 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
255 if mode == DC_PRED && trace {
256 let (rng, _) = dec.debug_state();
257 eprintln!(
258 "TRACE palette_y_mode value={} rng={rng}",
259 use_palette_y as i32
260 );
261 }
262 if use_palette_y {
263 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
264 if trace {
265 let (rng, _) = dec.debug_state();
266 eprintln!("TRACE palette_y_size n={n} rng={rng}");
267 }
268 let colors = read_palette_colors_y(dec, n, cache, fctx);
269 if trace {
270 let (rng, _) = dec.debug_state();
271 eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
272 }
273 palette_y_pending = Some((n, colors));
274 }
275 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
276 // unconditionally at this bit position whenever `uv_mode ==
277 // UV_DC_PRED`, regardless of whether Y just fired -- this decoder's
278 // scope always reconstructs chroma alongside luma (`decode_block`
279 // always calls `u.reconstruct`/`v.reconstruct`), so `is_chroma_ref`
280 // is always true here and does not need threading in.
281 //
282 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
283 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602), so a
284 // monochrome frame reads NO `palette_uv_mode`/`palette_uv_size`
285 // symbol even at this chroma-owning square block.
286 let palette_uv_mode_ctx = usize::from(use_palette_y);
287 if has_chroma
288 && uv_mode == DC_PRED
289 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
290 {
291 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
292 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
293 palette_uv_pending = Some((n, u_colors, v_colors));
294 }
295 }
296 // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
297 // `use_filter_intra` symbol this decoder never read at all until
298 // lane-av1real r10 -- silently skipping it left every bit past a
299 // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
300 // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
301 // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
302 // symbol's bits were never consumed).
303 let mut filter_intra = None;
304 // lane-tiles r12: `av1_filter_intra_allowed` (blockd.h) also requires
305 // `mbmi->palette_mode_info.palette_size[0] == 0` -- libaom writes NO
306 // `use_filter_intra` symbol for a Y-palette block, and reading one here
307 // desynced every screen-content stream from the first palette block on
308 // (it surfaced as a bogus "partition below 8x8" refusal further down the
309 // tile).
310 if mode == DC_PRED
311 && enable_filter_intra
312 && palette_y_pending.is_none()
313 && let Some(class) = filter_intra_size_class(side)
314 {
315 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
316 if trace {
317 eprintln!(
318 "TRACE use_filter_intra side={side} rng={} value={}",
319 dec.debug_state().0,
320 use_filter_intra as i32
321 );
322 }
323 istep!("use_filter_intra", use_filter_intra as i32);
324 if use_filter_intra {
325 hit!(FILTER_INTRA_HITS);
326 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
327 if trace {
328 eprintln!("TRACE filter_intra_mode value={fi_mode}");
329 }
330 istep!("filter_intra_mode", fi_mode as i32);
331 filter_intra = Some(fi_mode);
332 }
333 }
334 // `av1_visit_palette` (decoder.c:234): plane 0 (Y) then plane 1 (chroma,
335 // shared U/V map) -- the same order libaom's own loop visits them in.
336 let palette_y = palette_y_pending.map(|(n, colors)| {
337 let map = decode_color_index_map(
338 dec,
339 cdfs,
340 n,
341 side,
342 palette_onscreen(mi_r, mi_c, side, side, fctx),
343 false,
344 );
345 hit!(PALETTE_HITS);
346 if trace {
347 eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
348 }
349 PaletteY {
350 size: n,
351 colors,
352 map,
353 }
354 });
355 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
356 let on = palette_onscreen_uv(
357 (side, side),
358 palette_onscreen(mi_r, mi_c, side, side, fctx),
359 (side >> ss_x(fctx), side >> ss_y(fctx)),
360 (ss_x(fctx), ss_y(fctx)),
361 );
362 // lane-av1-422d: the chroma map's extent is the PLANE BLOCK
363 // `(side >> ss_x) x (side >> ss_y)` -- 4x8 at ss (1,0), not the
364 // square call's `(side >> ss_x)`-squared (4x4), which left a
365 // 16-entry map for a 32-sample unit and panicked the reconstruct.
366 let map = decode_color_index_map_wh(
367 dec,
368 cdfs,
369 n,
370 side >> ss_x(fctx),
371 side >> ss_y(fctx),
372 on,
373 true,
374 );
375 hit!(PALETTE_UV_HITS);
376 if trace {
377 eprintln!(
378 "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
379 &u_colors[..n],
380 &v_colors[..n]
381 );
382 }
383 PaletteUv {
384 size: n,
385 u_colors,
386 v_colors,
387 map,
388 }
389 });
390 Ok((
391 skip,
392 mode,
393 angle_delta_y,
394 uv_mode,
395 angle_delta_uv,
396 alpha,
397 filter_intra,
398 palette_y,
399 palette_uv,
400 ))
401}
402
403/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
404/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
405/// intra modes.
406pub(super) const UV_CFL_PRED: usize = 13;
407
408/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
409/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
410/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
411/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
412/// joint sign the same way. Returns each plane's final signed `alpha_q3`
413/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
414pub(super) fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
415 hit!(CFL_BLOCK_HITS);
416 let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
417 let sign_u = ((joint_sign + 1) * 11) >> 5;
418 let sign_v = (joint_sign + 1) - 3 * sign_u;
419 let alpha_u = if sign_u == 0 {
420 0
421 } else {
422 let ctx_u = (joint_sign + 1 - 3) as usize;
423 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
424 if sign_u == 2 { mag } else { -mag }
425 };
426 let alpha_v = if sign_v == 0 {
427 0
428 } else {
429 let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
430 let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
431 if sign_v == 2 { mag } else { -mag }
432 };
433 (alpha_u, alpha_v)
434}
435
436/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
437/// the reconstructed luma samples under a `side`-square block, subsampled
438/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
439/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
440/// to give the AC values [`cfl_scaled`] scales by alpha.
441pub(super) fn cfl_ac_q3(y: &PlaneBuf<'_>, px: usize, py: usize, side: usize) -> Vec<i32> {
442 cfl_ac_q3_at(px, py, side, side, |lx, ly| {
443 i32::from(y.data[ly * y.width + lx])
444 })
445}
446
447/// The one body [`cfl_ac_q3`] and [`cfl_ac_q3_rect`] share, reading its luma
448/// samples through `sample(x, y)` instead of a [`PlaneBuf`] -- so the encoder
449/// (lane-av1cfl) builds a CfL candidate's AC signal from its own `u8`
450/// reconstruction through THIS function rather than a second transcription of
451/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c`.
452/// CfL AC at the frame's subsampling. 4:2:0 keeps the 2x2 average; 4:4:4
453/// copies each luma sample shifted to Q3 (`cfl_luma_subsampling_444_lbd`).
454pub(super) fn cfl_ac_ss(
455 y: &PlaneBuf<'_>,
456 px: usize,
457 py: usize,
458 bw: usize,
459 bh: usize,
460 ss_x: usize,
461 ss_y: usize,
462) -> Vec<i32> {
463 if ss_x == 0 && ss_y == 0 {
464 hit!(CFL_AC_444_HITS);
465 let mut ac = vec![0i32; bw * bh];
466 let mut sum = 0i32;
467 for row in 0..bh {
468 for col in 0..bw {
469 let q3 = i32::from(y.data[(py + row) * y.width + px + col]) << 3;
470 ac[row * bw + col] = q3;
471 sum += q3;
472 }
473 }
474 let num_pel = (bw * bh) as i32;
475 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
476 ac.iter_mut().for_each(|v| *v -= avg);
477 ac
478 } else if ss_x == 1 && ss_y == 0 {
479 // lane-av1-422: `cfl_luma_subsampling_422_lbd_c` -- each chroma sample
480 // averages the HORIZONTAL luma pair above it, at full chroma height
481 // (`(a + b) >> 1` in Q3 is `(a + b) << 2`). A rect luma strip's chroma
482 // is square here, and the 4:2:0 rect/square helpers below would halve
483 // the height it must keep.
484 hit!(CFL_AC_422_HITS);
485 let (cw, ch) = (bw >> 1, bh);
486 let mut ac = vec![0i32; cw * ch];
487 let mut sum = 0i32;
488 for row in 0..ch {
489 for col in 0..cw {
490 let (lx, ly) = (px + col * 2, py + row);
491 let q3 = (i32::from(y.data[ly * y.width + lx])
492 + i32::from(y.data[ly * y.width + lx + 1]))
493 << 2;
494 ac[row * cw + col] = q3;
495 sum += q3;
496 }
497 }
498 let num_pel = (cw * ch) as i32;
499 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
500 ac.iter_mut().for_each(|v| *v -= avg);
501 ac
502 } else if bw == bh {
503 hit!(CFL_AC_420_SQ_HITS);
504 cfl_ac_q3(y, px, py, bw)
505 } else {
506 hit!(CFL_AC_420_RECT_HITS);
507 cfl_ac_q3_rect(y, px, py, bw, bh)
508 }
509}
510
511pub(crate) fn cfl_ac_q3_at(
512 px: usize,
513 py: usize,
514 bw: usize,
515 bh: usize,
516 sample: impl Fn(usize, usize) -> i32,
517) -> Vec<i32> {
518 hit!(CFL_AC_Q3_AT_HITS);
519 if crate::envflags::env_flag!("EC_HALVSWEEP") {
520 eprintln!("EC_HALV cfl_ac_q3_at px={px} py={py} bw={bw} bh={bh}");
521 }
522 let (cw, ch) = (bw / 2, bh / 2);
523 let mut ac = vec![0i32; cw * ch];
524 let mut sum = 0i32;
525 for cy in 0..ch {
526 for cx in 0..cw {
527 let (lx, ly) = (px + cx * 2, py + cy * 2);
528 let q3 =
529 (sample(lx, ly) + sample(lx + 1, ly) + sample(lx, ly + 1) + sample(lx + 1, ly + 1))
530 << 1;
531 ac[cy * cw + cx] = q3;
532 sum += q3;
533 }
534 }
535 let num_pel = (cw * ch) as i32;
536 let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
537 ac.iter_mut().for_each(|v| *v -= avg);
538 ac
539}
540
541/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
542/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
543/// ties away from zero on the shifted-out sign).
544pub(crate) fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
545 let v = alpha_q3 * ac_q3;
546 if v >= 0 {
547 (v + 32) >> 6
548 } else {
549 -((-v + 32) >> 6)
550 }
551}
552
553/// One plane's reconstruction buffer, `width * height` samples, and the
554/// prediction/residual reads and writes into it — the decode-side twin of
555/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
556/// (own-edge and reach clamps both), passing what it gathers straight to
557/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
558/// lane-tiny r4: raw padded-plane dump for filter-stage bisection, written
559/// only when `var` names a path. Same byte shape as `EC_AV1_PREFILT_DUMP`.
560/// lane-hgkf r2: 16-bit cropped stage dump, the high-bitdepth twin of
561/// [`dump_stage`] (whose `as u8` truncation hides |delta| <= 2 defects).
562/// lane-unwritten-dep: this doc previously said the dump "matches aomdec's own
563/// `ec_dump16` rung byte for byte (crop dims, u16 LE)", which was true only of
564/// the 4:2:0 crop it then used. The crop is now PER-AXIS, which is what the
565/// oracle's rung 1 actually does -- it writes `y_crop_width` x `y_crop_height`,
566/// `uv_crop_width` x `uv_crop_height`, `uv_crop_width` x `uv_crop_height` (the
567/// libaom `YV12_BUFFER_CONFIG` fields, each already per-axis). Byte shape per
568/// subsampling, `fw x fh` luma then both chroma planes, u16 LE, so:
569///
570/// ```text
571/// ss_x ss_y format luma chroma (each)
572/// 0 0 4:4:4 fw x fh fw x fh fw*fh*3 samples
573/// 1 1 4:2:0 fw x fh fw/2 x fh/2 fw*fh*3/2 samples
574/// 1 0 4:2:2 fw x fh fw/2 x fh fw*fh*2 samples
575/// 0 1 4:4:0 fw x fh fw x fh/2 fw*fh*3/2 samples
576/// ```
577///
578/// (`round_ss` is the rounding the decoder's own plane extents use; at ss = 1 it
579/// is `div_ceil(2)`, so every 4:2:0 dump is byte-for-byte unchanged by this.)
580/// lane-mc64 r1: the file name is keyed on [`dump_stage_idx`], a per-var
581/// decode-order counter -- both dumps used to write `.f0` unconditionally, so
582/// every frame overwrote the previous one and only the LAST frame survived,
583/// which silently defeats any per-frame filter-stage bisection (ledger, class
584/// stale-output-faked-measurement). A sibling accessor `stage_dump_idx()`, which
585/// derived the same number from `PREFILT_PICTURE_IDX`, had no caller and was
586/// deleted: `PREFILT_PICTURE_IDX` is bumped after this point, not before it, so
587/// the counter that names these files is the per-var map.
588// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
589#[allow(clippy::too_many_arguments)]
590pub(super) fn dump_stage16(
591 var: &str,
592 y: &PlaneBuf<'_>,
593 u: &PlaneBuf<'_>,
594 v: &PlaneBuf<'_>,
595 fw: usize,
596 fh: usize,
597 ss_x: usize,
598 ss_y: usize,
599) {
600 // lane-sbrect10 r2 / lane-cdef r1 (one shared helper): index the dump by
601 // decode-order picture like EC_AV1_PREFILT_DUMP already does -- a fixed
602 // `.f0` name kept only the LAST frame, so a mid-sequence divergence could
603 // not be read at all.
604 //
605 // lane-unwritten-dep: the chroma extent is PER-AXIS subsampling, not
606 // `div_ceil(2)` on both. The hardcoded pair was a 4:2:0 assumption and it
607 // was load-bearing: on a 64x64 4:2:2 frame (ss_x = 1, ss_y = 0) it wrote
608 // 32x32 chroma per plane where the frame carries 32x64, so HALF of each
609 // chroma plane appeared in NO stage dump at all. A stage bisect that reads
610 // "identical pre-deblock, differs post-deblock" off these dumps is then
611 // measuring the dump's blind spot, not the pipeline's: the samples it could
612 // not see are exactly the region where the 4:2:2 witness's output diverges
613 // (chroma rows 32..63 -- the old `fh.div_ceil(2)` crop wrote 32 of 64 rows,
614 // so everything from row 32 up was invisible; 2048 samples). `round_ss` is
615 // the same rounding the
616 // decoder's own plane extents use, and it matches the oracle's
617 // `uv_crop_width` / `uv_crop_height` per axis.
618 //
619 // ONE file per frame: `dump_stage_idx` advances on every call, so creating
620 // the file inside the plane loop would write three files per frame and
621 // shift every later frame's index.
622 //
623 // lane-av1dumploud: this used to be `let _ = f.write_all(&bytes)` per row, so
624 // a full filesystem left a SHORT file that no reader could tell from a
625 // complete one. `LoudDump` is given the exact expected length this function
626 // knows -- `(fw*fh + 2*cw*ch) * 2`, u16 LE -- and checks it against the file
627 // on disk; a shortfall aborts the decode instead of leaving a plausible
628 // artefact behind.
629 if let Ok(path) = crate::envflags::var(var) {
630 let cw = round_ss(fw, ss_x);
631 let ch = round_ss(fh, ss_y);
632 let expected = (fw * fh + 2 * cw * ch) * 2;
633 let mut d = crate::dumpio::LoudDump::create(
634 var,
635 format!("{path}.f{}", dump_stage_idx(var)),
636 expected,
637 );
638 for (p, w, h) in [(y, fw, fh), (u, cw, ch), (v, cw, ch)] {
639 for row in 0..h {
640 let mut bytes = Vec::with_capacity(w * 2);
641 for &s in &p.data[row * p.width..][..w] {
642 bytes.extend_from_slice(&s.to_le_bytes());
643 }
644 d.write(&bytes);
645 }
646 }
647 d.finish();
648 }
649}
650
651/// Decode-order index of the next [`dump_stage`]/[`dump_stage16`] file for a
652/// given env var -- lane-cdef r1: both used to write `.f0` unconditionally, so
653/// every frame overwrote the previous one and only the LAST frame survived,
654/// which silently defeats any per-frame filter-stage bisection.
655fn dump_stage_idx(var: &str) -> usize {
656 use std::collections::HashMap;
657 use std::sync::{Mutex, OnceLock};
658 static IDX: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
659 let mut m = IDX
660 .get_or_init(|| Mutex::new(HashMap::new()))
661 .lock()
662 .unwrap();
663 let e = m.entry(var.to_string()).or_insert(0);
664 let i = *e;
665 *e += 1;
666 i
667}
668
669pub(super) fn dump_stage(var: &str, y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
670 // lane-av1dumploud: loud on a short write (see [`crate::dumpio::LoudDump`]).
671 // The expected length is the three planes' own data lengths -- the writer
672 // iterates exactly `p.data`, so this is the same extent, not a re-derivation
673 // that could disagree with it.
674 if let Ok(path) = crate::envflags::var(var) {
675 let narrow = |p: &PlaneBuf<'_>| -> Vec<u8> { p.data.iter().map(|&s| s as u8).collect() };
676 crate::dumpio::write_planes(
677 var,
678 format!("{path}.f{}", dump_stage_idx(var)),
679 &[&narrow(y), &narrow(u), &narrow(v)],
680 );
681 }
682}
683
684/// `EC_AV1_PREFILT_WIDE_DUMP=<prefix>` -> `<prefix>.f<N>`, the pre-loop-filter
685/// reconstruction cropped to each plane's mi-ALIGNED true extent, byte for
686/// byte the shape aomdec's own rung 7 writes (`y_width`/`y_height`,
687/// `uv_width`/`uv_height`), so the two can be diffed directly.
688///
689/// lane-av1444edge: this used to be an inline block in the KEY-frame tile path
690/// only, with a FUNCTION-LOCAL `static IDX2` as its counter. Both facts were
691/// measurement traps, and the second one is why the first went unnoticed:
692/// the inter-frame path (`decode_inter_frame_tile_with_cdfs`) had no wide
693/// prefilter dump at all, so every 4:4:4 lossy divergence localized to an
694/// inter frame had no pre-filter rung to compare against and got attributed to
695/// reconstruction when the oracle could not see it. The `static` also restarted
696/// per monomorphisation, so every frame after the first overwrote `.f0` -- a
697/// per-frame bisection silently compared the LAST decoded frame. The counter
698/// is now the shared per-var [`dump_stage_idx`] map, and the call also sits on
699/// the inter path (skipped when the filter pipeline is active, which has
700/// already deblocked by the time the tile tail runs -- same condition
701/// `capture_filter_replay` guards itself with).
702pub(super) fn dump_prefilter_wide(y: &PlaneBuf<'_>, u: &PlaneBuf<'_>, v: &PlaneBuf<'_>) {
703 let Ok(path) = crate::envflags::var("EC_AV1_PREFILT_WIDE_DUMP") else {
704 return;
705 };
706 // lane-av1dumploud: loud on a short write. Expected length is
707 // `sum(true_width * true_height)` over the three planes -- the crop the
708 // writer itself builds, so the check cannot disagree with the bytes.
709 let idx = dump_stage_idx("EC_AV1_PREFILT_WIDE_DUMP");
710 let crop = |plane: &PlaneBuf<'_>| -> Vec<u8> {
711 let mut out = Vec::with_capacity(plane.true_width * plane.true_height);
712 for row in 0..plane.true_height {
713 out.extend(
714 plane.data[row * plane.width..][..plane.true_width]
715 .iter()
716 .map(|&s| s as u8),
717 );
718 }
719 out
720 };
721 let (cy, cu, cv) = (crop(y), crop(u), crop(v));
722 crate::dumpio::write_planes(
723 "EC_AV1_PREFILT_WIDE_DUMP",
724 format!("{path}.f{idx}"),
725 &[&cy, &cu, &cv],
726 );
727}
728
729/// Unwritten samples [`census_unwritten`] has counted since the last
730/// [`take_unwritten_samples`] -- process-global (not thread-local) because the
731/// gate reads it after the decode, from a different thread than the one that
732/// scanned the plane.
733pub(super) static UNWRITTEN_SAMPLES: std::sync::atomic::AtomicUsize =
734 std::sync::atomic::AtomicUsize::new(0);
735
736/// Turns [`PLANE_SENTINEL`] filling on for the CALLING thread, independently
737/// of `EC_AV1_PLANE_SENTINEL`. A gate cannot set a process-constant env var
738/// (see [`crate::envflags`]), and the census is the only honest way to ask
739/// "did the tile walk write every sample it was handed" -- a wrong-sample diff
740/// cannot tell an unwritten sample from a mis-predicted one.
741pub fn set_plane_sentinel(on: bool) {
742 PLANE_SENTINEL_ON.with(|c| c.set(on));
743}
744
745/// Reads and clears [`UNWRITTEN_SAMPLES`]: the number of samples the decode
746/// just handed to the tile walk never wrote, summed over every frame and
747/// plane. Zero is the only acceptable answer for a decoder whose output must
748/// not depend on its allocator.
749pub fn take_unwritten_samples() -> usize {
750 UNWRITTEN_SAMPLES.swap(0, std::sync::atomic::Ordering::SeqCst)
751}
752
753/// Samples in the PADDED TAIL -- every sample of each plane outside its own
754/// `true_width` x `true_height` extent -- that still holds [`plane_poison`] at
755/// the pre-deblock point. [`census_unwritten`] scans that region too, because
756/// "past the true extent nothing is ever read" was an ASSUMPTION the tail's
757/// census was built to avoid checking; this counter is the measurement.
758pub(super) static PAD_UNWRITTEN_SAMPLES: std::sync::atomic::AtomicUsize =
759 std::sync::atomic::AtomicUsize::new(0);
760
761/// Reads and clears [`PAD_UNWRITTEN_SAMPLES`].
762pub fn take_pad_unwritten_samples() -> usize {
763 PAD_UNWRITTEN_SAMPLES.swap(0, std::sync::atomic::Ordering::SeqCst)
764}
765
766/// The largest value reconstruction can produce, `(1 << 12) - 1`: the highest
767/// bit depth this decoder carries is 12. A sentinel at or below this could be
768/// a LEGAL sample, which would make the whole census vacuous -- every
769/// unwritten sample would look like an ordinary one.
770pub(super) const MAX_LEGAL_SAMPLE: u16 = 4095;
771
772/// The value [`fresh_plane`] fills with when the sentinel is on.
773///
774/// [`PLANE_SENTINEL`] unless `EC_AV1_PLANE_SENTINEL` names a different one in
775/// hex. Two different poisons are what turns the sentinel from "did a hole
776/// survive into the output" into "did the output depend on the buffer's
777/// initial content": a hole whose value reaches the picture changes the hash
778/// when the poison changes, and one that does not cannot have influenced
779/// anything. A value at or below [`MAX_LEGAL_SAMPLE`] is REFUSED (falls back
780/// to [`PLANE_SENTINEL`]) because the census's soundness rests on the sentinel
781/// being impossible. `EC_AV1_PLANE_SENTINEL=1` -- the spelling every existing
782/// caller and gate uses, and `env_flag!`'s mere presence test -- keeps
783/// [`PLANE_SENTINEL`].
784/// `pub(crate)` for lane-av1graincensus: `film_grain::uninit_plane` fills its
785/// destination with the SAME poison `fresh_plane` does, and
786/// [`census_unwritten_grained`] counts the same value. The fill and the census
787/// must agree on both the value and the predicate, or a "0" means nothing.
788pub(crate) fn plane_poison() -> u16 {
789 static V: std::sync::LazyLock<u16> = std::sync::LazyLock::new(|| {
790 let Ok(raw) = crate::envflags::var("EC_AV1_PLANE_SENTINEL") else {
791 return PLANE_SENTINEL;
792 };
793 let t = raw.trim();
794 if t.is_empty() || t == "1" {
795 return PLANE_SENTINEL;
796 }
797 let hex = t
798 .strip_prefix("0x")
799 .or_else(|| t.strip_prefix("0X"))
800 .unwrap_or(t);
801 match u16::from_str_radix(hex, 16) {
802 Ok(v) if v > MAX_LEGAL_SAMPLE => v,
803 _ => PLANE_SENTINEL,
804 }
805 });
806 *V
807}
808
809thread_local! {
810 /// The [`set_plane_sentinel`] override; `EC_AV1_PLANE_SENTINEL` is the
811 /// process-wide default.
812 static PLANE_SENTINEL_ON: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
813}
814
815/// Whether freshly allocated planes are [`PLANE_SENTINEL`]-filled.
816/// `pub(crate)` for the same reason as [`plane_poison`].
817pub(crate) fn plane_sentinel_on() -> bool {
818 crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL")
819 || PLANE_SENTINEL_ON.with(std::cell::Cell::get)
820}
821
822/// lane-av1unwritten: whether a subsize has a chroma PLANE BLOCK at this
823/// frame's subsampling -- libaom `av1_ss_size_lookup[bsize][ss_x][ss_y] !=
824/// BLOCK_INVALID` (`common_data.c`), which `decode_partition` checks on every
825/// subsize before descending into it:
826///
827/// ```c
828/// if (get_plane_block_size(subsize, pd_u->subsampling_x, pd_u->subsampling_y) ==
829/// BLOCK_INVALID)
830/// aom_internal_error(xd->error_info, AOM_CODEC_CORRUPT_FRAME,
831/// "Block size %dx%d invalid with this subsampling mode", ...);
832/// ```
833/// (`decodeframe.c:1449-1458`).
834///
835/// So at 4:2:2 a 4x8, 8x16, 16x32, 32x64, 64x128, 4x16, 8x32 or 16x64
836/// subsize is NOT DECODABLE: libaom rejects the frame outright and never
837/// reaches a transform size for it. This decoder walked those subsizes anyway,
838/// covering a chroma plane block whose shape did not match the luma one.
839///
840/// Two independent facts justify refusing rather than decoding, and NEITHER is
841/// this lane's pixel measurement:
842///
843/// 1. libaom REFUSES the shape. `aomdec` on the pinned
844/// `440_request_is_422.obu` (a 4:2:2 sequence header over a 4:2:0 key
845/// frame's tile) prints `Failed to decode frame 1: Corrupt frame detected`
846/// and `Block size 8x16 invalid with this subsampling mode`.
847/// 2. libaom's own ENCODER never emits it: `partition_search.c:3383-3389`
848/// gates `partition_rect_allowed` on this same table, so no conformant
849/// 4:2:2 stream can contain the shape and the refusal cannot reject legal
850/// content.
851///
852/// What led here was the observation that this decoder's output for such a
853/// witness DEPENDS ON UNWRITTEN PLANE CONTENT. Measured on lane/av1unwritten's
854/// branch point `8d6998d7` by two independent builds (`EC_AV1_FINAL_DUMP=<dir>/x`,
855/// the directory created FIRST -- the dump writes nothing if it does not exist):
856/// five runs with uninitialised planes gave TWO different output hashes, five runs
857/// with `EC_AV1_PLANE_SENTINEL=1` gave ONE hash, and the sentinel output differs
858/// from the plain one. At 8-bit the sentinel survives in the dump as the single
859/// byte `0xAD`, not the pair `DE AD` -- `PLANE_SENTINEL`'s u16 narrows in
860/// [`crate::stream`]'s u8 write path, so counting a two-byte `0xDEAD` in an
861/// 8-bit dump cannot find it.
862///
863/// That hash observation is HISTORICAL and its hash half did NOT reproduce: on
864/// the same `8d6998d7`, five plain runs of `440_request_is_422` gave ONE hash,
865/// `a761118c8dd5c8d0` (`lanes/unwritten-dep.report.md` §10, which also states in
866/// §13 that this pre-deblock census still has no committed reader on `main`).
867/// Ambient allocator content is machine-dependent, so a stable value on one host
868/// and a varying one on another would be the same defect; the hash spread is
869/// cited as measured-on-`8d6998d7`, not as a standing property.
870///
871/// What the census localised: the lane's own pre-deblock census
872/// ([`census_unwritten`]) found 112 unwritten samples per chroma plane on the
873/// witness, 224 total -- on that lane's tree, with a lane-only instrument. That
874/// count is a lane-tree measurement and is cited as such.
875///
876/// Which witness behaviour is CURRENT: `main` REFUSES this witness. The pin
877/// `440_request_is_422.obu` is exercised by
878/// `stream::tests::a_422_header_over_a_420_tile_refuses_the_subsize_libaom_calls_corrupt`,
879/// which asserts the decode ERRORS with libaom's own "invalid with this
880/// subsampling mode" wording, so `440_request_is_422` is not sweepable on the
881/// merge tree (`lanes/unwritten-dep.report.md` §10). The run-to-run hashes above
882/// are what the tree did BEFORE that refusal and cannot be re-measured on
883/// `main`. Facts (1) and (2) above -- libaom refusing the shape, and libaom's own
884/// encoder never emitting it -- are what make the refusal correct; the
885/// measurement history is why it was looked for.
886///
887/// `av1_ss_size_lookup`'s `BLOCK_INVALID` cells, transcribed verbatim:
888/// `(common_data.c:17-41`, rows in `BLOCK_SIZES_ALL` order, indexed
889/// `[subsampling_x][subsampling_y])`. Every entry below is an (luma width,
890/// luma height) whose plane block does not EXIST at that subsampling pair, so
891/// libaom refuses any subsize of that shape
892/// (`av1/decoder/decodeframe.c:1449-1458`, `AOM_CODEC_CORRUPT_FRAME`,
893/// "Block size %dx%d invalid with this subsampling mode").
894///
895/// There is no other `BLOCK_INVALID` cell in the table: at (0,0) 4:4:4 and at
896/// (1,1) 4:2:0 every row is valid, and the sixteen shapes below are the only
897/// ones that are invalid at (1,0) 4:2:2 or (0,1) 4:4:0. The table test
898/// [`chroma_plane_block_codable_matches_the_libaom_table`] re-transcribes all
899/// 22 rows and checks this list cell for cell -- a diff against the C source,
900/// not a restatement of it.
901///
902/// ```text
903/// BLOCK_4X8 {4X8, 4X4} {INVALID, 4X4} <- INVALID @ (1,0)
904/// BLOCK_8X4 {8X4, INVALID} {4X4, 4X4} <- INVALID @ (0,1)
905/// BLOCK_8X16 {8X16, 8X8} {INVALID, 4X8} <- INVALID @ (1,0)
906/// BLOCK_16X8 {16X8, INVALID} {8X8, 8X4} <- INVALID @ (0,1)
907/// BLOCK_16X32 {16X32, 16X16} {INVALID, 8X16} <- INVALID @ (1,0)
908/// BLOCK_32X16 {32X16, INVALID}{16X16, 16X8} <- INVALID @ (0,1)
909/// BLOCK_32X64 {32X64, 32X32} {INVALID, 16X32} <- INVALID @ (1,0)
910/// BLOCK_64X32 {64X32, INVALID}{32X32, 32X16} <- INVALID @ (0,1)
911/// BLOCK_64X128 {64X128,64X64} {INVALID, 32X64} <- INVALID @ (1,0)
912/// BLOCK_128X64 {128X64,INVALID}{64X64, 64X32} <- INVALID @ (0,1)
913/// BLOCK_4X16 {4X16, 4X8} {INVALID, 4X8} <- INVALID @ (1,0)
914/// BLOCK_16X4 {16X4, 8X4} {8X4, 8X4} <- valid @ (1,0)
915/// BLOCK_8X32 {8X32, 8X16} {INVALID, 4X16} <- INVALID @ (1,0)
916/// BLOCK_32X8 {32X8, 16X8} {32X8, 16X4} <- valid @ (0,1)
917/// BLOCK_16X64 {16X64,16X32} {INVALID, 8X32} <- INVALID @ (1,0)
918/// BLOCK_64X16 {64X16,32X16} {32X16, 32X8} <- valid @ (0,1)
919/// ```
920///
921/// The two "valid" rows are here on purpose: an earlier version of this
922/// predicate hardcoded BLOCK_16X4@(1,0) and BLOCK_32X8@(0,1) as invalid, which
923/// REFUSED a legal 4:2:2 shape -- one aomenc itself emits, since its own
924/// `partition_search.c:3383-3389` gates `partition_rect_allowed[HORZ]` with
925/// exactly this table.
926pub(super) const PLANE_BLOCK_INVALID_422: &[(usize, usize)] = &[
927 (4, 8),
928 (8, 16),
929 (16, 32),
930 (32, 64),
931 (64, 128),
932 (4, 16),
933 (8, 32),
934 (16, 64),
935];
936
937/// The same list at 4:4:0 `(0, 1)` -- a shape no `color_config` can request
938/// (libaom asserts `subsampling_y == 0` when `subsampling_x == 0`), kept so
939/// the table test can cover every cell rather than only the reachable ones.
940pub(super) const PLANE_BLOCK_INVALID_440: &[(usize, usize)] = &[
941 (8, 4),
942 (16, 8),
943 (32, 16),
944 (64, 32),
945 (128, 64),
946 (16, 4),
947 (32, 8),
948 (64, 16),
949];
950
951/// Whether `av1_ss_size_lookup[(bw, bh)][sx][sy]` is not `BLOCK_INVALID` -- i.e.
952/// whether libaom lets a subsize of this luma shape have a chroma plane block
953/// at this subsampling at all. `pub(crate)` so a fixture gate in `stream.rs`
954/// can assert WHICH shape its pin carries, rather than only that the decode
955/// refused -- a refusal gate that cannot name the shape is one decode-site
956/// change away from measuring the wrong thing.
957pub(crate) fn chroma_plane_block_codable(bw: usize, bh: usize, sx: usize, sy: usize) -> bool {
958 match (sx, sy) {
959 (1, 0) => !PLANE_BLOCK_INVALID_422.contains(&(bw, bh)),
960 (0, 1) => !PLANE_BLOCK_INVALID_440.contains(&(bw, bh)),
961 _ => true,
962 }
963}
964
965/// libaom `get_partition_subsize` (spec 6.10.3, `common_data.c`'s
966/// `subsize_lookup`) reduced to its DIMENSIONS -- all the `av1_ss_size_lookup`
967/// check needs, and, by construction, never the PARENT block's own shape
968/// (that is the r2 mistake in a new place: refusing `16x4` at 4:2:2 by testing
969/// the 16x8 parent). `PARTITION_HORZ_A`/`_B` and `PARTITION_VERT_A`/`_B` are
970/// the four-way arms, whose subsizes are the strips they visit.
971pub(super) fn partition_subsize_dims(bsize: (usize, usize), part: usize) -> (usize, usize) {
972 let (w, h) = bsize;
973 match part {
974 PARTITION_SPLIT => (w / 2, h / 2),
975 PARTITION_HORZ | PARTITION_HORZ_A | PARTITION_HORZ_B => (w, h / 2),
976 PARTITION_VERT | PARTITION_VERT_A | PARTITION_VERT_B => (w / 2, h),
977 PARTITION_HORZ_4 => (w, h / 4),
978 PARTITION_VERT_4 => (w / 4, h),
979 _ => (w, h),
980 }
981}
982
983/// [`chroma_plane_block_codable`] applied to the subsize a partition SYMBOL
984/// selected, exactly as `decode_partition` does at `decodeframe.c:1449-1458`
985/// before descending into it. Returns libaom's named refusal for the caller to
986/// propagate.
987#[track_caller]
988pub(super) fn refuse_invalid_subsize(
989 bsize: (usize, usize),
990 part: usize,
991 fctx: &crate::decode::FrameCtx,
992) -> Result<()> {
993 // lane-av1unwritten r6: the coverage artefact. A guard that sits INSIDE a
994 // `PARTITION_HORZ_A..=PARTITION_VERT_B` arm can only ever observe 4..=7, so
995 // "the guard is present" is not evidence that an offending value is caught --
996 // which is exactly how r5's three misplaced guards read as coverage. This
997 // records, per CALL SITE and per partition value, how often the guard was
998 // reached and how often it fired, so a site that never sees an offending
999 // value is visible instead of assumed covered.
1000 if crate::envflags::env_flag!("EC_AV1_SUBSIZE_GUARD_TRACE") {
1001 note_subsize_guard(
1002 std::panic::Location::caller(),
1003 bsize,
1004 part,
1005 chroma_plane_block_codable(
1006 partition_subsize_dims(bsize, part).0,
1007 partition_subsize_dims(bsize, part).1,
1008 ss_x(fctx),
1009 ss_y(fctx),
1010 ),
1011 );
1012 }
1013 let (bw, bh) = partition_subsize_dims(bsize, part);
1014 if chroma_plane_block_codable(bw, bh, ss_x(fctx), ss_y(fctx)) {
1015 Ok(())
1016 } else {
1017 Err(refuse_invalid_plane_block(bw, bh, fctx))
1018 }
1019}
1020
1021/// lane-av1unwritten r6: the OTHER half of the coverage artefact. The guard
1022/// table says what the guards see; this says what each DISPATCH ARM sees, so a
1023/// dispatch reached with an offending partition value and no guard above it is a
1024/// visible hole rather than an absence nobody noticed. `decode_probe` calls
1025/// [`dump_subsize_arm_scan`] at exit under `EC_AV1_SUBSIZE_ARM_TRACE`.
1026pub(super) static SUBSIZE_ARM: std::sync::LazyLock<
1027 std::sync::Mutex<std::collections::BTreeMap<(&'static str, usize), usize>>,
1028> = std::sync::LazyLock::new(|| std::sync::Mutex::new(Default::default()));
1029
1030#[track_caller]
1031pub(crate) fn note_subsize_arm(part: usize, codable: bool) {
1032 if !crate::envflags::env_flag!("EC_AV1_SUBSIZE_ARM_TRACE") {
1033 return;
1034 }
1035 let site = std::panic::Location::caller();
1036 let key = (
1037 format!("{}:{}", site.file(), site.line()).leak() as &'static str,
1038 part * 2 + usize::from(codable),
1039 );
1040 if let Ok(mut m) = SUBSIZE_ARM.lock() {
1041 *m.entry(key).or_insert(0) += 1;
1042 }
1043}
1044
1045/// Prints and clears the [`note_subsize_arm`] table.
1046pub fn dump_subsize_arm_scan() {
1047 let Ok(mut m) = SUBSIZE_ARM.lock() else {
1048 return;
1049 };
1050 for ((site, k), n) in m.iter() {
1051 eprintln!(
1052 "SUBSIZE_ARM site={site} part={} codable={} reached={n}",
1053 k / 2,
1054 if k % 2 == 1 { "true" } else { "false" },
1055 );
1056 }
1057 m.clear();
1058}
1059
1060/// Per-site, per-value counters for [`refuse_invalid_subsize`], plus the dump
1061/// that makes the reach/guard split readable. `EC_AV1_SUBSIZE_GUARD_TRACE`
1062/// records; `dump_subsize_guard_scan` prints (and clears) the table.
1063pub(super) static SUBSIZE_GUARD: std::sync::LazyLock<
1064 std::sync::Mutex<std::collections::BTreeMap<(&'static str, usize, usize, bool), usize>>,
1065> = std::sync::LazyLock::new(|| std::sync::Mutex::new(Default::default()));
1066
1067fn note_subsize_guard(
1068 site: &'static std::panic::Location<'static>,
1069 bsize: (usize, usize),
1070 part: usize,
1071 codable: bool,
1072) {
1073 let key = (
1074 format!("{}:{}", site.file(), site.line()).leak() as &'static str,
1075 bsize.0 * 256 + bsize.1,
1076 part,
1077 codable,
1078 );
1079 if let Ok(mut m) = SUBSIZE_GUARD.lock() {
1080 *m.entry(key).or_insert(0) += 1;
1081 }
1082}
1083
1084/// Prints and clears the [`refuse_invalid_subsize`] table: one line per
1085/// (site, block, partition value) with the times reached and whether the guard
1086/// fired. `decode_probe` calls this at exit.
1087pub fn dump_subsize_guard_scan() {
1088 let Ok(mut m) = SUBSIZE_GUARD.lock() else {
1089 return;
1090 };
1091 for ((site, bsize, part, codable), n) in m.iter() {
1092 eprintln!(
1093 "SUBSIZE_GUARD site={site} bsize={}x{} part={part} codable={codable} \
1094 reached={n}{}",
1095 bsize / 256,
1096 bsize % 256,
1097 if *codable { "" } else { " FIRED" },
1098 );
1099 }
1100 m.clear();
1101}
1102
1103/// [`chroma_plane_block_codable`] as libaom's refusal: a returned error naming
1104/// the shape and the subsampling mode, never an `assert!` -- a partition symbol
1105/// is stream data, so a hostile file can reach it.
1106pub(super) fn refuse_invalid_plane_block(
1107 _bw: usize,
1108 _bh: usize,
1109 _fctx: &crate::decode::FrameCtx,
1110) -> Error {
1111 unsupported(
1112 "a block size 4x8, 8x16 or 16x4 (or 8x4 at 4:4:0) has no chroma plane block at this \
1113 frame's subsampling mode (libaom: \"Block size %dx%d invalid with this subsampling \
1114 mode\", av1/decoder/decodeframe.c:1456, refusing by the same rule)",
1115 )
1116}
1117
1118/// The value [`fresh_plane`] fills with under `EC_AV1_PLANE_SENTINEL`: no
1119/// legal sample can equal it (reconstruction clamps to `(1 << bit_depth) - 1`,
1120/// at most 4095), so a decode that hashes identically under the flag proves
1121/// the output does not depend on the plane buffer's initial content.
1122pub(super) const PLANE_SENTINEL: u16 = 0xDEAD;
1123
1124/// lane-unwritten-dep: the census count at the LAST point of the pipeline, on the
1125/// exact bytes `EC_AV1_FINAL_DUMP` writes.
1126///
1127/// WHY A SECOND COUNT, and what it is actually for -- the justification this
1128/// comment originally carried was WRONG and is corrected here, because a reader
1129/// would otherwise re-derive the wrong conclusion. An earlier revision of this
1130/// lane claimed the pre-deblock plane was byte-identical plain-vs-sentinel and
1131/// that "deblock creates the dependence". That reading came from
1132/// [`dump_stage16`], which cropped chroma as `(fw/2, fh/2)` -- a 4:2:0
1133/// assumption. On a 64x64 4:2:2 frame (ss_x=1, ss_y=0) that wrote 32x32 chroma
1134/// where the frame carries 32x64, so 2048 chroma samples appeared in NO stage
1135/// dump, and they are exactly the region where the difference lives.
1136///
1137/// With per-axis extents the corrected measurement on `440_request_is_422` is:
1138/// the PRE-DEBLOCK dump already DIFFERS by 2158 bytes plain-vs-sentinel, and an
1139/// exact u16 whole-plane census finds 224 unwritten samples (U 112, V 112,
1140/// rows 36..63, whole 4x4 groups) -- the same number
1141/// `lanes/av1unwritten.report.md` reports. **The hole is present before any
1142/// filter runs, and the pre-deblock census sees it.** This comment previously
1143/// said the opposite; that was the instrument's blind spot read as a property of
1144/// the pipeline.
1145///
1146/// So what this second count is FOR, stated honestly: it is not there because the
1147/// pre-deblock census misses holes. It is there because it is the measurement
1148/// taken where the OUTPUT is taken -- the bytes stored into the reference slots
1149/// and handed to the caller. A hole can be created after reconstruction (a
1150/// filter stage, a superres step, a second pass) and be invisible to a scan taken
1151/// before it; this one cannot. It is a check on the whole span from the tile walk
1152/// to the caller's frame, not a claim that the pre-deblock scan is insufficient.
1153pub(super) static FINAL_UNWRITTEN_SAMPLES: std::sync::atomic::AtomicUsize =
1154 std::sync::atomic::AtomicUsize::new(0);
1155
1156/// lane-unwritten-dep: reads and clears [`FINAL_UNWRITTEN_SAMPLES`] -- unwritten
1157/// samples still present in the frame as handed to the caller, summed over every
1158/// frame and plane. Process-global, like the pre-deblock census's counter, so a
1159/// gate can read it after the decode from a different thread than the one that
1160/// scanned.
1161pub fn take_final_unwritten_samples() -> usize {
1162 FINAL_UNWRITTEN_SAMPLES.swap(0, std::sync::atomic::Ordering::SeqCst)
1163}
1164
1165/// lane-av1graincensus: samples still holding the poison after film grain, over
1166/// the picture [`crate::film_grain::apply_grain`] RETURNS -- i.e. the picture the
1167/// caller receives on a grained frame.
1168pub(super) static GRAINED_UNWRITTEN_SAMPLES: std::sync::atomic::AtomicUsize =
1169 std::sync::atomic::AtomicUsize::new(0);
1170
1171/// Reads and clears [`GRAINED_UNWRITTEN_SAMPLES`].
1172pub fn take_grained_unwritten_samples() -> usize {
1173 GRAINED_UNWRITTEN_SAMPLES.swap(0, std::sync::atomic::Ordering::SeqCst)
1174}
1175
1176/// A frame plane's own backing store, `n` samples, zero-filled.
1177///
1178/// The `true_width`/`true_height`/`width`/`height` arguments are kept for the
1179/// call sites' shape and the sentinel's poison fill; the zero fill itself reads
1180/// none of them. The former `EC_AV1_PLANE_ALLOC=uninit|padzero|extzero` arms
1181/// (uninitialised allocation for memcheck census) are gone: they needed
1182/// `set_len` over uninitialised memory, which the crate no longer contains. The
1183/// shipped default was already the zeroed arm (`lanes/av1uballoc.report.md` §1);
1184/// the poison sentinel (`EC_AV1_PLANE_SENTINEL`) still catches any read of the
1185/// initial content.
1186pub(super) fn fresh_plane(
1187 n: usize,
1188 _true_width: usize,
1189 _true_height: usize,
1190 _width: usize,
1191 _height: usize,
1192) -> Vec<u16> {
1193 if plane_sentinel_on() {
1194 return vec![plane_poison(); n];
1195 }
1196 vec![0u16; n]
1197}
1198
1199#[derive(Clone)]
1200pub(super) struct PlaneBuf<'a> {
1201 pub(super) data: std::borrow::Cow<'a, [u16]>,
1202 pub(super) width: usize,
1203 pub(super) height: usize,
1204 /// The frame's true, decodable extent in this plane's own units — past
1205 /// this, samples are the padded coding surface's invented tail, never a
1206 /// real decoder's edge or reach reads.
1207 pub(super) true_width: usize,
1208 pub(super) true_height: usize,
1209 /// This plane's own tile's top-left pixel origin (spec: intra prediction
1210 /// never reaches across a tile boundary even though an earlier-decoded
1211 /// tile's real pixels sit right there in the shared buffer) — set via
1212 /// [`Self::set_tile_origin`] before each tile's own superblock walk,
1213 /// `0` for the single-tile case. lane-tiles r2: only the left/top bound
1214 /// is threaded (the two-tile column-split stage 1 fixture's tile always
1215 /// ends at the frame's own right/bottom edge); a non-last tile's own
1216 /// right/bottom reach bound is still open, tracked in the report.
1217 pub(super) tile_x0: usize,
1218 pub(super) tile_y0: usize,
1219 /// lane-tiles r5: this plane's own tile's right/bottom pixel bound
1220 /// (exclusive) -- a non-last tile column/row's own reach must stop at
1221 /// its own SB-aligned tile boundary. `width`/`height` (this plane's
1222 /// full padded extent) for the single-tile/last-tile case, matching the
1223 /// old unclipped behaviour exactly.
1224 pub(super) tile_x1: usize,
1225 pub(super) tile_y1: usize,
1226 /// Which plane this buffer IS (0 luma, 1 U, 2 V) -- TEMPORARY probe.
1227 pub(super) plane: u8,
1228}
1229
1230/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
1231/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
1232/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
1233/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
1234/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
1235/// `ALTREF2`/`ALTREF`).
1236// lane-av1pixprobe: env-gated one-sample write probe -- `EC_AV1_PIXPROBE=x,y`
1237// prints one PIXWRITE line per reconstruction store landing on that sample,
1238// naming the store site, the value it replaces and the one it leaves. Re-anchored
1239// from `lane-av1-ibcwrite` @ 25f5c729 onto the main-shape sites (the two mc stores
1240// now live in `reconstruct_mc_rect`).
1241pub(super) static PIXPROBE_ON: std::sync::LazyLock<bool> =
1242 std::sync::LazyLock::new(|| std::env::var_os("EC_AV1_PIXPROBE").is_some());
1243
1244pub(super) static PIXPROBE: std::sync::LazyLock<Option<(usize, usize)>> =
1245 std::sync::LazyLock::new(|| {
1246 crate::envflags::var("EC_AV1_PIXPROBE").ok().and_then(|v| {
1247 let (x, y) = v.split_once(',')?;
1248 Some((
1249 x.trim().parse::<usize>().ok()?,
1250 y.trim().parse::<usize>().ok()?,
1251 ))
1252 })
1253 });
1254
1255#[inline]
1256// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1257#[allow(clippy::too_many_arguments)]
1258pub(super) fn pix_write(
1259 site: &str,
1260 bx: usize,
1261 by: usize,
1262 bside: usize,
1263 x: usize,
1264 y: usize,
1265 prev: u16,
1266 val: u16,
1267) {
1268 if *PIXPROBE_ON && Some((x, y)) == *PIXPROBE {
1269 eprintln!(
1270 "PIXWRITE {site} block=({bx},{by})+{bside} px=({x},{y}) prev={prev} val={val} at {}",
1271 std::panic::Location::caller()
1272 );
1273 }
1274}
1275
1276impl PlaneBuf<'_> {
1277 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
1278 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
1279 /// are already in this plane's own units (luma pixels for `y`, chroma
1280 /// pixels — halved — for `u`/`v`).
1281 pub(super) fn set_tile_origin(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
1282 self.tile_x0 = x0;
1283 self.tile_y0 = y0;
1284 self.tile_x1 = x1;
1285 self.tile_y1 = y1;
1286 }
1287
1288 pub(super) fn edges(
1289 &self,
1290 x: usize,
1291 y: usize,
1292 side: usize,
1293 reach: Reach,
1294 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
1295 let own_across = x + side.min(self.true_width.saturating_sub(x));
1296 let across = if reach.above_right {
1297 own_across + side.min(self.true_width.saturating_sub(own_across))
1298 } else {
1299 own_across
1300 }
1301 .min(self.width)
1302 .min(self.tile_x1);
1303 let own_down = y + side.min(self.true_height.saturating_sub(y));
1304 let down = if reach.below_left {
1305 own_down + side.min(self.true_height.saturating_sub(own_down))
1306 } else {
1307 own_down
1308 }
1309 .min(self.height)
1310 .min(self.tile_y1);
1311 let above = (y > self.tile_y0 && across > x)
1312 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
1313 let left = (x > self.tile_x0 && down > y).then(|| {
1314 (y..down)
1315 .map(|row| self.data[row * self.width + x - 1])
1316 .collect::<Vec<_>>()
1317 });
1318 let corner =
1319 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
1320 (above, left, corner)
1321 }
1322
1323 /// [`Self::edges`] for a true `bw`x`bh` block (lane-intradisp r1):
1324 /// the above/left reach each extend by their OWN axis (`bw` across,
1325 /// `bh` down), not one shared `side`.
1326 pub(super) fn edges_rect(
1327 &self,
1328 x: usize,
1329 y: usize,
1330 bw: usize,
1331 bh: usize,
1332 reach: Reach,
1333 ) -> (Option<Vec<u16>>, Option<Vec<u16>>, Option<u16>) {
1334 let own_across = x + bw.min(self.true_width.saturating_sub(x));
1335 let across = if reach.above_right {
1336 own_across + bw.min(self.true_width.saturating_sub(own_across))
1337 } else {
1338 own_across
1339 }
1340 .min(self.width)
1341 .min(self.tile_x1);
1342 let own_down = y + bh.min(self.true_height.saturating_sub(y));
1343 let down = if reach.below_left {
1344 own_down + bh.min(self.true_height.saturating_sub(own_down))
1345 } else {
1346 own_down
1347 }
1348 .min(self.height)
1349 .min(self.tile_y1);
1350 let above = (y > self.tile_y0 && across > x)
1351 .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
1352 let left = (x > self.tile_x0 && down > y).then(|| {
1353 (y..down)
1354 .map(|row| self.data[row * self.width + x - 1])
1355 .collect::<Vec<_>>()
1356 });
1357 let corner =
1358 (x > self.tile_x0 && y > self.tile_y0).then(|| self.data[(y - 1) * self.width + x - 1]);
1359 if matches!((bw, bh), (16, 8) | (8, 16)) {
1360 hit!(RECT_STRIP_PRED_HITS);
1361 if across > own_across || down > own_down {
1362 hit!(RECT_STRIP_REACH_HITS);
1363 }
1364 }
1365 (above, left, corner)
1366 }
1367
1368 /// [`Self::reconstruct`] for a true `bw`x`bh` block (lane-intradisp r1),
1369 /// via [`Self::edges_rect`] and [`crate::intra::predict`]'s own
1370 /// already-rect-capable `(bw, bh)` pair.
1371 #[allow(clippy::too_many_arguments)]
1372 #[track_caller]
1373 pub(super) fn reconstruct_rect(
1374 &mut self,
1375 x: usize,
1376 y: usize,
1377 bw: usize,
1378 bh: usize,
1379 mode: usize,
1380 angle_delta: i32,
1381 reach: Reach,
1382 residual: &[i32],
1383 cfl: Option<(i32, &[i32])>,
1384 filter_intra: Option<usize>,
1385 smooth_neighbor: bool,
1386 // lane-wave1 step (i): the palette/intrabc prediction override, taken
1387 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
1388 // than by this replay.
1389 pred: Option<Vec<u16>>,
1390 fctx: &crate::decode::FrameCtx,
1391 ) {
1392 // As [`Self::reconstruct`]'s own [`PALETTE_PRED`] override
1393 // (lane-palette2 r4): a palette block's prediction is the
1394 // reconstructed colour-index map, needing no edge pixels at all.
1395 // A override that is not `side x side` is not this block's (the palette
1396 // map of another block); predict from the edges instead of indexing past it.
1397 let prediction = if let Some(buf) = pred.filter(|buf| buf.len() == bw * bh) {
1398 buf
1399 } else {
1400 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
1401 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
1402 eprintln!(
1403 "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
1404 above.as_ref().map(|a| (a.len(), a[0])),
1405 left.as_ref().map(|l| l.len()),
1406 left.as_ref().map(|l| l[0]),
1407 self.tile_x0,
1408 self.tile_y0,
1409 self.true_width,
1410 self.true_height
1411 );
1412 }
1413 let mut prediction = vec![0u16; bw * bh];
1414 if let Some(fi_mode) = filter_intra {
1415 crate::intra::predict_filter_intra(
1416 fi_mode,
1417 above.as_deref(),
1418 left.as_deref(),
1419 corner,
1420 bw,
1421 bh,
1422 &mut prediction,
1423 fctx,
1424 );
1425 } else {
1426 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
1427 predict(
1428 mode as u8,
1429 angle_delta,
1430 above.as_deref(),
1431 left.as_deref(),
1432 corner,
1433 bw,
1434 bh,
1435 enable_edge_filter,
1436 smooth_neighbor,
1437 &mut prediction,
1438 fctx,
1439 );
1440 }
1441 prediction
1442 };
1443 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
1444 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
1445 if crate::envflags::env_flag!("EC_PRED") {
1446 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
1447 let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
1448 let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
1449 eprintln!(
1450 "@{} OUR_PRED x={x} y={y} plane={} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
1451 std::panic::Location::caller(),
1452 recon_plane(),
1453 i32::from(smooth_neighbor)
1454 );
1455 }
1456 let residual = dense_residual(residual, bw * bh);
1457 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
1458 let res0: Vec<i32> = residual[..bw.min(8)].to_vec();
1459 let pred0: Vec<u16> = prediction[..bw.min(8)].to_vec();
1460 eprintln!(
1461 "DBG192 rect x={x} y={y} bw={bw} bh={bh} mode={mode} pred0={pred0:?} res0={res0:?}"
1462 );
1463 }
1464 for row in 0..bh {
1465 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
1466 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
1467 // whose padded width is not superblock aligned hangs past it.
1468 if y + row >= self.height {
1469 break;
1470 }
1471 for col in 0..bw {
1472 if x + col >= self.width {
1473 break;
1474 }
1475 let idx = row * bw + col;
1476 let mut base = i32::from(prediction[idx]);
1477 if let Some((alpha_q3, ac_q3)) = cfl {
1478 // The AC buffer is sized for the CfL source block; a transform
1479 // block larger than it has no AC sample here, so it adds nothing.
1480 let ac = ac_q3.get(idx).copied().unwrap_or(0);
1481 base = (base + cfl_scaled(alpha_q3, ac)).clamp(0, sample_max(fctx));
1482 }
1483 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
1484 pix_write(
1485 "reconstruct_rect",
1486 x,
1487 y,
1488 bw,
1489 x + col,
1490 y + row,
1491 self.data[(y + row) * self.width + x + col],
1492 sample,
1493 );
1494 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
1495 }
1496 }
1497 // lane-d792: the RECONSTRUCTION rung beside `EC_PRED`'s prediction one
1498 // -- a block whose prediction matches the oracle's but whose written
1499 // samples do not is either a residual defect or a later overwrite, and
1500 // only this print separates the two.
1501 if crate::envflags::env_flag!("EC_PRED") {
1502 let row0: Vec<u16> = (0..bw.min(8))
1503 .map(|c| self.data[y * self.width + x + c])
1504 .collect();
1505 let col0: Vec<u16> = (0..bh.min(8))
1506 .map(|r| self.data[(y + r) * self.width + x])
1507 .collect();
1508 eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}");
1509 }
1510 }
1511
1512 /// Predicts under `mode` then adds `residual` (side*side, raster),
1513 /// writing the clamped reconstruction back into the plane at `(x, y)`.
1514 /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
1515 /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
1516 /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
1517 /// order (cfl.c).
1518 #[track_caller]
1519 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1520 #[allow(clippy::too_many_arguments)]
1521 pub(super) fn reconstruct(
1522 &mut self,
1523 x: usize,
1524 y: usize,
1525 side: usize,
1526 mode: usize,
1527 angle_delta: i32,
1528 reach: Reach,
1529 residual: &[i32],
1530 cfl: Option<(i32, &[i32])>,
1531 filter_intra: Option<usize>,
1532 // `smooth_neighbor` (spec `get_intra_edge_filter_type` /
1533 // libaom `get_filt_type`): true when the block's above OR left
1534 // neighbour's mode is `SMOOTH_PRED..=SMOOTH_H_PRED` (never `PAETH`).
1535 // Callers pass their own plane's neighbour-mode check
1536 // ([`is_smooth_mode`]) — chroma's is still hardcoded `false` by its
1537 // callers until a smooth/paeth `uv_mode` can reach this call at all
1538 // (still refused in `read_intra_mode`/`read_intra_mode_rect`), which
1539 // keeps `false` exact for chroma without this fn needing to know why.
1540 smooth_neighbor: bool,
1541 // lane-wave1 step (i): the palette/intrabc prediction override, taken
1542 // off `FrameCtx::palette_pred` by the PUSH site (parse order) rather
1543 // than by this replay.
1544 pred: Option<Vec<u16>>,
1545 fctx: &crate::decode::FrameCtx,
1546 ) {
1547 // A palette block's own [`PALETTE_PRED`] override (lane-palette r2)
1548 // takes priority over `predict()`/`predict_filter_intra` entirely --
1549 // palette prediction needs no edge pixels at all.
1550 // A override that is not `side x side` is not this block's (the palette
1551 // map of another block); predict from the edges instead of indexing past it.
1552 let prediction = if let Some(buf) = pred.filter(|buf| buf.len() == side * side) {
1553 buf
1554 } else {
1555 let (above, left, corner) = self.edges(x, y, side, reach);
1556 if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
1557 eprintln!(
1558 "EDGES_SQ x={x} y={y} side={side} mode={mode} above={:?} left={:?} corner={corner:?}",
1559 above.as_deref(),
1560 left.as_deref(),
1561 );
1562 }
1563 let mut prediction = vec![0u16; side * side];
1564 if let Some(fi_mode) = filter_intra {
1565 crate::intra::predict_filter_intra(
1566 fi_mode,
1567 above.as_deref(),
1568 left.as_deref(),
1569 corner,
1570 side,
1571 side,
1572 &mut prediction,
1573 fctx,
1574 );
1575 } else {
1576 // `enable_intra_edge_filter` is the sequence header's own flag
1577 // (`ENABLE_EDGE_FILTER`, set once per `decode_key_frame_tile_with_cdfs`
1578 // call, never per-block) -- threading it through every
1579 // `read_plane`/`decode_block`/`decode_leaf8` call would touch two
1580 // dozen sites for a value that never changes mid-decode, so it
1581 // rides a thread-local instead (this decoder is single-threaded
1582 // per stream).
1583 let enable_edge_filter = fctx.enable_edge_filter.with(std::cell::Cell::get);
1584 predict(
1585 mode as u8,
1586 angle_delta,
1587 above.as_deref(),
1588 left.as_deref(),
1589 corner,
1590 side,
1591 side,
1592 enable_edge_filter,
1593 smooth_neighbor,
1594 &mut prediction,
1595 fctx,
1596 );
1597 }
1598 prediction
1599 };
1600 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
1601 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
1602 if crate::envflags::env_flag!("EC_PRED") {
1603 let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
1604 let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
1605 let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
1606 eprintln!(
1607 "@{} OUR_PRED x={x} y={y} plane={} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
1608 std::panic::Location::caller(),
1609 recon_plane(),
1610 i32::from(smooth_neighbor)
1611 );
1612 }
1613 let residual = dense_residual(residual, side * side);
1614 if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
1615 let res0: Vec<i32> = residual[..side.min(8)].to_vec();
1616 let pred0: Vec<u16> = prediction[..side.min(8)].to_vec();
1617 eprintln!(
1618 "DBG192 sq x={x} y={y} side={side} mode={mode} cfl={} pred0={pred0:?} res0={res0:?}",
1619 cfl.is_some()
1620 );
1621 }
1622 for row in 0..side {
1623 // lane-sb128c r8: libaom's frame buffer is superblock
1624 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
1625 // transform unit of a 128x64 block at the BOTTOM frame edge
1626 // can hang past the last padded row (1920x792: a unit at
1627 // y=768 wants 832 rows of an 800-row buffer, which panicked
1628 // the film's key frames). Those samples are outside the
1629 // frame: never output, and no block below ever references
1630 // them.
1631 if y + row >= self.height {
1632 break;
1633 }
1634 for col in 0..side {
1635 if x + col >= self.width {
1636 break;
1637 }
1638 let idx = row * side + col;
1639 let mut base = i32::from(prediction[idx]);
1640 if let Some((alpha_q3, ac_q3)) = cfl {
1641 // The AC buffer is sized for the CfL source block; a transform
1642 // block larger than it has no AC sample here, so it adds nothing.
1643 let ac = ac_q3.get(idx).copied().unwrap_or(0);
1644 base = (base + cfl_scaled(alpha_q3, ac)).clamp(0, sample_max(fctx));
1645 }
1646 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
1647 pix_write(
1648 "reconstruct",
1649 x,
1650 y,
1651 side,
1652 x + col,
1653 y + row,
1654 self.data[(y + row) * self.width + x + col],
1655 sample,
1656 );
1657 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
1658 }
1659 }
1660 }
1661}
1662
1663/// Reads one plane's transform block, reconstructs it into `plane` at
1664/// `(x, y)`/`side`, and records what it leaves behind in `neighbours`.
1665#[allow(clippy::too_many_arguments)]
1666pub(super) fn read_plane(
1667 dec: &mut SymbolDecoder,
1668 cdfs: &mut Cdfs,
1669 set: TxbSet,
1670 scan: &[u16],
1671 plane_idx: usize,
1672 around: (bool, bool, i32),
1673 // The block's own luma mode — [`crate::tile::write_block_planes`] passes
1674 // it for every plane's `txb` lookup (it is what an intra transform type's
1675 // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
1676 tx_mode: usize,
1677 predict_mode: usize,
1678 angle_delta: i32,
1679 reach: Reach,
1680 y: &mut PlaneBuf<'static>,
1681 u: &mut PlaneBuf<'static>,
1682 v: &mut PlaneBuf<'static>,
1683 x: usize,
1684 cy: usize,
1685 side: usize,
1686 tx_side: usize,
1687 base_q_idx: u8,
1688 cfl: Option<(i32, CflSrc)>,
1689 filter_intra: Option<usize>,
1690 // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
1691 // smaller than its own block (spec `get_txb_ctx_general`'s
1692 // `plane_bsize != tx_size` branch), carrying the already-looked-up
1693 // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
1694 // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
1695 // formula below.
1696 luma_skip_ctx: Option<usize>,
1697 // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
1698 smooth_neighbor: bool,
1699 fctx: &crate::decode::FrameCtx,
1700) -> Result<Grid> {
1701 // lane-av1mono: a monochrome frame has `NumPlanes == 1`, so libaom's
1702 // coefficient loop (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`)
1703 // never reaches a chroma plane -- no u/v coefficient symbol is coded and
1704 // no chroma write is recorded. Return the all-zero grid the caller's
1705 // neighbour bookkeeping reads, without consuming a bit.
1706 if plane_idx > 0 && mono(fctx) {
1707 return Ok(Grid::Zero(side * side));
1708 }
1709 // lane-av1readcensus: the units read from here on are this plane's.
1710 set_census_plane(plane_idx);
1711 let skip_ctx = if plane_idx == 0 {
1712 luma_skip_ctx.unwrap_or(0)
1713 } else {
1714 // libaom `get_txb_ctx`: a chroma unit's context is
1715 // `combine_entropy_contexts(above, left)` plus 7, or plus 10 when the
1716 // plane block is bigger than the transform. Our chroma tables hold the
1717 // offset-7 rows first, so the caller adds 3 for the bigger-block case
1718 // (every chroma unit of a plane block above TX_4X4 -- lane-sb128b r3,
1719 // and lane-av1h5 measured the 4:4:4 lossless 128 root's TX_4X4 chroma
1720 // units reading the offset-10 rows too, against aomdec's `EC_DBGCTX`).
1721 usize::from(around.0) + usize::from(around.1) + luma_skip_ctx.unwrap_or(0)
1722 };
1723 // spec 5.11.47/libaom `av1_read_tx_type`: a filter-intra luma block's
1724 // `intra_ext_tx_cdf` row is indexed by `fimode_to_intradir[filter_intra_mode]`,
1725 // not by the block's ordinary `mode` (which is always DC_PRED whenever
1726 // filter-intra is on) -- caller passes the raw filter-intra mode 0..4 in
1727 // `filter_intra`, only meaningful for `plane_idx == 0` (chroma has no
1728 // filter-intra in AV1).
1729 // lane-av1444chr: per-TU mode trace with the PLANE named. `PlaneBuf`'s own
1730 // `OUR_PRED` rung cannot carry it (reconstruction does not know its
1731 // plane), and a rung whose plane has to be guessed from the values has
1732 // already produced wrong claims twice this session -- `read_coeffs_rect`
1733 // labelling its unit `plane=0`, and a sweep reading a second-luma-unit
1734 // phantom out of that label (class `rung-mislabels-plane`). Diagnostic
1735 // only: no gate asserts decode behaviour off this line.
1736 if crate::envflags::env_flag!("EC_TRACE_MODE") {
1737 eprintln!(
1738 "OUR_MODE plane={plane_idx} x={x} y={cy} side={side} mode={predict_mode} \
1739 ad={angle_delta} fi={filter_intra:?} reach={reach:?}"
1740 );
1741 }
1742 let tx_mode = if plane_idx == 0 {
1743 fi_tx_row(tx_mode, filter_intra)
1744 } else {
1745 tx_mode
1746 };
1747 let mut coding = cdfs.txb(set, tx_mode);
1748 // libaom `read_tx_type` (`av1/decoder/decodetxb.c`): "No need to read
1749 // transform type for lossless mode(qindex==0)" -- the symbol is not coded
1750 // at all, and `av1_get_tx_type` (`blockd.h`) returns DCT_DCT for every
1751 // plane of a lossless block (the residual then goes through the WHT, so
1752 // the type only picks the scan, which is the default one).
1753 if lossless(fctx) {
1754 coding.tx_type = None;
1755 }
1756 // A chroma plane's `tx_type` is *never* its own coded symbol
1757 // (`coding.tx_type` is always `None` for every `TxbSet::Chroma*`), so it is
1758 // resolved, not read. Three cases, in libaom's own order
1759 // (`av1_get_tx_type` / `av1_get_ext_tx_set_type`, `blockd.h`):
1760 //
1761 // * **intra** chroma: `intra_mode_to_tx_type(mbmi, PLANE_TYPE_UV)` -- the
1762 // plane's own predicted mode (`default_intra_tx_type`) -- then clamped by
1763 // `av1_get_ext_tx_set_type`. At 32 points and up that set is
1764 // `EXT_TX_SET_DCTONLY` (the `is_inter ? EXT_TX_SET_DCT_IDTX :
1765 // EXT_TX_SET_DCTONLY` line), which forces `DCT_DCT` no matter what the
1766 // mode-indexed table said. `TxbSet::Chroma8`/`Chroma16` never hit this --
1767 // every value `default_intra_tx_type` can produce is already a member of
1768 // both `TX_SET_INTRA_1`/`_2`, so nothing narrows there -- only
1769 // `Chroma32` and up do.
1770 // * **inter** chroma, i.e. [`INTRABC_CHROMA_TX`]: the same
1771 // `xd->tx_type_map` cell the luma unit stamped (`blk_row <<=
1772 // pd->subsampling_y`, `blk_col <<= pd->subsampling_x`), reduced by the
1773 // INTER transform set. At **32 points** that set is
1774 // `EXT_TX_SET_DCT_IDTX`, NOT `EXT_TX_SET_DCTONLY` -- so a 32-point
1775 // inter chroma unit inherits the luma's coded `IDTX`, and the identity
1776 // transform (a plain copy) is what libaom actually runs.
1777 // [`reduce_inherited_chroma_tx_type`] is that reduction verbatim.
1778 // * 64 points and up is `EXT_TX_SET_DCTONLY` for both, which the same
1779 // reduction already yields.
1780 //
1781 // The `side >= 32` -> `DCT_DCT` clamp this replaces was written for the
1782 // intra case (and read as libaom's clamp at `tx_size_sqr_up >= TX_32X32`),
1783 // but libaom's cap is `txsize_sqr_up_map[tx_size] > TX_32X32` -- 64 and up
1784 // -- so it also swallowed a 32-point INTER chroma unit's inherited `IDTX`
1785 // and ran `DCT_DCT` where libaom ran the identity transform.
1786 // Sub-32 units keep the raw inherited type exactly as before.
1787 let default_tx_type = if plane_idx == 0 {
1788 TxType::DctDct
1789 } else if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
1790 if side >= 32 {
1791 reduce_inherited_chroma_tx_type(inherited, side, side, fctx)
1792 } else {
1793 inherited
1794 }
1795 } else if side >= 32 {
1796 TxType::DctDct
1797 } else {
1798 default_intra_tx_type(predict_mode as u8)
1799 };
1800 // libaom `av1_get_tx_type` (`blockd.h`): a lossless block's type is
1801 // DCT_DCT on EVERY plane, so chroma never inherits or mode-derives one.
1802 let default_tx_type = if lossless(fctx) {
1803 TxType::DctDct
1804 } else {
1805 default_tx_type
1806 };
1807 let (grid, tx_type) = read_coeffs(
1808 dec,
1809 &mut coding,
1810 scan,
1811 skip_ctx,
1812 dc_sign_ctx(around.2),
1813 default_tx_type,
1814 None,
1815 )?;
1816 note_chroma_class1(plane_idx, tx_type);
1817 if plane_idx == 0 {
1818 fctx.luma_tx_type.with(|c| c.set(tx_type));
1819 }
1820 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
1821 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
1822 // dequantized grid stays zero, which `inverse_transform_2d`'s own `< 32`
1823 // guard also assumes.
1824 // `grid` is `tx_side x tx_side` (the coded corner); `dequant_and_inverse`
1825 // wants the true `side x side` transform, with dqDenom (spec 7.12.3)
1826 // keyed by that true size, not the coded corner's -- so the corner
1827 // goes into the top-left of a `side`-sized grid, not the reverse.
1828 let levels = extend_corner(grid, tx_side, tx_side, side, side);
1829 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
1830 let tx = TxParams {
1831 plane: plane_idx,
1832 w: side,
1833 h: side,
1834 bit_depth: bit_depth(fctx),
1835 q_idx: block_q_idx(fctx),
1836 dc_delta,
1837 ac_delta,
1838 tx_type,
1839 qm: block_iqmatrix(fctx, plane_idx, side, side, tx_type),
1840 stride: 0,
1841 lossless: lossless(fctx),
1842 };
1843 if crate::envflags::env_flag!("EC_AV1_TRACE") {
1844 let residual = tx.run(&levels);
1845 eprintln!(
1846 "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}",
1847 &*levels,
1848 );
1849 }
1850 push_intra_tx(
1851 y,
1852 u,
1853 v,
1854 plane_idx,
1855 x,
1856 cy,
1857 side,
1858 side,
1859 false,
1860 predict_mode,
1861 angle_delta,
1862 reach,
1863 tx,
1864 &levels,
1865 cfl,
1866 filter_intra,
1867 smooth_neighbor,
1868 fctx,
1869 );
1870 // `record`'s neighbour state only reads whether *the coded grid* (not the
1871 // residual) has nonzero entries, so the levels this function already
1872 // built are what it wants back -- both arms of the old `tx_side == side`
1873 // branch returned exactly that, one of them through a full `to_vec` copy
1874 // of the grid per intra transform unit (lane-coefbuf).
1875 Ok(levels)
1876}
1877
1878/// [`push_intra`] when the unit is square, [`push_intra_rect`] when it is a
1879/// rect (lane-av1-422f): a 4:2:2 square-block chroma unit is the plane
1880/// block's own rect shape, and the `rect` flag selects
1881/// [`PlaneBuf::reconstruct_rect`]'s two-dimensional loop.
1882#[allow(clippy::too_many_arguments)]
1883pub(super) fn push_intra_unit(
1884 y: &mut PlaneBuf<'static>,
1885 u: &mut PlaneBuf<'static>,
1886 v: &mut PlaneBuf<'static>,
1887 plane: usize,
1888 x: usize,
1889 cy: usize,
1890 w: usize,
1891 h: usize,
1892 mode: usize,
1893 angle_delta: i32,
1894 reach: Reach,
1895 residual: &[i32],
1896 cfl: Option<(i32, CflSrc)>,
1897 filter_intra: Option<usize>,
1898 smooth_neighbor: bool,
1899 fctx: &crate::decode::FrameCtx,
1900) {
1901 if w == h {
1902 push_intra(
1903 y,
1904 u,
1905 v,
1906 plane,
1907 x,
1908 cy,
1909 w,
1910 mode,
1911 angle_delta,
1912 reach,
1913 residual,
1914 cfl,
1915 filter_intra,
1916 smooth_neighbor,
1917 fctx,
1918 );
1919 } else {
1920 push_intra_rect(
1921 y,
1922 u,
1923 v,
1924 plane,
1925 x,
1926 cy,
1927 w,
1928 h,
1929 mode,
1930 angle_delta,
1931 reach,
1932 residual,
1933 cfl,
1934 filter_intra,
1935 smooth_neighbor,
1936 fctx,
1937 );
1938 }
1939}
1940
1941/// ONE RECT chroma transform unit of a square block's uv plane
1942/// (lane-av1-422f) -- a 4:2:2 frame's plane block is `(side/2, side)` and
1943/// `av1_get_max_uv_txsize` fills it with a single rect unit below side 64
1944/// (TX_4X8 / TX_8X16 / TX_16X32), which the square-shaped [`read_plane`]
1945/// cannot express. Same shape as [`leaf8_chroma422_unit`]'s proven read: the
1946/// [`TxbSet`] whose entropy class the unit squares up to, the unit-shaped
1947/// scan, `txb_skip_ctx` = above + left in the offset-7 rows (the unit covers
1948/// the plane block exactly, so no `+3` bigger-plane term -- that one lives in
1949/// the square multi-unit walks' `chroma_ctx_offset`), and the plane's
1950/// predicted mode supplies the mode-derived default `tx_type` unless an armed
1951/// [`INTRABC_CHROMA_TX`] slot carries the intrabc luma's own -- except at an
1952/// entropy class of 32x32 and up, where the spec forces `DCT_DCT`
1953/// ([`read_plane`]'s `side >= 32` clamp).
1954#[allow(clippy::too_many_arguments)]
1955pub(super) fn read_rect_chroma_unit(
1956 dec: &mut SymbolDecoder,
1957 cdfs: &mut Cdfs,
1958 set: TxbSet,
1959 scan: &[u16],
1960 w: usize,
1961 h: usize,
1962 plane_idx: usize,
1963 around: (bool, bool, i32),
1964 uv_predict_mode: usize,
1965 angle_delta_uv: i32,
1966 reach: Reach,
1967 // Unread, like [`read_plane`]'s own: the borrow proves the caller holds
1968 // the plane exclusively while the unit's coefficients are parsed.
1969 y: &mut PlaneBuf<'static>,
1970 u: &mut PlaneBuf<'static>,
1971 v: &mut PlaneBuf<'static>,
1972 x: usize,
1973 cy: usize,
1974 // Signature parity with [`read_plane`]; the dequant reads its q index
1975 // off `block_q_idx(fctx)` like every other reader here.
1976 _base_q_idx: u8,
1977 // lane-av1-422p: `get_txb_ctx_general`'s chroma branch
1978 // (txb_common.h) reads `txb_skip_ctx = above + left + ctx_offset`,
1979 // where `ctx_offset` is 10 when the plane block is bigger than the
1980 // transform and 7 otherwise. The port stores the offset-7 rows at
1981 // `txb_skip_chroma_8` rows 0..3 and the offset-10 rows at rows 3..6
1982 // (lane-av1-422b), so a unit SMALLER than its plane block passes
1983 // `Some(3)` to reach the offset-10 rows. Every unit that IS the whole
1984 // plane block stays `None` -- 4:2:2 plane blocks never shrink to a
1985 // rect unit except in the chunk arms.
1986 chroma_skip_offset: Option<usize>,
1987 cfl: Option<(i32, CflSrc)>,
1988 smooth_neighbor_uv: bool,
1989 fctx: &crate::decode::FrameCtx,
1990) -> Result<Grid> {
1991 if ss_x(fctx) == 1 && ss_y(fctx) == 0 && w != h {
1992 hit!(CHROMA422_RECT_HITS);
1993 }
1994 // The same three cases as [`read_plane`], for the same reason: at 32 points
1995 // an INTER chroma unit's transform set is `EXT_TX_SET_DCT_IDTX` (the luma's
1996 // coded `IDTX` survives) where the intra set is `EXT_TX_SET_DCTONLY`, and
1997 // an armed [`INTRABC_CHROMA_TX`] slot means the block IS an inter block.
1998 let default_tx = if let Some(inherited) = fctx.intrabc_chroma_tx.with(std::cell::Cell::get) {
1999 if w.max(h) >= 32 {
2000 reduce_inherited_chroma_tx_type(inherited, w, h, fctx)
2001 } else {
2002 inherited
2003 }
2004 } else if w.max(h) >= 32 {
2005 TxType::DctDct
2006 } else {
2007 default_intra_tx_type(uv_predict_mode as u8)
2008 };
2009 let mut coding = cdfs.txb(set, uv_predict_mode);
2010 let (levels, tx_type) = read_coeffs_rect(
2011 dec,
2012 &mut coding,
2013 scan,
2014 w,
2015 h,
2016 usize::from(around.0) + usize::from(around.1) + chroma_skip_offset.unwrap_or(0),
2017 dc_sign_ctx(around.2),
2018 default_tx,
2019 plane_idx,
2020 )?;
2021 let residual = dequant_and_inverse_typed_wh(
2022 &levels,
2023 w,
2024 h,
2025 crate::decode::bit_depth(fctx),
2026 block_q_idx(fctx),
2027 plane_q_delta(plane_idx, fctx).0,
2028 plane_q_delta(plane_idx, fctx).1,
2029 tx_type,
2030 block_iqmatrix(fctx, plane_idx, w, h, tx_type),
2031 );
2032 push_intra_rect(
2033 y,
2034 u,
2035 v,
2036 plane_idx,
2037 x,
2038 cy,
2039 w,
2040 h,
2041 uv_predict_mode,
2042 angle_delta_uv,
2043 reach,
2044 &residual,
2045 cfl,
2046 None,
2047 smooth_neighbor_uv,
2048 fctx,
2049 );
2050 Ok(levels)
2051}
2052
2053/// Decodes one whole-block coded superblock/quadrant/leaf: its mode, then its
2054/// three planes, reconstructing them into `y`/`u`/`v` and updating
2055/// `neighbours`.
2056#[allow(clippy::too_many_arguments)]
2057pub(super) fn decode_block(
2058 dec: &mut SymbolDecoder,
2059 cdfs: &mut Cdfs,
2060 neighbours: &mut Neighbours,
2061 at: (usize, usize),
2062 side: usize,
2063 luma_set: TxbSet,
2064 chroma_set: TxbSet,
2065 luma_tx: usize,
2066 chroma_tx: usize,
2067 scans: (&[u16], &[u16]),
2068 cfl: bool,
2069 y: &mut PlaneBuf<'static>,
2070 u: &mut PlaneBuf<'static>,
2071 v: &mut PlaneBuf<'static>,
2072 base_q_idx: u8,
2073 enable_filter_intra: bool,
2074 allow_screen_content_tools: bool,
2075 allow_intrabc: bool,
2076 scan32: &[u16],
2077 scan16: &[u16],
2078 scan8: &[u16],
2079 scan4: &[u16],
2080 tx_select: bool,
2081 reduced_tx_set: bool,
2082 fctx: &crate::decode::FrameCtx,
2083) -> Result<()> {
2084 let (r, c) = at;
2085 let (px, py) = (c * SUB, r * SUB);
2086 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
2087 let palette_uv_cache = neighbours.palette_uv_cache(at);
2088 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
2089 let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
2090 let (
2091 skip,
2092 mode,
2093 angle_delta_y,
2094 uv_mode,
2095 angle_delta_uv,
2096 alpha,
2097 filter_intra,
2098 palette_y,
2099 palette_uv,
2100 ) = read_intra_mode(
2101 dec,
2102 cdfs,
2103 nb_above_mode,
2104 nb_left_mode,
2105 cfl,
2106 side,
2107 enable_filter_intra,
2108 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
2109 allow_screen_content_tools,
2110 allow_intrabc,
2111 Some((palette_ctx, &palette_cache)),
2112 &palette_uv_cache,
2113 r * (SUB / MI),
2114 c * (SUB / MI),
2115 fctx,
2116 )?;
2117 if at_tile_left && palette_y.is_some() {
2118 hit!(PALETTE_TILE_LEFT_HITS);
2119 }
2120 // lane-lossless: a lossless BLOCK's transform is TX_4X4 on every plane
2121 // (libaom `read_tx_size`, `decodeframe.c`), so the caller's per-size
2122 // tables/scans are replaced by the 4x4 ones and the block always takes the
2123 // multi-transform-unit path below. lane-av1mixloss: this rewrite used to
2124 // sit at the TOP of the function -- before `read_intra_mode`, which is
2125 // where the block's own `segment_id` is read -- so a mixed frame resolved
2126 // every block's geometry against the PREVIOUS block's segment (a lossless
2127 // neighbour forced 4x4 units on a lossy block; a lossy one handed the
2128 // lossless TxParams an 8x8 grid). libaom's order is the opposite one:
2129 // `decode_mbmi_block` (segment id included) runs before any tx-size rule.
2130 // lane-av1mixmerge: the 4:4:4 chroma-size arm from main's copy of this
2131 // rewrite (which sat above `read_intra_mode`) rides along here -- same
2132 // per-frame `ss_x`/`ss_y` condition, now resolved against the block's own
2133 // segment like the lossless arm above it.
2134 let (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx_h, scans) = if lossless(fctx) {
2135 (TxbSet::Luma4, TxbSet::Chroma4, 4, 4, 4, (scan4, scan4))
2136 } else if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
2137 let tx = if side >= 64 { 32 } else { side };
2138 let (set, scan): (TxbSet, &[u16]) = match tx {
2139 32 => (TxbSet::Chroma32, scan32),
2140 16 => (TxbSet::Chroma16, scan16),
2141 8 => (TxbSet::Chroma8, scan8),
2142 _ => (TxbSet::Chroma4, scan4),
2143 };
2144 (luma_set, set, luma_tx, tx, tx, (scans.0, scan))
2145 } else if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
2146 // lane-av1-422f: the uv plane block is the (side/2, side) rect
2147 // (`ss_size_lookup[..][1][0]`), and `av1_get_max_uv_txsize` is
2148 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[plane_bsize])` --
2149 // the RECT that fills the plane block, NOT the square transform of
2150 // the smaller side (the oracle reads ONE TX_8X16 for a 16x16 block's
2151 // 8x16 plane where the old model read two 8x8 units): 4 -> TX_4X4
2152 // (the 2x4 plane rounds up to BLOCK_4X4), 8 -> TX_4X8, 16 ->
2153 // TX_8X16, 32 -> TX_16X32 (one unit per plane, the whole plane
2154 // block), 64 -> TX_32X64 adjusts to TX_32X32 and 128 -> TX_64X64
2155 // adjusts to TX_32X32 (square units, a 1x2 / 2x4 grid).
2156 // `chroma_tx` is the unit WIDTH, `chroma_tx_h` its HEIGHT; the
2157 // chroma walks below read one (chroma_tx, chroma_tx_h) unit per grid
2158 // cell and key their rect reads on `chroma_tx != chroma_tx_h`.
2159 let (tx_w, tx_h) = match side {
2160 4 => (4, 4),
2161 8 => (4, 8),
2162 16 => (8, 16),
2163 32 => (16, 32),
2164 // 64 and 128: TX_32X64 / TX_64X64 adjust down to TX_32X32.
2165 _ => (32, 32),
2166 };
2167 let (set, scan): (TxbSet, &[u16]) = match side {
2168 4 => (TxbSet::Chroma4, scan4),
2169 8 => (TxbSet::ChromaRect8x4, &SCAN_4X8[..]),
2170 16 => (TxbSet::ChromaRect16x8, &SCAN_8X16[..]),
2171 32 => (TxbSet::ChromaRect32x16, &SCAN_16X32[..]),
2172 _ => (TxbSet::Chroma32, scan32),
2173 };
2174 (luma_set, set, luma_tx, tx_w, tx_h, (scans.0, scan))
2175 } else {
2176 (luma_set, chroma_set, luma_tx, chroma_tx, chroma_tx, scans)
2177 };
2178 let intrabc_dv = fctx.intrabc_dv.with(|c| c.take());
2179 // `predict` panics outside `DC_PRED..=PAETH_PRED` (0..=12); `UV_CFL_PRED`
2180 // (13) predicts as `DC_PRED` with the [`cfl_scaled`] nudge carrying the
2181 // actual chroma-from-luma correlation, same as this decoder always did.
2182 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
2183 DC_PRED
2184 } else {
2185 uv_mode
2186 };
2187 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
2188 if smooth_neighbor {
2189 hit!(SMOOTH_LUMA_HITS);
2190 }
2191 let smooth_neighbor_uv =
2192 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
2193 if crate::envflags::env_flag!("EC_AV1_TRACE") {
2194 eprintln!(
2195 "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
2196 angle_delta_uv={angle_delta_uv}"
2197 );
2198 }
2199 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
2200 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
2201 // block, skipped or not. `logical_tx` is what the loop filter's edge
2202 // lookup and the next block's own `get_tx_size_context` want (the *nominal*
2203 // transform size -- 64 even for the 64x64 corner-scanned case, spec
2204 // 5.11.40); `coeff_tx_side` is the actual coded coefficient grid's side,
2205 // which only differs from it at that one corner case.
2206 // lane-t900 r32: spec 5.11.16 `read_block_tx_size` gates the `tx_depth`
2207 // symbol on `allowSelect = !skip || !is_inter`, and libaom's
2208 // `is_inter_block` counts an INTRABC block (`blockd.h:373`). So a SKIPPED
2209 // intrabc block reads NO tx-size symbol at all -- it takes
2210 // `maxRectTxSize` -- while every ordinary skipped intra block does read
2211 // one. Reading it anyway consumed a symbol libaom never wrote and desynced
2212 // the tile from that block on (class `equal-range-means-unread`).
2213 // lane-t900 r32: and an UNSKIPPED one reads the inter var-tx partition
2214 // tree instead (`read_var_tx_size`), the same syntax the inter block path
2215 // has always read -- libaom's `parse_decode_block` dispatches on
2216 // `is_inter_block`, so both branches of `read_block_tx_size` treat an
2217 // intrabc block as inter.
2218 let intrabc_skip_tx = intrabc_dv.is_some() && skip;
2219 // libaom `parse_decode_block`'s var-tx tree condition carries
2220 // `!xd->lossless[mbmi->segment_id]` (decodeframe.c:1237): an intrabc
2221 // block inside a LOSSLESS segment of a mixed frame reads NO
2222 // `txfm_partition` tree -- it falls to `read_tx_size`, whose first line
2223 // hands back TX_4X4. Invisible while every lossless frame was also
2224 // `CodedLossless` (`tx_mode` forced `Only4x4`, tree unreachable), which
2225 // is why the mixed frame is the first stream to reach it.
2226 let intrabc_vartx = intrabc_dv.is_some() && tx_select && !skip && !lossless(fctx);
2227 let intrabc_leaves = if intrabc_vartx {
2228 let max_tx = side.min(64);
2229 // `max_block_wide`/`max_block_high`: the frame's own mi grid
2230 // (`av1_calc_mi_size`, 8-px aligned), so a block hanging over the
2231 // right/bottom edge reads no split symbol for the units outside it.
2232 let mi_cols = 2 * y.true_width.div_ceil(8);
2233 let mi_rows = 2 * y.true_height.div_ceil(8);
2234 let side_mi = side / MI;
2235 let max_w_mi = side_mi.min(mi_cols.saturating_sub(mi_c));
2236 let max_h_mi = side_mi.min(mi_rows.saturating_sub(mi_r));
2237 let mut leaves = Vec::new();
2238 for row in (0..side_mi).step_by(max_tx / MI) {
2239 for col in (0..side_mi).step_by(max_tx / MI) {
2240 read_var_tx_size(
2241 dec,
2242 cdfs,
2243 neighbours,
2244 (mi_r, mi_c),
2245 side,
2246 (max_w_mi, max_h_mi),
2247 (max_tx, max_tx),
2248 0,
2249 row,
2250 col,
2251 &mut leaves,
2252 );
2253 }
2254 }
2255 hit!(INTRABC_VARTX_HITS);
2256 // lane-t900 r33 census: the t900 recipes resolved every tree UNIFORM.
2257 // lane-av1-ibcvtx: a tree that resolved to mixed leaf sizes is no
2258 // longer refused -- the luma reconstruct below walks the tree's own
2259 // leaf list per leaf (libaom `decode_token_recon_block`, whose token
2260 // loop reconstructs whatever `read_tx_size_vartx` resolved, per
2261 // transform unit), so mixed sizes reconstruct at their own stride.
2262 // The counter marks the shape so a gate can prove a witness actually
2263 // carries a mixed tree and not merely another uniform one.
2264 let uniform = leaves.first().is_some_and(|f| {
2265 leaves
2266 .iter()
2267 .all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3)
2268 });
2269 if !uniform {
2270 hit!(INTRABC_VARTX_MIXED_LEAVES_HITS);
2271 if crate::envflags::env_flag!("EC_AV1_IBCVTX_DEBUG") {
2272 eprintln!(
2273 "IBCVTX mixed intrabc tree mi=({mi_r},{mi_c}) side={side} \
2274 dv={intrabc_dv:?} leaves={leaves:?}"
2275 );
2276 }
2277 }
2278 Some(leaves)
2279 } else {
2280 None
2281 };
2282 let (logical_tx, coeff_tx_side) = if let Some(tx) = intrabc_leaves.as_ref().map(|l| l[0].2) {
2283 (tx, if tx == 64 { 32 } else { tx })
2284 } else if tx_select && !intrabc_skip_tx {
2285 let resolved = read_tx_size(dec, cdfs, neighbours, (mi_r, mi_c), side, fctx);
2286 (resolved, if resolved == 64 { 32 } else { resolved })
2287 } else {
2288 // lane-sb128b r1: `max_txsize_rect_lookup[BLOCK_128X128]` is
2289 // TX_64X64, so a 128x128 block is always FOUR luma transform units
2290 // even with `tx_select` off -- the TU loop below, never the
2291 // single-unit path.
2292 (lossless_tx(side.min(64), fctx), luma_tx)
2293 };
2294 if tx_select && logical_tx < side && uv_mode != DC_PRED {
2295 hit!(SQ_CHROMA_TX_HITS);
2296 }
2297 let luma_set = if tx_select {
2298 txbset_for(logical_tx, reduced_tx_set)
2299 } else {
2300 luma_set
2301 };
2302 let luma_set = if intrabc_dv.is_some() {
2303 inter_txbset_for(logical_tx, reduced_tx_set)
2304 } else {
2305 luma_set
2306 };
2307 let luma_scan = scan_for(coeff_tx_side, scan32, scan16, scan8, scan4);
2308 let reach = Reach::of(side, px, py, y.width, y.height, fctx);
2309 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
2310 let chroma_side = side >> ss_x(fctx);
2311 // lane-av1-422b: chroma extent per axis, `side` at ss_y 0 (4:2:2/4:4:4),
2312 // `side / 2` at 4:2:0.
2313 let chroma_height = side >> ss_y(fctx);
2314 // spec 7.11.3.4 with `use_intrabc`: the reference is the *current*
2315 // frame's own pre-loop-filter reconstruction (all loop filters are off
2316 // whenever `allow_intrabc`, frame.rs:194/210/252/272) at the full-pel
2317 // block vector, with the BILINEAR kernel libaom forces for intrabc --
2318 // luma is a straight copy, chroma lands half-pel whenever the luma DV is
2319 // odd, which is exactly what the bilinear taps then interpolate.
2320 let intrabc_bufs = intrabc_dv.map(|(dv_row, dv_col)| {
2321 let mut yb = vec![0u16; side * side];
2322 mc::predict_with_filter(
2323 &y.data,
2324 y.width,
2325 y.true_width,
2326 y.true_height,
2327 mv_to_q4(px, dv_col, 0),
2328 mv_to_q4(py, dv_row, 0),
2329 side,
2330 side,
2331 mc::InterpFilterKind::Bilinear,
2332 &mut yb,
2333 fctx,
2334 );
2335 let mut ub = vec![0u16; chroma_side * chroma_height];
2336 mc::predict_with_filter(
2337 &u.data,
2338 u.width,
2339 u.true_width,
2340 u.true_height,
2341 mv_to_q4(cpx, dv_col, ss_x(fctx)),
2342 mv_to_q4(cpy, dv_row, ss_y(fctx)),
2343 chroma_side,
2344 chroma_height,
2345 mc::InterpFilterKind::Bilinear,
2346 &mut ub,
2347 fctx,
2348 );
2349 let mut vb = vec![0u16; chroma_side * chroma_height];
2350 mc::predict_with_filter(
2351 &v.data,
2352 v.width,
2353 v.true_width,
2354 v.true_height,
2355 mv_to_q4(cpx, dv_col, ss_x(fctx)),
2356 mv_to_q4(cpy, dv_row, ss_y(fctx)),
2357 chroma_side,
2358 chroma_height,
2359 mc::InterpFilterKind::Bilinear,
2360 &mut vb,
2361 fctx,
2362 );
2363 (yb, ub, vb)
2364 });
2365 // A palette-Y block's own prediction is the reconstructed colour-index
2366 // map, not `predict()`'s edge-based one -- [`PALETTE_PRED`] carries it
2367 // to [`PlaneBuf::reconstruct`]'s next call rather than threading a
2368 // parameter through this function's dozen `y.reconstruct`/`read_plane`
2369 // sites. A split luma transform (`tx_select && logical_tx != side`)
2370 // would need the map sliced per-TU -- untested against a real
2371 // `--enable-palette=1` stream this round, so refuse by name rather than
2372 // guess at the slicing (charter's own named-acceptable fallback).
2373 let palette_y_buf: Option<Vec<u16>> = palette_y
2374 .as_ref()
2375 .map(|py| py.map.iter().map(|&idx| py.colors[idx as usize]).collect());
2376 // lane-t900 r32: the intrabc luma prediction rides the very same
2377 // whole-block override slot, so the multi-TU loop below windows it per
2378 // transform unit exactly like a palette map -- setting it once up front
2379 // handed the whole `side`x`side` buffer to the FIRST unit and left every
2380 // later one predicting off block edges (the var-tx tree above is what
2381 // first makes `logical_tx < side` reachable for an intrabc block).
2382 let palette_y_buf = match &intrabc_bufs {
2383 Some((yb, _, _)) => Some(yb.clone()),
2384 None => palette_y_buf,
2385 };
2386 // With one luma transform unit the whole `side`x`side` map is the
2387 // prediction; with several (`logical_tx != side`) each unit takes its own
2388 // `logical_tx`-sized window of that same map, set fresh inside the TU loop
2389 // below (lane-palette2 r7) -- setting the full-block buffer here would be
2390 // taken by the FIRST unit and indexed at the wrong stride.
2391 // lane-svt1: a SKIPPED block predicts the whole `side`x`side` in ONE call
2392 // (the `else` arm below -- a palette/intrabc block never takes the per-unit
2393 // `split_tx_skip` walk), so its map must be armed here even when the
2394 // transform is split. Gating the arm on `logical_tx == side` alone left a
2395 // 16x16 palette block with `tx_depth == 1` and `skip == 1` predicting DC
2396 // off its own edges: right symbols, wrong pixels (SVT-AV1 preset-8 screen
2397 // key frame; class override-slot-on-one-arm). Neither prediction is
2398 // edge-derived, so the whole-block buffer at the block's own stride is
2399 // exactly what that single call wants.
2400 // Counted on the SHAPE, not on the arm below, so a gate can tell a stream
2401 // that reaches this block apart from one that never does (class
2402 // gate-blind-to-feature).
2403 if palette_y_buf.is_some() && skip && logical_tx < side {
2404 hit!(SKIP_SPLIT_TX_OVERRIDE_HITS);
2405 }
2406 if let Some(buf) = &palette_y_buf
2407 && (logical_tx == side || skip)
2408 {
2409 set_palette_pred(buf.clone(), fctx);
2410 }
2411 // A UV-palette block's own chroma prediction override (lane-palette2 r1),
2412 // same [`PALETTE_PRED`] slot as Y above -- set fresh right before each
2413 // plane's own `reconstruct`/`read_plane` call below (never both planes at
2414 // once), since Y's own set-then-take already emptied the slot by the time
2415 // either of these run.
2416 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
2417 (
2418 puv.map
2419 .iter()
2420 .map(|&idx| puv.u_colors[idx as usize])
2421 .collect(),
2422 puv.map
2423 .iter()
2424 .map(|&idx| puv.v_colors[idx as usize])
2425 .collect(),
2426 )
2427 });
2428 // The chroma half of the intrabc prediction rides the same per-plane
2429 // override slot the UV-palette buffers do (set fresh before each plane's
2430 // own `reconstruct`/`read_plane` call below).
2431 let palette_uv_bufs = match &intrabc_bufs {
2432 Some((_, ub, vb)) => Some((ub.clone(), vb.clone())),
2433 None => palette_uv_bufs,
2434 };
2435 if skip {
2436 // A skipped block codes no residual syntax at all (spec 5.11.34):
2437 // straight prediction, on every plane.
2438 //
2439 // lane-hgkf r2: an intra block's `tx_depth` is read whether or not it
2440 // is skipped (only an INTER skip forces the largest transform), and
2441 // spec 7.11.2 / libaom `predict_and_reconstruct_intra_block` predicts
2442 // ONE TRANSFORM UNIT AT A TIME -- each unit's edges are the units
2443 // already written left/above of it inside this same block. Predicting
2444 // the whole `side`x`side` at once gives a different (uniformly off by
2445 // ~1) answer, which is exactly the residue this lane was chasing.
2446 // The palette/intrabc override path keeps the single-call shape (its
2447 // per-TU windowing is the non-skip loop's own `palette_y_buf` slice,
2448 // untested for skip and unreachable in these streams).
2449 // lane-sb128b r2: a 128x128 block's transform is TX_64X64 even with
2450 // `tx_select` off (`max_txsize_rect_lookup[BLOCK_128X128]`), so the
2451 // per-unit prediction is keyed on the transform being smaller than
2452 // the block, not on the tx-depth syntax. The counter keeps lane-hgkf's
2453 // narrower meaning (a READ split tx depth).
2454 let split_tx_skip = logical_tx < side && palette_y_buf.is_none() && intrabc_bufs.is_none();
2455 if split_tx_skip {
2456 if tx_select {
2457 hit!(SKIP_SPLIT_TX_HITS);
2458 }
2459 let n_axis = side / logical_tx;
2460 for tu_row in 0..n_axis {
2461 for tu_col in 0..n_axis {
2462 let tu_px = px + tu_col * logical_tx;
2463 let tu_py = py + tu_row * logical_tx;
2464 if tu_px >= y.true_width || tu_py >= y.true_height {
2465 continue;
2466 }
2467 let tu_reach = tu_reach(
2468 side,
2469 side,
2470 tu_col * logical_tx,
2471 tu_row * logical_tx,
2472 logical_tx,
2473 reach,
2474 px,
2475 py,
2476 y.width,
2477 y.height,
2478 fctx,
2479 );
2480 push_intra(
2481 y,
2482 u,
2483 v,
2484 0,
2485 tu_px,
2486 tu_py,
2487 logical_tx,
2488 mode,
2489 angle_delta_y,
2490 tu_reach,
2491 &ZERO_RESIDUAL[..logical_tx * logical_tx],
2492 None,
2493 filter_intra,
2494 smooth_neighbor,
2495 fctx,
2496 );
2497 }
2498 }
2499 } else {
2500 push_intra(
2501 y,
2502 u,
2503 v,
2504 0,
2505 px,
2506 py,
2507 side,
2508 mode,
2509 angle_delta_y,
2510 reach,
2511 &ZERO_RESIDUAL[..side * side],
2512 None,
2513 filter_intra,
2514 smooth_neighbor,
2515 fctx,
2516 );
2517 }
2518 let ac = alpha.map(|_| cfl_src(px, py, side));
2519 // lane-av1-422b: the chroma unit grid is `cn_cols` x `cn_rows` --
2520 // square at 4:2:0/4:4:4, at 4:2:2 `(side/2)/tx` units wide by
2521 // `side/tx` tall (the plane block is (side/2, side)). A unit's LUMA
2522 // anchor follows the per-axis shifts: `chroma_tx << ss_x` wide,
2523 // `chroma_tx_h << ss_y` tall (lane-av1-422f: the unit itself is the
2524 // (chroma_tx, chroma_tx_h) rect, so a 4:2:2 frame below side 64
2525 // reads ONE unit per plane, the whole plane block).
2526 let cn_cols = (chroma_side / chroma_tx).max(1);
2527 let cn_rows = (chroma_height / chroma_tx_h).max(1);
2528 let luma_span_x = chroma_tx << ss_x(fctx);
2529 let luma_span_y = chroma_tx_h << ss_y(fctx);
2530 for cu_row in 0..cn_rows {
2531 for cu_col in 0..cn_cols {
2532 let cu_r = if cn_rows == 1 && cn_cols == 1 {
2533 reach
2534 } else {
2535 tu_reach_rect(
2536 side,
2537 side,
2538 cu_col * luma_span_x,
2539 cu_row * luma_span_y,
2540 luma_span_x,
2541 luma_span_y,
2542 reach,
2543 px,
2544 py,
2545 y.width,
2546 y.height,
2547 fctx,
2548 )
2549 };
2550 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
2551 // lane-av1chromadc: the chroma override is a whole
2552 // `chroma_side x chroma_height` buffer and
2553 // `PlaneBuf::reconstruct` uses the buffer it takes as the
2554 // UNIT's own `chroma_tx x chroma_tx_h` prediction, so a
2555 // multi-unit plane block must hand each unit its own window of
2556 // it. Handing the whole buffer (the pre-fix shape) made every
2557 // unit predict from the top-left one: at 4:2:0 the chroma plane
2558 // block is a single 32x32 unit, so the whole buffer IS that
2559 // unit's window and the bug is invisible -- which is why every
2560 // 4:2:0 gate stayed green -- and at 4:4:4 a 64x64 block's 64x64
2561 // plane block is a 2x2 grid whose right and bottom columns were
2562 // a copy of its top-left unit.
2563 // MEASURED on `fixtures/r512.obu` (4:4:4 8-bit 512x512, three
2564 // frames): frame 0's skipped 64x64 intra-BC block at
2565 // `mi=(112,80)` `px=(320,448)` reconstructed its `cu=(1,0)`
2566 // unit at `px=(352,448)` as a flat 241 where the oracle has
2567 // 202 -- byte-identical to its `cu=(0,0)` prediction, sum
2568 // 882176 and all -- and the coded 64x64 to its right then read
2569 // 202/175 against the oracle's 165/166. Gate:
2570 // `a_444_skipped_64x64_square_block_windows_its_chroma_override_per_unit`.
2571 let chroma_window = |buf: &[u16]| -> Vec<u16> {
2572 if cn_cols == 1 && cn_rows == 1 {
2573 return buf.to_vec();
2574 }
2575 let mut window = Vec::with_capacity(chroma_tx * chroma_tx_h);
2576 for row in 0..chroma_tx_h {
2577 let at = (cu_row * chroma_tx_h + row) * chroma_side + cu_col * chroma_tx;
2578 window.extend_from_slice(&buf[at..at + chroma_tx]);
2579 }
2580 window
2581 };
2582 if let Some((ub, _)) = &palette_uv_bufs {
2583 if cn_cols * cn_rows > 1 {
2584 hit!(SKIP_CHROMA_OVERRIDE_WINDOW_HITS);
2585 }
2586 set_palette_pred(chroma_window(ub), fctx);
2587 }
2588 push_intra_unit(
2589 y,
2590 u,
2591 v,
2592 1,
2593 cu_x,
2594 cu_y,
2595 chroma_tx,
2596 chroma_tx_h,
2597 uv_predict_mode,
2598 angle_delta_uv,
2599 cu_r,
2600 &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h],
2601 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
2602 None,
2603 smooth_neighbor_uv,
2604 fctx,
2605 );
2606 if let Some((_, vb)) = &palette_uv_bufs {
2607 set_palette_pred(chroma_window(vb), fctx);
2608 }
2609 push_intra_unit(
2610 y,
2611 u,
2612 v,
2613 2,
2614 cu_x,
2615 cu_y,
2616 chroma_tx,
2617 chroma_tx_h,
2618 uv_predict_mode,
2619 angle_delta_uv,
2620 cu_r,
2621 &ZERO_RESIDUAL[..chroma_tx * chroma_tx_h],
2622 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
2623 None,
2624 smooth_neighbor_uv,
2625 fctx,
2626 );
2627 }
2628 }
2629 let luma_grid = vec![0i32; side * side];
2630 // lane-av1muchroma site 1: the skip arm's chroma grids are the
2631 // block's PLANE BLOCK per axis (`chroma_side` x `chroma_height`),
2632 // not a square. `chroma_side` here is `side >> ss_x` -- the key-frame
2633 // path's own binding, which at 4:2:2 (ss (1,0)) is `side / 2`, so the
2634 // old `chroma_side * chroma_side` allocated HALF the block's chroma:
2635 // a 64x64 block's plane block is 32x64 = 2048 samples and the square
2636 // held 1024, a 2x under-read for any per-row consumer. No current
2637 // consumer indexes it -- `record_rect` -> `record_mi_rect` reduces
2638 // each plane through `neighbour_state`, which sums the slice and
2639 // reads `grid[0]` only, and every sample is zero on a skip block --
2640 // so the shape is latent, not live (mutation-verified: sizing this
2641 // per-axis leaves every pinned 4:2:2 gate green, shrinking sites
2642 // 11/12 to per-axis reds two). Fixed here so the allocation cannot
2643 // go short if a per-row consumer ever lands. At 4:2:0 the two are
2644 // the same number and at 4:4:4 `chroma_side == chroma_height ==
2645 // side`, so only 4:2:2 changes.
2646 let u_grid = vec![0i32; chroma_side * chroma_height];
2647 let v_grid = vec![0i32; chroma_side * chroma_height];
2648 // The measured arm, not a proxy: how many samples this block's
2649 // chroma bookkeeping grid is SHORT of its own plane block. The
2650 // square form this lane removed is `chroma_side * chroma_side`,
2651 // which at 4:2:2 is half the plane block; restoring it makes this
2652 // non-zero on every 4:2:2 skip block, and the witness gate asserts
2653 // the total stayed 0.
2654 let plane_block = chroma_side * chroma_height;
2655 let short = plane_block.saturating_sub(u_grid.len());
2656 hit_do!(SKIP_ARM_CHROMA_SHORT_SAMPLES.with(|c| c.set(c.get() + short)));
2657 if chroma_side != chroma_height {
2658 hit!(SKIP_ARM_CHROMA_RECT_SHAPES);
2659 }
2660 neighbours.record(
2661 at,
2662 side,
2663 mode,
2664 uv_predict_mode,
2665 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
2666 );
2667 } else if logical_tx == side {
2668 // lane-sb128b r1: the test used to be `!tx_select || logical_tx == side`.
2669 // Without `tx_select` `logical_tx` IS `side` at every size <= 64, so
2670 // that arm was redundant -- and wrong at 128, where
2671 // `max_txsize_rect_lookup` caps the block's transform at 64 and the
2672 // block is four units whether or not `tx_select` is on.
2673 // A single luma transform unit -- the old path, unchanged (including
2674 // the 64x64 corner case, `logical_tx == side == 64` with
2675 // `coeff_tx_side == 32`).
2676 let around = neighbours.around(at, side);
2677 let luma_grid = read_plane(
2678 dec,
2679 cdfs,
2680 luma_set,
2681 luma_scan,
2682 0,
2683 around[0],
2684 mode,
2685 mode,
2686 angle_delta_y,
2687 reach,
2688 y,
2689 u,
2690 v,
2691 px,
2692 py,
2693 side,
2694 coeff_tx_side,
2695 base_q_idx,
2696 None,
2697 filter_intra,
2698 None,
2699 smooth_neighbor,
2700 fctx,
2701 )?;
2702 let ac = alpha.map(|_| cfl_src(px, py, side));
2703 // Armed for exactly this block's two chroma reads (see
2704 // [`INTRABC_CHROMA_TX`]); the luma call above just set
2705 // [`LUMA_TX_TYPE`] to the type it coded.
2706 if intrabc_dv.is_some() {
2707 fctx.intrabc_chroma_tx
2708 .with(|c| c.set(Some(fctx.luma_tx_type.with(std::cell::Cell::get))));
2709 }
2710 // lane-av1-444: this arm is one luma TU (`logical_tx == side`), including
2711 // the 64x64 case whose coefficient grid is 32. At 4:4:4 the chroma plane
2712 // is the same size as luma and `av1_get_max_uv_txsize` caps it at
2713 // TX_32X32, so a 64x64 block codes four chroma units, plane-major
2714 // (every U, then every V) — the same loop the multi-TU arm runs.
2715 // At 4:2:0 `chroma_side == chroma_tx`, so it stays one read.
2716 // lane-av1-422b: 4:2:2 never collapses to one read above a 4x4 luma
2717 // block -- the unit grid is `(side/2)/tx` wide by `side/tx` tall.
2718 // lane-av1-422f: `chroma_tx` is the unit WIDTH and `chroma_tx_h` its
2719 // HEIGHT, so below side 64 a 4:2:2 frame's grid is 1x1 and the one
2720 // unit is the plane block's own rect.
2721 let cn_cols = (chroma_side / chroma_tx).max(1);
2722 let cn_rows = (chroma_height / chroma_tx_h).max(1);
2723 let luma_span_x = chroma_tx << ss_x(fctx);
2724 let luma_span_y = chroma_tx_h << ss_y(fctx);
2725 let (u_grid, v_grid, chroma_units) = if cn_rows == 1 && cn_cols == 1 {
2726 if chroma_tx == chroma_tx_h {
2727 if let Some((ub, _)) = &palette_uv_bufs {
2728 set_palette_pred(ub.clone(), fctx);
2729 }
2730 let u_grid = read_plane(
2731 dec,
2732 cdfs,
2733 chroma_set,
2734 scans.1,
2735 1,
2736 around[1],
2737 mode,
2738 uv_predict_mode,
2739 angle_delta_uv,
2740 reach,
2741 y,
2742 u,
2743 v,
2744 cpx,
2745 cpy,
2746 chroma_side,
2747 chroma_tx,
2748 base_q_idx,
2749 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
2750 None,
2751 None,
2752 smooth_neighbor_uv,
2753 fctx,
2754 )?;
2755 if crate::envflags::env_flag!("EC_AV1_TRACE") {
2756 eprintln!(
2757 "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
2758 &u.data[cpy * u.width + cpx..][..chroma_side]
2759 );
2760 }
2761 if let Some((_, vb)) = &palette_uv_bufs {
2762 set_palette_pred(vb.clone(), fctx);
2763 }
2764 let v_grid = read_plane(
2765 dec,
2766 cdfs,
2767 chroma_set,
2768 scans.1,
2769 2,
2770 around[2],
2771 mode,
2772 uv_predict_mode,
2773 angle_delta_uv,
2774 reach,
2775 y,
2776 u,
2777 v,
2778 cpx,
2779 cpy,
2780 chroma_side,
2781 chroma_tx,
2782 base_q_idx,
2783 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
2784 None,
2785 None,
2786 smooth_neighbor_uv,
2787 fctx,
2788 )?;
2789 (u_grid, v_grid, Vec::new())
2790 } else {
2791 // lane-av1-422f: the one unit is a RECT filling the plane
2792 // block -- the square-shaped [`read_plane`] cannot express
2793 // it, so both planes go through [`read_rect_chroma_unit`]
2794 // (U, then V, the same order the square arm reads). The
2795 // chroma context reads per chroma 4-px cell (see
2796 // [`Neighbours::around_mi_422_chroma`]).
2797 let chroma_around = neighbours.around_mi_422_chroma((mi_r, mi_c), side, side);
2798 if let Some((ub, _)) = &palette_uv_bufs {
2799 set_palette_pred(ub.clone(), fctx);
2800 }
2801 let u_grid = read_rect_chroma_unit(
2802 dec,
2803 cdfs,
2804 chroma_set,
2805 scans.1,
2806 chroma_tx,
2807 chroma_tx_h,
2808 1,
2809 chroma_around[1],
2810 uv_predict_mode,
2811 angle_delta_uv,
2812 reach,
2813 y,
2814 u,
2815 v,
2816 cpx,
2817 cpy,
2818 base_q_idx,
2819 None,
2820 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
2821 smooth_neighbor_uv,
2822 fctx,
2823 )?;
2824 if let Some((_, vb)) = &palette_uv_bufs {
2825 set_palette_pred(vb.clone(), fctx);
2826 }
2827 let v_grid = read_rect_chroma_unit(
2828 dec,
2829 cdfs,
2830 chroma_set,
2831 scans.1,
2832 chroma_tx,
2833 chroma_tx_h,
2834 2,
2835 chroma_around[2],
2836 uv_predict_mode,
2837 angle_delta_uv,
2838 reach,
2839 y,
2840 u,
2841 v,
2842 cpx,
2843 cpy,
2844 base_q_idx,
2845 None,
2846 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
2847 smooth_neighbor_uv,
2848 fctx,
2849 )?;
2850 (u_grid, v_grid, Vec::new())
2851 }
2852 } else {
2853 let chroma_ctx_offset = Some(3);
2854 let mut u_pass: Vec<Grid> = Vec::new();
2855 let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new();
2856 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
2857 for plane_pass in 1..=2usize {
2858 let mut pass_idx = 0usize;
2859 for cu_row in 0..cn_rows {
2860 for cu_col in 0..cn_cols {
2861 let cu_mi = (
2862 mi_r + cu_row * (luma_span_y / MI),
2863 mi_c + cu_col * (luma_span_x / MI),
2864 );
2865 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
2866 // lane-av1-422f: chroma-only loop; per-chroma-cell
2867 // above votes (see [`Neighbours::around_mi_422_chroma`]).
2868 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
2869 } else {
2870 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
2871 };
2872 let cu_reach = tu_reach_rect(
2873 side,
2874 side,
2875 cu_col * luma_span_x,
2876 cu_row * luma_span_y,
2877 luma_span_x,
2878 luma_span_y,
2879 reach,
2880 px,
2881 py,
2882 y.width,
2883 y.height,
2884 fctx,
2885 );
2886 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
2887 if let Some((ub, vb)) = &palette_uv_bufs {
2888 let pbuf = if plane_pass == 1 { ub } else { vb };
2889 set_palette_pred(
2890 palette_window(
2891 pbuf,
2892 chroma_side,
2893 cu_col * chroma_tx,
2894 cu_row * chroma_tx_h,
2895 chroma_tx,
2896 chroma_tx_h,
2897 ),
2898 fctx,
2899 );
2900 }
2901 let cu_grid = read_plane(
2902 dec,
2903 cdfs,
2904 chroma_set,
2905 scans.1,
2906 plane_pass,
2907 cu_around[plane_pass],
2908 mode,
2909 uv_predict_mode,
2910 angle_delta_uv,
2911 cu_reach,
2912 y,
2913 u,
2914 v,
2915 cu_x,
2916 cu_y,
2917 chroma_tx,
2918 chroma_tx,
2919 base_q_idx,
2920 alpha
2921 .zip(ac)
2922 .map(|((au, av), ac)| (if plane_pass == 1 { au } else { av }, ac)),
2923 None,
2924 chroma_ctx_offset,
2925 smooth_neighbor_uv,
2926 fctx,
2927 )?;
2928 hit!(CHROMA_SPLIT_TX_HITS);
2929 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
2930 hit!(CHROMA422_SQUARE_HITS);
2931 }
2932 // Immediately, so the next unit of this block reads this
2933 // one's coefficient context. `record` below stamps one
2934 // chroma state across the whole block; the replay after
2935 // it puts the per-unit state back.
2936 neighbours.record_mi_chroma(
2937 cu_mi,
2938 luma_span_x,
2939 luma_span_y,
2940 plane_pass,
2941 &cu_grid,
2942 );
2943 if plane_pass == 1 {
2944 u_pass.push(cu_grid);
2945 } else {
2946 let u_grid = std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
2947 units.push((
2948 cu_mi,
2949 luma_span_x,
2950 luma_span_y,
2951 u_grid.clone(),
2952 cu_grid.clone(),
2953 ));
2954 last_grids = [u_grid, cu_grid];
2955 }
2956 pass_idx += 1;
2957 }
2958 }
2959 }
2960 (last_grids[0].clone(), last_grids[1].clone(), units)
2961 };
2962 fctx.intrabc_chroma_tx.with(|c| c.set(None));
2963 neighbours.record(
2964 at,
2965 side,
2966 mode,
2967 uv_predict_mode,
2968 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
2969 );
2970 for (cu_mi, sw, sh, u_unit, v_unit) in &chroma_units {
2971 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_unit);
2972 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_unit);
2973 }
2974 } else {
2975 // Several luma transform units, raster order (spec
2976 // `transform_block`'s loop): the block's resolved transform is
2977 // genuinely smaller than its own side, so each tile of it predicts
2978 // and codes independently, its own context read fresh off whatever
2979 // the earlier tiles in this same block already wrote -- the same
2980 // per-TU pattern [`decode_leaf8`] already runs for an 8x8 leaf.
2981 let n_axis = side / logical_tx;
2982 // lane-av1-422f: unit width/height per axis, like walk 2 above --
2983 // a 4:2:2 frame below side 64 reads ONE rect unit per plane per
2984 // chunk, the whole plane block.
2985 let cn_cols = (chroma_side / chroma_tx).max(1);
2986 let cn_rows = (chroma_height / chroma_tx_h).max(1);
2987 let luma_span_x = chroma_tx << ss_x(fctx);
2988 let luma_span_y = chroma_tx_h << ss_y(fctx);
2989 // libaom's transform-block loop is over 64x64 luma "mu" chunks
2990 // (`decode_token_recon_block`: `mu_blocks_wide/high` =
2991 // `mi_size_wide[BLOCK_64X64]`), and it codes EVERY PLANE of a chunk
2992 // before moving to the next one. Below 128 a block is a single chunk,
2993 // so this is byte-for-byte the all-luma-then-all-chroma order that has
2994 // always run; at 128 the four quadrants interleave Y,U,V per quadrant
2995 // and reading all four luma units first desyncs the tile at the second
2996 // one (lane-sb128b r3, measured against aomdec's `EC_TRACE_COEFF`).
2997 let nchunk = (side / 64).max(1);
2998 // `cn > 1` means the uv plane block is larger than the uv transform,
2999 // which moves libaom's chroma `txb_skip_ctx` offset from 7 to 10.
3000 let chroma_ctx_offset = if cn_rows * cn_cols > 1 { Some(3) } else { None };
3001 let tpc = (n_axis / nchunk).max(1);
3002 let cpc_rows = (cn_rows / nchunk).max(1);
3003 let cpc_cols = (cn_cols / nchunk).max(1);
3004 // The block's luma transform units, raster order inside each mu
3005 // chunk. lane-av1-ibcvtx: an intrabc block's units are the var-tx
3006 // tree's own leaf list -- mixed sizes included, exactly what libaom's
3007 // `decode_token_recon_block` token loop reconstructs (one
3008 // `av1_read_coeffs_txb` + inverse transform per resolved unit) --
3009 // while every other block's list is the uniform `logical_tx` grid
3010 // this loop has always walked, generated here in the same order.
3011 let mut chunk_tus: Vec<Vec<(usize, usize, usize)>> = vec![Vec::new(); nchunk * nchunk];
3012 if let Some(leaves) = &intrabc_leaves {
3013 for &(lr, lc, tw, _th) in leaves {
3014 let (off_y, off_x) = (lr * MI, lc * MI);
3015 chunk_tus[(off_y / 64) * nchunk + (off_x / 64)].push((off_y, off_x, tw));
3016 }
3017 } else {
3018 for tu_row in 0..n_axis {
3019 for tu_col in 0..n_axis {
3020 chunk_tus[(tu_row / tpc) * nchunk + (tu_col / tpc)].push((
3021 tu_row * logical_tx,
3022 tu_col * logical_tx,
3023 logical_tx,
3024 ));
3025 }
3026 }
3027 }
3028 let mut last_grids = [Grid::Zero(0), Grid::Zero(0)];
3029 let mut units: Vec<((usize, usize), usize, usize, Grid, Grid)> = Vec::new();
3030 for ch_row in 0..nchunk {
3031 for ch_col in 0..nchunk {
3032 // lane-av1-ibcvtx: the chunk's chroma units inherit the CHROMA tx
3033 // type of the co-located luma position (`av1_get_tx_type`,
3034 // blockd.h:1278: a non-Y plane of an inter-classified block -- and
3035 // intrabc is one -- reads `tx_type_map`, i.e. the coded type of the
3036 // luma unit covering it). Inside a mu chunk that is the chunk's
3037 // FIRST luma unit in raster order (the chunk origin is always the
3038 // first leaf's own origin). Captured right after that unit's read;
3039 // the single-TU arm below does the same for a whole-block unit.
3040 let mut first_leaf_tx: Option<TxType> = None;
3041 for &(tu_off_y, tu_off_x, tu_tx) in &chunk_tus[ch_row * nchunk + ch_col] {
3042 let tu_mi = (mi_r + tu_off_y / MI, mi_c + tu_off_x / MI);
3043 let tu_px = px + tu_off_x;
3044 let tu_py = py + tu_off_y;
3045 // Same libaom clip as `decode_rect_split`'s loop above; a
3046 // square block only hangs off the frame when the frame's mi
3047 // dimensions are odd at the block's own level.
3048 if tu_px >= y.true_width || tu_py >= y.true_height {
3049 continue;
3050 }
3051 let tu_around = neighbours.around_mi(tu_mi, tu_tx)[0];
3052 // A transform unit inside a block is NOT a block at that
3053 // position (lane-palette2 r12): `Reach::of` granted the
3054 // top-right 8x8 unit of a 16x16 D203 block bottom-left
3055 // pixels libaom refuses outright (`col_off > 0`), which is
3056 // the diagonal wedge seed 46 reconstructed wrong.
3057 let tu_reach = tu_reach(
3058 side, side, tu_off_x, tu_off_y, tu_tx, reach, px, py, y.width, y.height,
3059 fctx,
3060 );
3061 // This transform unit's own bsize (`tu_tx`) is smaller
3062 // than the block it sits in (`side`), so `txb_skip_ctx` is
3063 // the neighbour-magnitude table, not the lone-TU 0 (spec
3064 // `get_txb_ctx_general`'s `plane_bsize != tx_size` branch).
3065 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tu_tx / MI);
3066 // An intrabc unit's CDF set and scan follow the unit's OWN
3067 // resolved size (`get_txsize_entropy_ctx` /
3068 // `av1_get_scan` per `av1_read_coeffs_txb` call); the
3069 // uniform grid's precomputed pair already matches because
3070 // `tu_tx == logical_tx` there.
3071 let (tu_set, tu_scan) = if intrabc_dv.is_some() {
3072 (
3073 inter_txbset_for(tu_tx, reduced_tx_set),
3074 scan_for(
3075 if tu_tx == 64 { 32 } else { tu_tx },
3076 scan32,
3077 scan16,
3078 scan8,
3079 scan4,
3080 ),
3081 )
3082 } else {
3083 (luma_set, luma_scan)
3084 };
3085 if let Some(buf) = &palette_y_buf {
3086 hit!(PALETTE_SPLIT_TX_HITS);
3087 let mut window = vec![0u16; tu_tx * tu_tx];
3088 for row in 0..tu_tx {
3089 let src = (tu_off_y + row) * side + tu_off_x;
3090 window[row * tu_tx..][..tu_tx].copy_from_slice(&buf[src..][..tu_tx]);
3091 }
3092 set_palette_pred(window, fctx);
3093 }
3094 let tu_grid = read_plane(
3095 dec,
3096 cdfs,
3097 tu_set,
3098 tu_scan,
3099 0,
3100 tu_around,
3101 mode,
3102 mode,
3103 angle_delta_y,
3104 tu_reach,
3105 y,
3106 u,
3107 v,
3108 tu_px,
3109 tu_py,
3110 tu_tx,
3111 // The unit's own COEFFICIENT grid, half its side at
3112 // TX_64X64 (a 64-point transform codes nothing past 32);
3113 // identical to `tu_tx` at every smaller size
3114 // (lane-sb128b r1).
3115 if tu_tx == 64 { 32 } else { tu_tx },
3116 base_q_idx,
3117 None,
3118 filter_intra,
3119 Some(tu_skip_ctx),
3120 smooth_neighbor,
3121 fctx,
3122 )?;
3123 if crate::envflags::env_flag!("EC_AV1_TRACE") {
3124 eprintln!(
3125 "TRACE tu_bitpos mi=({},{}) tell={}",
3126 tu_mi.0,
3127 tu_mi.1,
3128 dec.debug_bitpos()
3129 );
3130 }
3131 neighbours.record_mi_luma(tu_mi, tu_tx, &tu_grid);
3132 if first_leaf_tx.is_none() {
3133 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
3134 }
3135 }
3136 // CfL is only allowed up to 32x32, i.e. only at `nchunk == 1`, where
3137 // this still runs after every luma unit of the block.
3138 let ac = alpha.map(|_| cfl_src(px, py, side));
3139 // lane-av1-ibcvtx: an intrabc block's chroma rides the luma's coded
3140 // tx type (see `first_leaf_tx` above) -- the same arm the single-TU
3141 // branch sets before its own chroma reads.
3142 if intrabc_dv.is_some()
3143 && let Some(t) = first_leaf_tx
3144 {
3145 fctx.intrabc_chroma_tx.with(|c| c.set(Some(t)));
3146 }
3147 // The block's uv plane block is `chroma_side` across but its uv
3148 // transform is `chroma_tx` (`av1_get_max_uv_txsize` =
3149 // `av1_get_adjusted_tx_size(max_txsize_rect_lookup[uv_plane_bsize])`):
3150 // identical at every size up to 64x64, but a 128x128 block's 64x64 uv
3151 // plane block adjusts TX_64X64 down to TX_32X32, so each plane is
3152 // FOUR units (lane-sb128b r2) -- one per mu chunk.
3153 // libaom `decode_token_recon_block` codes a mu chunk PLANE-MAJOR
3154 // (`for (plane..) for (blk_row..) for (blk_col..)`): every U unit of
3155 // the chunk, then every V unit. At one unit per plane per chunk --
3156 // every non-lossless case this decoder reaches -- that is the same
3157 // symbol order as the interleaved pair this loop used to read; a
3158 // lossless frame's 4x4 chroma units are the case where it differs
3159 // (lane-lossless2).
3160 let mut u_pass: Vec<Grid> = Vec::new();
3161 for plane_pass in 1..=2usize {
3162 let mut pass_idx = 0usize;
3163 for cu_row in ch_row * cpc_rows..(ch_row + 1) * cpc_rows {
3164 for cu_col in ch_col * cpc_cols..(ch_col + 1) * cpc_cols {
3165 // libaom `decode_reconstruct_tx`'s frame-edge clip
3166 // (decodeframe.c:299, `blk_row >= max_blocks_high || blk_col
3167 // >= max_blocks_wide` returns before ANY symbol is read): a
3168 // transform unit whose 4x4 origin sits outside the frame's mi
3169 // grid is not coded at all. The luma loop above carries the
3170 // same clip; its absence here read `txb_skip` (+coeffs) for
3171 // chroma units libaom never wrote -- the lossless 64x64 block
3172 // at mi(48,0) of a 320x240 frame overhangs the bottom edge by
3173 // 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units, not
3174 // eight (lane-av1-loss64; 48 chroma units per plane in
3175 // aomdec's EC_COEFF census vs the 64 this loop read).
3176 // `max_block_wide/high` (av1_common_int.h:1565): the plane
3177 // block's pixel span (4:2:0 halves the luma span, clamped to
3178 // 4 by `set_plane_n4`) plus the negative overhang
3179 // (`mb_to_*_edge` = `2 * overhang_mi` chroma px), in 4x4
3180 // units.
3181 let span_mi = side / MI;
3182 let over_w_mi = (2 * y.true_width.div_ceil(8)) as i32
3183 - mi_c as i32
3184 - span_mi as i32;
3185 let over_h_mi = (2 * y.true_height.div_ceil(8)) as i32
3186 - mi_r as i32
3187 - span_mi as i32;
3188 // `max_block_wide/high` in chroma pixels: the plane block's
3189 // own span (`side` at 4:4:4, `side / 2` at 4:2:0 -- the old
3190 // hardcoded `span_mi * 2` clipped three quarters of a 4:4:4
3191 // block's coded units and desynced the tile) plus the
3192 // negative overhang (`mb_to_*_edge >> (3 + ss)`), whose
3193 // chroma-px scale is `MI >> ss` per mi.
3194 let plane_px = (((span_mi * MI) >> ss_x(fctx)).max(4)) as i32;
3195 let over_w_px = over_w_mi.min(0) * (MI >> ss_x(fctx)) as i32;
3196 let over_h_px = over_h_mi.min(0) * (MI >> ss_y(fctx)) as i32;
3197 let max_units_w = ((plane_px + over_w_px) >> 2).max(0) as usize;
3198 // lane-av1-422f: the shared halved formula in the `else` counts
3199 // the plane span in 4-px units through the 2-px-per-mi
3200 // subsampled height, which a 4:2:2 plane does not have (ss_y
3201 // 0) -- its span is the full luma mi count, so a keyed
3202 // formula clips the same units libaom's `max_block_high`
3203 // does. 4:2:0 and 4:4:4 keep the proven shared rows (at 4:2:0
3204 // `MI >> ss_y` is 2, the same `2 * over_h_mi.min(0)` the
3205 // pre-ss form spelled).
3206 let max_units_h = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
3207 (span_mi as i32 + over_h_mi.min(0)).max(0) as usize
3208 } else {
3209 ((plane_px + over_h_px) >> 2).max(0) as usize
3210 };
3211 let (unit_w, unit_h) = (chroma_tx / 4, chroma_tx_h / 4);
3212 if cu_col * unit_w >= max_units_w || cu_row * unit_h >= max_units_h {
3213 hit!(CHROMA_EDGE_TU_CLIP_HITS);
3214 continue;
3215 }
3216 // The chroma context arrays are indexed in LUMA mi, so this
3217 // unit's anchor is its own luma quadrant (lane-av1-422b: the
3218 // quadrant spans `chroma_tx << ss_x` luma px wide by
3219 // `chroma_tx_h << ss_y` tall -- at 4:2:2 below side 64 the
3220 // one unit's quadrant is the whole block).
3221 let cu_mi = (
3222 mi_r + cu_row * (luma_span_y / MI),
3223 mi_c + cu_col * (luma_span_x / MI),
3224 );
3225 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
3226 // lane-av1-422f: chroma-only loop; per-chroma-cell above
3227 // votes (see [`Neighbours::around_mi_422_chroma`]).
3228 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
3229 } else {
3230 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
3231 };
3232 let cu_reach = if cn_rows == 1 && cn_cols == 1 {
3233 reach
3234 } else {
3235 tu_reach_rect(
3236 side,
3237 side,
3238 cu_col * luma_span_x,
3239 cu_row * luma_span_y,
3240 luma_span_x,
3241 luma_span_y,
3242 reach,
3243 px,
3244 py,
3245 y.width,
3246 y.height,
3247 fctx,
3248 )
3249 };
3250 let (cu_x, cu_y) =
3251 (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
3252 if let Some((ub, vb)) = &palette_uv_bufs {
3253 let pbuf = if plane_pass == 1 { ub } else { vb };
3254 set_palette_pred(
3255 palette_window(
3256 pbuf,
3257 chroma_side,
3258 cu_col * chroma_tx,
3259 cu_row * chroma_tx_h,
3260 chroma_tx,
3261 chroma_tx_h,
3262 ),
3263 fctx,
3264 );
3265 }
3266 let cu_grid = if chroma_tx == chroma_tx_h {
3267 read_plane(
3268 dec,
3269 cdfs,
3270 chroma_set,
3271 scans.1,
3272 plane_pass,
3273 cu_around[plane_pass],
3274 mode,
3275 uv_predict_mode,
3276 angle_delta_uv,
3277 cu_reach,
3278 y,
3279 u,
3280 v,
3281 cu_x,
3282 cu_y,
3283 chroma_tx,
3284 chroma_tx,
3285 base_q_idx,
3286 alpha.zip(ac).map(|((au, av), ac)| {
3287 (if plane_pass == 1 { au } else { av }, ac)
3288 }),
3289 None,
3290 chroma_ctx_offset,
3291 smooth_neighbor_uv,
3292 fctx,
3293 )?
3294 } else {
3295 // lane-av1-422f: the whole plane block as one rect unit;
3296 // `chroma_ctx_offset` is `None` there (the unit covers
3297 // the plane block, so the offset-7 skip rows are right).
3298 read_rect_chroma_unit(
3299 dec,
3300 cdfs,
3301 chroma_set,
3302 scans.1,
3303 chroma_tx,
3304 chroma_tx_h,
3305 plane_pass,
3306 cu_around[plane_pass],
3307 uv_predict_mode,
3308 angle_delta_uv,
3309 cu_reach,
3310 y,
3311 u,
3312 v,
3313 cu_x,
3314 cu_y,
3315 base_q_idx,
3316 None,
3317 alpha.zip(ac).map(|((au, av), ac)| {
3318 (if plane_pass == 1 { au } else { av }, ac)
3319 }),
3320 smooth_neighbor_uv,
3321 fctx,
3322 )?
3323 };
3324 if cn_rows * cn_cols > 1 {
3325 hit!(CHROMA_SPLIT_TX_HITS);
3326 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
3327 hit!(CHROMA422_SQUARE_HITS);
3328 }
3329 // Immediately, so the NEXT unit of this same block reads
3330 // this one's coefficient context (libaom's chroma
3331 // `txb_skip_ctx` for the second quadrant is 11, i.e. base
3332 // 1 from this left neighbour -- measured against aomdec).
3333 // The same writes are replayed after `record_split_luma`
3334 // below, which would otherwise clobber them whole-block.
3335 neighbours.record_mi_chroma(
3336 cu_mi,
3337 luma_span_x,
3338 luma_span_y,
3339 plane_pass,
3340 &cu_grid,
3341 );
3342 }
3343 if plane_pass == 1 {
3344 u_pass.push(cu_grid);
3345 } else {
3346 let u_grid =
3347 std::mem::replace(&mut u_pass[pass_idx], Grid::Zero(0));
3348 if cn_rows * cn_cols > 1 {
3349 units.push((
3350 cu_mi,
3351 luma_span_x,
3352 luma_span_y,
3353 u_grid.clone(),
3354 cu_grid.clone(),
3355 ));
3356 }
3357 last_grids = [u_grid, cu_grid];
3358 }
3359 pass_idx += 1;
3360 }
3361 }
3362 }
3363 }
3364 if intrabc_dv.is_some() {
3365 fctx.intrabc_chroma_tx.with(|c| c.set(None));
3366 }
3367 }
3368 // Mode/side bookkeeping plus, at `cn == 1`, the whole-plane chroma
3369 // context write; at `cn > 1` the per-unit writes above are what the
3370 // next block reads, so they run after this (last writer wins).
3371 neighbours.record_split_luma(
3372 at,
3373 side,
3374 mode,
3375 uv_predict_mode,
3376 [&last_grids[0], &last_grids[1]],
3377 );
3378 for (cu_mi, sw, sh, u_grid, v_grid) in &units {
3379 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 1, u_grid);
3380 neighbours.record_mi_chroma(*cu_mi, *sw, *sh, 2, v_grid);
3381 }
3382 }
3383 // Unconditional, `size == 0` for a non-palette block: clears any stale
3384 // neighbour palette state the same way [`Neighbours::record`] always
3385 // overwrites `above_mode`/`left_mode` regardless of this block's own mode
3386 // (the split-luma-TU branch above always refuses before reaching here
3387 // when `palette_y` is `Some`, so it is never live for that branch).
3388 let (py_size, py_colors) = palette_y
3389 .as_ref()
3390 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
3391 neighbours.record_palette_y(at, side, py_size, py_colors);
3392 let (puv_size, puv_colors) = palette_uv
3393 .as_ref()
3394 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
3395 neighbours.record_palette_uv(at, side, puv_size, puv_colors);
3396 neighbours.fill_skip_grid((r * (SUB / MI), c * (SUB / MI)), side / MI, skip);
3397 if intrabc_leaves.is_some() {
3398 // lane-av1422a2a4: the var-tx tree already published the
3399 // TXFM_CONTEXT bands per leaf ([`read_var_tx_size`] →
3400 // [`txfm_partition_update_rect`]); [`Self::fill_lf_grid_rect`]'s
3401 // whole-footprint publish would overwrite them with the block's own
3402 // `logical_tx` -- the same class [`Self::fill_lf_grid_rect_after_vartx`]
3403 // exists for (lane-av1oddheightfork3). Only the deblock grid is
3404 // still wanted here, so publish nothing.
3405 neighbours.fill_lf_grid_rect_after_vartx(
3406 (r * (SUB / MI), c * (SUB / MI)),
3407 side / MI,
3408 side / MI,
3409 logical_tx as u8,
3410 logical_tx as u8,
3411 0,
3412 fctx,
3413 );
3414 } else {
3415 neighbours.fill_lf_grid(
3416 (r * (SUB / MI), c * (SUB / MI)),
3417 side / MI,
3418 logical_tx as u8,
3419 0,
3420 fctx,
3421 );
3422 }
3423 // lane-t900 r32 / lane-av1txbands: libaom runs `set_txfm_ctxs(mbmi->tx_size,
3424 // n4_w, n4_h, skip_txfm && is_inter_block(mbmi), xd)` at the end of EVERY
3425 // `decode_block`. An intra-only frame's blocks also publish their TRANSFORM
3426 // size from [`Neighbours::fill_lf_grid_rect`], but this grid cannot express
3427 // libaom's `skip && is_inter` term -- the one thing that makes a SKIPPED
3428 // intrabc block publish its BLOCK size instead, intrabc being the only
3429 // "inter" block an intra-only frame codes (`blockd.h:373`). So this call
3430 // stays the authority wherever one can appear; with `allow_intrabc` unset
3431 // it writes exactly what the grid already did.
3432 //
3433 // lane-av1422a2a4: `parse_decode_block`'s tx branch (decodeframe.c:1227-1236)
3434 // is an EITHER/OR. When the var-tx branch ran, `read_tx_size_vartx` already
3435 // published per-leaf band sizes and libaom NEVER calls `set_txfm_ctxs` --
3436 // the blanket write below is the `else` branch's publish only. Writing it
3437 // after a var-tx tree clobbers the per-leaf band values with
3438 // `leaves[0]`'s transform: measured on the pinned A4 witness (256x224 4:2:2,
3439 // cq 30), the 32x32 intrabc block at mi(32,8) resolved a mixed tree
3440 // (8x8 leaves at (0,0)+(0,4), 16x16 leaves at (4,0)+(4,4)), leaving
3441 // `left_txfm[32..35] == 16`; the blanket write reset those cells to 8, so
3442 // the NEXT tree's sub-read at (32,16) took `txfm_partition_ctx` 10 where
3443 // libaom takes 9 (oracle operands: above=16, left=16) -- that frame's first
3444 // divergent read, surfacing ~30 partition symbols later as the
3445 // "block size 4x8 ... invalid" refusal (an E6/E7-class desync symptom, not
3446 // an invalid shape). Gate the blanket write on the tree NOT having run.
3447 if allow_intrabc && !(intrabc_leaves.is_some() && intrabc_leaves.as_ref().unwrap().len() > 1) {
3448 set_txfm_ctxs(
3449 neighbours,
3450 (mi_r, mi_c),
3451 logical_tx,
3452 side / MI,
3453 side / MI,
3454 skip && intrabc_dv.is_some(),
3455 );
3456 }
3457 record_intrabc_mi(mi_r, mi_c, side / MI, intrabc_dv, neighbours, fctx);
3458 Ok(())
3459}