forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

rect.rs4956 lines, 212.5 KiBHistoryRawDownload
1//! Rect block decoders: intra mode for rects, rect split, the intrabc rects and decode_leaf_rect. //! av1split: moved out of `decode/mod.rs`; the items are unchanged apart from visibility. (D19)
2
3use super::*;
4
5/// [`read_intra_mode`] for a true `bw`x`bh` rect strip (lane-intradisp r1,
6/// palette wired lane-palette2 r4): identical except the `use_filter_intra`
7/// size class comes from [`filter_intra_size_class_rect`] instead of the
8/// square-only [`filter_intra_size_class`], and the palette read (when
9/// `allow_screen_content_tools`) uses [`palette_bsize_ctx_wh`]/
10/// [`decode_color_index_map_wh`] instead of their square-only counterparts --
11/// every other symbol this reads (`skip`, `y_mode`, `angle_delta`, `uv_mode`,
12/// `cfl_alphas`) is indexed by mode or neighbour state, never by block size.
13#[allow(clippy::too_many_arguments)]
14pub(super) fn read_intra_mode_rect(
15 dec: &mut SymbolDecoder,
16 cdfs: &mut Cdfs,
17 above_mode: usize,
18 left_mode: usize,
19 cfl: bool,
20 // lane-r14: `is_chroma_reference` -- false only for a strip one mi tall
21 // (or wide) that is NOT the odd one of its 4:2:0 pair, where libaom reads
22 // no `uv_mode`/`cfl_alpha`/`angle_delta_uv`/`palette_uv` at all (the pair's
23 // chroma is coded once, on the closing strip). Every other caller is a
24 // block big enough to own its chroma and passes `true`.
25 has_chroma: bool,
26 bw: usize,
27 bh: usize,
28 enable_filter_intra: bool,
29 skip_ctx: usize,
30 allow_screen_content_tools: bool,
31 // As [`read_intra_mode`]'s own `palette`/`palette_uv_cache` params:
32 // `Some((palette_mode_ctx, color_cache))` reconstructs a real palette-Y
33 // block here, `None` still reads (and refuses on use) the symbol at ctx 0.
34 palette: Option<(usize, &[u16])>,
35 palette_uv_cache: &[u16],
36 mi_r: usize,
37 mi_c: usize,
38 fctx: &crate::decode::FrameCtx,
39) -> Result<(
40 bool,
41 usize,
42 i32,
43 usize,
44 i32,
45 Option<(i32, i32)>,
46 Option<usize>,
47 Option<PaletteY>,
48 Option<PaletteUv>,
49 // lane-av1-intrabc: the block vector, `Some` exactly when this block's
50 // `use_intrabc` symbol came out 1 -- libaom's `read_intrabc_info` returns
51 // straight out of `read_intra_frame_mode_info` then, so every later field
52 // of the tuple is at its default (mode/uv_mode DC, no angle, no palette,
53 // no filter intra). A caller that can reconstruct intrabc at its shape
54 // takes this and calls [`decode_intrabc_rect`]; one that cannot refuses by
55 // name with the same string it always did.
56 Option<(i32, i32)>,
57)> {
58 // lane-av1mono: libaom guards every chroma symbol read with
59 // `!cm->seq_params->monochrome && xd->is_chroma_ref` (`decodemv.c:933`),
60 // so a monochrome block codes no `uv_mode`/`cfl`/`angle_delta_uv`/
61 // `palette_uv` even on a chroma-reference strip. Fold the plane count
62 // into the same `has_chroma` this reader already gates on.
63 let has_chroma = has_chroma && !mono(fctx);
64 crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
65 let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
66 if ec_istep {
67 // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
68 // (decodemv.c:818), printed at the same point: before the first
69 // mode-info symbol of the block, so a cross-decoder range ladder can
70 // be keyed on the BLOCK, not just on the symbol sequence.
71 eprintln!(
72 "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=rect bw={bw} bh={bh} efi={} cls={:?} rng={}",
73 enable_filter_intra as i32,
74 filter_intra_size_class_rect(bw, bh),
75 dec.debug_state().0
76 );
77 }
78 macro_rules! istep {
79 ($name:literal, $val:expr) => {
80 if ec_istep {
81 let (rng, _) = dec.debug_state();
82 eprintln!(
83 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
84 $name, $val
85 );
86 }
87 };
88 }
89 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
90 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
91 // the one point every rect caller routes through, so no call site can
92 // offer the 14-symbol CFL alphabet on a 64-axis block (class
93 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
94 let cfl = if cfl && bw.max(bh) > 32 {
95 hit!(NOCFL_UV_MODE_HITS);
96 false
97 } else {
98 cfl
99 };
100 // lane-intra14 r1: on the INTER block path everything up to and including
101 // `is_inter` was already read by [`decode_inter_block`], so this reader
102 // starts at the mode syntax with the `skip` that caller read.
103 let inter = fctx.intra_in_inter_mode.with(std::cell::Cell::get);
104 let skip = if let Some((_, skip)) = inter {
105 skip
106 } else {
107 // Same `intra_segment_id` placement as the square reader above.
108 let (seg_w_mi, seg_h_mi) = (bw / 4, bh / 4);
109 if seg_id_pre_skip(fctx) {
110 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
111 }
112 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
113 istep!("skip", skip as i32);
114 if !seg_id_pre_skip(fctx) {
115 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
116 }
117 maybe_read_cdef_idx(dec, mi_r, mi_c, (bw / MI, bh / MI), skip, fctx);
118 istep!("cdef", 0);
119 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
120 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
121 // `false`.
122 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
123 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
124 istep!("dq", 0);
125 // `read_intrabc_info` (spec 5.11.13, libaom `decodemv.c:892`, right after
126 // `skip`/`segment_id`/`cdef`/`delta_q` and before `mbmi->mode`): the
127 // `use_intrabc` symbol is read for EVERY intra block of an `allow_intrabc`
128 // frame -- `av1_allow_intrabc` is a frame-level test with no shape term, so
129 // rect strips read it exactly like square leaves ([`read_intra_mode`],
130 // [`read_intra_mode_sub8`]). Missing it here desynced the arithmetic
131 // decoder at the FIRST symbol of the first rect block of every
132 // `--tune-content=screen` key frame. Reconstruction of a real intrabc
133 // block at this shape is out of scope, so the flag is consumed and
134 // refused by name when it fires.
135 if allow_intrabc_frame(fctx) {
136 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
137 hit!(RECT_INTRABC_READS);
138 istep!("intrabc", use_intrabc as i32);
139 if use_intrabc {
140 hit!(INTRABC_HITS);
141 // libaom `read_intrabc_info`: the DV read, then an immediate
142 // return out of the mode-info read -- no `y_mode`, no `uv_mode`,
143 // no angle deltas, no palette, no filter intra. The caller owns
144 // the reconstruction at its own shape.
145 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (bw / MI, bh / MI), fctx);
146 return Ok((
147 skip,
148 DC_PRED,
149 0,
150 DC_PRED,
151 0,
152 None,
153 None,
154 None,
155 None,
156 Some(dv),
157 ));
158 }
159 }
160 skip
161 };
162 // libaom `read_intra_block_mode_info` (decodemv.c:1189) vs the key
163 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
164 // off `kf_y_mode_cdf[above][left]`).
165 let mode = if let Some((size_group, _)) = inter {
166 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
167 dec.symbol(&mut cdfs.y_mode[size_group])
168 } else {
169 let above_ctx = INTRA_MODE_CTX[above_mode];
170 let left_ctx = INTRA_MODE_CTX[left_mode];
171 dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx])
172 };
173 istep!("mode", mode as i32);
174 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
175 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
176 } else {
177 0
178 };
179 istep!("angle_y", angle_delta_y);
180 // lane-sb128c r3 (class sweep): libaom `read_intra_mode_uv(.., is_cfl_allowed(xd), ..)`
181 // and `is_cfl_allowed` (blockd.h) is `block_size_wide[bsize] <= 32 &&
182 // block_size_high[bsize] <= 32` on the LUMA bsize. Deciding the alphabet
183 // here, from the block's own size, is the single point every caller routes
184 // through -- a caller passing `true` for a >32 strip used to pick the
185 // 14-symbol CFL CDF, same value but a different range (class
186 // wrong-alphabet-same-value).
187 let cfl = cfl && cfl_allowed_px(bw, bh, fctx);
188 let uv_mode = if !has_chroma {
189 DC_PRED
190 } else if cfl {
191 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
192 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
193 } else {
194 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
195 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
196 };
197 istep!("uv_mode", uv_mode as i32);
198 let alpha = if has_chroma && cfl && uv_mode == UV_CFL_PRED {
199 Some(read_cfl_alphas(dec, cdfs))
200 } else {
201 None
202 };
203 if has_chroma && (9..=12).contains(&uv_mode) {
204 hit!(SMOOTH_UV_HITS);
205 }
206 let angle_delta_uv = if has_chroma && (V_PRED..=D67_PRED).contains(&uv_mode) {
207 hit!(DIRECTIONAL_UV_HITS);
208 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
209 } else {
210 0
211 };
212 istep!("angle_uv", angle_delta_uv);
213 if angle_delta_uv != 0 {
214 hit!(UV_ANGLE_DELTA_HITS);
215 }
216 // `read_palette_mode_info` (spec 5.11.13), rect-generalised
217 // (lane-palette2 r4): same bsize-ctx-gated read as [`read_intra_mode`],
218 // just keyed by [`palette_bsize_ctx_wh`] instead of the square-only
219 // [`palette_bsize_ctx`]. Order matches spec/libaom exactly: mode/size/
220 // colours only here, the colour-index maps deferred past `filter_intra`
221 // (see [`read_intra_mode`]'s own comment on why -- `av1_visit_palette`
222 // runs from the caller, after the whole mode-info read).
223 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
224 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
225 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
226 // r6: this is the exact site the removed blanket refusal used to
227 // guard -- reached for EVERY rect strip in a screen-content frame,
228 // independent of whether the block ends up using a palette.
229 hit!(RECT_SCREEN_CONTENT_HITS);
230 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
231 let use_palette_y =
232 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
233 if use_palette_y {
234 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
235 let colors = read_palette_colors_y(dec, n, cache, fctx);
236 palette_y_pending = Some((n, colors));
237 }
238 let palette_uv_mode_ctx = usize::from(use_palette_y);
239 // `read_palette_mode_info`'s own `xd->is_chroma_ref` guard.
240 if has_chroma
241 && uv_mode == DC_PRED
242 && dec.symbol(&mut cdfs.palette_uv_mode[palette_uv_mode_ctx]) != 0
243 {
244 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
245 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, palette_uv_cache, fctx);
246 palette_uv_pending = Some((n, u_colors, v_colors));
247 }
248 }
249 let mut filter_intra = None;
250 if crate::envflags::env_flag!("EC_AV1_TRACE") {
251 let (rng, _) = dec.debug_state();
252 eprintln!(
253 "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
254 class={:?} rng={rng}",
255 enable_filter_intra as i32,
256 filter_intra_size_class_rect(bw, bh)
257 );
258 }
259 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
260 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
261 if mode == DC_PRED
262 && enable_filter_intra
263 && palette_y_pending.is_none()
264 && let Some(class) = filter_intra_size_class_rect(bw, bh)
265 {
266 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
267 if crate::envflags::env_flag!("EC_AV1_TRACE") {
268 eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
269 }
270 istep!("use_filter_intra", use_filter_intra as i32);
271 if use_filter_intra {
272 hit!(FILTER_INTRA_HITS);
273 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
274 istep!("filter_intra_mode", fi_mode as i32);
275 filter_intra = Some(fi_mode);
276 }
277 }
278 // `av1_visit_palette`: plane 0 (Y) then plane 1 (chroma, shared U/V map),
279 // same order as [`read_intra_mode`]'s own square path.
280 let palette_y = palette_y_pending.map(|(n, colors)| {
281 let map = decode_color_index_map_wh(
282 dec,
283 cdfs,
284 n,
285 bw,
286 bh,
287 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
288 false,
289 );
290 hit!(PALETTE_HITS);
291 hit!(PALETTE_RECT_HITS);
292 PaletteY {
293 size: n,
294 colors,
295 map,
296 }
297 });
298 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
299 // `av1_get_plane_block_size(bsize, 1, 1)` (`ss_size_lookup`), NOT a
300 // plain halving: BLOCK_16X4 subsamples to BLOCK_8X4 and BLOCK_4X16 to
301 // BLOCK_4X8, both floored at the 4-px transform. Halving the short
302 // axis to 2 read HALF the colour-index symbols of a 1:4 strip's
303 // chroma palette and desynced the tile from there.
304 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
305 let on = palette_onscreen_uv(
306 (bw, bh),
307 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
308 (cw, ch),
309 (ss_x(fctx), ss_y(fctx)),
310 );
311 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
312 hit!(PALETTE_UV_HITS);
313 PaletteUv {
314 size: n,
315 u_colors,
316 v_colors,
317 map,
318 }
319 });
320 Ok((
321 skip,
322 mode,
323 angle_delta_y,
324 uv_mode,
325 angle_delta_uv,
326 alpha,
327 filter_intra,
328 palette_y,
329 palette_uv,
330 None,
331 ))
332}
333
334/// Stamps a 1:4 strip's palette state into the mi-granular above/left arrays,
335/// at the strip's REAL mi position. `av1_get_palette_cache` reads
336/// `xd->above_mbmi`/`xd->left_mbmi`, i.e. the mi cell above/left of the
337/// block, so each strip owns its own rows and columns and no aliasing rule
338/// is needed (lane-kf900 r6).
339#[allow(clippy::too_many_arguments)]
340pub(super) fn record_strip_palette(
341 n: &mut Neighbours,
342 mi: (usize, usize),
343 bw: usize,
344 bh: usize,
345 y_size: usize,
346 y_colors: [u16; 8],
347 uv_size: usize,
348 uv_colors: [u16; 8],
349) {
350 let (r, c) = mi;
351 // lane-t900 r23 rung: every publication of a block's palette state into
352 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
353 // path left a stale `left_palette_size` behind when
354 // `av1_get_palette_mode_ctx` disagrees with libaom's.
355 if crate::envflags::env_flag!("EC_PALPUB") {
356 eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
357 }
358 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
359 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
360 // existed because the 16px [`SUB`] cell held one slot for all the strips
361 // of a HORZ_4/VERT_4 and leaf 0 zeroing the other axis threw away the
362 // real neighbour leaf 1 reads.
363 {
364 for cell in 0..(bw / MI).max(1) {
365 if let Some(e) = n.above_palette_size.get_mut(c + cell) {
366 *e = y_size as u8;
367 n.above_palette_uv_size[c + cell] = uv_size as u8;
368 // lane-publish2, see [`Neighbours::record_palette_y_rect`]:
369 // colours of a size-0 neighbour are never read.
370 if y_size > 0 {
371 n.above_palette_colors[c + cell] = y_colors;
372 }
373 if uv_size > 0 {
374 n.above_palette_uv_colors[c + cell] = uv_colors;
375 }
376 }
377 }
378 }
379 {
380 for cell in 0..(bh / MI).max(1) {
381 if n.left_palette_size.get(r + cell).is_none() {
382 break;
383 }
384 n.left_palette_size[r + cell] = y_size as u8;
385 n.left_palette_uv_size[r + cell] = uv_size as u8;
386 if y_size > 0 {
387 n.left_palette_colors[r + cell] = y_colors;
388 }
389 if uv_size > 0 {
390 n.left_palette_uv_colors[r + cell] = uv_colors;
391 }
392 }
393 }
394}
395
396/// [`cfl_ac_q3`] for a true `bw`x`bh` rect strip (lane-intradisp r1).
397pub(super) fn cfl_ac_q3_rect(
398 y: &PlaneBuf<'_>,
399 px: usize,
400 py: usize,
401 bw: usize,
402 bh: usize,
403) -> Vec<i32> {
404 cfl_ac_q3_at(px, py, bw, bh, |lx, ly| {
405 i32::from(y.data[ly * y.width + lx])
406 })
407}
408
409/// Everything a rect strip already read out of the stream before its luma
410/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle
411/// (nine values that would otherwise be nine more parameters).
412pub(super) struct RectStripModes {
413 pub(super) skip: bool,
414 pub(super) mode: usize,
415 pub(super) angle_delta_y: i32,
416 pub(super) uv_predict_mode: usize,
417 pub(super) angle_delta_uv: i32,
418 pub(super) alpha: Option<(i32, i32)>,
419 pub(super) filter_intra: Option<usize>,
420 pub(super) smooth_neighbor: bool,
421 pub(super) smooth_neighbor_uv: bool,
422 /// lane-palette2 r9: the strip's palette-Y prediction (`bw`x`bh`, already
423 /// mapped through the colour table), sliced per transform unit below --
424 /// palette prediction reads no edge pixels, so a unit's slice of the
425 /// whole-block map IS its prediction. Without this a palette strip whose
426 /// transform splits predicted DC and came out flat grey while the entropy
427 /// stream stayed in sync (the coefficients are read either way).
428 pub(super) palette_y: Option<Vec<u16>>,
429 /// As `palette_y`, for the un-split chroma transform (U, V).
430 pub(super) palette_uv: Option<(Vec<u16>, Vec<u16>)>,
431}
432
433/// The transform unit size (w, h) of a `bw`x`bh` intra block at tx `depth`
434/// -- libaom `depth_to_tx_size`, which walks `sub_tx_size_map` `depth` times
435/// from `max_txsize_rect_lookup[bsize]`. Every entry of that map halves the
436/// LONGER side of a rectangle and both sides of a square, so a 1:4 strip's
437/// first step is a 2:1 rect unit (`TX_32X8 -> TX_16X8`, `TX_64X16 ->
438/// TX_32X16`) and only the second reaches a square -- the reason
439/// `bw.min(bh) >> (depth - 1)` (correct for a 2:1 strip, where step one is
440/// already square) mis-tiled 1:4 strips.
441pub(super) fn depth_to_tx_wh(
442 bw: usize,
443 bh: usize,
444 depth: usize,
445 fctx: &crate::decode::FrameCtx,
446) -> (usize, usize) {
447 // lane-lossless: TX_4X4 whatever the strip's own size and depth (libaom
448 // `read_tx_size`: the lossless early return comes before
449 // `max_txsize_rect_lookup`), and no `tx_depth` symbol was read to get here.
450 if lossless(fctx) {
451 return (4, 4);
452 }
453 let (mut w, mut h) = (bw.min(64), bh.min(64));
454 for _ in 0..depth {
455 match w.cmp(&h) {
456 std::cmp::Ordering::Greater => w /= 2,
457 std::cmp::Ordering::Less => h /= 2,
458 std::cmp::Ordering::Equal => {
459 w /= 2;
460 h /= 2;
461 }
462 }
463 }
464 (w, h)
465}
466
467/// lane-av1-422stripanchor: [`decode_rect_split`]'s 4-wide-strip port of the
468/// split4 floored-pair anchor ([`sub8_leaf_chroma422`]'s rule). A 1-mi-wide
469/// strip (luma `(4, 16)` / `(4, 8)`) has NO chroma plane block of its own at
470/// ss (1, 0) -- `av1_ss_size_lookup[BLOCK_4X16][1][0]` and
471/// `[BLOCK_4X8][1][0]` are both BLOCK_INVALID (`common_data.c`), and a
472/// 2-px-wide area is not a transform shape. The strip pairs with its
473/// even-column sibling (`is_chroma_reference`'s `mi_col & 1` column clause,
474/// the rule [`decode_rect4_16_strip`] implements one partition level up), and
475/// the ODD-column strip codes the PAIR's `(4, bh)` plane anchored at
476/// `av1_setup_dst_planes`' mi-exact floor `(mi_col & !1) * MI >> ss_x`, with
477/// the entropy context on the floored cell. Returns
478/// `(pair block width, pair block height, write anchor x, entropy mi column)`
479/// for that pair, or `None` when the strip keeps its own plane block at its
480/// own origin -- which is every 4:2:0 and 4:4:4 cell (their chroma is never
481/// 2 px wide) and every 4:2:2 strip of 8 px or more.
482fn chroma422_pair_plane(
483 ss_x: bool,
484 ss_y: bool,
485 mi_col: usize,
486 bw: usize,
487 bh: usize,
488) -> Option<(usize, usize, usize, usize)> {
489 if ss_x && !ss_y && (bw >> 1) == 2 {
490 Some((4, bh, ((mi_col & !1) * MI) >> 1, mi_col & !1))
491 } else {
492 None
493 }
494}
495
496/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma
497/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every
498/// rect path here refused by name until now ("per-unit rect prediction is not
499/// ported").
500///
501/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth`
502/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1
503/// strip the very first step already lands on a SQUARE transform
504/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and
505/// every further step halves a square) -- so each unit is square and reads
506/// through the ordinary square [`read_plane`]. What is genuinely rectangular
507/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as
508/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose
509/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never
510/// split by luma's depth.
511///
512/// Each unit predicts off whatever the earlier units of this same block
513/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block`
514/// inside `av1_foreach_transformed_block`, raster order), which is exactly
515/// what predicting the whole strip in one shot got wrong.
516#[allow(clippy::too_many_arguments)]
517pub(super) fn decode_rect_split(
518 dec: &mut SymbolDecoder,
519 cdfs: &mut Cdfs,
520 neighbours: &mut Neighbours,
521 at_mi: (usize, usize),
522 bw: usize,
523 bh: usize,
524 // The transform unit's own width and height in pixels. Square for every
525 // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
526 // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
527 // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
528 tx_w: usize,
529 tx_h: usize,
530 m: &RectStripModes,
531 y: &mut PlaneBuf<'static>,
532 u: &mut PlaneBuf<'static>,
533 v: &mut PlaneBuf<'static>,
534 base_q_idx: u8,
535 reduced_tx_set: bool,
536 fctx: &crate::decode::FrameCtx,
537) -> Result<()> {
538 let (mi_r, mi_c) = at_mi;
539 let (px, py) = (mi_c * MI, mi_r * MI);
540 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
541 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
542 // lane-av1-422blockhalf: at ss (1,0) the tall/wide 1:2 and 1:4 strips'
543 // chroma plane block is BLOCK_INVALID (`av1_ss_size_lookup[...][1][0]`,
544 // blockd.h -- the 4:2:2 column maps BLOCK_8X16/16X32/32X64/64X128 and
545 // BLOCK_8X32/16X64, plus 4-wide BLOCK_4X16, to BLOCK_INVALID), so
546 // `av1_get_max_uv_txsize` indexes `max_txsize_rect_lookup` OUT OF BOUNDS
547 // and the pinned Release oracle byte there is TX_4X8 (the lane-av1-422m
548 // measurement). The plane is still coded -- `decode_token_recon_block`
549 // steps it in that (4, 8) unit shape -- so the strip's chroma tiles into
550 // 4x8 rect units, plane-major.
551 let chroma_422_oob = ss_x(fctx) == 1
552 && ss_y(fctx) == 0
553 && matches!(
554 (bw, bh),
555 (8, 16) | (16, 32) | (32, 64) | (64, 128) | (8, 32) | (16, 64)
556 );
557 // lane-av1-422stripanchor: the 4-wide strips' PAIR chroma -- the ported
558 // floored-pair anchor. `chroma422_pair_plane` is `Some` exactly when this
559 // strip's own chroma block would be 2 px wide at ss (1, 0); the pair's
560 // plane is then `(4, chroma_h)` written at the FLOORED cell
561 // (`chroma_x`), and the skip/tiled chroma arms below tile it in (4, 8)
562 // units (the OOB `max_txsize_rect_lookup[BLOCK_INVALID]` byte, TX_4X8 --
563 // the same walk the (8, 32) class takes). The lossless raster arm keeps
564 // the strip's own geometry: no caller of this function can present a
565 // 4-wide strip yet (the enumeration test pins the five callers at
566 // `8 <= min`), and the skip/tiled arms are the routes a future caller
567 // needs.
568 let chroma422_pair = chroma422_pair_plane(ss_x(fctx) == 1, ss_y(fctx) == 0, mi_c, bw, bh);
569 let chroma_422_pair_wide = chroma422_pair.is_some();
570 let (chroma_block_w, chroma_block_h, chroma_x) =
571 chroma422_pair.map_or((chroma_w, chroma_h, cpx), |(w, h, x, _)| (w, h, x));
572 // The chroma transform is picked before any symbol is read, so an
573 // unsupported chroma shape refuses before this strip desyncs the tile.
574 let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) {
575 (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])),
576 (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])),
577 (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])),
578 (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])),
579 // The 1:4 and sub-16 strips (lane-rectchroma r1 added the 32x8/8x32
580 // rows, lane-rectsplitx r1 the 16x4/4x16 ones). `get_txsize_entropy_ctx`
581 // squares a rect transform down to a CDF set by
582 // `(wide_log2 + high_log2 + 1) >> 1`: TX_32X8 -> the 16x16 set,
583 // TX_16X4 -> the 8x8 set, TX_8X4 -> the 8x8 set -- exactly the sets
584 // the UNSPLIT 1:4 (`decode_block_rect4`) and 16x8 (`decode_leaf_rect`)
585 // paths already prove for these same shapes.
586 (32, 8) => Some((TxbSet::Chroma16, &SCAN_32X8[..])),
587 (8, 32) => Some((TxbSet::Chroma16, &SCAN_8X32[..])),
588 (16, 4) => Some((TxbSet::Chroma8, &SCAN_16X4[..])),
589 (4, 16) => Some((TxbSet::Chroma8, &SCAN_4X16[..])),
590 (8, 4) => Some((TxbSet::ChromaRect8x4, &SCAN_8X4[..])),
591 (4, 8) => Some((TxbSet::ChromaRect8x4, &SCAN_4X8[..])),
592 _ => None,
593 };
594 // A 4:4:4 64-axis strip's chroma plane block is larger than one adjusted
595 // UV transform (TX_64X32 adjusts to TX_32X32). Those sizes are tiled
596 // below; everything else still needs a single-unit table.
597 // lane-av1-422: a 4:2:2 strip's chroma plane keeps the strip's HEIGHT and
598 // halves only the width, so a rect luma strip codes a SQUARE chroma block
599 // (16x8 luma -> 8x8 chroma) -- the square rows below. At 4:2:0 and 4:4:4 a
600 // rect strip's chroma is itself rect, so the square rows are unreachable
601 // there and cannot change their results.
602 // lane-av1-422blockhalf: the tiled arms below handle every shape this
603 // strip can carry (including the 4:2:2 BLOCK_INVALID planes), so the
604 // diagnostic names only the shapes that would actually refuse -- it used
605 // to fire for every tiled square too (the parent lane's `chroma=8x8`
606 // rows) and sent the next lane chasing handled shapes.
607 let chroma_tiled = chroma_422_pair_wide
608 || chroma_422_oob
609 || matches!(
610 (chroma_w, chroma_h),
611 (64, 32) | (32, 64) | (64, 16) | (16, 64) | (32, 32) | (16, 16) | (8, 8)
612 );
613 if !m.skip {
614 if let Some(i) = match (chroma_w, chroma_h) {
615 (32, 8) => Some(0),
616 (8, 32) => Some(1),
617 (8, 4) => Some(2),
618 (4, 8) => Some(3),
619 _ => None,
620 } {
621 hit_do! {
622 RECT_SPLIT_CHROMA_SHAPE_HITS.with(|c| {
623 let mut hits = c.get();
624 hits[i] += 1;
625 c.set(hits);
626 });
627 }
628 }
629 if !m.skip && chroma.is_none() && !chroma_tiled {
630 // Diagnostic for the next caller that lands here (class
631 // refusal-names-a-correlate: the message names the tool, not the
632 // shape); the refusal below keeps its inventory-pinned wording.
633 eprintln!(
634 "EC_RECTCHROMA_GAP luma={bw}x{bh} tx={tx_w}x{tx_h} \
635 chroma={chroma_w}x{chroma_h}"
636 );
637 }
638 }
639 // lane-rectsplit r2 (verifier finding): with both callers wired
640 // (`decode_block_rect`'s 32x16/16x32 and `decode_block_rect64`'s
641 // 64x32/32x64) every shape that reaches here has a table above, so this
642 // arm is UNREACHABLE today. It stays as the shape guard for the next
643 // caller -- a new strip size would otherwise hit the `expect` below and
644 // panic instead of refusing by name -- and so stays in
645 // `refusal_inventory::REFUSALS`.
646 if !m.skip && chroma.is_none() && !chroma_tiled {
647 return Err(unsupported(
648 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
649 ));
650 }
651 hit!(RECT_SPLIT_TX_HITS);
652 if bw.max(bh) == 64 && bw / tx_w > 1 && bh / tx_h > 1 {
653 hit!(RECT_SPLIT_SB_INTERIOR_TU_HITS);
654 }
655 // LUMA: `bw/tx` x `bh/tx` square transform units, raster order.
656 // A square unit reads through the ordinary square [`read_plane`]; a rect
657 // one (a 1:4 strip's first split) reads through [`read_coeffs_rect`] with
658 // the very tables the unsplit 16x8/32x16 paths use.
659 let luma_rect: Option<(TxbSet, &[u16])> = match (tx_w, tx_h) {
660 (w, h) if w == h => None,
661 (16, 8) | (8, 16) => Some((
662 if reduced_tx_set {
663 TxbSet::LumaRect16x8
664 } else {
665 TxbSet::LumaRect16x8Set1
666 },
667 if tx_w == 16 {
668 &SCAN_16X8[..]
669 } else {
670 &SCAN_8X16[..]
671 },
672 )),
673 (32, 16) => Some((TxbSet::LumaRect32x16, &SCAN_32X16[..])),
674 (16, 32) => Some((TxbSet::LumaRect32x16, &SCAN_16X32[..])),
675 // lane-rect64port r1: the un-split TX_64X32/TX_32X64 of a 64-level
676 // strip, read through the `luma_64corner` arm below instead of a rect
677 // table -- a 64-length axis codes only its low 32 coefficients
678 // (`av1_get_max_eob` / the zero-out of `av1_get_adjusted_tx_size`), so
679 // the coded unit is the 32x32 corner [`decode_block_rect64`]'s own
680 // depth-0 arm already reads on the key-frame path.
681 //
682 // lane-sub8x4 r3: WITNESS FOUND, so this is no longer behind
683 // `EC_RECT64_SPLIT`. r1's "no witness" was true only while the
684 // sub-8x8 intra leaves still refused: with those lifted (r2) the
685 // first 50 frame OBUs of the 10-bit 3840x1608 stream's head decode
686 // all 33 frames pixel-exact against ffmpeg while this arm fires 90x
687 // 64x32 + 5x 32x64 -- pinned as `fixtures/reelb_rect64_intra16x4_witness.obu`
688 // and gated by `a_10bit_film_frames_with_rect64_corner_tus_decode_pixel_exact`.
689 // lane-wit16x4 r1 re-measured that fixture on the merged tip: this arm
690 // fires 64x32=148 32x64=123 (the 90/5 above were counted out of the
691 // frame-33 desync lane-frame36 r2 fixed), all 33 frames pixel-exact.
692 (64, 32) | (32, 64) => None,
693 _ => {
694 return Err(unsupported(format!(
695 "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma \
696 coefficient tables for that shape here)"
697 )));
698 }
699 };
700 // The `None` above that is NOT the square arm.
701 let luma_64corner = tx_w != tx_h;
702 // lane-rectsplitx r1, MEASURED: the SQUARE-unit walk below is pixel-exact
703 // on a real stream (the pinned 16x8 filter-intra fixture decodes its whole
704 // frame exactly, two sub-16 split strips in it), but the RECT-unit arm --
705 // a 1:4 strip's depth-1 TX_16X8/TX_32X16 -- mismatched ffmpeg on the
706 // 32-level 1:4 band fixture (8-bit, cq 12, seed 42). The tables and the
707 // per-unit rect walk stay wired above/below; the round that finds that
708 // defect deletes this refusal and nothing else.
709 let luma_set = txbset_for(tx_w.min(tx_h), reduced_tx_set);
710 let luma_scan = default_scan(tx_w.min(tx_h));
711 let zero_tu = vec![0i32; tx_w * tx_h];
712 // The strip's OWN edge availability, the fallback for a transform unit
713 // whose top-right/bottom-left pixels fall outside the strip.
714 let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
715 for tu_row in 0..bh / tx_h {
716 for tu_col in 0..bw / tx_w {
717 let tu_mi = (mi_r + tu_row * (tx_h / MI), mi_c + tu_col * (tx_w / MI));
718 let (tu_px, tu_py) = (px + tu_col * tx_w, py + tu_row * tx_h);
719 let (col_off, row_off) = (tu_col * tx_w, tu_row * tx_h);
720 // lane-hgkf r1 (ported from lane-golomb 791d87a, unmerged):
721 // libaom clips `av1_foreach_transformed_block_in_plane` to
722 // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
723 // i.e. `mi_cols * 4` / `mi_rows * 4`): a transform unit whose
724 // TOP-LEFT sample falls outside the frame is never coded. We read
725 // coefficients for those phantom units and desynced the stream at
726 // the very next symbol.
727 if tu_px >= y.true_width || tu_py >= y.true_height {
728 continue;
729 }
730 // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
731 // transform unit INSIDE a block, which is a different rule from
732 // the standalone-block table [`Reach::of`] applies -- and the
733 // reason a depth-2 superblock strip came out one sample off
734 // before this: `Reach::of(tx, ..)` answered as if the unit were
735 // its own block at that superblock position.
736 // * top-right: if the unit's right neighbour is still inside the
737 // strip the pixels are already reconstructed (`col_off +
738 // tx_wide < plane_bw`); otherwise only the strip's own top row
739 // of units can reach past it, through the block-level answer.
740 // * bottom-left: a unit that is not in the strip's left column
741 // has none (`col_off > 0` returns 0); inside the strip
742 // (`row_off + tx_high < plane_bh`) they are the left
743 // neighbour's, already reconstructed; the last row falls back
744 // to the block-level answer.
745 let tu_reach = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block_reach);
746 // The unit's own window on the block's palette prediction.
747 if let Some(buf) = &m.palette_y {
748 let tu_buf: Vec<u16> = (0..tx_h)
749 .flat_map(|i| {
750 let base = (row_off + i) * bw + col_off;
751 buf[base..base + tx_w].iter().copied()
752 })
753 .collect();
754 set_palette_pred(tu_buf, fctx);
755 }
756 if m.skip {
757 push_intra_rect(
758 y,
759 u,
760 v,
761 0,
762 tu_px,
763 tu_py,
764 tx_w,
765 tx_h,
766 m.mode,
767 m.angle_delta_y,
768 tu_reach,
769 &zero_tu,
770 None,
771 m.filter_intra,
772 m.smooth_neighbor,
773 fctx,
774 );
775 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &zero_tu);
776 } else if luma_64corner && luma_rect.is_none() {
777 // The un-split 64-level luma transform: `read_coeffs` on the
778 // 32x32 CDF set [`TxbSet::Luma64`] with `default_scan(TX32)`
779 // and the real rect shape passed through for
780 // `av1_nz_map_ctx_offset` -- byte for byte
781 // [`decode_block_rect64`]'s depth-0 read, which the key-frame
782 // 64-level strip gate already proves. `tx_type` is not coded
783 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
784 // the square-up size is TX_64X64), and this unit covers its
785 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
786 if crate::envflags::env_flag!("EC_RECT64TU") {
787 eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
788 }
789 hit_do! {
790 RECT64_CORNER_TU_HITS.with(|c| {
791 let mut v = c.get();
792 v[usize::from(tx_h > tx_w)] += 1;
793 c.set(v);
794 });
795 }
796 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
797 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
798 let (corner, tu_tx_type) = read_coeffs(
799 dec,
800 &mut coding,
801 default_scan(TX32),
802 0,
803 dc_sign_ctx(tu_around.2),
804 TxType::DctDct,
805 Some((tx_w, tx_h)),
806 )?;
807 let (cw, ch) = (tx_w.min(TX32), tx_h.min(TX32));
808 let mut tu_grid = vec![0i32; tx_w * tx_h];
809 for row in 0..ch {
810 tu_grid[row * tx_w..][..cw].copy_from_slice(&corner[row * cw..][..cw]);
811 }
812 let residual = dequant_and_inverse_typed_wh(
813 &tu_grid,
814 tx_w,
815 tx_h,
816 crate::decode::bit_depth(fctx),
817 block_q_idx(fctx),
818 plane_q_delta(0, fctx).0,
819 plane_q_delta(0, fctx).1,
820 tu_tx_type,
821 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
822 );
823 push_intra_rect(
824 y,
825 u,
826 v,
827 0,
828 tu_px,
829 tu_py,
830 tx_w,
831 tx_h,
832 m.mode,
833 m.angle_delta_y,
834 tu_reach,
835 &residual,
836 None,
837 m.filter_intra,
838 m.smooth_neighbor,
839 fctx,
840 );
841 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
842 } else if let Some((rect_set, rect_scan)) = luma_rect {
843 // The rect-unit twin of the square arm below: same contexts,
844 // same order, through the rect coefficient reader. The
845 // `tx_type` CDF row of a filter-intra block is
846 // `fimode_to_intradir[filter_intra_mode]`, never the block's
847 // own (always DC_PRED) mode -- [`read_plane`] applies that
848 // for the square arm, so this one must too.
849 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
850 // libaom `get_txb_ctx`: a LUMA transform that covers its whole
851 // block (`plane_bsize == txsize_to_bsize[tx_size]`, i.e. the
852 // unsplit depth-0 strip) reads txb_skip ctx 0 flat -- the
853 // neighbour-magnitude table is for a unit SMALLER than its
854 // block. [`decode_block_rect`]'s own unsplit read passes a
855 // literal 0 for the same reason; this arm applied the table
856 // unconditionally and desynced every depth-0 rect strip that
857 // reached it (lane-intrarect r2: ctx 5 where aomdec read 0).
858 let tu_skip_ctx = if tx_w == bw && tx_h == bh {
859 0
860 } else {
861 neighbours.luma_skip_ctx_rect(tu_mi, tx_w / MI, tx_h / MI)
862 };
863 let mut coding = cdfs.txb(rect_set, fi_tx_row(m.mode, m.filter_intra));
864 let (tu_grid, tu_tx_type) = read_coeffs_rect(
865 dec,
866 &mut coding,
867 rect_scan,
868 tx_w,
869 tx_h,
870 tu_skip_ctx,
871 dc_sign_ctx(tu_around.2),
872 TxType::DctDct,
873 0,
874 )?;
875 let residual = dequant_and_inverse_typed_wh(
876 &tu_grid,
877 tx_w,
878 tx_h,
879 crate::decode::bit_depth(fctx),
880 block_q_idx(fctx),
881 plane_q_delta(0, fctx).0,
882 plane_q_delta(0, fctx).1,
883 tu_tx_type,
884 block_iqmatrix(fctx, 0, tx_w, tx_h, tu_tx_type),
885 );
886 push_intra_rect(
887 y,
888 u,
889 v,
890 0,
891 tu_px,
892 tu_py,
893 tx_w,
894 tx_h,
895 m.mode,
896 m.angle_delta_y,
897 tu_reach,
898 &residual,
899 None,
900 m.filter_intra,
901 m.smooth_neighbor,
902 fctx,
903 );
904 neighbours.record_mi_luma_rect(tu_mi, tx_w, tx_h, &tu_grid);
905 } else {
906 let tu_around = neighbours.around_mi(tu_mi, tx_w)[0];
907 // This unit is smaller than the block it sits in, so
908 // `txb_skip_ctx` is the neighbour-magnitude table, not the
909 // lone-TU 0 (spec `get_txb_ctx_general`).
910 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx_w / MI);
911 let tu_grid = read_plane(
912 dec,
913 cdfs,
914 luma_set,
915 luma_scan,
916 0,
917 tu_around,
918 m.mode,
919 m.mode,
920 m.angle_delta_y,
921 tu_reach,
922 y,
923 u,
924 v,
925 tu_px,
926 tu_py,
927 tx_w,
928 tx_w,
929 base_q_idx,
930 None,
931 m.filter_intra,
932 Some(tu_skip_ctx),
933 m.smooth_neighbor,
934 fctx,
935 )?;
936 neighbours.record_mi_luma(tu_mi, tx_w, &tu_grid);
937 }
938 }
939 }
940 // CHROMA: one un-split rect transform for the whole strip.
941 // lane-lossless2: except on a lossless frame, where it is a raster of 4x4
942 // units -- each stamps its own neighbour context as it is read, and the
943 // whole-block `record_split_luma_rect_mi` below would overwrite all of
944 // them with the LAST unit's state (class `override-slot-on-one-arm`: the
945 // next block then read `dc_sign_ctx` 1 where libaom reads 0). They are
946 // collected here and replayed after that record.
947 let mut ll_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
948 // The chroma_tiled arm below stamps each unit's coefficient context
949 // immediately (so the NEXT unit reads it), then the whole-strip
950 // `record_split_luma_rect_mi` rewrites every chroma cell with ONE
951 // whole-strip state and the per-unit DC signs and levels are lost
952 // (class `override-slot-on-one-arm`). The units are collected here and
953 // replayed after that record, the way the lossless arm's
954 // `ll_chroma_units` and `decode_inter_block`'s `mu_chroma_units` tail
955 // already do.
956 let mut tiled_chroma_units: Vec<((usize, usize), usize, Grid, usize, usize)> = Vec::new();
957 let ac = m.alpha.map(|_| {
958 // lane-av1-422stripanchor: the pair unit's CfL source is the PAIR's
959 // luma -- the 8-px-wide region the floored 4-px chroma block covers
960 // (`av1_setup_dst_planes`' floor), never the odd strip's own 4 px.
961 if chroma_422_pair_wide {
962 cfl_src_rect((mi_c & !1) * MI, py, 8, bh)
963 } else {
964 cfl_src_rect(px, py, bw, bh)
965 }
966 });
967 let reach = if chroma_422_pair_wide {
968 // The chroma units predict off the PAIR block's edges: an odd-column
969 // strip's pair starts 4 luma px to the strip's left, so the strip's
970 // own answer names the wrong above/right samples (the pair16 arm's
971 // `pair_reach`, one partition level up).
972 Reach::of_rect(8, bh, (mi_c & !1) * MI, py, y.width, y.height, fctx)
973 } else {
974 block_reach
975 };
976 let (u_grid, v_grid) = if mono(fctx) {
977 // lane-av1mono: a monochrome frame codes no chroma coefficients on
978 // any block (`plane < av1_num_planes == 1`), so the whole chroma
979 // section -- the skipped-strip pushes, the lossless raster and the
980 // un-split `read_coeffs_rect` below -- is bypassed.
981 let zero = Grid::Zero(chroma_w * chroma_h);
982 (zero.clone(), zero)
983 } else if m.skip {
984 let zero = Grid::Zero(chroma_block_w * chroma_block_h);
985 if chroma_422_pair_wide || chroma_422_oob {
986 // lane-av1-422blockhalf: libaom predicts an INTRA strip's chroma
987 // per transform unit even when the strip is skipped
988 // (`decode_token_recon_block`'s per-TU plane walk runs before the
989 // skip guard), so the BLOCK_INVALID plane predicts as (4, 8)
990 // units -- one whole-plane push here would ask the intra
991 // predictor for a 1:8 rect it never needs.
992 // lane-av1-422stripanchor: the 4-wide strip's PAIR plane does the
993 // same, over the pair's own `(chroma_block_w, chroma_block_h)`
994 // grid at the floored anchor `chroma_x`.
995 let (uw, uh) = (4usize, 8usize);
996 for plane_idx in 1..=2 {
997 if let Some((ub, vb)) = &m.palette_uv {
998 let buf = if plane_idx == 1 { ub } else { vb };
999 set_palette_pred(buf.clone(), fctx);
1000 }
1001 for cu_row in 0..chroma_block_h / uh {
1002 for cu_col in 0..chroma_block_w / uw {
1003 push_intra_rect(
1004 y,
1005 u,
1006 v,
1007 plane_idx,
1008 chroma_x + cu_col * uw,
1009 cpy + cu_row * uh,
1010 uw,
1011 uh,
1012 m.uv_predict_mode,
1013 m.angle_delta_uv,
1014 reach,
1015 &ZERO_RESIDUAL[..uw * uh],
1016 m.alpha
1017 .zip(ac)
1018 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
1019 None,
1020 m.smooth_neighbor_uv,
1021 fctx,
1022 );
1023 }
1024 }
1025 }
1026 } else {
1027 if let Some((ub, _)) = &m.palette_uv {
1028 set_palette_pred(ub.clone(), fctx);
1029 }
1030 push_intra_rect(
1031 y,
1032 u,
1033 v,
1034 1,
1035 cpx,
1036 cpy,
1037 chroma_w,
1038 chroma_h,
1039 m.uv_predict_mode,
1040 m.angle_delta_uv,
1041 reach,
1042 &zero,
1043 m.alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
1044 None,
1045 m.smooth_neighbor_uv,
1046 fctx,
1047 );
1048 if let Some((_, vb)) = &m.palette_uv {
1049 set_palette_pred(vb.clone(), fctx);
1050 }
1051 push_intra_rect(
1052 y,
1053 u,
1054 v,
1055 2,
1056 cpx,
1057 cpy,
1058 chroma_w,
1059 chroma_h,
1060 m.uv_predict_mode,
1061 m.angle_delta_uv,
1062 reach,
1063 &zero,
1064 m.alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
1065 None,
1066 m.smooth_neighbor_uv,
1067 fctx,
1068 );
1069 }
1070 (zero.clone(), zero)
1071 } else if lossless(fctx) {
1072 // lane-lossless: the strip's chroma plane block is coded as 4x4
1073 // transform units too (libaom `read_tx_size` returns TX_4X4 for every
1074 // plane), PLANE-MAJOR inside the block -- U's units first, then V's
1075 // (`decode_token_recon_block`'s mu-chunk loop, measured against
1076 // aomdec's `EC_TRACE_COEFF` on a `-crf 0` stream: plane=1, plane=1,
1077 // plane=2, plane=2 for a 16x8 strip). `get_txb_ctx` adds its `+10`
1078 // offset (our `+3` row base) whenever the plane block is bigger than
1079 // the transform.
1080 let scan4 = default_scan(4);
1081 let offset = (chroma_w > 4 || chroma_h > 4).then_some(3);
1082 let (cw_n, ch_n) = (chroma_w / 4, chroma_h / 4);
1083 // lane-av1-llband: one 4x4 chroma unit's extent in LUMA pixels -- 4
1084 // chroma px scaled by the plane's own subsampling. The hardcoded 8
1085 // was the 4:2:0 unit's span; at 4:4:4 a unit is 4x4 LUMA px (one mi
1086 // cell), and the 8-px step made every unit past the first column/row
1087 // read its `txb_skip` context at the WRONG mi (two cells over) and
1088 // stamp a 2-cell span with one unit's state -- the polluted above-band
1089 // cell behind a 16x8 leaf's U bc=2 unit of the 444 lossless key frame
1090 // (measured: oracle `EC_DBGCTX` reads 1-cell spans at 1-mi steps;
1091 // ours read `above[28..29]` where the oracle read `above[26]`).
1092 let span_x = 4 << ss_x(fctx);
1093 let span_y = 4 << ss_y(fctx);
1094 let mut last = [Grid::Zero(16), Grid::Zero(16)];
1095 for plane_idx in 1..=2 {
1096 for cu_row in 0..ch_n {
1097 for cu_col in 0..cw_n {
1098 // lane-av1offtile: the CHROMA twin of the luma walk's
1099 // `max_blocks_wide/high` clip (decode.rs:12516, lane-hgkf
1100 // r1). libaom computes those bounds per PLANE
1101 // (`max_block_wide(xd, plane_bsize, plane)`,
1102 // av1_common_int.h:1565 -- `mb_to_right_edge >>
1103 // (3 + pd->subsampling_x)`, then `>> MI_SIZE_LOG2`), so a
1104 // chroma unit whose top-left sample falls outside the
1105 // CHROMA plane is never coded. This walk counted
1106 // `chroma_w / 4` x `chroma_h / 4` units off the BLOCK's
1107 // own extent instead.
1108 //
1109 // MEASURED on `mix_176x144_6.obu` (4:2:0 8-bit,
1110 // --cq-level=0 --aq-mode=1 altref; the 48x16 bottom-right
1111 // sliver, block mi=(32,32) px=(128,128) bw=64 bh=32):
1112 // the chroma plane is 88x72, so `cw_n` must be
1113 // `(88 - 64) / 4 = 6` and `ch_n` `(72 - 64) / 4 = 2` --
1114 // the oracle's own `EC_ECDUMP_IN` for that block is
1115 // exactly 12 units per plane (bc 0..5 x br 0..1). Ours
1116 // walked 8 x 4 = 32 per plane: 20 phantom units x 2
1117 // planes = the 40 extra `txb_skip` reads after SYMR
1118 // 25791, all at `mi=(32,32)`, all `all_zero`, all with
1119 // the bit position FROZEN at 36288 -- reads out of a
1120 // tile already exhausted, which is what turned the
1121 // desync 11 970 reads later into a hard
1122 // `REFUSED: unsupported: AV1 tile (a Golomb tail longer
1123 // than this decoder reads)`.
1124 if cpx + cu_col * 4 >= u.true_width || cpy + cu_row * 4 >= u.true_height {
1125 hit!(RECT_SPLIT_LOSSLESS_CHROMA_OFFTILE_HITS);
1126 continue;
1127 }
1128 let cu_mi = (mi_r + cu_row * (span_y / MI), mi_c + cu_col * (span_x / MI));
1129 // lane-av1422llintra: at ss (1, 0) one chroma column
1130 // spans TWO luma mi columns, so the plain rect walk sums
1131 // its whole-unit dc sign TWICE where libaom's
1132 // `get_txb_ctx_general` reads `txb_w_unit` chroma cells
1133 // -- one per column. `dc_sign_ctx` only sees the vote's
1134 // SIGNUM, so a doubled above vote flips the row exactly
1135 // when above and left cancel (a+l = 0 -> ctx 0 becomes
1136 // 2a+l = +a). Measured on the pinned 4:2:2 all-intra
1137 // lossless control `ll422_allintra.obu`: the V 4x4 unit
1138 // at chroma (24, 8) of the BLOCK_32X8 at mi(2,8) --
1139 // oracle `EC_DBGCTX above0=23 left0=13` sums to dc 0 and
1140 // reads `dc_sign_cdf[0]`; ours summed the above column
1141 // twice, got vote +1, and read `dc_sign_cdf[2]`, so the
1142 // DC sign symbol came out inverted and the whole tile
1143 // desynced from there. Identical to the guard one arm up
1144 // at 12865.
1145 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
1146 neighbours.around_mi_422_chroma(cu_mi, span_x, span_y)
1147 } else {
1148 neighbours.around_mi_rect(cu_mi, span_x, span_y)
1149 };
1150 let cu_reach = tu_reach(
1151 bw,
1152 bh,
1153 cu_col * span_x,
1154 cu_row * span_y,
1155 span_x,
1156 block_reach,
1157 px,
1158 py,
1159 y.width,
1160 y.height,
1161 fctx,
1162 );
1163 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
1164 if let Some((ub, vb)) = &m.palette_uv {
1165 let pbuf = if plane_idx == 1 { ub } else { vb };
1166 set_palette_pred(
1167 palette_window(pbuf, chroma_w, cu_col * 4, cu_row * 4, 4, 4),
1168 fctx,
1169 );
1170 }
1171 let grid = read_plane(
1172 dec,
1173 cdfs,
1174 TxbSet::Chroma4,
1175 scan4,
1176 plane_idx,
1177 cu_around[plane_idx],
1178 m.mode,
1179 m.uv_predict_mode,
1180 m.angle_delta_uv,
1181 cu_reach,
1182 y,
1183 u,
1184 v,
1185 cu_x,
1186 cu_y,
1187 4,
1188 4,
1189 base_q_idx,
1190 m.alpha
1191 .zip(ac)
1192 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
1193 None,
1194 offset,
1195 m.smooth_neighbor_uv,
1196 fctx,
1197 )?;
1198 if span_x == 4 && span_y == 4 {
1199 hit!(RECT_SPLIT_LOSSLESS_CHROMA444_HITS);
1200 }
1201 neighbours.record_mi_chroma(cu_mi, span_x, span_y, plane_idx, &grid);
1202 ll_chroma_units.push((cu_mi, plane_idx, grid.clone(), span_x, span_y));
1203 last[plane_idx - 1] = grid;
1204 }
1205 }
1206 }
1207 let [ug, vg] = last;
1208 (ug, vg)
1209 } else if chroma_tiled {
1210 let (uw, uh, set, scan): (usize, usize, TxbSet, &[u16]) =
1211 if chroma_422_pair_wide || chroma_422_oob {
1212 // lane-av1-422blockhalf / lane-av1-422stripanchor: the
1213 // BLOCK_INVALID-plane chroma's (4, 8) units -- the Release
1214 // oracle's out-of-bounds `max_txsize_rect_lookup` byte (TX_4X8,
1215 // see above). For the 4-wide strip the units tile the PAIR's
1216 // plane, stepping from the floored anchor.
1217 (4, 8, TxbSet::ChromaRect8x4, &SCAN_4X8)
1218 } else {
1219 match (chroma_w, chroma_h) {
1220 (64, 32) | (32, 64) | (32, 32) => (32, 32, TxbSet::Chroma32, default_scan(32)),
1221 (64, 16) => (32, 16, TxbSet::ChromaRect32x16, &SCAN_32X16),
1222 (16, 64) => (16, 32, TxbSet::ChromaRect32x16, &SCAN_16X32),
1223 // lane-av1-422: the 4:2:2 square chroma planes (height unhalved),
1224 // through the square reader like every other square chroma unit.
1225 (16, 16) => (16, 16, TxbSet::Chroma16, default_scan(16)),
1226 (8, 8) => (8, 8, TxbSet::Chroma8, default_scan(8)),
1227 _ => unreachable!("chroma_tiled"),
1228 }
1229 };
1230 // lane-av1-422: the witness counter, keyed to ss (1,0) so only a 4:2:2
1231 // frame's square chroma units count it.
1232 if uw == uh && ss_x(fctx) == 1 && ss_y(fctx) == 0 {
1233 hit!(CHROMA422_SQUARE_HITS);
1234 }
1235 if chroma_422_pair_wide {
1236 hit!(CHROMA422_PAIR_WIDE_HITS);
1237 }
1238 let (nw, nh) = (chroma_block_w / uw, chroma_block_h / uh);
1239 // lane-av1-422stripanchor: the pair's plane block is BLOCK_INVALID
1240 // whatever the pair size (`num_pels_log2_lookup[255]` reads 0xff in
1241 // the pinned Release oracle), so its txb_skip rows always carry the
1242 // bigger-plane +3 (the av1422q rule the pair16 arm measures).
1243 let bigger = chroma_422_pair_wide || chroma_w * chroma_h > uw * uh;
1244 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
1245 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra;
1246 // smaller rect units (the 4:2:2 BLOCK_INVALID-plane (4, 8)s) take the
1247 // mode-indexed default, the same rule the unsplit arm below applies.
1248 let default_tx = if uw.max(uh) >= 32 {
1249 TxType::DctDct
1250 } else {
1251 default_intra_tx_type(m.uv_predict_mode as u8)
1252 };
1253 let mut last = [Grid::Zero(uw * uh), Grid::Zero(uw * uh)];
1254 for plane_idx in 1..=2 {
1255 for cu_row in 0..nh {
1256 for cu_col in 0..nw {
1257 let luma_span_x = uw << ss_x(fctx);
1258 let luma_span_y = uh << ss_y(fctx);
1259 let cu_mi = (
1260 mi_r + cu_row * (luma_span_y / MI),
1261 if chroma_422_pair_wide {
1262 mi_c & !1
1263 } else {
1264 mi_c
1265 } + cu_col * (luma_span_x / MI),
1266 );
1267 // lane-av1-422blockhalf: the 4:2:2 (4, 8) units read their
1268 // chroma context per chroma cell
1269 // ([`Neighbours::around_mi_422_chroma`], the block-8
1270 // rule) -- the plain rect walk samples one chroma cell
1271 // twice at ss_x 1. Every pre-existing shape keeps its own
1272 // walk.
1273 // lane-av1422mi24: the plain rect walk's double-count
1274 // hits EVERY unit shape at ss (1,0), not just the (4, 8)
1275 // one -- the (8, 8) unit of a 16x8 intra-in-inter strip
1276 // read its above dc votes twice and its U dc_sign one
1277 // ctx row high (t422 frame 1). Route every ss (1,0)
1278 // unit through the every-second-above-cell sampling;
1279 // 4:2:0/4:4:4 keep the plain walk verbatim.
1280 let cu_around = if chroma_422_oob || (ss_x(fctx) == 1 && ss_y(fctx) == 0) {
1281 neighbours.around_mi_422_chroma(cu_mi, luma_span_x, luma_span_y)
1282 } else {
1283 neighbours.around_mi_rect(cu_mi, luma_span_x, luma_span_y)
1284 };
1285 let (cu_x, cu_y) = (chroma_x + cu_col * uw, cpy + cu_row * uh);
1286 let cfl = m.alpha.map(|(au, av)| {
1287 let alpha = if plane_idx == 1 { au } else { av };
1288 (
1289 alpha,
1290 if chroma_422_pair_wide {
1291 // The unit's co-located luma is the PAIR's
1292 // 8-px-wide band at the floored mi column.
1293 cfl_src_rect(
1294 (mi_c & !1) * MI + cu_col * luma_span_x,
1295 py + cu_row * luma_span_y,
1296 luma_span_x,
1297 luma_span_y,
1298 )
1299 } else {
1300 cfl_src_rect(
1301 px + cu_col * luma_span_x,
1302 py + cu_row * luma_span_y,
1303 luma_span_x,
1304 luma_span_y,
1305 )
1306 },
1307 )
1308 });
1309 // lane-av1-422kf: the palette colour map is consumed per
1310 // unit here like every other chroma arm (`av1_visit_palette`
1311 // feeds the whole plane block; window it to this unit).
1312 // Without this the square chroma rows decoded a uv-palette
1313 // strip's chroma as plain DC (class same-symbols-silent-
1314 // prediction: the rng stayed in sync, only the prediction
1315 // was dropped).
1316 if let Some((ub, vb)) = &m.palette_uv {
1317 let buf = if plane_idx == 1 { ub } else { vb };
1318 set_palette_pred(
1319 palette_window(buf, chroma_block_w, cu_col * uw, cu_row * uh, uw, uh),
1320 fctx,
1321 );
1322 }
1323 // libaom computes `has_top_right` PER TRANSFORM UNIT (defined
1324 // reconintra.c:196, called from `av1_build_intra_predictors` at
1325 // reconintra.c:1847 with the txb walk's own
1326 // `blk_col`/`blk_row`), never per block: the
1327 // `row_off == 0` arm asks `col_off + top_right_count_unit
1328 // < plane_bw_unit`, so the FIRST unit of a 2-wide chroma
1329 // grid reads its above-right out of the already-reconstructed
1330 // block ABOVE even when the block's own right edge is the
1331 // frame's. Passing this walk's block-level `reach` gave
1332 // every unit the same answer, and `PlaneBuf::edges`
1333 // (decode.rs:20840) truncates the above row at
1334 // `own_across` when `above_right` is false -- so a
1335 // directional unit whose angle is below 90
1336 // (`need_right`, intra.rs:546) predicted with a 32-sample
1337 // above row where libaom used 64.
1338 // MEASURED on `fixtures/r512_rect2x1_1x2_444.obu`
1339 // (4:4:4 8-bit 256x256, one frame): frame 0 plane U 130
1340 // samples and plane V 30 samples wrong, every one of them
1341 // in the right 6 columns of the `cu=(0,0)` unit at
1342 // `mi=(48,48)` `px=(192,192)` -- the unit whose above-right
1343 // the block reach denied. Row0 and col0 of the prediction
1344 // matched the oracle exactly and the prediction SUM did
1345 // not (172662 vs 171512 on U, 125978 vs 126008 on V), so
1346 // the residual read is bit-identical and the divergence is
1347 // prediction-side, not entropy. Gate:
1348 // `a_444_rect_strip_chroma_tiled_2x1_and_1x2_units_take_their_own_above_right_reach`.
1349 let cu_reach = tu_reach_rect(
1350 bw,
1351 bh,
1352 (cu_col * uw) << ss_x(fctx),
1353 (cu_row * uh) << ss_y(fctx),
1354 uw << ss_x(fctx),
1355 uh << ss_y(fctx),
1356 reach,
1357 px,
1358 py,
1359 y.width,
1360 y.height,
1361 fctx,
1362 );
1363 if cu_reach.above_right != reach.above_right
1364 || cu_reach.below_left != reach.below_left
1365 {
1366 hit!(RECT_TILED_CHROMA_UNIT_REACH_HITS);
1367 }
1368 if nw * nh > 1 {
1369 match (nw, nh) {
1370 (2, 1) => hit!(RECT_TILED_CHROMA_2X1_HITS),
1371 (1, 2) => hit!(RECT_TILED_CHROMA_1X2_HITS),
1372 _ => hit!(RECT_TILED_CHROMA_NXN_HITS),
1373 }
1374 }
1375 // 32x32 does not fit read_coeffs_rect's scratch (768). The
1376 // square reader is the path every other 32x32 chroma unit uses.
1377 let levels = if uw == uh {
1378 read_plane(
1379 dec,
1380 cdfs,
1381 set,
1382 scan,
1383 plane_idx,
1384 cu_around[plane_idx],
1385 m.mode,
1386 m.uv_predict_mode,
1387 m.angle_delta_uv,
1388 cu_reach,
1389 y,
1390 u,
1391 v,
1392 cu_x,
1393 cu_y,
1394 uw,
1395 uw,
1396 base_q_idx,
1397 cfl,
1398 None,
1399 bigger.then_some(3),
1400 m.smooth_neighbor_uv,
1401 fctx,
1402 )?
1403 } else {
1404 let skip_ctx = usize::from(cu_around[plane_idx].0)
1405 + usize::from(cu_around[plane_idx].1)
1406 + usize::from(bigger) * 3;
1407 let mut coding = cdfs.txb(set, m.uv_predict_mode);
1408 let (levels, tx_type) = read_coeffs_rect(
1409 dec,
1410 &mut coding,
1411 scan,
1412 uw,
1413 uh,
1414 skip_ctx,
1415 dc_sign_ctx(cu_around[plane_idx].2),
1416 default_tx,
1417 plane_idx,
1418 )?;
1419 let residual = dequant_and_inverse_typed_wh(
1420 &levels,
1421 uw,
1422 uh,
1423 crate::decode::bit_depth(fctx),
1424 block_q_idx(fctx),
1425 plane_q_delta(plane_idx, fctx).0,
1426 plane_q_delta(plane_idx, fctx).1,
1427 tx_type,
1428 block_iqmatrix(fctx, plane_idx, uw, uh, tx_type),
1429 );
1430 push_intra_rect(
1431 y,
1432 u,
1433 v,
1434 plane_idx,
1435 cu_x,
1436 cu_y,
1437 uw,
1438 uh,
1439 m.uv_predict_mode,
1440 m.angle_delta_uv,
1441 cu_reach,
1442 &residual,
1443 cfl,
1444 None,
1445 m.smooth_neighbor_uv,
1446 fctx,
1447 );
1448 levels
1449 };
1450 neighbours.record_mi_chroma(
1451 cu_mi,
1452 luma_span_x,
1453 luma_span_y,
1454 plane_idx,
1455 &levels,
1456 );
1457 tiled_chroma_units.push((
1458 cu_mi,
1459 plane_idx,
1460 levels.clone(),
1461 luma_span_x,
1462 luma_span_y,
1463 ));
1464 last[plane_idx - 1] = levels;
1465 }
1466 }
1467 }
1468 (last[0].clone(), last[1].clone())
1469 } else {
1470 let (chroma_set, chroma_scan) = chroma.expect("refused above when None");
1471 // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size
1472 // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra,
1473 // so only the 16x8/8x16 pair takes the mode-indexed default.
1474 let default_tx = if chroma_w.max(chroma_h) >= 32 {
1475 TxType::DctDct
1476 } else {
1477 default_intra_tx_type(m.uv_predict_mode as u8)
1478 };
1479 // lane-av1422mi24: at ss (1,0) the chroma above span is `bw >> 1`
1480 // chroma cells spread over `bw` luma mi columns -- the per-mi gather
1481 // counts every chroma column's whole-unit dc sign twice (the t422
1482 // frame-1 mi(26,60) intra-in-inter strip's U dc_sign read one ctx
1483 // row high). Luma keeps the per-mi gather; the two chroma planes
1484 // take [`Neighbours::around_mi_422_chroma`]'s every-second
1485 // above-cell sampling, like every other 4:2:2 chroma gather.
1486 let mut around = neighbours.around_mi_rect(at_mi, bw, bh);
1487 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
1488 let c = neighbours.around_mi_422_chroma(at_mi, bw, bh);
1489 around[1] = c[1];
1490 around[2] = c[2];
1491 }
1492 let mut grids: Vec<Grid> = Vec::with_capacity(2);
1493 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
1494 #[allow(clippy::needless_range_loop)]
1495 for plane_idx in 1..=2 {
1496 let skip_ctx = usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1);
1497 let mut coding = cdfs.txb(chroma_set, m.uv_predict_mode);
1498 let (levels, tx_type) = read_coeffs_rect(
1499 dec,
1500 &mut coding,
1501 chroma_scan,
1502 chroma_w,
1503 chroma_h,
1504 skip_ctx,
1505 dc_sign_ctx(around[plane_idx].2),
1506 default_tx,
1507 plane_idx,
1508 )?;
1509 // The same delta_q proof the unsplit rect64 path records
1510 // (lane-rectsplit r4: lifting the split-transform refusal moved
1511 // superblock strips onto this path, so only counting there would
1512 // leave the delta_q gate's counter silent for them).
1513 if bw.max(bh) == 64 && fctx.current_q_idx.with(|c| c.get()) != i32::from(base_q_idx) {
1514 hit!(RECT64_QIDX_DRIFT_HITS);
1515 }
1516 let residual = dequant_and_inverse_typed_wh(
1517 &levels,
1518 chroma_w,
1519 chroma_h,
1520 crate::decode::bit_depth(fctx),
1521 // lane-d792: the BLOCK's quantizer index, i.e. the frame's
1522 // own index PLUS this block's segment `SEG_LVL_ALT_Q` --
1523 // reading `current_q_idx` here dropped the segment feature
1524 // that every other dequant site applies (class
1525 // `parsed-then-discarded`).
1526 block_q_idx(fctx),
1527 plane_q_delta(plane_idx, fctx).0,
1528 plane_q_delta(plane_idx, fctx).1,
1529 tx_type,
1530 block_iqmatrix(fctx, plane_idx, chroma_w, chroma_h, tx_type),
1531 );
1532 let cfl = m
1533 .alpha
1534 .zip(ac)
1535 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac));
1536 if let Some((ub, vb)) = &m.palette_uv {
1537 let buf = if plane_idx == 1 { ub } else { vb };
1538 set_palette_pred(buf.clone(), fctx);
1539 }
1540 push_intra_rect(
1541 y,
1542 u,
1543 v,
1544 plane_idx,
1545 cpx,
1546 cpy,
1547 chroma_w,
1548 chroma_h,
1549 m.uv_predict_mode,
1550 m.angle_delta_uv,
1551 reach,
1552 &residual,
1553 cfl,
1554 None,
1555 m.smooth_neighbor_uv,
1556 fctx,
1557 );
1558 grids.push(levels);
1559 }
1560 let mut it = grids.into_iter();
1561 (it.next().unwrap(), it.next().unwrap())
1562 };
1563 neighbours.record_split_luma_rect_mi(
1564 at_mi,
1565 bw,
1566 bh,
1567 m.mode,
1568 m.uv_predict_mode,
1569 [&u_grid, &v_grid],
1570 );
1571 for (cu_mi, plane, unit, span_w, span_h) in &ll_chroma_units {
1572 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
1573 }
1574 for (cu_mi, plane, unit, span_w, span_h) in &tiled_chroma_units {
1575 neighbours.record_mi_chroma(*cu_mi, *span_w, *span_h, *plane, unit);
1576 }
1577 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip);
1578 neighbours.fill_lf_grid_rect(
1579 (mi_r, mi_c),
1580 bw / MI,
1581 bh / MI,
1582 tx_w as u8,
1583 tx_h as u8,
1584 0,
1585 fctx,
1586 );
1587 if crate::envflags::env_flag!("EC_AV1_TRACE") {
1588 let (rng, _) = dec.debug_state();
1589 eprintln!(
1590 "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
1591 tx={tx_w}x{tx_h} rng={rng}"
1592 );
1593 }
1594 Ok(())
1595}
1596
1597/// One intra-coded HORZ/VERT strip on the INTER block path (lane-intrarect
1598/// r1) -- the shape [`decode_inter_block`]'s intra arm refused by name
1599/// because it predicts squares only. Every pixel here goes through the rect
1600/// machinery the key-frame paths already prove: [`decode_rect_split`], which
1601/// at `depth == 0` is the unsplit strip as a single transform unit and
1602/// beyond it the per-unit walk of [`depth_to_tx_wh`].
1603///
1604/// What is genuinely different from [`decode_block_rect`] is the mode
1605/// syntax: on an inter frame an intra block reads `y_mode[size_group]` and
1606/// `uv_mode` (libaom `read_intra_block_mode_info`, decodemv.c:1065), never
1607/// the key frame's `kf_y_mode` above/left pair. This mirrors the square
1608/// intra-in-inter arm's own reads at the rect footprint, including its
1609/// inherited gaps -- no `use_filter_intra` symbol (every inter gate recipe
1610/// pins `--enable-filter-intra=0`; lane-fiinter owns that read for both the
1611/// square and this arm) and a nonzero luma angle delta refused by name.
1612///
1613/// The strip's own neighbour records (luma per transform unit, chroma, skip
1614/// grid, deblock grid) are [`decode_rect_split`]'s; the caller adds the
1615/// inter-side bands and the mi map.
1616#[allow(clippy::too_many_arguments)]
1617/// The `(size_group_lookup, bsize_to_tx_size_cat)` row an INTRA block coded
1618/// inside an inter frame reads its `y_mode` and `tx_depth` symbols from, for
1619/// the rect footprints [`decode_intra_rect_in_inter`] resolves itself (the
1620/// 128-root halves and the 16x4/4x16 strips of a 1:4 partition take their own
1621/// branches before this). libaom `common_data.h:61` / `blockd.h:1347`: the 2:1
1622/// strips keep the group/category diagonal (BLOCK_16X8 -> 1/1, BLOCK_32X16 ->
1623/// 2/2, BLOCK_64X32 -> 3/3), the 1:4 ones break it (BLOCK_32X8 is group 1 but
1624/// category 2, BLOCK_64X16 group 2 and category 3), which is why the row is a
1625/// table here rather than a shift of `bw.min(bh)`.
1626fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
1627 Some(match (bw.min(bh), bw.max(bh)) {
1628 (8, 16) => (1usize, 1usize),
1629 (16, 32) => (2, 2),
1630 (32, 64) => (3, 3),
1631 (8, 32) => (1, 2),
1632 (16, 64) => (2, 3),
1633 _ => return None,
1634 })
1635}
1636
1637/// lane-t900 r20, refusal B ("an intra-coded {bw}x{bh} block on the inter
1638/// block path"): the shapes that can reach that arm, enumerated against the
1639/// MEASURED domain of the inter block path
1640/// ([`INTER_BLOCK_SHAPES`], the census the gate
1641/// `a_block_shape_census_over_three_real_streams_leaves_the_rect_residual_refusal_unreachable`
1642/// fills from three real streams).
1643///
1644/// [`decode_intra_rect_in_inter`] is called from one site, under
1645/// `write_w != side || write_h != side`, and only after two earlier arms have
1646/// taken their shapes: a footprint with a side below 8 is either a 16x4/4x16
1647/// strip WITH a chroma-pair record (the `strip16` branch) or refused by name,
1648/// and a 128-px footprint returns from the `bw.max(bh) == 128` branch. What is
1649/// left is every rectangular census shape with `8 <= min` and `max <= 64` --
1650/// and each of those has a row, so the refusal names a shape no measured
1651/// stream can present.
1652#[test]
1653fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
1654 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
1655 // names that string exactly (placeholders included) and pins its guard
1656 // site. The enumeration below establishes the shape domain; on its own it
1657 // never said WHICH string the domain was about, so under a real function
1658 // boundary -- rather than a window that ran into the next test -- the row
1659 // read as unanchored.
1660 const REFUSAL: &str = "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)";
1661 assert!(
1662 crate::test_source::module_source("decode").contains(REFUSAL),
1663 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
1664 );
1665 let mut checked = 0;
1666 for &(side, w, h) in &INTER_BLOCK_SHAPES {
1667 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
1668 continue;
1669 }
1670 assert!(
1671 intra_in_inter_size_row(w, h).is_some(),
1672 "the inter path decodes {w}x{h} blocks, and an INTRA one of that shape would hit \
1673 the \"no size-group/tx-category row\" refusal"
1674 );
1675 checked += 1;
1676 }
1677 assert_eq!(
1678 checked, 10,
1679 "the block-shape census changed: {checked} rect shapes reach the intra-in-inter row \
1680 lookup, not the 10 this claim was measured over"
1681 );
1682}
1683
1684/// The `motion_mode` / `obmc` CDF row for a block footprint: libaom's
1685/// `motion_mode_cdf[mbmi->bsize]`, in this crate's packed row order (which
1686/// `cdf::MOTION_MODE` documents -- the 128-px rows come last, so they are
1687/// matched before the square arm's `log2` shortcut).
1688///
1689/// `None` is the refusal "a motion_mode symbol for a block shape with no CDF
1690/// row here"; the enumeration below is what proves no conformant block can
1691/// reach it.
1692pub(crate) fn motion_mode_cdf_row(write_w: usize, write_h: usize) -> Option<usize> {
1693 Some(match (write_w, write_h) {
1694 // lane-sb128c r5: the 128 root's own rows come FIRST -- the square arm
1695 // below maps 128 to row 4 (BLOCK_16X32).
1696 (64, 128) => 14,
1697 (128, 64) => 15,
1698 (128, 128) => 16,
1699 (w, h) if w == h => (w.trailing_zeros() - 3) as usize,
1700 (16, 32) => 4,
1701 (32, 16) => 5,
1702 (32, 64) => 6,
1703 (64, 32) => 7,
1704 (8, 32) => 8,
1705 (32, 8) => 9,
1706 (16, 64) => 10,
1707 (64, 16) => 11,
1708 // lane-inter4 r3: the 16x16-level rect inter leaves.
1709 (8, 16) => 12,
1710 (16, 8) => 13,
1711 _ => return None,
1712 })
1713}
1714
1715/// Every `BLOCK_SIZES_ALL` footprint, as `(width, height)` in pixels: the six
1716/// squares, the ten 2:1 shapes and the six 1:4 ones (libaom `common_data.h`,
1717/// `block_size_wide`/`block_size_high`).
1718#[cfg(test)]
1719pub(super) const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
1720 (4, 4),
1721 (4, 8),
1722 (8, 4),
1723 (8, 8),
1724 (8, 16),
1725 (16, 8),
1726 (16, 16),
1727 (16, 32),
1728 (32, 16),
1729 (32, 32),
1730 (32, 64),
1731 (64, 32),
1732 (64, 64),
1733 (64, 128),
1734 (128, 64),
1735 (128, 128),
1736 (4, 16),
1737 (16, 4),
1738 (8, 32),
1739 (32, 8),
1740 (16, 64),
1741 (64, 16),
1742];
1743
1744/// lane-t900 r25, enumeration: the refusal "a motion_mode symbol for a block
1745/// shape with no CDF row here" names a shape no conformant stream can present.
1746///
1747/// A `motion_mode`/`obmc` symbol is read only under `motion_mode_eligible`,
1748/// whose `write_w.min(write_h) >= 8` clause is libaom's
1749/// `is_motion_variation_allowed_bsize` (`blockd.h:1455`). So the reachable
1750/// domain of [`motion_mode_cdf_row`] is exactly the `BLOCK_SIZES_ALL`
1751/// footprints with `min(bw, bh) >= 8` -- 17 of the 22 -- and each of those
1752/// must map to a distinct row of the 17-row `Cdfs::motion_mode` table. The
1753/// five it excludes (4x4, 4x8, 8x4, 4x16, 16x4) are the ones the eligibility
1754/// clause rejects before the lookup.
1755#[test]
1756fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
1757 // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
1758 // names it and pins its guard site.
1759 const REFUSAL: &str = "a motion_mode symbol for a block shape with no CDF row here";
1760 assert!(
1761 crate::refusal_inventory::pins_refusal(
1762 crate::test_source::module_source("decode"),
1763 REFUSAL
1764 ),
1765 "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
1766 );
1767 let mut rows = std::collections::BTreeSet::new();
1768 let mut excluded = 0;
1769 for (w, h) in BLOCK_SIZES_ALL_WH {
1770 if w.min(h) < 8 {
1771 excluded += 1;
1772 assert!(
1773 w == 4 || h == 4,
1774 "{w}x{h} is not one of the sub-8 shapes is_motion_variation_allowed_bsize rejects"
1775 );
1776 continue;
1777 }
1778 let row = motion_mode_cdf_row(w, h).unwrap_or_else(|| {
1779 panic!(
1780 "a {w}x{h} block passes is_motion_variation_allowed_bsize and reads a motion_mode \
1781 symbol, but has no CDF row -- the refusal is a real gap, not a dead arm"
1782 )
1783 });
1784 assert!(
1785 row < 17,
1786 "{w}x{h} maps to motion_mode row {row}, outside the 17-row table"
1787 );
1788 assert!(rows.insert(row), "{w}x{h} shares motion_mode row {row}");
1789 }
1790 assert_eq!(excluded, 5, "the sub-8 footprint set changed");
1791 assert_eq!(
1792 rows.len(),
1793 17,
1794 "17 eligible footprints must fill all 17 rows of the motion_mode table"
1795 );
1796}
1797
1798/// lane-av1-422stripanchor, format-cell census for the 4-wide-strip pair port
1799/// ([`chroma422_pair_plane`], [`decode_rect_split`]'s chroma routing): over
1800/// every `BLOCK_SIZES_ALL` footprint at every subsampling cell, the pair arm
1801/// fires exactly when libaom's own `av1_ss_size_lookup[..][1][0]` column
1802/// (`common_data.c`) marks the plane block BLOCK_INVALID AND the plane would
1803/// be 2 px wide -- the 4-wide footprints. The tall/wide BLOCK_INVALID shapes
1804/// stay on the pre-existing `chroma_422_oob` (4, 8) tiling, and 4:2:0 /
1805/// 4:4:4 never enter either arm (the byte-identical claim, checked per cell).
1806#[test]
1807fn chroma422_pair_plane_matches_the_ss_size_lookup_cells() {
1808 // The `av1_ss_size_lookup[..][1][0]` column verbatim (pinned oracle,
1809 // `common_data.c`), keyed by footprint: `true` = BLOCK_INVALID.
1810 let ss10_invalid: &[(&str, bool)] = &[
1811 ("4x4", false),
1812 ("4x8", true),
1813 ("8x4", false),
1814 ("8x8", false),
1815 ("8x16", true),
1816 ("16x8", false),
1817 ("16x16", false),
1818 ("16x32", true),
1819 ("32x16", false),
1820 ("32x32", false),
1821 ("32x64", true),
1822 ("64x32", false),
1823 ("64x64", false),
1824 ("64x128", true),
1825 ("128x64", false),
1826 ("128x128", false),
1827 ("4x16", true),
1828 ("16x4", false),
1829 ("8x32", true),
1830 ("32x8", false),
1831 ("16x64", true),
1832 ("64x16", false),
1833 ];
1834 for (footprint, invalid10) in ss10_invalid {
1835 let (w, h) = footprint.split_once('x').unwrap();
1836 let (bw, bh) = (w.parse::<usize>().unwrap(), h.parse::<usize>().unwrap());
1837 // BLOCK_4X4 is the SQUARE path's leaf, never a strip: its ss cell is
1838 // valid because a (2, 4) plane area rounds UP to the 4x4 read
1839 // (`sub8_leaf_chroma422`'s own rule), and it never reaches
1840 // [`decode_rect_split`] at all.
1841 if (bw, bh) == (4, 4) {
1842 continue;
1843 }
1844 // 4:2:0 and 4:4:4: the port never fires, whatever the footprint.
1845 for (ss_x, ss_y) in [(false, false), (true, true)] {
1846 assert!(
1847 chroma422_pair_plane(ss_x, ss_y, 7, bw, bh).is_none(),
1848 "{bw}x{bh} at ss ({ss_x}, {ss_y}) must keep its own plane block"
1849 );
1850 }
1851 // 4:2:2: the pair arm is exactly the 2-px-wide (4-wide) slice of the
1852 // BLOCK_INVALID column, anchored at the floored mi column.
1853 let pair = chroma422_pair_plane(true, false, 7, bw, bh);
1854 assert_eq!(
1855 pair.is_some(),
1856 *invalid10 && bw == 4,
1857 "{bw}x{bh} at ss (1, 0): pair routing disagrees with ss_size_lookup"
1858 );
1859 if let Some((block_w, block_h, x, ctx_col)) = pair {
1860 assert_eq!((block_w, block_h), (4, bh), "{bw}x{bh} pair plane shape");
1861 assert_eq!(x, ((7 & !1) * MI) >> 1, "{bw}x{bh} floored write anchor");
1862 assert_eq!(ctx_col, 6, "{bw}x{bh} entropy cell is the floored column");
1863 // An even-column strip anchors at its own cell.
1864 let (x_even, col_even) = match chroma422_pair_plane(true, false, 6, bw, bh) {
1865 Some((_, _, x, c)) => (x, c),
1866 None => panic!("{bw}x{bh} lost its pair arm at an even mi_col"),
1867 };
1868 assert_eq!(
1869 (x_even, col_even),
1870 (12, 6),
1871 "even column keeps its own cell"
1872 );
1873 }
1874 }
1875 // The tall/wide BLOCK_INVALID shapes (8 px wide or more) are the
1876 // `chroma_422_oob` tiling's residents, not the pair arm's: both are
1877 // 4:2:2-only, so the two arms partition the BLOCK_INVALID column.
1878 for (bw, bh) in [
1879 (8usize, 16),
1880 (16, 32),
1881 (32, 64),
1882 (64, 128),
1883 (8, 32),
1884 (16, 64),
1885 ] {
1886 assert!(chroma422_pair_plane(true, false, 7, bw, bh).is_none());
1887 }
1888}
1889
1890// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1891#[allow(clippy::too_many_arguments)]
1892pub(super) fn decode_intra_rect_in_inter(
1893 dec: &mut SymbolDecoder,
1894 cdfs: &mut Cdfs,
1895 neighbours: &mut Neighbours,
1896 at: (usize, usize),
1897 bw: usize,
1898 bh: usize,
1899 skip: bool,
1900 allow_screen_content_tools: bool,
1901 // `(PARTITION_HORZ_4, is_chroma_reference)` when this strip is one of the
1902 // four 16x4 / 4x16 strips of a 16x16-level 1:4 partition (lane-intra16x4).
1903 strip16: Option<(bool, bool)>,
1904 y: &mut PlaneBuf<'static>,
1905 u: &mut PlaneBuf<'static>,
1906 v: &mut PlaneBuf<'static>,
1907 base_q_idx: u8,
1908 fctx: &crate::decode::FrameCtx,
1909) -> Result<()> {
1910 // `at` is in MI units (the inter path's own unit since lane-inter4);
1911 // `(r, c)` is the enclosing SUB cell the SUB-granular neighbour bands
1912 // below are still keyed by.
1913 let (mi_r, mi_c) = at;
1914 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
1915 // `size_group_lookup` (libaom common_data.h) and `bsize_to_tx_size_cat`
1916 // (blockd.h) for the three 2:1 strip shapes: BLOCK_16X8 -> group 1 /
1917 // cat 1, BLOCK_32X16 -> 2 / 2, BLOCK_64X32 -> 3 / 3 (the rectsplitx
1918 // finding -- the category is NOT the same for every strip size).
1919 // A 1:4 strip breaks that diagonal (BLOCK_32X8 is group 1 but cat 2), so
1920 // it is refused by name rather than read from the wrong CDF row.
1921 // lane-intra16x4: the 16x16-level 1:4 strip. `size_group_lookup`
1922 // (common_data.h:61) puts BLOCK_16X4/BLOCK_4X16 in group 0 and its
1923 // tx-depth category is 1 -- but nothing here has to know either, because
1924 // the strip decodes through the very body the KEY FRAME path proves for
1925 // this shape ([`decode_rect4_16_strip`]), including the 4:2:0 chroma
1926 // pairing (`is_chroma_reference`: strips 0 and 2 read no chroma at all,
1927 // strips 1 and 3 code one 8x4 (4x8) unit at the PAIR's origin). The only
1928 // inter-frame difference is the mode-info read, which
1929 // [`INTRA_IN_INTER_MODE`] switches to `read_intra_block_mode_info`'s
1930 // `y_mode[0]` plus the `skip` this caller already read.
1931 if let Some((horz, has_chroma)) = strip16 {
1932 // lane-t900 r22: the screen-content refusal here was STALE (class
1933 // stale-premise): [`decode_rect4_16_strip`] takes
1934 // `allow_screen_content_tools` and reads the whole palette syntax
1935 // (mode/size/colours/colour-index map, its own `palette_ctx_and_cache_mi`
1936 // pair) -- the key frame proves that body. Lifted with the 10-bit
1937 // witness `palette_screen_witness_10bit.obu`, whose inter frames carry
1938 // 16x4/4x16 intra strips inside a `--tune-content=screen` frame.
1939 debug_assert_eq!((bw, bh), if horz { (16, 4) } else { (4, 16) });
1940 fctx.intra_in_inter_mode.with(|c| c.set(Some((0, skip))));
1941 let res = decode_rect4_16_strip(
1942 dec,
1943 cdfs,
1944 neighbours,
1945 (mi_r, mi_c),
1946 horz,
1947 has_chroma,
1948 // The inter strips of the same partition publish their own
1949 // mi-exact mode, so the key-frame caller's coarse-cell stand-in
1950 // has nothing to add here.
1951 None,
1952 y,
1953 u,
1954 v,
1955 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
1956 allow_screen_content_tools,
1957 base_q_idx,
1958 fctx.tx_select_inter.with(std::cell::Cell::get),
1959 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
1960 fctx,
1961 );
1962 fctx.intra_in_inter_mode.with(|c| c.set(None));
1963 let (mode, uv, (tx_w, tx_h)) = res?;
1964 // lane-intra16x4, the same publication the 2:1 intra-in-inter strip
1965 // makes ([`decode_intra_rect_in_inter`]'s own tail): libaom runs
1966 // `set_txfm_ctxs(tx_size, n4_w, n4_h, skip && is_inter, xd)` for EVERY
1967 // block of an inter frame, intra ones included, and
1968 // `txfm_partition_update` for the var-tx context. The key-frame body
1969 // writes neither (a key frame has no var-tx tree and its own readers
1970 // use the deblock grid), so the block AFTER this strip read a stale
1971 // band -- measured: a 128x128 8-bit stream decoded the two intra 16x4
1972 // strips at mi(23,16)/(23,20) exactly and then broke on the very next
1973 // 16x16 row.
1974 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
1975 for i in 0..bw / MI {
1976 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
1977 *cell = tx_w as u8;
1978 }
1979 }
1980 for i in 0..bh / MI {
1981 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
1982 *cell = tx_h as u8;
1983 }
1984 }
1985 // [`decode_rect4_16`]'s own post-loop publication, per strip (the
1986 // coarse 16-px cell holds one entry for the whole 16x16 and the last
1987 // block to write it wins).
1988 neighbours.above_mode[c] = mode;
1989 neighbours.left_mode[r] = mode;
1990 if let Some(uvm) = uv {
1991 neighbours.above_uv_mode[c] = uvm;
1992 neighbours.left_uv_mode[r] = uvm;
1993 }
1994 neighbours.above_side[c] = bw;
1995 neighbours.left_side[r] = bh;
1996 if crate::envflags::env_flag!("EC_INTRA16X4") {
1997 eprintln!(
1998 "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
1999 mi_c * MI,
2000 mi_r * MI
2001 );
2002 }
2003 hit_do! {
2004 INTRA16X4_IN_INTER_HITS.with(|h| {
2005 let mut v = h.get();
2006 v[usize::from(!horz)] += 1;
2007 v[2] += usize::from(has_chroma);
2008 h.set(v);
2009 });
2010 }
2011 return Ok(());
2012 }
2013 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
2014 // coded INTRA inside an inter frame. `size_group_lookup` (common_data.h:61)
2015 // puts BLOCK_128X64/64X128/128X128 in group 3 and
2016 // `max_txsize_rect_lookup` caps them at TX_64X64, i.e. the same
2017 // `tx_size_cat3` row [`decode_block_128rect`] already reads -- so the whole
2018 // block decodes through the very body the KEY FRAME path proves for this
2019 // shape (square 64x64 luma units, one TX_32X32 chroma unit per 64x64 mu
2020 // chunk on the offset-10 txb_skip rows, per-TU prediction, the mu-chunk
2021 // `Reach` rule and the frame-edge write clip). The only inter-frame
2022 // differences live inside that body: the mode-info read
2023 // ([`INTRA_IN_INTER_MODE`] -> `y_mode[3]` plus the `skip` this caller
2024 // already read), the `tx_depth` context (the real TXFM_CONTEXT bands) and
2025 // the `set_txfm_ctxs` publication. CfL (>32), filter intra (>32) and
2026 // palette (>64) do not exist at this size and are refused by name there.
2027 // lane-t900 r18: the opt-in is LIFTED -- the arm has a witness.
2028 // `intra128_in_inter_witness2.obu` (gate
2029 // `an_intra_coded_128_half_inside_an_inter_frame_decodes_pixel_exact`)
2030 // fires it 3x 128x64 + 6x 64x128 and decodes byte-exact on every plane of
2031 // all 15 frames, so the hits are counted out of exact frames (class
2032 // `counter-from-refused-stream`). What r16/r17 could not find, and what
2033 // that recipe exploits: libaom's RD essentially never PICKS a 128-root
2034 // HORZ/VERT in the interior -- the 512x512 r16 witness and a textured
2035 // 640x384 sweep code 128 roots as NONE or SPLIT only. The shape appears
2036 // where the frame EDGE forces it: a partial last superblock row has
2037 // `has_rows128 == false`, so the 128x64 top half is implied, and a
2038 // partial last column implies the 64x128 left half. Put content no
2039 // reference holds (a fresh smooth ramp) in exactly those two bands of an
2040 // inter frame and the encoder codes those forced halves INTRA.
2041 if bw.max(bh) == 128 {
2042 // lane-t900 r32: no screen-content refusal here. `av1_allow_palette`
2043 // rejects every footprint with a 128-pixel side (`bw > 64 || bh > 64`,
2044 // enumerated by `no_block_footprint_with_a_128_pixel_side_can_carry_\
2045 // palette_syntax`), so a 128-root half consumes no palette syntax and
2046 // a screen-content frame's half is syntactically identical to the
2047 // non-screen one this arm already decodes byte-exact.
2048 if coeff_trace_on() {
2049 // lane-t900 r16: which decode-order frame this arm fires in --
2050 // interleaved with the `EC_COEFF_FRAME` markers, this is what
2051 // proves the hit is counted out of a frame that compares exact
2052 // (class `counter-from-refused-stream`).
2053 eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
2054 }
2055 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
2056 let res = decode_block_128rect(
2057 dec,
2058 cdfs,
2059 neighbours,
2060 (r, c),
2061 bw,
2062 bh,
2063 y,
2064 u,
2065 v,
2066 base_q_idx,
2067 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
2068 allow_screen_content_tools,
2069 fctx.tx_select_inter.with(std::cell::Cell::get),
2070 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
2071 fctx,
2072 );
2073 fctx.intra_in_inter_mode.with(|c| c.set(None));
2074 return res;
2075 }
2076 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
2077 if crate::envflags::env_flag!("EC_OBMCREC") {
2078 eprintln!(
2079 "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
2080 );
2081 }
2082 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
2083 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
2084 // can arrive here are enumerated against the measured block-shape
2085 // census ([`INTER_BLOCK_SHAPES`]) by
2086 // [`every_intra_in_inter_shape_the_census_lists_has_a_size_group_row`]
2087 // -- every one of them has a row, so this arm names a shape no stream
2088 // has been able to present.
2089 return Err(unsupported(format!(
2090 "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"
2091 )));
2092 };
2093 // lane-t900 r21: this arm used to refuse EVERY rect strip of a
2094 // screen-content frame ("palette syntax is consumed for square blocks
2095 // only"). It is not: [`read_intra_mode_rect`] generalised the palette read
2096 // to rect blocks on the key-frame path, and the 1:4 arm below goes through
2097 // it, while the 2:1 reader inlined further down now codes the same syntax
2098 // itself. A real `--tune-content=screen` inter stream reached this refusal
2099 // on 8x16 / 16x8 strips (gate
2100 // `a_real_aomenc_screen_inter_sequence_codes_palette_syntax_on_rect_intra_strips`).
2101 // lane-intra14 r1: a 1:4 strip decodes through the very readers the KEY
2102 // FRAME path already proves for this shape ([`decode_block_rect4`] at the
2103 // 32 level, [`decode_block_rect64`] at 64 -- both already handle the 1:4
2104 // luma/chroma transform tables, the per-unit split walk and the strip's
2105 // own neighbour records). The ONLY difference on an inter frame is the
2106 // mode-info read, which [`INTRA_IN_INTER_MODE`] switches to
2107 // `read_intra_block_mode_info`'s `y_mode[size_group]` plus the `skip`
2108 // this caller already read. `tx_cat` above is the same category those
2109 // readers hardcode (cat 2 in `decode_block_rect4`, cat 3 in
2110 // `decode_block_rect64`), asserted here so a future shape cannot drift.
2111 if bw.max(bh) == 4 * bw.min(bh) {
2112 debug_assert_eq!(tx_cat, if bw.max(bh) == 64 { 3 } else { 2 });
2113 fctx.intra_in_inter_mode
2114 .with(|c| c.set(Some((size_group, skip))));
2115 let res = if bw.max(bh) == 64 {
2116 decode_block_rect64(
2117 dec,
2118 cdfs,
2119 neighbours,
2120 (mi_r / (SUB / MI), mi_c / (SUB / MI)),
2121 bw,
2122 bh,
2123 y,
2124 u,
2125 v,
2126 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
2127 allow_screen_content_tools,
2128 base_q_idx,
2129 fctx.tx_select_inter.with(std::cell::Cell::get),
2130 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
2131 fctx,
2132 )
2133 } else {
2134 decode_block_rect4(
2135 dec,
2136 cdfs,
2137 neighbours,
2138 (mi_r, mi_c),
2139 bw,
2140 bh,
2141 None,
2142 y,
2143 u,
2144 v,
2145 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
2146 allow_screen_content_tools,
2147 base_q_idx,
2148 fctx.tx_select_inter.with(std::cell::Cell::get),
2149 fctx,
2150 )
2151 .map(|_| ())
2152 };
2153 fctx.intra_in_inter_mode.with(|c| c.set(None));
2154 res?;
2155 let shape = match (bw, bh) {
2156 (64, 16) => 0,
2157 (16, 64) => 1,
2158 (32, 8) => 2,
2159 _ => 3,
2160 };
2161 hit_do! {
2162 INTRA_RECT4_IN_INTER_HITS.with(|h| {
2163 let mut v = h.get();
2164 v[shape] += 1;
2165 h.set(v);
2166 });
2167 }
2168 return Ok(());
2169 }
2170 crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
2171 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
2172 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
2173 // own, so a cross-decoder bisection could only see the block's first
2174 // coefficient. Same names/format as [`read_tx_size`]'s rung.
2175 let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
2176 if step_trace {
2177 eprintln!(
2178 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
2179 dec.debug_state().0
2180 );
2181 }
2182 if mode >= 13 {
2183 return Err(unsupported(
2184 "an intra mode this decoder does not code (round 2)",
2185 ));
2186 }
2187 // lane-angleinter (merged on main for the square intra-in-inter arm):
2188 // the delta is read off `angle_delta_cdf[mode - V_PRED]` and feeds the
2189 // directional predictor; this arm refused a nonzero one before the merge.
2190 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
2191 read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED])
2192 } else {
2193 0
2194 };
2195 if angle_delta_y != 0 {
2196 hit!(INTRA_IN_INTER_ANGLE_DELTA_Y_HITS);
2197 }
2198 // `is_cfl_allowed` (spec 5.11.5) caps CFL at 32x32, so the
2199 // superblock-level strip reads the no-CFL alphabet -- the same split
2200 // [`read_intra_mode_rect`] makes for [`decode_block_rect64`].
2201 //
2202 // lane-av1mono: a monochrome strip codes no chroma mode/CFL symbol
2203 // (libaom `decodemv.c:933`).
2204 let has_chroma = !mono(fctx);
2205 let cfl_allowed = has_chroma && cfl_allowed_px(bw, bh, fctx);
2206 let uv_mode = if !has_chroma {
2207 DC_PRED
2208 } else if cfl_allowed {
2209 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
2210 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
2211 } else {
2212 crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
2213 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
2214 };
2215 if step_trace {
2216 eprintln!(
2217 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
2218 u8::from(cfl_allowed),
2219 dec.debug_state().0
2220 );
2221 }
2222 if (9..=12).contains(&uv_mode) {
2223 hit!(SMOOTH_UV_HITS);
2224 }
2225 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
2226 Some(read_cfl_alphas(dec, cdfs))
2227 } else {
2228 None
2229 };
2230 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
2231 DC_PRED
2232 } else {
2233 uv_mode
2234 };
2235 let angle_delta_uv = if (V_PRED..=D67_PRED).contains(&uv_mode) {
2236 hit!(DIRECTIONAL_UV_HITS);
2237 read_angle_delta(dec, &mut cdfs.angle_delta[uv_mode - V_PRED])
2238 } else {
2239 0
2240 };
2241 if angle_delta_uv != 0 {
2242 hit!(UV_ANGLE_DELTA_HITS);
2243 hit!(INTRA_IN_INTER_ANGLE_DELTA_UV_HITS);
2244 }
2245 // `read_palette_mode_info` (spec 5.11.13), in the position
2246 // `read_intra_block_mode_info` writes it: after the chroma mode and
2247 // before `filter_intra`. lane-t900 r21: a `--tune-content=screen` inter
2248 // frame writes `palette_y_mode`/`palette_uv_mode` for every block whose
2249 // shape [`palette_bsize_ctx_wh`] admits, intra strips included, so
2250 // skipping the syntax here desynced the tile at the strip's own symbol.
2251 // lane-t900 r22: reconstructed, not refused -- the strip's real mode
2252 // context and colour cache at its own mi position, and the two
2253 // colour-index maps decoded after `filter_intra` (`av1_visit_palette`),
2254 // exactly as [`read_intra_mode_rect`] does on the key-frame path.
2255 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi((mi_r, mi_c));
2256 let palette_uv_cache = neighbours.palette_uv_cache_mi((mi_r, mi_c));
2257 let mut palette_y_pending: Option<(usize, [u16; 8])> = None;
2258 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
2259 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx_wh(bw, bh) {
2260 hit!(INTRA_RECT_IN_INTER_SCREEN_HITS);
2261 let use_palette_y =
2262 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][palette_ctx]) != 0;
2263 if use_palette_y {
2264 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
2265 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
2266 }
2267 // A 2:1 strip of at least 8x8 is always a chroma reference, so
2268 // `read_palette_mode_info`'s `xd->is_chroma_ref` guard holds here.
2269 // lane-av1mono: libaom's actual guard is `num_planes > 1 &&
2270 // uv_mode == UV_DC_PRED && xd->is_chroma_ref` (decodemv.c:602).
2271 let use_palette_uv = has_chroma
2272 && uv_mode == DC_PRED
2273 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
2274 if crate::envflags::env_flag!("EC_PALSYN") {
2275 eprintln!(
2276 "EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}",
2277 use_palette_y as i32,
2278 use_palette_uv as i32,
2279 dec.debug_state().0
2280 );
2281 }
2282 if use_palette_uv {
2283 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
2284 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
2285 palette_uv_pending = Some((n, u_colors, v_colors));
2286 }
2287 }
2288 // lane-fiinter (merged on main for the square intra-in-inter arm):
2289 // `read_filter_intra_mode_info` is the tail of
2290 // `read_intra_block_mode_info`, after the palette syntax (refused whole
2291 // above for this shape), and `av1_filter_intra_allowed_bsize` admits the
2292 // 2:1 strips with both sides <= 32 -- their own CDF rows
2293 // ([`filter_intra_size_class_rect`]).
2294 let mut filter_intra = None;
2295 if mode == DC_PRED
2296 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
2297 // `av1_filter_intra_allowed` excludes a palette-Y block.
2298 && palette_y_pending.is_none()
2299 && let Some(class) = filter_intra_size_class_rect(bw, bh)
2300 && dec.symbol(&mut cdfs.filter_intra[class]) != 0
2301 {
2302 hit!(FILTER_INTRA_HITS);
2303 hit!(INTRA_IN_INTER_FILTER_INTRA_HITS);
2304 filter_intra = Some(dec.symbol(&mut cdfs.filter_intra_mode));
2305 }
2306 // `av1_visit_palette`: Y's colour-index map then the shared chroma one.
2307 let palette_y = palette_y_pending.map(|(n, colors)| {
2308 let map = decode_color_index_map_wh(
2309 dec,
2310 cdfs,
2311 n,
2312 bw,
2313 bh,
2314 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
2315 false,
2316 );
2317 hit!(PALETTE_HITS);
2318 hit!(PALETTE_RECT_HITS);
2319 hit!(INTRA_IN_INTER_PALETTE_Y_HITS);
2320 PaletteY {
2321 size: n,
2322 colors,
2323 map,
2324 }
2325 });
2326 let palette_uv = palette_uv_pending.map(|(n, u_colors, v_colors)| {
2327 let (cw, ch) = ((bw >> ss_x(fctx)).max(4), (bh >> ss_y(fctx)).max(4));
2328 let on = palette_onscreen_uv(
2329 (bw, bh),
2330 palette_onscreen(mi_r, mi_c, bw, bh, fctx),
2331 (cw, ch),
2332 (ss_x(fctx), ss_y(fctx)),
2333 );
2334 let map = decode_color_index_map_wh(dec, cdfs, n, cw, ch, on, true);
2335 hit!(PALETTE_UV_HITS);
2336 hit!(INTRA_IN_INTER_PALETTE_UV_HITS);
2337 PaletteUv {
2338 size: n,
2339 u_colors,
2340 v_colors,
2341 map,
2342 }
2343 });
2344 // The intra-edge filter type is the NEIGHBOUR's mode (libaom
2345 // `get_filt_type`), luma's off the luma neighbours and chroma's off the
2346 // chroma ones -- [`decode_block_rect`]'s own pair.
2347 // lane-t900 r4: the coarse pair is keyed on the 16x16 cell's OWN top-left
2348 // mi, so both 8x16 halves of a VERT split read the neighbours of the FIRST
2349 // half. libaom's `above_mbmi`/`left_mbmi` are this block's own
2350 // (`mi[-mi_stride]` / `mi[-1]`) -- take the mi-exact pair over the coarse
2351 // one exactly as [`decode_leaf8`] already does (class
2352 // context-read-from-one-cell).
2353 let coarse_pair = neighbours.modes_above_left(r, c);
2354 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left_mi(mi_r, mi_c, coarse_pair);
2355 if (nb_above_mode, nb_left_mode) != coarse_pair {
2356 hit!(EDGE_FILTER_MI_FIX_HITS);
2357 }
2358 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
2359 if smooth_neighbor {
2360 hit!(SMOOTH_LUMA_HITS);
2361 }
2362 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(mi_r, mi_c, r, c, fctx);
2363 // lane-av1mixloss: the lossless-segment early return (`decodeframe.c:1203`)
2364 // precedes `TX_MODE_SELECT`, so a lossless-segment intra-rect block inside
2365 // an inter frame codes no depth symbol either (`xd->lossless` is per
2366 // segment regardless of frame type; class sweep of the sub8 leaf's fix).
2367 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) {
2368 // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`].
2369 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
2370 let d = match tx_cat {
2371 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
2372 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
2373 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
2374 };
2375 if step_trace {
2376 eprintln!(
2377 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
2378 dec.debug_state().0
2379 );
2380 }
2381 d
2382 } else {
2383 0
2384 };
2385 if depth != 0 || lossless(fctx) {
2386 hit!(TX_DEPTH_HITS);
2387 // lane-intrasplit r1: a split intra strip in an inter frame walks the
2388 // key frame's own per-TU path ([`decode_rect_split`] below); what was
2389 // wrong when this refusal was written was the depth SYMBOL, not the walk.
2390 hit_do! {
2391 INTRA_RECT_IN_INTER_SPLIT_TX_HITS.with(|h| {
2392 let mut v = h.get();
2393 v[depth.min(2)] += 1;
2394 h.set(v);
2395 });
2396 }
2397 }
2398 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
2399 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
2400 // the two are indistinguishable when the diagnostic fires on splits alone.
2401 if crate::envflags::env_flag!("EC_SPLITSTRIP") {
2402 eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
2403 }
2404 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
2405 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
2406 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
2407 // of an inter frame, intra ones included -- with the skip term 0 it
2408 // memsets `above_txfm_context` to `tx_size_wide` over the block's width
2409 // and `left_txfm_context` to `tx_size_high` over its height. This strip
2410 // wrote neither, so the next block's var-tx `txfm_partition` context read
2411 // a stale band: on a 192x128 8-bit stream the 16x8 intra strip at
2412 // mi(14,0) left 8 where libaom has 16, giving ctx 13 instead of 12 at
2413 // mi(16,0) and desyncing the tile at that symbol.
2414 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
2415 let modes = RectStripModes {
2416 skip,
2417 mode,
2418 angle_delta_y,
2419 uv_predict_mode,
2420 angle_delta_uv,
2421 alpha,
2422 filter_intra,
2423 smooth_neighbor,
2424 smooth_neighbor_uv,
2425 palette_y: palette_y
2426 .as_ref()
2427 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
2428 palette_uv: palette_uv.as_ref().map(|p| {
2429 (
2430 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
2431 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
2432 )
2433 }),
2434 };
2435 decode_rect_split(
2436 dec,
2437 cdfs,
2438 neighbours,
2439 (mi_r, mi_c),
2440 bw,
2441 bh,
2442 tx_w,
2443 tx_h,
2444 &modes,
2445 y,
2446 u,
2447 v,
2448 base_q_idx,
2449 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
2450 fctx,
2451 )?;
2452 // `set_txfm_ctxs` (libaom `decodeframe.c:1078`, at the end of
2453 // `decode_token_recon_block`): an INTRA block records its TRANSFORM size in
2454 // both `TXFM_CONTEXT` bands -- the above row over the block's width, the
2455 // left column over its height. This arm wrote neither before lane-intrasplit
2456 // r1, so every later block in the frame read a stale `tx_size`/`txfm_split`
2457 // context across the strip's footprint.
2458 for i in 0..bw / MI {
2459 if let Some(cell) = neighbours.above_txfm.get_mut(mi_c + i) {
2460 *cell = tx_w as u8;
2461 }
2462 }
2463 for i in 0..bh / MI {
2464 if let Some(cell) = neighbours.left_txfm.get_mut(mi_r + i) {
2465 *cell = tx_h as u8;
2466 }
2467 }
2468 // The strip's own palette state into the mi-granular neighbour bands, so
2469 // the next block's colour cache and `palette_y_mode` context are libaom's.
2470 record_strip_palette(
2471 neighbours,
2472 (mi_r, mi_c),
2473 bw,
2474 bh,
2475 palette_y.as_ref().map_or(0, |p| p.size),
2476 palette_y.as_ref().map_or([0u16; 8], |p| p.colors),
2477 palette_uv.as_ref().map_or(0, |p| p.size),
2478 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
2479 );
2480 let class = match bw.max(bh) {
2481 64 => 0,
2482 32 => 1,
2483 _ => 2,
2484 };
2485 hit_do! {
2486 INTRA_RECT_IN_INTER_HITS.with(|h| {
2487 let mut v = h.get();
2488 v[class] += 1;
2489 h.set(v);
2490 });
2491 }
2492 Ok(())
2493}
2494
2495/// Reconstructs one rectangular INTRABC block, `bw`x`bh` pixels at the real
2496/// mi `(mi_r, mi_c)` (lane-av1-intrabc).
2497///
2498/// libaom treats an intrabc block as INTER for everything except the mode-info
2499/// read itself: `is_inter_block` is `is_intrabc_block(mbmi) || ref > INTRA`
2500/// (`blockd.h:373`), so
2501///
2502/// * `parse_decode_block` reads the transform size through the INTER var-tx
2503/// tree (`read_tx_size_vartx`) -- [`read_block_tx_size_rect`], whose
2504/// `txfm_partition` context comes off the real `TXFM_CONTEXT` bands and
2505/// whose leaves publish their own resolved size back;
2506/// * `predict_inter_block` predicts the WHOLE block once, from the CURRENT
2507/// frame's own pre-loop-filter reconstruction, at the coded block vector
2508/// with the BILINEAR kernel `read_intrabc_info` forces (`decodemv.c:913`);
2509/// * `decode_token_recon_block`'s inter branch then reads one residual per
2510/// transform unit, through the INTER coefficient sets
2511/// ([`read_inter_plane_rect`]/[`read_inter_plane`]) with the chroma plane
2512/// inheriting the colocated luma unit's coded `tx_type`.
2513///
2514/// Text order is libaom's: transform tree, prediction, luma residual, chroma
2515/// residual, bookkeeping. A skipped block codes no residual at all -- the
2516/// prediction is the reconstruction.
2517#[allow(clippy::too_many_arguments)]
2518pub(super) fn decode_intrabc_rect(
2519 dec: &mut SymbolDecoder,
2520 cdfs: &mut Cdfs,
2521 neighbours: &mut Neighbours,
2522 (mi_r, mi_c): (usize, usize),
2523 (bw, bh): (usize, usize),
2524 skip: bool,
2525 (dv_row, dv_col): (i32, i32),
2526 y: &mut PlaneBuf<'static>,
2527 u: &mut PlaneBuf<'static>,
2528 v: &mut PlaneBuf<'static>,
2529 base_q_idx: u8,
2530 fctx: &crate::decode::FrameCtx,
2531) -> Result<()> {
2532 hit!(INTRABC_RECT_HITS);
2533 // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`.
2534 let idx = usize::from(bh > bw);
2535 if skip {
2536 INTRABC_RECT_SKIPPED_HITS.with(|c| {
2537 let mut seen = c.get();
2538 seen[idx] += 1;
2539 c.set(seen);
2540 });
2541 } else {
2542 INTRABC_RECT_CODED_HITS.with(|c| {
2543 let mut seen = c.get();
2544 seen[idx] += 1;
2545 c.set(seen);
2546 });
2547 }
2548 let (px, py) = (mi_c * MI, mi_r * MI);
2549 // lane-whtshape: a LOSSLESS block's chroma plane block is
2550 // `bw >> ss_x` by `bh >> ss_y` at its own origin -- `av1_get_max_uv_txsize`
2551 // is `ss_size_lookup[bsize]` (no halving of its own), so at 4:4:4 that is
2552 // the block's OWN footprint, not the 4:2:0 halving the lossy arm hard-codes.
2553 // Measured on this lane's 4:4:4 lossless witness: with the halving, a
2554 // 16x8 intrabc block's chroma plane block came out 8x4 and the lossless
2555 // walk below coded 2 units per plane where libaom codes 8.
2556 //
2557 // lane-ibc444c: UNSCOPED now. lane-whtshape split this on `lossless` and
2558 // named the LOSSY 4:4:4 footprint as another lane's open cell; this is
2559 // that cell. Measured on `444_intrabc_rect4_witness.obu`: with the
2560 // halving, an 8x16 luma block's 8x16 chroma plane block was read as ONE
2561 // 4x8 rect unit where libaom codes ONE TX_8X16, and the U `txb_skip` of
2562 // the block at mi (92, 104) read all_zero=0 here against the oracle's
2563 // all_zero=1 -- the bit position forks there. Identical arithmetic at
2564 // 4:2:0, where `ss_x = ss_y = 1`, so the pinned 4:2:0 twin of the
2565 // witness is the identity arm of this lane's gate.
2566 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
2567 // `av1_get_max_uv_txsize(bw x bh)`: 4:2:0 halves the footprint and the
2568 // halved shape's own `max_txsize_rect_lookup` entry IS that size for every
2569 // shape this helper is called at, so the uv plane block is ONE unit --
2570 // the same call `decode_token_recon_block`'s own chroma loop makes.
2571 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
2572 // lane-av1-intrabc r2: the square stride the proven INTER path uses
2573 // (`side`). The residual grids, the prediction windows AND
2574 // `TxParams::stride` are all laid out at it -- the block's own width
2575 // panicked `TxParams::run` on every coded VERT strip (8x16/16x32: `h`
2576 // exceeds the stride).
2577 let side = bw.max(bh);
2578 let cside = cw.max(ch);
2579 // `av1_calc_mi_size`'s 8-px-aligned grid: a block hanging over the right
2580 // or bottom frame edge reads no transform-tree symbol for the units
2581 // outside it.
2582 let mi_cols = 2 * y.true_width.div_ceil(8);
2583 let mi_rows = 2 * y.true_height.div_ceil(8);
2584 let leaves = read_block_tx_size_rect(
2585 dec,
2586 cdfs,
2587 neighbours,
2588 (mi_r, mi_c),
2589 (bw, bh),
2590 (mi_cols, mi_rows),
2591 skip,
2592 fctx,
2593 )?;
2594 if leaves.is_some() {
2595 hit!(INTRABC_RECT_VARTX_HITS);
2596 }
2597 if ss_x(fctx) == 0 && ss_y(fctx) == 0 {
2598 hit!(IBC_RECT_CHROMA_FOOTPRINT_444_HITS);
2599 }
2600 // lane-ibc444c: per-block geometry, for the chroma-tail attribution.
2601 if crate::envflags::env_flag!("EC_IBCBLOCK") {
2602 eprintln!(
2603 "EC_IBCBLOCK mi=({mi_r},{mi_c}) bw={bw} bh={bh} cpx={cpx} cpy={cpy} \
2604 cw={cw} ch={ch} cside={cside} skip={skip}"
2605 );
2606 }
2607 // The whole-block prediction: `predict_inter_block` runs once, before any
2608 // coefficient is read. The source is this frame's own reconstruction,
2609 // which is already written.
2610 // `mc::predict_with_filter` writes a DENSE window; the residual machinery
2611 // reads it at the square stride, so re-lay it -- the same step the inter
2612 // path takes for its own square prediction buffer.
2613 let mut pred_y_dense = vec![0u16; bw * bh];
2614 mc::predict_with_filter(
2615 &y.data,
2616 y.width,
2617 y.true_width,
2618 y.true_height,
2619 mv_to_q4(px, dv_col, 0),
2620 mv_to_q4(py, dv_row, 0),
2621 bw,
2622 bh,
2623 mc::InterpFilterKind::Bilinear,
2624 &mut pred_y_dense,
2625 fctx,
2626 );
2627 let mut pred_y = vec![0u16; side * side];
2628 for row in 0..bh {
2629 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
2630 }
2631 let mut pred_u_dense = vec![0u16; cw * ch];
2632 mc::predict_with_filter(
2633 &u.data,
2634 u.width,
2635 u.true_width,
2636 u.true_height,
2637 mv_to_q4(cpx, dv_col, ss_x(fctx)),
2638 mv_to_q4(cpy, dv_row, ss_y(fctx)),
2639 cw,
2640 ch,
2641 mc::InterpFilterKind::Bilinear,
2642 &mut pred_u_dense,
2643 fctx,
2644 );
2645 let mut pred_u = vec![0u16; cside * cside];
2646 for row in 0..ch {
2647 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
2648 }
2649 let mut pred_v_dense = vec![0u16; cw * ch];
2650 mc::predict_with_filter(
2651 &v.data,
2652 v.width,
2653 v.true_width,
2654 v.true_height,
2655 mv_to_q4(cpx, dv_col, ss_x(fctx)),
2656 mv_to_q4(cpy, dv_row, ss_y(fctx)),
2657 cw,
2658 ch,
2659 mc::InterpFilterKind::Bilinear,
2660 &mut pred_v_dense,
2661 fctx,
2662 );
2663 let mut pred_v = vec![0u16; cside * cside];
2664 for row in 0..ch {
2665 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
2666 }
2667 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
2668 let luma_tx_type: TxType;
2669 let (luma_grid, u_grid, v_grid);
2670 // lane-whtshape: the LOSSLESS chroma walk's composed plane-major grids,
2671 // kept so their per-4x4 slices can be re-stamped over the whole-block
2672 // record in the tail. `None` on every other arm.
2673 let mut ll_chroma: Option<(Vec<i32>, Vec<i32>)> = None;
2674 if skip {
2675 // No residual syntax at all: the prediction IS the block.
2676 // Residual stride is `side` (and `cside`), not `bw`: reconstruct_mc_rect indexes
2677 // `residual[row * side .. row*side + w]` for row in 0..h, so a skipped VERT strip
2678 // (bh > bw) overruns a `bw * bh` slice. Bug-for-bug with the inter skip arm.
2679 push_mc_rect(
2680 y,
2681 u,
2682 v,
2683 0,
2684 px,
2685 py,
2686 side,
2687 bw,
2688 bh,
2689 Pred::Inline(&pred_y, side),
2690 &ZERO_RESIDUAL[..side * side],
2691 fctx,
2692 );
2693 push_mc_rect(
2694 y,
2695 u,
2696 v,
2697 1,
2698 cpx,
2699 cpy,
2700 cside,
2701 cw,
2702 ch,
2703 Pred::Inline(&pred_u, cside),
2704 &ZERO_RESIDUAL[..cside * cside],
2705 fctx,
2706 );
2707 push_mc_rect(
2708 y,
2709 u,
2710 v,
2711 2,
2712 cpx,
2713 cpy,
2714 cside,
2715 cw,
2716 ch,
2717 Pred::Inline(&pred_v, cside),
2718 &ZERO_RESIDUAL[..cside * cside],
2719 fctx,
2720 );
2721 if let Some(ls) = leaves.as_ref() {
2722 // lane-av1-loss64, merged: the same reset [`decode_intrabc_owned_rect`]'s
2723 // skip arm performs -- libaom `av1_reset_entropy_context`
2724 // (`if (mbmi->skip_txfm)`, decodeframe.c:1262 -> blockd.c:58): a
2725 // SKIPPED block zeroes its whole entropy-band footprint. This
2726 // helper serves `decode_block_rect4`'s 1:4 strips on this tree,
2727 // so a skipped lossless strip whose `leaves` resolved (every
2728 // lossless frame -- `read_block_tx_size_rect`'s lossless arm
2729 // returns the 4x4 grid before it looks at `skip`) left the
2730 // PREVIOUS occupant's luma bands standing and the NEXT block's
2731 // partition parse diverged from libaom's: the 320x242 lossless
2732 // sb128 gate read a phantom unskipped 8x32 intrabc strip at
2733 // mi(56,66) right after the skipped 8x16 one at mi(48,66).
2734 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
2735 for &(row, col, tw, th) in ls {
2736 neighbours.record_mi_luma_rect(
2737 (mi_r + row, mi_c + col),
2738 tw,
2739 th,
2740 &ZERO_RESIDUAL[..tw * th],
2741 );
2742 }
2743 }
2744 luma_tx_type = TxType::DctDct;
2745 luma_grid = Grid::Zero(side * side);
2746 u_grid = Grid::Zero(cside * cside);
2747 v_grid = Grid::Zero(cside * cside);
2748 } else {
2749 match leaves.as_ref() {
2750 None => {
2751 // One whole-block rectangular transform unit.
2752 // lane-av1422mi24: at ss (1,0) the chroma above span is
2753 // `bw >> 1` chroma cells spread over `bw` luma mi columns --
2754 // the per-mi gather counts every chroma column's whole-unit
2755 // dc sign twice (t422 frame 1, the mi(26,60) intra-in-inter
2756 // strip's U dc_sign read ctx 1 where the oracle's cell sum
2757 // is 0 -> ctx 0). Luma keeps the per-mi gather; the two
2758 // chroma planes take
2759 // [`Neighbours::around_mi_422_chroma`]'s every-second
2760 // above-cell sampling, like every other 4:2:2 chroma gather.
2761 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
2762 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
2763 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
2764 around[1] = c[1];
2765 around[2] = c[2];
2766 }
2767 let (grid, tx_type) = read_inter_plane_rect(
2768 dec,
2769 cdfs,
2770 rect_inter_luma_set(bw, bh, fctx)?,
2771 (bw, bh),
2772 side,
2773 0,
2774 around[0],
2775 0,
2776 y,
2777 u,
2778 v,
2779 px,
2780 py,
2781 Pred::Inline(&pred_y, side),
2782 None,
2783 None,
2784 fctx,
2785 )?;
2786 luma_tx_type = tx_type;
2787 luma_grid = embed_grid_stride(&grid, bw, bh, side);
2788 let (ug, _) = read_inter_plane_rect(
2789 dec,
2790 cdfs,
2791 rect_inter_chroma_set(cw, ch)?,
2792 (cw, ch),
2793 cside,
2794 1,
2795 around[1],
2796 0,
2797 y,
2798 u,
2799 v,
2800 cpx,
2801 cpy,
2802 Pred::Inline(&pred_u, cside),
2803 Some(luma_tx_type),
2804 None,
2805 fctx,
2806 )?;
2807 u_grid = embed_grid_stride(&ug, cw, ch, cside);
2808 let (vg, _) = read_inter_plane_rect(
2809 dec,
2810 cdfs,
2811 rect_inter_chroma_set(cw, ch)?,
2812 (cw, ch),
2813 cside,
2814 2,
2815 around[2],
2816 0,
2817 y,
2818 u,
2819 v,
2820 cpx,
2821 cpy,
2822 Pred::Inline(&pred_v, cside),
2823 Some(luma_tx_type),
2824 None,
2825 fctx,
2826 )?;
2827 v_grid = embed_grid_stride(&vg, cw, ch, cside);
2828 }
2829 Some(leaves) => {
2830 // P2 (lane-av1-intrabc r2): libaom `get_transform_size` applies
2831 // the split override to LUMA only, per leaf -- the step the
2832 // proven inter var-tx path applies right after its own residual
2833 // loop ([`Neighbours::fill_lf_grid_leaf_luma`]). Without it the
2834 // leaf's own transform edges are never filtered.
2835 for &(row, col, tw, th) in leaves.iter() {
2836 neighbours.fill_lf_grid_leaf_luma(
2837 (mi_r + row, mi_c + col),
2838 tw / MI,
2839 th / MI,
2840 tw as u8,
2841 th as u8,
2842 );
2843 }
2844 // One residual per transform unit, in the order the tree coded
2845 // them; each unit reads its own neighbour-magnitude context off
2846 // the units already decoded before it, and every unit adds onto
2847 // its own window of the block's single prediction.
2848 let mut first_tx_type = TxType::DctDct;
2849 for (idx, &(row, col, tw, th)) in leaves.iter().enumerate() {
2850 let tu_mi = (mi_r + row, mi_c + col);
2851 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
2852 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
2853 let (tu_grid, tu_tx_type) = if tw == th {
2854 let scan = default_scan(tw.min(32));
2855 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
2856 read_inter_plane(
2857 dec,
2858 cdfs,
2859 inter_txbset_for(tw, reduced),
2860 scan,
2861 0,
2862 neighbours.around_mi(tu_mi, tw)[0],
2863 0,
2864 y,
2865 u,
2866 v,
2867 tu_px,
2868 tu_py,
2869 tw,
2870 base_q_idx,
2871 tu_pred,
2872 None,
2873 Some(tu_skip_ctx),
2874 fctx,
2875 )?
2876 } else {
2877 let tu_skip_ctx = neighbours.luma_skip_ctx_rect(tu_mi, tw / MI, th / MI);
2878 read_inter_plane_rect(
2879 dec,
2880 cdfs,
2881 rect_inter_luma_set(tw, th, fctx)?,
2882 (tw, th),
2883 side,
2884 0,
2885 neighbours.around_mi_rect(tu_mi, tw, th)[0],
2886 0,
2887 y,
2888 u,
2889 v,
2890 tu_px,
2891 tu_py,
2892 tu_pred,
2893 None,
2894 Some(tu_skip_ctx),
2895 fctx,
2896 )?
2897 };
2898 if idx == 0 {
2899 first_tx_type = tu_tx_type;
2900 }
2901 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
2902 }
2903 // `av1_get_tx_type`'s chroma lookup lands on the colocated
2904 // LUMA unit, which for a split block is the top-left one.
2905 luma_tx_type = first_tx_type;
2906 // lane-av1422mi24: same 4:2:2 chroma gather rule as the
2907 // `None` arm above -- the per-mi rect gather double-counts
2908 // each chroma column's whole-unit dc sign at ss (1,0).
2909 let mut around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh);
2910 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
2911 let c = neighbours.around_mi_422_chroma((mi_r, mi_c), bw, bh);
2912 around[1] = c[1];
2913 around[2] = c[2];
2914 }
2915 if lossless(fctx) {
2916 // lane-whtshape: at lossless libaom codes TX_4X4 on EVERY
2917 // plane of a block -- `read_tx_size` returns `TX_4X4` for a
2918 // lossless block before it looks at a tree, `read_tx_mode`
2919 // already forced `ONLY_4X4` for the frame, and
2920 // `get_vartx_max_txsize` returns `TX_4X4` for every plane
2921 // -- so this block's chroma plane block is a
2922 // `(cw/4) * (ch/4)` raster of 4x4 units, PLANE-MAJOR
2923 // (`decode_token_recon_block`: every U unit, then every V
2924 // unit), not the single rect unit the two
2925 // `read_inter_plane_rect` calls below read. That single
2926 // 8x4 unit is what reached the lossless WHT with the wrong
2927 // shape (the `debug_assert_eq!((w, h), (4, 4))` this lane
2928 // replaced). Same helper, same walk, as the inter 8x8 and
2929 // 128 paths.
2930 hit!(INTRABC_RECT_LOSSLESS_CHROMA4_HITS);
2931 let mut uo = vec![0i32; cside * cside];
2932 let mut vo = vec![0i32; cside * cside];
2933 read_inter_chroma_lossless(
2934 y,
2935 u,
2936 v,
2937 dec,
2938 cdfs,
2939 neighbours,
2940 Pred::Inline(&pred_u, cside),
2941 Pred::Inline(&pred_v, cside),
2942 (mi_r, mi_c),
2943 (cpx, cpy),
2944 (0, 0),
2945 (cw, ch),
2946 (cw, ch),
2947 cside,
2948 0,
2949 base_q_idx,
2950 &mut uo,
2951 &mut vo,
2952 fctx,
2953 )?;
2954 // The per-unit walk stamped every unit's own coefficient
2955 // context, but the whole-block `record_split_luma_rect_mi`
2956 // in the tail rewrites every chroma cell with ONE composed
2957 // state, which drops the per-unit DC signs and levels (class
2958 // `override-slot-on-one-arm` -- the same one
2959 // `decode_rect_split`'s `ll_chroma_units` replay exists
2960 // for). The grids are kept here and replayed AFTER that
2961 // record, from the same 4x4 slices, so the same states.
2962 u_grid = embed_grid_stride(&Grid::Own(uo.clone()), cw, ch, cside);
2963 v_grid = embed_grid_stride(&Grid::Own(vo.clone()), cw, ch, cside);
2964 ll_chroma = Some((uo, vo));
2965 luma_grid = Grid::Zero(side * side);
2966 } else {
2967 let (ug, _) = read_inter_plane_rect(
2968 dec,
2969 cdfs,
2970 rect_inter_chroma_set(cw, ch)?,
2971 (cw, ch),
2972 cside,
2973 1,
2974 around[1],
2975 0,
2976 y,
2977 u,
2978 v,
2979 cpx,
2980 cpy,
2981 Pred::Inline(&pred_u, cside),
2982 Some(luma_tx_type),
2983 None,
2984 fctx,
2985 )?;
2986 u_grid = embed_grid_stride(&ug, cw, ch, cside);
2987 let (vg, _) = read_inter_plane_rect(
2988 dec,
2989 cdfs,
2990 rect_inter_chroma_set(cw, ch)?,
2991 (cw, ch),
2992 cside,
2993 2,
2994 around[2],
2995 0,
2996 y,
2997 u,
2998 v,
2999 cpx,
3000 cpy,
3001 Pred::Inline(&pred_v, cside),
3002 Some(luma_tx_type),
3003 None,
3004 fctx,
3005 )?;
3006 v_grid = embed_grid_stride(&vg, cw, ch, cside);
3007 luma_grid = Grid::Zero(side * side);
3008 }
3009 }
3010 }
3011 }
3012 let _ = luma_tx_type;
3013 // Bookkeeping. An intrabc block publishes mode `DC_PRED` everywhere the
3014 // next block reads a neighbour mode, its own block size in both `TXFM`
3015 // bands (already done by `read_block_tx_size_rect`), a zeroed palette
3016 // state (a stale entry would feed the next block's colour cache), and its
3017 // DV into the intrabc mi grid the next block's DV predictor reads.
3018 if leaves.is_some() {
3019 neighbours.record_split_luma_rect_mi(
3020 (mi_r, mi_c),
3021 bw,
3022 bh,
3023 DC_PRED,
3024 DC_PRED,
3025 [&u_grid, &v_grid],
3026 );
3027 } else {
3028 neighbours.record_rect_mi(
3029 (mi_r, mi_c),
3030 bw,
3031 bh,
3032 DC_PRED,
3033 DC_PRED,
3034 &[&luma_grid, &u_grid, &v_grid],
3035 );
3036 }
3037 // lane-whtshape: replay the LOSSLESS walk's per-4x4 chroma states over
3038 // the whole-block record above, so the NEXT block reads the per-unit DC
3039 // signs and levels libaom's plane-major walk left behind instead of one
3040 // composed state for the whole plane block.
3041 if let Some((uo, vo)) = ll_chroma {
3042 for (plane_idx, comp) in [(1usize, &uo), (2, &vo)] {
3043 for ur in 0..ch / 4 {
3044 for uc in 0..cw / 4 {
3045 let mut unit = Vec::with_capacity(16);
3046 for r in 0..4 {
3047 unit.extend_from_slice(&comp[(ur * 4 + r) * cside + uc * 4..][..4]);
3048 }
3049 neighbours.record_mi_chroma(
3050 // lane-av1lm444loss-corr: the MI STEP between chroma
3051 // units is that same footprint expressed in luma mi
3052 // cells, `(4 << ss) / MI` -- which is exactly what
3053 // `decode_inter_block`'s reference `mu_chroma_units`
3054 // construction writes (decode.rs:43688,
3055 // `at.0 + cr * ((cu << ss_y(fctx)) / MI)` with
3056 // `cu = 4` on a lossless frame). The `4 >> ss_y` form
3057 // this replaces is 4:2:0-only arithmetic that happens
3058 // to agree there: at ss (1,1) it is `4 >> 1` = 2 mi
3059 // and the footprint form is `(4 << 1) / 4` = 2 mi, the
3060 // SAME value, so 4:2:0 is unchanged by construction.
3061 // At ss (0,0) it is `4 >> 0` = 4 mi -- four luma mi
3062 // (16 luma px) per 4x4 chroma unit, where a TX_4X4
3063 // chroma unit covers `4 << 0` = 4 luma px = ONE mi.
3064 // The step therefore lands every replayed unit at 4x
3065 // its own mi row/column on a 4:4:4 lossless frame, and
3066 // the whole block's per-unit states are stamped over
3067 // cells that belong to other blocks (or to nothing).
3068 (
3069 mi_r + ur * ((4 << ss_y(fctx)) / MI),
3070 mi_c + uc * ((4 << ss_x(fctx)) / MI),
3071 ),
3072 4 << ss_x(fctx),
3073 4 << ss_y(fctx),
3074 plane_idx,
3075 &Grid::Own(unit),
3076 );
3077 }
3078 }
3079 }
3080 }
3081 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
3082 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
3083 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
3084 // lane-av1oddheightfork3: `read_block_tx_size_rect` ran above, so the
3085 // bands are the tree's own per-leaf publication (libaom's var-tx branch
3086 // never calls `set_txfm_ctxs`) -- publishing the block's own size over
3087 // them here is the defect this call site carried.
3088 neighbours.fill_lf_grid_rect_after_vartx(
3089 (mi_r, mi_c),
3090 bw / MI,
3091 bh / MI,
3092 bw.min(64) as u8,
3093 bh.min(64) as u8,
3094 0,
3095 fctx,
3096 );
3097 record_intrabc_mi_rect(
3098 mi_r,
3099 mi_c,
3100 bw / MI,
3101 bh / MI,
3102 Some((dv_row, dv_col)),
3103 neighbours,
3104 fctx,
3105 );
3106 Ok(())
3107}
3108
3109/// lane-av1-ibcrect: reconstruction for a `use_intrabc` block on a 128-root
3110/// HORZ/VERT strip (`BLOCK_128X64` / `BLOCK_64X128`) -- the shape
3111/// `decode_block_128rect` refused by name before this port. libaom decodes
3112/// such a block through the INTER machinery (an intrabc block
3113/// `is_inter_block`): `predict_inter_block` copies the whole block from this
3114/// frame's own reconstruction at the integer block vector once, then
3115/// `decode_token_recon_block`'s inter arm walks 64x64 "mu" chunks --
3116/// per chunk every plane, luma units at the block's own resolved transform
3117/// (`read_block_tx_size_rect`, TX_64X64 roots) and chroma at
3118/// `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32, one unit per plane per
3119/// chunk at 4:2:0. Chroma never codes its own `tx_type`; each unit inherits
3120/// the coded type of the luma leaf covering its quadrant (`av1_get_tx_type`,
3121/// blockd.h:1291). `mode`/`uv_mode` read as `DC_PRED`/`UV_DC_PRED` back in
3122/// [`read_intra_mode_rect`]; no palette/filter-intra/CFL symbol exists here.
3123#[allow(clippy::too_many_arguments)]
3124pub(super) fn decode_intrabc_128rect(
3125 dec: &mut SymbolDecoder,
3126 cdfs: &mut Cdfs,
3127 neighbours: &mut Neighbours,
3128 (mi_r, mi_c): (usize, usize),
3129 (bw, bh): (usize, usize),
3130 skip: bool,
3131 (dv_row, dv_col): (i32, i32),
3132 y: &mut PlaneBuf<'static>,
3133 u: &mut PlaneBuf<'static>,
3134 v: &mut PlaneBuf<'static>,
3135 base_q_idx: u8,
3136 fctx: &crate::decode::FrameCtx,
3137) -> Result<()> {
3138 hit!(INTRABC_128RECT_HITS);
3139 if crate::envflags::env_flag!("EC_AV1_TRACE") {
3140 let (rng, _) = dec.debug_state();
3141 eprintln!(
3142 "EC_IBC128 mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} skip={skip} dv=({dv_row},{dv_col}) rng={rng}"
3143 );
3144 }
3145 let (px, py) = (mi_c * MI, mi_r * MI);
3146 // lane-av1-ibc128chunk: the block's chroma PLANE BLOCK is per-axis
3147 // `(bw >> ss_x) x (bh >> ss_y)` -- 4:2:0 halves both (this fn's
3148 // `mv_to_q4(cpy, dv_row, ss_y(fctx))` calls two lines below already
3149 // scaled the DV on the y axis by ITS OWN subsampling, so the hardcoded
3150 // `/2` origin and extent made the prediction window half as tall as
3151 // the motion vector asked for), 4:2:2 is HALF-WIDTH and FULL-HEIGHT,
3152 // 4:4:4 is luma-sized. At ss (1,1) every value below is the old
3153 // `bw / 2, bh / 2` line-for-line.
3154 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
3155 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
3156 // The square strides the proven INTER path lays its residual grids,
3157 // prediction windows and `TxParams` at (see [`decode_intrabc_rect`]'s r2
3158 // note): 128/64 here.
3159 let side = bw.max(bh);
3160 let cside = cw.max(ch);
3161 // `av1_calc_mi_size`'s 8-px-aligned grid: units past the frame edge code
3162 // nothing (`decode_reconstruct_tx`'s max_blocks_* early return).
3163 let mi_cols = 2 * y.true_width.div_ceil(8);
3164 let mi_rows = 2 * y.true_height.div_ceil(8);
3165 // An intrabc block is is_inter_block: the tx tree is the INTER one, and
3166 // [`read_block_tx_size_rect`]'s 128-root branch already carries the
3167 // LARGEST (no symbol, two TX_64X64 units), TX_MODE_SELECT (var-tx tree
3168 // rooted at TX_64X64), skip (band stamp only) and lossless (TX_4X4 grid)
3169 // arms (lane-sb128c r7).
3170 let leaves = read_block_tx_size_rect(
3171 dec,
3172 cdfs,
3173 neighbours,
3174 (mi_r, mi_c),
3175 (bw, bh),
3176 (mi_cols, mi_rows),
3177 skip,
3178 fctx,
3179 )?;
3180 // Whole-block prediction, once, before any coefficient is read
3181 // (`predict_inter_block`); the source is this frame's own
3182 // reconstruction, including the writes this superblock has queued.
3183 let mut pred_y_dense = vec![0u16; bw * bh];
3184 mc::predict_with_filter(
3185 &y.data,
3186 y.width,
3187 y.true_width,
3188 y.true_height,
3189 mv_to_q4(px, dv_col, 0),
3190 mv_to_q4(py, dv_row, 0),
3191 bw,
3192 bh,
3193 mc::InterpFilterKind::Bilinear,
3194 &mut pred_y_dense,
3195 fctx,
3196 );
3197 let mut pred_y = vec![0u16; side * side];
3198 for row in 0..bh {
3199 pred_y[row * side..][..bw].copy_from_slice(&pred_y_dense[row * bw..][..bw]);
3200 }
3201 let mut pred_u_dense = vec![0u16; cw * ch];
3202 mc::predict_with_filter(
3203 &u.data,
3204 u.width,
3205 u.true_width,
3206 u.true_height,
3207 mv_to_q4(cpx, dv_col, ss_x(fctx)),
3208 mv_to_q4(cpy, dv_row, ss_y(fctx)),
3209 cw,
3210 ch,
3211 mc::InterpFilterKind::Bilinear,
3212 &mut pred_u_dense,
3213 fctx,
3214 );
3215 let mut pred_u = vec![0u16; cside * cside];
3216 for row in 0..ch {
3217 pred_u[row * cside..][..cw].copy_from_slice(&pred_u_dense[row * cw..][..cw]);
3218 }
3219 let mut pred_v_dense = vec![0u16; cw * ch];
3220 mc::predict_with_filter(
3221 &v.data,
3222 v.width,
3223 v.true_width,
3224 v.true_height,
3225 mv_to_q4(cpx, dv_col, ss_x(fctx)),
3226 mv_to_q4(cpy, dv_row, ss_y(fctx)),
3227 cw,
3228 ch,
3229 mc::InterpFilterKind::Bilinear,
3230 &mut pred_v_dense,
3231 fctx,
3232 );
3233 let mut pred_v = vec![0u16; cside * cside];
3234 for row in 0..ch {
3235 pred_v[row * cside..][..cw].copy_from_slice(&pred_v_dense[row * cw..][..cw]);
3236 }
3237 let (luma_grid, u_grid, v_grid);
3238 // lane-av1-ibcrect: whether the coded arm stamped its CHROMA neighbour
3239 // contexts per transform unit -- the replay after this fn's end-of-block
3240 // record restores them (the record itself re-stamps both planes with ONE
3241 // composed state, class `override-slot-on-one-arm`).
3242 let mut mu_chroma = false;
3243 if skip {
3244 // No residual syntax at all: the prediction IS the block. Strides are
3245 // `side`/`cside`, not `bw` -- `reconstruct_mc_rect` indexes
3246 // `row * stride + w` for row in 0..h (the r5 VERT-strip overrun).
3247 push_mc_rect(
3248 y,
3249 u,
3250 v,
3251 0,
3252 px,
3253 py,
3254 side,
3255 bw,
3256 bh,
3257 Pred::Inline(&pred_y, side),
3258 &ZERO_RESIDUAL[..side * side],
3259 fctx,
3260 );
3261 push_mc_rect(
3262 y,
3263 u,
3264 v,
3265 1,
3266 cpx,
3267 cpy,
3268 cside,
3269 cw,
3270 ch,
3271 Pred::Inline(&pred_u, cside),
3272 &ZERO_RESIDUAL[..cside * cside],
3273 fctx,
3274 );
3275 push_mc_rect(
3276 y,
3277 u,
3278 v,
3279 2,
3280 cpx,
3281 cpy,
3282 cside,
3283 cw,
3284 ch,
3285 Pred::Inline(&pred_v, cside),
3286 &ZERO_RESIDUAL[..cside * cside],
3287 fctx,
3288 );
3289 if let Some(ls) = leaves.as_ref() {
3290 // A LOSSLESS frame's `read_block_tx_size_rect` resolves the TX_4X4
3291 // grid before it looks at `skip`; the skipped block still zeroes
3292 // its entropy-band footprint over every unit (libaom
3293 // `av1_reset_entropy_context` under `if (mbmi->skip_txfm)`) --
3294 // the same arm [`decode_intrabc_rect`]'s loss64 merge added.
3295 hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
3296 for &(row, col, tw, th) in ls {
3297 neighbours.record_mi_luma_rect(
3298 (mi_r + row, mi_c + col),
3299 tw,
3300 th,
3301 &ZERO_RESIDUAL[..tw * th],
3302 );
3303 }
3304 }
3305 luma_grid = Grid::Zero(side * side);
3306 u_grid = Grid::Zero(cside * cside);
3307 v_grid = Grid::Zero(cside * cside);
3308 } else {
3309 let leaves = leaves
3310 .expect("read_block_tx_size_rect returns None only for skip below 128 at this shape");
3311 // libaom `get_transform_size`'s split override applies to LUMA only,
3312 // per leaf -- each unit's own transform edges get filtered
3313 // ([`decode_intrabc_rect`]'s P2, the proven inter path's step).
3314 for &(row, col, tw, th) in leaves.iter() {
3315 neighbours.fill_lf_grid_leaf_luma(
3316 (mi_r + row, mi_c + col),
3317 tw / MI,
3318 th / MI,
3319 tw as u8,
3320 th as u8,
3321 );
3322 }
3323 let reduced = fctx.reduced_tx_set_inter.with(std::cell::Cell::get);
3324 let mut u_units: Vec<i32> = Vec::new();
3325 let mut v_units: Vec<i32> = Vec::new();
3326 let mut leaf_tx_types: Vec<(usize, usize, usize, usize, TxType)> = Vec::new();
3327 // Frame-edge clip of the mu walk (`max_block_wide/high`): a unit whose
3328 // top-left sample is outside the frame codes nothing.
3329 let max_w_mi = (bw / MI).min(mi_cols.saturating_sub(mi_c));
3330 let max_h_mi = (bh / MI).min(mi_rows.saturating_sub(mi_r));
3331 // lane-av1h5: chunk-major token order at 128 (see [`mu_chunk_order`]).
3332 let (order, _mu_reordered) = mu_chunk_order(&leaves, side);
3333 for (pos, &idx) in order.iter().enumerate() {
3334 let (row, col, tw, th) = leaves[idx];
3335 debug_assert_eq!(
3336 tw, th,
3337 "a square TX_64X64 tree root only yields square leaves"
3338 );
3339 let tu_mi = (mi_r + row, mi_c + col);
3340 let (tu_px, tu_py) = (px + col * MI, py + row * MI);
3341 if tu_px >= y.true_width || tu_py >= y.true_height {
3342 continue;
3343 }
3344 let tu_pred = Pred::Inline(&pred_y, side).offset(row * MI * side + col * MI);
3345 let scan = default_scan(tw.min(32));
3346 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tw / MI);
3347 let (tu_grid, tu_tx_type) = read_inter_plane(
3348 dec,
3349 cdfs,
3350 inter_txbset_for(tw, reduced),
3351 scan,
3352 0,
3353 neighbours.around_mi(tu_mi, tw)[0],
3354 0,
3355 y,
3356 u,
3357 v,
3358 tu_px,
3359 tu_py,
3360 tw,
3361 base_q_idx,
3362 tu_pred,
3363 None,
3364 Some(tu_skip_ctx),
3365 fctx,
3366 )?;
3367 leaf_tx_types.push((row, col, tw, th, tu_tx_type));
3368 neighbours.record_mi_luma_rect(tu_mi, tw, th, &tu_grid);
3369 // libaom `decode_token_recon_block` codes EVERY PLANE of a 64x64
3370 // mu chunk before the next one starts: once this chunk's leaves
3371 // are done, its chroma is read immediately (the inter 128 path's
3372 // interleave).
3373 let chunk = (row / 16, col / 16);
3374 let done = pos + 1 == order.len()
3375 || (leaves[order[pos + 1]].0 / 16, leaves[order[pos + 1]].1 / 16) != chunk;
3376 if done {
3377 let (cr, cc) = chunk;
3378 // `av1_get_max_uv_txsize(BLOCK_128X64)` = TX_32X32: one
3379 // TX_32X32 chroma unit per plane per chunk at 4:2:0, raster
3380 // within the chunk, plane-major inside the chunk.
3381 let cu_tx = 32usize;
3382 // lane-av1-ibc128chunk: a 64x64 mu chunk's chroma plane
3383 // block is PER-AXIS `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at
3384 // 4:2:0, TWO STACKED TX_32X32 at 4:2:2 (the chunk's chroma
3385 // plane block is 32x64 there), four at 4:4:4. The old
3386 // `chunk_chroma = cside * 64 / side` walked a
3387 // `chroma_side`-SQUARE chunk, i.e. the 4:2:0 count on both
3388 // axes: at 4:2:2 it read HALF the chroma units of a chunk
3389 // (one 32x32 at the chunk's top-left instead of two), left
3390 // the chunk's lower 32 chroma rows with no residual at all,
3391 // and stamped every unit's entropy context over a 16x16-mi
3392 // luma span instead of 16x8. The same defect and the same
3393 // per-axis repair as `decode_inter_block`'s
3394 // `chunk_chroma_w/chunk_chroma_h` (lane-av1-422bigblock,
3395 // witnessed on `422_sb128_3f.obu`).
3396 let chunk_chroma_w = (64usize) >> ss_x(fctx);
3397 let chunk_chroma_h = (64usize) >> ss_y(fctx);
3398 // The unit's own footprint on the LUMA mi grid, per axis:
3399 // `(32 << ss) px` = `(32 << ss) / MI` mi -- 16x16 at 4:2:0,
3400 // 16x8 at 4:2:2, 8x8 at 4:4:4. `around_mi_rect` reads and
3401 // `record_mi_chroma` stamp exactly the unit's own cells.
3402 let unit_luma_w = cu_tx << ss_x(fctx);
3403 let unit_luma_h = cu_tx << ss_y(fctx);
3404 INTRABC_128RECT_CHUNK_SHAPE.with(|c| {
3405 c.set((chunk_chroma_w << 8) | chunk_chroma_h);
3406 });
3407 let chunk_w_mi = 16.min(max_w_mi.saturating_sub(cc * 16));
3408 let chunk_h_mi = 16.min(max_h_mi.saturating_sub(cr * 16));
3409 let units_x = chunk_w_mi / (unit_luma_w / MI);
3410 let units_y = chunk_h_mi / (unit_luma_h / MI);
3411 if lossless(fctx) {
3412 // TX_4X4 chroma units over this chunk (lane-lossless2's
3413 // walk, shared with the inter 128 path).
3414 read_inter_chroma_lossless(
3415 y,
3416 u,
3417 v,
3418 dec,
3419 cdfs,
3420 neighbours,
3421 Pred::Inline(&pred_u, cside),
3422 Pred::Inline(&pred_v, cside),
3423 (mi_r, mi_c),
3424 (cpx, cpy),
3425 (cc * chunk_chroma_w, cr * chunk_chroma_h),
3426 (chunk_chroma_w, chunk_chroma_h),
3427 (cw, ch),
3428 cside,
3429 0,
3430 base_q_idx,
3431 &mut u_units,
3432 &mut v_units,
3433 fctx,
3434 )?;
3435 // lane-av1-ibcrect: read_inter_chroma_lossless stamped
3436 // every TX_4X4 unit's own context (`record_mi_chroma`
3437 // inside the walk) -- the end-of-block record below must
3438 // not overwrite them with the composed grid (the inter
3439 // 128 path sets the same flag on this arm).
3440 mu_chroma = true;
3441 continue;
3442 }
3443 let cu_scan = default_scan(cu_tx);
3444 for plane_idx in 1..3 {
3445 let src = if plane_idx == 1 {
3446 Pred::Inline(&pred_u, cside)
3447 } else {
3448 Pred::Inline(&pred_v, cside)
3449 };
3450 for ur in 0..units_y {
3451 for uc in 0..units_x {
3452 let unit_mi = (
3453 mi_r + cr * 16 + ur * (unit_luma_h / MI),
3454 mi_c + cc * 16 + uc * (unit_luma_w / MI),
3455 );
3456 // Per unit, AFTER the earlier units' stamps: this
3457 // unit's coefficient context must see them.
3458 //
3459 // lane-av1muchunk422sym: same 4:2:2 pair rule as
3460 // `decode_inter_block`'s mu-chunk walk -- at ss
3461 // (1, 0) one CHROMA column spans two luma mi
3462 // columns, so the plain rect gather doubles the
3463 // above dc vote and flips `dc_sign_ctx` whenever
3464 // above and left cancel.
3465 let cu_around = if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
3466 neighbours.around_mi_422_chroma(unit_mi, unit_luma_w, unit_luma_h)
3467 } else {
3468 neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h)
3469 };
3470 if crate::envflags::env_flag!("EC_ECDUMP") {
3471 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
3472 #[allow(clippy::needless_range_loop)]
3473 for p in 1..3 {
3474 let ab: Vec<String> = (0..unit_luma_w / MI)
3475 .map(|k| {
3476 format!(
3477 "{:?}/{}",
3478 neighbours.above[unit_mi.1 + k][p].dc,
3479 neighbours.above[unit_mi.1 + k][p].level
3480 )
3481 })
3482 .collect();
3483 let lf: Vec<String> = (0..unit_luma_h / MI)
3484 .map(|k| {
3485 format!(
3486 "{:?}/{}",
3487 neighbours.left[unit_mi.0 + k][p].dc,
3488 neighbours.left[unit_mi.0 + k][p].level
3489 )
3490 })
3491 .collect();
3492 eprintln!(
3493 "EC_IBC128_BANDS mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={p} ctx=({},{},{}) above=[{}] left=[{}]",
3494 cu_around[p].0,
3495 cu_around[p].1,
3496 cu_around[p].2,
3497 ab.join(","),
3498 lf.join(",")
3499 );
3500 }
3501 }
3502 let (cu_x, cu_y) = (
3503 cpx + cc * chunk_chroma_w + uc * cu_tx,
3504 cpy + cr * chunk_chroma_h + ur * cu_tx,
3505 );
3506 // `av1_get_tx_type` (blockd.h:1291): an inter
3507 // block's chroma unit never codes a tx_type; it
3508 // inherits the coded type of the luma leaf
3509 // covering its own quadrant (all of this chunk's
3510 // leaves are read by now).
3511 let unit_rel_mi = (unit_mi.0 - mi_r, unit_mi.1 - mi_c);
3512 let covering = covering_leaf_tx_type(&leaf_tx_types, unit_rel_mi);
3513 // The prediction window is the block's own square
3514 // `cside` buffer with the unit's true per-axis
3515 // position inside it.
3516 let cu_pred = src.offset(
3517 (cr * chunk_chroma_h + ur * cu_tx) * cside
3518 + cc * chunk_chroma_w
3519 + uc * cu_tx,
3520 );
3521 let cu_grid = read_inter_plane(
3522 dec,
3523 cdfs,
3524 TxbSet::Chroma32,
3525 cu_scan,
3526 plane_idx,
3527 cu_around[plane_idx],
3528 0,
3529 y,
3530 u,
3531 v,
3532 cu_x,
3533 cu_y,
3534 cu_tx,
3535 base_q_idx,
3536 cu_pred,
3537 Some(covering.unwrap_or(TxType::DctDct)),
3538 Some(3),
3539 fctx,
3540 )?
3541 .0;
3542 // Immediately, so the NEXT unit reads this one's
3543 // coefficient context.
3544 neighbours.record_mi_chroma(
3545 unit_mi,
3546 unit_luma_w,
3547 unit_luma_h,
3548 plane_idx,
3549 &cu_grid,
3550 );
3551 if crate::envflags::env_flag!("EC_ECDUMP") {
3552 let st = crate::decode::neighbour_state(&cu_grid);
3553 eprintln!(
3554 "EC_IBC128_STAMP mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={plane_idx} state=({:?},{})",
3555 st.dc, st.level
3556 );
3557 }
3558 hit!(CHROMA_SPLIT_TX_HITS);
3559 INTRABC_128RECT_CHROMA_CHUNK_HITS.with(|c| c.set(c.get() + 1));
3560 // lane-av1-ibcrect: per-unit chroma context -- the
3561 // end-of-block record's composed-grid re-stamp
3562 // must not stand (replayed below).
3563 mu_chroma = true;
3564 let dst = mu_units(
3565 if plane_idx == 1 {
3566 &mut u_units
3567 } else {
3568 &mut v_units
3569 },
3570 cside * cside,
3571 );
3572 for rr in 0..cu_tx {
3573 let start = (cr * chunk_chroma_h + ur * cu_tx + rr) * cside
3574 + cc * chunk_chroma_w
3575 + uc * cu_tx;
3576 dst[start..start + cu_tx]
3577 .copy_from_slice(&cu_grid[rr * cu_tx..][..cu_tx]);
3578 }
3579 }
3580 }
3581 }
3582 }
3583 }
3584 // The block-level luma bands were recorded per leaf above; the
3585 // composed chroma grids carry every unit in place.
3586 luma_grid = Grid::Zero(side * side);
3587 u_grid = if u_units.is_empty() {
3588 Grid::Zero(cside * cside)
3589 } else {
3590 Grid::Own(std::mem::take(&mut u_units))
3591 };
3592 v_grid = if v_units.is_empty() {
3593 Grid::Zero(cside * cside)
3594 } else {
3595 Grid::Own(std::mem::take(&mut v_units))
3596 };
3597 }
3598 // Bookkeeping (see [`decode_intrabc_rect`]): DC_PRED everywhere a
3599 // neighbour reads a mode, zeroed palette state, the skip grid, the
3600 // TXFM_CONTEXT bands (`read_block_tx_size_rect` already stamped them),
3601 // and the DV into the intrabc mi grid.
3602 if skip {
3603 neighbours.record_rect_mi(
3604 (mi_r, mi_c),
3605 bw,
3606 bh,
3607 DC_PRED,
3608 DC_PRED,
3609 &[&luma_grid[..], &u_grid[..], &v_grid[..]],
3610 );
3611 } else {
3612 neighbours.record_split_luma_rect_mi(
3613 (mi_r, mi_c),
3614 bw,
3615 bh,
3616 DC_PRED,
3617 DC_PRED,
3618 [&u_grid[..], &v_grid[..]],
3619 );
3620 }
3621 // lane-av1-ibcrect: the coded arm's chroma contexts were stamped PER
3622 // TRANSFORM UNIT (libaom `av1_set_entropy_contexts` inside
3623 // `decode_reconstruct_tx`'s mu-chunk loop), but the record above re-stamps
3624 // both planes with ONE `neighbour_state(composed_grid)` over the whole
3625 // span -- level = the SUM of every unit's levels and dc = the top-left
3626 // unit's sign (lane-vert46 r1 measured the same smearing at the 64x128
3627 // inter block: the next block read a stale `dc_sign_ctx` one row low).
3628 // Measured on this shape: the 128x64 block at mi(64,32) of the
3629 // `ibcrect-hunt/E2` sb128 screen stream left chunk-1 U's level 1 smeared
3630 // into chunk-0's cells and the block below read `txb_skip` off the sum.
3631 // Replay every coded unit's own state after the record, in mu-chunk order
3632 // so a later unit still wins over an earlier one on the shared seam cells
3633 // (the composed construction `mu_chroma_units` uses, transcribed here).
3634 if mu_chroma {
3635 let cu = if lossless(fctx) { 4usize } else { 32usize };
3636 // The unit's own footprint on the LUMA mi grid (the chroma context
3637 // bands are luma-mi indexed, [`Self::record_mi_chroma`]'s
3638 // convention), PER AXIS: `cu << ss` px, i.e. 8 px per TX_4x4 unit and
3639 // 64 px per TX_32X32 one at 4:2:0 -- 4 px / 32 px at 4:2:2.
3640 let unit_luma_w = cu << ss_x(fctx);
3641 let unit_luma_h = cu << ss_y(fctx);
3642 // A 64x64 mu chunk's chroma plane block is PER-AXIS
3643 // `(64 >> ss_x) x (64 >> ss_y)` -- 32x32 at 4:2:0 (ONE TX_32X32 per
3644 // chunk), 32x64 at 4:2:2 (TWO STACKED), 64x64 at 4:4:4 (FOUR);
3645 // `av1_get_max_uv_txsize` caps the unit at 32 on each axis.
3646 let chunk_chroma_w = (64usize) >> ss_x(fctx);
3647 let chunk_chroma_h = (64usize) >> ss_y(fctx);
3648 if lossless(fctx) {
3649 // lane-av1-ibc128chunk, PRE-EXISTING and NOT this lane's: on a
3650 // LOSSLESS frame `cu` is 4 and the composed plane grid is a raster
3651 // of TX_4x4 units, not a `cu`-per-chunk tiling -- so `rows`/`cols`
3652 // below (which count mu CHUNKS at the 4:2:0 chunk extent) do not
3653 // enumerate it, and this arm re-stamps only the 4x4 at each
3654 // chunk's top-left with a 2x2-mi span. The twin
3655 // (`decode_inter_block`'s `mu_chroma_units`, lane-av1-llinter)
3656 // instead raster-walks the WHOLE plane block at `cu` steps, and
3657 // that is the correct shape here too. It is left as-is on purpose:
3658 // it is a 4:2:0 defect, not a subsampling square-cut, and fixing
3659 // it would change 4:2:0 LOSSLESS output -- which this lane's
3660 // byte-identity requirement forbids doing on an unverified
3661 // reconstruction. Measured unreachability: this arm is entered
3662 // 0 times by the whole `lossless` and `intrabc` gate battery
3663 // (temporary env-gated counter in the arm). Unblock: one
3664 // lossless sb128 4:2:0 stream coding a NON-SKIP 128-root
3665 // intrabc strip (`--lossless=1 --sb-size=128
3666 // --min-partition-size=64 --enable-rect-partitions=1
3667 // --enable-intrabc=1` over near-match screen content).
3668 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
3669 for cr in 0..rows {
3670 for cc in 0..cols {
3671 let unit_mi = (
3672 mi_r + cr * (unit_luma_h / MI),
3673 mi_c + cc * (unit_luma_w / MI),
3674 );
3675 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
3676 let mut unit = Vec::with_capacity(cu * cu);
3677 for rr in 0..cu {
3678 let start = (cr * chunk_chroma_h + rr) * cside + cc * chunk_chroma_w;
3679 unit.extend_from_slice(&grid[start..start + cu]);
3680 }
3681 neighbours.record_mi_chroma(
3682 unit_mi,
3683 unit_luma_w,
3684 unit_luma_h,
3685 plane_idx,
3686 &unit,
3687 );
3688 }
3689 }
3690 }
3691 } else {
3692 // The chunk count on each axis, then EVERY unit inside each
3693 // chunk at its own mi origin, its own `(cu << ss)`-px entropy-cell
3694 // span, and its own quadrant of the composed plane grid -- the
3695 // twin's loop (decode_inter_block's `mu_chroma_units`,
3696 // lane-av1-444 c8). lane-av1-ibc128chunk: the loop used to count
3697 // mu CHUNKS in `rows`/`cols` and then step the mi origin and read
3698 // the grid PER UNIT, which only agrees when a chunk holds exactly
3699 // one unit. At 4:2:0 (`chunk_chroma == cu`) it is
3700 // line-identical to the old walk; at 4:2:2 and 4:4:4 a chunk holds
3701 // 2 or 4, so the old body reached only the first of the stacked
3702 // units and the rest of the chunk kept the composed-grid smearing
3703 // this replay exists to undo. A unit the frame edge clipped codes
3704 // nothing and carries no composed samples beyond the clip, so it
3705 // replays as the zero state exactly like libaom's uncoded unit.
3706 let (ur, uc) = (chunk_chroma_h / cu, chunk_chroma_w / cu);
3707 let (rows, cols) = ((ch / chunk_chroma_h).max(1), (cw / chunk_chroma_w).max(1));
3708 for cr in 0..rows {
3709 for cc in 0..cols {
3710 for kr in 0..ur {
3711 for kc in 0..uc {
3712 let unit_mi = (
3713 mi_r + (cr * 64 + kr * unit_luma_h) / MI,
3714 mi_c + (cc * 64 + kc * unit_luma_w) / MI,
3715 );
3716 let (cy, cx) =
3717 (cr * chunk_chroma_h + kr * cu, cc * chunk_chroma_w + kc * cu);
3718 for (plane_idx, grid) in [(1usize, &u_grid), (2usize, &v_grid)] {
3719 let mut unit = Vec::with_capacity(cu * cu);
3720 for rr in 0..cu {
3721 let start = (cy + rr) * cside + cx;
3722 unit.extend_from_slice(&grid[start..start + cu]);
3723 }
3724 neighbours.record_mi_chroma(
3725 unit_mi,
3726 unit_luma_w,
3727 unit_luma_h,
3728 plane_idx,
3729 &unit,
3730 );
3731 }
3732 }
3733 }
3734 }
3735 }
3736 }
3737 }
3738 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
3739 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, 0, [0u16; 8]);
3740 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
3741 // lane-av1oddheightfork3: see `decode_intrabc_rect`'s call -- the tree
3742 // published the bands, so no whole-footprint publish here.
3743 neighbours.fill_lf_grid_rect_after_vartx(
3744 (mi_r, mi_c),
3745 bw / MI,
3746 bh / MI,
3747 bw.min(64) as u8,
3748 bh.min(64) as u8,
3749 0,
3750 fctx,
3751 );
3752 record_intrabc_mi_rect(
3753 mi_r,
3754 mi_c,
3755 bw / MI,
3756 bh / MI,
3757 Some((dv_row, dv_col)),
3758 neighbours,
3759 fctx,
3760 );
3761 Ok(())
3762}
3763
3764/// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip
3765/// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's
3766/// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/
3767/// `uv_mode`/`filter_intra`/`tx_depth` are read exactly per spec either way
3768/// (so a skip strip elsewhere in the tile stays in sync), but this decoder
3769/// has no rectangular-transform coefficient reader, and a chroma plane here
3770/// is genuinely `TX_16X8`/`TX_8X16` (`av1_get_max_uv_txsize`, spec 5.11.16)
3771/// with no depth-based square-tiling escape the way luma's own resolved
3772/// `tx_depth` has (`sub_tx_size_map[TX_32X16]` == `TX_16X16`, square) --
3773/// so a coded (non-skip) strip is refused by name instead of guess-decoded.
3774#[allow(clippy::too_many_arguments)]
3775pub(super) fn decode_block_rect(
3776 dec: &mut SymbolDecoder,
3777 cdfs: &mut Cdfs,
3778 neighbours: &mut Neighbours,
3779 at: (usize, usize),
3780 bw: usize,
3781 bh: usize,
3782 y: &mut PlaneBuf<'static>,
3783 u: &mut PlaneBuf<'static>,
3784 v: &mut PlaneBuf<'static>,
3785 enable_filter_intra: bool,
3786 allow_screen_content_tools: bool,
3787 base_q_idx: u8,
3788 tx_select: bool,
3789 reduced_tx_set: bool,
3790 fctx: &crate::decode::FrameCtx,
3791) -> Result<()> {
3792 let (r, c) = at;
3793 let (px, py) = (c * SUB, r * SUB);
3794 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
3795 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
3796 let palette_uv_cache = neighbours.palette_uv_cache(at);
3797 let (
3798 skip,
3799 mode,
3800 angle_delta_y,
3801 uv_mode,
3802 angle_delta_uv,
3803 alpha,
3804 filter_intra,
3805 palette_y,
3806 palette_uv,
3807 intrabc,
3808 ) = read_intra_mode_rect(
3809 dec,
3810 cdfs,
3811 nb_above_mode,
3812 nb_left_mode,
3813 true,
3814 true,
3815 bw,
3816 bh,
3817 enable_filter_intra,
3818 neighbours.skip_txfm_ctx(r * (SUB / MI), c * (SUB / MI)),
3819 allow_screen_content_tools,
3820 Some((palette_ctx, &palette_cache)),
3821 &palette_uv_cache,
3822 r * (SUB / MI),
3823 c * (SUB / MI),
3824 fctx,
3825 )?;
3826
3827 if let Some((dv_row, dv_col)) = intrabc {
3828 return decode_intrabc_rect(
3829 dec,
3830 cdfs,
3831 neighbours,
3832 (r * (SUB / MI), c * (SUB / MI)),
3833 (bw, bh),
3834 skip,
3835 (dv_row, dv_col),
3836 y,
3837 u,
3838 v,
3839 base_q_idx,
3840 fctx,
3841 );
3842 }
3843 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
3844 if smooth_neighbor {
3845 hit!(SMOOTH_LUMA_HITS);
3846 }
3847 // lane-chroma r3: chroma's own edge-filter-strength neighbour check
3848 // (spec `get_intra_edge_filter_type`) reads the CHROMA neighbour's
3849 // `uv_mode`, not the luma one.
3850 let smooth_neighbor_uv =
3851 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
3852 // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
3853 // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
3854 // rectangle just as happily), so a `use_filter_intra` strip at this level
3855 // predicts instead of refusing. The below-16x16 leaf arm
3856 // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
3857 if filter_intra.is_some() {
3858 hit!(FILTER_INTRA_RECT_HITS);
3859 }
3860 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
3861 DC_PRED
3862 } else {
3863 uv_mode
3864 };
3865 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
3866 // The tx-depth symbol EXISTS only under TX_MODE_SELECT. Both square paths
3867 // gate their `read_tx_size` on `tx_select` for exactly this reason; this
3868 // one did not, so with `--enable-tx-size-search=0` -- which several gate
3869 // recipes use -- the decoder consumed a symbol the encoder never wrote and
3870 // desynced the tile from that point on. That is why both strips of the
3871 // pinned HORZ quadrant were wrong from their very first pixel, and why our
3872 // range after the read equalled the oracle's range for the whole block.
3873 // lane-av1mixloss: the lossless-segment early return
3874 // (`decodeframe.c:1203`) precedes `TX_MODE_SELECT`, so a lossless-segment
3875 // rect block codes no depth symbol here either (class sweep of the sub8
3876 // leaf's fix).
3877 let depth = if tx_select && !lossless(fctx) {
3878 // lane-av1txbands: EVERY frame now reads the real `TXFM_CONTEXT`
3879 // bands (`get_tx_size_context`, libaom `pred_common.h:342`) -- an
3880 // intra-only frame publishes them from every block too
3881 // ([`Neighbours::fill_lf_grid_rect`]). Measured on the 10-bit
3882 // 1920x792 128-superblock stream,
3883 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
3884 // `tx_size_cat2` row 1 where libaom reads row 2.
3885 let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
3886 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
3887 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
3888 eprintln!(
3889 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
3890 dec.debug_state().0
3891 );
3892 }
3893 d
3894 } else {
3895 0
3896 };
3897 // lane-av1-intrabc r3: this strip's own `set_txfm_ctxs` when the frame
3898 // reads the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
3899 publish_txfm_bands_if_in_inter(
3900 neighbours,
3901 (mi_r, mi_c),
3902 depth_to_tx_wh(bw, bh, depth, fctx),
3903 (bw, bh),
3904 fctx,
3905 );
3906 if depth != 0 || lossless(fctx) {
3907 hit!(TX_DEPTH_HITS);
3908 // lane-rectsplit r1: a split transform is predicted and reconstructed
3909 // per transform unit, each unit taking its edges from the previous
3910 // unit's reconstruction inside this same strip (spec 5.11.36) --
3911 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
3912 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
3913 if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
3914 eprintln!(
3915 "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
3916 depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
3917 angle_y={angle_delta_y}"
3918 );
3919 }
3920 let modes = RectStripModes {
3921 skip,
3922 mode,
3923 angle_delta_y,
3924 uv_predict_mode,
3925 angle_delta_uv,
3926 alpha,
3927 filter_intra,
3928 smooth_neighbor,
3929 smooth_neighbor_uv,
3930 palette_y: palette_y
3931 .as_ref()
3932 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect()),
3933 palette_uv: palette_uv.as_ref().map(|p| {
3934 (
3935 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
3936 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
3937 )
3938 }),
3939 };
3940 if palette_y.is_some() || palette_uv.is_some() {
3941 hit!(PALETTE_SPLIT_TX_HITS);
3942 }
3943 decode_rect_split(
3944 dec,
3945 cdfs,
3946 neighbours,
3947 (mi_r, mi_c),
3948 bw,
3949 bh,
3950 tx_w,
3951 tx_h,
3952 &modes,
3953 y,
3954 u,
3955 v,
3956 base_q_idx,
3957 reduced_tx_set,
3958 fctx,
3959 )?;
3960 // This early return skips this fn's own tail, so the palette
3961 // neighbour state has to be stamped HERE too: without it a split-tx
3962 // strip left the above/left palette arrays holding a DEAD block's
3963 // colours, and the next block's colour cache
3964 // ([`Neighbours::palette_uv_cache`]) then hit a cached entry with the
3965 // wrong VALUE -- same bit count, so the entropy stream stayed in sync
3966 // and only those pixels were wrong (lane-palette2 r10).
3967 let (py_size, py_colors) = palette_y
3968 .as_ref()
3969 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
3970 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
3971 let (puv_size, puv_colors) = palette_uv
3972 .as_ref()
3973 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
3974 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
3975 hit!(RECT_PARTITION_HITS);
3976 return Ok(());
3977 }
3978 let (tx_w, tx_h) = (bw, bh);
3979 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
3980 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
3981 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
3982 if crate::envflags::env_flag!("EC_AV1_TRACE") {
3983 let (rng, _) = dec.debug_state();
3984 eprintln!(
3985 "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
3986 skip={} tx={depth} rng={rng}",
3987 skip as i32
3988 );
3989 }
3990 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
3991 // block's prediction is the reconstructed colour-index map, set fresh
3992 // right before each `reconstruct_rect` call below (lane-palette2 r4).
3993 if let Some(ref pyv) = palette_y {
3994 let buf: Vec<u16> = pyv
3995 .map
3996 .iter()
3997 .map(|&idx| pyv.colors[idx as usize])
3998 .collect();
3999 set_palette_pred(buf, fctx);
4000 }
4001 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|puv| {
4002 (
4003 puv.map
4004 .iter()
4005 .map(|&idx| puv.u_colors[idx as usize])
4006 .collect(),
4007 puv.map
4008 .iter()
4009 .map(|&idx| puv.v_colors[idx as usize])
4010 .collect(),
4011 )
4012 });
4013 if skip {
4014 push_intra_rect(
4015 y,
4016 u,
4017 v,
4018 0,
4019 px,
4020 py,
4021 bw,
4022 bh,
4023 mode,
4024 angle_delta_y,
4025 reach,
4026 &ZERO_RESIDUAL[..bw * bh],
4027 None,
4028 filter_intra,
4029 smooth_neighbor,
4030 fctx,
4031 );
4032 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
4033 if let Some((ub, _)) = &palette_uv_bufs {
4034 set_palette_pred(ub.clone(), fctx);
4035 }
4036 push_intra_rect(
4037 y,
4038 u,
4039 v,
4040 1,
4041 cpx,
4042 cpy,
4043 chroma_w,
4044 chroma_h,
4045 uv_predict_mode,
4046 angle_delta_uv,
4047 reach,
4048 &ZERO_RESIDUAL[..chroma_w * chroma_h],
4049 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
4050 None,
4051 smooth_neighbor_uv,
4052 fctx,
4053 );
4054 if let Some((_, vb)) = &palette_uv_bufs {
4055 set_palette_pred(vb.clone(), fctx);
4056 }
4057 push_intra_rect(
4058 y,
4059 u,
4060 v,
4061 2,
4062 cpx,
4063 cpy,
4064 chroma_w,
4065 chroma_h,
4066 uv_predict_mode,
4067 angle_delta_uv,
4068 reach,
4069 &ZERO_RESIDUAL[..chroma_w * chroma_h],
4070 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
4071 None,
4072 smooth_neighbor_uv,
4073 fctx,
4074 );
4075 neighbours.record_rect(
4076 at,
4077 bw,
4078 bh,
4079 mode,
4080 uv_predict_mode,
4081 &[
4082 &ZERO_RESIDUAL[..bw * bh],
4083 &ZERO_RESIDUAL[..chroma_w * chroma_h],
4084 &ZERO_RESIDUAL[..chroma_w * chroma_h],
4085 ],
4086 );
4087 } else {
4088 // lane-rectwire r2: real coefficients. `get_txsize_entropy_ctx`
4089 // reduces both size pairs to their square-up CDF sets
4090 // (`TxbSet::LumaRect32x16`/`ChromaRect16x8`, see those variants' own
4091 // doc comments); the scan order and 2D context tables are the real
4092 // rect ones (`SCAN_32X16`/etc, `base_ctx_rect`/`br_ctx_rect`).
4093 let luma_scan: &[u16] = if bw > bh { &SCAN_32X16 } else { &SCAN_16X32 };
4094 // Chroma tx follows the plane block, not a hardcoded half. At 4:2:0 a
4095 // 32x16 strip's chroma is 16x8 (ChromaRect16x8); at 4:4:4 it is 32x16
4096 // (ChromaRect32x16, DCT-only — ADST is undefined on a 32-point axis).
4097 let (chroma_set, chroma_scan): (TxbSet, &[u16]) = match (chroma_w, chroma_h) {
4098 (32, 16) => (TxbSet::ChromaRect32x16, &SCAN_32X16),
4099 (16, 32) => (TxbSet::ChromaRect32x16, &SCAN_16X32),
4100 (16, 8) => (TxbSet::ChromaRect16x8, &SCAN_16X8),
4101 (8, 16) => (TxbSet::ChromaRect16x8, &SCAN_8X16),
4102 // lane-av1-422: a 4:2:2 strip halves only the width. A 32x16
4103 // luma strip's chroma is a 16x16 SQUARE (`TxbSet::Chroma16`, the
4104 // set any 16x16 chroma plane reads); a 16x32 strip's chroma is
4105 // 8x32, whose entropy set is the 16x16 one and whose DCT-only
4106 // default follows the >=32 rule below -- the same pairing the
4107 // (8,32) row of [`decode_rect_split`]'s chroma table proves. At
4108 // 4:2:0 and 4:4:4 a strip's chroma is itself rect, so neither row
4109 // is reachable there.
4110 (16, 16) => (TxbSet::Chroma16, default_scan(16)),
4111 (8, 32) => (TxbSet::Chroma16, &SCAN_8X32),
4112 _ => {
4113 return Err(unsupported(
4114 "a rectangular chroma transform whose size has no coefficient table",
4115 ));
4116 }
4117 };
4118 let chroma_default_tx = if chroma_w.max(chroma_h) >= 32 {
4119 TxType::DctDct
4120 } else {
4121 default_intra_tx_type(uv_predict_mode as u8)
4122 };
4123 // lane-rectwire r3: real coefficients desync a pixel-exact gate
4124 // (rectwire-flake-1.obu, seed 55) -- both 32x16 strips of frame 0's
4125 // mi(8,8) HORZ quadrant come out ~100% wrong from their very first
4126 // pixel (not a subtle context-table off-by-one), while the sibling
4127 // non-rect quadrants of the same frame match. Range-ladder bisection
4128 // against a real aomdec (EC_TRACE_COEFF/EC_TRACE_MODE) was started
4129 // but the intra key-frame path has no traced symbol between the
4130 // partition read and the first coefficient block (mode/skip/tx_depth
4131 // reads are all untraced in libaom's decodeframe.c intra path, unlike
4132 // the inter EC_TRACE_MODE this round added), so a same-length range
4133 // comparison wasn't reachable within budget -- see
4134 // lanes/rectwire-r3.report.md for what was ruled out (base_ctx_rect's
4135 // 5-neighbour offsets, u/v_skip_ctx's above+left formula, and
4136 // dc_sign_ctx's around-index all cross-checked byte-for-byte against
4137 // libaom and match). lane-rectwire r4: range-ladder against the
4138 // now-instrumented oracle (EC_TRACE_MODE's intra EC_IMODE/EC_IMODE_VAL)
4139 // narrowed the divergence past skip/y_mode/uv_mode (values AND range
4140 // both confirmed in sync -- rng=58692 on both sides right after
4141 // uv_mode, with `enable_filter_intra=0` on this frame so neither side
4142 // reads a filter_intra symbol) to the `tx_size_cat2` depth read
4143 // immediately after: ours moves rng 58692 -> 43570, which cannot be
4144 // reconciled with oracle's own EC_IMODE_VAL (rng=58692, taken *after*
4145 // its own tx_size read) unless oracle's tx symbol is a near-certainty
4146 // CDF that barely narrows the range -- i.e. this decoder's
4147 // tx-depth ctx or `cdfs.tx_size_cat2` CDF selection for
4148 // a 32x16/16x32 strip is the first diverging symbol, not the
4149 // coefficient-context math r3 already cleared. Not confirmed byte-
4150 // exact (would need a decodemv.c EC_TRACE_MODE patch specifically on
4151 // `read_tx_size`'s own rng, not attempted this round -- budget), so
4152 // r5 CONFIRMED the suspect and it was simpler than the CDF row: the
4153 // tx-depth symbol exists only under TX_MODE_SELECT, and this path read
4154 // it unconditionally where both square paths gate on `tx_select`. With
4155 // --enable-tx-size-search=0 the encoder writes no such symbol, so the
4156 // decoder consumed one that was never there.
4157 {
4158 // lane-av1422warp r20: this 32x16/16x32 strip reader is the SIBLING of
4159 // `decode_leaf_rect`, and it was the one left ungated: at ss (1,0) the
4160 // strip's chroma is a square (side/2, side) block whose above cells
4161 // spread over `side` LUMA mi columns, so the per-mi rect gather
4162 // double-counts every chroma column's whole-unit dc sign. Measured on
4163 // the pinned 4:2:2 rotzoom stream (a1.obu frame 0): the chroma-U 4x4
4164 // transform of the 32x16 strip at mi(68,16) reads its DC sign from
4165 // `dc_sign_ctx` 1 where libaom reads row 0 -- the first read of
4166 // 45260 whose pre-state, bit position and symbol all match and only
4167 // the CDF row differs, and the first divergence in the EC_SYMR
4168 // sequence (all 45259 reads before it pair exactly). Luma keeps the
4169 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
4170 let mut around = neighbours.around_rect(at, bw, bh);
4171 if ss_x(fctx) == 1 && ss_y(fctx) == 0 {
4172 let c2 =
4173 neighbours.around_mi_422_chroma((at.0 * (SUB / MI), at.1 * (SUB / MI)), bw, bh);
4174 around[1] = c2[1];
4175 around[2] = c2[2];
4176 }
4177 let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x16, fi_tx_row(mode, filter_intra));
4178 let (luma_levels, luma_tx_type) = read_coeffs_rect(
4179 dec,
4180 &mut luma_coding,
4181 luma_scan,
4182 bw,
4183 bh,
4184 0,
4185 dc_sign_ctx(around[0].2),
4186 TxType::DctDct,
4187 0,
4188 )?;
4189 if crate::envflags::env_flag!("EC_AV1_TRACE") {
4190 let (rng, _) = dec.debug_state();
4191 eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
4192 }
4193 let luma_residual = dequant_and_inverse_typed_wh(
4194 &luma_levels,
4195 bw,
4196 bh,
4197 crate::decode::bit_depth(fctx),
4198 block_q_idx(fctx),
4199 plane_q_delta(0, fctx).0,
4200 plane_q_delta(0, fctx).1,
4201 luma_tx_type,
4202 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
4203 );
4204 push_intra_rect(
4205 y,
4206 u,
4207 v,
4208 0,
4209 px,
4210 py,
4211 bw,
4212 bh,
4213 mode,
4214 angle_delta_y,
4215 reach,
4216 &luma_residual,
4217 None,
4218 filter_intra,
4219 smooth_neighbor,
4220 fctx,
4221 );
4222 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
4223 if let Some((ub, _)) = &palette_uv_bufs {
4224 set_palette_pred(ub.clone(), fctx);
4225 }
4226 let u_default_tx = chroma_default_tx;
4227 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
4228 let mut u_coding = cdfs.txb(chroma_set, uv_predict_mode);
4229 let (u_levels, u_tx_type) = read_chroma_coeffs_rect(
4230 dec,
4231 &mut u_coding,
4232 chroma_scan,
4233 chroma_w,
4234 chroma_h,
4235 u_skip_ctx,
4236 dc_sign_ctx(around[1].2),
4237 u_default_tx,
4238 fctx,
4239 1,
4240 )?;
4241 if crate::envflags::env_flag!("EC_AV1_TRACE") {
4242 let (rng, _) = dec.debug_state();
4243 eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
4244 }
4245 let u_residual = dequant_and_inverse_typed_wh(
4246 &u_levels,
4247 chroma_w,
4248 chroma_h,
4249 crate::decode::bit_depth(fctx),
4250 block_q_idx(fctx),
4251 plane_q_delta(1, fctx).0,
4252 plane_q_delta(1, fctx).1,
4253 u_tx_type,
4254 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
4255 );
4256 push_intra_rect(
4257 y,
4258 u,
4259 v,
4260 1,
4261 cpx,
4262 cpy,
4263 chroma_w,
4264 chroma_h,
4265 uv_predict_mode,
4266 angle_delta_uv,
4267 reach,
4268 &u_residual,
4269 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
4270 None,
4271 smooth_neighbor_uv,
4272 fctx,
4273 );
4274 if let Some((_, vb)) = &palette_uv_bufs {
4275 set_palette_pred(vb.clone(), fctx);
4276 }
4277 let v_default_tx = chroma_default_tx;
4278 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
4279 let mut v_coding = cdfs.txb(chroma_set, uv_predict_mode);
4280 let (v_levels, v_tx_type) = read_chroma_coeffs_rect(
4281 dec,
4282 &mut v_coding,
4283 chroma_scan,
4284 chroma_w,
4285 chroma_h,
4286 v_skip_ctx,
4287 dc_sign_ctx(around[2].2),
4288 v_default_tx,
4289 fctx,
4290 2,
4291 )?;
4292 if crate::envflags::env_flag!("EC_AV1_TRACE") {
4293 let (rng, _) = dec.debug_state();
4294 eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
4295 }
4296 let v_residual = dequant_and_inverse_typed_wh(
4297 &v_levels,
4298 chroma_w,
4299 chroma_h,
4300 crate::decode::bit_depth(fctx),
4301 block_q_idx(fctx),
4302 plane_q_delta(2, fctx).0,
4303 plane_q_delta(2, fctx).1,
4304 v_tx_type,
4305 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
4306 );
4307 push_intra_rect(
4308 y,
4309 u,
4310 v,
4311 2,
4312 cpx,
4313 cpy,
4314 chroma_w,
4315 chroma_h,
4316 uv_predict_mode,
4317 angle_delta_uv,
4318 reach,
4319 &v_residual,
4320 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
4321 None,
4322 smooth_neighbor_uv,
4323 fctx,
4324 );
4325 neighbours.record_rect(
4326 at,
4327 bw,
4328 bh,
4329 mode,
4330 uv_predict_mode,
4331 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
4332 );
4333 hit!(RECT_COEFF_HITS);
4334 }
4335 }
4336 let (py_size, py_colors) = palette_y
4337 .as_ref()
4338 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
4339 neighbours.record_palette_y_rect((mi_r, mi_c), bw, bh, py_size, py_colors);
4340 let (puv_size, puv_colors) = palette_uv
4341 .as_ref()
4342 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
4343 neighbours.record_palette_uv_rect((mi_r, mi_c), bw, bh, puv_size, puv_colors);
4344 neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, skip);
4345 neighbours.fill_lf_grid_rect(
4346 (mi_r, mi_c),
4347 bw / MI,
4348 bh / MI,
4349 tx_w as u8,
4350 tx_h as u8,
4351 0,
4352 fctx,
4353 );
4354 hit!(RECT_PARTITION_HITS);
4355 if crate::envflags::env_flag!("EC_AV1_TRACE") {
4356 eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
4357 }
4358 Ok(())
4359}
4360
4361/// Decodes one `bw`x`bh` rect strip of a plain 16x16-level `PARTITION_HORZ`/
4362/// `PARTITION_VERT` (lane-rect16 r2), sibling to [`decode_block_rect`] but
4363/// addressed by REAL mi coordinates rather than derived from an [`SUB`]-grid
4364/// `outer_at`, the same relationship [`decode_leaf8`] has to `decode_block`:
4365/// the second strip of a HORZ/VERT split sits offset by half the 16x16
4366/// parent, which `decode_block_rect`'s `at`-derived `px = c * SUB` can't
4367/// name. `prev_leaf` mirrors `decode_leaf8`'s own convention -- when the
4368/// previous strip is directly above (same column, `mi_h` rows up) or
4369/// directly left (same row, `mi_w` cols over), its mode overrides the coarse
4370/// per-16x16-cell `above_mode`/`left_mode` slot for THIS strip's own mode
4371/// context read, and bookkeeping goes through the `_mi`/`_rect` neighbour
4372/// writers (`record_mi_rect`, `fill_skip_grid_rect`, `fill_lf_grid_rect`) at
4373/// this strip's real position, never the coarse `record_rect` (which the
4374/// caller uses once, after both strips, exactly like the `VERT_B` arm next
4375/// to it). The non-skip case (lane-rectx) reads real `TX_16X8`/`TX_8X16`
4376/// luma coefficients (`TxbSet::LumaRect16x8`) and their `TX_8X4`/`TX_4X8`
4377/// chroma half (`TxbSet::ChromaRect8x4`) at 4:2:0 -- an 8x8 *square* chroma
4378/// plane (`TxbSet::Chroma8` + the default scan) at 4:2:2 (lane-av1-422e:
4379/// half-width, unhalved height), the two size classes one level
4380/// under [`decode_block_rect`]'s own 32x16/16x32 strip.
4381#[allow(clippy::too_many_arguments)]
4382pub(super) fn decode_leaf_rect(
4383 dec: &mut SymbolDecoder,
4384 cdfs: &mut Cdfs,
4385 neighbours: &mut Neighbours,
4386 outer_at: (usize, usize),
4387 leaf_mi: (usize, usize),
4388 bw: usize,
4389 bh: usize,
4390 prev_leaf: Option<((usize, usize), usize)>,
4391 y: &mut PlaneBuf<'static>,
4392 u: &mut PlaneBuf<'static>,
4393 v: &mut PlaneBuf<'static>,
4394 enable_filter_intra: bool,
4395 allow_screen_content_tools: bool,
4396 base_q_idx: u8,
4397 tx_select: bool,
4398 reduced_tx_set: bool,
4399 fctx: &crate::decode::FrameCtx,
4400) -> Result<usize> {
4401 let _ = base_q_idx;
4402 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
4403 eprintln!(
4404 "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
4405 dec.debug_state().0
4406 );
4407 }
4408 let (r, c) = outer_at;
4409 let mut above_mode = neighbours.above_mode[c];
4410 let mut left_mode = neighbours.left_mode[r];
4411 let (mi_w, mi_h) = (bw / MI, bh / MI);
4412 if let Some(((pr, pc), pmode)) = prev_leaf {
4413 if pc == leaf_mi.1 && leaf_mi.0 == pr + mi_h {
4414 above_mode = pmode;
4415 } else if pr == leaf_mi.0 && leaf_mi.1 == pc + mi_w {
4416 left_mode = pmode;
4417 }
4418 }
4419 // Same mi-exact override [`decode_leaf8`] takes: one coarse 16x16 slot
4420 // cannot hold the modes a split (or a pair of strips) leaves behind, so
4421 // when the map holds the block at exactly this strip's above/left mi it
4422 // is the neighbour libaom's `above_mi`/`left_mi` reads.
4423 // lane-rectsplitx r2 (same class as the 1:4 fix): mi-exact AND
4424 // availability-correct -- four 16x8 strips share one coarse 16x16
4425 // `left_mode` cell too, so the fallback must not stand in for an absent
4426 // tile-edge neighbour.
4427 let (above_mode, left_mode) =
4428 neighbours.modes_above_left_mi(leaf_mi.0, leaf_mi.1, (above_mode, left_mode));
4429 let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode);
4430 if smooth_neighbor {
4431 hit!(SMOOTH_LUMA_HITS);
4432 }
4433 // The palette-Y mode CDF row is picked by the neighbours' palette use
4434 // (`palette_ctx_and_cache`), so this sub-16x16 leaf must pass its own real
4435 // ctx/cache -- reading `palette_y_mode` off row 0 when a neighbour did use
4436 // a palette narrows the wrong interval and desyncs the tile even when the
4437 // decoded bit is the same. The cell is the 16px-SUB cell containing the
4438 // leaf (the palette neighbour arrays have no finer granularity).
4439 // lane-kf900 r6: the leaf's REAL mi position -- the second leaf of a 16x8
4440 // pair sits 8 px into the 16px cell, and both the cache's superblock-top-row
4441 // exclusion and the neighbour palette lookup itself are mi-granular
4442 // (see [`Neighbours::palette_ctx_and_cache_mi`]).
4443 let pal_at = leaf_mi;
4444 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache_mi(pal_at);
4445 let palette_uv_cache = neighbours.palette_uv_cache_mi(pal_at);
4446 let (
4447 skip,
4448 mode,
4449 angle_delta_y,
4450 uv_mode,
4451 angle_delta_uv,
4452 alpha,
4453 filter_intra,
4454 palette_y,
4455 palette_uv,
4456 intrabc,
4457 ) = read_intra_mode_rect(
4458 dec,
4459 cdfs,
4460 above_mode,
4461 left_mode,
4462 true,
4463 true,
4464 bw,
4465 bh,
4466 enable_filter_intra,
4467 neighbours.skip_txfm_ctx(leaf_mi.0, leaf_mi.1),
4468 allow_screen_content_tools,
4469 Some((palette_ctx, &palette_cache)),
4470 &palette_uv_cache,
4471 leaf_mi.0,
4472 leaf_mi.1,
4473 fctx,
4474 )?;
4475
4476 if let Some((dv_row, dv_col)) = intrabc {
4477 decode_intrabc_rect(
4478 dec,
4479 cdfs,
4480 neighbours,
4481 leaf_mi,
4482 (bw, bh),
4483 skip,
4484 (dv_row, dv_col),
4485 y,
4486 u,
4487 v,
4488 base_q_idx,
4489 fctx,
4490 )?;
4491 return Ok(DC_PRED);
4492 }
4493 // lane-kf900 r4: palette prediction on this shape, the same colour-index
4494 // map -> base colours buffer [`decode_block_rect`] hands each
4495 // `reconstruct_rect` through [`set_palette_pred`].
4496 if palette_y.is_some() || palette_uv.is_some() {
4497 hit!(RECT4_PALETTE_HITS);
4498 }
4499 let palette_y_buf: Option<Vec<u16>> = palette_y
4500 .as_ref()
4501 .map(|p| p.map.iter().map(|&i| p.colors[i as usize]).collect());
4502 let palette_uv_bufs: Option<(Vec<u16>, Vec<u16>)> = palette_uv.as_ref().map(|p| {
4503 (
4504 p.map.iter().map(|&i| p.u_colors[i as usize]).collect(),
4505 p.map.iter().map(|&i| p.v_colors[i as usize]).collect(),
4506 )
4507 });
4508 let (pal_y_size, pal_y_colors) = palette_y
4509 .as_ref()
4510 .map_or((0, [0u16; 8]), |p| (p.size, p.colors));
4511 let (pal_uv_size, pal_uv_colors) = palette_uv
4512 .as_ref()
4513 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
4514 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
4515 eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
4516 }
4517 if filter_intra.is_some() {
4518 // lane-fistrip r1: `predict_filter_intra` already walks its 4x2
4519 // patches over a true `bw`x`bh` block (lane-rectsplit r1), so an
4520 // 8x16/16x8 strip predicts through the same call `reconstruct_rect`
4521 // below already makes; this refusal was square-only prose.
4522 hit!(FILTER_INTRA_RECT_HITS);
4523 hit!(FILTER_INTRA_RECT_SUB16_HITS);
4524 }
4525 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
4526 DC_PRED
4527 } else {
4528 uv_mode
4529 };
4530 // lane-cfl r1, same defect as [`decode_leaf_8x8`]: chroma's intra-edge
4531 // filter type is the NEIGHBOUR's `uv_mode` (libaom `get_filt_type`), not
4532 // a constant `false`.
4533 let smooth_neighbor_uv = neighbours.smooth_uv_neighbour(leaf_mi.0, leaf_mi.1, r, c, fctx);
4534 let depth = if tx_select && !lossless(fctx) {
4535 // lane-t900 r2 (sibling sweep): the in-inter `TXFM_CONTEXT` band read
4536 // every other rect reader now does -- a no-op on a key frame.
4537 // lane-av1mixloss: libaom `read_tx_size`'s first line
4538 // (`decodeframe.c:1203`, `if (xd->lossless[segment_id]) return
4539 // TX_4X4;`) precedes the `TX_MODE_SELECT` test, so a lossless-segment
4540 // rect leaf codes NO depth symbol (`depth_to_tx_wh` clamps to 4x4).
4541 // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours
4542 // read `tx_size_cat1` (rng 55700->49918) where the oracle's next
4543 // read was the leaf's own txb_skip.
4544 let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx);
4545 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
4546 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
4547 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
4548 // count (3), different CDF row: a wrong-table read of a real symbol,
4549 // the class that cost lane-rectsplit r1 its 64x32 depth.
4550 // lane-rect1d r1: the CATEGORY of this leaf is 1, not 2. libaom's
4551 // `bsize_to_tx_size_cat` reads `bsize_to_tx_size_depth_table` and
4552 // subtracts one: BLOCK_16X8/8X16 (and the 1:4 BLOCK_16X4/4X16 this
4553 // function also decodes) sit at depth 2, so they read
4554 // `tx_size_cdf[1]` -- the same table a 16x16 square block reads --
4555 // while `tx_size_cat2` belongs to the 32-level shapes
4556 // ([`decode_block_rect`]). Both tables carry three symbols, so the
4557 // wrong one decodes a plausible depth from the wrong probabilities:
4558 // the range diverges silently at the first such leaf and every later
4559 // symbol in the tile is read from the wrong place (class
4560 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
4561 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
4562 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
4563 eprintln!(
4564 "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
4565 leaf_mi.0,
4566 leaf_mi.1,
4567 dec.debug_state().0
4568 );
4569 }
4570 d
4571 } else {
4572 0
4573 };
4574 // lane-av1-intrabc r3: this leaf's own `set_txfm_ctxs` when the frame reads
4575 // the `TXFM_CONTEXT` bands -- see [`publish_txfm_bands_if_in_inter`].
4576 publish_txfm_bands_if_in_inter(
4577 neighbours,
4578 leaf_mi,
4579 depth_to_tx_wh(bw, bh, depth, fctx),
4580 (bw, bh),
4581 fctx,
4582 );
4583 if depth != 0 || lossless(fctx) {
4584 // The same per-transform-unit walk the bigger strips take
4585 // (`depth_to_tx_wh`: TX_16X8 -> TX_8X8 at depth 1, -> TX_4X4 at
4586 // depth 2), addressed at this leaf's own mi position.
4587 hit!(TX_DEPTH_HITS);
4588 hit!(SUB16_SPLIT_HITS);
4589 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
4590 let modes = RectStripModes {
4591 skip,
4592 mode,
4593 angle_delta_y,
4594 uv_predict_mode,
4595 angle_delta_uv,
4596 alpha,
4597 filter_intra,
4598 smooth_neighbor,
4599 // lane-rectsplitx r3: the split arm hard-coded `false` here while
4600 // the unsplit arm below passes the real neighbour answer -- chroma
4601 // of a tx-split 16x8/8x16 leaf lost its intra-edge filter type.
4602 smooth_neighbor_uv,
4603 palette_y: palette_y_buf.clone(),
4604 palette_uv: palette_uv_bufs.clone(),
4605 };
4606 if palette_y.is_some() || palette_uv.is_some() {
4607 hit!(PALETTE_SPLIT_TX_HITS);
4608 }
4609 decode_rect_split(
4610 dec,
4611 cdfs,
4612 neighbours,
4613 leaf_mi,
4614 bw,
4615 bh,
4616 tx_w,
4617 tx_h,
4618 &modes,
4619 y,
4620 u,
4621 v,
4622 base_q_idx,
4623 reduced_tx_set,
4624 fctx,
4625 )?;
4626 record_strip_palette(
4627 neighbours,
4628 pal_at,
4629 bw,
4630 bh,
4631 pal_y_size,
4632 pal_y_colors,
4633 pal_uv_size,
4634 pal_uv_colors,
4635 );
4636 return Ok(mode);
4637 }
4638 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
4639 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
4640 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
4641 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
4642 let (luma_levels, u_levels, v_levels);
4643 if skip {
4644 luma_levels = Grid::Zero(bw * bh);
4645 u_levels = Grid::Zero(chroma_w * chroma_h);
4646 v_levels = Grid::Zero(chroma_w * chroma_h);
4647 if let Some(b) = &palette_y_buf {
4648 set_palette_pred(b.clone(), fctx);
4649 }
4650 push_intra_rect(
4651 y,
4652 u,
4653 v,
4654 0,
4655 px,
4656 py,
4657 bw,
4658 bh,
4659 mode,
4660 angle_delta_y,
4661 reach,
4662 &luma_levels,
4663 None,
4664 filter_intra,
4665 smooth_neighbor,
4666 fctx,
4667 );
4668 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
4669 if let Some((ub, _)) = &palette_uv_bufs {
4670 set_palette_pred(ub.clone(), fctx);
4671 }
4672 push_intra_rect(
4673 y,
4674 u,
4675 v,
4676 1,
4677 cpx,
4678 cpy,
4679 chroma_w,
4680 chroma_h,
4681 uv_predict_mode,
4682 angle_delta_uv,
4683 reach,
4684 &u_levels,
4685 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
4686 None,
4687 smooth_neighbor_uv,
4688 fctx,
4689 );
4690 if let Some((_, vb)) = &palette_uv_bufs {
4691 set_palette_pred(vb.clone(), fctx);
4692 }
4693 push_intra_rect(
4694 y,
4695 u,
4696 v,
4697 2,
4698 cpx,
4699 cpy,
4700 chroma_w,
4701 chroma_h,
4702 uv_predict_mode,
4703 angle_delta_uv,
4704 reach,
4705 &v_levels,
4706 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
4707 None,
4708 smooth_neighbor_uv,
4709 fctx,
4710 );
4711 } else {
4712 // lane-rectx: a genuine 16x8/8x16 luma transform (`TxbSet::LumaRect16x8`,
4713 // real `EOB_PT_128_LUMA` alphabet + the same mode-indexed `tx_type`
4714 // symbol the square `Luma16` set reads -- `get_ext_tx_set_type`'s
4715 // `use_reduced_set` branch returns `EXT_TX_SET_DTT4_IDTX` at
4716 // `tx_size_sqr_up == TX_16X16` regardless of the true, non-square
4717 // `tx_size`) and its chroma half (8x4/4x8, `TxbSet::ChromaRect8x4`).
4718 // lane-av1-422e: a 4:2:2 strip halves only the width, so the chroma
4719 // half of a 16x8/8x16 luma leaf is an 8x8 SQUARE (`TxbSet::Chroma8` +
4720 // the default scan -- the pairing any 8x8 chroma plane reads). 4:2:0
4721 // halves both axes (8x4/4x8 rect, `TxbSet::ChromaRect8x4`); 4:4:4
4722 // leaves the full 16x8/8x16 rect (`TxbSet::ChromaRect16x8`).
4723 let chroma_422 = ss_x(fctx) == 1 && ss_y(fctx) == 0;
4724 let (luma_scan, chroma_scan): (&[u16], &[u16]) = if ss_x(fctx) == 0 {
4725 if bw == 16 {
4726 (&SCAN_16X8, &SCAN_16X8)
4727 } else {
4728 (&SCAN_8X16, &SCAN_8X16)
4729 }
4730 } else if chroma_422 {
4731 if bw == 16 {
4732 (&SCAN_16X8, default_scan(8))
4733 } else {
4734 (&SCAN_8X16, default_scan(8))
4735 }
4736 } else if bw == 16 {
4737 (&SCAN_16X8, &SCAN_8X4)
4738 } else {
4739 (&SCAN_8X16, &SCAN_4X8)
4740 };
4741 let chroma_rect_set = if ss_x(fctx) == 0 {
4742 TxbSet::ChromaRect16x8
4743 } else if chroma_422 {
4744 TxbSet::Chroma8
4745 } else {
4746 TxbSet::ChromaRect8x4
4747 };
4748 // lane-av1422warp: at ss (1,0) this leaf's chroma is a SQUARE
4749 // (side/2, side) block, so `side` chroma 4-px cells above it spread
4750 // over `side` LUMA mi columns -- one chroma column per PAIR of luma
4751 // mi cells, and both carry the covering unit's whole-unit dc sign.
4752 // The per-mi rect gather therefore double-counts every chroma
4753 // column's sign. `around_mi_422_chroma`'s every-second above-cell
4754 // sampling is libaom's `txb_w_unit` sum, and every other 4:2:2 chroma
4755 // gather in this file already routes through it (see the gate at this
4756 // arm's siblings); this one did not, so a 4:2:2 rect leaf voted over
4757 // luma unit counts. Measured on the pinned 4:2:2 rotzoom stream
4758 // (a1.obu frame 0): the 16x8 leaf at mi(48,28) resolved its V plane's
4759 // dc sign from vote 0 (`dc_sign_cdf[0]`) where the oracle resolves a
4760 // negative vote (`dc_sign_cdf[1]`), which is the first bit-position
4761 // divergence in the frame (the bit offset is a clean constant through
4762 // coefficient unit 1418 and turns 6 bits at 1419). Luma keeps the
4763 // per-mi gather; 4:2:0 and 4:4:4 keep the plain rect walk verbatim.
4764 let mut around = neighbours.around_mi_rect(leaf_mi, bw, bh);
4765 if chroma_422 {
4766 let c = neighbours.around_mi_422_chroma(leaf_mi, bw, bh);
4767 around[1] = c[1];
4768 around[2] = c[2];
4769 }
4770 let luma_set = if reduced_tx_set {
4771 TxbSet::LumaRect16x8
4772 } else {
4773 TxbSet::LumaRect16x8Set1
4774 };
4775 let mut luma_coding = cdfs.txb(luma_set, fi_tx_row(mode, filter_intra));
4776 let (l_levels, luma_tx_type) = read_coeffs_rect(
4777 dec,
4778 &mut luma_coding,
4779 luma_scan,
4780 bw,
4781 bh,
4782 0,
4783 dc_sign_ctx(around[0].2),
4784 TxType::DctDct,
4785 0,
4786 )?;
4787 if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
4788 let nz: Vec<(usize, i32)> = l_levels
4789 .iter()
4790 .copied()
4791 .enumerate()
4792 .filter(|(_, v)| *v != 0)
4793 .collect();
4794 eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
4795 }
4796 luma_levels = l_levels;
4797 let luma_residual = dequant_and_inverse_typed_wh(
4798 &luma_levels,
4799 bw,
4800 bh,
4801 crate::decode::bit_depth(fctx),
4802 block_q_idx(fctx),
4803 plane_q_delta(0, fctx).0,
4804 plane_q_delta(0, fctx).1,
4805 luma_tx_type,
4806 block_iqmatrix(fctx, 0, bw, bh, luma_tx_type),
4807 );
4808 if let Some(b) = &palette_y_buf {
4809 set_palette_pred(b.clone(), fctx);
4810 }
4811 push_intra_rect(
4812 y,
4813 u,
4814 v,
4815 0,
4816 px,
4817 py,
4818 bw,
4819 bh,
4820 mode,
4821 angle_delta_y,
4822 reach,
4823 &luma_residual,
4824 None,
4825 filter_intra,
4826 smooth_neighbor,
4827 fctx,
4828 );
4829 let ac = alpha.map(|_| cfl_src_rect(px, py, bw, bh));
4830 let u_default_tx = default_intra_tx_type(uv_predict_mode as u8);
4831 let u_skip_ctx = usize::from(around[1].0) + usize::from(around[1].1);
4832 let mut u_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
4833 let (u_l, u_tx_type) = read_chroma_coeffs_rect(
4834 dec,
4835 &mut u_coding,
4836 chroma_scan,
4837 chroma_w,
4838 chroma_h,
4839 u_skip_ctx,
4840 dc_sign_ctx(around[1].2),
4841 u_default_tx,
4842 fctx,
4843 1,
4844 )?;
4845 u_levels = u_l;
4846 let u_residual = dequant_and_inverse_typed_wh(
4847 &u_levels,
4848 chroma_w,
4849 chroma_h,
4850 crate::decode::bit_depth(fctx),
4851 block_q_idx(fctx),
4852 plane_q_delta(1, fctx).0,
4853 plane_q_delta(1, fctx).1,
4854 u_tx_type,
4855 block_iqmatrix(fctx, 1, chroma_w, chroma_h, u_tx_type),
4856 );
4857 if let Some((ub, _)) = &palette_uv_bufs {
4858 set_palette_pred(ub.clone(), fctx);
4859 }
4860 push_intra_rect(
4861 y,
4862 u,
4863 v,
4864 1,
4865 cpx,
4866 cpy,
4867 chroma_w,
4868 chroma_h,
4869 uv_predict_mode,
4870 angle_delta_uv,
4871 reach,
4872 &u_residual,
4873 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
4874 None,
4875 smooth_neighbor_uv,
4876 fctx,
4877 );
4878 let v_default_tx = default_intra_tx_type(uv_predict_mode as u8);
4879 let v_skip_ctx = usize::from(around[2].0) + usize::from(around[2].1);
4880 let mut v_coding = cdfs.txb(chroma_rect_set, uv_predict_mode);
4881 let (v_l, v_tx_type) = read_chroma_coeffs_rect(
4882 dec,
4883 &mut v_coding,
4884 chroma_scan,
4885 chroma_w,
4886 chroma_h,
4887 v_skip_ctx,
4888 dc_sign_ctx(around[2].2),
4889 v_default_tx,
4890 fctx,
4891 2,
4892 )?;
4893 v_levels = v_l;
4894 let v_residual = dequant_and_inverse_typed_wh(
4895 &v_levels,
4896 chroma_w,
4897 chroma_h,
4898 crate::decode::bit_depth(fctx),
4899 block_q_idx(fctx),
4900 plane_q_delta(2, fctx).0,
4901 plane_q_delta(2, fctx).1,
4902 v_tx_type,
4903 block_iqmatrix(fctx, 2, chroma_w, chroma_h, v_tx_type),
4904 );
4905 if let Some((_, vb)) = &palette_uv_bufs {
4906 set_palette_pred(vb.clone(), fctx);
4907 }
4908 push_intra_rect(
4909 y,
4910 u,
4911 v,
4912 2,
4913 cpx,
4914 cpy,
4915 chroma_w,
4916 chroma_h,
4917 uv_predict_mode,
4918 angle_delta_uv,
4919 reach,
4920 &v_residual,
4921 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
4922 None,
4923 smooth_neighbor_uv,
4924 fctx,
4925 );
4926 hit!(RECT_LEAF_COEFF_HITS);
4927 }
4928 neighbours.record_mi_rect(
4929 leaf_mi,
4930 bw,
4931 bh,
4932 &[&luma_levels[..], &u_levels[..], &v_levels[..]],
4933 );
4934 neighbours.fill_skip_grid_rect(leaf_mi, mi_w, mi_h, skip);
4935 neighbours.fill_lf_grid_rect(leaf_mi, mi_w, mi_h, bw as u8, bh as u8, 0, fctx);
4936 // The leaf's own palette state (`0` clears, as this site always did
4937 // while a palette leaf refused -- lane-palette2 r8), written on the SPLIT
4938 // AXIS only until the pair's closing leaf: the coarse cell holds one
4939 // entry for both leaves, and leaf 0 zeroing the LEFT one threw away the
4940 // real left neighbour leaf 1 reads (lane-kf900 r4).
4941 record_strip_palette(
4942 neighbours,
4943 pal_at,
4944 bw,
4945 bh,
4946 pal_y_size,
4947 pal_y_colors,
4948 pal_uv_size,
4949 pal_uv_colors,
4950 );
4951 // A rect leaf spans mi_w x mi_h, so its mode reaches several columns and
4952 // rows -- record the whole span, not one cell.
4953 neighbours.record_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, mode);
4954 neighbours.record_uv_mode_mi(leaf_mi.0, leaf_mi.1, mi_w, mi_h, uv_predict_mode);
4955 Ok(mode)
4956}