forge
Explore
Log in

Don't you dare go Hollow

wip(av1): b128r lane snapshot at the turn cap (orchestrator)

Browse files at this commit

5fd3825b8b0959ea8eb38a0603c4ab5b4533b687Ahmet Kaan GümüşParent: e8ba89f
crates/ec-av1/src/encode.rsmodified+208 -4
@@ -733,6 +733,42 @@ fn b128_root() -> bool {
733 *ENV733 *ENV
734 }734 }
735 735
736+/// lane-b128r: whether the 128 root prices a REAL residual as well as the
737+/// skip arm -- four TX_64X64 luma units interleaved with a TX_32X32 chroma
738+/// pair per 64x64 mu chunk, var-tx depth 0 (the shape
739+/// [`crate::tile::write_inter_block_128`] codes and `decode_inter_block`
740+/// reads). On by default; `EC_AV1_B128RES=0` restores lane-b128's skip-only
741+/// root, which is this arm's own attribution control.
742+fn b128_residual() -> bool {
743+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
744+ crate::envflags::var("EC_AV1_B128RES").ok().map(|v| v != "0")
745+ });
746+ ENV.unwrap_or(true) && b128_root()
747+}
748+
749+/// Test-only: take the 128 root's residual arm whatever it costs, so a
750+/// witness clip codes the shape rather than waiting for content on which the
751+/// RD picks it (the same role [`force_sb128`] plays for the superblock size).
752+/// Never read outside `#[cfg(test)]` builds.
753+static FORCE_B128_RESIDUAL: std::sync::atomic::AtomicBool =
754+ std::sync::atomic::AtomicBool::new(false);
755+
756+/// Arms [`FORCE_B128_RESIDUAL`] for the rest of the process.
757+#[cfg(test)]
758+pub(crate) fn force_b128_residual(on: bool) {
759+ FORCE_B128_RESIDUAL.store(on, std::sync::atomic::Ordering::Relaxed);
760+}
761+
762+/// How many 128 roots came out cheaper WITH a residual than skipped, since
763+/// the last [`take_b128_residual_hits`] (class `gate-blind-to-feature`).
764+static B128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize =
765+ std::sync::atomic::AtomicUsize::new(0);
766+
767+/// The 128-residual count since the last call, and zero it.
768+pub fn take_b128_residual_hits() -> usize {
769+ B128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
770+}
771+
736 /// How many 128x128 `PARTITION_NONE` roots the search took since the last772 /// How many 128x128 `PARTITION_NONE` roots the search took since the last
737 /// [`take_b128_none_hits`] (class `gate-blind-to-feature`): a flat BD result773 /// [`take_b128_none_hits`] (class `gate-blind-to-feature`): a flat BD result
738 /// is only attributable once the fire count is known.774 /// is only attributable once the fire count is known.
@@ -9428,7 +9464,16 @@ fn search_root_128(
9428 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))9464 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
9429 .sum::<f64>()9465 .sum::<f64>()
9430 / 4.0;9466 / 4.0;
9431- let root_search = Search { lambda, ..search };9467+ // The qindex this root is really quantized at: the delta_q unit is the
9468+ // 128 superblock, so the root's own top-left cell is the one coded
9469+ // (lane-b128m), and the residual arm below has to quantize at exactly it.
9470+ let root_search = Search {
9471+ lambda,
9472+ ..match sb_q {
9473+ Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
9474+ None => search,
9475+ }
9476+ };
9432 let stack = find_mv_stack(9477 let stack = find_mv_stack(
9433 grid,9478 grid,
9434 mi_row,9479 mi_row,
@@ -9452,7 +9497,84 @@ fn search_root_128(
9452 &[],9497 &[],
9453 fctx,9498 fctx,
9454 );9499 );
9455- let (cost, block) = found?;9500+ let (mut cost, mut block) = found?;
9501+ // lane-b128r: the same prediction with a REAL residual, priced against
9502+ // the skip arm the search just committed to the planes (which IS the
9503+ // winner's prediction, sample for sample). The block's residual is four
9504+ // TX_64X64 luma units, one per 64x64 mu chunk, each interleaved with its
9505+ // own TX_32X32 chroma pair -- so it is coded here as twelve trials at
9506+ // sides the forward network already reaches, never as one 128-point
9507+ // transform. Var-tx depth 0 only: the four units ARE the tree's leaves.
9508+ //
9509+ // The four `txfm_partition` symbols the writer codes for them are not
9510+ // priced, exactly as the 64 root does not price its own (their contexts
9511+ // are only known at write time); at four symbols a root this is under a
9512+ // bit against residuals of hundreds.
9513+ if b128_residual() && block.skip {
9514+ // Every unit's coded level grid is 32x32 (a 64-point transform codes
9515+ // only its top-left corner), packed per plane into one 64-wide grid
9516+ // with chunk (cr, cc) at (cr * 32, cc * 32) -- the layout
9517+ // `write_inter_block_128` slices back out in the same chunk order.
9518+ let mut packed = [vec![0i32; 64 * 64], vec![0i32; 64 * 64], vec![0i32; 64 * 64]];
9519+ let mut chunks: Vec<((usize, usize), [Trial; 3])> = Vec::new();
9520+ let (mut sse_skip, mut sse_res, mut coeff_bits) = (0.0f64, 0.0f64, 0.0f64);
9521+ for (cr, cc) in [(0usize, 0usize), (0, 1), (1, 0), (1, 1)] {
9522+ let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
9523+ let (cx, cy) = (px / 2, py / 2);
9524+ let half = SUPERBLOCK / 2;
9525+ let pred_y = rows_of(&luma.reconstruction, luma.width, px, py, SUPERBLOCK);
9526+ let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
9527+ let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
9528+ sse_skip += luma.block_sse(px, py, SUPERBLOCK, &pred_y)
9529+ + chroma[0].block_sse(cx, cy, half, &pred_u)
9530+ + chroma[1].block_sse(cx, cy, half, &pred_v);
9531+ let trials = [
9532+ luma.code_from_prediction(
9533+ px, py, SUPERBLOCK, &pred_y, false, root_search.base_q_idx,
9534+ root_search.deadzone, TxbSet::Luma64,
9535+ ),
9536+ chroma[0].code_from_prediction(
9537+ cx, cy, half, &pred_u, false, root_search.base_q_idx,
9538+ root_search.deadzone, TxbSet::Chroma32,
9539+ ),
9540+ chroma[1].code_from_prediction(
9541+ cx, cy, half, &pred_v, false, root_search.base_q_idx,
9542+ root_search.deadzone, TxbSet::Chroma32,
9543+ ),
9544+ ];
9545+ for (plane, trial) in trials.iter().enumerate() {
9546+ sse_res += trial.sse;
9547+ coeff_bits += trial.bits;
9548+ for row in 0..32 {
9549+ packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
9550+ .copy_from_slice(&trial.levels[row * 32..][..32]);
9551+ }
9552+ }
9553+ chunks.push(((cr, cc), trials));
9554+ }
9555+ // `cost` is the skip arm's own `sse + lambda * syntax`; the residual
9556+ // arm pays the same syntax with `skip` coded 0 instead of 1, plus its
9557+ // coefficients.
9558+ let unskip = skip_bits_at(&stack, false) - skip_bits_at(&stack, true);
9559+ let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
9560+ if res_cost < cost || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed) {
9561+ B128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9562+ for ((cr, cc), trials) in &chunks {
9563+ let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
9564+ let half = SUPERBLOCK / 2;
9565+ luma.commit(px, py, SUPERBLOCK, &trials[0]);
9566+ chroma[0].commit(px / 2, py / 2, half, &trials[1]);
9567+ chroma[1].commit(px / 2, py / 2, half, &trials[2]);
9568+ }
9569+ cost = res_cost;
9570+ block.skip = false;
9571+ block.tx_depth = 0;
9572+ block.luma_tx_types = Vec::new();
9573+ block.luma = coeffs(&packed[0], 64);
9574+ block.u = coeffs(&packed[1], 64);
9575+ block.v = coeffs(&packed[2], 64);
9576+ }
9577+ }
9456 let after = snapshot(luma, chroma, (x128, y128), SIDE);9578 let after = snapshot(luma, chroma, (x128, y128), SIDE);
9457 restore(luma, chroma, (x128, y128), SIDE, &base);9579 restore(luma, chroma, (x128, y128), SIDE, &base);
9458 Some((9580 Some((
@@ -12722,7 +12844,10 @@ pub(crate) fn encode_inter_frame(
12722 // cost, the same weighing the 64 root does one size down. Both sides12844 // cost, the same weighing the 64 root does one size down. Both sides
12723 // carry their own partition symbol, so the comparison is complete.12845 // carry their own partition symbol, so the comparison is complete.
12724 if let Some((cost128, lambda128, block, after)) = root12812846 if let Some((cost128, lambda128, block, after)) = root128
12725- && cost128 < root_cost + lambda128 * crate::tile::partition_bits(128, true)12847+ && (cost128 < root_cost + lambda128 * crate::tile::partition_bits(128, true)
12848+ // The witness knob takes the root whatever it costs, so the
12849+ // forced residual block really reaches the writer.
12850+ || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed))
12726 {12851 {
12727 B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);12852 B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12728 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);12853 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
@@ -12772,8 +12897,15 @@ pub(crate) fn encode_inter_frame(
12772 .iter()12897 .iter()
12773 .filter(|q| !matches!(q, Quadrant::Covered))12898 .filter(|q| !matches!(q, Quadrant::Covered))
12774 .count();12899 .count();
12900+ // lane-b128r: of those roots, how many code a REAL residual rather
12901+ // than the skip-only block lane-b128 shipped -- the fire count this
12902+ // arm's own gate row is read against.
12903+ let residual = blocks
12904+ .iter()
12905+ .filter(|q| matches!(q, Quadrant::Whole128(b) if !b.skip))
12906+ .count();
12775 eprintln!(12907 eprintln!(
12776- "B128 census: inter frame, {whole} whole 128x128 roots, {roots} coded blocks ({:.1}% of the frame's area at 128)",12908+ "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual), {roots} coded blocks ({:.1}% of the frame's area at 128)",
12777 100.0 * (whole * 16) as f64 / blocks.len().max(1) as f64,12909 100.0 * (whole * 16) as f64 / blocks.len().max(1) as f64,
12778 );12910 );
12779 }12911 }
@@ -16061,6 +16193,78 @@ mod tests {
16061 }16193 }
16062 }16194 }
16063 16195
16196+ /// lane-b128r: the 128 root's own RESIDUAL arm -- four TX_64X64 luma
16197+ /// units interleaved with a TX_32X32 chroma pair per 64x64 mu chunk. The
16198+ /// same pan the skip-only witness above uses, coded at a quantizer where
16199+ /// the residual is worth its bits, so the counters below are non-zero;
16200+ /// RED before this lane by construction (`write_inter_block_128` refused
16201+ /// every non-skip 128 block, so the count was 0 and no such block
16202+ /// existed to decode).
16203+ ///
16204+ /// cargo test -p ec-av1 --release --lib -- --ignored \
16205+ /// a_128_root_block_with_a_real_residual --nocapture
16206+ #[test]
16207+ #[ignore = "sets the process-global superblock size: run it alone"]
16208+ fn a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders() {
16209+ let _knobs = crate::speed::knob_write();
16210+ if !have_ffmpeg() {
16211+ eprintln!("SKIP: no ffmpeg");
16212+ return;
16213+ }
16214+ force_sb128(true);
16215+ let dir = std::env::temp_dir().join(format!("ec-av1-b128r-{}", std::process::id()));
16216+ std::fs::create_dir_all(&dir).unwrap();
16217+ let clip = dir.join("smpte-pan-1280x768.y4m");
16218+ let ok = Command::new("ffmpeg")
16219+ .args(["-v", "error", "-y", "-f", "lavfi"])
16220+ .args(["-i", "smptebars=size=1600x768:rate=24"])
16221+ .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
16222+ .args(["-pix_fmt", "yuv420p"])
16223+ .arg(&clip)
16224+ .status()
16225+ .expect("ffmpeg failed to run")
16226+ .success();
16227+ assert!(ok, "ffmpeg could not write the synthetic clip");
16228+ let (width, height) = (1280usize, 768usize);
16229+ let pictures =
16230+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
16231+ let _ = take_b128_residual_hits();
16232+ let _ = crate::tile::take_sb128_residual_hits();
16233+ force_b128_residual(true);
16234+ let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
16235+ let (won, coded) =
16236+ (take_b128_residual_hits(), crate::tile::take_sb128_residual_hits());
16237+ eprintln!("128x128 blocks WITH a residual: search won {won}, writer coded {coded}");
16238+ assert!(
16239+ coded > 0,
16240+ "no 128x128 block carried a residual on this clip, so it cannot witness the arm",
16241+ );
16242+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
16243+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
16244+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
16245+ let recon = &frame.reconstruction;
16246+ for (plane, got, want) in [
16247+ ("luma", &dec.y, &recon.y),
16248+ ("U", &dec.u, &recon.u),
16249+ ("V", &dec.v, &recon.v),
16250+ ] {
16251+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
16252+ assert_eq!(
16253+ differ, 0,
16254+ "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
16255+ own reconstruction",
16256+ got.len()
16257+ );
16258+ }
16259+ }
16260+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
16261+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
16262+ assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
16263+ assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
16264+ assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
16265+ }
16266+ }
16267+
16064 #[test]16268 #[test]
16065 #[ignore = "sets the process-global superblock size: run it alone"]16269 #[ignore = "sets the process-global superblock size: run it alone"]
16066 fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {16270 fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {
crates/ec-av1/src/tile.rsmodified+153 -11
@@ -215,14 +215,20 @@ fn write_sb128_root(
215 /// 32x32-mi window, the motion mode, and the transform syntax, with the mi215 /// 32x32-mi window, the motion mode, and the transform syntax, with the mi
216 /// grid and every neighbour band published over all thirty-two mi cells.216 /// grid and every neighbour band published over all thirty-two mi cells.
217 ///217 ///
218-/// SKIP only, and refused otherwise: a 128x128 block's residual is four218+/// lane-b128r: a block that carries a RESIDUAL codes it as the four 64x64 mu
219-/// TX_64X64 luma units interleaved with a TX_32X32 chroma pair per 64x64 mu219+/// chunks libaom's `decode_token_recon_block` walks -- per chunk one
220-/// chunk (the chroma units reading the offset-10 `txb_skip` rows), which220+/// TX_64X64 luma unit (its coded 32x32 corner, `TxbSet::Luma64`, DCT-only at
221-/// this writer has no path for. A skipped block writes no `cdef_idx` and no221+/// this size) then one TX_32X32 unit per chroma plane on the offset-10
222-/// `delta_q` either, exactly as the 64 root's skip arm does.222+/// `txb_skip` rows, each publishing its own coefficient context before the
223+/// next unit reads it. Its transform syntax is the var-tx tree's four
224+/// depth-0 `txfm_partition` symbols, one per chunk. The levels arrive packed
225+/// per plane into a 64-wide grid, chunk (cr, cc) at (cr * 32, cc * 32)
226+/// ([`crate::encode::search_root_128`]). A skipped block writes no
227+/// `cdef_idx` and no `delta_q`, exactly as the 64 root's skip arm does.
223 ///228 ///
224 /// # Errors229 /// # Errors
225-/// A block that is intra, or carries a residual, at this size.230+/// A block that is intra, that is compound with a residual, or whose var-tx
231+/// depth is not 0, at this size.
226 #[allow(clippy::too_many_arguments)]232 #[allow(clippy::too_many_arguments)]
227 fn write_inter_block_128(233 fn write_inter_block_128(
228 enc: &mut SymbolEncoder,234 enc: &mut SymbolEncoder,
@@ -239,13 +245,16 @@ fn write_inter_block_128(
239 /// The block's side in samples and in 4x4 mode-info units.245 /// The block's side in samples and in 4x4 mode-info units.
240 const SIDE: usize = 128;246 const SIDE: usize = 128;
241 const SIDE_MI: usize = SIDE / MI;247 const SIDE_MI: usize = SIDE / MI;
248+ /// The four 64x64 "mu" chunks, in the order libaom's
249+ /// `decode_token_recon_block` walks them (raster).
250+ const CHUNKS: [(usize, usize); 4] = [(0, 0), (0, 1), (1, 0), (1, 1)];
242 let info = block.inter.ok_or_else(|| {251 let info = block.inter.ok_or_else(|| {
243 Error::unsupported("AV1 tile", "a 128x128 superblock root block is coded inter")252 Error::unsupported("AV1 tile", "a 128x128 superblock root block is coded inter")
244 })?;253 })?;
245- if !block.skip {254+ if !block.skip && block.tx_depth != 0 {
246 return Err(Error::unsupported(255 return Err(Error::unsupported(
247 "AV1 tile",256 "AV1 tile",
248- "a 128x128 superblock root block carries a residual",257+ "a 128x128 superblock root block splits its var-tx tree below TX_64X64",
249 ));258 ));
250 }259 }
251 let (mi_r, mi_c) = (sb_at.0 * (SUB / MI), sb_at.1 * (SUB / MI));260 let (mi_r, mi_c) = (sb_at.0 * (SUB / MI), sb_at.1 * (SUB / MI));
@@ -253,9 +262,9 @@ fn write_inter_block_128(
253 let has_left = neighbours.has_left(mi_c);262 let has_left = neighbours.has_left(mi_c);
254 let skip_ctx =263 let skip_ctx =
255 usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);264 usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
256- enc.symbol(1, &mut cdfs.skip[skip_ctx]);265+ enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
257- write_cdef_idx(enc, (mi_r, mi_c), true);266+ write_cdef_idx(enc, (mi_r, mi_c), block.skip);
258- write_delta_q(enc, cdfs, (mi_r, mi_c), true, true);267+ write_delta_q(enc, cdfs, (mi_r, mi_c), true, block.skip);
259 let ii_ctx = intra_inter_ctx(268 let ii_ctx = intra_inter_ctx(
260 has_above,269 has_above,
261 has_left,270 has_left,
@@ -340,20 +349,129 @@ fn write_inter_block_128(
340 )?;349 )?;
341 }350 }
342 if tx_select {351 if tx_select {
352+ if block.skip {
343 write_tx_syntax_inter(enc, cdfs, neighbours, (mi_r, mi_c), SIDE, true, true, 0);353 write_tx_syntax_inter(enc, cdfs, neighbours, (mi_r, mi_c), SIDE, true, true, 0);
354+ } else {
355+ // The var-tx tree of a 128x128 block enters at TX_64X64 once per
356+ // mu chunk (`read_block_tx_size`'s `max_tx = side.min(64)` loop),
357+ // so it is four depth-0 `txfm_split` flags of zero, each read
358+ // against the bands the chunks before it published.
359+ for (cr, cc) in CHUNKS {
360+ let unit = (mi_r + cr * 16, mi_c + cc * 16);
361+ let ctx = txfm_partition_ctx_rect(
362+ neighbours.above_txfm[unit.1],
363+ neighbours.left_txfm[unit.0],
364+ SIDE,
365+ 64,
366+ 64,
367+ );
368+ enc.symbol(0, &mut cdfs.txfm_partition[ctx]);
369+ neighbours.record_txfm(unit, 64, 64, 64);
370+ }
371+ }
344 }372 }
345 let zero_grids = [373 let zero_grids = [
346 vec![0i32; TX32 * TX32],374 vec![0i32; TX32 * TX32],
347 vec![0i32; TX32 * TX32],375 vec![0i32; TX32 * TX32],
348 vec![0i32; TX32 * TX32],376 vec![0i32; TX32 * TX32],
349 ];377 ];
378+ if !block.skip {
379+ // The packed 64-wide level grids the search hands over, one plane
380+ // each (see this function's doc).
381+ let packed = [
382+ level_grid(&block.luma, 64)?,
383+ level_grid(&block.u, 64)?,
384+ level_grid(&block.v, 64)?,
385+ ];
386+ let scan32 = default_scan(TX32);
387+ let unit_of = |plane: usize, cr: usize, cc: usize| -> Vec<i32> {
388+ (0..32)
389+ .flat_map(|row| {
390+ packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32].to_vec()
391+ })
392+ .collect()
393+ };
394+ let mut chroma_units: Vec<((usize, usize), [Vec<i32>; 2])> = Vec::new();
395+ for (cr, cc) in CHUNKS {
396+ let unit_mi = (mi_r + cr * 16, mi_c + cc * 16);
397+ // The luma unit: its own `txb_skip_ctx` is the neighbour
398+ // magnitude table (the unit is smaller than its block), and it
399+ // publishes its context before the next chunk reads it.
400+ let luma = unit_of(0, cr, cc);
401+ let skip_ctx = neighbours.luma_skip_ctx(unit_mi, 64 / MI);
402+ let around = neighbours.around_mi(unit_mi, 64);
403+ write_coeffs(
404+ enc,
405+ &mut cdfs.txb(TxbSet::Luma64, 0),
406+ &luma,
407+ &scan32,
408+ skip_ctx,
409+ dc_sign_ctx(around[0].dc_vote),
410+ Some(0),
411+ TxType::DctDct,
412+ );
413+ neighbours.record_mi_luma(unit_mi, 64, &luma);
414+ // Then this chunk's chroma pair, before the next chunk's luma:
415+ // libaom codes every plane of a mu chunk before moving on. The
416+ // chroma `txb_skip_ctx` takes `get_txb_ctx`'s offset-10 rows
417+ // (+3 here) because the uv plane block is bigger than the unit.
418+ let mut pair = [Vec::new(), Vec::new()];
419+ for plane in 1..3usize {
420+ let grid = unit_of(plane, cr, cc);
421+ let around = neighbours.around_mi(unit_mi, 64)[plane];
422+ write_coeffs(
423+ enc,
424+ &mut cdfs.txb(TxbSet::Chroma32, 0),
425+ &grid,
426+ &scan32,
427+ usize::from(around.above_coded) + usize::from(around.left_coded) + 3,
428+ dc_sign_ctx(around.dc_vote),
429+ Some(plane),
430+ TxType::DctDct,
431+ );
432+ neighbours.record_mi_chroma(unit_mi, 64, plane, &grid);
433+ pair[plane - 1] = grid;
434+ }
435+ chroma_units.push((unit_mi, pair));
436+ }
437+ // decode.rs' own tail (`record_split_luma_rect_mi` then the
438+ // `mu_chroma_units` re-stamp): the block-level write off the WHOLE
439+ // assembled chroma plane grid, luma kept because each unit already
440+ // published its own, and then the per-unit chroma writes replayed
441+ // over it -- last writer wins, so the next block reads the units.
442+ let block_grids = [
443+ vec![0i32; TX32 * TX32],
444+ packed[1].clone(),
445+ packed[2].clone(),
446+ ];
447+ neighbours.record_planes(sb_at, SIDE, 0, &block_grids, false);
448+ for (unit_mi, pair) in &chroma_units {
449+ neighbours.record_mi_chroma(*unit_mi, 64, 1, &pair[0]);
450+ neighbours.record_mi_chroma(*unit_mi, 64, 2, &pair[1]);
451+ }
452+ } else {
350 neighbours.record(sb_at, SIDE, 0, &zero_grids);453 neighbours.record(sb_at, SIDE, 0, &zero_grids);
454+ }
351 neighbours.record_inter(sb_at, SIDE, true, true, block_ref(block));455 neighbours.record_inter(sb_at, SIDE, true, true, block_ref(block));
352 record_block_compound(neighbours, (mi_r, mi_c), SIDE, block);456 record_block_compound(neighbours, (mi_r, mi_c), SIDE, block);
353 SB128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);457 SB128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
458+ if !block.skip {
459+ SB128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
460+ }
354 Ok(())461 Ok(())
355 }462 }
356 463
464+/// lane-b128r: how many of those blocks carried a REAL residual (four
465+/// TX_64X64 luma units plus their per-chunk chroma pair) rather than being
466+/// skipped, since the last [`take_sb128_residual_hits`].
467+static SB128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize =
468+ std::sync::atomic::AtomicUsize::new(0);
469+
470+/// The 128x128-with-residual count since the last call, and zero it.
471+pub fn take_sb128_residual_hits() -> usize {
472+ SB128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
473+}
474+
357 /// How many 128x128 `PARTITION_NONE` blocks the inter writer has coded since475 /// How many 128x128 `PARTITION_NONE` blocks the inter writer has coded since
358 /// the last [`take_sb128_none_hits`] (class `gate-blind-to-feature`).476 /// the last [`take_sb128_none_hits`] (class `gate-blind-to-feature`).
359 static SB128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);477 static SB128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
@@ -2718,6 +2836,30 @@ impl Neighbours {
2718 }2836 }
2719 }2837 }
2720 2838
2839+ /// lane-b128r: publishes ONE chroma transform unit's coefficient context,
2840+ /// the decoder's own `record_mi_chroma` -- a 128x128 block's chroma is one
2841+ /// TX_32X32 unit per plane per 64x64 mu chunk, and the next chunk reads
2842+ /// the previous one's state (its `txb_skip_ctx` base 1 from the left
2843+ /// neighbour). `span_px` is the unit's LUMA span, which is what the
2844+ /// luma-mi-indexed bands are addressed in.
2845+ fn record_mi_chroma(
2846+ &mut self,
2847+ (mi_r, mi_c): (usize, usize),
2848+ span_px: usize,
2849+ plane: usize,
2850+ grid: &[i32],
2851+ ) {
2852+ let round_up_even = |n: usize| n.div_ceil(2) * 2;
2853+ let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
2854+ let state = neighbour_state(grid);
2855+ for cell in 0..(span_px / MI).min(bound_h.saturating_sub(mi_r)) {
2856+ self.left[mi_r + cell][plane] = state;
2857+ }
2858+ for cell in 0..(span_px / MI).min(bound_w.saturating_sub(mi_c)) {
2859+ self.above[mi_c + cell][plane] = state;
2860+ }
2861+ }
2862+
2721 /// Writes one coded block into every 16x16 column and row it covers, and,2863 /// Writes one coded block into every 16x16 column and row it covers, and,
2722 /// on the finer 4x4 grid libaom's entropy context arrays are actually2864 /// on the finer 4x4 grid libaom's entropy context arrays are actually
2723 /// kept on, into every unit up to the true frame edge -- the units past2865 /// kept on, into every unit up to the true frame edge -- the units past