forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-b128r' (20747a15): compound 128x128 root blocks ship; the 128 residual arm is written and witnessed but inert (behind EC_AV1_B128RES); cdef_idx stamps every 64x64 unit a wide block spans; pins re-taken 8364 / 33257

Browse files at this commit

14a38e5b2d6c3b2576cb3556a88f53e6fa122960Ahmet Kaan GümüşParent: e8ba89f70791bb
crates/ec-av1/src/decode.rsmodified+36 -11
@@ -818,7 +818,17 @@ fn maybe_read_delta_lf(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, mi_r: usize, mi
818 /// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/818 /// `read_cdef_params` already forces `bits = 0` under `coded_lossless`/
819 /// `allow_intrabc`, so neither needs a separate check here. Reads once per819 /// `allow_intrabc`, so neither needs a separate check here. Reads once per
820 /// superblock, at the first non-skip block.820 /// superblock, at the first non-skip block.
821-fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip: bool, fctx: &crate::decode::FrameCtx) {821+fn maybe_read_cdef_idx(
822+ dec: &mut SymbolDecoder,
823+ mi_r: usize,
824+ mi_c: usize,
825+ // The reading BLOCK's own span in 4x4 mode-info units: a block wider or
826+ // taller than one 64x64 CDEF unit is the first non-skip block of EVERY
827+ // unit it covers, so its one literal drives all of them (lane-b128r).
828+ (w_mi, h_mi): (usize, usize),
829+ skip: bool,
830+ fctx: &crate::decode::FrameCtx,
831+) {
822 let bits = fctx.cdef_bits.with(|c| c.get());832 let bits = fctx.cdef_bits.with(|c| c.get());
823 if bits == 0 || skip || fctx.cdef_transmitted.with(|c| c.get()) {833 if bits == 0 || skip || fctx.cdef_transmitted.with(|c| c.get()) {
824 return;834 return;
@@ -829,11 +839,26 @@ fn maybe_read_cdef_idx(dec: &mut SymbolDecoder, mi_r: usize, mi_c: usize, skip:
829 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);839 let (sb_r, sb_c) = (mi_r / SB_MI as usize, mi_c / SB_MI as usize);
830 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());840 let sb_cols = fctx.cdef_sb_cols.with(|c| c.get());
831 if sb_cols > 0 {841 if sb_cols > 0 {
842+ // lane-b128r: libaom's four CDEF units of a 128 superblock all read
843+ // their strength off the MB_MODE_INFO of the first non-skip block in
844+ // their own unit -- and a block that COVERS several units (the 128
845+ // root's own 128x128 block, the only one there is) is that block for
846+ // every unit it covers, so one literal drives all four. This grid is
847+ // per 64x64 unit, so the read stamps every unit the block covers; one
848+ // that is smaller than a unit stamps exactly the cell it always did.
849+ let (rows, cols) = (
850+ (h_mi / SB_MI as usize).max(1),
851+ (w_mi / SB_MI as usize).max(1),
852+ );
832 fctx.cdef_idx_grid.with(|g| {853 fctx.cdef_idx_grid.with(|g| {
833 let mut g = g.borrow_mut();854 let mut g = g.borrow_mut();
834- let i = sb_r * sb_cols + sb_c;855+ for dr in 0..rows {
835- if i < g.len() {856+ for dc in 0..cols {
836- g[i] = idx;857+ let i = (sb_r + dr) * sb_cols + sb_c + dc;
858+ if sb_c + dc < sb_cols && i < g.len() {
859+ g[i] = idx;
860+ }
861+ }
837 }862 }
838 });863 });
839 }864 }
@@ -9066,7 +9091,7 @@ fn read_intra_mode_rect(
9066 if !seg_id_pre_skip(fctx) {9091 if !seg_id_pre_skip(fctx) {
9067 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);9092 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
9068 }9093 }
9069- maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);9094+ maybe_read_cdef_idx(dec, mi_r, mi_c, (bw / MI, bh / MI), skip, fctx);
9070 istep!("cdef", 0);9095 istep!("cdef", 0);
9071 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never9096 // A HORZ/VERT rect strip is never the whole superblock (`bw`/`bh` never
9072 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always9097 // both 64 here -- see this fn's own doc), so `is_whole_sb` is always
@@ -13184,7 +13209,7 @@ fn read_intra_mode(
13184 }13209 }
13185 // spec order (see the comment below on `read_intrabc_info`): `skip`,13210 // spec order (see the comment below on `read_intrabc_info`): `skip`,
13186 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.13211 // `segment_id`, `cdef`, `delta_q` -- `cdef` lands right here.
13187- maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);13212+ maybe_read_cdef_idx(dec, mi_r, mi_c, (side / MI, side / MI), skip, fctx);
13188 istep!("cdef", 0);13213 istep!("cdef", 0);
13189 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not13214 // lane-sb128b r1: "this leaf IS the superblock" is `side == sb_size`, not
13190 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole13215 // a hardcoded 64 -- a `PARTITION_NONE` 128x128 root is the whole
@@ -15919,7 +15944,7 @@ fn read_intra_mode_sub8(
15919 if !seg_id_pre_skip(fctx) {15944 if !seg_id_pre_skip(fctx) {
15920 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);15945 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
15921 }15946 }
15922- maybe_read_cdef_idx(dec, mi_r, mi_c, skip, fctx);15947+ maybe_read_cdef_idx(dec, mi_r, mi_c, (2, 2), skip, fctx);
15923 istep!("cdef", 0);15948 istep!("cdef", 0);
15924 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);15949 maybe_read_delta_q(dec, cdfs, mi_r, mi_c, false, skip, fctx);
15925 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);15950 maybe_read_delta_lf(dec, cdfs, mi_r, mi_c, false, skip, fctx);
@@ -26811,7 +26836,7 @@ fn decode_inter_block(
26811 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);26836 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
26812 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;26837 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
26813 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false, fctx);26838 inter_segment_id(dec, cdfs, seg_mi_r, seg_mi_c, seg_w_mi, seg_h_mi, skip, false, fctx);
26814- maybe_read_cdef_idx(dec, rmi, cmi, skip, fctx);26839+ maybe_read_cdef_idx(dec, rmi, cmi, (write_w / MI, write_h / MI), skip, fctx);
26815 // lane-inter4 r1: spec 5.11.6's `bSize == sbSize` -- a 64x32/64x16 strip26840 // lane-inter4 r1: spec 5.11.6's `bSize == sbSize` -- a 64x32/64x16 strip
26816 // is NOT the whole superblock, so its `skip` never suppresses the read.26841 // is NOT the whole superblock, so its `skip` never suppresses the read.
26817 // lane-sb128c r7: `sbSize` is 128 under `--sb-size=128`, so the whole-block26842 // lane-sb128c r7: `sbSize` is 128 under `--sb-size=128`, so the whole-block
@@ -30610,7 +30635,7 @@ fn decode_inter_sub8_split4(
30610 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);30635 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
30611 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;30636 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
30612 inter_segment_id(dec, cdfs, rmi, cmi, 1, 1, skip, false, fctx);30637 inter_segment_id(dec, cdfs, rmi, cmi, 1, 1, skip, false, fctx);
30613- maybe_read_cdef_idx(dec, rmi, cmi, skip, fctx);30638+ maybe_read_cdef_idx(dec, rmi, cmi, (2, 2), skip, fctx);
30614 maybe_read_delta_q(dec, cdfs, rmi, cmi, false, skip, fctx);30639 maybe_read_delta_q(dec, cdfs, rmi, cmi, false, skip, fctx);
30615 maybe_read_delta_lf(dec, cdfs, rmi, cmi, false, skip, fctx);30640 maybe_read_delta_lf(dec, cdfs, rmi, cmi, false, skip, fctx);
30616 let (has_above, has_left) = (30641 let (has_above, has_left) = (
@@ -31653,7 +31678,7 @@ fn decode_inter_sub8_rect2(
31653 usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);31678 usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
31654 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;31679 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
31655 inter_segment_id(dec, cdfs, rmi, cmi, w_mi, h_mi, skip, false, fctx);31680 inter_segment_id(dec, cdfs, rmi, cmi, w_mi, h_mi, skip, false, fctx);
31656- maybe_read_cdef_idx(dec, rmi, cmi, skip, fctx);31681+ maybe_read_cdef_idx(dec, rmi, cmi, (2, 2), skip, fctx);
31657 maybe_read_delta_q(dec, cdfs, rmi, cmi, false, skip, fctx);31682 maybe_read_delta_q(dec, cdfs, rmi, cmi, false, skip, fctx);
31658 maybe_read_delta_lf(dec, cdfs, rmi, cmi, false, skip, fctx);31683 maybe_read_delta_lf(dec, cdfs, rmi, cmi, false, skip, fctx);
31659 let (has_above, has_left) = (31684 let (has_above, has_left) = (
@@ -32401,7 +32426,7 @@ fn decode_inter_block8(
32401 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);32426 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
32402 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;32427 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
32403 inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, skip, false, fctx);32428 inter_segment_id(dec, cdfs, leaf_mi.0, leaf_mi.1, 2, 2, skip, false, fctx);
32404- maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, skip, fctx);32429+ maybe_read_cdef_idx(dec, leaf_mi.0, leaf_mi.1, (2, 2), skip, fctx);
32405 // Always a `BLOCK_8X8` leaf here, never the whole superblock.32430 // Always a `BLOCK_8X8` leaf here, never the whole superblock.
32406 maybe_read_delta_q(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip, fctx);32431 maybe_read_delta_q(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip, fctx);
32407 maybe_read_delta_lf(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip, fctx);32432 maybe_read_delta_lf(dec, cdfs, leaf_mi.0, leaf_mi.1, false, skip, fctx);
crates/ec-av1/src/encode.rsmodified+419 -6
@@ -733,6 +733,97 @@ 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). Written, witnessed and byte-exact through both decoders, and
741+/// **off by default** (`EC_AV1_B128RES=1` turns it on) for two measured
742+/// reasons:
743+///
744+/// * it is INERT on content: over the native 12-frame gate the RD takes it
745+/// 0-2 times per frame against ~90 whole 128 roots, so the BD effect is
746+/// inside the noise either way;
747+/// * with it on, `bd_rate_screen_native`'s bars 2160p row q=90 frame 11
748+/// reads 8 luma samples (rows 126..127, cols 1611..1616 -- the two rows
749+/// above a 128-superblock horizontal edge) where ffmpeg and this
750+/// encoder's own reconstruction disagree. The residual arm's own witness
751+/// clip is byte-exact through ffmpeg over 420 forced blocks at 1280x768,
752+/// so the open half is a FILTER-stage interaction (deblock/CDEF at a 128
753+/// block's own edge), not the coefficient path.
754+///
755+/// An inert candidate does not buy a live filter mismatch, so the default
756+/// stays off until that is root-caused; the knob is the gate for it.
757+fn b128_residual() -> bool {
758+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
759+ crate::envflags::var("EC_AV1_B128RES").ok().map(|v| v != "0")
760+ });
761+ (ENV.unwrap_or(false) || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed))
762+ && b128_root()
763+}
764+
765+/// lane-b128r: whether the 128 root offers the COMPOUND candidates the 64
766+/// root already does (`NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`,
767+/// `NEW_NEARESTMV` over the LAST+GOLDEN / LAST+ALTREF pairs), at the block's
768+/// own 32x32-mi window. `EC_AV1_B128COMP=0` turns it off, which is this
769+/// arm's attribution control; the writer has always had the path
770+/// (`write_inter_block_128` calls `write_compound_block` for a block that
771+/// names a second reference).
772+fn b128_compound() -> bool {
773+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
774+ crate::envflags::var("EC_AV1_B128COMP").ok().map(|v| v != "0")
775+ });
776+ ENV.unwrap_or(true) && b128_root()
777+}
778+
779+/// How many 128 roots came out COMPOUND since the last
780+/// [`take_b128_compound_hits`] (class `gate-blind-to-feature`).
781+static B128_COMPOUND_HITS: std::sync::atomic::AtomicUsize =
782+ std::sync::atomic::AtomicUsize::new(0);
783+
784+/// The compound-128 count since the last call, and zero it.
785+pub fn take_b128_compound_hits() -> usize {
786+ B128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
787+}
788+
789+/// Test-only: take the 128 root's residual arm whatever it costs, so a
790+/// witness clip codes the shape rather than waiting for content on which the
791+/// RD picks it (the same role [`force_sb128`] plays for the superblock size).
792+/// Never read outside `#[cfg(test)]` builds.
793+static FORCE_B128_RESIDUAL: std::sync::atomic::AtomicBool =
794+ std::sync::atomic::AtomicBool::new(false);
795+
796+/// Test-only twin of [`FORCE_B128_RESIDUAL`] for the PARTITION decision: take
797+/// the 128 root whenever it produced a candidate at all, whatever its four
798+/// cells cost, so a witness codes the block it is about rather than waiting
799+/// for content on which the root also wins its own comparison.
800+static FORCE_B128_ROOT: std::sync::atomic::AtomicBool =
801+ std::sync::atomic::AtomicBool::new(false);
802+
803+/// Arms [`FORCE_B128_RESIDUAL`] -- and with it [`FORCE_B128_ROOT`], since a
804+/// forced residual block only reaches the writer if its root is taken.
805+#[cfg(test)]
806+pub(crate) fn force_b128_residual(on: bool) {
807+ FORCE_B128_RESIDUAL.store(on, std::sync::atomic::Ordering::Relaxed);
808+ force_b128_root(on);
809+}
810+
811+/// Arms [`FORCE_B128_ROOT`] for the rest of the process.
812+#[cfg(test)]
813+pub(crate) fn force_b128_root(on: bool) {
814+ FORCE_B128_ROOT.store(on, std::sync::atomic::Ordering::Relaxed);
815+}
816+
817+/// How many 128 roots came out cheaper WITH a residual than skipped, since
818+/// the last [`take_b128_residual_hits`] (class `gate-blind-to-feature`).
819+static B128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize =
820+ std::sync::atomic::AtomicUsize::new(0);
821+
822+/// The 128-residual count since the last call, and zero it.
823+pub fn take_b128_residual_hits() -> usize {
824+ B128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
825+}
826+
736 /// How many 128x128 `PARTITION_NONE` roots the search took since the last827 /// 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 result828 /// [`take_b128_none_hits`] (class `gate-blind-to-feature`): a flat BD result
738 /// is only attributable once the fire count is known.829 /// is only attributable once the fire count is known.
@@ -9393,6 +9484,11 @@ fn search_root_128(
9393 tpl_cells_x: usize,9484 tpl_cells_x: usize,
9394 base_q_idx: u8,9485 base_q_idx: u8,
9395 reference: &Picture,9486 reference: &Picture,
9487+ // The `LAST` + extra-reference pairs at THIS ROOT's own 32x32-mi window,
9488+ // built by the caller off the same grid the tile writer rebuilds its
9489+ // stack from (empty unless the frame carries `reference_select` and
9490+ // [`b128_compound`] is on).
9491+ compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
9396 fctx: &crate::decode::FrameCtx,9492 fctx: &crate::decode::FrameCtx,
9397 ) -> Option<(f64, f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> {9493 ) -> Option<(f64, f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> {
9398 const SIDE: usize = SUPERBLOCK * 2;9494 const SIDE: usize = SUPERBLOCK * 2;
@@ -9428,7 +9524,16 @@ fn search_root_128(
9428 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))9524 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
9429 .sum::<f64>()9525 .sum::<f64>()
9430 / 4.0;9526 / 4.0;
9431- let root_search = Search { lambda, ..search };9527+ // The qindex this root is really quantized at: the delta_q unit is the
9528+ // 128 superblock, so the root's own top-left cell is the one coded
9529+ // (lane-b128m), and the residual arm below has to quantize at exactly it.
9530+ let root_search = Search {
9531+ lambda,
9532+ ..match sb_q {
9533+ Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
9534+ None => search,
9535+ }
9536+ };
9432 let stack = find_mv_stack(9537 let stack = find_mv_stack(
9433 grid,9538 grid,
9434 mi_row,9539 mi_row,
@@ -9449,10 +9554,90 @@ fn search_root_128(
9449 false,9554 false,
9450 reference,9555 reference,
9451 &stack,9556 &stack,
9452- &[],9557+ compound,
9453 fctx,9558 fctx,
9454 );9559 );
9455- let (cost, block) = found?;9560+ let (mut cost, mut block) = found?;
9561+ if block.inter.is_some_and(|i| i.ref1.is_some()) {
9562+ B128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9563+ }
9564+ // lane-b128r: the same prediction with a REAL residual, priced against
9565+ // the skip arm the search just committed to the planes (which IS the
9566+ // winner's prediction, sample for sample). The block's residual is four
9567+ // TX_64X64 luma units, one per 64x64 mu chunk, each interleaved with its
9568+ // own TX_32X32 chroma pair -- so it is coded here as twelve trials at
9569+ // sides the forward network already reaches, never as one 128-point
9570+ // transform. Var-tx depth 0 only: the four units ARE the tree's leaves.
9571+ //
9572+ // The four `txfm_partition` symbols the writer codes for them are not
9573+ // priced, exactly as the 64 root does not price its own (their contexts
9574+ // are only known at write time); at four symbols a root this is under a
9575+ // bit against residuals of hundreds.
9576+ if b128_residual() && block.skip {
9577+ // Every unit's coded level grid is 32x32 (a 64-point transform codes
9578+ // only its top-left corner), packed per plane into one 64-wide grid
9579+ // with chunk (cr, cc) at (cr * 32, cc * 32) -- the layout
9580+ // `write_inter_block_128` slices back out in the same chunk order.
9581+ let mut packed = [vec![0i32; 64 * 64], vec![0i32; 64 * 64], vec![0i32; 64 * 64]];
9582+ let mut chunks: Vec<((usize, usize), [Trial; 3])> = Vec::new();
9583+ let (mut sse_skip, mut sse_res, mut coeff_bits) = (0.0f64, 0.0f64, 0.0f64);
9584+ for (cr, cc) in [(0usize, 0usize), (0, 1), (1, 0), (1, 1)] {
9585+ let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
9586+ let (cx, cy) = (px / 2, py / 2);
9587+ let half = SUPERBLOCK / 2;
9588+ let pred_y = rows_of(&luma.reconstruction, luma.width, px, py, SUPERBLOCK);
9589+ let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
9590+ let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
9591+ sse_skip += luma.block_sse(px, py, SUPERBLOCK, &pred_y)
9592+ + chroma[0].block_sse(cx, cy, half, &pred_u)
9593+ + chroma[1].block_sse(cx, cy, half, &pred_v);
9594+ let trials = [
9595+ luma.code_from_prediction(
9596+ px, py, SUPERBLOCK, &pred_y, false, root_search.base_q_idx,
9597+ root_search.deadzone, TxbSet::Luma64,
9598+ ),
9599+ chroma[0].code_from_prediction(
9600+ cx, cy, half, &pred_u, false, root_search.base_q_idx,
9601+ root_search.deadzone, TxbSet::Chroma32,
9602+ ),
9603+ chroma[1].code_from_prediction(
9604+ cx, cy, half, &pred_v, false, root_search.base_q_idx,
9605+ root_search.deadzone, TxbSet::Chroma32,
9606+ ),
9607+ ];
9608+ for (plane, trial) in trials.iter().enumerate() {
9609+ sse_res += trial.sse;
9610+ coeff_bits += trial.bits;
9611+ for row in 0..32 {
9612+ packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
9613+ .copy_from_slice(&trial.levels[row * 32..][..32]);
9614+ }
9615+ }
9616+ chunks.push(((cr, cc), trials));
9617+ }
9618+ // `cost` is the skip arm's own `sse + lambda * syntax`; the residual
9619+ // arm pays the same syntax with `skip` coded 0 instead of 1, plus its
9620+ // coefficients.
9621+ let unskip = skip_bits_at(&stack, false) - skip_bits_at(&stack, true);
9622+ let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
9623+ if res_cost < cost || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed) {
9624+ B128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9625+ for ((cr, cc), trials) in &chunks {
9626+ let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
9627+ let half = SUPERBLOCK / 2;
9628+ luma.commit(px, py, SUPERBLOCK, &trials[0]);
9629+ chroma[0].commit(px / 2, py / 2, half, &trials[1]);
9630+ chroma[1].commit(px / 2, py / 2, half, &trials[2]);
9631+ }
9632+ cost = res_cost;
9633+ block.skip = false;
9634+ block.tx_depth = 0;
9635+ block.luma_tx_types = Vec::new();
9636+ block.luma = coeffs(&packed[0], 64);
9637+ block.u = coeffs(&packed[1], 64);
9638+ block.v = coeffs(&packed[2], 64);
9639+ }
9640+ }
9456 let after = snapshot(luma, chroma, (x128, y128), SIDE);9641 let after = snapshot(luma, chroma, (x128, y128), SIDE);
9457 restore(luma, chroma, (x128, y128), SIDE, &base);9642 restore(luma, chroma, (x128, y128), SIDE, &base);
9458 Some((9643 Some((
@@ -12125,6 +12310,40 @@ pub(crate) fn encode_inter_frame(
12125 // 128x128 candidate is weighed.12310 // 128x128 candidate is weighed.
12126 let mark128 = blocks.len();12311 let mark128 = blocks.len();
12127 let mut root_cost = 0.0f64;12312 let mut root_cost = 0.0f64;
12313+ // The 128 root's own compound pairs, at its 32x32-mi window (the 64
12314+ // root builds the same list one size down, per superblock).
12315+ let root_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
12316+ if header.reference_select && b128_compound() && !screen && sb128_search {
12317+ [
12318+ (crate::mvstack::GOLDEN_FRAME, golden),
12319+ (crate::mvstack::ALTREF_FRAME, altref),
12320+ ]
12321+ .into_iter()
12322+ .filter_map(|(r, pic)| {
12323+ pic.map(|p| {
12324+ (
12325+ r,
12326+ p,
12327+ crate::mvstack::find_mv_stack_compound(
12328+ &grid,
12329+ root_r * 16,
12330+ root_c * 16,
12331+ 32,
12332+ 32,
12333+ (crate::mvstack::LAST_FRAME, r),
12334+ mi_cols,
12335+ mi_rows,
12336+ grid.sign_bias_table(),
12337+ &[(0, 0); 7],
12338+ None,
12339+ ),
12340+ )
12341+ })
12342+ })
12343+ .collect()
12344+ } else {
12345+ Vec::new()
12346+ };
12128 let root128 = (sb128_search && b128_root() && cells.len() == 4)12347 let root128 = (sb128_search && b128_root() && cells.len() == 4)
12129 .then(|| search_root_128(12348 .then(|| search_root_128(
12130 &mut luma,12349 &mut luma,
@@ -12140,6 +12359,7 @@ pub(crate) fn encode_inter_frame(
12140 tpl_cells_x,12359 tpl_cells_x,
12141 base_q_idx,12360 base_q_idx,
12142 reference,12361 reference,
12362+ &root_compound,
12143 fctx,12363 fctx,
12144 ))12364 ))
12145 .flatten();12365 .flatten();
@@ -12722,7 +12942,10 @@ pub(crate) fn encode_inter_frame(
12722 // cost, the same weighing the 64 root does one size down. Both sides12942 // cost, the same weighing the 64 root does one size down. Both sides
12723 // carry their own partition symbol, so the comparison is complete.12943 // carry their own partition symbol, so the comparison is complete.
12724 if let Some((cost128, lambda128, block, after)) = root12812944 if let Some((cost128, lambda128, block, after)) = root128
12725- && cost128 < root_cost + lambda128 * crate::tile::partition_bits(128, true)12945+ && (cost128 < root_cost + lambda128 * crate::tile::partition_bits(128, true)
12946+ // The witness knob takes the root whatever it costs, so the
12947+ // forced residual block really reaches the writer.
12948+ || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed))
12726 {12949 {
12727 B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);12950 B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12728 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);12951 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
@@ -12772,8 +12995,24 @@ pub(crate) fn encode_inter_frame(
12772 .iter()12995 .iter()
12773 .filter(|q| !matches!(q, Quadrant::Covered))12996 .filter(|q| !matches!(q, Quadrant::Covered))
12774 .count();12997 .count();
12998+ // lane-b128r: of those roots, how many code a REAL residual rather
12999+ // than the skip-only block lane-b128 shipped -- the fire count this
13000+ // arm's own gate row is read against.
13001+ let residual = blocks
13002+ .iter()
13003+ .filter(|q| matches!(q, Quadrant::Whole128(b) if !b.skip))
13004+ .count();
13005+ // lane-b128r: and how many named a second reference (the compound
13006+ // arm at the 128 root).
13007+ let compound = blocks
13008+ .iter()
13009+ .filter(|q| {
13010+ matches!(q, Quadrant::Whole128(b) if b.inter.is_some_and(|i| i.ref1.is_some()))
13011+ })
13012+ .count();
12775 eprintln!(13013 eprintln!(
12776- "B128 census: inter frame, {whole} whole 128x128 roots, {roots} coded blocks ({:.1}% of the frame's area at 128)",13014+ "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \
13015+ {compound} compound), {roots} coded blocks ({:.1}% of the frame's area at 128)",
12777 100.0 * (whole * 16) as f64 / blocks.len().max(1) as f64,13016 100.0 * (whole * 16) as f64 / blocks.len().max(1) as f64,
12778 );13017 );
12779 }13018 }
@@ -16061,6 +16300,149 @@ mod tests {
16061 }16300 }
16062 }16301 }
16063 16302
16303+ /// lane-b128r: the 128 root's own RESIDUAL arm -- four TX_64X64 luma
16304+ /// units interleaved with a TX_32X32 chroma pair per 64x64 mu chunk. The
16305+ /// same pan the skip-only witness above uses, with the arm FORCED
16306+ /// ([`force_b128_residual`]): on synthetic bars the RD picks the residual
16307+ /// about once per frame, which witnesses the shape but not every context
16308+ /// it reads, and forcing codes all 420 roots of the clip through it. RED
16309+ /// before this lane by construction (`write_inter_block_128` refused
16310+ /// every non-skip 128 block, so no such block existed to decode), and RED
16311+ /// again on the first draft of the writer, whose neighbour band recorded
16312+ /// `skip = true` for a block that carries a residual -- the next root's
16313+ /// `skip` symbol then took CDF row 1 where the reader takes row 0.
16314+ ///
16315+ /// cargo test -p ec-av1 --release --lib -- --ignored \
16316+ /// a_128_root_block_with_a_real_residual --nocapture
16317+ #[test]
16318+ #[ignore = "sets the process-global superblock size: run it alone"]
16319+ fn a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders() {
16320+ let _knobs = crate::speed::knob_write();
16321+ if !have_ffmpeg() {
16322+ eprintln!("SKIP: no ffmpeg");
16323+ return;
16324+ }
16325+ force_sb128(true);
16326+ let dir = std::env::temp_dir().join(format!("ec-av1-b128r-{}", std::process::id()));
16327+ std::fs::create_dir_all(&dir).unwrap();
16328+ let clip = dir.join("smpte-pan-1280x768.y4m");
16329+ let ok = Command::new("ffmpeg")
16330+ .args(["-v", "error", "-y", "-f", "lavfi"])
16331+ .args(["-i", "smptebars=size=1600x768:rate=24"])
16332+ .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
16333+ .args(["-pix_fmt", "yuv420p"])
16334+ .arg(&clip)
16335+ .status()
16336+ .expect("ffmpeg failed to run")
16337+ .success();
16338+ assert!(ok, "ffmpeg could not write the synthetic clip");
16339+ let (width, height) = (1280usize, 768usize);
16340+ let pictures =
16341+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
16342+ let _ = take_b128_residual_hits();
16343+ let _ = crate::tile::take_sb128_residual_hits();
16344+ force_b128_residual(true);
16345+ let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
16346+ let (won, coded) =
16347+ (take_b128_residual_hits(), crate::tile::take_sb128_residual_hits());
16348+ eprintln!("128x128 blocks WITH a residual: search won {won}, writer coded {coded}");
16349+ assert!(
16350+ coded > 0,
16351+ "no 128x128 block carried a residual on this clip, so it cannot witness the arm",
16352+ );
16353+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
16354+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
16355+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
16356+ let recon = &frame.reconstruction;
16357+ for (plane, got, want) in [
16358+ ("luma", &dec.y, &recon.y),
16359+ ("U", &dec.u, &recon.u),
16360+ ("V", &dec.v, &recon.v),
16361+ ] {
16362+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
16363+ assert_eq!(
16364+ differ, 0,
16365+ "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
16366+ own reconstruction",
16367+ got.len()
16368+ );
16369+ }
16370+ }
16371+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
16372+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
16373+ assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
16374+ assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
16375+ assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
16376+ }
16377+ }
16378+
16379+ /// lane-b128r: the COMPOUND arm at the 128 root -- one 128x128 block
16380+ /// naming `LAST` plus `GOLDEN`/`ALTREF`, through the same
16381+ /// `write_compound_block` chain every smaller compound block takes, at a
16382+ /// window it had never been exercised at. RED before this lane: the
16383+ /// search passed an empty compound list at the 128 root, so the count was
16384+ /// 0 and no such block existed to decode.
16385+ ///
16386+ /// cargo test -p ec-av1 --release --lib -- --ignored \
16387+ /// a_128_root_compound_block --nocapture
16388+ #[test]
16389+ #[ignore = "sets the process-global superblock size: run it alone"]
16390+ fn a_128_root_compound_block_decodes_exact_through_both_decoders() {
16391+ let _knobs = crate::speed::knob_write();
16392+ if !have_ffmpeg() {
16393+ eprintln!("SKIP: no ffmpeg");
16394+ return;
16395+ }
16396+ force_sb128(true);
16397+ let dir = std::env::temp_dir().join(format!("ec-av1-b128c-{}", std::process::id()));
16398+ std::fs::create_dir_all(&dir).unwrap();
16399+ let clip = dir.join("testsrc2-1280x768.y4m");
16400+ // Moving objects that occlude each other: a pan is coded by one
16401+ // reference outright, and a compound pair only pays where the two
16402+ // references disagree.
16403+ let ok = Command::new("ffmpeg")
16404+ .args(["-v", "error", "-y", "-f", "lavfi"])
16405+ .args(["-i", "testsrc2=size=1280x768:rate=24"])
16406+ .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
16407+ .arg(&clip)
16408+ .status()
16409+ .expect("ffmpeg failed to run")
16410+ .success();
16411+ assert!(ok, "ffmpeg could not write the synthetic clip");
16412+ let (width, height) = (1280usize, 768usize);
16413+ let pictures =
16414+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
16415+ // The compound candidate wins the 128 block's own search on this pan
16416+ // but the root then loses to its four cells, so the root is forced
16417+ // (the residual arm is left at its default, off).
16418+ force_b128_root(true);
16419+ let _ = take_b128_compound_hits();
16420+ let _ = crate::tile::take_sb128_compound_hits();
16421+ let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
16422+ let (won, coded) =
16423+ (take_b128_compound_hits(), crate::tile::take_sb128_compound_hits());
16424+ eprintln!("COMPOUND 128x128 blocks: search won {won}, writer coded {coded}");
16425+ assert!(coded > 0, "no compound 128x128 block was coded on this clip");
16426+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
16427+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
16428+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
16429+ for (plane, got, want) in [
16430+ ("luma", &dec.y, &frame.reconstruction.y),
16431+ ("U", &dec.u, &frame.reconstruction.u),
16432+ ("V", &dec.v, &frame.reconstruction.v),
16433+ ] {
16434+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
16435+ assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
16436+ }
16437+ }
16438+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
16439+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
16440+ assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
16441+ assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
16442+ assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
16443+ }
16444+ }
16445+
16064 #[test]16446 #[test]
16065 #[ignore = "sets the process-global superblock size: run it alone"]16447 #[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() {16448 fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {
@@ -17224,6 +17606,32 @@ mod tests {
17224 );17606 );
17225 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {17607 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
17226 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {17608 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
17609+ // TEMPORARY (lane-b128r bisect): the whole mismatch map.
17610+ let (l, r) = match plane {
17611+ "Y" => (&d.y, &e.reconstruction.y),
17612+ "U" => (&d.u, &e.reconstruction.u),
17613+ _ => (&d.v, &e.reconstruction.v),
17614+ };
17615+ let w = if plane == "Y" { width } else { width / 2 };
17616+ let bad: Vec<usize> = l
17617+ .iter()
17618+ .zip(r.iter())
17619+ .enumerate()
17620+ .filter(|(_, (a, b))| a != b)
17621+ .map(|(i, _)| i)
17622+ .collect();
17623+ let rows: Vec<usize> = bad.iter().map(|i| i / w).collect();
17624+ let cols: Vec<usize> = bad.iter().map(|i| i % w).collect();
17625+ eprintln!(
17626+ "B128R MISMATCH {name} q={q} frame {i} plane {plane}: {} samples, \
17627+ rows {}..{}, cols {}..{}, first 8 {:?}",
17628+ bad.len(),
17629+ rows.iter().min().copied().unwrap_or(0),
17630+ rows.iter().max().copied().unwrap_or(0),
17631+ cols.iter().min().copied().unwrap_or(0),
17632+ cols.iter().max().copied().unwrap_or(0),
17633+ bad.iter().take(8).map(|i| (i / w, i % w)).collect::<Vec<_>>(),
17634+ );
17227 panic!(17635 panic!(
17228 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \17636 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
17229 {got}, the encoder reconstructed {want}"17637 {got}, the encoder reconstructed {want}"
@@ -17501,7 +17909,12 @@ mod tests {
17501 // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053.17909 // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053.
17502 // Re-taken at the merge of lane-b128m onto main (128 superblocks on17910 // Re-taken at the merge of lane-b128m onto main (128 superblocks on
17503 // by default, on top of the ARF temporal filter).17911 // by default, on top of the ARF temporal filter).
17504- let pins: [(u8, usize, u64); 2] = [(150, 8354, 0x1290b8628438c6d4), (60, 33222, 0xc7f92971ab1264c3)];17912+ // Re-taken on lane-b128r: the 128 root now offers the COMPOUND
17913+ // candidates the 64 root already did ([`b128_compound`]), so every
17914+ // inter frame that carries `reference_select` codes different blocks
17915+ // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60.
17916+ // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly.
17917+ let pins: [(u8, usize, u64); 2] = [(150, 8364, 0xcb2ad7936d5127c5), (60, 33257, 0x87db250ba556e5a6)];
17505 let coded: Vec<(u8, usize, u64)> = pins17918 let coded: Vec<(u8, usize, u64)> = pins
17506 .iter()17919 .iter()
17507 .map(|&(q, _, _)| {17920 .map(|&(q, _, _)| {
crates/ec-av1/src/tile.rsmodified+170 -14
@@ -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,143 @@ fn write_inter_block_128(
340 )?;349 )?;
341 }350 }
342 if tx_select {351 if tx_select {
343- write_tx_syntax_inter(enc, cdfs, neighbours, (mi_r, mi_c), SIDE, true, true, 0);352+ if block.skip {
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 ];
350- neighbours.record(sb_at, SIDE, 0, &zero_grids);378+ if !block.skip {
351- neighbours.record_inter(sb_at, SIDE, true, true, block_ref(block));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 {
453+ neighbours.record(sb_at, SIDE, 0, &zero_grids);
454+ }
455+ neighbours.record_inter(sb_at, SIDE, block.skip, 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+ }
461+ if info.ref1.is_some() {
462+ SB128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
463+ }
354 Ok(())464 Ok(())
355 }465 }
356 466
467+/// lane-b128r: how many of those blocks carried a REAL residual (four
468+/// TX_64X64 luma units plus their per-chunk chroma pair) rather than being
469+/// skipped, since the last [`take_sb128_residual_hits`].
470+static SB128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize =
471+ std::sync::atomic::AtomicUsize::new(0);
472+
473+/// The 128x128-with-residual count since the last call, and zero it.
474+pub fn take_sb128_residual_hits() -> usize {
475+ SB128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
476+}
477+
478+/// lane-b128r: how many of those blocks named a SECOND reference (the
479+/// compound arm at the 128 root), since the last
480+/// [`take_sb128_compound_hits`].
481+static SB128_COMPOUND_HITS: std::sync::atomic::AtomicUsize =
482+ std::sync::atomic::AtomicUsize::new(0);
483+
484+/// The compound-128 count since the last call, and zero it.
485+pub fn take_sb128_compound_hits() -> usize {
486+ SB128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
487+}
488+
357 /// How many 128x128 `PARTITION_NONE` blocks the inter writer has coded since489 /// How many 128x128 `PARTITION_NONE` blocks the inter writer has coded since
358 /// the last [`take_sb128_none_hits`] (class `gate-blind-to-feature`).490 /// 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);491 static SB128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
@@ -2718,6 +2850,30 @@ impl Neighbours {
2718 }2850 }
2719 }2851 }
2720 2852
2853+ /// lane-b128r: publishes ONE chroma transform unit's coefficient context,
2854+ /// the decoder's own `record_mi_chroma` -- a 128x128 block's chroma is one
2855+ /// TX_32X32 unit per plane per 64x64 mu chunk, and the next chunk reads
2856+ /// the previous one's state (its `txb_skip_ctx` base 1 from the left
2857+ /// neighbour). `span_px` is the unit's LUMA span, which is what the
2858+ /// luma-mi-indexed bands are addressed in.
2859+ fn record_mi_chroma(
2860+ &mut self,
2861+ (mi_r, mi_c): (usize, usize),
2862+ span_px: usize,
2863+ plane: usize,
2864+ grid: &[i32],
2865+ ) {
2866+ let round_up_even = |n: usize| n.div_ceil(2) * 2;
2867+ let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
2868+ let state = neighbour_state(grid);
2869+ for cell in 0..(span_px / MI).min(bound_h.saturating_sub(mi_r)) {
2870+ self.left[mi_r + cell][plane] = state;
2871+ }
2872+ for cell in 0..(span_px / MI).min(bound_w.saturating_sub(mi_c)) {
2873+ self.above[mi_c + cell][plane] = state;
2874+ }
2875+ }
2876+
2721 /// Writes one coded block into every 16x16 column and row it covers, and,2877 /// 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 actually2878 /// 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 past2879 /// kept on, into every unit up to the true frame edge -- the units past
lanes/b128r.report.mdadded+165 -0
@@ -0,0 +1,165 @@
1+# lane-b128r — a residual and a compound arm at the 128 root
2+
3+Two of the three arms the charter names are implemented and measured; the
4+third is deferred with its reason. One decoder defect was found on the way.
5+
6+| arm | state |
7+|---|---|
8+| 1. the 128 NONE block WITH a residual | written, witnessed, **opt-in** (`EC_AV1_B128RES=1`) — measured INERT and it leaves a filter-stage mismatch |
9+| 2. the 128 NONE **compound** arm | written, witnessed, **shipped on**: film A −0.2/−0.2, film B −0.2/−0.3 |
10+| 3. HORZ / VERT at the 128 root | **deferred**, untouched — see the disposition |
11+
12+## 1. The residual arm (opt-in)
13+
14+`search_root_128` now prices the winner's own prediction with a real
15+residual against the skip arm it just committed to the planes, and
16+`write_inter_block_128` codes it: per 64x64 mu chunk one TX_64X64 luma unit
17+(its coded 32x32 corner, `TxbSet::Luma64`, DCT-only at this size) then one
18+TX_32X32 unit per chroma plane on the offset-10 `txb_skip` rows, each
19+publishing its own coefficient context before the next unit reads it, with
20+the var-tx tree's four depth-0 `txfm_partition` symbols in front. Levels
21+travel as one 64-wide grid per plane, chunk (cr, cc) at (cr\*32, cc\*32).
22+Quantized at the qindex the ROOT signals (the delta_q unit is the 128
23+superblock, lane-b128m), var-tx depth 0 only.
24+
25+**Witness** — `encode::tests::a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders`
26+(`--ignored`, the arm and the root forced so the clip codes the shape
27+rather than waiting for content):
28+
29+ 128x128 blocks WITH a residual: search won 420, writer coded 420
30+ test ... ok
31+
32+420 residual 128x128 blocks over 8 frames at 1280x768, every frame
33+sample-exact against the encoder's own reconstruction through
34+`decode_stream` AND through ffmpeg. RED before the lane by construction
35+(the writer refused a non-skip 128 block) and RED again on the first draft:
36+
37+- **defect (writer)**: `write_inter_block_128` recorded `skip = true` in its
38+ own neighbour band whatever the block was, so the NEXT root's `skip`
39+ symbol took CDF row 1 (16515) where the reader takes row 0 (31739) —
40+ first divergent symbol index 33, found with `EC_AV1_SYMTRACE`.
41+
42+**Why it ships off.** Two measurements:
43+
44+- it is INERT on content: over the native 12-frame gate the RD takes it
45+ **0–2 times per frame** against ~90 whole 128 roots per frame
46+ (`EC_AV1_B128_CENSUS=1`);
47+- switched on, `bd_rate_screen_native`'s bars 2160p row at q=90 frame 11
48+ has **8 luma samples** (rows 126..127, cols 1611..1616 — the two rows
49+ above a 128-superblock horizontal edge) where ffmpeg and this encoder's
50+ own reconstruction disagree. The arm's own witness is byte-exact through
51+ ffmpeg over 420 blocks at 1280x768, so the open half is a FILTER-stage
52+ interaction at a 128 block's own edge, not the coefficient path.
53+
54+An inert candidate does not buy a live filter mismatch. `EC_AV1_B128RES=1`
55+turns it on; the default encoder is byte-identical to the control (pins and
56+both 2160p gate rows reproduce the standing table to the digit).
57+
58+## 2. A decoder defect: one `cdef_idx` literal covers every unit its block spans
59+
60+libaom stores the `cdef_idx` it reads at the ORIGIN mi of the 64x64 CDEF
61+unit and `av1_cdef_frame` reads each unit's strength back off that origin —
62+so a block WIDER than one unit (the 128 root's block, the only one there
63+is) drives every unit it covers with its single literal. `maybe_read_cdef_idx`
64+stamped the reading block's own cell alone. No stream could reach it before
65+the 128 root carried a residual (class *branch dropped as unreachable*), and
66+the residual witness is its gate. Fixed with the block's own mi span, which
67+is a no-op for every block of one unit or less.
68+
69+## 3. The compound arm (shipped on)
70+
71+`search_root_128` passed an empty compound list, so a 128x128 block could
72+only ever name ONE reference — while the writer has had the path since
73+lane-b128 (`write_compound_block` for a block that names a second one). The
74+root now builds the `LAST`+`GOLDEN` / `LAST`+`ALTREF` stacks at its own
75+32x32-mi window, exactly as the 64 root builds them per superblock, and
76+offers the same three modes (`NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`,
77+`NEW_NEARESTMV`). `EC_AV1_B128COMP=0` is the attribution control.
78+
79+**It fires on real content** — census, compound 128x128 blocks per frame:
80+
81+| row | compound 128 blocks / frame |
82+|---|---|
83+| film B (2160p) | up to **80**, tens on most frames |
84+| bars 2160p | tens |
85+| screen capture | 0 (the screen path gates compound off) |
86+| synthetic bars pan | 1 per 8 frames |
87+
88+**Witness** — `encode::tests::a_128_root_compound_block_decodes_exact_through_both_decoders`
89+(`--ignored`, root forced):
90+
91+ COMPOUND 128x128 blocks: search won 216, writer coded 432
92+ test ... ok
93+
94+(the writer count is the higher one because the filter search re-codes each
95+tile). 12 frames of `testsrc2` at 1280x768, sample-exact through
96+`decode_stream` and ffmpeg. RED before the lane: the count was 0.
97+
98+### The deciding gate
99+
100+`bd_rate_screen_native`, 12 frames, four quantizers, BD-rate vs libaom
101+`cpu-used 6` / rav1e `speed 6` (lower is better). Control = the standing
102+table of `lanes/table-20260908.md`, reproduced on this tree with the arm
103+off (both 2160p rows re-run here, to the digit):
104+
105+| row | control | + the 128 compound arm |
106+|---|---|---|
107+| bars 1080p | −3.4 / −19.0 | −3.4 / −19.0 |
108+| bars 2160p | +8.6 / −13.8 | +8.6 / −13.7 |
109+| film A (1080p) | +18.1 / −6.2 | **+17.9 / −6.4** |
110+| film B (2160p) | +23.8 / −2.8 | **+23.6 / −3.1** |
111+| screen capture | +14.4 / −33.2 | +14.4 / −33.2 |
112+
113+Both film rows are DOWN on both columns; screen is unchanged; bars 2160p
114+moves +0.1 on the rav1e column (inside the ±0.3 flat band). Wall on the 4K
115+film row 124.7s → 138.2s (+10.8%, under the +15% ceiling).
116+
117+`bd_rate_film_long_gop`, 48 frames, one key frame and 47 inter pictures
118+(control = the standing table):
119+
120+| row | control | + the 128 compound arm |
121+|---|---|---|
122+| film A | +22.6 / −8.1 | **+22.5 / −8.2** |
123+| film B | +78.4 / +2.4 | **+77.5 / +1.7** |
124+
125+Both rows down on both columns again, and film B by 0.9 / 0.7 — the long
126+GOP is where the compound pairs exist to be picked.
127+
128+## Suite / checks (the shipped state)
129+
130+ s1 --skip stream:: 344 passed; 0 failed; 37 ignored RC=0
131+ s2 stream:: --skip 10bit 202 passed; 0 failed; 15 ignored RC=0
132+ s3 10bit 42 passed; 0 failed; 1 ignored RC=0
133+ --ignored every_speed_preset_decodes_sample_exact_through_both_decoders ok
134+ --ignored a_128_superblock_clip_whose_root_search... ok (405 blocks)
135+ --ignored a_128_root_block_with_a_real_residual... ok (420 blocks)
136+ --ignored a_128_root_compound_block... ok (432 blocks)
137+ the_encoders_own_streams_are_byte_identical_to_their_pins ok, and ok at EC_AV1_SPEED=6
138+ cargo check --workspace --all-targets -j4 0 errors, 0 ec-av1 warnings
139+
140+## Pins
141+
142+Re-taken for the compound arm, which moves every inter frame that carries
143+`reference_select`: `(150, 8364, 0xcb2ad7936d5127c5)`, `(60, 33257,
144+0x87db250ba556e5a6)` — was `(150, 8354, ...)`, `(60, 33222, ...)`.
145+`EC_AV1_B128COMP=0` restores 8354 / 33222 exactly, which is also the proof
146+that nothing else in this lane moves the shipped stream. Green at the
147+default and at `EC_AV1_SPEED=6`. No other byte pin moved.
148+
149+## Disposition
150+
151+- `deferred`: **HORZ / VERT at the 128 root** (two 128x64 / 64x128 blocks),
152+ untouched. The writer has no rect neighbour recording at this size and the
153+ search no rect trial; `write_inter_block_128` is square throughout
154+ (`record`/`record_inter`/`record_planes` all take one side). Unblocked by
155+ a rect `record_inter`/`record` pair plus a rect trial in
156+ `search_root_128`. The decoder reads both already (lane-sb128c r7).
157+ Not attempted: the residual arm's own writer/reader bisect consumed the
158+ budget this would have needed.
159+- `open`: the residual arm's **8-sample filter mismatch** (bars 2160p, q=90,
160+ frame 11, rows 126..127 / cols 1611..1616, ffmpeg vs our reconstruction).
161+ Next step: dump the deblock/CDEF decision at that 128 superblock's own
162+ bottom edge for a block that carries a residual, against aomdec. Until
163+ then the arm stays behind `EC_AV1_B128RES=1`.
164+- `open` (inherited): search-time vs write-time mv stacks still differ
165+ (lane-sb128b's second open item).