forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-b128hv' (c2cc62bc): the 128 root offers PARTITION_HORZ / PARTITION_VERT skip halves, the writer's first rectangular blocks; long-GOP both films down on both columns; pins 8291 / 33227

Browse files at this commit

b4cfa0980424699a1d66df30d38f649d65be41eaAhmet Kaan GümüşParent: 1fcce5892339f4
The tile writer had never coded a rectangular block at any size: every neighbour record took one side into both bands. Rect recording (record_planes_rect, record_mi_planes_rect, record_inter_rect_mi, record_compound_rect_mi, record_txfm_rect, both palette bands), write_inter_block_128_rect, search_root_128_rect with MiGrid::snapshot_rect / restore_rect, search_skip_64 over a (w,h) footprint. EC_AV1_B128HV=0 is the control. Long-GOP film A +22.0/-8.4 to +21.9/-8.6, film B +76.5/+1.2 to +75.8/+0.8 vs libaom 6 / rav1e 6; 12-frame film rows +0.1, bars 2160p +8.4/-14.0, screen unchanged; wall +10.5% / +2.9%. Witness: forced HORZ, forced VERT and unforced passes decode exact through both decoders. Open: the rect root candidate does not price its delta_q group. Deferred: rect halves' residual (shares EC_AV1_B128RES), AB shapes at the 128 root.
crates/ec-av1/src/encode.rsmodified+498 -52
@@ -786,6 +786,46 @@ pub fn take_b128_compound_hits() -> usize {
786786 B128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
787787 }
788788
789+/// lane-b128hv: whether the 128 superblock root offers its `PARTITION_HORZ`
790+/// and `PARTITION_VERT` candidates -- two 128x64 / 64x128 inter blocks, the
791+/// same skip-only single-reference/compound machinery the NONE arm ships,
792+/// halved ([`search_root_128_rect`], `crate::tile::write_inter_block_128_rect`).
793+/// `EC_AV1_B128HV=0` is this arm's attribution control.
794+fn b128_rect() -> bool {
795+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
796+ crate::envflags::var("EC_AV1_B128HV").ok().map(|v| v != "0")
797+ });
798+ ENV.unwrap_or(true) && b128_root()
799+}
800+
801+/// How many 128 roots the search left as two 128x64 (HORZ) / 64x128 (VERT)
802+/// halves since the last take (class `gate-blind-to-feature`).
803+static B128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
804+/// The VERT twin of [`B128_HORZ_HITS`].
805+static B128_VERT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
806+
807+/// The HORZ-128-root count since the last call, and zero it.
808+pub fn take_b128_horz_hits() -> usize {
809+ B128_HORZ_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
810+}
811+
812+/// The VERT-128-root count since the last call, and zero it.
813+pub fn take_b128_vert_hits() -> usize {
814+ B128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
815+}
816+
817+/// Test-only: force the 128 root's rect partition whatever it costs -- 0 off,
818+/// 1 `PARTITION_HORZ`, 2 `PARTITION_VERT`. The witness needs it because
819+/// synthetic content is where the shape is cheapest to decode-check and the
820+/// RD there prefers one whole block; the gate census is the unforced count.
821+static FORCE_B128_RECT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
822+
823+/// Arms [`FORCE_B128_RECT`] for the rest of the process (0 / 1 HORZ / 2 VERT).
824+#[cfg(test)]
825+pub(crate) fn force_b128_rect(which: u8) {
826+ FORCE_B128_RECT.store(which, std::sync::atomic::Ordering::Relaxed);
827+}
828+
789829 /// Test-only: take the 128 root's residual arm whatever it costs, so a
790830 /// witness clip codes the shape rather than waiting for content on which the
791831 /// RD picks it (the same role [`force_sb128`] plays for the superblock size).
@@ -3079,6 +3119,17 @@ impl Plane<'_> {
30793119 rows_of(self.source, self.width, x, y, side)
30803120 }
30813121
3122+ /// lane-b128hv: [`Self::source_block`] over a rectangle, for the 128
3123+ /// root's own HORZ/VERT motion search.
3124+ fn source_block_rect(&self, x: usize, y: usize, w: usize, h: usize) -> Vec<u8> {
3125+ let mut out = vec![0u8; w * h];
3126+ for row in 0..h {
3127+ out[row * w..][..w]
3128+ .copy_from_slice(&self.source[(y + row) * self.width + x..][..w]);
3129+ }
3130+ out
3131+ }
3132+
30823133 /// The reconstructed samples of one square, so that a partition trial can
30833134 /// be undone.
30843135 /// The reconstructed samples of one square AND the coefficient contexts
@@ -7368,6 +7419,31 @@ fn record_mi(
73687419 }
73697420 }
73707421
7422+/// lane-b128hv: [`record_mi`] for a RECTANGULAR block -- the mi stamp the
7423+/// writer's own `write_inter_block_128_rect` makes, so the second half of a
7424+/// HORZ/VERT 128 root searches against the stack the writer will rebuild.
7425+fn record_mi_rect(
7426+ grid: &mut MiGrid,
7427+ mi_row: usize,
7428+ mi_col: usize,
7429+ (w_mi, h_mi): (usize, usize),
7430+ inter: Option<InterInfo>,
7431+ skip: bool,
7432+) {
7433+ record_mi(grid, mi_row, mi_col, w_mi.min(h_mi) as u8, inter, skip);
7434+ // `record_mi` stamped the square corner; widen it to the true footprint,
7435+ // with the block's own (rect) size fields.
7436+ let mut info = grid.get_frame(mi_row, mi_col).expect("just recorded");
7437+ info.size = w_mi as u8;
7438+ info.size_h = h_mi as u8;
7439+ for dr in 0..h_mi {
7440+ for dc in 0..w_mi {
7441+ grid.set(mi_row + dr, mi_col + dc, info);
7442+ grid.set_skip(mi_row + dr, mi_col + dc, skip);
7443+ }
7444+ }
7445+}
7446+
73717447 /// The reconstructed samples one 32x32 square covers in all three planes, so
73727448 /// that a partition trial can be undone.
73737449 /// One square of a plane, row-major, the inverse of [`Plane::restore`].
@@ -9557,7 +9633,7 @@ fn search_root_128(
95579633 luma,
95589634 chroma,
95599635 (x128, y128),
9560- SIDE,
9636+ (SIDE, SIDE),
95619637 &root_search,
95629638 false,
95639639 reference,
@@ -9656,6 +9732,165 @@ fn search_root_128(
96569732 ))
96579733 }
96589734
9735+/// lane-b128hv: the `PARTITION_HORZ` / `PARTITION_VERT` candidate for a whole
9736+/// 128 superblock root -- two 128x64 (`horz`) or 64x128 inter blocks, the
9737+/// shipped NONE machinery halved. Skip only, single reference or compound,
9738+/// exactly what `crate::tile::write_inter_block_128_rect` codes and
9739+/// `decode_inter_block` reads at `sb128_rect`.
9740+///
9741+/// The FIRST half is published into `grid` before the second is searched --
9742+/// the writer publishes it too, so a second half searched against the stale
9743+/// grid would be priced (and its mv predicted) off a stack the decoder never
9744+/// derives (class `encoder-grid-drift-invisible-to-pixel-gate`). The grid and
9745+/// both planes are put back before returning; the caller re-applies the
9746+/// winner.
9747+///
9748+/// Returns `(cost, lambda, the two halves, reconstruction)`, the cost already
9749+/// carrying the root's own partition symbol so it ranks against
9750+/// [`search_root_128`] and against the four superblocks below.
9751+#[allow(clippy::too_many_arguments)]
9752+fn search_root_128_rect(
9753+ luma: &mut Plane,
9754+ chroma: &mut [Plane; 2],
9755+ grid: &mut crate::mvstack::MiGrid,
9756+ (root_r, root_c): (usize, usize),
9757+ (rows, cols): (usize, usize),
9758+ (mi_cols, mi_rows): (u32, u32),
9759+ search: Search<'_>,
9760+ tpl_factors: &Option<Vec<f64>>,
9761+ sb_q: Option<&Vec<u8>>,
9762+ sb_cols: usize,
9763+ tpl_cells_x: usize,
9764+ base_q_idx: u8,
9765+ reference: &Picture,
9766+ // The `LAST` + extra-reference pairs offered at this root; only the
9767+ // reference and its picture are read here, since each HALF derives its
9768+ // own compound stack at its own rectangular window.
9769+ compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
9770+ horz: bool,
9771+ fctx: &crate::decode::FrameCtx,
9772+) -> Option<(f64, f64, [BlockCoeffs; 2], [(Vec<u8>, Vec<CoefCtx>); 3])> {
9773+ const SIDE: usize = SUPERBLOCK * 2;
9774+ const SIDE_MI: usize = SIDE / 4;
9775+ let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
9776+ let (mi_row, mi_col) = (root_r * 16, root_c * 16);
9777+ if root_r * 2 + 3 >= rows
9778+ || root_c * 2 + 3 >= cols
9779+ || (mi_row + SIDE_MI) as u32 > mi_rows
9780+ || (mi_col + SIDE_MI) as u32 > mi_cols
9781+ || x128 + SIDE > luma.true_width
9782+ || y128 + SIDE > luma.true_height
9783+ {
9784+ return None;
9785+ }
9786+ // The root's own lambda, the mean of its four superblocks' -- the same
9787+ // one [`search_root_128`] prices with, so the three root candidates and
9788+ // the four-superblock arm are all comparable.
9789+ let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
9790+ (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
9791+ (None, Some(f)) => {
9792+ let mean = (0..16)
9793+ .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
9794+ .sum::<f64>()
9795+ / 16.0;
9796+ search.lambda * mean
9797+ }
9798+ (None, None) => search.lambda,
9799+ };
9800+ let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
9801+ .iter()
9802+ .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
9803+ .sum::<f64>()
9804+ / 4.0;
9805+ let root_search = Search {
9806+ lambda,
9807+ ..match sb_q {
9808+ Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
9809+ None => search,
9810+ }
9811+ };
9812+ let (w, h) = if horz { (SIDE, SUPERBLOCK) } else { (SUPERBLOCK, SIDE) };
9813+ let (w_mi, h_mi) = (w / 4, h / 4);
9814+ let base = snapshot(luma, chroma, (x128, y128), SIDE);
9815+ let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
9816+ let mut cost = 0.0f64;
9817+ let mut halves: Vec<BlockCoeffs> = Vec::with_capacity(2);
9818+ for i in 0..2usize {
9819+ let (mr, mc) = if horz {
9820+ (mi_row + i * 16, mi_col)
9821+ } else {
9822+ (mi_row, mi_col + i * 16)
9823+ };
9824+ let stack = find_mv_stack(
9825+ grid,
9826+ mr,
9827+ mc,
9828+ w_mi,
9829+ h_mi,
9830+ LAST_FRAME,
9831+ mi_cols as usize,
9832+ mi_rows as usize,
9833+ );
9834+ let half_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
9835+ .iter()
9836+ .map(|&(r, pic, _)| {
9837+ (
9838+ r,
9839+ pic,
9840+ crate::mvstack::find_mv_stack_compound(
9841+ grid,
9842+ mr,
9843+ mc,
9844+ w_mi,
9845+ h_mi,
9846+ (LAST_FRAME, r),
9847+ mi_cols as usize,
9848+ mi_rows as usize,
9849+ grid.sign_bias_table(),
9850+ &[(0, 0); 7],
9851+ None,
9852+ ),
9853+ )
9854+ })
9855+ .collect();
9856+ let found = search_skip_64(
9857+ luma,
9858+ chroma,
9859+ (mc * 4, mr * 4),
9860+ (w, h),
9861+ &root_search,
9862+ false,
9863+ reference,
9864+ &stack,
9865+ &half_compound,
9866+ fctx,
9867+ );
9868+ match found {
9869+ Some((c, block)) => {
9870+ cost += c;
9871+ record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
9872+ halves.push(block);
9873+ }
9874+ None => {
9875+ restore(luma, chroma, (x128, y128), SIDE, &base);
9876+ grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
9877+ return None;
9878+ }
9879+ }
9880+ }
9881+ let after = snapshot(luma, chroma, (x128, y128), SIDE);
9882+ restore(luma, chroma, (x128, y128), SIDE, &base);
9883+ grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
9884+ let symbol = if horz { 1 } else { 2 };
9885+ let [b0, b1] = <[BlockCoeffs; 2]>::try_from(halves).ok()?;
9886+ Some((
9887+ cost + lambda * crate::tile::partition_bits_sym(SIDE, symbol),
9888+ lambda,
9889+ [b0, b1],
9890+ after,
9891+ ))
9892+}
9893+
96599894 /// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):
96609895 /// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded
96619896 /// SKIP, priced through the same `symbol_bits` path every other candidate
@@ -9670,12 +9905,14 @@ fn search_skip_64(
96709905 luma: &mut Plane,
96719906 chroma: &mut [Plane; 2],
96729907 (x, y): (usize, usize),
9673- // The root's side in samples: [`SUPERBLOCK`] at a 64 root, twice that at
9674- // the 128 one [`search_root_128`] drives (lane-b128). Every trial below
9675- // is a square of this side and its half in chroma, and the residual arm
9676- // is only ever asked for at 64 -- a 128 block's residual is four
9908+ // The root's footprint in samples: [`SUPERBLOCK`] square at a 64 root,
9909+ // twice that at the 128 one [`search_root_128`] drives (lane-b128), and
9910+ // 128x64 / 64x128 at the rect halves of [`search_root_128_rect`]
9911+ // (lane-b128hv). Every trial below tiles it into squares of its SHORTER
9912+ // side (one square when it is square, two otherwise), and the residual
9913+ // arm is only ever asked for at 64 -- a 128 block's residual is four
96779914 // TX_64X64 units the writer has no path for.
9678- side: usize,
9915+ (bw, bh): (usize, usize),
96799916 search: &Search,
96809917 // Whether the non-skip arm is priced at all ([`b64_residual`], and off on
96819918 // screen content -- see that function's doc).
@@ -9688,7 +9925,23 @@ fn search_skip_64(
96889925 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
96899926 fctx: &crate::decode::FrameCtx,
96909927 ) -> Option<(f64, BlockCoeffs)> {
9691- debug_assert!(side == SUPERBLOCK || !residual, "a 128 root has no residual arm");
9928+ debug_assert!(
9929+ (bw, bh) == (SUPERBLOCK, SUPERBLOCK) || !residual,
9930+ "only a 64 root has a residual arm"
9931+ );
9932+ // The square units every trial below is taken on: the block itself when
9933+ // it is square, its two halves otherwise. Luma first (in raster order),
9934+ // then each chroma plane over the same tiling at half the side -- which is
9935+ // exactly `[(0, x, y, side), (1, ..), (2, ..)]` at bw == bh.
9936+ let sq = bw.min(bh);
9937+ let units: Vec<(usize, usize, usize, usize, bool)> = (0..3usize)
9938+ .flat_map(|plane| {
9939+ let (ox, oy, s) = if plane == 0 { (x, y, sq) } else { (x / 2, y / 2, sq / 2) };
9940+ (0..bh / sq).flat_map(move |j| {
9941+ (0..bw / sq).map(move |i| (plane, ox + i * s, oy + j * s, s, plane == 0))
9942+ })
9943+ })
9944+ .collect();
96929945 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
96939946 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
96949947 let ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
@@ -9726,7 +9979,7 @@ fn search_skip_64(
97269979 // candidate below to pair with the second reference's NEAREST half.
97279980 let mut last_new_mv: Option<(i32, i32)> = None;
97289981 if leaf_new_mv() {
9729- let source_block = luma.source_block(x, y, side);
9982+ let source_block = luma.source_block_rect(x, y, bw, bh);
97309983 let (seeds, seed_n) = mv_seeds(stack);
97319984 let found = motion::search(
97329985 &reference.y,
@@ -9736,8 +9989,8 @@ fn search_skip_64(
97369989 &source_block,
97379990 x,
97389991 y,
9739- side,
9740- side,
9992+ bw,
9993+ bh,
97419994 stack.pred_mv,
97429995 &seeds[..seed_n],
97439996 search.lambda,
@@ -9754,14 +10007,11 @@ fn search_skip_64(
975410007 }
975510008 }
975610009
9757- let mut best: Option<(f64, f64, InterInfo, [Trial; 3])> = None;
10010+ let mut best: Option<(f64, f64, InterInfo, Vec<Trial>)> = None;
975810011 for (bits, info) in cands {
9759- let trials = [
9760- (0usize, x, y, side, true),
9761- (1, x / 2, y / 2, side / 2, false),
9762- (2, x / 2, y / 2, side / 2, false),
9763- ]
9764- .map(|(plane, px, py, s, is_luma)| {
10012+ let trials: Vec<Trial> = units
10013+ .iter()
10014+ .map(|&(plane, px, py, s, is_luma)| {
976510015 let (samples, stride, w, h) = match plane {
976610016 0 => (&reference.y, reference.width, luma.true_width, luma.true_height),
976710017 1 => (
@@ -9792,11 +10042,10 @@ fn search_skip_64(
979210042 search.deadzone,
979310043 TxbSet::Luma32Inter,
979410044 )
9795- });
9796- let cost = trials[0].sse
9797- + trials[1].sse
9798- + trials[2].sse
9799- + search.lambda * (fixed + bits);
10045+ })
10046+ .collect();
10047+ let cost =
10048+ trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * (fixed + bits);
980010049 if best.as_ref().is_none_or(|b| cost < b.0) {
980110050 best = Some((cost, fixed + bits, info, trials));
980210051 }
@@ -9855,12 +10104,9 @@ fn search_skip_64(
985510104 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
985610105 ccands.dedup_by_key(|c| c.0);
985710106 for (mvs, bits, info) in ccands {
9858- let trials = [
9859- (0usize, x, y, side, true),
9860- (1, x / 2, y / 2, side / 2, false),
9861- (2, x / 2, y / 2, side / 2, false),
9862- ]
9863- .map(|(plane, px, py, s, is_luma)| {
10107+ let trials: Vec<Trial> = units
10108+ .iter()
10109+ .map(|&(plane, px, py, s, is_luma)| {
986410110 let (r0, r1) = match plane {
986510111 0 => (
986610112 (reference.y.as_slice(), reference.width, luma.true_width, luma.true_height),
@@ -9898,10 +10144,10 @@ fn search_skip_64(
989810144 search.deadzone,
989910145 TxbSet::Luma32Inter,
990010146 )
9901- });
10147+ })
10148+ .collect();
990210149 let syntax = fixed - ref_bits + bits;
9903- let cost =
9904- trials[0].sse + trials[1].sse + trials[2].sse + search.lambda * syntax;
10150+ let cost = trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * syntax;
990510151 if best.as_ref().is_none_or(|b| cost < b.0) {
990610152 best = Some((cost, syntax, info, trials));
990710153 }
@@ -9931,11 +10177,13 @@ fn search_skip_64(
993110177 let mut luma_levels: Option<(Vec<i32>, u8, Vec<TxType>)> = None;
993210178 if residual {
993310179 let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
10180+ // Square by construction (the `debug_assert` above), so `units` is
10181+ // one entry per plane and `chosen.2[plane]` is that plane's trial.
993410182 let residual_trials = [0usize, 1, 2].map(|plane| {
993510183 let (target, px, py, s) = if plane == 0 {
9936- (&*luma, x, y, side)
10184+ (&*luma, x, y, bw)
993710185 } else {
9938- (&chroma[plane - 1], x / 2, y / 2, side / 2)
10186+ (&chroma[plane - 1], x / 2, y / 2, bw / 2)
993910187 };
994010188 target.code_from_prediction(
994110189 px,
@@ -9967,7 +10215,7 @@ fn search_skip_64(
996710215 commit_inter_luma(
996810216 luma,
996910217 (x, y),
9970- side,
10218+ bw,
997110219 info.mv,
997210220 (&reference.y, reference.width, luma.true_width, luma.true_height),
997310221 search,
@@ -9988,18 +10236,20 @@ fn search_skip_64(
998810236 B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
998910237 }
999010238 luma_levels = Some((levels, depth, tx_types));
9991- chosen = (cost, false, residual_trials);
10239+ chosen = (cost, false, residual_trials.to_vec());
999210240 }
999310241 }
999410242
999510243 let (cost, skip, trials) = chosen;
999610244 // `commit_inter_luma` already wrote the residual arm's luma (its four
999710245 // split units are not one 64-sided trial); a skip winner overwrites it.
9998- if skip || !luma_committed {
9999- luma.commit(x, y, side, &trials[0]);
10246+ for (&(plane, px, py, s, _), trial) in units.iter().zip(&trials) {
10247+ match plane {
10248+ 0 if skip || !luma_committed => luma.commit(px, py, s, trial),
10249+ 0 => {}
10250+ _ => chroma[plane - 1].commit(px, py, s, trial),
10251+ }
1000010252 }
10001- chroma[0].commit(x / 2, y / 2, side / 2, &trials[1]);
10002- chroma[1].commit(x / 2, y / 2, side / 2, &trials[2]);
1000310253 Some((
1000410254 cost,
1000510255 BlockCoeffs {
@@ -10019,8 +10269,8 @@ fn search_skip_64(
1001910269 (false, Some((levels, _, _))) => coeffs(levels, BLOCK),
1002010270 (false, None) => coeffs(&trials[0].levels, BLOCK),
1002110271 },
10022- u: if skip { Vec::new() } else { coeffs(&trials[1].levels, side / 2) },
10023- v: if skip { Vec::new() } else { coeffs(&trials[2].levels, side / 2) },
10272+ u: if skip { Vec::new() } else { coeffs(&trials[1].levels, bw / 2) },
10273+ v: if skip { Vec::new() } else { coeffs(&trials[2].levels, bw / 2) },
1002410274 ..BlockCoeffs::default()
1002510275 },
1002610276 ))
@@ -12371,6 +12621,44 @@ pub(crate) fn encode_inter_frame(
1237112621 fctx,
1237212622 ))
1237312623 .flatten();
12624+ // lane-b128hv: the same root as two 128x64 / 64x128 halves. Both cuts
12625+ // are priced; the cheaper one competes with the NONE block and with
12626+ // the four superblocks below.
12627+ let forced_rect = FORCE_B128_RECT.load(std::sync::atomic::Ordering::Relaxed);
12628+ let root_rect = (sb128_search && b128_rect() && cells.len() == 4)
12629+ .then(|| {
12630+ let mut best: Option<(bool, _)> = None;
12631+ for horz in [true, false] {
12632+ if forced_rect != 0 && forced_rect != u8::from(horz) + u8::from(!horz) * 2 {
12633+ continue;
12634+ }
12635+ let Some(found) = search_root_128_rect(
12636+ &mut luma,
12637+ &mut chroma,
12638+ &mut grid,
12639+ (root_r, root_c),
12640+ (rows, cols),
12641+ (header.mi_cols, header.mi_rows),
12642+ search,
12643+ &tpl_factors,
12644+ sb_q.as_ref(),
12645+ sb_cols,
12646+ tpl_cells_x,
12647+ base_q_idx,
12648+ reference,
12649+ &root_compound,
12650+ horz,
12651+ fctx,
12652+ ) else {
12653+ continue;
12654+ };
12655+ if best.as_ref().is_none_or(|b: &(bool, (f64, f64, _, _))| found.0 < b.1.0) {
12656+ best = Some((horz, found));
12657+ }
12658+ }
12659+ best
12660+ })
12661+ .flatten();
1237412662 for (sb_r, sb_c) in cells {
1237512663 // lane-b64: the whole superblock as ONE 64x64 block, tried before
1237612664 // its quadrants are (`search_skip_64`) and compared against the
@@ -12470,7 +12758,7 @@ pub(crate) fn encode_inter_frame(
1247012758 &mut luma,
1247112759 &mut chroma,
1247212760 (x64, y64),
12473- SUPERBLOCK,
12761+ (SUPERBLOCK, SUPERBLOCK),
1247412762 &sb_search,
1247512763 b64_residual() && !screen,
1247612764 reference,
@@ -12949,18 +13237,56 @@ pub(crate) fn encode_inter_frame(
1294913237 // `partition_w128` symbol) against what its four superblocks really
1295013238 // cost, the same weighing the 64 root does one size down. Both sides
1295113239 // carry their own partition symbol, so the comparison is complete.
12952- if let Some((cost128, lambda128, block, after)) = root128
13240+ // lane-b128hv: `None` is the NONE arm, `Some(horz)` a rect cut.
13241+ let mut cands: Vec<(f64, f64, Option<bool>, Vec<BlockCoeffs>, _)> = Vec::new();
13242+ if let Some((c, l, b, a)) = root128 {
13243+ cands.push((c, l, None, vec![b], a));
13244+ }
13245+ if let Some((horz, (c, l, halves, a))) = root_rect {
13246+ cands.push((c, l, Some(horz), halves.to_vec(), a));
13247+ }
13248+ // The rect witness knob drops the NONE arm outright: on synthetic
13249+ // content the whole block always wins its own comparison.
13250+ if forced_rect != 0 {
13251+ cands.retain(|c| c.2.is_some());
13252+ }
13253+ cands.sort_by(|a, b| a.0.total_cmp(&b.0));
13254+ if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next()
1295313255 && (cost128 < root_cost + lambda128 * crate::tile::partition_bits(128, true)
12954- // The witness knob takes the root whatever it costs, so the
12955- // forced residual block really reaches the writer.
12956- || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed))
13256+ // The witness knobs take the root whatever it costs, so the
13257+ // forced block really reaches the writer.
13258+ || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed)
13259+ || forced_rect != 0)
1295713260 {
12958- B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1295913261 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
1296013262 blocks.truncate(mark128);
1296113263 restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after);
12962- record_mi(&mut grid, root_r * 16, root_c * 16, 32, block.inter, block.skip);
12963- blocks.push(((root_r * 2) * cols + root_c * 2, Quadrant::Whole128(block)));
13264+ let at = (root_r * 2) * cols + root_c * 2;
13265+ match shape {
13266+ None => {
13267+ B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13268+ let block = halves.into_iter().next().expect("the NONE arm's block");
13269+ record_mi(&mut grid, root_r * 16, root_c * 16, 32, block.inter, block.skip);
13270+ blocks.push((at, Quadrant::Whole128(block)));
13271+ }
13272+ Some(horz) => {
13273+ if horz {
13274+ B128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13275+ } else {
13276+ B128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13277+ }
13278+ let (w_mi, h_mi) = if horz { (32usize, 16usize) } else { (16, 32) };
13279+ for (i, half) in halves.iter().enumerate() {
13280+ let (mr, mc) = if horz {
13281+ (root_r * 16 + i * 16, root_c * 16)
13282+ } else {
13283+ (root_r * 16, root_c * 16 + i * 16)
13284+ };
13285+ record_mi_rect(&mut grid, mr, mc, (w_mi, h_mi), half.inter, half.skip);
13286+ }
13287+ blocks.push((at, Quadrant::Rect128(horz, halves)));
13288+ }
13289+ }
1296413290 for q in 1..16 {
1296513291 let (r32, c32) = (root_r * 2 + q / 4, root_c * 2 + q % 4);
1296613292 blocks.push((r32 * cols + c32, Quadrant::Covered));
@@ -13018,10 +13344,28 @@ pub(crate) fn encode_inter_frame(
1301813344 matches!(q, Quadrant::Whole128(b) if b.inter.is_some_and(|i| i.ref1.is_some()))
1301913345 })
1302013346 .count();
13347+ // lane-b128hv: and how many roots took a rect cut instead, per shape
13348+ // -- the HORZ/VERT fire count the gate rows are read against.
13349+ let horz = blocks
13350+ .iter()
13351+ .filter(|q| matches!(q, Quadrant::Rect128(true, _)))
13352+ .count();
13353+ let vert = blocks
13354+ .iter()
13355+ .filter(|q| matches!(q, Quadrant::Rect128(false, _)))
13356+ .count();
13357+ let rect_compound = blocks
13358+ .iter()
13359+ .filter(|q| {
13360+ matches!(q, Quadrant::Rect128(_, hs)
13361+ if hs.iter().any(|b| b.inter.is_some_and(|i| i.ref1.is_some())))
13362+ })
13363+ .count();
1302113364 eprintln!(
1302213365 "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \
13023- {compound} compound), {roots} coded blocks ({:.1}% of the frame's area at 128)",
13024- 100.0 * (whole * 16) as f64 / blocks.len().max(1) as f64,
13366+ {compound} compound), {horz} HORZ + {vert} VERT roots ({rect_compound} with a \
13367+ compound half), {roots} coded blocks ({:.1}% of the frame's area at 128)",
13368+ 100.0 * ((whole + horz + vert) * 16) as f64 / blocks.len().max(1) as f64,
1302513369 );
1302613370 }
1302713371 let modes = blocks
@@ -16536,6 +16880,102 @@ mod tests {
1653616880 }
1653716881 }
1653816882
16883+ /// lane-b128hv: the 128 root's `PARTITION_HORZ` and `PARTITION_VERT`
16884+ /// arms -- two 128x64 / 64x128 inter blocks where the NONE arm codes one
16885+ /// square. Three passes over one `testsrc2` clip:
16886+ ///
16887+ /// * HORZ forced at every root ([`force_b128_rect`]), so every context
16888+ /// the 128x64 shape reads is exercised rather than the handful the RD
16889+ /// would pick;
16890+ /// * VERT forced the same way;
16891+ /// * UNFORCED, which is the count the gate rows are read against -- the
16892+ /// same clip with the RD free to choose among NONE / HORZ / VERT /
16893+ /// four superblocks.
16894+ ///
16895+ /// Each pass is sample-exact against the encoder's own reconstruction
16896+ /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
16897+ /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
16898+ /// before this lane by construction: `write_sb128_root` could only name
16899+ /// `PARTITION_NONE` or `PARTITION_SPLIT`, so the count was 0 on all three.
16900+ ///
16901+ /// cargo test -p ec-av1 --release --lib -- --ignored \
16902+ /// a_128_root_horz_and_vert --nocapture
16903+ #[test]
16904+ #[ignore = "sets the process-global superblock size: run it alone"]
16905+ fn a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders() {
16906+ let _knobs = crate::speed::knob_write();
16907+ if !have_ffmpeg() {
16908+ eprintln!("SKIP: no ffmpeg");
16909+ return;
16910+ }
16911+ force_sb128(true);
16912+ let dir = std::env::temp_dir().join(format!("ec-av1-b128hv-{}", std::process::id()));
16913+ std::fs::create_dir_all(&dir).unwrap();
16914+ let clip = dir.join("testsrc2-1280x768.y4m");
16915+ let ok = Command::new("ffmpeg")
16916+ .args(["-v", "error", "-y", "-f", "lavfi"])
16917+ .args(["-i", "testsrc2=size=1280x768:rate=24"])
16918+ .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
16919+ .arg(&clip)
16920+ .status()
16921+ .expect("ffmpeg failed to run")
16922+ .success();
16923+ assert!(ok, "ffmpeg could not write the synthetic clip");
16924+ let (width, height) = (1280usize, 768usize);
16925+ let pictures =
16926+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
16927+ let mut unforced = (0usize, 0usize);
16928+ for (label, force) in [("HORZ", 1u8), ("VERT", 2), ("unforced", 0)] {
16929+ force_b128_rect(force);
16930+ let _ = take_b128_horz_hits();
16931+ let _ = take_b128_vert_hits();
16932+ let _ = crate::tile::take_sb128_horz_hits();
16933+ let _ = crate::tile::take_sb128_vert_hits();
16934+ let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
16935+ let (won_h, won_v) = (take_b128_horz_hits(), take_b128_vert_hits());
16936+ let (coded_h, coded_v) = (
16937+ crate::tile::take_sb128_horz_hits(),
16938+ crate::tile::take_sb128_vert_hits(),
16939+ );
16940+ eprintln!(
16941+ "{label}: search won {won_h} HORZ + {won_v} VERT roots, writer coded \
16942+ {coded_h} 128x64 + {coded_v} 64x128 halves"
16943+ );
16944+ match force {
16945+ 1 => assert!(coded_h > 0, "no 128x64 half was coded with HORZ forced"),
16946+ 2 => assert!(coded_v > 0, "no 64x128 half was coded with VERT forced"),
16947+ // The unforced count is REPORTED, not asserted: it is the
16948+ // number the gate is read against, and a zero here would be
16949+ // an RD result, not a defect (the forced passes already prove
16950+ // the writer and the reader agree on the shape).
16951+ _ => unforced = (won_h, won_v),
16952+ }
16953+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
16954+ assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
16955+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
16956+ for (plane, got, want) in [
16957+ ("luma", &dec.y, &frame.reconstruction.y),
16958+ ("U", &dec.u, &frame.reconstruction.u),
16959+ ("V", &dec.v, &frame.reconstruction.v),
16960+ ] {
16961+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
16962+ assert_eq!(differ, 0, "{label} frame {i}: {plane} -- {differ} samples differ");
16963+ }
16964+ }
16965+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
16966+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
16967+ assert_eq!(dec.y, frame.reconstruction.y, "{label} frame {i}: ffmpeg luma");
16968+ assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
16969+ assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
16970+ }
16971+ }
16972+ force_b128_rect(0);
16973+ eprintln!(
16974+ "unforced on testsrc2: {} HORZ + {} VERT roots over 12 frames",
16975+ unforced.0, unforced.1
16976+ );
16977+ }
16978+
1653916979 #[test]
1654016980 #[ignore = "sets the process-global superblock size: run it alone"]
1654116981 fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {
@@ -17987,7 +18427,13 @@ mod tests {
1798718427 // 33017 at q=60 (the same LENGTH, different bytes).
1798818428 // Re-taken at the merge of lane-arftf (ARF filter strength 2) and
1798918429 // lane-rlclamp onto the 128 compound default.
17990- let pins: [(u8, usize, u64); 2] = [(150, 8290, 0x92cb11033d1f5813), (60, 33227, 0x57ee6b1f8eacd881)];
18430+ // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ
18431+ // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks,
18432+ // so every inter frame whose RD takes one codes a different partition
18433+ // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that
18434+ // quantizer the rect cut never wins its own comparison on this clip.
18435+ // `EC_AV1_B128HV=0` restores 8290 exactly.
18436+ let pins: [(u8, usize, u64); 2] = [(150, 8291, 0x1f00bb0eb099a27f), (60, 33227, 0x57ee6b1f8eacd881)];
1799118437 let coded: Vec<(u8, usize, u64)> = pins
1799218438 .iter()
1799318439 .map(|&(q, _, _)| {
crates/ec-av1/src/mvstack.rsmodified+43 -0
@@ -372,6 +372,49 @@ impl MiGrid {
372372 }
373373 }
374374
375+ /// lane-b128hv: the raw cells and skip flags of one rect region, and the
376+ /// write-back that undoes a trial that published into it -- the 128
377+ /// root's HORZ/VERT search stamps its FIRST half so that the second
378+ /// half's mv stack is the one the writer will rebuild, then puts the grid
379+ /// back for the four-superblock arm it is weighed against.
380+ pub fn snapshot_rect(
381+ &self,
382+ row: usize,
383+ col: usize,
384+ h: usize,
385+ w: usize,
386+ ) -> (Vec<Option<MiInfo>>, Vec<bool>) {
387+ let mut cells = Vec::with_capacity(h * w);
388+ let mut skips = Vec::with_capacity(h * w);
389+ for r in row..(row + h).min(self.rows) {
390+ let c1 = (col + w).min(self.cols);
391+ cells.extend_from_slice(&self.cells[r * self.cols + col..r * self.cols + c1]);
392+ skips.extend_from_slice(&self.skips[r * self.cols + col..r * self.cols + c1]);
393+ }
394+ (cells, skips)
395+ }
396+
397+ /// Puts a [`Self::snapshot_rect`] back.
398+ pub fn restore_rect(
399+ &mut self,
400+ row: usize,
401+ col: usize,
402+ h: usize,
403+ w: usize,
404+ snap: &(Vec<Option<MiInfo>>, Vec<bool>),
405+ ) {
406+ let mut i = 0;
407+ for r in row..(row + h).min(self.rows) {
408+ let c1 = (col + w).min(self.cols);
409+ let n = c1 - col;
410+ self.cells[r * self.cols + col..r * self.cols + c1]
411+ .copy_from_slice(&snap.0[i..i + n]);
412+ self.skips[r * self.cols + col..r * self.cols + c1]
413+ .copy_from_slice(&snap.1[i..i + n]);
414+ i += n;
415+ }
416+ }
417+
375418 /// The unit at `(row, col)`, or `None` when it is outside the grid, hasn't
376419 /// been coded, or sits outside the current tile's own bounds ([`Self::set_tile_bounds`]).
377420 pub fn get(&self, row: usize, col: usize) -> Option<MiInfo> {
crates/ec-av1/src/tile.rsmodified+395 -30
@@ -464,6 +464,184 @@ fn write_inter_block_128(
464464 Ok(())
465465 }
466466
467+/// lane-b128hv: one 128x64 (HORZ) or 64x128 (VERT) inter block, the two
468+/// halves a `PARTITION_HORZ`/`PARTITION_VERT` 128 superblock root carries --
469+/// the syntax `decode_inter_block` reads for `sb128_rect` (decode.rs ~35343):
470+/// the same chain [`write_inter_block_128`] writes, at the block's own
471+/// rectangular window. Every CDF/context decision is taken at the enclosing
472+/// square `side` of 128 (what the decoder's `inter_piece!` passes), and the
473+/// block's true footprint governs only its mv-stack window, its mi/grid stamp
474+/// and its neighbour bands (decode.rs' own `write_w`/`write_h` split).
475+///
476+/// SKIP only: the decoder reads a rect half's residual through the mu-chunk
477+/// loop, but the 128 NONE residual arm it would share is itself parked
478+/// (`EC_AV1_B128RES`), so offering one here would buy the same open filter
479+/// mismatch for a candidate the RD takes 0-2 times a frame.
480+///
481+/// # Errors
482+/// A block that is intra or that is not skipped.
483+#[allow(clippy::too_many_arguments)]
484+fn write_inter_block_128_rect(
485+ enc: &mut SymbolEncoder,
486+ cdfs: &mut Cdfs,
487+ neighbours: &mut Neighbours,
488+ grid: &mut MiGrid,
489+ // The half's own top-left position in mode-info (4x4) units.
490+ at_mi: (usize, usize),
491+ // Its true footprint in samples: (128, 64) at HORZ, (64, 128) at VERT.
492+ (w, h): (usize, usize),
493+ block: &BlockCoeffs,
494+ mi_cols: u32,
495+ mi_rows: u32,
496+ tx_select: bool,
497+) -> Result<()> {
498+ let info = block.inter.ok_or_else(|| {
499+ Error::unsupported("AV1 tile", "a 128-root rectangular half is coded inter")
500+ })?;
501+ if !block.skip {
502+ return Err(Error::unsupported(
503+ "AV1 tile",
504+ "a 128-root rectangular half carries a residual",
505+ ));
506+ }
507+ let (mi_r, mi_c) = at_mi;
508+ let (w_mi, h_mi) = (w / MI, h / MI);
509+ let has_above = neighbours.has_above(mi_r);
510+ let has_left = neighbours.has_left(mi_c);
511+ let skip_ctx =
512+ usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
513+ enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
514+ write_cdef_idx(enc, (mi_r, mi_c), block.skip);
515+ // NOT a whole superblock: decode.rs' `whole_sb` is `write_w == write_h ==
516+ // sb_px`, so a rect half reads its `delta_q` group even when skipped.
517+ write_delta_q(enc, cdfs, (mi_r, mi_c), false, block.skip);
518+ let ii_ctx = intra_inter_ctx(
519+ has_above,
520+ has_left,
521+ neighbours.above_inter[mi_c],
522+ neighbours.left_inter[mi_r],
523+ );
524+ enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]);
525+ write_comp_mode(
526+ enc,
527+ cdfs,
528+ neighbours,
529+ (mi_r, mi_c),
530+ (has_above, has_left),
531+ info.ref1.is_some(),
532+ );
533+ let (mv, mv1, is_new_mv) = if info.ref1.is_some() {
534+ write_compound_block(
535+ enc,
536+ cdfs,
537+ neighbours,
538+ grid,
539+ (mi_r, mi_c),
540+ (w_mi, h_mi),
541+ (has_above, has_left),
542+ info,
543+ (mi_cols as usize, mi_rows as usize),
544+ )?
545+ } else {
546+ write_single_ref(
547+ enc,
548+ cdfs,
549+ info.ref_frame,
550+ neighbours.above_ref[mi_c],
551+ neighbours.above_ref1[mi_c],
552+ neighbours.left_ref[mi_r],
553+ neighbours.left_ref1[mi_r],
554+ );
555+ let stack = find_mv_stack(
556+ grid,
557+ mi_r,
558+ mi_c,
559+ w_mi,
560+ h_mi,
561+ info.ref_frame,
562+ mi_cols as usize,
563+ mi_rows as usize,
564+ );
565+ let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
566+ (mv, (0, 0), is_new_mv)
567+ };
568+ for dr in 0..h_mi {
569+ for dc in 0..w_mi {
570+ grid.set(
571+ mi_r + dr,
572+ mi_c + dc,
573+ MiInfo {
574+ is_inter: true,
575+ ref_frame: info.ref_frame,
576+ ref_frame1: info.ref1.unwrap_or(NO_REF1),
577+ mv1: mv16(mv1),
578+ mv: mv16(mv),
579+ is_new_mv,
580+ size: w_mi as u8,
581+ size_h: h_mi as u8,
582+ is_global_mv0: false,
583+ is_global_mv1: false,
584+ },
585+ );
586+ }
587+ }
588+ if info.ref1.is_none() {
589+ write_motion_mode(
590+ enc,
591+ cdfs,
592+ grid,
593+ (mi_r, mi_c),
594+ (w_mi, h_mi),
595+ (w, h),
596+ (mi_cols as usize, mi_rows as usize),
597+ info.ref_frame,
598+ block.motion_mode,
599+ )?;
600+ }
601+ if tx_select {
602+ // `read_block_tx_size_rect`'s skip arm: `txfm_partition_update_rect`
603+ // with the BLOCK's own size in both bands, no symbol.
604+ neighbours.record_txfm_rect((mi_r, mi_c), (w, h), (w, h));
605+ }
606+ let zero_grids = [
607+ vec![0i32; TX32 * TX32],
608+ vec![0i32; TX32 * TX32],
609+ vec![0i32; TX32 * TX32],
610+ ];
611+ // A 128 root's half is always SUB (16 px) aligned, so the coarse mode /
612+ // side bands are named by the same SUB-grid origin every square block
613+ // uses.
614+ let at_sub = (mi_r / (SUB / MI), mi_c / (SUB / MI));
615+ neighbours.record_planes_rect(at_sub, (w, h), 0, &zero_grids, true);
616+ neighbours.record_inter_rect_mi((mi_r, mi_c), (w, h), block.skip, true, block_ref(block));
617+ if let Some(r1) = info.ref1 {
618+ neighbours.record_compound_rect_mi((mi_r, mi_c), (w, h), r1, 0, 1);
619+ }
620+ if w > h {
621+ SB128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
622+ } else {
623+ SB128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
624+ }
625+ Ok(())
626+}
627+
628+/// lane-b128hv: how many 128x64 / 64x128 halves the inter writer has coded
629+/// since the last [`take_sb128_horz_hits`] / [`take_sb128_vert_hits`] (class
630+/// `gate-blind-to-feature`).
631+static SB128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
632+/// The VERT twin of [`SB128_HORZ_HITS`].
633+static SB128_VERT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
634+
635+/// The 128x64-half count since the last call, and zero it.
636+pub fn take_sb128_horz_hits() -> usize {
637+ SB128_HORZ_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
638+}
639+
640+/// The 64x128-half count since the last call, and zero it.
641+pub fn take_sb128_vert_hits() -> usize {
642+ SB128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
643+}
644+
467645 /// lane-b128r: how many of those blocks carried a REAL residual (four
468646 /// TX_64X64 luma units plus their per-chunk chroma pair) rather than being
469647 /// skipped, since the last [`take_sb128_residual_hits`].
@@ -1672,6 +1850,10 @@ fn ec_rng_trace(msg: impl FnOnce() -> String) {
16721850
16731851 /// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided.
16741852 const PARTITION_NONE: usize = 0;
1853+/// `PARTITION_HORZ` (spec 6.10.4): the block cut into a top and a bottom half.
1854+const PARTITION_HORZ: usize = 1;
1855+/// `PARTITION_VERT` (spec 6.10.4): the block cut into a left and a right half.
1856+const PARTITION_VERT: usize = 2;
16751857 /// `PARTITION_SPLIT` (spec 6.10.4): the block cut into four quadrants.
16761858 const PARTITION_SPLIT: usize = 3;
16771859
@@ -2403,6 +2585,15 @@ pub enum Quadrant {
24032585 /// interleaved with its chroma per 64x64 mu chunk, which this writer has
24042586 /// no path for; [`crate::tile::write_inter_block_128`] refuses one.
24052587 Whole128(BlockCoeffs),
2588+ /// lane-b128hv: the two 128x64 (`true`) or 64x128 (`false`) inter blocks a
2589+ /// `PARTITION_HORZ` / `PARTITION_VERT` 128 superblock root carries, in the
2590+ /// order the decoder reads them (top then bottom, left then right).
2591+ /// Carried by the top-left 32x32 entry of the root's sixteen, exactly as
2592+ /// [`Whole128`](Quadrant::Whole128) is.
2593+ ///
2594+ /// SKIP only ([`crate::tile::write_inter_block_128_rect`] refuses a
2595+ /// residual), single reference or compound.
2596+ Rect128(bool, Vec<BlockCoeffs>),
24062597 /// A quadrant a [`Whole64`](Quadrant::Whole64) at its superblock's
24072598 /// top-left already coded; it carries no block of its own.
24082599 Covered,
@@ -2415,7 +2606,7 @@ impl Quadrant {
24152606 Quadrant::Whole(block) | Quadrant::Whole64(block) | Quadrant::Whole128(block) => {
24162607 std::slice::from_ref(block)
24172608 }
2418- Quadrant::Split(blocks) => blocks.as_slice(),
2609+ Quadrant::Split(blocks) | Quadrant::Rect128(_, blocks) => blocks.as_slice(),
24192610 Quadrant::Covered => &[],
24202611 }
24212612 }
@@ -2760,14 +2951,18 @@ impl Neighbours {
27602951 /// [`Self::record_palette_y`] for the chroma bands (decode.rs
27612952 /// `record_palette_uv_rect`) -- `size == 0` clears stale state the same
27622953 /// way, and the span is in LUMA pixels for both planes' bands alike.
2763- fn record_palette_uv(&mut self, (r, c): (usize, usize), side: usize, size: u8, colors: [u16; 8]) {
2764- for cell in 0..(side / MI).max(1) {
2954+ fn record_palette_uv(&mut self, (r, c): (usize, usize), (w, h): (usize, usize), size: u8, colors: [u16; 8]) {
2955+ // lane-b128hv: the above band spans the block's WIDTH and the left
2956+ // band its HEIGHT; identical to the one loop this replaces at w == h.
2957+ for cell in 0..(w / MI).max(1) {
27652958 if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) {
27662959 *e = size;
27672960 if size > 0 {
27682961 self.above_palette_uv_colors[c + cell] = colors;
27692962 }
27702963 }
2964+ }
2965+ for cell in 0..(h / MI).max(1) {
27712966 if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) {
27722967 *e = size;
27732968 if size > 0 {
@@ -2780,14 +2975,18 @@ impl Neighbours {
27802975 /// What a just-written block leaves in the palette bands (decode.rs
27812976 /// `record_palette_y_rect`): its size and colours over every 4x4 unit it
27822977 /// spans, `0` for a block that took no palette.
2783- fn record_palette_y(&mut self, (r, c): (usize, usize), side: usize, size: u8, colors: [u16; 8]) {
2784- for cell in 0..(side / MI).max(1) {
2978+ fn record_palette_y(&mut self, (r, c): (usize, usize), (w, h): (usize, usize), size: u8, colors: [u16; 8]) {
2979+ // lane-b128hv: the above band spans the block's WIDTH and the left
2980+ // band its HEIGHT; identical to the one loop this replaces at w == h.
2981+ for cell in 0..(w / MI).max(1) {
27852982 if let Some(e) = self.above_palette_size.get_mut(c + cell) {
27862983 *e = size;
27872984 if size > 0 {
27882985 self.above_palette_colors[c + cell] = colors;
27892986 }
27902987 }
2988+ }
2989+ for cell in 0..(h / MI).max(1) {
27912990 if let Some(e) = self.left_palette_size.get_mut(r + cell) {
27922991 *e = size;
27932992 if size > 0 {
@@ -2814,6 +3013,27 @@ impl Neighbours {
28143013 }
28153014 }
28163015
3016+ /// lane-b128hv: decode.rs `txfm_partition_update_rect` -- the two bands
3017+ /// take the transform's own HEIGHT (left) and WIDTH (above), over the
3018+ /// txb's own rect span. [`Self::record_txfm`] is this at `tx_w == tx_h`.
3019+ fn record_txfm_rect(
3020+ &mut self,
3021+ (mi_r, mi_c): (usize, usize),
3022+ (tx_w, tx_h): (usize, usize),
3023+ (txb_w, txb_h): (usize, usize),
3024+ ) {
3025+ for i in 0..txb_h / MI {
3026+ if let Some(cell) = self.left_txfm.get_mut(mi_r + i) {
3027+ *cell = tx_h as u8;
3028+ }
3029+ }
3030+ for i in 0..txb_w / MI {
3031+ if let Some(cell) = self.above_txfm.get_mut(mi_c + i) {
3032+ *cell = tx_w as u8;
3033+ }
3034+ }
3035+ }
3036+
28173037 /// `get_tx_size_context` as libaom writes it for a block inside an INTER
28183038 /// frame (decode.rs `tx_size_context_txfm_rect`): the `TXFM_CONTEXT`
28193039 /// bands, except that an *inter* neighbour contributes its own BLOCK size.
@@ -2935,15 +3155,31 @@ impl Neighbours {
29353155 mode: usize,
29363156 grids: &[Vec<i32>; 3],
29373157 luma: bool,
3158+ ) {
3159+ self.record_planes_rect(at, (side, side), mode, grids, luma);
3160+ }
3161+
3162+ /// lane-b128hv: [`Self::record_planes`] with independent above (width) /
3163+ /// left (height) extents, decode.rs `record_rect_mi`'s own split -- the
3164+ /// 128 root's HORZ/VERT halves are the writer's first rect blocks.
3165+ fn record_planes_rect(
3166+ &mut self,
3167+ at: (usize, usize),
3168+ (w, h): (usize, usize),
3169+ mode: usize,
3170+ grids: &[Vec<i32>; 3],
3171+ luma: bool,
29383172 ) {
29393173 let (r, c) = at;
2940- for cell in 0..side / SUB {
3174+ for cell in 0..w / SUB {
29413175 self.above_mode[c + cell] = mode;
3176+ self.above_side[c + cell] = w;
3177+ }
3178+ for cell in 0..h / SUB {
29423179 self.left_mode[r + cell] = mode;
2943- self.above_side[c + cell] = side;
2944- self.left_side[r + cell] = side;
3180+ self.left_side[r + cell] = h;
29453181 }
2946- self.record_mi_planes((r * (SUB / MI), c * (SUB / MI)), side, grids, luma);
3182+ self.record_mi_planes_rect((r * (SUB / MI), c * (SUB / MI)), (w, h), grids, luma);
29473183 }
29483184
29493185 /// The coefficient-context half of [`Self::record`], taking the block's
@@ -2964,19 +3200,33 @@ impl Neighbours {
29643200 side: usize,
29653201 grids: &[Vec<i32>; 3],
29663202 luma: bool,
3203+ ) {
3204+ self.record_mi_planes_rect(at_mi, (side, side), grids, luma);
3205+ }
3206+
3207+ /// [`Self::record_mi_planes`] with independent above (width) / left
3208+ /// (height) extents (lane-b128hv, decode.rs `record_mi_rect`).
3209+ fn record_mi_planes_rect(
3210+ &mut self,
3211+ at_mi: (usize, usize),
3212+ (w, h): (usize, usize),
3213+ grids: &[Vec<i32>; 3],
3214+ luma: bool,
29673215 ) {
29683216 let (mi_r, mi_c) = at_mi;
29693217 if screen_armed() {
29703218 let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8]));
2971- self.record_palette_y(at_mi, side, size, colors);
3219+ self.record_palette_y(at_mi, (w, h), size, colors);
29723220 let (uv_size, uv_colors) = self.pending_palette_uv.take().unwrap_or((0, [0u16; 8]));
2973- self.record_palette_uv(at_mi, side, uv_size, uv_colors);
3221+ self.record_palette_uv(at_mi, (w, h), uv_size, uv_colors);
29743222 }
29753223 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
2976- let side_mi = side / MI;
2977- for cell in 0..side_mi {
2978- self.left_side_mi[mi_r + cell] = side;
2979- self.above_side_mi[mi_c + cell] = side;
3224+ let (w_mi, h_mi) = (w / MI, h / MI);
3225+ for cell in 0..h_mi {
3226+ self.left_side_mi[mi_r + cell] = h;
3227+ }
3228+ for cell in 0..w_mi {
3229+ self.above_side_mi[mi_c + cell] = w;
29803230 }
29813231 // libaom rounds the luma edge up to the plane's own 4x4 unit before
29823232 // clamping a subsampled plane (`ROUND_POWER_OF_TWO(max_blocks_high,
@@ -2995,25 +3245,29 @@ impl Neighbours {
29953245 round_up_even(self.mi_cols),
29963246 round_up_even(self.mi_cols),
29973247 ];
2998- for cell in 0..side_mi {
3248+ for cell in 0..h_mi {
29993249 let keep_left = self.left[mi_r + cell][0];
3000- let keep_above = self.above[mi_c + cell][0];
30013250 self.left[mi_r + cell] = std::array::from_fn(|plane| {
3002- if cell < side_mi.min(bound_h[plane].saturating_sub(mi_r)) {
3251+ if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) {
30033252 states[plane]
30043253 } else {
30053254 Default::default()
30063255 }
30073256 });
3257+ if !luma {
3258+ self.left[mi_r + cell][0] = keep_left;
3259+ }
3260+ }
3261+ for cell in 0..w_mi {
3262+ let keep_above = self.above[mi_c + cell][0];
30083263 self.above[mi_c + cell] = std::array::from_fn(|plane| {
3009- if cell < side_mi.min(bound_w[plane].saturating_sub(mi_c)) {
3264+ if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) {
30103265 states[plane]
30113266 } else {
30123267 Default::default()
30133268 }
30143269 });
30153270 if !luma {
3016- self.left[mi_r + cell][0] = keep_left;
30173271 self.above[mi_c + cell][0] = keep_above;
30183272 }
30193273 }
@@ -3027,6 +3281,56 @@ impl Neighbours {
30273281 self.record_inter_mi((r * (SUB / MI), c * (SUB / MI)), side, skip, is_inter, ref_frame);
30283282 }
30293283
3284+ /// lane-b128hv: [`Self::record_inter_mi`] with independent above (width)
3285+ /// / left (height) spans, decode.rs `record_inter_rect_mi`'s own split.
3286+ fn record_inter_rect_mi(
3287+ &mut self,
3288+ (mi_r, mi_c): (usize, usize),
3289+ (w, h): (usize, usize),
3290+ skip: bool,
3291+ is_inter: bool,
3292+ ref_frame: i8,
3293+ ) {
3294+ let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME;
3295+ for cell in 0..h / MI {
3296+ self.left_skip[mi_r + cell] = skip;
3297+ self.left_inter[mi_r + cell] = is_inter;
3298+ self.left_ref[mi_r + cell] = ref_frame;
3299+ self.left_ref1[mi_r + cell] = None;
3300+ self.left_comp_group_idx[mi_r + cell] = if altref { 3 } else { 0 };
3301+ self.left_compound_idx[mi_r + cell] = u8::from(altref);
3302+ }
3303+ for cell in 0..w / MI {
3304+ self.above_skip[mi_c + cell] = skip;
3305+ self.above_inter[mi_c + cell] = is_inter;
3306+ self.above_ref[mi_c + cell] = ref_frame;
3307+ self.above_ref1[mi_c + cell] = None;
3308+ self.above_comp_group_idx[mi_c + cell] = if altref { 3 } else { 0 };
3309+ self.above_compound_idx[mi_c + cell] = u8::from(altref);
3310+ }
3311+ }
3312+
3313+ /// [`Self::record_compound_mi`] over a rect block's own two spans.
3314+ fn record_compound_rect_mi(
3315+ &mut self,
3316+ (mi_r, mi_c): (usize, usize),
3317+ (w, h): (usize, usize),
3318+ ref1: i8,
3319+ comp_group_idx: u8,
3320+ compound_idx: u8,
3321+ ) {
3322+ for cell in 0..h / MI {
3323+ self.left_ref1[mi_r + cell] = Some(ref1);
3324+ self.left_comp_group_idx[mi_r + cell] = comp_group_idx;
3325+ self.left_compound_idx[mi_r + cell] = compound_idx;
3326+ }
3327+ for cell in 0..w / MI {
3328+ self.above_ref1[mi_c + cell] = Some(ref1);
3329+ self.above_comp_group_idx[mi_c + cell] = comp_group_idx;
3330+ self.above_compound_idx[mi_c + cell] = compound_idx;
3331+ }
3332+ }
3333+
30303334 /// [`Self::record_inter_mi`]'s compound half (decode.rs
30313335 /// `Neighbours::record_compound_ctx_rect_mi`): overwrites the ALTREF
30323336 /// single-reference default with a real compound block's own second
@@ -3435,7 +3739,10 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
34353739 match quadrant {
34363740 // A 64x64 root is an INTER-frame partition; a
34373741 // key frame codes one as `Superblock::Whole`.
3438- Quadrant::Whole64(_) | Quadrant::Whole128(_) | Quadrant::Covered => {
3742+ Quadrant::Whole64(_)
3743+ | Quadrant::Whole128(_)
3744+ | Quadrant::Rect128(..)
3745+ | Quadrant::Covered => {
34393746 return Err(Error::unsupported(
34403747 "AV1 tile",
34413748 "a key frame codes a 64x64 block as `Superblock::Whole`",
@@ -5103,7 +5410,7 @@ pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 {
51035410 // lane-b128: a 128x128 root is SKIP by construction (the
51045411 // writer refuses a residual at that size), so it names no
51055412 // coefficients on any plane.
5106- Quadrant::Whole128(_) => return 0.0,
5413+ Quadrant::Whole128(_) | Quadrant::Rect128(..) => return 0.0,
51075414 Quadrant::Whole(_) => 32,
51085415 Quadrant::Split(_) => 16,
51095416 // lane-tx64: a 64x64 root that codes a residual pays for one
@@ -5725,6 +6032,22 @@ pub(crate) fn partition_bits(side: usize, split: bool) -> f64 {
57256032 crate::encode::symbol_bits(cdf, symbol)
57266033 }
57276034
6035+/// lane-b128hv: [`partition_bits`] for any partition symbol, at the same
6036+/// fixed (round-2) tables -- what the 128 root's HORZ/VERT candidate is priced
6037+/// with (`PARTITION_HORZ` = 1, `PARTITION_VERT` = 2).
6038+pub(crate) fn partition_bits_sym(side: usize, symbol: usize) -> f64 {
6039+ static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2));
6040+ let cdfs = &*CDFS;
6041+ let cdf: &[u16] = match side {
6042+ 128 => &cdfs.partition_w128[0],
6043+ SB => &cdfs.partition_w64[0],
6044+ BLOCK => &cdfs.partition_w32[0],
6045+ TX8 => &cdfs.partition_w8[0],
6046+ _ => &cdfs.partition_w16[0],
6047+ };
6048+ crate::encode::symbol_bits(cdf, symbol)
6049+}
6050+
57286051 /// coeffs() for one plane's transform block of any coefficients the base and
57296052 /// base-range syntax reach (spec 5.11.39).
57306053 ///
@@ -6807,12 +7130,17 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
68077130 if sb128 && sb_start {
68087131 // The 128x128 block a `PARTITION_NONE` root carries, held by the
68097132 // top-left 32x32 entry of the root's sixteen.
6810- let root_block = ((sb_r & !1) * 2 < rows && (sb_c & !1) * 2 < cols)
6811- .then(|| &blocks[(((sb_r & !1) * 2) * cols + (sb_c & !1) * 2) as usize])
6812- .and_then(|q| match q {
6813- Quadrant::Whole128(block) => Some(block),
6814- _ => None,
6815- });
7133+ let root_entry = ((sb_r & !1) * 2 < rows && (sb_c & !1) * 2 < cols)
7134+ .then(|| &blocks[(((sb_r & !1) * 2) * cols + (sb_c & !1) * 2) as usize]);
7135+ let root_block = root_entry.and_then(|q| match q {
7136+ Quadrant::Whole128(block) => Some(block),
7137+ _ => None,
7138+ });
7139+ // lane-b128hv: the two rectangular halves a HORZ/VERT root carries.
7140+ let root_rect = root_entry.and_then(|q| match q {
7141+ Quadrant::Rect128(horz, halves) => Some((*horz, halves)),
7142+ _ => None,
7143+ });
68167144 write_sb128_root(
68177145 &mut enc,
68187146 &mut cdfs,
@@ -6821,7 +7149,12 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
68217149 sb_c,
68227150 mi_cols,
68237151 mi_rows,
6824- if root_block.is_some() { PARTITION_NONE } else { PARTITION_SPLIT },
7152+ match (root_block.is_some(), root_rect) {
7153+ (true, _) => PARTITION_NONE,
7154+ (_, Some((true, _))) => PARTITION_HORZ,
7155+ (_, Some((false, _))) => PARTITION_VERT,
7156+ _ => PARTITION_SPLIT,
7157+ },
68257158 );
68267159 if let Some(block) = root_block {
68277160 let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
@@ -6839,6 +7172,35 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
68397172 sb128_none = true;
68407173 continue;
68417174 }
7175+ if let Some((horz, halves)) = root_rect {
7176+ // libaom `decode_partition` at BLOCK_128X128: `subsize` at
7177+ // (mi_row, mi_col) and a second one at + hbs (16 mi) along the
7178+ // cut axis, the second only when it is inside the frame -- the
7179+ // search only offers a root wholly inside, so both are.
7180+ let base_mi = ((sb_r & !1) as usize * SB_MI as usize, (sb_c & !1) as usize * SB_MI as usize);
7181+ let (w, h) = if horz { (128usize, 64usize) } else { (64, 128) };
7182+ for (i, half) in halves.iter().enumerate() {
7183+ let at_mi = if horz {
7184+ (base_mi.0 + i * 16, base_mi.1)
7185+ } else {
7186+ (base_mi.0, base_mi.1 + i * 16)
7187+ };
7188+ write_inter_block_128_rect(
7189+ &mut enc,
7190+ &mut cdfs,
7191+ &mut neighbours,
7192+ &mut grid,
7193+ at_mi,
7194+ (w, h),
7195+ half,
7196+ mi_cols,
7197+ mi_rows,
7198+ tx_select,
7199+ )?;
7200+ }
7201+ sb128_none = true;
7202+ continue;
7203+ }
68427204 }
68437205 {
68447206 if !sb128 {
@@ -7084,7 +7446,10 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
70847446 let block = match site {
70857447 // Already coded by the `Whole64` above -- but only inside
70867448 // a superblock that really carried one.
7087- Quadrant::Whole64(_) | Quadrant::Whole128(_) | Quadrant::Covered => {
7449+ Quadrant::Whole64(_)
7450+ | Quadrant::Whole128(_)
7451+ | Quadrant::Rect128(..)
7452+ | Quadrant::Covered => {
70887453 return Err(Error::unsupported(
70897454 "AV1 tile",
70907455 "a `Whole64`/`Covered` quadrant needs its superblock's \
lanes/b128hv.report.mdadded+205 -0
@@ -0,0 +1,205 @@
1+# lane-b128hv — HORZ and VERT at the 128 superblock root
2+
3+The partition lane-b128 deferred and lane-b128r deferred again: a
4+`PARTITION_HORZ` / `PARTITION_VERT` 128x128 root, two 128x64 / 64x128 inter
5+blocks where the NONE arm codes one square. Written, witnessed on both cuts
6+through both decoders, measured on all five 12-frame rows and both long-GOP
7+rows, and **shipped on** (`EC_AV1_B128HV=0` is the attribution control).
8+
9+## 1. What the deferral actually cost
10+
11+Both earlier reports name the blocker as "rect neighbour recording in the
12+writer and rect trials in the search". That is exactly right and it was the
13+whole of the work: **this writer had no rectangular block of any size**.
14+`record` / `record_planes` / `record_mi_planes` / `record_inter_mi` /
15+`record_txfm` and both palette bands each took ONE side and stamped it into
16+the above band AND the left band. Every one of them now has an
17+(above = width, left = height) twin, with the square entry point delegating to
18+it — decode.rs' own `record_rect` / `record_inter_rect_mi` /
19+`txfm_partition_update_rect` split, mirrored on the writer side.
20+
21+> **Stale premise in the charter**: "the 64 root's rect machinery
22+> (64x32/32x64 in `code_square`/`code_rect` paths) is the model". There is no
23+> such machinery: `grep PARTITION_HORZ crates/ec-av1/src/tile.rs` was empty
24+> before this lane. The tile writer has only ever coded `PARTITION_NONE` and
25+> `PARTITION_SPLIT` at every level. decode.rs' `sb128_rect` arm
26+> (decode.rs:35343) was the only model, and it is the one this mirrors.
27+
28+## 2. The writer
29+
30+`write_inter_block_128_rect` codes one half: `skip`, `cdef_idx`, `delta_q`,
31+`intra_inter`, `comp_mode`, the reference/mode chain, the motion mode and the
32+transform syntax — the same chain `write_inter_block_128` writes, with every
33+CDF/context decision taken at the enclosing **square** side of 128 (what the
34+decoder's `inter_piece!` passes as `side`) and only the mv-stack window, the
35+mi/grid stamp and the neighbour bands taking the block's true `128x64` /
36+`64x128` footprint. Two details the square arm does not have:
37+
38+- **`delta_q` is coded.** decode.rs' `whole_sb` is `side == write_w ==
39+ write_h == sb_px`, so a rect half is NOT the whole superblock and its
40+ `delta_q` group is read even when the block is skipped — where a skipped
41+ NONE root writes none. A writer passing `is_whole_sb = true` here would drop
42+ a symbol group the reader reads.
43+- **`record_txfm_rect`**, since `read_block_tx_size_rect`'s skip arm records
44+ the BLOCK's own width above and height left, not one square side.
45+
46+SKIP only. The decoder reads a rect half's residual (it is in
47+`rect_inter_residual_supported`), but the residual arm it would share is the
48+128 NONE one, which is parked behind `EC_AV1_B128RES=1` over an open
49+filter-stage mismatch (lane-b128r) — an inert candidate does not buy a live
50+mismatch, and the same holds here.
51+
52+`Quadrant::Rect128(horz, halves)` carries the pair on the root's top-left
53+32x32 entry, exactly as `Whole128` does.
54+
55+## 3. The search
56+
57+`search_root_128_rect` prices the root as two halves, single reference or
58+compound, through the same `search_skip_64` the NONE arm uses — which now
59+takes a `(w, h)` footprint and tiles it into squares of its SHORTER side (one
60+square when it is square, so the square path is byte-identical; two 64x64
61+luma + two 32x32 chroma squares per half otherwise). Both cuts are priced and
62+the cheaper one competes with the NONE block and with the four superblocks,
63+all four candidates carrying their own partition symbol
64+(`tile::partition_bits_sym`).
65+
66+**The first half is published into the mi grid before the second is
67+searched.** The writer publishes it (`grid.set` over the half's footprint), so
68+a second half searched against the stale grid would be priced — and its mv
69+predicted — off a stack the decoder never derives (class
70+*encoder-grid-drift-invisible-to-pixel-gate*). `MiGrid::snapshot_rect` /
71+`restore_rect` put the root's 32x32-mi window back before the four-superblock
72+arm is measured against it.
73+
74+## 4. Witness (red before / green after)
75+
76+`encode::tests::a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders`
77+(`--ignored`, it moves the process-global superblock size), three passes over
78+one 12-frame `testsrc2` clip at 1280x768:
79+
80+ HORZ: search won 660 HORZ + 0 VERT roots, writer coded 2640 128x64 + 0 64x128 halves
81+ VERT: search won 0 HORZ + 660 VERT roots, writer coded 0 128x64 + 2640 64x128 halves
82+ unforced: search won 17 HORZ + 9 VERT roots, writer coded 68 128x64 + 36 64x128 halves
83+ test ... ok
84+
85+(the writer counts are 4x the search counts because the filter search re-codes
86+each tile). Every pass sample-exact against the encoder's own reconstruction
87+through `decode_stream` **and** through ffmpeg. RED before this lane by
88+construction: `write_sb128_root` could only name `PARTITION_NONE` or
89+`PARTITION_SPLIT`, so all three counts were 0 and no such block existed to
90+decode. It was green on the first draft — no bisect was needed.
91+
92+The **unforced** row is the point: 17 HORZ + 9 VERT roots over 12 frames of
93+film-like content, with no knob set.
94+
95+## 5. Census on real content (`EC_AV1_B128_CENSUS=1`)
96+
97+Extended with the two shapes; the 4K 12-frame gate, 88 inter frames:
98+
99+| shape | per frame | total |
100+|---|---|---|
101+| whole 128x128 NONE roots | 89-102 | — |
102+| **HORZ roots** | 0-3 | **175** |
103+| **VERT roots** | 0-1 | **119** |
104+
105+On the long-GOP film A rows the 128 root fires far less often overall (3-8
106+whole roots a frame, 2-7% of the frame's area) and the rect cut fires 0 there
107+— the lever is a 4K/quiet-content one.
108+
109+## 6. Gates
110+
111+`bd_rate_screen_native`, 12 frames, four quantizers, BD-rate vs libaom
112+`cpu-used 6` / rav1e `speed 6` (lower is better). Control = the same binary at
113+`EC_AV1_B128HV=0`, which is byte-identical to the merge base (pin evidence
114+below).
115+
116+| row | control | + HORZ/VERT |
117+|---|---|---|
118+| bars 1080p | -3.5 / -19.0 | -3.4 / -19.0 |
119+| film A (1080p) | +17.9 / -6.4 | +18.0 / -6.3 |
120+| bars 2160p | +8.6 / -13.7 | **+8.4 / -14.0** |
121+| film B (2160p) | +22.9 / -3.6 | +23.0 / -3.5 |
122+| screen capture | +14.4 / -33.2 | +14.4 / -33.2 |
123+
124+The two film rows move +0.1 on both columns — WORSE, inside the ±0.3 flat
125+band but not an improvement; bars 2160p is 0.2/0.3 better; screen is
126+unchanged to the digit.
127+
128+`bd_rate_film_long_gop`, 48 pictures, one key frame and 47 inter:
129+
130+| row | control | + HORZ/VERT |
131+|---|---|---|
132+| film A | +22.0 / -8.4 | **+21.9 / -8.6** |
133+| film B | +76.5 / +1.2 | **+75.8 / +0.8** |
134+
135+**Both films down on both columns**, film B by 0.7 / 0.4. This is where the
136+arm pays and it is the arm his exports are: a 48-picture GOP has the long
137+reference chains whose 128-wide regions split cleanly along one axis.
138+
139+Wall on the long-GOP arm: film A 537.6s -> 594.0s (+10.5%), film B 434.2s ->
140+446.7s (+2.9%) — both under the +15% ceiling. (The gate's own `ours:rav1e`
141+ratios are noisier than the raw walls here: rav1e's own column moved 50.3s vs
142+55.8s between the two runs.)
143+
144+**Verdict: ships on.** Both long-GOP film rows improve on both columns, the
145+12-frame film rows are flat at ±0.1 (inside the band the compound arm shipped
146+under), screen is unchanged and bars 2160p improves.
147+
148+## 7. Pins
149+
150+`encode::tests::the_encoders_own_streams_are_byte_identical_to_their_pins`
151+re-taken: **`(150, 8291, 0x1f00bb0eb099a27f)`** — was `(150, 8290,
152+0x92cb11033d1f5813)`. The **q=60 pin does NOT move** (`(60, 33227,
153+0x57ee6b1f8eacd881)` stands): at that quantizer the rect cut never wins its
154+own comparison on the pin clip, which is itself the cheapest possible
155+statement of how sparse the arm is. `EC_AV1_B128HV=0` restores 8290 exactly —
156+the proof that nothing else in this lane touches the shipped stream. Green at
157+the default and at `EC_AV1_SPEED=6`. No other byte pin moved.
158+
159+## 8. Suite / checks (the shipped state)
160+
161+ cargo check --workspace --all-targets -j4 0 errors, 0 ec-av1 warnings
162+ s1 --skip stream:: 345 passed; 0 failed; 38 ignored RC=0
163+ s2 stream:: --skip 10bit 202 passed; 0 failed; 15 ignored RC=0
164+ s3 10bit 42 passed; 0 failed; 1 ignored RC=0
165+ --ignored every_speed_preset_decodes_sample_exact_through_both_decoders ok
166+ --ignored a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders ok
167+ the_encoders_own_streams_are_byte_identical_to_their_pins ok, and ok at EC_AV1_SPEED=6
168+
169+`encoder::tests::bitrate_target_lands_within_5_percent_over_48_frames` (it is
170+NOT `--ignored`; it runs inside s1). Its numbers on this tree, tolerance ±5%:
171+
172+| target | flat | pyramid |
173+|---|---|---|
174+| 384 kbit/s | -1.9% | +2.0% |
175+| 768 kbit/s | -2.6% | -0.0% |
176+| 1536 kbit/s | **-2.8%** | +0.1% |
177+| 2000 kbit/s | -1.7% | +0.0% |
178+
179+Worst arm -2.8%, and the arm the test's own doc calls its ceiling (the 2
180+Mbit/s pyramid, -4.4% when the tolerance was cut) now lands at +0.0%. It is
181+not sitting near its bound on this tree.
182+
183+## 9. Disposition
184+
185+- `open`: **the rect root's `delta_q` group is not priced.** A rect 128 root
186+ codes a `delta_q` symbol group that a SKIPPED NONE root omits (section 2),
187+ and `search_root_128_rect`'s cost does not charge for it — so the arm is
188+ under-priced by a few bits per root. This is the most likely reason the two
189+ 12-frame film rows read +0.1 instead of flat-or-better while the long-GOP
190+ rows gain. Next step: add `delta_q`'s own symbol cost to the rect candidate
191+ and re-run the 12-frame film rows; if they go flat-or-down the arm is a
192+ clean win on both arms of the gate.
193+- `deferred`: **the rect halves' RESIDUAL.** The decoder already reads it
194+ (`rect_inter_residual_supported` lists (128,64)/(64,128) and
195+ `read_block_tx_size_rect` codes two TX_64X64 units per half), but the arm it
196+ would share is the 128 NONE residual, parked behind `EC_AV1_B128RES=1` over
197+ an open filter-stage mismatch at a 128 block's own edge (lane-b128r).
198+ Unblocked by root-causing that mismatch.
199+- `deferred`: **the AB shapes at the 128 root** (`PARTITION_HORZ_A/_B`,
200+ `VERT_A/_B` — one 128x64/64x128 half plus two 64x64 quadrants). The decoder
201+ reads them (`sb128_ab`, decode.rs:35330); the writer now has the rect
202+ half it needs, so this is the cheapest remaining partition lever at the
203+ root.
204+- `open` (inherited): search-time vs write-time mv stacks still differ
205+ (lane-sb128b's second open item).