forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

coeffs.rs4498 lines, 200.4 KiBHistoryRawDownload
1//! Coefficient readers, the Neighbours context state, filter-intra and palette helpers. //! av1split: moved out of `decode/mod.rs`; the items are unchanged apart from visibility. (D20)
2
3use super::*;
4
5/// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each.
6/// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so
7/// nine of them inside the base/sign loops pinned nine sets of values in the
8/// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill
9/// traffic). Out of line, the loop keeps its values in registers and the
10/// trace output is character-for-character what it was.
11#[cold]
12#[inline(never)]
13fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
14 eprintln!(
15 "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
16 );
17}
18
19#[cold]
20#[inline(never)]
21fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
22 eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
23}
24
25#[cold]
26#[inline(never)]
27fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) {
28 eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}");
29}
30
31#[cold]
32#[inline(never)]
33fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) {
34 let (rng, _) = dec.debug_state();
35 eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}");
36}
37
38#[cold]
39#[inline(never)]
40fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) {
41 let (rng, _) = dec.debug_state();
42 eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}");
43}
44
45#[cold]
46#[inline(never)]
47fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) {
48 let (rng, _) = dec.debug_state();
49 eprintln!(
50 "EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}",
51 negative as i32
52 );
53}
54
55#[cold]
56#[inline(never)]
57fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) {
58 let (rng, _) = dec.debug_state();
59 eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
60}
61
62#[cold]
63#[inline(never)]
64fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) {
65 let (rng, _) = dec.debug_state();
66 eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
67}
68
69// lane-ibc444c: see `read_coeffs_rect`'s `#[track_caller]`.
70#[track_caller]
71pub(super) fn read_coeffs(
72 dec: &mut SymbolDecoder,
73 coding: &mut TxbTables,
74 scan: &[u16],
75 skip_ctx: usize,
76 sign_ctx: usize,
77 // The chroma default (spec `Intra_Mode_To_Tx_Type`, see
78 // [`default_intra_tx_type`]) for the sizes where `coding.tx_type` codes
79 // nothing at all; `DctDct` for every luma call and every chroma call at
80 // a size the spec forces to `DCT_DCT` regardless of mode (32-point and
81 // up, `EXT_TX_SET_DCTONLY`) -- the caller already folds that in.
82 default_tx_type: TxType,
83 // `Some((w, h))` with `w != h` when this read is a superblock-level
84 // HORZ/VERT strip's truncated luma corner: the CDF *set* resolves square
85 // (`side`/`coding` above), but `av1_nz_map_ctx_offset`'s position table
86 // is indexed by the real, un-adjusted rectangular shape (lane-sbpart r8
87 // root cause, see [`base_ctx`]). `None` everywhere else -- every other
88 // caller's block genuinely is `side` x `side`.
89 rect_shape: Option<(usize, usize)>,
90) -> Result<(Grid, TxType)> {
91 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
92 let side = coding.side;
93 // lane-av1readcensus: this unit's own entry state, so the census line
94 // carries the pre-read rng and pairs against the oracle's `EC_COEFF`
95 // (which prints `r->ec.rng` before the same `txb_skip` read).
96 let census_entry_rng = dec.debug_state().0;
97 let (census_w, census_h) = rect_shape.unwrap_or((side, side));
98 // lane-av1ibcfork: the per-unit BIT INTERVAL, the twin of the oracle's
99 // `EC_ECDUMP_IN` / `_OUT` / `_END`. The census plane, not a fresh label:
100 // it is the same source `census_unit` reads, so the interval line and the
101 // census line can never disagree about which plane a unit is on.
102 let iv_plane = CENSUS_PLANE.with(|c| c.get()).min(2);
103 let iv_bit = unit_iv_in(iv_plane, census_w, census_h, skip_ctx, dec);
104 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
105 let (range, value) = dec.debug_state();
106 eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
107 }
108 if crate::envflags::env_flag!("EC_ECDUMP_IN") {
109 let (range, value) = dec.debug_state();
110 let bit = dec.debug_bitpos();
111 eprintln!(
112 "EC_ECDUMP_IN side={side} ctx={skip_ctx} dcctx={sign_ctx} ECIN=({value},{range},{bit})"
113 );
114 }
115 let dbg_txbskip = if coeff_trace_on() {
116 coding.txb_skip[skip_ctx]
117 } else {
118 [0; 3]
119 };
120 let sq_bit = if coeff_trace_on() {
121 dec.debug_bitpos()
122 } else {
123 0
124 };
125 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
126 unit_iv_skip(
127 dec, iv_bit, iv_plane, census_w, census_h, skip_ctx, all_zero,
128 );
129 // lane-ibc444c: this reader logs an `all_zero` step even for a read that
130 // consumes ZERO bits, so `post_bit == bit` means "no symbol was read" --
131 // filter on it before pairing anything against the oracle.
132 if crate::envflags::env_flag!("EC_IBCTX") {
133 eprintln!(
134 "EC_IBCTX2 side={} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={sq_bit} at {}",
135 coding.side,
136 std::panic::Location::caller(),
137 );
138 }
139 if coeff_trace_on() {
140 let (rng, _) = dec.debug_state();
141 eprintln!(
142 "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} dcctx={sign_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng} bit={sq_bit} post_bit={}",
143 coding.side,
144 all_zero as i32,
145 dec.debug_bitpos()
146 );
147 }
148 if crate::envflags::env_flag!("EC_AV1_TELL") {
149 eprintln!(
150 "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
151 all_zero as u8,
152 dec.debug_bitpos(),
153 dec.debug_state().0
154 );
155 }
156 if trace {
157 eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
158 }
159 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
160 let (range, value) = dec.debug_state();
161 eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
162 }
163 if all_zero {
164 // lane-coefgrid: the all-zero unit (60% of the 4K segment's) names the
165 // shared zero grid instead of allocating and zeroing its own.
166 census_unit(
167 census_w,
168 census_h,
169 TxType::DctDct,
170 0,
171 true,
172 census_entry_rng,
173 dec,
174 );
175 unit_iv_end(dec, iv_plane, census_w, census_h, skip_ctx);
176 return Ok((Grid::Zero(side * side), TxType::DctDct));
177 }
178 let mut grid = vec![0i32; side * side];
179 let mut tx_type = default_tx_type;
180 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
181 // The CDF row's own width names its set (lane-cdffwd2: extended
182 // past the original two-way intra split once wider `reduced_tx_set
183 // == 0` inter sets joined the table): 17 slots (16 symbols) is
184 // `EXT_TX_SET_ALL16`, 13 (12 symbols) `EXT_TX_SET_DTT9_IDTX_1DDCT`,
185 // 8 (7 symbols) `TX_SET_INTRA_1`, everything else (6 slots, 5
186 // symbols) the reduced `TX_SET_INTRA_2`/`TX_SET_INTER_3` two sets
187 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
188 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
189 let len = tx_type_cdf.len();
190 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
191 eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
192 }
193 crate::msac::SymbolDecoder::set_symr_cdf("tx_type");
194 let t = dec.symbol(tx_type_cdf);
195 crate::census::tx_type(len, t);
196 if coeff_trace_on() {
197 let (rng, _) = dec.debug_state();
198 eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
199 }
200 if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
201 let (range, value) = dec.debug_state();
202 eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
203 }
204 if trace {
205 eprintln!("TRACE tx_type value={t} len={len}");
206 }
207 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
208 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
209 })?;
210 }
211
212 let class = TxClass::of(tx_type);
213 if class != TxClass::TwoD {
214 hit!(TX_CLASS1_HITS);
215 hit!(RECT_CLASS1_HITS);
216 }
217 let eob = read_eob(dec, coding, class);
218 if trace {
219 eprintln!("TRACE eob value={eob}");
220 }
221 let ec_trace_coeff = coeff_trace_on();
222 if ec_trace_coeff {
223 let (rng, _) = dec.debug_state();
224 let cls = match class {
225 TxClass::TwoD => "2d",
226 TxClass::Horiz => "horiz",
227 TxClass::Vert => "vert",
228 };
229 eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
230 }
231 let class_scan;
232 let scan: &[u16] = if class == TxClass::TwoD {
233 scan
234 } else {
235 class_scan = class_scan_table(side, class);
236 &class_scan
237 };
238 // `side` is one of 4/8/16/32 (every `TxbTables` row), so the per-
239 // coefficient `pos / side`, `pos % side` was a hardware divide where a
240 // shift and a mask say the same thing, and the level buffer fits a fixed
241 // 32x32 frame of stack instead of a heap allocation per transform block.
242 debug_assert!(side.is_power_of_two() && side <= 32);
243 let sh = side.trailing_zeros();
244 let col_mask = side - 1;
245 // lane-coef2: padded like libaom's own level buffer (see [`neighbour`]):
246 // `stride = side + 4` columns and four spare rows, so the widest read
247 // `base_ctx` makes -- `(row + 4, col)` / `(row, col + 4)` with
248 // `row, col <= side - 1` -- stays inside `(side + 4) * (side + 4)`, at
249 // most `36 * 36`. Only `col < side`, `row < side` cells are ever written.
250 let stride = side + 4;
251 let mut levels_buf = [0u8; 36 * 36];
252 let levels = &mut levels_buf[..stride * stride];
253 // lane-coefread: the sign pass used to re-walk `scan[..eob]`, redo the
254 // `pos >> sh` / `& mask` decomposition and load the level back out of the
255 // padded frame just to skip the zeros. The base pass already knows both,
256 // so it records `(scan_idx << 4) | level` for each NON-ZERO coefficient
257 // (`scan_idx < 1024`, `level <= 15` -- both loops assert it), and the sign
258 // pass walks that list in reverse (the base pass runs in reverse scan
259 // order, so reversing it is forward scan order: the same coefficients, in
260 // the same order, with the same `c` the trace prints).
261 let mut nz_buf = [0u16; 1024];
262 let mut nz_n = 0usize;
263 let (base_taps, br_taps) = flat_taps(stride, class);
264 for scan_idx in (0..eob).rev() {
265 let pos = scan[scan_idx] as usize;
266 let (row, col) = (pos >> sh, pos & col_mask);
267 let idx = row * stride + col;
268 let level = if scan_idx == eob - 1 {
269 let ctx = eob_coeff_ctx(scan_idx, side * side);
270 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
271 if trace {
272 trace_base_eob(scan_idx, pos, row, col, ctx, v);
273 }
274 v
275 } else {
276 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {
277 if row == 0 && col == 0 {
278 0
279 } else {
280 base_mag(levels, idx, &base_taps)
281 + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
282 }
283 } else {
284 base_ctx(levels, stride, row, col, class, rect_shape)
285 };
286 let v = dec.symbol(&mut coding.base[ctx]) as i32;
287 if ec_trace_coeff {
288 // `pos` in libaom's column-major `coeff_idx` convention, so
289 // the ladder lines up with instrumented `aomdec`.
290 coeff_step_base(dec, scan_idx, col * side + row, ctx, v);
291 }
292 if trace {
293 trace_base(scan_idx, pos, row, col, ctx, v);
294 }
295 v
296 };
297 let level = if level > NUM_BASE_LEVELS {
298 let ctx = {
299 let mag = br_mag(levels, idx, &br_taps);
300 if row == 0 && col == 0 {
301 mag
302 } else {
303 let near_origin = match class {
304 TxClass::TwoD => row < 2 && col < 2,
305 TxClass::Horiz => col == 0,
306 TxClass::Vert => row == 0,
307 };
308 if near_origin { mag + 7 } else { mag + 14 }
309 }
310 };
311 let mut level = level;
312 let mut sent = 0;
313 loop {
314 let k = dec.symbol(&mut coding.br[ctx]) as i32;
315 if ec_trace_coeff {
316 // lane-leaf8tx r3: the `br` rung was missing from THIS
317 // path's trace, so the cross-decoder range ladder was
318 // blind to every base-range symbol and mis-reported the
319 // first divergence (class [[gate-blind-to-feature]]).
320 coeff_step_br(dec, scan_idx, col * side + row, ctx, k);
321 }
322 if trace {
323 trace_br(scan_idx, pos, row, col, ctx, k);
324 }
325 level += k;
326 sent += BR_STEP;
327 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
328 break;
329 }
330 }
331 level
332 } else {
333 level
334 };
335 if ec_trace_coeff && scan_idx == eob - 1 {
336 coeff_step_base_eob_level(dec, level);
337 }
338 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus
339 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is
340 // added in the sign pass below, straight into `grid`), so the context
341 // frame is bytes -- the five-tap sum in [`base_ctx`]/[`br_ctx`] is a
342 // byte gather (lane-coefbuf).
343 debug_assert!((0..=15).contains(&level), "level {level} past the u8 frame");
344 levels[idx] = level as u8;
345 if level != 0 {
346 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
347 nz_n += 1;
348 }
349 }
350 if ec_trace_coeff {
351 let (rng, _) = dec.debug_state();
352 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
353 }
354
355 for &packed in nz_buf[..nz_n].iter().rev() {
356 let c = (packed >> 4) as usize;
357 let pos = scan[c] as usize;
358 let level = (packed & 15) as i32;
359 let negative = if pos == 0 {
360 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
361 if trace {
362 eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
363 }
364 v
365 } else {
366 dec.literal(1) == 1
367 };
368 if ec_trace_coeff {
369 coeff_step_sign(dec, c, negative);
370 }
371 let level = if level > MAX_BR_LEVEL {
372 let g = read_golomb(dec)?;
373 if trace {
374 eprintln!("TRACE golomb pos={pos} value={g}");
375 }
376 level + g as i32
377 } else {
378 level
379 };
380 if ec_trace_coeff {
381 coeff_step_post_golomb(dec, c, level);
382 }
383 grid[pos] = if negative { -level } else { level };
384 }
385 census_unit(
386 census_w,
387 census_h,
388 tx_type,
389 eob,
390 false,
391 census_entry_rng,
392 dec,
393 );
394 unit_iv_end(dec, iv_plane, census_w, census_h, skip_ctx);
395 Ok((Grid::Own(grid), tx_type))
396}
397
398/// [`read_coeffs`] widened to `(w, h)` (lane-rectwire; lane-rectx added the
399/// `tx_type` read [`TxbSet::LumaRect16x8`] needs), restricted to
400/// `TxClass::TwoD` -- the only class any rect size pair this decoder codes
401/// can ever produce, since every `tx_type` this decoder's rect sets can read
402/// (`EXT_TX_SET_DTT4_IDTX`'s five members) is itself 2D: refuses by name
403/// rather than guess-decode if a non-2D class ever shows up here, since
404/// neither `base_ctx_rect`/`br_ctx_rect` nor [`class_scan_table`] have a rect
405/// form for those.
406// lane-ibc444c: `#[track_caller]` so the EC_IBCTX rung below names the CALLER
407// of this reader -- the only thing that identifies a unit's route. No plane is
408// printed here: the plane is the ORACLE's side of the pairing, and a label
409// here is one more thing that can disagree with it.
410#[track_caller]
411// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
412#[allow(clippy::too_many_arguments)]
413pub(super) fn read_coeffs_rect(
414 dec: &mut SymbolDecoder,
415 coding: &mut TxbTables,
416 scan: &[u16],
417 w: usize,
418 h: usize,
419 skip_ctx: usize,
420 sign_ctx: usize,
421 default_tx_type: TxType,
422 // lane-av1chrtx: the plane this unit belongs to (0 luma, 1 U, 2 V) --
423 // printed by the two `EC_COEFF_STEP` traces below, which hardcoded
424 // `plane=0` and so mis-attributed a CHROMA read as a luma one in two
425 // independent lane reports.
426 plane: usize,
427) -> Result<(Grid, TxType)> {
428 let rect_trace = coeff_trace_on();
429 let entry_rng = dec.debug_state().0;
430 // lane-av1readcensus: this reader is handed the real plane (lane-av1chrtx
431 // threaded it in for the `EC_COEFF_STEP` traces), so it stamps the census
432 // plane itself rather than inheriting whichever reader did last. The
433 // luma-only readers (`decode_rect_split`, `decode_block_rect64`,
434 // `read_inter_plane_rect`'s corner) are all plane 0 -- the stamp's initial
435 // value -- and the other plane-owning readers stamp on entry.
436 set_census_plane(plane);
437 let ibctx_on = crate::envflags::env_flag!("EC_IBCTX");
438 let entry_bit = if ibctx_on { dec.debug_bitpos() } else { 0 };
439 let iv_bit = unit_iv_in(plane, w, h, skip_ctx, dec);
440 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
441 unit_iv_skip(dec, iv_bit, plane, w, h, skip_ctx, all_zero);
442 if rect_trace {
443 eprintln!(
444 "EC_COEFF_STEP tag=all_zero plane={plane} ctx={skip_ctx} entry={entry_rng} all_zero={} rng={} bit={entry_bit} post_bit={}",
445 all_zero as i32,
446 dec.debug_state().0,
447 dec.debug_bitpos()
448 );
449 }
450 if ibctx_on {
451 // lane-ibc444c. `bit`/`post_bit` are the STREAM POSITION, not the coder
452 // range: the only collision-free key for pairing this unit against the
453 // oracle's `EC_ECDUMP_IN`. And `post_bit != bit` is how a caller tells
454 // a real symbol read from a 0-bit one -- the SQUARE reader logs a step
455 // either way, which is exactly the artifact that made an earlier
456 // round of this lane claim a false exactness.
457 eprintln!(
458 "EC_IBCTX w={w} h={h} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={entry_bit} post_bit={} at {}",
459 dec.debug_bitpos(),
460 std::panic::Location::caller(),
461 );
462 }
463 if all_zero {
464 census_unit(w, h, TxType::DctDct, 0, true, entry_rng, dec);
465 unit_iv_end(dec, plane, w, h, skip_ctx);
466 return Ok((Grid::Zero(w * h), TxType::DctDct));
467 }
468 let mut grid = vec![0i32; w * h];
469 hit!(RECT_COEFF_TU_HITS);
470 // lane-tx4x8: a 4x8/8x4 luma TU DOES carry a `tx_type` symbol (its set is
471 // `EXT_TX_SET_DTT4_IDTX(_1DDCT)`, `tx_size_sqr_up == TX_8X8`), including
472 // the `V_DCT`/`H_DCT` members whose 1D tx class needs its own scan and
473 // context offsets -- both of which now have rect forms
474 // ([`class_scan_table_wh`], [`base_ctx_rect`]/[`br_ctx_rect`]'s `class`).
475 // The rect sets that carry no symbol at all still pass `None` here.
476 let mut tx_type = default_tx_type;
477 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
478 let len = tx_type_cdf.len();
479 let t = dec.symbol(tx_type_cdf);
480 crate::census::tx_type(len, t);
481 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
482 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
483 })?;
484 if rect_trace {
485 eprintln!(
486 "EC_COEFF_STEP tag=tx_type plane={plane} rng={}",
487 dec.debug_state().0
488 );
489 }
490 }
491 let class = TxClass::of(tx_type);
492 if class != TxClass::TwoD {
493 hit!(TX_CLASS1_HITS);
494 }
495 let eob = read_eob(dec, coding, class);
496 if rect_trace {
497 eprintln!(
498 "EC_COEFF_STEP tag=eob eob={eob} rng={}",
499 dec.debug_state().0
500 );
501 }
502 let class_scan;
503 let scan: &[u16] = if class == TxClass::TwoD {
504 scan
505 } else {
506 class_scan = class_scan_table_wh(w, h, class);
507 &class_scan
508 };
509 // lane-coef2: a heap `vec![0i32; w * h]` per rect transform unit became a
510 // stack frame sized to the unit -- same reasoning as [`read_coeffs`]:
511 // `neighbour_rect` returns 0 outside `(w, h)` and every write is
512 // `levels[pos]` with `pos < w * h`. `w` is a power of two at every AV1
513 // rect size, so the per-coefficient `pos / w`, `pos % w` is a shift and a
514 // mask rather than a hardware divide.
515 let stride = w + 4;
516 let n = stride * (h + 4);
517 if !(w.is_power_of_two() && n <= 36 * 36) {
518 panic!("rect coeff scratch w={w} h={h} n={n}");
519 }
520 let (mut b96, mut b256, mut b768);
521 // Byte levels, same `0..=15` bound [`read_coeffs`] states.
522 let levels: &mut [u8] = if n <= 96 {
523 b96 = [0u8; 96];
524 &mut b96[..n]
525 } else if n <= 256 {
526 b256 = [0u8; 256];
527 &mut b256[..n]
528 } else {
529 b768 = [0u8; 768];
530 &mut b768[..n]
531 };
532 let wsh = w.trailing_zeros();
533 let wmask = w - 1;
534 // lane-coefread: the non-zero list [`read_coeffs`] documents.
535 let mut nz_buf = [0u16; 1024];
536 let mut nz_n = 0usize;
537 let (base_taps, br_taps) = flat_taps(stride, class);
538 let (wlt, wgt) = (w < h, w > h);
539 for scan_idx in (0..eob).rev() {
540 let pos = scan[scan_idx] as usize;
541 let (row, col) = (pos >> wsh, pos & wmask);
542 let idx = row * stride + col;
543 // libaom's column-major `coeff_idx`, for ladder comparison.
544 let _apos = col * h + row;
545 let level = if scan_idx == eob - 1 {
546 let ctx = eob_coeff_ctx(scan_idx, w * h);
547 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
548 // lane-av1oddheightfork2: the `base_eob` rung moved to the end of
549 // the loop body (below). libaom prints its `tag=base_eob` AFTER
550 // that coefficient's own br loop (decodetxb.c:317-338), so the rung
551 // has to carry the POST-br level and rng to be the oracle's twin;
552 // printed here it labelled the pre-br read and every rect unit's
553 // ladder disagreed with aomdec by exactly its br tail.
554 v
555 } else {
556 let ctx = if class == TxClass::TwoD {
557 if row == 0 && col == 0 {
558 0
559 } else {
560 let m = base_mag(levels, idx, &base_taps);
561 if wlt && row < 2 {
562 m + 11
563 } else if wgt && col < 2 {
564 m + 16
565 } else {
566 m + cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize
567 }
568 }
569 } else {
570 base_ctx_rect(levels, stride, w, h, row, col, class)
571 };
572 let v = dec.symbol(&mut coding.base[ctx]) as i32;
573 if rect_trace {
574 eprintln!(
575 "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
576 dec.debug_state().0
577 );
578 }
579 v
580 };
581 let level = if level > NUM_BASE_LEVELS {
582 let ctx = {
583 let mag = br_mag(levels, idx, &br_taps);
584 if row == 0 && col == 0 {
585 mag
586 } else {
587 let near_origin = match class {
588 TxClass::TwoD => row < 2 && col < 2,
589 TxClass::Horiz => col == 0,
590 TxClass::Vert => row == 0,
591 };
592 if near_origin { mag + 7 } else { mag + 14 }
593 }
594 };
595 let mut level = level;
596 let mut sent = 0;
597 loop {
598 let k = dec.symbol(&mut coding.br[ctx]) as i32;
599 if rect_trace {
600 eprintln!(
601 "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
602 dec.debug_state().0
603 );
604 }
605 level += k;
606 sent += BR_STEP;
607 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
608 break;
609 }
610 }
611 level
612 } else {
613 level
614 };
615 debug_assert!((0..=15).contains(&level), "level {level} past the u8 frame");
616 levels[idx] = level as u8;
617 if level != 0 {
618 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
619 nz_n += 1;
620 }
621 if rect_trace && scan_idx == eob - 1 {
622 // the oracle's `tag=base_eob`: POST-br level, POST-br rng, with the
623 // same `get_lower_levels_ctx_eob` ctx (the same `eob_coeff_ctx`).
624 let ctx = eob_coeff_ctx(scan_idx, w * h);
625 let (rng, _) = dec.debug_state();
626 eprintln!(
627 "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={level} rng={rng}"
628 );
629 }
630 }
631 if rect_trace {
632 let (rng, _) = dec.debug_state();
633 eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
634 }
635 for &packed in nz_buf[..nz_n].iter().rev() {
636 let pos = scan[(packed >> 4) as usize] as usize;
637 let level = (packed & 15) as i32;
638 let negative = if pos == 0 {
639 dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
640 } else {
641 dec.literal(1) == 1
642 };
643 if rect_trace {
644 let (rng, _) = dec.debug_state();
645 eprintln!(
646 "EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}",
647 u8::from(negative)
648 );
649 }
650 let level = if level > MAX_BR_LEVEL {
651 let g = read_golomb(dec)?;
652 level + g as i32
653 } else {
654 level
655 };
656 if rect_trace {
657 // lane-av1oddheightfork2: the twin of the square reader's
658 // `coeff_step_post_golomb`. The oracle's `EC_COEFF_STEP
659 // tag=post_golomb` (decodetxb.c, after read_golomb) fires for a RECT
660 // unit exactly as it does for a square one, but this reader had no
661 // rung for it, so every rect unit's ladder was one step short and
662 // the pairing had to guess whether a golomb had been read. This
663 // rung reads no bits: it prints the state after the read it labels.
664 let (rng, _) = dec.debug_state();
665 eprintln!(
666 "EC_COEFF_STEP tag=post_golomb c={} pos={pos} level={level} rng={rng}",
667 (packed >> 4)
668 );
669 }
670 grid[pos] = if negative { -level } else { level };
671 }
672 // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the
673 // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose
674 // grids differ is a reader defect, one whose grids agree is a transform
675 // defect.
676 if crate::envflags::env_flag!("EC_DQCOEFF") {
677 let nz: Vec<String> = grid
678 .iter()
679 .enumerate()
680 .filter(|&(_, &v)| v != 0)
681 .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w))
682 .collect();
683 eprintln!(
684 "OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}",
685 nz.join(",")
686 );
687 }
688 census_unit(w, h, tx_type, eob, false, entry_rng, dec);
689 unit_iv_end(dec, plane, w, h, skip_ctx);
690 Ok((Grid::Own(grid), tx_type))
691}
692
693/// [`read_coeffs_rect`] for a CHROMA plane, carrying the monochrome gate the
694/// [`read_plane`] family already has.
695///
696/// A monochrome frame has `NumPlanes == 1`, so libaom's coefficient loop
697/// (`for (plane = 0; plane < av1_num_planes(cm); ++plane)`) never reaches a
698/// chroma plane: no u/v coefficient symbol is coded, and consuming one moves
699/// the arithmetic decoder off the stream for the rest of the tile. [`read_plane`]
700/// enforces that for every strip that reads its chroma through it, but the rect
701/// strip paths ([`decode_block_rect`], [`decode_leaf_rect`],
702/// [`decode_block_rect4`], [`decode_rect4_16_strip`], [`decode_block_rect64`])
703/// call `read_coeffs_rect` on planes 1/2 DIRECTLY, so each of those sites takes
704/// this gate instead (class `reader-gate-not-on-every-path`). One un-gated
705/// chroma read desyncs at the FIRST rect leaf of the frame and every later
706/// symbol -- and therefore every later pixel -- is decoded from the wrong
707/// place, without ever tripping a refusal (the desynced values stay inside
708/// every coded alphabet).
709// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
710#[allow(clippy::too_many_arguments)]
711pub(super) fn read_chroma_coeffs_rect(
712 dec: &mut SymbolDecoder,
713 coding: &mut TxbTables,
714 scan: &[u16],
715 w: usize,
716 h: usize,
717 skip_ctx: usize,
718 sign_ctx: usize,
719 default_tx_type: TxType,
720 fctx: &crate::decode::FrameCtx,
721 // lane-av1chrtx: the plane index, threaded to `read_coeffs_rect`'s
722 // `EC_COEFF_STEP` traces (they used to print a hardcoded `plane=0`, so a
723 // V-plane read was indistinguishable from a luma one in the log).
724 plane: usize,
725) -> Result<(Grid, TxType)> {
726 if mono(fctx) {
727 return Ok((Grid::Zero(w * h), TxType::DctDct));
728 }
729 read_coeffs_rect(
730 dec,
731 coding,
732 scan,
733 w,
734 h,
735 skip_ctx,
736 sign_ctx,
737 default_tx_type,
738 plane,
739 )
740}
741
742/// What one coded block leaves behind for the blocks that read it as a
743/// neighbour: whether it coded anything at all, and the sign of its DC —
744/// [`crate::tile`]'s own private `Neighbour`.
745#[derive(Clone, Copy, Default)]
746pub(super) struct Neighbour {
747 /// The transform unit's cumulative coefficient level (spec `cul_level`,
748 /// `decodetxb.c`'s `read_coeffs_txb`): the sum of every coded level's
749 /// magnitude, clamped to `COEFF_CONTEXT_MASK` (7). A plain "coded or not"
750 /// boolean (`level != 0`) is enough for every context this decoder read
751 /// until now, but the *luma* `txb_skip_ctx` of a transform unit smaller
752 /// than its own block (`TxMode::Select`, spec `get_txb_ctx_general`)
753 /// needs the actual magnitude tier of its above/left neighbours, not
754 /// just whether they coded anything.
755 pub(super) level: u8,
756 pub(super) dc: Option<bool>,
757}
758
759/// `dst[start .. start + n] = v`, with the same per-cell bounds behaviour the
760/// per-4x4-cell `get_mut` loops it replaces had: a cell past the end of the
761/// grid is dropped, never a panic. One `memset` per grid row instead of a
762/// bounds check per cell (lane-mi) -- the index span a row of a mi rect covers
763/// is contiguous, so this writes exactly the cells the cell loop did,
764/// including the ones a `mi_c + cc` past `skip_grid_cols_mi` folded into the
765/// next row.
766#[inline]
767pub(super) fn fill_span<T: Copy>(dst: &mut [T], start: usize, n: usize, v: T) {
768 let end = (start + n).min(dst.len());
769 if start < end {
770 dst[start..end].fill(v);
771 }
772}
773
774pub(super) fn neighbour_state(grid: &[i32]) -> Neighbour {
775 // lane-coefgrid: the shared zero grid sums to zero by construction; this
776 // sum has no early exit, so the 60% of units that code nothing used to
777 // walk their whole grid here.
778 if is_zero_grid(grid) {
779 return Neighbour::default();
780 }
781 let cul: u32 = grid.iter().map(|&l| l.unsigned_abs()).sum();
782 Neighbour {
783 level: cul.min(7) as u8,
784 dc: (grid[0] != 0).then_some(grid[0] < 0),
785 }
786}
787
788/// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
789/// transform unit smaller than the block it sits in): `top`/`left` are the
790/// above/left neighbours' magnitude tiers, each already clamped to 4.
791pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [
792 [1, 2, 2, 2, 3],
793 [2, 4, 4, 4, 5],
794 [2, 4, 4, 4, 5],
795 [2, 4, 4, 4, 5],
796 [3, 5, 5, 5, 6],
797];
798
799/// The `skip` flag, its written-instrument bit, and the covering coded
800/// block's origin and dims, packed into ONE 8-byte cell (lane-publish): the
801/// four maps are written together by `Neighbours::fill_skip_grid_rect` and by
802/// nothing else, so a block's row is one fill instead of four, and the
803/// deblocker's `pu_edge` reads origin and dims off one cache line.
804#[derive(Clone, Copy)]
805pub(super) struct BlkCell {
806 pub(super) skip: bool,
807 pub(super) written: bool,
808 pub(super) org: [u16; 2],
809 pub(super) dim: [u8; 2],
810}
811
812/// The neighbour state a block's contexts are read from — a duplicate of
813/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
814/// territory this round), kept at the same two granularities the real writer
815/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
816/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
817/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
818/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
819/// chroma transform straddling the true, odd-sized frame edge see its
820/// neighbour's state clamped at its own subsampled edge rather than luma's.
821#[derive(Clone)]
822pub(super) struct Neighbours {
823 pub(super) above: Vec<[Neighbour; 3]>,
824 pub(super) left: Vec<[Neighbour; 3]>,
825 pub(super) above_mode: Vec<usize>,
826 pub(super) left_mode: Vec<usize>,
827 /// Chroma's own `uv_mode` companion to `above_mode`/`left_mode` (lane-chroma
828 /// r3): a smooth/paeth `uv_mode`'s edge-filter strength (spec
829 /// `get_intra_edge_filter_type`) reads the CHROMA neighbour's mode, not the
830 /// luma one -- the same block can (and often does) code a different
831 /// `uv_mode` than its own `mode`. Coarse [`SUB`]-grid like `above_mode`;
832 /// [`Self::decode_leaf8`]'s per-leaf `prev_leaf` override (a real
833 /// within-block neighbour finer than this grid) is luma-only -- a known,
834 /// unexercised-by-gate corner-cut (every real-encoder gate in `stream.rs`
835 /// uses `--min-partition-size=16`, so no leaf8 8x8 split ever reaches this).
836 pub(super) above_uv_mode: Vec<usize>,
837 pub(super) left_uv_mode: Vec<usize>,
838 pub(super) above_side: Vec<usize>,
839 pub(super) left_side: Vec<usize>,
840 /// The same as `above_side`/`left_side`, but kept at the finer mi (4x4)
841 /// granularity `above`/`left` are, rather than [`SUB`] -- [`crate::tile`]'s
842 /// `above_side_mi`/`left_side_mi`: two 8x8 leaves of one straddling 16x16
843 /// block (lane-av1-rect) share a single [`SUB`]-grid cell, so a coarse
844 /// array cannot tell the second leaf's partition symbol that the first
845 /// one was coded at 8x8.
846 /// lane-publish2: `u8` (a block side is at most 128 px, and so is
847 /// [`NO_NEIGHBOUR_SIDE`]) -- every block stamps these per mi.
848 pub(super) above_side_mi: Vec<u8>,
849 pub(super) left_side_mi: Vec<u8>,
850 /// The luma `mode` of the last `BLOCK_4X4` leaf decoded at each mi column
851 /// / row, with the mi position it was written at
852 /// (`(usize::MAX, _)` = never written). `above_mode`/`left_mode` are on
853 /// the coarse 16x16 grid, which cannot distinguish the two 4x4 leaves an
854 /// 8x8 `PARTITION_SPLIT` puts in one mi column; libaom's intra-mode
855 /// context reads `mi(row, col-1)`/`mi(row-1, col)` exactly, so a sub-8x8
856 /// leaf whose neighbour is another split group needs that group's leaf 3
857 /// (bottom-right), not the leaf the coarse slot happens to hold. Written
858 /// and read only by [`decode_leaf_split4`]; the position guard makes it
859 /// fall back to the coarse slot whenever the real neighbour was a block
860 /// of 8x8 or larger (whose one mode is correct for every row it spans).
861 /// lane-publish2: `(mi position, mode)` narrowed from `(usize, usize)` to
862 /// `(u16, u8)` -- every block stamps these mi-granular maps, and 16 bytes
863 /// per mi per side of publish traffic was pure width. `u16::MAX` is the
864 /// "never written" sentinel (an mi index cannot reach it: AV1's largest
865 /// frame is 65536 px = 16384 mi).
866 pub(super) sub8_mode_col: Vec<(u16, u8)>,
867 pub(super) sub8_mode_row: Vec<(u16, u8)>,
868 /// The `uv_mode` twin of `sub8_mode_col`/`sub8_mode_row` (lane-sub8 r5):
869 /// chroma's edge-filter type reads the CHROMA neighbour's `uv_mode`
870 /// (`get_intra_edge_filter_type`, reconintra.c:974), and the coarse
871 /// [`SUB`] slots cannot name it once a 16x16 is split into 8x8 leaves --
872 /// the leaf above writes the same row slot the block to the left owns.
873 pub(super) uv_mode_col: Vec<(u16, u8)>,
874 pub(super) uv_mode_row: Vec<(u16, u8)>,
875 /// Every mi cell's own `uv_mode`, the mi grid libaom's
876 /// `chroma_above_mbmi`/`chroma_left_mbmi` read directly (`set_mi_row_col`,
877 /// blockd.h). lane-t900 r12: the one-slot-per-column
878 /// `uv_mode_col`/`uv_mode_row` maps above hold only the LAST block written
879 /// in that column, so a sub-8x8 pair's own first (non-chroma-ref) half
880 /// overwrote the row the pair's chroma-ref half then wanted to read --
881 /// the mi-exact match failed and the coarse [`SUB`] band answered instead.
882 /// `u8::MAX` = no block has written this cell yet (fall back to the maps).
883 pub(super) uv_mode_grid: Vec<u8>,
884 /// [`Self::uv_mode_grid`]'s stride, in mi units (superblock-padded, like
885 /// every other band here).
886 pub(super) uv_grid_cols: usize,
887 /// lane-av1leftwit: which BLOCK wrote each cell of [`Self::uv_mode_grid`],
888 /// as `(epoch << 24) | (mi_r << 12) | mi_c` of the writing block's own
889 /// top-left mi. The `uv_mode` value alone cannot answer "are the two cells
890 /// the `+ss_y` read compares written by the same block?", which is the
891 /// whole question the `+ss_y` term turns on: the term is only observable
892 /// when the left neighbour is 1 mi tall, i.e. when the cell this decoder
893 /// used to read and the cell libaom reads hold DIFFERENT blocks. `epoch`
894 /// is [`UV_OWNER_EPOCH`], bumped once per tile, so a cell no block wrote
895 /// in this tile can never be mistaken for a written one.
896 pub(super) uv_owner: Vec<u32>,
897 /// Whether the block above/left of this column/row was coded `skip` --
898 /// an inter frame's own `skip` context (spec `SkipContext`), which the
899 /// key-frame writer never tracks (its skip context is always zero); a
900 /// duplicate of [`crate::tile`]'s private `Neighbours::above_skip`/
901 /// `left_skip`.
902 pub(super) above_skip: Vec<bool>,
903 pub(super) left_skip: Vec<bool>,
904 /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), at
905 /// 4x4 mi granularity: the transform *width* (above) / *height* (left) in
906 /// pixels last written over each unit by `set_txfm_ctxs`/
907 /// `txfm_partition_update`, which is what an inter block's `txfm_split`
908 /// symbol reads its context from (lane-txselect, spec 5.11.17).
909 /// [`TXFM_CTX_INIT`] until a block writes one; a fresh full-height `left`
910 /// array is exactly libaom's per-superblock-row reset, since each mi row
911 /// is only ever visited inside one superblock row.
912 pub(super) above_txfm: Vec<u8>,
913 pub(super) left_txfm: Vec<u8>,
914 /// Whether the block above/left of this column/row coded `skip_mode`
915 /// (spec 5.11.23) -- `av1_get_skip_mode_context`'s own neighbour lookup,
916 /// lane-av1comp round 14.
917 pub(super) above_skip_mode: Vec<bool>,
918 pub(super) left_skip_mode: Vec<bool>,
919 /// Whether the block above/left was coded inter -- the `is_inter`
920 /// context (spec `av1_get_intra_inter_context`), a duplicate of
921 /// [`crate::tile`]'s private `Neighbours::above_inter`/`left_inter`.
922 pub(super) above_inter: Vec<bool>,
923 pub(super) left_inter: Vec<bool>,
924 /// The actual reference frame (`1..=7`, spec's `MV_REFERENCE_FRAME`
925 /// alphabet) the block above/left of this column/row coded, or `-1` for
926 /// an intra neighbour/frame border -- the `single_ref_p1`..`p6` context
927 /// functions (`mvstack::ref_ctx` family) need the real reference, not
928 /// just "was it inter" (lane-av1refs: every inter block used to be
929 /// `LAST_FRAME` by construction, so `above_inter`/`left_inter` alone was
930 /// enough).
931 pub(super) above_ref: Vec<i8>,
932 pub(super) left_ref: Vec<i8>,
933 /// The block above/left's *second* reference frame when it was coded
934 /// compound (spec `RefFrames[1]`), or `None` for single-ref/intra --
935 /// lane-av1comp: `mvstack::reference_mode_ctx`/`comp_reference_type_ctx`
936 /// need a full [`crate::mvstack::NeighbourRef`], not just `above_ref`'s
937 /// `i8`, once a compound `read_ref_frames` lands.
938 /// lane-publish2 audit: the "always `None` today" note this doc used to
939 /// carry is long stale -- compound blocks do occur, and
940 /// [`Self::record_compound_ctx_rect_mi`] stamps the real second reference
941 /// over their span right after [`Self::record_inter_rect_mi`]'s reset.
942 /// The array IS read: `single_ref_p*`/`comp_ref` contexts and every
943 /// [`crate::mvstack::NeighbourRef`] construction (class
944 /// [[branch-dropped-as-unreachable]] -- the note, not the code, was wrong).
945 pub(super) above_ref1: Vec<Option<i8>>,
946 pub(super) left_ref1: Vec<Option<i8>>,
947 /// The precomputed `get_comp_group_idx_context`/`get_comp_index_context`
948 /// neighbour contribution (spec 5.11.25, libaom `pred_common.h`):
949 /// a compound neighbour's own `comp_group_idx`/`compound_idx` bit, or
950 /// the "ref_frame[0] == ALTREF_FRAME" special case (`3`/`1`) for a
951 /// single-ref one, or `0` for intra/unavailable -- lane-av1comp.
952 pub(super) above_comp_group_idx: Vec<u8>,
953 pub(super) left_comp_group_idx: Vec<u8>,
954 pub(super) above_compound_idx: Vec<u8>,
955 pub(super) left_compound_idx: Vec<u8>,
956 /// `interp_filter[0]`/`[1]` (horizontal/vertical kernel index, 0..=2, or
957 /// `3` = "no info": an intra neighbour or the frame's own border) of the
958 /// block above/left of this column/row -- spec
959 /// `av1_get_pred_context_switchable_interp`'s own neighbour lookup.
960 pub(super) above_filter: Vec<[u8; 2]>,
961 pub(super) left_filter: Vec<[u8; 2]>,
962 pub(super) mi_cols: usize,
963 pub(super) mi_rows: usize,
964 /// Per-8x8 (2x2 mi cells) `skip_txfm` flag over the whole padded frame,
965 /// spec `av1_cdef_compute_sb_list`'s `is_8x8_block_skip`: CDEF (spec
966 /// 7.15) never filters an 8x8 luma block whose covering coded block read
967 /// `skip` -- one flag per 4x4 mi cell (finer than needed, but matches the
968 /// grain [`Self::record_mi`] already writes at), read back at 8x8
969 /// granularity by [`apply_cdef`] since `skip` is constant across every
970 /// mi cell one coded block covers.
971 /// The four per-mi maps [`Neighbours::blk_grid`] packs, in one cell.
972 /// lane-cdefstrip r1 instrument: whether any coded block actually WROTE
973 /// the `skip` bit at this mi cell during this frame. A fresh
974 /// `Neighbours` seeds `skip_grid` all-`false` ("not skip"), so a decode
975 /// arm that forgets [`Self::fill_skip_grid_rect`] silently makes
976 /// [`apply_cdef`] filter an 8x8 unit libaom's `is_8x8_block_skip`
977 /// (`cdef.c:29-38`) excludes -- exactly the lane-cdef defect, and
978 /// unobservable from the pixels alone. Counted by
979 /// [`cdef_unwritten_skip_units`].
980 /// Per-4x4-mi origin `(mi_row, mi_col)` of the coded (prediction) block
981 /// covering that cell -- spec 7.14.2's `isBlockEdge`/libaom `pu_edge`,
982 /// which re-enables the loop filter at a prediction boundary between two
983 /// skipped inter blocks (lane-mergefix r4). Written by
984 /// [`Self::fill_skip_grid_rect`], whose `at_mi` IS that origin.
985 /// Per-4x4-mi `(width, height)` in mi units of the coded block covering
986 /// that cell -- the other half of `pu_edge`: libaom tests the edge
987 /// coordinate against the block's size in the FILTERED plane's own
988 /// pixels, which for chroma is `max(luma_dim / 2, 4)` (lane-t900 r30b).
989 pub(super) blk_grid: Vec<BlkCell>,
990 pub(super) skip_grid_cols_mi: usize,
991 /// Per-4x4-mi `is_inter_block` of the coded block COVERING that cell --
992 /// lane-av1txctxband. libaom's `get_tx_size_context`
993 /// (`av1/common/pred_common.h:361-370`) gates its "an inter neighbour
994 /// contributes its own BLOCK size" override on `xd->above_mbmi` /
995 /// `xd->left_mbmi`, which `set_mi_offsets` takes as `xd->mi[-mi_stride]`
996 /// / `xd->mi[-1]`: the block whose bottom (left) edge abuts THIS block's
997 /// top (right) edge at THIS cell. `setup_mbs` (`decodeframe.c:355-361`)
998 /// writes that pointer into EVERY mi cell a block covers, so libaom's
999 /// granularity is the covering block PER CELL -- not one slot per column.
1000 /// [`Self::above_inter`]/[`Self::left_inter`] are per-COLUMN bands holding
1001 /// the LAST block written in that column, which is the covering block only
1002 /// for the block immediately below it: on a 4:4:4 lossy `--sb-size=128`
1003 /// cq-62 stream the 8x4 intra leaf at mi(57,52) read `above_inter` as
1004 /// `true` (stale, from an intrabc block earlier in column 52) with
1005 /// `above_side_mi` 4, took the override, and read `tx_size_cat0[1]` where
1006 /// libaom reads row 2 -- the `EC_SYMR` fork at read 32813.
1007 /// Written by exactly the three places that already write the bands:
1008 /// [`Self::record_inter_rect_mi`], `record_intrabc_mi_rect` and
1009 /// `fill_lf_grid_rect`'s intra-only clear.
1010 pub(super) inter_grid: Vec<bool>,
1011 /// Per-4x4-mi luma transform width in pixels (8/16/32/64) -- this decoder
1012 /// never splits a coded block's transform below its own size (round 2:
1013 /// `TxMode::Select`/`tx_depth` refused), so a block's own side *is* its
1014 /// transform size, spec 7.14's `get_transform_size`/`get_filter_level`
1015 /// edge-length lookup (`apply_deblock`).
1016 pub(super) tx_grid: Vec<u8>,
1017 /// The transform HEIGHT companion to [`Self::tx_grid`]'s width --
1018 /// lane-rect r2: TX_32X16/TX_16X32 strips deblock their horizontal
1019 /// edges by tx height (spec 7.14.2 `set_lpf_parameters` dir==VERT).
1020 pub(super) tx_h_grid: Vec<u8>,
1021 /// Per-4x4-mi CHROMA transform width/height in pixels -- lane-tiny r4.
1022 /// A block's chroma transform is `av1_get_max_uv_txsize(bsize)`: the
1023 /// largest transform covering the subsampled BLOCK, capped at 32x32. It
1024 /// does NOT follow luma's `tx_depth` split, so deriving it as
1025 /// `tx_grid / 2` invented chroma transform edges the deblocker then
1026 /// filtered (32x16 frames, U plane, seeds 42/47). Written from the
1027 /// block's own mi span in [`Self::fill_lf_grid_rect`], the one place
1028 /// every caller routes through.
1029 pub(super) uv_tx_grid: Vec<u8>,
1030 pub(super) uv_tx_h_grid: Vec<u8>,
1031 /// Per-4x4-mi reference frame (`0` = intra, magnitude `1..=7` =
1032 /// `MV_REFERENCE_FRAME`, negative = that reference coded as `GLOBALMV` --
1033 /// `lf_level`'s `mode_lf_lut` row 0, lane-av1golden2)
1034 /// -- the loop filter's ref/mode delta lookup (spec 7.14.4
1035 /// `get_filter_level`, `loop_filter_ref_deltas[ref_frame]`; lane-av1refs:
1036 /// widened from a bare `is_inter` bool, which collapsed every non-`LAST`
1037 /// reference onto `LAST_FRAME`'s own delta).
1038 pub(super) ref_grid: Vec<i8>,
1039 /// Per-4x4-mi snapshot of [`CURRENT_DELTA_LF`] at the moment this cell's
1040 /// block was decoded (spec `DeltaLF[i]`, `i` in `0..FRAME_LF_COUNT`,
1041 /// Y-vertical/Y-horizontal/U/V) -- lane-realworld r5: `lf_level`'s
1042 /// per-block additive term, mirroring [`Self::ref_grid`]'s own snapshot
1043 /// pattern. `!delta_lf_multi` mode broadcasts index 0 into all 4 slots
1044 /// at write time ([`Self::fill_lf_grid_rect`]) so a reader never needs
1045 /// to know which mode produced the value.
1046 pub(super) delta_lf_grid: Vec<[i8; 4]>,
1047 /// The block above/left's own palette-Y size (0 = not a palette block)
1048 /// and its base colours -- `av1_get_palette_mode_ctx`/
1049 /// `av1_get_palette_cache` (pred_common.c)'s neighbour lookup, lane-palette
1050 /// r2. UV has no equivalent yet (stage 2, unreconstructed).
1051 pub(super) above_palette_size: Vec<u8>,
1052 pub(super) left_palette_size: Vec<u8>,
1053 pub(super) above_palette_colors: Vec<[u16; 8]>,
1054 pub(super) left_palette_colors: Vec<[u16; 8]>,
1055 /// As the four fields above, for the neighbour's own chroma (U-channel
1056 /// only -- `av1_get_palette_cache`'s plane-1 lookup, [`Self::palette_uv_cache`])
1057 /// palette size/colours (lane-palette2 r1).
1058 pub(super) above_palette_uv_size: Vec<u8>,
1059 pub(super) left_palette_uv_size: Vec<u8>,
1060 pub(super) above_palette_uv_colors: Vec<[u16; 8]>,
1061 pub(super) left_palette_uv_colors: Vec<[u16; 8]>,
1062 /// This tile's own top-left corner, in 4x4 mode-info units (spec
1063 /// `MiRowStart`/`MiColStart`) -- lane-tiles: every "is there really a
1064 /// neighbour" check compares against this instead of literal `0`, since a
1065 /// block at the tile's own top/left edge has no usable neighbour even
1066 /// though a decoded block sits there in the picture (spec `decode_tile`'s
1067 /// per-tile `clear_above_context`/`left_available`/`up_available`).
1068 /// `0` for a single-tile frame, matching every existing caller exactly.
1069 pub(super) tile_row0_mi: usize,
1070 pub(super) tile_col0_mi: usize,
1071}
1072
1073#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1074impl Neighbours {
1075 /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
1076 /// true (unpadded) size in 4x4 mode-info units.
1077 pub(super) fn new(
1078 cols: usize,
1079 rows: usize,
1080 mi_cols: usize,
1081 mi_rows: usize,
1082 fctx: &crate::decode::FrameCtx,
1083 ) -> Self {
1084 // lane-sb128c r7: a 128x64 block at the bottom frame edge records its
1085 // neighbour state over the whole 64-row extent, past the frame's last
1086 // mi row (mi_rows 198, block rows 192..208). libaom's own context
1087 // buffers are superblock-aligned for exactly that reason
1088 // (`av1_alloc_context_buffers` rounds to `MAX_MIB_SIZE`), so pad the
1089 // side arrays to a superblock multiple and leave those cells unread --
1090 // every availability check uses the true `mi_rows`/`mi_cols` below.
1091 let sb_sub = (sb_mi_cur(fctx) as usize) / (SUB / MI);
1092 let (cols, rows) = (cols.next_multiple_of(sb_sub), rows.next_multiple_of(sb_sub));
1093 Self {
1094 above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
1095 left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
1096 above_mode: vec![DC_PRED; cols],
1097 left_mode: vec![DC_PRED; rows],
1098 above_uv_mode: vec![DC_PRED; cols],
1099 left_uv_mode: vec![DC_PRED; rows],
1100 above_side: vec![NO_NEIGHBOUR_SIDE; cols],
1101 left_side: vec![NO_NEIGHBOUR_SIDE; rows],
1102 above_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; cols * (SUB / MI)],
1103 left_side_mi: vec![NO_NEIGHBOUR_SIDE as u8; rows * (SUB / MI)],
1104 sub8_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
1105 sub8_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
1106 uv_mode_col: vec![(u16::MAX, 0); cols * (SUB / MI)],
1107 uv_mode_row: vec![(u16::MAX, 0); rows * (SUB / MI)],
1108 uv_mode_grid: vec![u8::MAX; cols * (SUB / MI) * rows * (SUB / MI)],
1109 uv_grid_cols: cols * (SUB / MI),
1110 uv_owner: vec![0; cols * (SUB / MI) * rows * (SUB / MI)],
1111 above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
1112 left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
1113 // lane-inter8 r2: mi(4px)-granular, not [`SUB`]-granular -- an
1114 // 8x8 inter leaf's left neighbour is the OTHER leaf row of the
1115 // 16x16 block beside it, which a SUB-grid slot cannot name
1116 // (class context-read-from-one-cell).
1117 above_skip: vec![false; cols * (SUB / MI)],
1118 left_skip: vec![false; rows * (SUB / MI)],
1119 above_skip_mode: vec![false; cols * (SUB / MI)],
1120 left_skip_mode: vec![false; rows * (SUB / MI)],
1121 above_inter: vec![false; cols * (SUB / MI)],
1122 left_inter: vec![false; rows * (SUB / MI)],
1123 above_ref: vec![-1; cols * (SUB / MI)],
1124 left_ref: vec![-1; rows * (SUB / MI)],
1125 above_ref1: vec![None; cols * (SUB / MI)],
1126 left_ref1: vec![None; rows * (SUB / MI)],
1127 above_comp_group_idx: vec![0; cols * (SUB / MI)],
1128 left_comp_group_idx: vec![0; rows * (SUB / MI)],
1129 above_compound_idx: vec![0; cols * (SUB / MI)],
1130 left_compound_idx: vec![0; rows * (SUB / MI)],
1131 above_filter: vec![[3u8; 2]; cols * (SUB / MI)],
1132 left_filter: vec![[3u8; 2]; rows * (SUB / MI)],
1133 mi_cols,
1134 mi_rows,
1135 blk_grid: vec![
1136 BlkCell {
1137 skip: false,
1138 written: false,
1139 org: [0; 2],
1140 dim: [1; 2]
1141 };
1142 cols * (SUB / MI) * rows * (SUB / MI)
1143 ],
1144 skip_grid_cols_mi: cols * (SUB / MI),
1145 inter_grid: vec![false; cols * (SUB / MI) * rows * (SUB / MI)],
1146 tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
1147 tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
1148 uv_tx_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
1149 uv_tx_h_grid: vec![0u8; cols * (SUB / MI) * rows * (SUB / MI)],
1150 ref_grid: vec![0i8; cols * (SUB / MI) * rows * (SUB / MI)],
1151 delta_lf_grid: vec![[0i8; 4]; cols * (SUB / MI) * rows * (SUB / MI)],
1152 above_palette_size: vec![0; cols * (SUB / MI)],
1153 left_palette_size: vec![0; rows * (SUB / MI)],
1154 above_palette_colors: vec![[0u16; 8]; cols * (SUB / MI)],
1155 left_palette_colors: vec![[0u16; 8]; rows * (SUB / MI)],
1156 above_palette_uv_size: vec![0; cols * (SUB / MI)],
1157 left_palette_uv_size: vec![0; rows * (SUB / MI)],
1158 above_palette_uv_colors: vec![[0u16; 8]; cols * (SUB / MI)],
1159 left_palette_uv_colors: vec![[0u16; 8]; rows * (SUB / MI)],
1160 tile_row0_mi: 0,
1161 tile_col0_mi: 0,
1162 }
1163 }
1164
1165 /// spec `decode_tile`'s per-tile reset: `clear_above_context` over this
1166 /// tile's own column span (`col1_mi` exclusive), plus recording
1167 /// `(row0_mi, col0_mi)` as the tile's own top-left mi cell for every
1168 /// availability check below. Left context resets every superblock row
1169 /// regardless of tile ([`Self::start_row`], already called once per SB
1170 /// row by every caller) so it needs no tile-specific reset here.
1171 pub(super) fn start_tile(
1172 &mut self,
1173 row0_mi: usize,
1174 col0_mi: usize,
1175 col1_mi: usize,
1176 fctx: &crate::decode::FrameCtx,
1177 ) {
1178 // lane-seg: `AvailU`/`AvailL` for the segment-id neighbour prediction
1179 // are tile-relative, same as every other neighbour lookup here.
1180 fctx.seg_tile_origin.with(|c| c.set((row0_mi, col0_mi)));
1181 // lane-av1leftwit: a fresh epoch stamps every `uv_owner` cell this
1182 // tile writes, so the `+ss_y` read's "different block?" probe never
1183 // compares against a cell a previous tile left behind.
1184 UV_OWNER_EPOCH.with(|c| c.set(c.get().wrapping_add(1) | (1 << 24)));
1185 self.tile_row0_mi = row0_mi;
1186 self.tile_col0_mi = col0_mi;
1187 let end = col1_mi.min(self.above.len());
1188 for i in col0_mi.min(end)..end {
1189 self.above[i] = Default::default();
1190 self.above_side_mi[i] = NO_NEIGHBOUR_SIDE as u8;
1191 }
1192 let (sc0, sc1) = (
1193 col0_mi / (SUB / MI),
1194 (col1_mi / (SUB / MI)).min(self.above_mode.len()),
1195 );
1196 for i in sc0.min(sc1)..sc1 {
1197 self.above_mode[i] = DC_PRED;
1198 self.above_side[i] = NO_NEIGHBOUR_SIDE;
1199 }
1200 // lane-inter8 r2: the inter bands are mi-granular, so they reset over
1201 // the tile's own mi column span directly.
1202 let mend = col1_mi.min(self.above_skip.len());
1203 for i in col0_mi.min(mend)..mend {
1204 self.above_skip[i] = false;
1205 self.above_skip_mode[i] = false;
1206 self.above_inter[i] = false;
1207 self.above_ref[i] = -1;
1208 self.above_ref1[i] = None;
1209 self.above_comp_group_idx[i] = 0;
1210 self.above_compound_idx[i] = 0;
1211 self.above_filter[i] = [3u8; 2];
1212 }
1213 // lane-sub8 r6: the mi-granular column maps are per tile too -- a
1214 // stale `(row, mode)` from the tile to the LEFT names an mi row this
1215 // tile's first block would read as its own above neighbour.
1216 let mcol_end = col1_mi.min(self.sub8_mode_col.len());
1217 for i in col0_mi.min(mcol_end)..mcol_end {
1218 self.sub8_mode_col[i] = (u16::MAX, 0);
1219 self.uv_mode_col[i] = (u16::MAX, 0);
1220 }
1221 // lane-mergefix r2: `av1_zero_above_context` also memsets the txfm row
1222 // over the tile's own column span (to `tx_size_wide[TX_SIZES_LARGEST]`,
1223 // not zero) -- without it a second tile column reads the first one's
1224 // resolved transform sizes as its own above context.
1225 let tend = col1_mi.min(self.above_txfm.len());
1226 for i in col0_mi.min(tend)..tend {
1227 self.above_txfm[i] = TXFM_CTX_INIT;
1228 }
1229 }
1230
1231 /// Writes a just-decoded block's own palette-Y size/colours (`size == 0`
1232 /// for a non-palette block, clearing any stale neighbour state) into every
1233 /// [`SUB`]-grid cell it covers on both the above and left edges --
1234 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
1235 /// call sites are all square blocks).
1236 pub(super) fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
1237 self.record_palette_y_rect(
1238 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
1239 side,
1240 side,
1241 size,
1242 colors,
1243 );
1244 }
1245
1246 /// [`Self::record_palette_y`] with independent above (`w`)/left (`h`)
1247 /// extents (lane-palette2 r4, mirrors [`Self::record_rect`] vs
1248 /// [`Self::record`]): a true rect strip's above/left neighbour spans
1249 /// differ.
1250 pub(super) fn record_palette_y_rect(
1251 &mut self,
1252 mi: (usize, usize),
1253 w: usize,
1254 h: usize,
1255 size: usize,
1256 colors: [u16; 8],
1257 ) {
1258 let (r, c) = mi;
1259 if crate::envflags::env_flag!("EC_PALPUB") {
1260 eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
1261 }
1262 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
1263 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
1264 // cell immediately left of the block, not its 16px [`SUB`] cell. The
1265 // old SUB grid let a 16x8 strip pair share one slot, so the second
1266 // strip of mi(0,8) read the FIRST strip's palette size and the colour
1267 // cache came out one entry short (class [[context-read-from-one-cell]]).
1268 for cell in 0..(w / MI).max(1) {
1269 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
1270 *e = size as u8;
1271 // lane-publish2: spec 5.11.46 `get_palette_cache` reads a
1272 // neighbour's colours only where its palette size > 0, so a
1273 // non-palette block need not stamp 16 bytes of zeroes here.
1274 if size > 0 {
1275 self.above_palette_colors[c + cell] = colors;
1276 }
1277 }
1278 }
1279 for cell in 0..(h / MI).max(1) {
1280 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
1281 *e = size as u8;
1282 if size > 0 {
1283 self.left_palette_colors[r + cell] = colors;
1284 }
1285 }
1286 }
1287 }
1288
1289 /// `av1_get_palette_mode_ctx` (pred_common.h:197): count of the above/left
1290 /// neighbours that are themselves a palette-Y block, plus
1291 /// `av1_get_palette_cache`'s own merged, ascending, deduplicated colour
1292 /// cache (pred_common.c:73).
1293 ///
1294 /// The SB-top-row exclusion of the above neighbour (`row % 64` in
1295 /// pred_common.c:76, `r % 4 == 0` here in [`SUB`]-grid units) belongs to
1296 /// the CACHE ALONE -- `av1_get_palette_mode_ctx` reads plain
1297 /// `xd->above_mbmi` with no such guard (lane-palette2 r7). Applying it to
1298 /// the ctx too made every superblock in the frame's second SB row read
1299 /// `palette_y_mode` off CDF row 0 while libaom used row 1, so a real
1300 /// palette block decoded as "no palette" and the tile desynced from
1301 /// there (class [[cdf-row-held-constant]]).
1302 pub(super) fn palette_ctx_and_cache(&self, at: (usize, usize)) -> (usize, Vec<u16>) {
1303 self.palette_ctx_and_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
1304 }
1305
1306 /// [`Self::palette_ctx_and_cache`] with the block's REAL mi row, which a
1307 /// 1:4 strip does not share with its [`SUB`] cell: `av1_get_palette_cache`
1308 /// drops the above neighbour on a 64-px superblock boundary
1309 /// (pred_common.c:76, `row % (1 << MIN_SB_SIZE_LOG2)` with `row` the
1310 /// block's own PIXEL row), and strip 1 of a HORZ_4 sits 8 px into the
1311 /// cell -- reading `at.0 % 4` there excludes strip 0 from the cache of
1312 /// every strip in an SB's top cell row, which libaom does not do.
1313 pub(super) fn palette_ctx_and_cache_mi(&self, mi: (usize, usize)) -> (usize, Vec<u16>) {
1314 let (r, c) = mi;
1315 let above_ok = r % 16 != 0;
1316 // `xd->above_mbmi` exists for every row but the tile's own first.
1317 let above_is_palette = r > self.tile_row0_mi && self.above_palette_size[c] > 0;
1318 let (above_n, above_colors) = if above_ok && self.above_palette_size[c] > 0 {
1319 (
1320 usize::from(self.above_palette_size[c]),
1321 self.above_palette_colors[c],
1322 )
1323 } else {
1324 (0, [0u16; 8])
1325 };
1326 // lane-tiles r11: `av1_get_palette_cache` takes `xd->left_mbmi`, which
1327 // is NULL whenever the block sits at its TILE's own left column
1328 // (`left_available`), not the frame's -- without this guard a second
1329 // tile column reads the previous tile's palette colours into its cache
1330 // and its `palette_y_mode` ctx.
1331 let left_ok = c > self.tile_col0_mi;
1332 let (left_n, left_colors) = if left_ok && self.left_palette_size[r] > 0 {
1333 (
1334 usize::from(self.left_palette_size[r]),
1335 self.left_palette_colors[r],
1336 )
1337 } else {
1338 (0, [0u16; 8])
1339 };
1340 let ctx = usize::from(above_is_palette) + usize::from(left_n > 0);
1341 let mut cache = Vec::with_capacity(16);
1342 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
1343 if cache.last() != Some(&v) {
1344 cache.push(v);
1345 }
1346 };
1347 let (mut ai, mut li) = (0usize, 0usize);
1348 while ai < above_n && li < left_n {
1349 let (va, vl) = (above_colors[ai], left_colors[li]);
1350 if vl < va {
1351 push_dedup(&mut cache, vl);
1352 li += 1;
1353 } else {
1354 push_dedup(&mut cache, va);
1355 ai += 1;
1356 if vl == va {
1357 li += 1;
1358 }
1359 }
1360 }
1361 while ai < above_n {
1362 push_dedup(&mut cache, above_colors[ai]);
1363 ai += 1;
1364 }
1365 while li < left_n {
1366 push_dedup(&mut cache, left_colors[li]);
1367 li += 1;
1368 }
1369 (ctx, cache)
1370 }
1371
1372 /// As [`Self::record_palette_y`], for a just-decoded block's own chroma
1373 /// (U-channel) palette size/colours -- `size == 0` clears stale state the
1374 /// same way (lane-palette2 r1).
1375 pub(super) fn record_palette_uv(
1376 &mut self,
1377 at: (usize, usize),
1378 side: usize,
1379 size: usize,
1380 colors: [u16; 8],
1381 ) {
1382 self.record_palette_uv_rect(
1383 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
1384 side,
1385 side,
1386 size,
1387 colors,
1388 );
1389 }
1390
1391 /// [`Self::record_palette_uv`] with independent above (`w`)/left (`h`)
1392 /// extents, in LUMA pixels (lane-palette2 r4, same convention as
1393 /// [`Self::record_palette_y_rect`] -- the above/left grids are indexed at
1394 /// luma resolution regardless of which plane the recorded state is for).
1395 pub(super) fn record_palette_uv_rect(
1396 &mut self,
1397 mi: (usize, usize),
1398 w: usize,
1399 h: usize,
1400 size: usize,
1401 colors: [u16; 8],
1402 ) {
1403 let (r, c) = mi;
1404 // mi granularity, see [`Self::record_palette_y_rect`].
1405 for cell in 0..(w / MI).max(1) {
1406 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
1407 *e = size as u8;
1408 if size > 0 {
1409 self.above_palette_uv_colors[c + cell] = colors;
1410 }
1411 }
1412 }
1413 for cell in 0..(h / MI).max(1) {
1414 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
1415 *e = size as u8;
1416 if size > 0 {
1417 self.left_palette_uv_colors[r + cell] = colors;
1418 }
1419 }
1420 }
1421 }
1422
1423 /// [`Self::palette_ctx_and_cache`]'s cache half, for the U channel
1424 /// (`av1_get_palette_cache(xd, 1, cache)`) -- `palette_uv_mode_ctx` needs
1425 /// no neighbour lookup at all (it is this block's own just-decided Y
1426 /// palette use, `read_palette_mode_info`'s `pmi->palette_size[0] > 0`),
1427 /// so only the cache is wanted here.
1428 pub(super) fn palette_uv_cache(&self, at: (usize, usize)) -> Vec<u16> {
1429 self.palette_uv_cache_mi((at.0 * (SUB / MI), at.1 * (SUB / MI)))
1430 }
1431
1432 /// [`Self::palette_uv_cache`] with the block's real mi row -- see
1433 /// [`Self::palette_ctx_and_cache_mi`].
1434 pub(super) fn palette_uv_cache_mi(&self, mi: (usize, usize)) -> Vec<u16> {
1435 let (r, c) = mi;
1436 let above_ok = r % 16 != 0;
1437 let (above_n, above_colors) = if above_ok && self.above_palette_uv_size[c] > 0 {
1438 (
1439 usize::from(self.above_palette_uv_size[c]),
1440 self.above_palette_uv_colors[c],
1441 )
1442 } else {
1443 (0, [0u16; 8])
1444 };
1445 // Same tile-relative left availability as the luma cache above.
1446 let left_ok = c > self.tile_col0_mi;
1447 let (left_n, left_colors) = if left_ok && self.left_palette_uv_size[r] > 0 {
1448 (
1449 usize::from(self.left_palette_uv_size[r]),
1450 self.left_palette_uv_colors[r],
1451 )
1452 } else {
1453 (0, [0u16; 8])
1454 };
1455 let mut cache = Vec::with_capacity(16);
1456 let push_dedup = |cache: &mut Vec<u16>, v: u16| {
1457 if cache.last() != Some(&v) {
1458 cache.push(v);
1459 }
1460 };
1461 let (mut ai, mut li) = (0usize, 0usize);
1462 while ai < above_n && li < left_n {
1463 let (va, vl) = (above_colors[ai], left_colors[li]);
1464 if vl < va {
1465 push_dedup(&mut cache, vl);
1466 li += 1;
1467 } else {
1468 push_dedup(&mut cache, va);
1469 ai += 1;
1470 if vl == va {
1471 li += 1;
1472 }
1473 }
1474 }
1475 while ai < above_n {
1476 push_dedup(&mut cache, above_colors[ai]);
1477 ai += 1;
1478 }
1479 while li < left_n {
1480 push_dedup(&mut cache, left_colors[li]);
1481 li += 1;
1482 }
1483 cache
1484 }
1485
1486 /// Marks every 4x4 mi cell a just-decoded coded block covers with its own
1487 /// transform width (in pixels) and `is_inter` flag -- the loop filter's
1488 /// per-edge lookup (`apply_deblock`), filled at the same call sites and
1489 /// units as [`Self::fill_skip_grid`].
1490 pub(super) fn fill_lf_grid(
1491 &mut self,
1492 at_mi: (usize, usize),
1493 side_mi: usize,
1494 tx_px: u8,
1495 ref_frame: i8,
1496 fctx: &crate::decode::FrameCtx,
1497 ) {
1498 self.fill_lf_grid_rect(at_mi, side_mi, side_mi, tx_px, tx_px, ref_frame, fctx);
1499 }
1500
1501 /// [`Self::fill_lf_grid`] with independent row/col extents -- lane-partitions
1502 /// r1: a true rectangular strip's mi span isn't `side_mi` square (`w_mi`
1503 /// != `h_mi`); `tx_px` still names a single scalar (this decoder's
1504 /// existing corner-cut, `Neighbours::tx_grid`'s own doc comment -- a
1505 /// rectangular strip's transform is `TX_32X16`/`TX_16X32`, not tracked
1506 /// per-axis, matching lane-warp r5's `HORZ_B` top-strip precedent).
1507 /// libaom `set_one_param_for_line_luma`/`_chroma`: an edge that is a
1508 /// transform-unit edge but NOT a prediction-unit edge is not filtered when
1509 /// `curr_skipped = mbmi->skip_txfm && is_inter_block(mbmi)`. Widening this
1510 /// block's published transform extent to its own size is exactly that
1511 /// suppression for the deblocker's `x0 % tx != 0` test -- the only shape
1512 /// that needs it is the 128 root, whose chroma extent is the one
1513 /// [`Self::fill_lf_grid_rect`]'s TX_32X32 cap narrows. An INTRA block is
1514 /// never suppressed (libaom's `is_inter_block` term), so this is called
1515 /// only from the skipped-inter branch.
1516 ///
1517 /// The extent is the block's own CHROMA footprint, `w_mi * MI >> ss_x` per
1518 /// axis -- `av1_setup_dst_planes`'s `get_plane_block_size(bsize, ss_x,
1519 /// ss_y)` (`common_data.c:38`, which at ss (0,0) is BLOCK_128X128
1520 /// itself, so 128 and not 64). This used to be a hardcoded `w_mi * MI / 2`,
1521 /// correct at 4:2:0 by the `>> 1 == / 2` identity and half the truth at
1522 /// 4:4:4; lane-av1txsizeaudit r2 replaced it with the per-axis shift, the
1523 /// form its sibling `fill_lf_grid_rect` already used. The `fctx` is
1524 /// threaded in for it: `Neighbours` carries no subsampling of its own, so
1525 /// no format guard was possible inside this method until now.
1526 ///
1527 /// **MEASURED INERT, and do not go looking for a pixel regression.** The
1528 /// widening defeats the deblocker's alignment gate (`x0 & (tx - 1)`), but
1529 /// every edge it lets through then meets the SAME libaom rule applied at
1530 /// the correct place, `edge_params_body`'s spec-7.14.2 / libaom
1531 /// `set_lpf_parameters` term `!pu_edge && cur_ref != 0 && pv_ref != 0 &&
1532 /// skip_at && skip_at`. Inside one skipped block both cells are that same
1533 /// block, so all four terms hold and the edge dies there too. The masking
1534 /// is TOTAL, not incidental: this method is only ever called for a block
1535 /// that is itself skipped, so no input exists on which one side of an
1536 /// internal edge is not skipped. Measured over 26 frames / 2 555 904
1537 /// samples across five 4:4:4 `--sb-size=128` streams that fire this arm
1538 /// 30 times: `64` and `128` both decode pixel-exact against aomdec, and
1539 /// differ from each other in not one sample. The gate for this value is
1540 /// therefore a source scan, not a pixel gate --
1541 /// `refusal_inventory::the_skipped_128_root_chroma_suppression_publishes_the_blocks_own_per_axis_chroma_extent`.
1542 pub(super) fn suppress_internal_lf_edges(
1543 &mut self,
1544 at_mi: (usize, usize),
1545 w_mi: usize,
1546 h_mi: usize,
1547 fctx: &FrameCtx,
1548 ) {
1549 let (mi_r, mi_c) = at_mi;
1550 let (uv_w, uv_h) = (
1551 ((w_mi * MI) >> ss_x(fctx)).max(4) as u8,
1552 ((h_mi * MI) >> ss_y(fctx)).max(4) as u8,
1553 );
1554 for rr in 0..h_mi {
1555 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
1556 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_w);
1557 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_h);
1558 }
1559 }
1560
1561 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1562 #[allow(clippy::too_many_arguments)]
1563 pub(super) fn fill_lf_grid_rect(
1564 &mut self,
1565 at_mi: (usize, usize),
1566 w_mi: usize,
1567 h_mi: usize,
1568 tx_px: u8,
1569 tx_h_px: u8,
1570 ref_frame: i8,
1571 fctx: &crate::decode::FrameCtx,
1572 ) {
1573 self.fill_lf_grid_rect_inner(at_mi, w_mi, h_mi, tx_px, tx_h_px, ref_frame, true, fctx)
1574 }
1575
1576 /// [`Self::fill_lf_grid_rect`] for a block whose transform tree ALREADY
1577 /// published its own `TXFM_CONTEXT` bands -- every body that ran
1578 /// [`read_block_tx_size_rect`] / [`read_block_tx_size`] / an inline
1579 /// var-tx tree of its own.
1580 ///
1581 /// libaom's `parse_decode_block` (`decodeframe.c:1227-1236`) is an
1582 /// EITHER/OR: the var-tx branch calls `read_tx_size_vartx`, which
1583 /// publishes through `txfm_partition_update` PER LEAF
1584 /// (`av1_common_int.h:1684-1695`) and never calls `set_txfm_ctxs`; the
1585 /// `else` branch calls `read_tx_size` + `set_txfm_ctxs` exactly once, over
1586 /// the whole block. So on the var-tx path there is NO whole-footprint
1587 /// publish to reproduce, and one written here is not merely redundant --
1588 /// it OVERWRITES the leaves' sizes with the block's own.
1589 ///
1590 /// lane-av1oddheightfork3, measured on the pinned
1591 /// `420_oddheight_320x236.obu` (then diverging: Y 234349 / U 56957 /
1592 /// V 52981, 0/16 frames; byte-exact since this lane): the INTRABC 8x16
1593 /// block at mi(44,58) split into two 8x8
1594 /// leaves, whose per-leaf writes put `8` into `left_txfm[44..48]`, and
1595 /// this publish then put the BLOCK's `16` back over those same four
1596 /// cells. The next block, the INTRABC 8x16 at mi(44,60), read
1597 /// `txfm_partition_context` with `left = 16` where libaom has `8` (the
1598 /// `above` operand agreed at 8 on both sides, printed by the oracle rung
1599 /// `EC_VARTXCTX` in `scripts/instrument-aom-oracle.sh`), took ctx 12
1600 /// against libaom's 13, decoded `is_split = 0` against libaom's `1`, and
1601 /// read no children against libaom's two -- the frame's first divergent
1602 /// read.
1603 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1604 #[allow(clippy::too_many_arguments)]
1605 pub(super) fn fill_lf_grid_rect_after_vartx(
1606 &mut self,
1607 at_mi: (usize, usize),
1608 w_mi: usize,
1609 h_mi: usize,
1610 tx_px: u8,
1611 tx_h_px: u8,
1612 ref_frame: i8,
1613 fctx: &crate::decode::FrameCtx,
1614 ) {
1615 self.fill_lf_grid_rect_inner(at_mi, w_mi, h_mi, tx_px, tx_h_px, ref_frame, false, fctx)
1616 }
1617
1618 #[allow(clippy::too_many_arguments)]
1619 pub(super) fn fill_lf_grid_rect_inner(
1620 &mut self,
1621 at_mi: (usize, usize),
1622 w_mi: usize,
1623 h_mi: usize,
1624 tx_px: u8,
1625 tx_h_px: u8,
1626 ref_frame: i8,
1627 publish_txfm_bands: bool,
1628 fctx: &crate::decode::FrameCtx,
1629 ) {
1630 let (mi_r, mi_c) = at_mi;
1631 // `av1_get_max_uv_txsize` under 4:2:0: the block's chroma extent is
1632 // half its luma one (min 4 px, the smallest transform), capped at
1633 // TX_32X32 -- independent of this block's luma `tx_depth`.
1634 let uv_tx_w = ((w_mi * MI) >> ss_x(fctx)).clamp(4, 32) as u8;
1635 let uv_tx_h = ((h_mi * MI) >> ss_y(fctx)).clamp(4, 32) as u8;
1636 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
1637 eprintln!(
1638 "EC_LFGRID mi_row={mi_r} mi_col={mi_c} w_mi={w_mi} h_mi={h_mi} tx_px={tx_px} tx_h_px={tx_h_px}"
1639 );
1640 }
1641 crate::census::tx(tx_px, tx_h_px);
1642 let cur = fctx.current_delta_lf.with(|c| c.get());
1643 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
1644 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
1645 } else {
1646 [cur[0].clamp(-63, 63) as i8; 4]
1647 };
1648 for rr in 0..h_mi {
1649 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
1650 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
1651 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
1652 fill_span(&mut self.uv_tx_grid, start, w_mi, uv_tx_w);
1653 fill_span(&mut self.uv_tx_h_grid, start, w_mi, uv_tx_h);
1654 fill_span(&mut self.ref_grid, start, w_mi, ref_frame);
1655 fill_span(&mut self.delta_lf_grid, start, w_mi, snapshot);
1656 }
1657 if publish_txfm_bands && fctx.intra_only.with(std::cell::Cell::get) {
1658 // libaom's `parse_decode_block` runs `set_txfm_ctxs(mbmi->tx_size,
1659 // xd->width, xd->height, mbmi->skip_txfm && is_inter_block(mbmi),
1660 // xd)` for EVERY block, an intra-only frame's included, and
1661 // `get_tx_size_context` / `txfm_partition_context` read those two
1662 // `TXFM_CONTEXT` bands. This grid carries the same transform size
1663 // over the same footprint, so the publish is this write: the
1664 // `skip && is_inter` term is 0 for every intra-only block that is
1665 // not an intrabc one, and the bodies that can code an intrabc
1666 // block publish their own (the term is then the BLOCK size, a value
1667 // this grid cannot express -- see `decode_block`/`decode_leaf8`).
1668 // Inter frames publish at their own sites and are excluded here
1669 // because their skipped-block term needs the block size too.
1670 txfm_partition_update_rect(
1671 self,
1672 at_mi,
1673 (tx_px as usize, tx_h_px as usize),
1674 (w_mi * MI, h_mi * MI),
1675 );
1676 // libaom `is_inter_block` counts an INTRABC block (`blockd.h:373`),
1677 // so `get_tx_size_context` reads an intrabc NEIGHBOUR's block size
1678 // instead of its transform band. Every block stamps its own cells
1679 // here; the intrabc bodies re-stamp theirs `true` afterwards
1680 // (`record_intrabc_inter_bands`).
1681 for i in 0..w_mi {
1682 if let Some(cell) = self.above_inter.get_mut(mi_c + i) {
1683 *cell = false;
1684 }
1685 }
1686 for i in 0..h_mi {
1687 if let Some(cell) = self.left_inter.get_mut(mi_r + i) {
1688 *cell = false;
1689 }
1690 }
1691 // lane-av1txctxband: the same clear at libaom's own per-CELL
1692 // granularity. The band above clears one slot per column, so a
1693 // block that covered column 52 and a later block in the SAME
1694 // column but a different row leave the band describing whichever
1695 // wrote last; the grid clears exactly the cells this block owns.
1696 self.mark_inter_grid_rect(at_mi, w_mi, h_mi, false);
1697 }
1698 // lane-av1-intrabc r4: publish this coded block's own mi footprint
1699 // into the intrabc MV grid's block-COVERAGE map -- every coded block,
1700 // not just the intrabc ones. A later intrabc block's DV predictor is
1701 // built by libaom's own row/col scans over `xd->mi[]`, which holds an
1702 // `MB_MODE_INFO` for EVERY block and steps by
1703 // `mi_size_wide/height[candidate->bsize]`; without this footprint a
1704 // non-intrabc neighbour reads as uncovered and the scan advances it
1705 // by one cell instead of by its real width.
1706 fctx.intrabc_mi_grid.with(|g| {
1707 if let Some((grid, _, _)) = g.borrow_mut().as_mut() {
1708 grid.cover_rect(mi_r, mi_c, w_mi, h_mi);
1709 }
1710 });
1711 }
1712
1713 /// One var-tx / split-tx LEAF's own LUMA transform dims over its mi span.
1714 /// libaom `get_transform_size` (av1_loopfilter.c:207) applies the split
1715 /// override only `if ((plane == AOM_PLANE_Y) && ...)` -- chroma keeps
1716 /// `av1_get_max_uv_txsize(mbmi->bsize)`, the whole BLOCK's uv transform.
1717 /// Routing a leaf through [`Self::fill_lf_grid_rect`] recomputed the uv
1718 /// dims from the LEAF span and so invented chroma transform edges the
1719 /// deblocker then filtered (lane-golomb r6). `ref_grid`/`delta_lf_grid`
1720 /// are already correct from the block's own fill over the same span.
1721 pub(super) fn fill_lf_grid_leaf_luma(
1722 &mut self,
1723 at_mi: (usize, usize),
1724 w_mi: usize,
1725 h_mi: usize,
1726 tx_px: u8,
1727 tx_h_px: u8,
1728 ) {
1729 let (mi_r, mi_c) = at_mi;
1730 if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
1731 eprintln!(
1732 "EC_LFLEAF mi_row={mi_r} mi_col={mi_c} w_mi={w_mi} h_mi={h_mi} tx_px={tx_px} tx_h_px={tx_h_px}"
1733 );
1734 }
1735 for rr in 0..h_mi {
1736 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
1737 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
1738 fill_span(&mut self.tx_h_grid, start, w_mi, tx_h_px);
1739 }
1740 }
1741
1742 /// Marks every 4x4 mi cell a just-decoded coded block covers with its
1743 /// `skip` flag -- `at_mi`/`side_mi` are the block's own position and
1744 /// width/height in 4x4 mode-info units (mirroring [`Self::record_mi`]'s
1745 /// own units, not [`Self::record`]'s [`SUB`]-grid ones).
1746 pub(super) fn fill_skip_grid(&mut self, at_mi: (usize, usize), side_mi: usize, skip: bool) {
1747 self.fill_skip_grid_rect(at_mi, side_mi, side_mi, skip);
1748 }
1749
1750 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
1751 pub(super) fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
1752 let (mi_r, mi_c) = at_mi;
1753 if skip && w_mi != h_mi {
1754 hit!(RECT_SKIP_BAND_HITS);
1755 }
1756 // lane-census: an INTRA frame's blocks never reach the inter
1757 // publisher, and this one is what every coded block writes.
1758 crate::census::block_intra_frame(w_mi, h_mi, skip);
1759 for rr in 0..h_mi {
1760 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
1761 fill_span(
1762 &mut self.blk_grid,
1763 start,
1764 w_mi,
1765 BlkCell {
1766 skip,
1767 written: true,
1768 org: [mi_r as u16, mi_c as u16],
1769 dim: [w_mi as u8, h_mi as u8],
1770 },
1771 );
1772 }
1773 }
1774 /// Publishes one coded block's `is_inter_block` over EVERY 4x4 mi cell it
1775 /// covers -- lane-av1txctxband. libaom's `setup_mbs`
1776 /// (`decodeframe.c:355-361`) writes the block's own `MB_MODE_INFO`
1777 /// pointer into all of them, so `xd->mi[-xd->mi_stride]` /
1778 /// `xd->mi[-1]` name the block COVERING the cell, not "the last block
1779 /// written in this column" ([`Self::above_inter`] /
1780 /// [`Self::left_inter`], which is a per-column band and therefore stale
1781 /// for any block below the last writer in its column).
1782 /// Separate from [`Self::fill_skip_grid_rect`] because the two publishers
1783 /// run in BOTH orders at different call sites; both write disjoint fields,
1784 /// so the order does not matter. The value read is libaom's
1785 /// `is_inter_block` (`blockd.h:372-374`): an INTRABC block counts.
1786 pub(super) fn mark_inter_grid_rect(
1787 &mut self,
1788 at_mi: (usize, usize),
1789 w_mi: usize,
1790 h_mi: usize,
1791 is_inter: bool,
1792 ) {
1793 for rr in 0..h_mi {
1794 let start = (at_mi.0 + rr) * self.skip_grid_cols_mi + at_mi.1;
1795 fill_span(&mut self.inter_grid, start, w_mi, is_inter);
1796 }
1797 }
1798
1799 /// `is_inter_block` of the coded block covering the mi cell
1800 /// `(mi_r, mi_c)`, or `false` for a cell no block has written yet (a tile
1801 /// border or a not-yet-decoded cell) -- lane-av1txctxband. The caller's
1802 /// `up_available` / `left_available` guard already excludes the borders.
1803 pub(super) fn inter_at(&self, mi_r: usize, mi_c: usize) -> bool {
1804 self.inter_grid
1805 .get(mi_r * self.skip_grid_cols_mi + mi_c)
1806 .copied()
1807 .unwrap_or(false)
1808 }
1809
1810 /// The covering block's own `(block_size_wide, block_size_high)` in
1811 /// pixels at the mi cell `(mi_r, mi_c)`, from [`Self::blk_grid`]'s `dim`
1812 /// (the published mi extent) scaled by [`MI`] -- lane-av1txctxband. This
1813 /// is libaom's `block_size_wide[above_mbmi->bsize]` /
1814 /// `block_size_high[left_mbmi->bsize]`, read at the abutting CELL rather
1815 /// than from the per-column [`Self::above_side_mi`] /
1816 /// [`Self::left_side_mi`] band.
1817 pub(super) fn blk_side_at(&self, mi_r: usize, mi_c: usize) -> (usize, usize) {
1818 self.blk_grid
1819 .get(mi_r * self.skip_grid_cols_mi + mi_c)
1820 .filter(|c| c.written)
1821 .map_or((0, 0), |c| (c.dim[0] as usize * MI, c.dim[1] as usize * MI))
1822 }
1823
1824 /// Whether the 8x8 luma block at mi position `(mi_r, mi_c)` (2x2 mi
1825 /// cells) was `skip_txfm` -- [`apply_cdef`]'s dlist membership test.
1826 /// Spec/libaom `is_8x8_block_skip` requires *every* one of the four 4x4
1827 /// mi cells the 8x8 covers to be skip (a smaller-than-8x8 partition can
1828 /// straddle the region with a mix of skip/non-skip blocks).
1829 /// A single 4x4 mi cell's own `skip` flag, unaggregated (unlike
1830 /// [`Self::is_skip_txfm`]'s 8x8 all-four-cells rule) -- what the loop
1831 /// filter's `curr_skipped`/`pv_skip_txfm` (spec 7.14.2) want, since a
1832 /// filtered edge's two sides are each exactly one coded block wide.
1833 pub(super) fn skip_at(&self, mi_r: usize, mi_c: usize) -> bool {
1834 self.blk_grid
1835 .get(mi_r * self.skip_grid_cols_mi + mi_c)
1836 .is_some_and(|c| c.skip)
1837 }
1838
1839 /// The `skip_txfm` context of a block whose top-left mi cell is
1840 /// `(mi_r, mi_c)`: libaom `av1_get_skip_txfm_context`
1841 /// (`pred_common.h:175-181`) is `above_mi->skip_txfm + left_mi->skip_txfm`,
1842 /// with an absent neighbour contributing 0. The mi grid is per tile, so
1843 /// row/column 0 is a tile edge and has no neighbour on that axis.
1844 pub(super) fn skip_txfm_ctx(&self, mi_r: usize, mi_c: usize) -> usize {
1845 usize::from(mi_r > self.tile_row0_mi && self.skip_at(mi_r - 1, mi_c))
1846 + usize::from(mi_c > self.tile_col0_mi && self.skip_at(mi_r, mi_c - 1))
1847 }
1848
1849 pub(super) fn is_skip_txfm(&self, mi_r: usize, mi_c: usize) -> bool {
1850 (0..2).all(|rr| {
1851 (0..2).all(|cc| {
1852 self.blk_grid
1853 .get((mi_r + rr) * self.skip_grid_cols_mi + (mi_c + cc))
1854 .is_some_and(|c| c.skip)
1855 })
1856 })
1857 }
1858
1859 pub(super) fn start_row(&mut self) {
1860 self.left.iter_mut().for_each(|l| *l = Default::default());
1861 self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
1862 self.left_uv_mode.iter_mut().for_each(|m| *m = DC_PRED);
1863 self.left_side
1864 .iter_mut()
1865 .for_each(|s| *s = NO_NEIGHBOUR_SIDE);
1866 self.left_side_mi
1867 .iter_mut()
1868 .for_each(|s| *s = NO_NEIGHBOUR_SIDE as u8);
1869 self.left_skip.iter_mut().for_each(|s| *s = false);
1870 self.left_skip_mode.iter_mut().for_each(|s| *s = false);
1871 self.left_inter.iter_mut().for_each(|i| *i = false);
1872 self.left_ref.iter_mut().for_each(|r| *r = -1);
1873 self.left_ref1.iter_mut().for_each(|r| *r = None);
1874 self.left_comp_group_idx.iter_mut().for_each(|r| *r = 0);
1875 self.left_compound_idx.iter_mut().for_each(|r| *r = 0);
1876 self.left_filter.iter_mut().for_each(|f| *f = [3u8; 2]);
1877 // lane-sub8 r6: mi-granular row maps reset with the rest of the left
1878 // context (a tile/SB-row boundary has no left neighbour).
1879 self.sub8_mode_row
1880 .iter_mut()
1881 .for_each(|s| *s = (u16::MAX, 0));
1882 self.uv_mode_row.iter_mut().for_each(|s| *s = (u16::MAX, 0));
1883 // lane-tiles r11 (COMMON's NEIGHBOUR MAPS rule): the palette side bands
1884 // are per-mi maps like every other one here, so they reset with the
1885 // row too -- the left guard above is what actually stops a cross-tile
1886 // read, this keeps a stale colour out of the arrays at all.
1887 self.left_palette_size.iter_mut().for_each(|s| *s = 0);
1888 self.left_palette_colors
1889 .iter_mut()
1890 .for_each(|c| *c = [0u16; 8]);
1891 self.left_palette_uv_size.iter_mut().for_each(|s| *s = 0);
1892 self.left_palette_uv_colors
1893 .iter_mut()
1894 .for_each(|c| *c = [0u16; 8]);
1895 // lane-mergefix r2: `av1_zero_left_context` memsets
1896 // `left_txfm_context_buffer` to `tx_size_high[TX_SIZES_LARGEST]` at
1897 // every superblock row of every tile -- the var-tx left context does
1898 // NOT carry over a tile boundary (its `txfm_partition` ctx read the
1899 // previous tile column's last block otherwise).
1900 self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
1901 }
1902
1903 /// Records a block's `skip`/`is_inter`/`interp_filter` state for the next
1904 /// block that reads it as a neighbour -- [`crate::tile`]'s
1905 /// `record_inter`. `filter` is `[3, 3]` for an intra block (spec
1906 /// `get_ref_filter_type`'s "not this ref frame" case reads the same as
1907 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
1908 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
1909 /// the real value, not just `is_inter`).
1910 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1911 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1912 #[allow(clippy::too_many_arguments)]
1913 pub(super) fn record_inter(
1914 &mut self,
1915 at: (usize, usize),
1916 side: usize,
1917 skip: bool,
1918 is_inter: bool,
1919 ref_frame: i8,
1920 filter: [u8; 2],
1921 skip_mode: bool,
1922 ) {
1923 self.record_inter_rect(at, side, side, skip, is_inter, ref_frame, filter, skip_mode);
1924 }
1925
1926 /// [`Self::record_inter`] with independent above (`w_sub`, [`SUB`]-grid
1927 /// columns) / left (`h_sub`, [`SUB`]-grid rows) extents -- lane-partitions
1928 /// r1: a true rectangular strip's above-context span (its own width) and
1929 /// left-context span (its own height) differ, unlike every caller before
1930 /// this round (class neighbour-votes-all-its-fields).
1931 #[allow(clippy::too_many_arguments)]
1932 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1933 pub(super) fn record_inter_rect(
1934 &mut self,
1935 at: (usize, usize),
1936 w_sub: usize,
1937 h_sub: usize,
1938 skip: bool,
1939 is_inter: bool,
1940 ref_frame: i8,
1941 filter: [u8; 2],
1942 skip_mode: bool,
1943 ) {
1944 let (r, c) = at;
1945 self.record_inter_rect_mi(
1946 (r * (SUB / MI), c * (SUB / MI)),
1947 w_sub / MI,
1948 h_sub / MI,
1949 skip,
1950 is_inter,
1951 ref_frame,
1952 filter,
1953 skip_mode,
1954 );
1955 }
1956
1957 /// [`Self::record_inter_rect`] in mi (4px) units -- lane-inter8 r2: an
1958 /// 8x8 leaf covers 2x2 mi, half a [`SUB`] cell in each direction, so the
1959 /// side bands are written (and read) per mi. Every [`SUB`]-unit caller
1960 /// routes through the wrapper above.
1961 #[allow(clippy::too_many_arguments)]
1962 pub(super) fn record_inter_rect_mi(
1963 &mut self,
1964 at_mi: (usize, usize),
1965 w_mi: usize,
1966 h_mi: usize,
1967 skip: bool,
1968 is_inter: bool,
1969 ref_frame: i8,
1970 filter: [u8; 2],
1971 skip_mode: bool,
1972 ) {
1973 let (r, c) = at_mi;
1974 crate::census::block(w_mi, h_mi, is_inter, ref_frame, skip);
1975 // lane-t900 r8 (class new-map-ignores-tile-edge's twin: a map NOBODY
1976 // writes for a whole block class): an INTER block left the luma mode
1977 // map untouched, so a later intra block's `get_intra_edge_filter_type`
1978 // (spec 7.11.2, libaom `reconintra.h`'s `is_smooth`) fell back to the
1979 // coarse SUB-row band, which still held a SMOOTH mode from an earlier
1980 // block in that pixel row -- the directional edge filter then ran at
1981 // strength 3 instead of 2. libaom reads `mbmi->mode` of the neighbour,
1982 // which for an inter block is an INTER mode (>= NEARESTMV) and is
1983 // never smooth; DC_PRED is this map's equivalent (the sub-8x8 groups
1984 // already stamped it).
1985 // The chroma twin: `is_smooth(mbmi, plane > 0)` returns 0 outright for
1986 // an inter neighbour ("uv_mode is not set for inter blocks"), so the
1987 // uv map must read DC_PRED over an inter block's cells too.
1988 if is_inter {
1989 self.record_mode_mi(r, c, w_mi, h_mi, DC_PRED);
1990 self.record_uv_mode_mi(r, c, w_mi, h_mi, DC_PRED);
1991 }
1992 // lane-av1txctxband: the per-CELL `is_inter_block` the per-column
1993 // `above_inter` band stands in for, at libaom's own granularity.
1994 self.mark_inter_grid_rect(at_mi, w_mi, h_mi, is_inter);
1995 let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
1996 self.above_skip[c..c + w_mi].fill(skip);
1997 self.above_skip_mode[c..c + w_mi].fill(skip_mode);
1998 self.above_inter[c..c + w_mi].fill(is_inter);
1999 self.above_ref[c..c + w_mi].fill(ref_frame);
2000 // The single-ref default: `record_compound_ctx_rect_mi` overwrites
2001 // this with the block's real second reference for a compound block,
2002 // called right after this one (lane-publish2 audit).
2003 self.above_ref1[c..c + w_mi].fill(None);
2004 // libaom `get_comp_group_idx_context`/`get_comp_index_context`'s
2005 // single-ref special case: `ref_frame[0] == ALTREF_FRAME` reads
2006 // as `3`/`1` even though this block has no second reference.
2007 // `record_compound_ctx` overwrites this with the real bit for an
2008 // actual compound block's cells, called right after this one.
2009 self.above_comp_group_idx[c..c + w_mi].fill(if altref { 3 } else { 0 });
2010 self.above_compound_idx[c..c + w_mi].fill(u8::from(altref));
2011 self.above_filter[c..c + w_mi].fill(filter);
2012 self.left_skip[r..r + h_mi].fill(skip);
2013 self.left_skip_mode[r..r + h_mi].fill(skip_mode);
2014 self.left_inter[r..r + h_mi].fill(is_inter);
2015 self.left_ref[r..r + h_mi].fill(ref_frame);
2016 self.left_ref1[r..r + h_mi].fill(None);
2017 self.left_comp_group_idx[r..r + h_mi].fill(if altref { 3 } else { 0 });
2018 self.left_compound_idx[r..r + h_mi].fill(u8::from(altref));
2019 self.left_filter[r..r + h_mi].fill(filter);
2020 }
2021
2022 /// Overwrites [`Self::record_inter`]'s ALTREF-special-case default with
2023 /// a real compound block's own `comp_group_idx`/`compound_idx` bits
2024 /// (libaom `has_second_ref(mbmi)` branch of `get_comp_group_idx_context`/
2025 /// `get_comp_index_context`) -- called right after `record_inter` for
2026 /// the same `at`/`side`, only on the `COMPOUND_REFERENCE` path. Also
2027 /// stamps `above_ref1`/`left_ref1` with the block's real second
2028 /// reference, which `record_inter` always clears to `None` (lane-av1comp:
2029 /// this is the one caller that actually knows it) -- so the next block's
2030 /// [`NeighbourRef`](crate::mvstack::NeighbourRef) sees a real compound
2031 /// neighbour instead of `record_inter`'s single-ref default.
2032 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2033 pub(super) fn record_compound_ctx(
2034 &mut self,
2035 at: (usize, usize),
2036 side: usize,
2037 ref1: i8,
2038 comp_group_idx: u8,
2039 compound_idx: u8,
2040 ) {
2041 self.record_compound_ctx_rect(at, side, side, ref1, comp_group_idx, compound_idx);
2042 }
2043
2044 /// [`Self::record_compound_ctx`] with independent above/left extents,
2045 /// mirroring [`Self::record_inter_rect`] (lane-partitions r1).
2046 #[allow(clippy::too_many_arguments)]
2047 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2048 pub(super) fn record_compound_ctx_rect(
2049 &mut self,
2050 at: (usize, usize),
2051 w_sub: usize,
2052 h_sub: usize,
2053 ref1: i8,
2054 comp_group_idx: u8,
2055 compound_idx: u8,
2056 ) {
2057 let (r, c) = at;
2058 self.record_compound_ctx_rect_mi(
2059 (r * (SUB / MI), c * (SUB / MI)),
2060 w_sub / MI,
2061 h_sub / MI,
2062 ref1,
2063 comp_group_idx,
2064 compound_idx,
2065 );
2066 }
2067
2068 /// [`Self::record_compound_ctx_rect`] in mi units (lane-inter8 r2, see
2069 /// [`Self::record_inter_rect_mi`]).
2070 pub(super) fn record_compound_ctx_rect_mi(
2071 &mut self,
2072 at_mi: (usize, usize),
2073 w_mi: usize,
2074 h_mi: usize,
2075 ref1: i8,
2076 comp_group_idx: u8,
2077 compound_idx: u8,
2078 ) {
2079 let (r, c) = at_mi;
2080 crate::census::compound();
2081 for cell in 0..w_mi {
2082 self.above_ref1[c + cell] = Some(ref1);
2083 self.above_comp_group_idx[c + cell] = comp_group_idx;
2084 self.above_compound_idx[c + cell] = compound_idx;
2085 }
2086 for cell in 0..h_mi {
2087 self.left_ref1[r + cell] = Some(ref1);
2088 self.left_comp_group_idx[r + cell] = comp_group_idx;
2089 self.left_compound_idx[r + cell] = compound_idx;
2090 }
2091 }
2092
2093 /// The context of a block's partition symbol: delegates to the mi-precise
2094 /// reader (same pattern as `around`/`around_mi`) -- `above_side`/
2095 /// `left_side` are only ever advanced in whole-[`SUB`] steps by
2096 /// [`Self::record`], so a leaf8's `record_mi` (lane-av1-rect) -- which
2097 /// only touches the finer mi arrays -- leaves them stale for the *next*
2098 /// sibling's own partition symbol.
2099 pub(super) fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
2100 let (r, c) = at;
2101 self.partition_ctx_mi((r * (SUB / MI), c * (SUB / MI)), side)
2102 }
2103
2104 /// [`Self::partition_ctx`] at mi granularity, for an 8x8 leaf of a
2105 /// straddling 16x16 block: reads the finer `above_side_mi`/`left_side_mi`
2106 /// arrays so the second leaf sees the first leaf's own 8x8 side rather
2107 /// than the enclosing 16x16 slot's stale, shared state.
2108 pub(super) fn partition_ctx_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
2109 2 * usize::from(usize::from(self.left_side_mi[mi_r]) * 2 <= side)
2110 + usize::from(usize::from(self.above_side_mi[mi_c]) * 2 <= side)
2111 }
2112
2113 /// The gathered coded/DC-sign state of the blocks above and to the left
2114 /// of a block `side` samples across, per plane.
2115 pub(super) fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
2116 self.around_mi((r * (SUB / MI), c * (SUB / MI)), side)
2117 }
2118
2119 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
2120 /// units, for the same reason [`Self::record_mi`] does.
2121 pub(super) fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
2122 let side_mi = side / MI;
2123 // One pass over the cells accumulating all three planes, not one pass
2124 // per plane: the three planes of a cell live in the same
2125 // `[Neighbour; 3]` (6 bytes), so the per-plane form loaded the same
2126 // cache lines three times (lane-publish). Clamp each edge to the true
2127 // frame extent: a block at the right/bottom edge may be padded beyond
2128 // `mi_cols`/`mi_rows`, and libaom's unavailable context is zero there.
2129 let above_mi = side_mi.min(self.mi_cols.saturating_sub(mi_c));
2130 let left_mi = side_mi.min(self.mi_rows.saturating_sub(mi_r));
2131 let mut out = [(false, false, 0i32); 3];
2132 for cell in 0..above_mi {
2133 let above = &self.above[mi_c + cell];
2134 for (plane, o) in out.iter_mut().enumerate() {
2135 o.0 |= above[plane].level != 0;
2136 o.2 += dc_vote(above[plane].dc);
2137 }
2138 }
2139 for cell in 0..left_mi {
2140 let left = &self.left[mi_r + cell];
2141 for (plane, o) in out.iter_mut().enumerate() {
2142 o.1 |= left[plane].level != 0;
2143 o.2 += dc_vote(left[plane].dc);
2144 }
2145 }
2146 out
2147 }
2148
2149 /// [`Self::around_mi_rect`] for the CHROMA planes of a 4:2:2 frame
2150 /// (lane-av1-422f): libaom `get_txb_ctx_general` reads its above votes
2151 /// over `txb_w_unit` CHROMA 4-px cells, and at ss_x 1 one chroma cell
2152 /// spans TWO luma mi columns. Both cells of a column carry the covering
2153 /// unit's whole-unit dc sign (the same value libaom stores), so the
2154 /// per-luma-mi sum counts each chroma column twice -- and
2155 /// `dc_sign_ctx`'s signum flips whenever the above and left votes have
2156 /// opposite signs with equal magnitude (measured at mi(4,4) plane 1 of
2157 /// the t422 fixture: ours read `dc_sign_cdf[1]`, the oracle row 0).
2158 /// Sampling every second above cell counts each chroma column once,
2159 /// which IS libaom's sum. The left extent is unsubsquared at ss_y 0, so
2160 /// its per-mi cells already line up one-to-one. The level booleans are
2161 /// ORs over duplicated cells, so the sampling cannot change them.
2162 pub(super) fn around_mi_422_chroma(
2163 &self,
2164 (mi_r, mi_c): (usize, usize),
2165 w: usize,
2166 h: usize,
2167 ) -> [(bool, bool, i32); 3] {
2168 let (w_mi, h_mi) = (w / MI, h / MI);
2169 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
2170 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
2171 let mut out = [(false, false, 0i32); 3];
2172 for cell in (0..above_mi).step_by(2) {
2173 let above = &self.above[mi_c + cell];
2174 for (plane, o) in out.iter_mut().enumerate() {
2175 o.0 |= above[plane].level != 0;
2176 o.2 += dc_vote(above[plane].dc);
2177 }
2178 }
2179 for cell in 0..left_mi {
2180 let left = &self.left[mi_r + cell];
2181 for (plane, o) in out.iter_mut().enumerate() {
2182 o.1 |= left[plane].level != 0;
2183 o.2 += dc_vote(left[plane].dc);
2184 }
2185 }
2186 if crate::envflags::env_flag!("EC_DCDUMP") {
2187 // lane-av1422mi24: same dump [`Self::around_mi_rect`] prints, so
2188 // a rerouted 4:2:2 chroma gather stays visible under EC_DCDUMP=1.
2189 // The above rows are the SAMPLED (every-second) cells.
2190 for (plane, o) in out.iter().enumerate() {
2191 let vote = o.2;
2192 let ab: Vec<String> = (0..above_mi)
2193 .step_by(2)
2194 .map(|k| {
2195 format!(
2196 "{:?}/{}",
2197 self.above[mi_c + k][plane].dc,
2198 self.above[mi_c + k][plane].level
2199 )
2200 })
2201 .collect();
2202 let lf: Vec<String> = (0..left_mi)
2203 .map(|k| {
2204 format!(
2205 "{:?}/{}",
2206 self.left[mi_r + k][plane].dc,
2207 self.left[mi_r + k][plane].level
2208 )
2209 })
2210 .collect();
2211 eprintln!(
2212 "EC_DCDUMP422 mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
2213 ab.join(","),
2214 lf.join(",")
2215 );
2216 }
2217 }
2218 out
2219 }
2220
2221 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
2222 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
2223 /// extent pattern for a true rectangular strip's own coefficient context.
2224 pub(super) fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
2225 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
2226 }
2227
2228 /// [`Self::around_rect`] taking the block's position directly in 4x4
2229 /// mode-info units, mirroring [`Self::around_mi`].
2230 pub(super) fn around_mi_rect(
2231 &self,
2232 (mi_r, mi_c): (usize, usize),
2233 w: usize,
2234 h: usize,
2235 ) -> [(bool, bool, i32); 3] {
2236 let (w_mi, h_mi) = (w / MI, h / MI);
2237 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
2238 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
2239 // [`Self::around_mi`]'s single pass, with the two extents split.
2240 let mut out = [(false, false, 0i32); 3];
2241 for cell in 0..above_mi {
2242 let above = &self.above[mi_c + cell];
2243 for (plane, o) in out.iter_mut().enumerate() {
2244 o.0 |= above[plane].level != 0;
2245 o.2 += dc_vote(above[plane].dc);
2246 }
2247 }
2248 for cell in 0..left_mi {
2249 let left = &self.left[mi_r + cell];
2250 for (plane, o) in out.iter_mut().enumerate() {
2251 o.1 |= left[plane].level != 0;
2252 o.2 += dc_vote(left[plane].dc);
2253 }
2254 }
2255 if crate::envflags::env_flag!("EC_DCDUMP") {
2256 for (plane, o) in out.iter().enumerate() {
2257 let vote = o.2;
2258 let ab: Vec<String> = (0..above_mi)
2259 .map(|k| {
2260 format!(
2261 "{:?}/{}",
2262 self.above[mi_c + k][plane].dc,
2263 self.above[mi_c + k][plane].level
2264 )
2265 })
2266 .collect();
2267 let lf: Vec<String> = (0..left_mi)
2268 .map(|k| {
2269 format!(
2270 "{:?}/{}",
2271 self.left[mi_r + k][plane].dc,
2272 self.left[mi_r + k][plane].level
2273 )
2274 })
2275 .collect();
2276 eprintln!(
2277 "EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
2278 ab.join(","),
2279 lf.join(",")
2280 );
2281 }
2282 }
2283 out
2284 }
2285
2286 /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
2287 /// (spec `get_txb_ctx_general`, plane 0, `plane_bsize != tx_size`): the
2288 /// above/left neighbours' magnitude tiers, OR-reduced over the unit's own
2289 /// span and each clamped to 4, indexed into [`SKIP_CONTEXTS`]. Unlike
2290 /// [`Self::around_mi`]'s plain coded/uncoded bit, this needs the real
2291 /// cumulative level -- a lone-TU block never calls this (its `txb_skip_ctx`
2292 /// is always 0, spec's `plane_bsize == tx_size` branch).
2293 pub(super) fn luma_skip_ctx(&self, at_mi: (usize, usize), side_mi: usize) -> usize {
2294 self.luma_skip_ctx_rect(at_mi, side_mi, side_mi)
2295 }
2296
2297 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
2298 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
2299 /// context over `tx_size_wide` and the left one over `tx_size_high`.
2300 pub(super) fn luma_skip_ctx_rect(&self, (mi_r, mi_c): (usize, usize), w_mi: usize, h_mi: usize) -> usize {
2301 let side_mi = w_mi;
2302 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
2303 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
2304 let mut top = 0u8;
2305 let mut left = 0u8;
2306 for cell in 0..above_mi {
2307 top |= self.above[mi_c + cell][0].level;
2308 }
2309 for cell in 0..left_mi {
2310 left |= self.left[mi_r + cell][0].level;
2311 }
2312 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
2313 if crate::envflags::env_flag!("EC_ECDUMP") {
2314 let ab: Vec<String> = (0..above_mi)
2315 .map(|k| self.above[mi_c + k][0].level.to_string())
2316 .collect();
2317 let lf: Vec<String> = (0..left_mi)
2318 .map(|k| self.left[mi_r + k][0].level.to_string())
2319 .collect();
2320 // lane-av1mix: the last few msac register states, so the
2321 // byte-position of the `all_zero` read can be matched against
2322 // aomdec's `EC=(value,rng,bytepos)` dump (decodetxb.c) without a
2323 // second run.
2324 let recent = crate::msac::symtrace::ecdump_recent(4)
2325 .iter()
2326 .map(|(_low, value, rng, bytepos)| format!("({value},{rng},{bytepos})"))
2327 .collect::<Vec<_>>()
2328 .join(" ");
2329 eprintln!(
2330 "EC_ECDUMP plane=0 mi=({mi_r},{mi_c}) wh=({w_mi},{h_mi}) ctx={ctx} above=[{},] left=[{},] recentEC=[{}]",
2331 ab.join(","),
2332 lf.join(","),
2333 recent
2334 );
2335 }
2336 if crate::envflags::env_flag!("EC_AV1_TRACE") {
2337 eprintln!(
2338 "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
2339 self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
2340 );
2341 }
2342 ctx
2343 }
2344
2345 /// Writes one coded block into every cell it covers, on both grids: the
2346 /// mode/side arrays up to `side`'s own width, and the coefficient-context
2347 /// arrays up to the true frame edge — the units past it are left at their
2348 /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
2349 /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
2350 /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
2351 /// not from this block's own side).
2352 pub(super) fn record(
2353 &mut self,
2354 at: (usize, usize),
2355 side: usize,
2356 mode: usize,
2357 uv_mode: usize,
2358 grids: &[&[i32]; 3],
2359 ) {
2360 self.record_rect(at, side, side, mode, uv_mode, grids);
2361 }
2362
2363 /// [`Self::record`] with independent above (`w`)/left (`h`) extents, in
2364 /// pixels -- lane-partitions r1: `above_side`/`left_side` (read back by
2365 /// [`Self::partition_ctx`]) are the neighbour's own width/height per the
2366 /// spec's per-edge partition-context rule, so a true rectangular block
2367 /// naturally wants two different values here rather than one.
2368 /// Writes this block's luma `mode` into the mi-granular
2369 /// [`Self::sub8_mode_col`]/[`Self::sub8_mode_row`] maps, keyed by the mi
2370 /// position a *later* neighbour would read it from: the block's LAST mi
2371 /// row for every column it spans (what the block below reads via
2372 /// `mi(row-1, col)`) and its LAST mi column for every row (what the
2373 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
2374 /// read these back, and only when the recorded position is exactly their
2375 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
2376 pub(super) fn record_mode_mi(&mut self, mi_r: usize, mi_c: usize, mi_w: usize, mi_h: usize, mode: usize) {
2377 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);
2378 let mode = mode as u8;
2379 for cell in 0..mi_w {
2380 if let Some(slot) = self.sub8_mode_col.get_mut(mi_c + cell) {
2381 *slot = (last_r, mode);
2382 }
2383 }
2384 for cell in 0..mi_h {
2385 if let Some(slot) = self.sub8_mode_row.get_mut(mi_r + cell) {
2386 *slot = (last_c, mode);
2387 }
2388 }
2389 }
2390
2391 /// The mi-exact above/left neighbour luma mode for a block whose top-left
2392 /// mi is `(mi_r, mi_c)`, or `None` when no block has recorded that exact
2393 /// mi position (then the coarse [`SUB`]-grid slot is right by
2394 /// construction). See [`Self::record_mode_mi`].
2395 pub(super) fn mode_above_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
2396 match self.sub8_mode_col.get(mi_c) {
2397 Some(&(row, m)) if mi_r > self.tile_row0_mi && usize::from(row) == mi_r - 1 => {
2398 Some(usize::from(m))
2399 }
2400 _ => None,
2401 }
2402 }
2403
2404 pub(super) fn mode_left_mi(&self, mi_r: usize, mi_c: usize) -> Option<usize> {
2405 match self.sub8_mode_row.get(mi_r) {
2406 Some(&(col, m)) if mi_c > self.tile_col0_mi && usize::from(col) == mi_c - 1 => {
2407 Some(usize::from(m))
2408 }
2409 _ => None,
2410 }
2411 }
2412
2413 /// [`Self::record_mode_mi`] for the block's `uv_mode`, into
2414 /// [`Self::uv_mode_col`]/[`Self::uv_mode_row`].
2415 pub(super) fn record_uv_mode_mi(
2416 &mut self,
2417 mi_r: usize,
2418 mi_c: usize,
2419 mi_w: usize,
2420 mi_h: usize,
2421 uv_mode: usize,
2422 ) {
2423 let (last_r, last_c) = (mi_r + mi_h - 1, mi_c + mi_w - 1);
2424 fill_span(
2425 &mut self.uv_mode_col,
2426 mi_c,
2427 mi_w,
2428 (last_r as u16, uv_mode as u8),
2429 );
2430 fill_span(
2431 &mut self.uv_mode_row,
2432 mi_r,
2433 mi_h,
2434 (last_c as u16, uv_mode as u8),
2435 );
2436 // libaom writes one `MB_MODE_INFO` pointer into every mi cell a block
2437 // covers, so the chroma neighbour read below is a plain grid read.
2438 let stride = self.uv_grid_cols;
2439 let n = stride.saturating_sub(mi_c).min(last_c + 1 - mi_c);
2440 for row in mi_r..=last_r {
2441 fill_span(
2442 &mut self.uv_mode_grid,
2443 row * stride + mi_c,
2444 n,
2445 uv_mode as u8,
2446 );
2447 }
2448 // lane-av1leftwit: stamp the writing block's own mi over its extent,
2449 // the same cells and the same clipping as `uv_mode_grid` above.
2450 let owner = UV_OWNER_EPOCH.with(|c| c.get()) | ((mi_r as u32) << 12) | mi_c as u32;
2451 for row in mi_r..=last_r {
2452 fill_span(&mut self.uv_owner, row * stride + mi_c, n, owner);
2453 }
2454 if crate::envflags::env_flag!("EC_LEFTSSY") {
2455 eprintln!("EC_LEAF mi=({mi_r},{mi_c}) wh=({mi_w},{mi_h}) uv_mode={uv_mode}");
2456 }
2457 }
2458
2459 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
2460 /// coded a smooth `uv_mode` -- libaom's `intra_edge_filter_type` for
2461 /// planes 1/2. Falls back to the coarse [`SUB`] slot on whichever axis no
2462 /// block has recorded the exact neighbouring mi.
2463 pub(super) fn smooth_uv_neighbour(
2464 &self,
2465 mi_r: usize,
2466 mi_c: usize,
2467 r: usize,
2468 c: usize,
2469 fctx: &crate::decode::FrameCtx,
2470 ) -> bool {
2471 // lane-kf900 r2: libaom reads the chroma neighbours off the CHROMA
2472 // REFERENCE block, not off the mi that carries the chroma syntax.
2473 // `set_mi_row_col` (`blockd.h`) takes
2474 // `base_mi = &xd->mi[-(mi_row & ss_y) * stride - (mi_col & ss_x)]` and
2475 // only then `chroma_above_mbmi = base_mi[-stride]` /
2476 // `chroma_left_mbmi = base_mi[-1]`. A sub-8 pair codes its chroma at
2477 // the ODD mi, so without the snap we looked one mi row/column too far
2478 // down/right -- the mi-exact slot never matched and the coarse
2479 // fallback answered instead. Measured on a 4K 10-bit key frame, chroma
2480 // 8x4 at (688, 100) = mi (51, 344): libaom's
2481 // `get_intra_edge_filter_type` is 1 (the chroma block above it is
2482 // `UV_SMOOTH_PRED`), ours was 0, which flips
2483 // `av1_use_intra_edge_upsample(8, 4, -6, type)` (`blk_wh == 12`:
2484 // false for type 1, TRUE for type 0) and upsampled an edge libaom
2485 // leaves alone -- +1 on rows 2/3 of that block and every chroma block
2486 // predicting from it (class `context-read-from-one-cell`).
2487 // lane-av1-444: the snap is the SEQUENCE's subsampling, hardcoded
2488 // `& !1` before -- at subsampling 0/0 libaom's `mi_row & 0` snaps
2489 // nothing, and the hardcoded snap read a 4x4 leaf's smooth
2490 // neighbour two mi away (frame 0 of `av1-profile1-444.ivf`, leaf
2491 // mi(5,15): left neighbour SMOOTH_V at mi(5,14), read at mi(4,13)).
2492 let snap_y = (1usize << ss_y(fctx)) - 1;
2493 let snap_x = (1usize << ss_x(fctx)) - 1;
2494 // The snap IS libaom's `base_mi` de-offsetting (`set_mi_row_col`,
2495 // `av1_common_int.h:1395-1412`): `base_mi` is the block's own mi moved
2496 // by `-(mi_row & ss_y) * stride - (mi_col & ss_x)`. The helper applies
2497 // the two chroma-reference offsets on top of it -- see its own comment
2498 // for which axis each one moves.
2499 self.smooth_uv_neighbour_unsnapped(
2500 mi_r & !snap_y,
2501 mi_c & !snap_x,
2502 r,
2503 c,
2504 ss_x(fctx),
2505 ss_y(fctx),
2506 true,
2507 )
2508 }
2509
2510 /// [`Self::smooth_uv_neighbour`] without the chroma-reference snap, i.e.
2511 /// read off the mi passed in exactly. Only the 16x4/4x16 pair witness
2512 /// counter wants this: it measures how often the snap CHANGES the answer,
2513 /// which is what the lane-kf1200/kf900 chroma-reference fix buys. Every
2514 /// decode path uses the snapping form.
2515 /// `decode_path` is `true` only for the snapping form every decode call
2516 /// site uses; the 16x4/4x16 pair witness's mirror passes `false`, so the
2517 /// `+ss_y` counters measure a read that actually filters a chroma edge and
2518 /// not the counter-only one.
2519 ///
2520 /// lane-av1leftwit: the mirror's justification used to be "no committed
2521 /// fixture reaches the shape on the decode path", and that was false --
2522 /// `UV_LEFT_1MI_SPLIT_HITS` fires on five of them. The flag stays (a
2523 /// counter-only mirror at an ODD mi row is still not a decode-path read,
2524 /// and its result feeds only `RECT4_16_UV_PAIR_FILT_HITS`), but it is no
2525 /// longer evidence about the `+ss_y` term, and nothing may cite it as such.
2526 /// The decode path's own reach is `uv_left_1mi_split_hits()`.
2527 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
2528 #[allow(clippy::too_many_arguments)]
2529 pub(super) fn smooth_uv_neighbour_unsnapped(
2530 &self,
2531 mi_r: usize,
2532 mi_c: usize,
2533 r: usize,
2534 c: usize,
2535 ss_x: usize,
2536 ss_y: usize,
2537 decode_path: bool,
2538 ) -> bool {
2539 // lane-mtfix r1: availability is TILE-relative on BOTH axes and on the
2540 // coarse fallback too. `above_uv_mode` is a frame-wide [`SUB`]-grid
2541 // array that `start_tile` does not clear, so a block on a tile's first
2542 // mi row used to read the uv_mode of the block above it in the tile
2543 // ABOVE and filter its chroma edge at that neighbour's strength
2544 // (2x2-tile intra gate, seed 46: chroma-only +-1..2 over the 8x8 block
2545 // at chroma (120, 32), the top-right tile's first block).
2546 let have_above = mi_r > self.tile_row0_mi;
2547 let have_left = mi_c > self.tile_col0_mi;
2548 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
2549 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
2550 {
2551 hit!(UV_TILE_EDGE_SUPPRESSED_HITS);
2552 }
2553 // The mi grid is libaom's own read; the two maps below stay as the
2554 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
2555 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
2556 (col < self.uv_grid_cols)
2557 .then(|| grid.get(row * self.uv_grid_cols + col).copied())
2558 .flatten()
2559 .filter(|&m| m != u8::MAX)
2560 .map(usize::from)
2561 };
2562 // libaom's two chroma-reference mi, from `set_mi_row_col`
2563 // (`av1_common_int.h:1400-1401`), with `mi_r`/`mi_c` already
2564 // de-offset by the caller's `(mi_row & ss_y)` / `(mi_col & ss_x)`
2565 // snap -- i.e. already libaom's `base_mi`:
2566 //
2567 // chroma_above_mi = base_mi[-mi_stride + ss_x] row -1, col +ss_x
2568 // chroma_left_mi = base_mi[ss_y*mi_stride - 1] row +ss_y, col -1
2569 //
2570 // SHIPPED: the above COLUMN. It is `+ss_x` wherever `ss_x == 1` --
2571 // 4:2:0, 4:2:2 AND 4:4:0 all carry that column shift, and only 4:4:4
2572 // (`ss_x == 0`) leaves the read where it was. Measured: folding it in
2573 // leaves the 4:2:0 control byte-identical to `aomdec --rawvideo`; the
2574 // boolean it feeds is simply not exercised differently by that stream
2575 // at its blocks. One chroma column spans two luma mi columns, so the
2576 // chroma edge reaches into the right-hand luma block, and that is where
2577 // its reference lives.
2578 //
2579 // SHIPPED (lane-av1leftref): the left read's `+ss_y` ROW term -- the
2580 // last open item lane-av1422warp carried. libaom puts the left
2581 // reference one mi row DOWN at 4:2:0 and 4:4:0 (`ss_y == 1`) and on
2582 // its own row at 4:2:2 (`ss_y == 0`); this read its own row at every
2583 // subsampling. An earlier attempt applied the `ss_y` term to the WRONG
2584 // read (the above) and regressed the byte-exact 4:2:0 control, which
2585 // is what exposed the crossing. lane-av1leftwit CORRECTED the claim
2586 // this comment used to make: "six committed 4:2:0 fixtures reach it,
2587 // and on `reelb_ss600_key_frame.obu` the boolean flips" was never
2588 // measured. Measured over all 48 committed fixtures that decode
2589 // (`lanes/av1leftwit.report.md`), `reelb_ss600_key_frame.obu` reads
2590 // `mode_diff=0 smooth_diff=0 split1mi=0`, and exactly FIVE fixtures
2591 // put a 1-mi-tall left neighbour in front of a decode-path read at
2592 // all -- `gm_small_side_witness` (5), `reelc_sb128_inter_witness` (7),
2593 // `av112bit-{inter,compound,compound-masked}` (1 each) -- and in every
2594 // one of those reads the two blocks agree on `uv_mode`. So the SHAPE is
2595 // reachable (see `UV_LEFT_1MI_SPLIT_HITS`) and the term's VALUE
2596 // changing is what is still unwitnessed.
2597 let above_mi = (mi_r.saturating_sub(1), mi_c + ss_x);
2598 // lane-av1leftref: libaom's LEFT read carries the `+ss_y` ROW term --
2599 // `base_mi[ss_y * mi_stride - 1]` (`av1_common_int.h:1400-1401`) is
2600 // one mi row DOWN at 4:2:0 and 4:4:0 (`ss_y == 1`), and on its own
2601 // row at 4:2:2 (`ss_y == 0`) and 4:4:4. The read below used its own
2602 // row at every subsampling. The term is only observable when the two
2603 // cells hold DIFFERENT blocks, i.e. the left neighbour is 1 mi tall or
2604 // shorter -- then `(row, col-1)` and `(row+1, col-1)` are two blocks
2605 // and only libaom's is the chroma reference. Three counters measure
2606 // that, and the third is the one the other two need: a read can only
2607 // differ if the two cells are written by DIFFERENT blocks, which
2608 // `UV_LEFT_1MI_SPLIT_HITS` counts off the per-cell owner stamp
2609 // (`uv_owner`, below). A DIFF bucket that reads 0 while SPLIT reads 0
2610 // was never in contention; a DIFF bucket that reads 0 while SPLIT
2611 // reads > 0 is the term being unobservable on real material, not
2612 // unreachable. `..._MODE_DIFF_HITS` / `..._SMOOTH_DIFF_HITS` then say
2613 // whether the mode value, and the boolean this feeds
2614 // (`is_smooth_mode` -> `av1_get_intra_edge_filter_type` -> the chroma
2615 // edge filter), actually moved.
2616 let left_mi = (mi_r + ss_y, mi_c.saturating_sub(1));
2617 let read_left = |row: usize| -> usize {
2618 match self.uv_mode_row.get(row) {
2619 _ if have_left && let Some(m) = cell(&self.uv_mode_grid, row, left_mi.1) => m,
2620 Some(&(col, m)) if have_left && usize::from(col) == left_mi.1 => usize::from(m),
2621 _ if have_left => self.left_uv_mode[r],
2622 _ => DC_PRED,
2623 }
2624 };
2625 let above = match self.uv_mode_col.get(above_mi.1) {
2626 _ if have_above && let Some(m) = cell(&self.uv_mode_grid, above_mi.0, above_mi.1) => m,
2627 Some(&(row, m)) if have_above && usize::from(row) == above_mi.0 => usize::from(m),
2628 _ if have_above => self.above_uv_mode[c],
2629 _ => DC_PRED,
2630 };
2631 let left = read_left(left_mi.0);
2632 // lane-av1leftref: the gate's reach + load-bearing counters. `READS` is
2633 // how many chroma edge-filter-type reads took this path at all, so a
2634 // gate can tell "the arm never ran" from "the arm ran and the `+ss_y`
2635 // term did not change the answer". The two DIFF buckets compare
2636 // libaom's read cell against the pre-lane own-row cell; both read 0 on
2637 // every committed fixture and every one of the ~1000 encodes swept in
2638 // `lanes/av1leftref.report.md`, which is what makes the read change a
2639 // proven no-op on today's material rather than an unmeasured guess.
2640 if decode_path && have_left && ss_y > 0 {
2641 hit!(UV_LEFT_SS_Y_READS);
2642 // The pre-lane read, kept as the counter's own-row arm: it is what
2643 // this decoder answered before the `+ss_y` term landed, and
2644 // comparing against it is what proves the term is load-bearing.
2645 let own_row = read_left(mi_r);
2646 if own_row != left {
2647 hit!(UV_LEFT_SS_Y_MODE_DIFF_HITS);
2648 }
2649 if is_smooth_mode(own_row) != is_smooth_mode(left) {
2650 hit!(UV_LEFT_SS_Y_SMOOTH_DIFF_HITS);
2651 }
2652 // lane-av1leftwit: the geometry the `+ss_y` term needs. The two
2653 // cells are one left mi column apart, so they are two different
2654 // blocks exactly when the left neighbour is 1 mi tall or shorter.
2655 let col = left_mi.1;
2656 let epoch = UV_OWNER_EPOCH.with(|c| c.get()) & 0xff00_0000;
2657 let own = (col < self.uv_grid_cols)
2658 .then(|| self.uv_owner.get(mi_r * self.uv_grid_cols + col).copied())
2659 .flatten()
2660 .filter(|o| o & 0xff00_0000 == epoch)
2661 .unwrap_or(0);
2662 let down = self
2663 .uv_owner
2664 .get((mi_r + ss_y) * self.uv_grid_cols + col)
2665 .copied()
2666 .filter(|o| o & 0xff00_0000 == epoch)
2667 .unwrap_or(0);
2668 if own != 0 && down != 0 && own != down {
2669 hit!(UV_LEFT_1MI_SPLIT_HITS);
2670 if crate::envflags::env_flag!("EC_LEFTSSY") {
2671 eprintln!(
2672 "EC_LEFTSSY epoch={} mi=({mi_r},{mi_c}) left_col={col} \
2673 owners=({},{})->({},{}) modes={own_row}/{left}",
2674 epoch >> 24,
2675 own >> 12 & 0xfff,
2676 own & 0xfff,
2677 down >> 12 & 0xfff,
2678 down & 0xfff,
2679 );
2680 }
2681 }
2682 }
2683 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
2684 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m)
2685 }) || have_left && cell(&self.uv_mode_grid, left_mi.0, left_mi.1).is_some_and(|m| {
2686 !matches!(self.uv_mode_row.get(left_mi.0), Some(&(col, cm)) if usize::from(col) == left_mi.1 && usize::from(cm) == m)
2687 }) {
2688 hit!(UV_MODE_GRID_OVERRIDE_HITS);
2689 }
2690 // lane-cfl r1 counter: how often the mi-exact chroma neighbour differs
2691 // from the coarse [`SUB`] slot -- i.e. how often a chroma edge would
2692 // have been filtered at the wrong strength by the coarse map alone.
2693 if above != self.above_uv_mode[c] || left != self.left_uv_mode[r] {
2694 hit!(UV_MODE_MI_OVERRIDE_HITS);
2695 }
2696 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
2697 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
2698 {
2699 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
2700 }
2701 is_smooth_mode(above) || is_smooth_mode(left)
2702 }
2703
2704 /// The above/left luma modes libaom's `above_mi`/`left_mi` really see for a
2705 /// block at coarse [`SUB`]-grid `(r, c)`. lane-rectx r5: the coarse
2706 /// `above_mode`/`left_mode` slots are written in 16x16 cells, so a
2707 /// sub-16x16 neighbour (a 16x8 rect leaf, an 8x8 split cell) leaves them
2708 /// holding an OLDER, larger block's mode -- it only ever recorded into the
2709 /// mi-exact map. Every `kf_y_mode` reader goes through here, not just the
2710 /// strip path ([`decode_leaf_rect`] took this override in r4; a 32x16 strip
2711 /// whose left neighbour was a 16x8 leaf still read the stale row and picked
2712 /// a different CDF for the same mode value).
2713 /// lane-rectsplitx r2: availability-correct above/left luma modes for a
2714 /// block whose top-left mi is `(mi_r, mi_c)`. libaom reads `above_mbmi`
2715 /// only when `up_available` and `left_mbmi` only when `left_available`;
2716 /// the coarse [`SUB`] bands cannot express that, and with 8-px strips they
2717 /// actively lie -- four 32x8 strips of one `HORZ_4` share ONE 16x16
2718 /// `left_mode` cell, so the second strip at tile column 0 read the FIRST
2719 /// strip's mode as its "left neighbour" (measured on the band fixture at
2720 /// mi(10,0): mode 2 where libaom has DC, a different `kf_y_mode` row).
2721 pub(super) fn modes_above_left_mi(
2722 &self,
2723 mi_r: usize,
2724 mi_c: usize,
2725 fallback: (usize, usize),
2726 ) -> (usize, usize) {
2727 let above = if mi_r > self.tile_row0_mi {
2728 self.mode_above_mi(mi_r, mi_c).unwrap_or(fallback.0)
2729 } else {
2730 DC_PRED
2731 };
2732 let left = if mi_c > self.tile_col0_mi {
2733 self.mode_left_mi(mi_r, mi_c).unwrap_or(fallback.1)
2734 } else {
2735 DC_PRED
2736 };
2737 (above, left)
2738 }
2739
2740 /// lane-modectx r1: the coarse-[`SUB`]-grid entry point, now availability
2741 /// correct. The mi-exact lookups already refuse to cross a tile edge, but
2742 /// their FALLBACK (`above_mode`/`left_mode`) did not: `left_mode` is reset
2743 /// per superblock row and never per tile, so the first block column of
2744 /// tile 2..N read the previous tile's mode as its left neighbour, and the
2745 /// above band survives across a tile ROW boundary the same way lane-mtfix's
2746 /// `above_uv_mode` did. libaom reads `above_mbmi`/`left_mbmi` only when
2747 /// `up_available`/`left_available` and uses DC_PRED otherwise
2748 /// ([`Self::modes_above_left_mi`]).
2749 pub(super) fn modes_above_left(&self, r: usize, c: usize) -> (usize, usize) {
2750 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
2751 let (above, left) =
2752 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
2753 if above != self.above_mode[c] || left != self.left_mode[r] {
2754 hit!(MODE_MI_OVERRIDE_HITS);
2755 }
2756 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
2757 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
2758 {
2759 hit!(INTER_NEIGHBOUR_NOT_SMOOTH_HITS);
2760 }
2761 // A neighbour the coarse band offered where the tile edge makes it
2762 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
2763 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
2764 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
2765 {
2766 hit!(MODE_TILE_EDGE_COARSE_LEAKS);
2767 }
2768 (above, left)
2769 }
2770
2771 pub(super) fn record_rect(
2772 &mut self,
2773 at: (usize, usize),
2774 w: usize,
2775 h: usize,
2776 mode: usize,
2777 uv_mode: usize,
2778 grids: &[&[i32]; 3],
2779 ) {
2780 self.record_rect_mi(sub16_to_mi(at), w, h, mode, uv_mode, grids);
2781 }
2782
2783 /// [`Self::record_rect`] in mi (4 px) units -- lane-inter4 r1: a
2784 /// 32x8/8x32 strip of a 32-level 1:4 partition sits at an 8-px offset the
2785 /// [`SUB`]-unit `at` cannot name. The coarse 16-px bands are still keyed
2786 /// by the enclosing cell (a sub-16 extent writes none of them, exactly as
2787 /// the [`SUB`]-unit path does).
2788 pub(super) fn record_rect_mi(
2789 &mut self,
2790 at_mi: (usize, usize),
2791 w: usize,
2792 h: usize,
2793 mode: usize,
2794 uv_mode: usize,
2795 grids: &[&[i32]; 3],
2796 ) {
2797 self.record_rect_mi_modes(at_mi, w, h, mode, uv_mode);
2798 self.record_mi_rect(at_mi, w, h, grids);
2799 }
2800
2801 /// [`Self::record_rect_mi`]'s mode and transform-size half, without the
2802 /// coefficient-context stamp.
2803 pub(super) fn record_rect_mi_modes(
2804 &mut self,
2805 at_mi: (usize, usize),
2806 w: usize,
2807 h: usize,
2808 mode: usize,
2809 uv_mode: usize,
2810 ) {
2811 let (r, c) = (at_mi.0 / (SUB / MI), at_mi.1 / (SUB / MI));
2812 // lane-inter4 r2: a strip whose own footprint runs past the frame's
2813 // last 16-px column/row stamps only the cells that exist (libaom's
2814 // arrays are padded past the frame and those cells are never read).
2815 for cell in 0..w / SUB {
2816 if c + cell >= self.above_mode.len() {
2817 break;
2818 }
2819 self.above_mode[c + cell] = mode;
2820 self.above_uv_mode[c + cell] = uv_mode;
2821 self.above_side[c + cell] = w;
2822 }
2823 for cell in 0..h / SUB {
2824 if r + cell >= self.left_mode.len() {
2825 break;
2826 }
2827 self.left_mode[r + cell] = mode;
2828 self.left_uv_mode[r + cell] = uv_mode;
2829 self.left_side[r + cell] = h;
2830 }
2831 self.record_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, mode);
2832 self.record_uv_mode_mi(at_mi.0, at_mi.1, w / MI, h / MI, uv_mode);
2833 }
2834
2835 /// lane-av1chromarect: [`Self::record_rect_mi`] for a block whose uv
2836 /// plane block is SEVERAL transform units, each of which stamped its own
2837 /// span through [`Self::record_mi_chroma`]. Writing one whole-block state
2838 /// over them is the `override-slot-on-one-arm` class: libaom keeps the
2839 /// per-unit above/left contexts distinct, and the next block's first
2840 /// unit reads them. The luma plane has one unit here, so it is stamped
2841 /// exactly as the whole-block record stamps it.
2842 pub(super) fn record_rect_mi_luma_only(
2843 &mut self,
2844 at_mi: (usize, usize),
2845 w: usize,
2846 h: usize,
2847 mode: usize,
2848 uv_mode: usize,
2849 luma_grid: &[i32],
2850 ) {
2851 self.record_rect_mi_modes(at_mi, w, h, mode, uv_mode);
2852 fill_span(&mut self.left_side_mi, at_mi.0, h / MI, h as u8);
2853 fill_span(&mut self.above_side_mi, at_mi.1, w / MI, w as u8);
2854 self.record_mi_luma_rect(at_mi, w, h, luma_grid);
2855 }
2856
2857 /// The coefficient-context half of [`Self::record`], taking the block's
2858 /// position directly in 4x4 mode-info units rather than [`SUB`]-grid
2859 /// `(r, c)`: an 8x8 leaf under a straddling 16x16 (lane-av1-rect) sits at
2860 /// a mi offset [`Self::record`]'s SUB-unit `at` cannot name.
2861 pub(super) fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[&[i32]; 3]) {
2862 self.record_mi_rect(at_mi, side, side, grids);
2863 }
2864
2865 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
2866 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
2867 pub(super) fn record_mi_rect(&mut self, at_mi: (usize, usize), w: usize, h: usize, grids: &[&[i32]; 3]) {
2868 let (mi_r, mi_c) = at_mi;
2869 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));
2870 let (w_mi, h_mi) = (w / MI, h / MI);
2871 if crate::envflags::env_flag!("EC_ECPUB") {
2872 eprintln!(
2873 "EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}",
2874 states[0].level
2875 );
2876 }
2877 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
2878 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
2879 // A chroma 4x4 unit straddling the true luma edge is still whole in
2880 // chroma's own halved grid, so libaom rounds the luma bound up to the
2881 // plane's own 4x4 unit before clamping a subsampled plane
2882 // (`av1_write_intra_coeffs_mb`, encodetxb.c).
2883 let round_up_even = |n: usize| n.div_ceil(2) * 2;
2884 let bound_h = [
2885 self.mi_rows,
2886 round_up_even(self.mi_rows),
2887 round_up_even(self.mi_rows),
2888 ];
2889 let bound_w = [
2890 self.mi_cols,
2891 round_up_even(self.mi_cols),
2892 round_up_even(self.mi_cols),
2893 ];
2894 // lane-sb128c r7: a 128x64 at the bottom frame edge names mi rows
2895 // past the padded side arrays (mi_rows 198, block rows 192..208);
2896 // libaom's own arrays are superblock-sized, so those cells simply
2897 // have no reader -- [`fill_span`] drops them, as the `break` did.
2898 // `bound_h[1] == bound_h[2] >= bound_h[0]`, so the per-cell plane
2899 // predicate is three contiguous runs: all planes, chroma only, none
2900 // (lane-mi).
2901 let luma_h = h_mi.min(bound_h[0].saturating_sub(mi_r));
2902 let chroma_h = h_mi.min(bound_h[1].saturating_sub(mi_r));
2903 let uv_only = [Neighbour::default(), states[1], states[2]];
2904 fill_span(&mut self.left, mi_r, luma_h, states);
2905 fill_span(&mut self.left, mi_r + luma_h, chroma_h - luma_h, uv_only);
2906 fill_span(
2907 &mut self.left,
2908 mi_r + chroma_h,
2909 h_mi - chroma_h,
2910 [Neighbour::default(); 3],
2911 );
2912 let luma_w = w_mi.min(bound_w[0].saturating_sub(mi_c));
2913 let chroma_w = w_mi.min(bound_w[1].saturating_sub(mi_c));
2914 let uv_only_w = [Neighbour::default(), states[1], states[2]];
2915 fill_span(&mut self.above, mi_c, luma_w, states);
2916 fill_span(&mut self.above, mi_c + luma_w, chroma_w - luma_w, uv_only_w);
2917 fill_span(
2918 &mut self.above,
2919 mi_c + chroma_w,
2920 w_mi - chroma_w,
2921 [Neighbour::default(); 3],
2922 );
2923 }
2924
2925 /// [`Self::record_mi`]'s plane-0 half only, for one luma transform unit
2926 /// inside a coded block whose luma transform is smaller than its own
2927 /// side (`TxMode::Select`): the real per-transform-unit coefficient
2928 /// context (spec `AboveLevelContext`/`LeftLevelContext`), unlike the
2929 /// coarse per-block `tx_grid`/`fill_lf_grid` state
2930 /// [`Self::record_split_luma`] still writes once for the whole block.
2931 /// Leaves `above_side_mi`/`left_side_mi` and the chroma planes alone --
2932 /// the caller's own [`Self::record_split_luma`] call sets those once,
2933 /// at the block's own true side, not this TU's.
2934 pub(super) fn record_mi_luma(&mut self, at_mi: (usize, usize), tx_px: usize, grid: &[i32]) {
2935 self.record_mi_luma_rect(at_mi, tx_px, tx_px, grid);
2936 }
2937
2938 /// [`Self::record_mi_luma`] for ONE CHROMA transform unit of a block whose
2939 /// uv plane block is several units (lane-sb128b r2: a 128x128 block's
2940 /// 64x64 uv plane block is four TX_32X32 units, `av1_get_max_uv_txsize`).
2941 /// `w_px`/`h_px` are the unit's extent in LUMA pixels -- the chroma
2942 /// coefficient-context arrays are indexed by luma mi, the convention
2943 /// [`Self::record_split_luma_rect_mi`] already writes them in, frame-edge
2944 /// clamp included.
2945 pub(super) fn record_mi_chroma(
2946 &mut self,
2947 (mi_r, mi_c): (usize, usize),
2948 w_px: usize,
2949 h_px: usize,
2950 plane: usize,
2951 grid: &[i32],
2952 ) {
2953 // lane-arfchroma: a 4x4 CHROMA transform unit is `4 << ss` luma px per
2954 // axis, i.e. `1 << ss` LUMA mi, so its context cell is the step-aligned
2955 // group of mi a block may only PART of. A block starting mid-cell (a
2956 // 16x4 / 4x16 1:4 strip, whose mi row/col is ODD at 4:2:0) stamped its
2957 // own origin plus the mi row/col BELOW it, so the strip above a block
2958 // handed that block a "left neighbour" libaom never had -- its chroma
2959 // cell is one row up -- and the block's chroma `txb_skip` context came
2960 // out one base high (ours 2, libaom 7+1 = 8, at 320x240 frame 2 block
2961 // mi (4,0) of the 4:2:0 lossless alt-ref witness). Align the origin
2962 // DOWN to the cell: that is where libaom's per-plane 2-D
2963 // `left/above_context_map` cell lives, indexed in the PLANE's own 4x4
2964 // units rather than in luma mi.
2965 let (step_x, step_y) = (w_px / MI, h_px / MI);
2966 // the flags read the CALLER's origin, before the shadowing align below
2967 let (row_mid, col_mid) = (mi_r & (step_y - 1) != 0, mi_c & (step_x - 1) != 0);
2968 if row_mid || col_mid {
2969 CHROMA_MIDCELL_PUB_HITS.with(|c| {
2970 let mut v = c.get();
2971 v[0] += usize::from(row_mid);
2972 v[1] += usize::from(col_mid);
2973 v[2] += usize::from(row_mid && col_mid);
2974 c.set(v);
2975 });
2976 }
2977 let (mi_r, mi_c) = (mi_r & !(step_y - 1), mi_c & !(step_x - 1));
2978 let round_up_even = |n: usize| n.div_ceil(2) * 2;
2979 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
2980 let state = neighbour_state(grid);
2981 if crate::envflags::env_flag!("EC_CHROMA_PUB") {
2982 eprintln!(
2983 "EC_CHROMA_PUB plane={plane} mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={} dc={}",
2984 state.level,
2985 state.dc.map_or(-1, i32::from)
2986 );
2987 }
2988 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
2989 self.left[mi_r + cell][plane] = state;
2990 }
2991 for cell in 0..(w_px / MI).min(bound_w.saturating_sub(mi_c)) {
2992 self.above[mi_c + cell][plane] = state;
2993 }
2994 }
2995
2996 /// [`Self::record_mi_luma`] for a RECTANGULAR transform unit (lane-rectsplitx
2997 /// r1): the above context spans the unit's width, the left context its
2998 /// height, which for a square unit is the same loop it always was.
2999 pub(super) fn record_mi_luma_rect(
3000 &mut self,
3001 (mi_r, mi_c): (usize, usize),
3002 w_px: usize,
3003 h_px: usize,
3004 grid: &[i32],
3005 ) {
3006 let state = neighbour_state(grid);
3007 if crate::envflags::env_flag!("EC_ECPUB") {
3008 eprintln!(
3009 "EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}",
3010 state.level
3011 );
3012 }
3013 for cell in 0..h_px / MI {
3014 if mi_r + cell < self.mi_rows {
3015 self.left[mi_r + cell][0] = state;
3016 }
3017 }
3018 for cell in 0..w_px / MI {
3019 if mi_c + cell < self.mi_cols {
3020 self.above[mi_c + cell][0] = state;
3021 }
3022 }
3023 }
3024
3025 /// [`Self::record`]'s mode/side and chroma-context bookkeeping, for a
3026 /// block whose luma was decoded as several transform units through
3027 /// [`Self::record_mi_luma`] rather than [`Self::record`]'s own single
3028 /// whole-block luma write -- everything [`Self::record`] does except
3029 /// plane 0, which is already correct per-TU by the time this runs.
3030 pub(super) fn record_split_luma(
3031 &mut self,
3032 at: (usize, usize),
3033 side: usize,
3034 mode: usize,
3035 uv_mode: usize,
3036 chroma_grids: [&[i32]; 2],
3037 ) {
3038 self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids);
3039 }
3040
3041 /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`)
3042 /// extents in pixels (lane-rectsplit r1), the same relationship
3043 /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose
3044 /// luma transform split into several square units needs exactly this
3045 /// bookkeeping, at its own true rectangular extents.
3046 pub(super) fn record_split_luma_rect(
3047 &mut self,
3048 at: (usize, usize),
3049 w: usize,
3050 h: usize,
3051 mode: usize,
3052 uv_mode: usize,
3053 chroma_grids: [&[i32]; 2],
3054 ) {
3055 let (r, c) = at;
3056 self.record_split_luma_rect_mi(
3057 (r * (SUB / MI), c * (SUB / MI)),
3058 w,
3059 h,
3060 mode,
3061 uv_mode,
3062 chroma_grids,
3063 );
3064 }
3065
3066 /// [`Self::record_split_luma_rect`] addressed in mi units (lane-rectsplitx
3067 /// r1) -- a strip 8 px tall starts mid-[`SUB`]-cell, which the coarse
3068 /// `(r, c)` form cannot name. The coarse mode/side arrays are stamped for
3069 /// every cell the strip TOUCHES (`div_ceil`), last writer wins, the
3070 /// convention [`decode_block_rect4`] already established for 1:4 strips.
3071 pub(super) fn record_split_luma_rect_mi(
3072 &mut self,
3073 at_mi: (usize, usize),
3074 w: usize,
3075 h: usize,
3076 mode: usize,
3077 uv_mode: usize,
3078 chroma_grids: [&[i32]; 2],
3079 ) {
3080 self.record_split_luma_rect_mi_modes(at_mi, w, h, mode, uv_mode);
3081 let (mi_r, _) = at_mi;
3082 let (w_mi, h_mi) = (w / MI, h / MI);
3083 let round_up_even = |n: usize| n.div_ceil(2) * 2;
3084 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
3085 for (plane_idx, grid) in chroma_grids.into_iter().enumerate() {
3086 let plane = plane_idx + 1;
3087 let state = neighbour_state(grid);
3088 for cell in 0..h_mi {
3089 if cell < h_mi.min(bound_h.saturating_sub(mi_r)) {
3090 self.left[mi_r + cell][plane] = state;
3091 }
3092 }
3093 for cell in 0..w_mi {
3094 if cell < w_mi.min(bound_w.saturating_sub(at_mi.1)) {
3095 self.above[at_mi.1 + cell][plane] = state;
3096 }
3097 }
3098 }
3099 }
3100
3101 /// [`Self::record_split_luma_rect_mi`]'s mode and transform-size half,
3102 /// without the per-plane coefficient stamp -- see
3103 /// [`Self::record_rect_mi_luma_only`] for why a multi-unit chroma block
3104 /// must not take the whole-block stamp.
3105 pub(super) fn record_split_luma_rect_mi_modes(
3106 &mut self,
3107 at_mi: (usize, usize),
3108 w: usize,
3109 h: usize,
3110 mode: usize,
3111 uv_mode: usize,
3112 ) {
3113 let (mi_r, mi_c) = at_mi;
3114 let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI));
3115 for cell in 0..w.div_ceil(SUB) {
3116 if c + cell >= self.above_mode.len() {
3117 break;
3118 }
3119 self.above_mode[c + cell] = mode;
3120 self.above_uv_mode[c + cell] = uv_mode;
3121 self.above_side[c + cell] = w;
3122 }
3123 for cell in 0..h.div_ceil(SUB) {
3124 if r + cell >= self.left_mode.len() {
3125 break;
3126 }
3127 self.left_mode[r + cell] = mode;
3128 self.left_uv_mode[r + cell] = uv_mode;
3129 self.left_side[r + cell] = h;
3130 }
3131
3132 let (w_mi, h_mi) = (w / MI, h / MI);
3133 self.record_mode_mi(mi_r, mi_c, w_mi, h_mi, mode);
3134 self.record_uv_mode_mi(mi_r, mi_c, w_mi, h_mi, uv_mode);
3135 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
3136 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
3137 }
3138}
3139
3140/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
3141/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
3142/// exactly — including its skip context, which the real key-frame writer
3143/// always writes at a fixed context of zero (it never tracks a neighbour-based
3144/// one for intra blocks; that is the inter-frame writer's rule instead).
3145/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
3146/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
3147/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
3148/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
3149/// plain DC chroma.
3150/// spec 5.11.47 / libaom `av1_read_tx_type`'s `fimode_to_intradir`: which
3151/// `intra_ext_tx_cdf` row a luma transform reads. A filter-intra block's
3152/// `mode` is always `DC_PRED`, so the row comes from the FILTER-INTRA mode
3153/// instead (the defect commit 1a89ed9 fixed at the square sites).
3154pub(crate) fn fi_tx_row(mode: usize, filter_intra: Option<usize>) -> usize {
3155 const FIMODE_TO_INTRADIR: [usize; 5] = [DC_PRED, V_PRED, H_PRED, D157_PRED, DC_PRED];
3156 filter_intra.map_or(mode, |fi| FIMODE_TO_INTRADIR[fi])
3157}
3158
3159/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
3160/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
3161/// bound (spec `filter_intra_mode_info` never reads a symbol there).
3162pub(crate) fn filter_intra_size_class(side: usize) -> Option<usize> {
3163 match side {
3164 4 => Some(0),
3165 8 => Some(1),
3166 16 => Some(2),
3167 32 => Some(3),
3168 _ => None,
3169 }
3170}
3171
3172/// [`filter_intra_size_class`] for a true `bw`x`bh` rect strip
3173/// (lane-intradisp r1): `av1_filter_intra_allowed_bsize` permits any bsize
3174/// with both dims <= 32, which includes `BLOCK_32X16`/`BLOCK_16X32` -- their
3175/// own distinct `cdf::FILTER_INTRA` rows, classes 4/5.
3176pub(super) fn filter_intra_size_class_rect(bw: usize, bh: usize) -> Option<usize> {
3177 match (bw, bh) {
3178 (32, 16) => Some(4),
3179 (16, 32) => Some(5),
3180 // lane-rectx r3: `av1_filter_intra_allowed_bsize` is "both sides <=
3181 // 32", so a 16x8/8x16 strip reads the flag too -- returning `None`
3182 // here dropped that symbol on every DC_PRED strip of that size and
3183 // desynced the tile (caught against an aomdec EC_TRACE_COEFF ladder:
3184 // identical mode/uv_mode values, range 34808 vs the oracle's 40668).
3185 (16, 8) => Some(6),
3186 (8, 16) => Some(7),
3187 // lane-fi8 r1: the sub-8 rect leaves are allowed too (both sides <=
3188 // 32), and `decode_leaf_rect8` codes them -- rows 1/2 of
3189 // `default_filter_intra_cdfs`, NOT BLOCK_4X4's row 0.
3190 (4, 8) => Some(8),
3191 (8, 4) => Some(9),
3192 // lane-fi32x8 r1: same bound, the 32x32-level 1:4 pair
3193 // (`decode_block_rect4`'s 32x8/8x32 strips). `None` here read no
3194 // `use_filter_intra` symbol on those strips although aomenc writes
3195 // one for every DC_PRED block of that shape with
3196 // `--enable-filter-intra=1` (its default), silently desyncing the
3197 // tile (class symbol-consumption-gap).
3198 (32, 8) => Some(10),
3199 (8, 32) => Some(11),
3200 // lane-r14: the 16x16-level 1:4 pair (`decode_rect4_16`'s 16x4/4x16
3201 // strips), rows 17/16 of `default_filter_intra_cdfs`.
3202 (16, 4) => Some(12),
3203 (4, 16) => Some(13),
3204 _ if bw == bh => filter_intra_size_class(bw),
3205 _ => None,
3206 }
3207}
3208
3209/// `av1_allow_palette`'s size bound (blockd.h: `block_size_wide/high <=
3210/// MAX_PALETTE_BLOCK_WIDTH/HEIGHT` (64) and `sb_type >= BLOCK_8X8`) plus
3211/// `av1_get_palette_bsize_ctx` (pred_common.h: `num_pels_log2_lookup[bsize]
3212/// - num_pels_log2_lookup[BLOCK_8X8]`, i.e. `log2(bw*bh) - 6`) -- `None` past
3213/// the bound (never gates a palette read), `Some(bsize_ctx)` otherwise.
3214pub(crate) fn palette_bsize_ctx(side: usize) -> Option<usize> {
3215 palette_bsize_ctx_wh(side, side)
3216}
3217
3218/// [`palette_bsize_ctx`], generalised to a true `bw`x`bh` rect strip
3219/// (lane-palette2 r4) -- the same `log2(bw*bh) - 6` formula libaom's
3220/// `num_pels_log2_lookup[bsize] - num_pels_log2_lookup[BLOCK_8X8]` computes
3221/// for ANY bsize, not just the square ones a hand-picked table happened to
3222/// enumerate before ([[cdf-row-held-constant]]: a table narrowed to a pinned
3223/// row breaks the moment its indexing field moves off the diagonal, and a
3224/// 64x32/32x64 superblock-level strip is exactly such a move). Every AV1
3225/// block dimension is a power of two, so `bw*bh` always is too and
3226/// `trailing_zeros` is `log2` exactly. `None` past `av1_allow_palette`'s own
3227/// bound (`block_size_wide/high <= 64`, `sb_type >= BLOCK_8X8`).
3228pub(super) fn palette_bsize_ctx_wh(bw: usize, bh: usize) -> Option<usize> {
3229 // lane-r14: `av1_allow_palette`'s bound is `sb_type >= BLOCK_8X8` by the
3230 // BLOCK_SIZES_ALL enum INDEX, which the 1:4 shapes BLOCK_4X16 (16) and
3231 // BLOCK_16X4 (17) clear -- a 64-pixel block, so `av1_get_palette_bsize_ctx`
3232 // (`num_pels_log2 - num_pels_log2[BLOCK_8X8]`) is 0 for them, exactly as
3233 // for an 8x8. Reading the dimension bound as "both sides >= 8" dropped
3234 // `palette_y_mode` on every 16x4/4x16 strip of a screen-content frame.
3235 if bw > 64 || bh > 64 || bw * bh < 64 {
3236 return None;
3237 }
3238 Some(((bw * bh) as u32).trailing_zeros() as usize - 6)
3239}
3240
3241/// A just-decoded palette-Y block's own size, base colours (only the first
3242/// `size` entries are real), and per-pixel colour-index map (`side*side`,
3243/// row-major, each entry `< size`).
3244pub(super) struct PaletteY {
3245 pub(super) size: usize,
3246 pub(super) colors: [u16; 8],
3247 pub(super) map: Vec<u8>,
3248}
3249
3250/// As [`PaletteY`], for a just-decoded chroma palette block: one shared
3251/// per-pixel colour-index map (spec `av1_visit_palette`'s plane-1 pass is
3252/// shared between U and V, both co-located after 4:2:0 subsampling) plus
3253/// each plane's own base colours.
3254pub(super) struct PaletteUv {
3255 pub(super) size: usize,
3256 pub(super) u_colors: [u16; 8],
3257 pub(super) v_colors: [u16; 8],
3258 pub(super) map: Vec<u8>,
3259}
3260
3261/// `aom_ceil_log2` (aom_dsp/bitwriter_buffer.h-adjacent helper, used both by
3262/// `read_palette_colors_y`'s shrinking `bits` and `av1_read_uniform`'s
3263/// `get_unsigned_bits`, which is the same formula): smallest `n` with
3264/// `2^n >= x`, `0` for `x <= 1`.
3265pub(crate) fn ceil_log2(x: u32) -> u32 {
3266 if x < 2 {
3267 0
3268 } else {
3269 32 - (x - 1).leading_zeros()
3270 }
3271}
3272
3273/// `av1_read_uniform` (decoder.h:425): a uniform `0..n` value coded as
3274/// `l-1` raw bits plus a conditional extra bit, `l = get_unsigned_bits(n)`.
3275fn read_uniform(dec: &mut SymbolDecoder, n: usize) -> usize {
3276 let l = ceil_log2(n as u32);
3277 let m = (1usize << l) - n;
3278 let v = dec.literal(l - 1) as usize;
3279 if v < m {
3280 v
3281 } else {
3282 (v << 1) - m + dec.literal(1) as usize
3283 }
3284}
3285
3286/// `merge_colors` (decodemv.c:462): interleaves the ascending `cached`
3287/// colours (already-known, from the above/left neighbours) with the
3288/// ascending `transmitted` ones (delta-coded off the wire) back into one
3289/// ascending list of `cached.len() + transmitted.len()` colours -- a tied
3290/// value picks the cached copy first, matching the C `<=`.
3291fn merge_colors(transmitted: &[u16], cached: &[u16]) -> Vec<u16> {
3292 let mut out = Vec::with_capacity(transmitted.len() + cached.len());
3293 let (mut ci, mut ti) = (0, 0);
3294 while ci < cached.len() && ti < transmitted.len() {
3295 if cached[ci] <= transmitted[ti] {
3296 out.push(cached[ci]);
3297 ci += 1;
3298 } else {
3299 out.push(transmitted[ti]);
3300 ti += 1;
3301 }
3302 }
3303 out.extend_from_slice(&cached[ci..]);
3304 out.extend_from_slice(&transmitted[ti..]);
3305 out
3306}
3307
3308/// `read_palette_colors_y` (decodemv.c:478), at the sequence's real
3309/// `bit_depth` -- lane-kf900 r3: every raw literal here (the first colour,
3310/// each delta's width, the `range` bound and the clamp) is sized by
3311/// `bit_depth`, and hardcoding 8 read 2 bits too few per colour on every
3312/// 10-bit palette block. Raw literals are EQUIPROBABLE, and at the ranges
3313/// this stream reaches (e.g. 62728) an equiprobable read is a FIXED POINT of
3314/// the msac range, so a cross-decoder range ladder stays bit-identical
3315/// through the whole miscount -- only the decoded VALUE differs (class
3316/// `compare-range-not-tell`'s blind spot). (this
3317/// decoder is 8-bit only): accepts up to `n` colours straight from `cache`
3318/// (one flag bit each, in cache order), then delta-codes the remainder
3319/// (first value raw, each following delta `>= 1` off a shrinking bit width),
3320/// and merges the two ascending lists back together.
3321pub(super) fn read_palette_colors_y(
3322 dec: &mut SymbolDecoder,
3323 n: usize,
3324 cache: &[u16],
3325 fctx: &crate::decode::FrameCtx,
3326) -> [u16; 8] {
3327 let mut cached = Vec::with_capacity(n);
3328 for &c in cache {
3329 if cached.len() >= n {
3330 break;
3331 }
3332 if dec.literal(1) == 1 {
3333 cached.push(c);
3334 }
3335 }
3336 let bd = u32::from(bit_depth(fctx));
3337 let max_val = (1i32 << bd) - 1;
3338 let mut colors = [0u16; 8];
3339 let n_cached = cached.len();
3340 if n_cached < n {
3341 let mut transmitted = Vec::with_capacity(n - n_cached);
3342 let first = dec.literal(bd) as u16;
3343 transmitted.push(first);
3344 if n_cached + 1 < n {
3345 let min_bits = bd - 3;
3346 let mut bits = min_bits + dec.literal(2);
3347 let mut range = (1i32 << bd) - i32::from(first) - 1;
3348 for _ in (n_cached + 1)..n {
3349 let delta = dec.literal(bits) as i32 + 1;
3350 let prev = *transmitted.last().unwrap();
3351 let val = (i32::from(prev) + delta).clamp(0, max_val) as u16;
3352 range -= i32::from(val) - i32::from(prev);
3353 bits = bits.min(ceil_log2(range.max(0) as u32));
3354 transmitted.push(val);
3355 }
3356 }
3357 let merged = merge_colors(&transmitted, &cached);
3358 colors[..n].copy_from_slice(&merged);
3359 } else {
3360 colors[..n].copy_from_slice(&cached[..n]);
3361 }
3362 colors
3363}
3364
3365/// `read_palette_colors_uv` (decodemv.c:509), at the sequence's real
3366/// `bit_depth` (see [`read_palette_colors_y`]): U reads
3367/// exactly [`read_palette_colors_y`]'s cache/delta scheme (against the U-only
3368/// cache, `range` starting at `255 - prev` with no `-1`, and each raw `delta`
3369/// unbiased by `+1` -- both differences from Y's own reader, matching the C
3370/// side by side). V never uses a cache: a leading bit picks either `n` raw
3371/// literals, or a first raw value plus `n-1` signed deltas that wrap mod 256
3372/// rather than clamp.
3373pub(super) fn read_palette_colors_uv(
3374 dec: &mut SymbolDecoder,
3375 n: usize,
3376 cache: &[u16],
3377 fctx: &crate::decode::FrameCtx,
3378) -> ([u16; 8], [u16; 8]) {
3379 let mut cached = Vec::with_capacity(n);
3380 for &c in cache {
3381 if cached.len() >= n {
3382 break;
3383 }
3384 if dec.literal(1) == 1 {
3385 cached.push(c);
3386 }
3387 }
3388 let bd = u32::from(bit_depth(fctx));
3389 let max_val = 1i32 << bd;
3390 let mut u_colors = [0u16; 8];
3391 let n_cached = cached.len();
3392 if n_cached < n {
3393 let mut transmitted = Vec::with_capacity(n - n_cached);
3394 let first = dec.literal(bd) as u16;
3395 transmitted.push(first);
3396 if n_cached + 1 < n {
3397 let min_bits = bd - 3;
3398 let mut bits = min_bits + dec.literal(2);
3399 let mut range = max_val - i32::from(first);
3400 for _ in (n_cached + 1)..n {
3401 let delta = dec.literal(bits) as i32;
3402 let prev = *transmitted.last().unwrap();
3403 let val = (i32::from(prev) + delta).clamp(0, max_val - 1) as u16;
3404 range -= i32::from(val) - i32::from(prev);
3405 bits = bits.min(ceil_log2(range.max(0) as u32));
3406 transmitted.push(val);
3407 }
3408 }
3409 let merged = merge_colors(&transmitted, &cached);
3410 u_colors[..n].copy_from_slice(&merged);
3411 } else {
3412 u_colors[..n].copy_from_slice(&cached[..n]);
3413 }
3414 let mut v_colors = [0u16; 8];
3415 if dec.literal(1) == 1 {
3416 let min_bits_v = bd - 4;
3417 let bits = min_bits_v + dec.literal(2);
3418 v_colors[0] = dec.literal(bd) as u16;
3419 for i in 1..n {
3420 let mut delta = dec.literal(bits) as i32;
3421 if delta != 0 && dec.literal(1) == 1 {
3422 delta = -delta;
3423 }
3424 let mut val = i32::from(v_colors[i - 1]) + delta;
3425 if val < 0 {
3426 val += max_val;
3427 }
3428 if val >= max_val {
3429 val -= max_val;
3430 }
3431 v_colors[i] = val as u16;
3432 }
3433 } else {
3434 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
3435 #[allow(clippy::needless_range_loop)]
3436 for i in 0..n {
3437 v_colors[i] = dec.literal(bd) as u16;
3438 }
3439 }
3440 (u_colors, v_colors)
3441}
3442
3443/// `av1_palette_color_index_context_lookup` (entropymode.c:889): maps a
3444/// `NUM_PALETTE_NEIGHBORS`-weighted score hash (`0..=8`) to the real
3445/// `0..=4` context, `-1` for hashes no real neighbour configuration produces.
3446pub(super) const PALETTE_COLOR_INDEX_CONTEXT_LOOKUP: [i32; 9] = [-1, -1, 0, -1, -1, 4, 3, 2, 1];
3447
3448/// `av1_get_palette_color_index_context` (entropymode.c:893): the colour-index
3449/// map's own per-pixel context and colour-order permutation, from the
3450/// left/up-left/up already-decoded neighbours (weights `[2, 1, 2]`, top-3
3451/// selection sort). `map`'s stride is `side` (this decoder never crops a
3452/// palette block's map to a narrower plane edge, [`decode_color_index_map`]'s
3453/// own doc). Returns `(ctx, color_order)`; `color_order[symbol]` is the
3454/// actual colour index to store.
3455pub(crate) fn palette_color_index_context(
3456 map: &[u8],
3457 side: usize,
3458 row: usize,
3459 col: usize,
3460 n: usize,
3461) -> (usize, [u8; 8]) {
3462 let left = if col >= 1 {
3463 Some(map[row * side + col - 1])
3464 } else {
3465 None
3466 };
3467 let up_left = if col >= 1 && row >= 1 {
3468 Some(map[(row - 1) * side + col - 1])
3469 } else {
3470 None
3471 };
3472 let up = if row >= 1 {
3473 Some(map[(row - 1) * side + col])
3474 } else {
3475 None
3476 };
3477 let mut scores = [0i32; 8];
3478 for (neighbour, weight) in [(left, 2), (up_left, 1), (up, 2)] {
3479 if let Some(v) = neighbour {
3480 scores[v as usize] += weight;
3481 }
3482 }
3483 let mut color_order = [0u8; 8];
3484 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
3485 #[allow(clippy::needless_range_loop)]
3486 for i in 0..8 {
3487 color_order[i] = i as u8;
3488 }
3489 for i in 0..3 {
3490 let mut max = scores[i];
3491 let mut max_idx = i;
3492 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
3493 #[allow(clippy::needless_range_loop)]
3494 for j in (i + 1)..n {
3495 if scores[j] > max {
3496 max = scores[j];
3497 max_idx = j;
3498 }
3499 }
3500 if max_idx != i {
3501 let max_score = scores[max_idx];
3502 let max_color = color_order[max_idx];
3503 for k in (i + 1..=max_idx).rev() {
3504 scores[k] = scores[k - 1];
3505 color_order[k] = color_order[k - 1];
3506 }
3507 scores[i] = max_score;
3508 color_order[i] = max_color;
3509 }
3510 }
3511 let hash = scores[0] + scores[1] * 2 + scores[2] * 2;
3512 let ctx = PALETTE_COLOR_INDEX_CONTEXT_LOOKUP[hash as usize];
3513 (ctx as usize, color_order)
3514}
3515
3516/// spec 5.11.50 `palette_tokens` / `av1_get_block_dimensions` (blockd.h:1512):
3517/// the ON-SCREEN part of a block at `(mi_r, mi_c)`, in luma pixels. A block
3518/// cut by the frame's bottom or right mi edge codes its colour-index map only
3519/// over this part and replicates it outward -- reading the full `bw x bh` grid
3520/// consumed symbols libaom never wrote and desynced the rest of the tile
3521/// (lane-svtinter; class map-read-past-frame-edge).
3522pub(super) fn palette_onscreen(
3523 mi_r: usize,
3524 mi_c: usize,
3525 bw: usize,
3526 bh: usize,
3527 fctx: &crate::decode::FrameCtx,
3528) -> (usize, usize) {
3529 // lane-palw: the ENCODER's own in-process reconstruct runs on a
3530 // `FrameCtx::for_encoder`, which never sees `set_segmentation` -- both
3531 // frame encoders publish the header's mi dims onto it themselves
3532 // (`encode.rs`, beside their `true_width`/`true_height`) so that this
3533 // clamp and `tile::write_color_index_map`'s now agree there too.
3534 let (mi_rows, mi_cols) = fctx.seg_mi_dims.with(|c| c.get());
3535 palette_onscreen_dims(mi_r, mi_c, bw, bh, (mi_rows, mi_cols))
3536}
3537
3538/// [`palette_onscreen`] off explicit mi dims, which is how the WRITER reaches
3539/// it (`tile::write_palette_syntax`, armed per frame): the two sides must
3540/// compute the same on-screen extent or the decoder reads a different number
3541/// of symbols than the encoder wrote.
3542pub(crate) fn palette_onscreen_dims(
3543 mi_r: usize,
3544 mi_c: usize,
3545 bw: usize,
3546 bh: usize,
3547 (mi_rows, mi_cols): (usize, usize),
3548) -> (usize, usize) {
3549 (
3550 bw.min(mi_cols.saturating_sub(mi_c) * MI),
3551 bh.min(mi_rows.saturating_sub(mi_r) * MI),
3552 )
3553}
3554
3555/// [`palette_onscreen`] carried into the chroma plane: `>> subsampling` plus
3556/// the SAME sub-8 bump the caller's own `(bw >> ss).max(4)` applies to the
3557/// block dimensions (`is_chroma_sub8_x/y`, blockd.h:1533) -- both must move
3558/// together or a cut 8-wide block reads its chroma map at the wrong width.
3559/// lane-av1-444: the shifts are the sequence's own subsampling (a 4:4:4
3560/// intra-in-inter palette read its chroma map at the 4:2:0 extent and
3561/// panicked feeding the 4:2:0-sized prediction to a full-size reconstruct).
3562pub(crate) fn palette_onscreen_uv(
3563 luma: (usize, usize),
3564 on: (usize, usize),
3565 chroma: (usize, usize),
3566 ss: (usize, usize),
3567) -> (usize, usize) {
3568 (
3569 (on.0 >> ss.0) + (chroma.0 - (luma.0 >> ss.0)),
3570 (on.1 >> ss.1) + (chroma.1 - (luma.1 >> ss.1)),
3571 )
3572}
3573
3574/// `decode_color_map_tokens` (detokenize.c:25): the palette-Y colour-index
3575/// map's wavefront decode over a `side x side` grid, read over the on-screen
3576/// `on_side x on_side` corner (see [`palette_onscreen`]).
3577pub(super) fn decode_color_index_map(
3578 dec: &mut SymbolDecoder,
3579 cdfs: &mut Cdfs,
3580 n: usize,
3581 side: usize,
3582 on: (usize, usize),
3583 uv: bool,
3584) -> Vec<u8> {
3585 decode_color_index_map_wh(dec, cdfs, n, side, side, on, uv)
3586}
3587
3588/// [`decode_color_index_map`], generalised to a true `bw`x`bh` rect strip
3589/// (lane-palette2 r4): `decode_color_map_tokens`'s own wavefront diagonal
3590/// (`row = i - j`, `col = j`) walked over `cols = bw`, `rows = bh`
3591/// independently rather than one shared `side` -- the square call above is
3592/// just `bw == bh`.
3593pub(super) fn decode_color_index_map_wh(
3594 dec: &mut SymbolDecoder,
3595 cdfs: &mut Cdfs,
3596 n: usize,
3597 bw: usize,
3598 bh: usize,
3599 // `(onscreenWidth, onscreenHeight)` in this plane's own units.
3600 on: (usize, usize),
3601 uv: bool,
3602) -> Vec<u8> {
3603 let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
3604 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
3605 if on_bw < bw || on_bh < bh {
3606 hit!(PALETTE_ONSCREEN_CUT_HITS);
3607 }
3608 let mut map = vec![0u8; bw * bh];
3609 if trace {
3610 let (rng, _) = dec.debug_state();
3611 eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
3612 }
3613 map[0] = read_uniform(dec, n) as u8;
3614 if trace {
3615 let (rng, _) = dec.debug_state();
3616 eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
3617 }
3618 for i in 1..(on_bw + on_bh - 1) {
3619 let j_hi = i.min(on_bw - 1);
3620 let j_lo = i.saturating_sub(on_bh - 1);
3621 for j in (j_lo..=j_hi).rev() {
3622 let row = i - j;
3623 let col = j;
3624 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
3625 if trace {
3626 let (rng, _) = dec.debug_state();
3627 let row_cdf = if uv {
3628 &cdfs.palette_uv_color_index[n - 2][ctx]
3629 } else {
3630 &cdfs.palette_y_color_index[n - 2][ctx]
3631 };
3632 eprintln!(
3633 "EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}",
3634 row_cdf[0], row_cdf[n]
3635 );
3636 }
3637 let symbol = if uv {
3638 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
3639 } else {
3640 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
3641 };
3642 map[row * bw + col] = color_order[symbol];
3643 if trace {
3644 let (rng, _) = dec.debug_state();
3645 eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
3646 }
3647 }
3648 }
3649 palette_replicate(&mut map, bw, bh, on);
3650 map
3651}
3652
3653/// `decode_color_map_tokens`'s own two extension loops (detokenize.c:71): the
3654/// last on-screen column then the last on-screen row are replicated over the
3655/// off-screen remainder, so the prediction still covers the whole block. The
3656/// ENCODER runs this over its searched map too (`encode.rs`'s palette arms),
3657/// so the pixels it prices and reconstructs are the ones the on-screen
3658/// symbols it writes really decode to.
3659pub(crate) fn palette_replicate(map: &mut [u8], bw: usize, bh: usize, on: (usize, usize)) {
3660 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
3661 for row in 0..on_bh {
3662 let last = map[row * bw + on_bw - 1];
3663 map[row * bw + on_bw..row * bw + bw].fill(last);
3664 }
3665 for row in on_bh..bh {
3666 map.copy_within((on_bh - 1) * bw..on_bh * bw, row * bw);
3667 }
3668}
3669
3670/// `read_angle_delta`/`Angle_Delta` (spec 5.11.42 + 9.3): the symbol minus
3671/// [`ANGLE_DELTA_ZERO`] gives the signed `-MAX_ANGLE_DELTA..=MAX_ANGLE_DELTA`
3672/// delta [`crate::intra::predict`] wants; bumps [`ANGLE_DELTA_HITS`] whenever
3673/// it lands away from zero, for gate tests to prove a real stream fired one.
3674pub(super) fn read_angle_delta(dec: &mut SymbolDecoder, cdf: &mut [u16]) -> i32 {
3675 let symbol = dec.symbol(cdf);
3676 if symbol != ANGLE_DELTA_ZERO {
3677 hit!(ANGLE_DELTA_HITS);
3678 }
3679 symbol as i32 - ANGLE_DELTA_ZERO as i32
3680}
3681
3682/// lane-perf7 step 1: [`cdef_filter_block`]'s AVX2 kernel -- the scalar
3683/// filter was 13.1% of a 4K decode's self time. Nothing here is spec logic:
3684/// the same taps, the same `constrain`, the same `min`/`max` clamp with the
3685/// `CDEF_VERY_LARGE` sentinel excluded from the max, the same
3686/// `y + ((8 + sum - (sum < 0)) >> 4)` rounding, done 16 samples (two rows) at
3687/// a time in 16-bit lanes.
3688///
3689/// 16-bit lanes are exact for every value this filter sees: window samples
3690/// are in `[0, CDEF_VERY_LARGE]` (0x4000), so a tap difference fits in
3691/// `i16`, a `constrain` result is bounded by the threshold (at most
3692/// `15 << 4`), and the tap-weighted sum by `24 *` that.
3693/// Spec 7.14: the in-loop deblocking filter, applied once per frame after
3694/// tile reconstruction and before [`apply_cdef`]. Uniform-level path only --
3695/// `stream.rs` already refuses `delta_lf_present`/segmentation upstream, so
3696/// every block's level comes from [`LoopFilterParams::level`] plus the
3697/// `ref_deltas`/`mode_deltas` adjustment alone (spec 7.14.4's
3698/// `get_filter_level`, precomputed per-block here rather than cached in a
3699/// table the way libaom's `av1_loop_filter_frame_init` does).
3700///
3701/// Ported from libaom's `av1/common/av1_loopfilter.c` (edge/level decision)
3702/// and `aom_dsp/loopfilter.c` (the `aom_lpf_*` pixel kernels).
3703// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
3704#[allow(clippy::too_many_arguments)]
3705pub(super) fn apply_deblock(
3706 y: &mut PlaneBuf<'static>,
3707 u: &mut PlaneBuf<'static>,
3708 v: &mut PlaneBuf<'static>,
3709 lf: &LoopFilterParams,
3710 n: &Neighbours,
3711 frame_width: usize,
3712 frame_height: usize,
3713 fctx: &crate::decode::FrameCtx,
3714) {
3715 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
3716 // mismatch between the raw reconstruction and post-filter output.
3717 if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_DEBLOCK") {
3718 return;
3719 }
3720 if lf.level[0] != 0 || lf.level[1] != 0 {
3721 deblock_plane(y, 0, lf, n, frame_width, frame_height, fctx);
3722 }
3723 if lf.level[2] != 0 {
3724 deblock_plane(u, 1, lf, n, frame_width, frame_height, fctx);
3725 }
3726 if lf.level[3] != 0 {
3727 deblock_plane(v, 2, lf, n, frame_width, frame_height, fctx);
3728 }
3729}
3730
3731/// Luma-mi-grid position (row or col) a plane-local pixel coordinate falls
3732/// in -- `Neighbours::tx_grid`/`ref_grid` are always indexed at the luma
3733/// 4x4-mi grain, even when `coord` is a chroma coordinate (2 chroma px per
3734/// mi unit under this decoder's assumed 4:2:0 subsampling).
3735///
3736/// lane-t900 r30b: the chroma arm ORs in the subsampling, exactly as
3737/// `set_lpf_parameters` does (`av1_loopfilter.c:245`, `mi_col = scale_horz |
3738/// ((x << scale_horz) >> MI_SIZE_LOG2)`) -- "for sub8x8 block, chroma
3739/// prediction mode is obtained from the bottom/right mi structure of the
3740/// co-located 8x8 luma block, so for chroma plane both mi_row and mi_col
3741/// should be odd". Dropping that `| 1` read the group's TOP-LEFT mi, which
3742/// is the same cell for every block 8x8 and larger and a DIFFERENT coded
3743/// block (different tx size, ref frame, skip flag and delta_lf) as soon as
3744/// the group is split into 4x4 luma blocks (class
3745/// `context-read-from-one-cell`).
3746pub(super) fn plane_to_mi(chroma: bool, coord: usize, ss: usize) -> usize {
3747 // scale | ((coord << scale) >> 2). ss=1 is (coord/2)|1; ss=0 is coord/4.
3748 if chroma {
3749 ss | ((coord << ss) >> 2)
3750 } else {
3751 coord / 4
3752 }
3753}
3754
3755/// This plane's own transform width in pixels at the covering block, spec
3756/// `get_transform_size`'s plane-aware lookup: `tx_grid` stores the luma
3757/// width directly; chroma halves it (this decoder's UV transform is always
3758/// half its coded block's luma transform, spec's `av1_get_max_uv_txsize`
3759/// under 4:2:0 and a block that never splits its own transform).
3760pub(super) fn tx_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
3761 let grid = if chroma { &n.uv_tx_grid } else { &n.tx_grid };
3762 grid.get(mi_r * n.skip_grid_cols_mi + mi_c)
3763 .copied()
3764 .unwrap_or(0) as u32
3765}
3766
3767/// [`tx_px_at`]'s HEIGHT twin (lane-rect r2): the deblocker's horizontal
3768/// edges step and gate by transform height, which differs from width only
3769/// on rect partition strips.
3770pub(super) fn tx_h_px_at(n: &Neighbours, chroma: bool, mi_r: usize, mi_c: usize) -> u32 {
3771 let grid = if chroma {
3772 &n.uv_tx_h_grid
3773 } else {
3774 &n.tx_h_grid
3775 };
3776 grid.get(mi_r * n.skip_grid_cols_mi + mi_c)
3777 .copied()
3778 .unwrap_or(0) as u32
3779}
3780
3781/// `get_tx_size_context` (spec 9.3's `TxDepthCtx`, libaom
3782/// `TXFM_CONTEXT`/`entropymode.c`): the sum of two boolean terms, each
3783/// present only when its neighbour exists inside the true frame -- whether
3784/// the block immediately above (at this block's own leftmost mi column) or
3785/// to the left (at its own topmost mi row) coded a transform at least as wide
3786/// (tall) as this block's own `max_txsize_rect_lookup[bsize]`.
3787///
3788/// lane-av1txbands: this reads the real `TXFM_CONTEXT` bands
3789/// ([`Neighbours::above_txfm`]/[`Neighbours::left_txfm`]) for EVERY frame
3790/// now -- libaom maintains them on intra-only frames too (`parse_decode_block`
3791/// runs `set_txfm_ctxs` for every block, and
3792/// [`Neighbours::fill_lf_grid_rect`] publishes them there), except that an
3793/// *inter* neighbour contributes its own BLOCK size rather than its transform
3794/// size -- and libaom's `is_inter_block` counts an INTRABC block
3795/// (`blockd.h:373`), which is what the `above_inter`/`left_inter` bands carry.
3796/// The previous deblock-grid approximation coincided with this only while
3797/// every neighbour coded one whole-block transform, which is exactly what
3798/// `TxMode::Select` ends.
3799///
3800/// The rect form (lane-intrasplit r1): `get_tx_size_context` compares the
3801/// neighbour ABOVE against `tx_size_wide[max_txsize_rect_lookup[bsize]]` and
3802/// the neighbour to the LEFT against `tx_size_high[...]` (libaom
3803/// `pred_common.h:342`), which for a 2:1 strip are two different numbers.
3804pub(super) fn tx_size_context_txfm_rect(
3805 n: &Neighbours,
3806 (mi_r, mi_c): (usize, usize),
3807 own_w: usize,
3808 own_h: usize,
3809 fctx: &crate::decode::FrameCtx,
3810) -> usize {
3811 hit!(INTRA_IN_INTER_TXCTX_HITS);
3812 // `max_txsize_rect_lookup[bsize]` tops out at TX_64X64: no transform is
3813 // wider or taller than 64, so a block with a 128 side resolves against 64
3814 // (lane-sb128b r1).
3815 let (own_w, own_h) = (own_w.min(64), own_h.min(64));
3816 let has_above = mi_r > n.tile_row0_mi;
3817 let has_left = mi_c > n.tile_col0_mi;
3818 let mut above = usize::from(n.above_txfm[mi_c]) >= own_w;
3819 let mut left = usize::from(n.left_txfm[mi_r]) >= own_h;
3820 // lane-av1txctxband: the override's gate and its size term are read at
3821 // the ABUTTING CELL -- libaom's `xd->above_mbmi` is `xd->mi[-mi_stride]`
3822 // and `xd->left_mbmi` is `xd->mi[-1]` (`set_mi_offsets`,
3823 // av1_common_int.h:1381-1389), which `setup_mbs` fills with the pointer
3824 // of the block COVERING that cell (decodeframe.c:355-361). The old code
3825 // read the per-COLUMN `above_inter`/`left_inter` bands and the matching
3826 // `above_side_mi`/`left_side_mi` bands, i.e. the LAST block written in
3827 // that column, which names the abutting block only for the block directly
3828 // below it. Measured: on the 4:4:4 lossy `--sb-size=128` cq-62 stream the
3829 // 8x4 intra leaf at mi(57,52) saw a stale `above_inter=true` (from an
3830 // intrabc block earlier in column 52) with `above_side=4`, took the
3831 // override, and read `tx_size_cat0[1]` where libaom reads row 2.
3832 if has_above && n.inter_at(mi_r - 1, mi_c) {
3833 above = n.blk_side_at(mi_r - 1, mi_c).0 >= own_w;
3834 }
3835 if has_left && n.inter_at(mi_r, mi_c - 1) {
3836 left = n.blk_side_at(mi_r, mi_c - 1).1 >= own_h;
3837 }
3838 // lane-av1txctxband: the non-vacuity arm. It counts the reads whose
3839 // RESOLVED context term differs from what the old per-column bands would
3840 // have produced -- not merely reads where the two `is_inter` booleans
3841 // disagree, because on the measured witness they AGREE (`above_inter` and
3842 // the per-cell cover are both true at mi(57,52)) and it is the SIZE term
3843 // that is stale (band 4 vs the covering block's own 8), which is what put
3844 // the read on `tx_size_cat0[1]` instead of row 2.
3845 {
3846 let band_above = has_above
3847 && if n.above_inter[mi_c] {
3848 usize::from(n.above_side_mi[mi_c]) >= own_w
3849 } else {
3850 usize::from(n.above_txfm[mi_c]) >= own_w
3851 };
3852 let band_left = has_left
3853 && if n.left_inter[mi_r] {
3854 usize::from(n.left_side_mi[mi_r]) >= own_h
3855 } else {
3856 usize::from(n.left_txfm[mi_r]) >= own_h
3857 };
3858 if band_above != (has_above && usize::from(above) != 0)
3859 || band_left != (has_left && usize::from(left) != 0)
3860 {
3861 hit!(TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS);
3862 }
3863 }
3864 if crate::envflags::env_flag!("EC_TXCTX") {
3865 eprintln!(
3866 "EC_TXCTX mi={mi_r},{mi_c} own={own_w}x{own_h} ha={has_above} hl={has_left} \
3867 intra_only={} above_txfm={} left_txfm={} above_inter={} left_inter={} \
3868 above_side={} left_side={} above={above} left={left} \
3869 | cell_inter ab={} lb={} ab_side={} lb_side={}",
3870 fctx.intra_only.with(std::cell::Cell::get),
3871 n.above_txfm[mi_c],
3872 n.left_txfm[mi_r],
3873 n.above_inter[mi_c],
3874 n.left_inter[mi_r],
3875 n.above_side_mi[mi_c],
3876 n.left_side_mi[mi_r],
3877 // lane-av1txctxband: the per-CELL terms this read now uses, next to
3878 // the per-column bands it used to use, so a divergence names which
3879 // of the two disagreed.
3880 if has_above { n.inter_at(mi_r - 1, mi_c) } else { false },
3881 if has_left { n.inter_at(mi_r, mi_c - 1) } else { false },
3882 if has_above { n.blk_side_at(mi_r - 1, mi_c).0 } else { 0 },
3883 if has_left { n.blk_side_at(mi_r, mi_c - 1).1 } else { 0 },
3884 );
3885 }
3886 let ctx = match (has_above, has_left) {
3887 (true, true) => usize::from(above) + usize::from(left),
3888 (true, false) => usize::from(above),
3889 (false, true) => usize::from(left),
3890 (false, false) => 0,
3891 };
3892 {
3893 let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w)
3894 + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h);
3895 if ctx != stale {
3896 hit!(TXCTX_DEBLOCK_DIVERGENCE_HITS);
3897 }
3898 }
3899 ctx
3900}
3901
3902/// lane-intrasplit r3: `above_inter`/`left_inter` are mi-granular bands (they
3903/// are written and read everywhere else with a raw mi index); the SUB-cell
3904/// division this pair used read a cell four blocks away, so the inter-neighbour
3905/// override above fired on the wrong neighbour -- the first divergence of the
3906/// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1,
3907/// at the intra block right of an inter one).
3908pub(super) fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
3909 let has_above = mi_r > n.tile_row0_mi;
3910 let has_left = mi_c > n.tile_col0_mi;
3911 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
3912 let mut left = usize::from(n.left_txfm[mi_r]) >= side;
3913 // lane-angledelta r1 (class [[context-read-from-one-cell]]): both
3914 // `above_inter`/`left_inter` bands are written per MI unit
3915 // (`record_inter_rect_mi`), so they are read per MI too -- the `/ (SUB /
3916 // MI)` here read the 16-px cell's FIRST mi instead, i.e. a different
3917 // block whenever the neighbour column/row is not the cell's first. A
3918 // 16x16 intra block whose left neighbour is an inter block at mi row 4
3919 // then missed libaom's "an inter neighbour contributes its BLOCK size"
3920 // override and read `tx_size_cat1` row 1 where aomdec reads row 2.
3921 // lane-angledelta r1 (class [[context-read-from-one-cell]]) fixed the
3922 // `/ (SUB / MI)` on this pair; lane-av1txctxband fixes what it could not:
3923 // the bands are per COLUMN, so they name the last block written in the
3924 // column, not the block covering the abutting cell. libaom's
3925 // `xd->above_mbmi` is `xd->mi[-xd->mi_stride]` and `xd->left_mbmi` is
3926 // `xd->mi[-1]` (`set_mi_offsets`, av1_common_int.h:1381-1389), and
3927 // `setup_mbs` (decodeframe.c:355-361) writes the covering block's own
3928 // pointer into every mi cell the block covers.
3929 if has_above && n.inter_at(mi_r - 1, mi_c) {
3930 above = n.blk_side_at(mi_r - 1, mi_c).0 >= side;
3931 }
3932 if has_left && n.inter_at(mi_r, mi_c - 1) {
3933 left = n.blk_side_at(mi_r, mi_c - 1).1 >= side;
3934 }
3935 // lane-av1txctxband: the non-vacuity arm (see the rect form above).
3936 {
3937 let band_above = has_above
3938 && if n.above_inter[mi_c] {
3939 usize::from(n.above_side_mi[mi_c]) >= side
3940 } else {
3941 usize::from(n.above_txfm[mi_c]) >= side
3942 };
3943 let band_left = has_left
3944 && if n.left_inter[mi_r] {
3945 usize::from(n.left_side_mi[mi_r]) >= side
3946 } else {
3947 usize::from(n.left_txfm[mi_r]) >= side
3948 };
3949 if band_above != (has_above && usize::from(above) != 0)
3950 || band_left != (has_left && usize::from(left) != 0)
3951 {
3952 hit!(TXCTX_INTER_CELL_BAND_DIVERGENCE_HITS);
3953 }
3954 }
3955 if crate::envflags::env_flag!("EC_TXCTX") {
3956 eprintln!(
3957 "EC_TXCTX mi={mi_r},{mi_c} own={side} ha={has_above} hl={has_left} \
3958 above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
3959 above={above} left={left} | cell_inter ab={} lb={} ab_side={} lb_side={}",
3960 n.above_txfm[mi_c],
3961 n.left_txfm[mi_r],
3962 n.above_inter[mi_c],
3963 n.left_inter[mi_r],
3964 n.above_side_mi[mi_c],
3965 n.left_side_mi[mi_r],
3966 if has_above { n.inter_at(mi_r - 1, mi_c) } else { false },
3967 if has_left { n.inter_at(mi_r, mi_c - 1) } else { false },
3968 if has_above { n.blk_side_at(mi_r - 1, mi_c).0 } else { 0 },
3969 if has_left { n.blk_side_at(mi_r, mi_c - 1).1 } else { 0 },
3970 );
3971 }
3972 match (has_above, has_left) {
3973 (true, true) => usize::from(above) + usize::from(left),
3974 (true, false) => usize::from(above),
3975 (false, true) => usize::from(left),
3976 (false, false) => 0,
3977 }
3978}
3979
3980/// `read_tx_size`/`read_selected_tx_size` (spec 5.11.16): under
3981/// `TxMode::Select`, an intra block's `tx_depth` symbol, resolved straight to
3982/// the transform's own side in pixels (`side >> depth`) -- this decoder's
3983/// four square categories (8/16/32/64) each halve at most twice, matching
3984/// libaom's own per-size depth cap (`cdf::TX_SIZE_CAT0`..`TX_SIZE_CAT3`).
3985pub(super) fn read_tx_size(
3986 dec: &mut SymbolDecoder,
3987 cdfs: &mut Cdfs,
3988 n: &Neighbours,
3989 at_mi: (usize, usize),
3990 side: usize,
3991 fctx: &crate::decode::FrameCtx,
3992) -> usize {
3993 // libaom `read_tx_size`'s FIRST line (decodeframe.c:1203):
3994 // `if (xd->lossless[xd->mi[0]->segment_id]) return TX_4X4;` -- before the
3995 // `tx_mode == TX_MODE_SELECT` test and before any symbol. Invisible while
3996 // every lossless frame was ALSO `CodedLossless` (its `tx_mode` is forced
3997 // `Only4x4`, so this function never ran); a MIXED frame keeps
3998 // `TxMode::Select`, so its lossless segments reach the symbol read and
3999 // must take the early return (lane-av1mixloss).
4000 if lossless(fctx) {
4001 return 4;
4002 }
4003 // `max_txsize_rect_lookup[bsize]` (libaom `read_selected_tx_size` /
4004 // `get_tx_size_context`): a block wider than 64 still tops out at
4005 // TX_64X64, so BLOCK_128X128 reads BLOCK_64X64's own category (its depth
4006 // chain 64->32->16->8->4 is the same four steps) and resolves against 64,
4007 // never against its own 128 side (lane-sb128b r1).
4008 let max_tx = side.min(64);
4009 let ctx = tx_size_context_txfm(n, at_mi, max_tx);
4010 let depth = match max_tx {
4011 8 => dec.symbol(&mut cdfs.tx_size_cat0[ctx]),
4012 16 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
4013 32 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
4014 64 => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
4015 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),
4016 };
4017 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
4018 let (rng, _) = dec.debug_state();
4019 let (mi_r, mi_c) = at_mi;
4020 eprintln!(
4021 "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
4022 );
4023 }
4024 if depth != 0 {
4025 hit!(TX_DEPTH_HITS);
4026 }
4027 max_tx >> depth
4028}
4029
4030/// `txfm_partition_context` (libaom `av1_common_int.h`): an inter block's
4031/// `txfm_split` context -- a category from the block's own largest square
4032/// transform and whether this unit already sits below it, times three, plus
4033/// the two neighbour terms (whether the transform last written above/left of
4034/// this unit is narrower/shorter than the unit itself).
4035#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4036pub(super) fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
4037 txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px)
4038}
4039
4040/// [`txfm_partition_ctx`] for a *rectangular* transform (lane-inter4 r2):
4041/// libaom's `txfm_partition_context` compares the above context against
4042/// `tx_size_wide` and the left one against `tx_size_high`, and takes its
4043/// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one
4044/// side for a square transform, which is why the square form above is a
4045/// special case of this one.
4046pub(crate) fn txfm_partition_ctx_rect(
4047 above_px: u8,
4048 left_px: u8,
4049 blk_max_px: usize,
4050 tx_w: usize,
4051 tx_h: usize,
4052) -> usize {
4053 let above = usize::from(usize::from(above_px) < tx_w);
4054 let left = usize::from(usize::from(left_px) < tx_h);
4055 let tx_px = tx_w.max(tx_h);
4056 // `get_sqr_tx_size(max(block_size_wide, block_size_high))`, capped at the
4057 // largest transform (`TX_64X64`); `TX_4X4`..`TX_64X64` index as
4058 // `log2(px) - 2`.
4059 let max_tx = blk_max_px.min(64);
4060 let max_idx = max_tx.trailing_zeros() as usize - 2;
4061 let category = usize::from(tx_px != max_tx && max_tx > 8) + (4 - max_idx) * 2;
4062 category * 3 + above + left
4063}
4064
4065/// `txfm_partition_update` (libaom `av1_common_int.h`): once a var-tx unit
4066/// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
4067/// resolved transform's own size.
4068#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
4069pub(super) fn txfm_partition_update(n: &mut Neighbours, at_mi: (usize, usize), tx_px: usize, txb_px: usize) {
4070 txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px));
4071}
4072
4073/// [`txfm_partition_update`] for a rectangular transform (lane-inter4 r2):
4074/// the left column records `tx_size_high` over the parent's own height and
4075/// the above row records `tx_size_wide` over its width.
4076/// libaom `set_txfm_ctxs` + `txfm_partition_update` (`decodeframe.c`, end of
4077/// `decode_token_recon_block`): EVERY block of an inter frame publishes its
4078/// TRANSFORM size into both `TXFM_CONTEXT` bands, intra blocks included. The
4079/// key frame writes neither (its readers use the deblock grid), so the
4080/// key-frame bodies reused by [`decode_intra_rect_in_inter`] have to do it
4081/// themselves when they run inside an inter frame. The 2:1 and 16x4 arms do it
4082/// at the call site (the transform size comes back to them); the 1:4 arms
4083/// ([`decode_block_rect4`] / [`decode_block_rect64`]) keep their size inside,
4084/// so they call this where their own depth resolves. A no-op on a key frame
4085/// ([`INTRA_IN_INTER_MODE`] unset), where those bands are not read at all.
4086///
4087/// lane-t900 r1 root cause: the HORZ_4 32x8 intra strip at mi(0,312) of an
4088/// inter frame left `left_txfm[0]` at a stale 32 where libaom's own
4089/// `set_txfm_ctxs` writes 8, so the intra 8x16 block at mi(0,320) read
4090/// `tx_size_cat1` row 1 instead of row 0 -- same depth VALUE, different CDF,
4091/// range 39156 where the reference has 54736 (class tx-grid-published-block-side
4092/// / early-return-skips-tail).
4093///
4094/// lane-av1-intrabc r3: an `allow_intrabc` KEY frame reads the same bands --
4095/// `read_intra_frame_mode_info` returns early for an intrabc block, so
4096/// [`read_block_tx_size_rect`]'s var-tx tree is the intra path's one
4097/// `txfm_partition_context` reader, and it reads whatever the block ABOVE and
4098/// the block LEFT published. [`decode_block`] has published on such a frame
4099/// since lane-t900 r32; the RECT strips did not, so the band still held the
4100/// value of an older, smaller neighbour -- measured on the 256x192 testsrc2
4101/// cq45 var-tx arm: the coded 16x8 intrabc strip at mi(38,48) read ctx 14
4102/// where libaom reads 13 (`left_ctx` 4 vs the 8 the 16x8 intra strip at
4103/// mi(38,44) should have published), desyncing the tile there.
4104pub(super) fn publish_txfm_bands_if_in_inter(
4105 n: &mut Neighbours,
4106 at_mi: (usize, usize),
4107 (tx_w, tx_h): (usize, usize),
4108 (bw, bh): (usize, usize),
4109 fctx: &crate::decode::FrameCtx,
4110) {
4111 if fctx
4112 .intra_in_inter_mode
4113 .with(std::cell::Cell::get)
4114 .is_none()
4115 && !allow_intrabc_frame(fctx)
4116 {
4117 return;
4118 }
4119 let (mi_r, mi_c) = at_mi;
4120 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
4121 for i in 0..bw / MI {
4122 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
4123 *cell = tx_w as u8;
4124 }
4125 }
4126 for i in 0..bh / MI {
4127 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
4128 *cell = tx_h as u8;
4129 }
4130 }
4131}
4132
4133pub(super) fn txfm_partition_update_rect(
4134 n: &mut Neighbours,
4135 (mi_r, mi_c): (usize, usize),
4136 (tx_w, tx_h): (usize, usize),
4137 (txb_w, txb_h): (usize, usize),
4138) {
4139 if crate::envflags::env_flag!("EC_TXUPD") {
4140 eprintln!(
4141 "EC_TXUPD rect mi=({},{}) tx=({tx_w},{tx_h}) txb=({txb_w},{txb_h})",
4142 mi_r, mi_c
4143 );
4144 }
4145 for i in 0..txb_h / MI {
4146 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
4147 *cell = tx_h as u8;
4148 }
4149 }
4150 for i in 0..txb_w / MI {
4151 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
4152 *cell = tx_w as u8;
4153 }
4154 }
4155}
4156
4157/// `set_txfm_ctxs` (libaom `av1_common_int.h`): the non-var-tx write of the
4158/// same contexts -- a skipped *inter* block records its own block size rather
4159/// than its transform size.
4160pub(super) fn set_txfm_ctxs(
4161 n: &mut Neighbours,
4162 (mi_r, mi_c): (usize, usize),
4163 tx_px: usize,
4164 w_mi: usize,
4165 h_mi: usize,
4166 skip_inter: bool,
4167) {
4168 if crate::envflags::env_flag!("EC_TXUPD") {
4169 eprintln!(
4170 "EC_TXUPD ctxs mi=({mi_r},{mi_c}) tx={tx_px} wh=({w_mi},{h_mi}) skip_inter={skip_inter}"
4171 );
4172 }
4173 let bw = if skip_inter { w_mi * MI } else { tx_px };
4174 let bh = if skip_inter { h_mi * MI } else { tx_px };
4175 for i in 0..w_mi {
4176 if let Some(cell) = n.above_txfm.get_mut(mi_c + i) {
4177 *cell = bw as u8;
4178 }
4179 }
4180 for i in 0..h_mi {
4181 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
4182 *cell = bh as u8;
4183 }
4184 }
4185}
4186
4187/// The value libaom initialises both transform contexts to -- NOT zero:
4188/// `av1_zero_above_context` memsets the txfm row to
4189/// `tx_size_wide[TX_SIZES_LARGEST]` and `av1_zero_left_context` does the same
4190/// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
4191/// pixels, so an unwritten neighbour reads as the *widest* possible
4192/// transform, not the narrowest.
4193pub(crate) const TXFM_CTX_INIT: u8 = 64;
4194
4195/// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
4196/// twice below its own largest transform.
4197pub(super) const MAX_VARTX_DEPTH: usize = 2;
4198
4199/// libaom `sub_tx_size_map[TX_SIZES_ALL]` (`common_data.c`): the transform
4200/// one `txfm_split` step below `tx_size`. RECTANGULAR for the 1:4 shapes
4201/// (`[TX_64X16] == TX_32X16`, `[TX_16X64] == TX_16X32`) and for the 4:1
4202/// small ones, square everywhere else.
4203pub(super) fn sub_tx_size_map(tx_w: usize, tx_h: usize) -> (usize, usize) {
4204 match (tx_w, tx_h) {
4205 (4, 4) => (4, 4),
4206 (8, 8) => (4, 4),
4207 (16, 16) => (8, 8),
4208 (32, 32) => (16, 16),
4209 (64, 64) => (32, 32),
4210 (4, 8) | (8, 4) => (4, 4),
4211 (8, 16) | (16, 8) => (8, 8),
4212 (16, 32) | (32, 16) => (16, 16),
4213 (32, 64) | (64, 32) => (32, 32),
4214 (4, 16) => (4, 8),
4215 (16, 4) => (8, 4),
4216 (8, 32) => (8, 16),
4217 (32, 8) => (16, 8),
4218 (16, 64) => (16, 32),
4219 (64, 16) => (32, 16),
4220 _ => unreachable!("not a TX_SIZES_ALL shape: {tx_w}x{tx_h}"),
4221 }
4222}
4223
4224#[test]
4225fn sub_tx_size_map_matches_libaom() {
4226 // libaom `common_data.c` `sub_tx_size_map`, in TX_SIZES_ALL order.
4227 const TABLE: [((usize, usize), (usize, usize)); 19] = [
4228 ((4, 4), (4, 4)),
4229 ((8, 8), (4, 4)),
4230 ((16, 16), (8, 8)),
4231 ((32, 32), (16, 16)),
4232 ((64, 64), (32, 32)),
4233 ((4, 8), (4, 4)),
4234 ((8, 4), (4, 4)),
4235 ((8, 16), (8, 8)),
4236 ((16, 8), (8, 8)),
4237 ((16, 32), (16, 16)),
4238 ((32, 16), (16, 16)),
4239 ((32, 64), (32, 32)),
4240 ((64, 32), (32, 32)),
4241 ((4, 16), (4, 8)),
4242 ((16, 4), (8, 4)),
4243 ((8, 32), (8, 16)),
4244 ((32, 8), (16, 8)),
4245 ((16, 64), (16, 32)),
4246 ((64, 16), (32, 16)),
4247 ];
4248 for (tx, want) in TABLE {
4249 assert_eq!(sub_tx_size_map(tx.0, tx.1), want, "sub_tx_size_map({tx:?})");
4250 }
4251}
4252
4253/// lane-av1oddheightfork3: `txfm_partition_update_rect`'s EXTENT is the
4254/// transform NODE (`txb`), its VALUE is the resolved leaf -- the rule
4255/// `txfm_partition_update` states as
4256/// `bsize = txsize_to_bsize[txb_size]; bh = mi_size_high[bsize];
4257/// bw = mi_size_wide[bsize]; left_ctx[0..bh] = tx_size_high[tx_size];
4258/// above_ctx[0..bw] = tx_size_wide[tx_size]` (`av1_common_int.h:1684-1695`).
4259///
4260/// The 320x236 ticket named the RECT case as the suspect ("`txsize_to_bsize`
4261/// for a rect `txb_size` is the awkward part"). It is not: for every
4262/// `TX_SIZE`, `mi_size_wide[txsize_to_bsize[t]] * MI == tx_size_wide[t]`, which
4263/// is what makes `txb_w / MI` the right cell count. This test pins that
4264/// identity from libaom's OWN `mi_size_wide`/`mi_size_high` rows (blockd.h)
4265/// -- transcribed, not derived from the shape -- and then pins the primitive
4266/// on a rect node, where an extent taken from the leaf instead of the node
4267/// would write 1 cell where libaom writes 2 and 1 where libaom writes 4.
4268#[test]
4269fn txfm_partition_update_rect_extent_is_the_node_not_the_leaf() {
4270 // libaom `blockd.h`: (bsize, mi_size_wide, mi_size_high) for every
4271 // `txsize_to_bsize` image a `TX_SIZE` can name.
4272 const BSIZES: [(&str, usize, usize); 12] = [
4273 ("BLOCK_4X4", 1, 1),
4274 ("BLOCK_4X8", 1, 2),
4275 ("BLOCK_8X4", 2, 1),
4276 ("BLOCK_8X8", 2, 2),
4277 ("BLOCK_8X16", 2, 4),
4278 ("BLOCK_16X8", 4, 2),
4279 ("BLOCK_16X16", 4, 4),
4280 ("BLOCK_16X32", 4, 8),
4281 ("BLOCK_32X16", 8, 4),
4282 ("BLOCK_32X32", 8, 8),
4283 ("BLOCK_4X16", 1, 4),
4284 ("BLOCK_16X4", 4, 1),
4285 ];
4286 for (name, mi_w, mi_h) in BSIZES {
4287 // `tx_size_wide`/`tx_size_high` of the TX_SIZE that maps to this
4288 // bsize, and the same quantity as a pixel size.
4289 let (tx_w, tx_h) = (mi_w * MI, mi_h * MI);
4290 assert_eq!(tx_w / MI, mi_w, "{name}: width identity");
4291 assert_eq!(tx_h / MI, mi_h, "{name}: height identity");
4292 }
4293
4294 // The primitive on a RECT node: an 8x16 node whose TX_4X4 early-return
4295 // leaf resolved (libaom `read_tx_size_vartx`'s `sub_txs == TX_4X4` arm,
4296 // which calls `txfm_partition_update(..., TX_4X4, tx_size)` with the
4297 // PARENT as the node).
4298 let fctx = &crate::decode::FrameCtx::new();
4299 let mut n = Neighbours::new(4, 4, 32, 32, fctx);
4300 for cell in n.above_txfm.iter_mut() {
4301 *cell = 0;
4302 }
4303 for cell in n.left_txfm.iter_mut() {
4304 *cell = 0;
4305 }
4306 txfm_partition_update_rect(&mut n, (4, 4), (4, 4), (8, 16));
4307 assert_eq!(
4308 &n.above_txfm[4..6],
4309 &[4, 4],
4310 "the node's OWN width (2 mi) carries the leaf's width"
4311 );
4312 assert_eq!(
4313 &n.left_txfm[4..8],
4314 &[4, 4, 4, 4],
4315 "the node's OWN height (4 mi) carries the leaf's height"
4316 );
4317 assert_eq!(n.above_txfm[6], 0, "and nothing past the node's extent");
4318 assert_eq!(n.left_txfm[8], 0, "and nothing past the node's extent");
4319}
4320
4321/// The domain of var-tx leaf sizes, enumerated against the two refusals that
4322/// name a leaf "larger than 32x32" / "larger than 64x64".
4323///
4324/// [`read_var_tx_size`] emits a leaf in exactly three places, and each one is
4325/// either the unit it was entered with or a `sub_tx_size_map` step below it:
4326/// the depth cap, the `!split` return, and libaom's `sub_txs == TX_4X4` early
4327/// return. So the leaf set reachable from an entry unit is that unit plus the
4328/// chain of `sub_tx_size_map` steps under it, capped at `MAX_VARTX_DEPTH` --
4329/// which this test enumerates, and over which no leaf is ever larger than the
4330/// entry.
4331///
4332/// That closes both refusals:
4333///
4334/// * [`read_block_tx_size_rect`]'s `bw.max(bh) > 64` branch enters every unit
4335/// at TX_64X64 (`max_txsize_rect_lookup[BLOCK_128X64]`), so "larger than
4336/// 64x64" names a leaf the tree cannot produce;
4337/// * [`read_block_tx_size`] enters at `side.min(64)` with a ceiling of 32
4338/// below the 128 root. The only entry that exceeds that ceiling is 64x64,
4339/// reached only when `side == 64`, and then the block is ONE unit whose only
4340/// above-ceiling leaf is the whole 64x64 unit itself -- which is the `single`
4341/// case the refusal is guarded by.
4342#[test]
4343fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() {
4344 // lane-av1refusalspan: this gate is the PROOF for both var-tx refusals, so
4345 // it names both and pins both guard sites. The walk below proves the leaf
4346 // domain; it never said which two strings that domain was about.
4347 for refusal in [
4348 "an inter var-tx tree with a leaf transform larger than 32x32",
4349 "an inter var-tx tree with a leaf transform larger than 64x64",
4350 ] {
4351 assert!(
4352 crate::refusal_inventory::pins_refusal(crate::test_source::module_source("decode"), refusal),
4353 "this gate proves {refusal:?}, but that string is no longer in decode.rs"
4354 );
4355 }
4356 // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h).
4357 fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) {
4358 out.push((depth, entry.0, entry.1));
4359 if depth == MAX_VARTX_DEPTH {
4360 return;
4361 }
4362 let sub = sub_tx_size_map(entry.0, entry.1);
4363 if sub == (4, 4) {
4364 out.push((depth + 1, 4, 4));
4365 return;
4366 }
4367 reachable(sub, depth + 1, out);
4368 }
4369
4370 for entry in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64)] {
4371 let mut leaves = Vec::new();
4372 reachable(entry, 0, &mut leaves);
4373 for (depth, w, h) in &leaves {
4374 assert!(
4375 w.max(h) <= &entry.0.max(entry.1),
4376 "a {}x{} unit reaches a {w}x{h} leaf at depth {depth}",
4377 entry.0,
4378 entry.1
4379 );
4380 }
4381 // Above-ceiling leaves of a 64x64 entry: the entry itself, at depth 0.
4382 if entry == (64, 64) {
4383 let above: Vec<&(usize, usize, usize)> =
4384 leaves.iter().filter(|(_, w, h)| w.max(h) > &32).collect();
4385 assert_eq!(
4386 above,
4387 [&(0usize, 64usize, 64usize)],
4388 "64x64 entry, leaves above 32"
4389 );
4390 }
4391 }
4392
4393 // The entry size and ceiling each caller uses, over the block sides that
4394 // reach them (`read_block_tx_size`'s square path; the 128-root rect path
4395 // enters at a fixed 64).
4396 for side in [8usize, 16, 32, 64, 128] {
4397 let max_tx = side.min(64);
4398 let ceiling = if side > 64 { 64 } else { 32 };
4399 let units = (side / max_tx) * (side / max_tx);
4400 if max_tx <= ceiling {
4401 continue;
4402 }
4403 assert_eq!(
4404 (side, units),
4405 (64, 1),
4406 "a {side}px block enters var-tx at {max_tx} over a ceiling of {ceiling} in \
4407 {units} units -- an above-ceiling leaf there would NOT be the `single` case"
4408 );
4409 }
4410}
4411
4412/// `read_var_tx_size` (spec 5.11.17, libaom `decodeframe.c`
4413/// `read_tx_size_vartx`): the recursive `txfm_split` tree of one
4414/// max-transform-sized unit of an inter block, collecting the resolved leaf
4415/// transform units into `out` as `(row offset, col offset, side)` in mi units
4416/// -- exactly the order `decode_reconstruct_tx` later reads their
4417/// coefficients in. `blk_row`/`blk_col` are mi offsets inside the block;
4418/// `max_w_mi`/`max_h_mi` clip it to the true frame edge (`max_block_wide`/
4419/// `max_block_high`).
4420#[allow(clippy::too_many_arguments)]
4421pub(super) fn read_var_tx_size(
4422 dec: &mut SymbolDecoder,
4423 cdfs: &mut Cdfs,
4424 n: &mut Neighbours,
4425 at_mi: (usize, usize),
4426 blk_max_px: usize,
4427 (max_w_mi, max_h_mi): (usize, usize),
4428 (tx_w, tx_h): (usize, usize),
4429 depth: usize,
4430 blk_row: usize,
4431 blk_col: usize,
4432 out: &mut Vec<(usize, usize, usize, usize)>,
4433) {
4434 if blk_row >= max_h_mi || blk_col >= max_w_mi {
4435 return;
4436 }
4437 let unit = (at_mi.0 + blk_row, at_mi.1 + blk_col);
4438 if depth == MAX_VARTX_DEPTH {
4439 out.push((blk_row, blk_col, tx_w, tx_h));
4440 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
4441 return;
4442 }
4443 let ctx = txfm_partition_ctx_rect(
4444 n.above_txfm[unit.1],
4445 n.left_txfm[unit.0],
4446 blk_max_px,
4447 tx_w,
4448 tx_h,
4449 );
4450 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
4451 hit!(TXFM_SPLIT_READS);
4452 if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
4453 let (rng, _) = dec.debug_state();
4454 eprintln!(
4455 "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
4456 unit.0,
4457 unit.1,
4458 u8::from(split)
4459 );
4460 }
4461 if !split {
4462 out.push((blk_row, blk_col, tx_w, tx_h));
4463 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
4464 return;
4465 }
4466 hit!(TXFM_SPLIT_HITS);
4467 let (sub_w, sub_h) = sub_tx_size_map(tx_w, tx_h);
4468 if (sub_w, sub_h) == (4, 4) {
4469 // libaom's `sub_txs == TX_4X4` early return: every mi cell of the
4470 // unit is marked 4x4 (raster order) without recursing.
4471 for row in 0..tx_h / MI {
4472 for col in 0..tx_w / MI {
4473 if blk_row + row < max_h_mi && blk_col + col < max_w_mi {
4474 out.push((blk_row + row, blk_col + col, 4, 4));
4475 }
4476 }
4477 }
4478 txfm_partition_update_rect(n, unit, (4, 4), (tx_w, tx_h));
4479 return;
4480 }
4481 for row in (0..tx_h / MI).step_by(sub_h / MI) {
4482 for col in (0..tx_w / MI).step_by(sub_w / MI) {
4483 read_var_tx_size(
4484 dec,
4485 cdfs,
4486 n,
4487 at_mi,
4488 blk_max_px,
4489 (max_w_mi, max_h_mi),
4490 (sub_w, sub_h),
4491 depth + 1,
4492 blk_row + row,
4493 blk_col + col,
4494 out,
4495 );
4496 }
4497 }
4498}