diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs
index d7f7a60c..797cb3cf 100644
--- a/crates/ec-av1/src/encode.rs
+++ b/crates/ec-av1/src/encode.rs
@@ -755,9 +755,7 @@ fn b128_root() -> bool {
/// the decoder derives, and on this HEAD the same row re-measures three-way
/// EXACT (encoder reconstruction == ffmpeg == `decode_stream`, every frame,
/// every plane, both gates). The knob stays as the arm's gate, not as a
-/// defect flag; the residual arm is also what
-/// [`crate::tile::write_inter_block_128_rect`]'s skip-only halves would
-/// share if they ever carry one.
+/// defect flag.
fn b128_residual() -> bool {
static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| {
crate::envflags::var("EC_AV1_B128RES").ok().map(|v| v != "0")
@@ -765,6 +763,49 @@ fn b128_residual() -> bool {
(ENV.unwrap_or(false) || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed))
&& b128_root()
}
+/// lane-rectres: whether the 128 root's RECTANGULAR pieces -- the two
+/// HORZ/VERT halves and the four AB shapes' three pieces (two 64x64 squares
+/// plus one half) -- price a REAL residual in the RD as well as the skip arm
+/// ([`search_root_128_rect`] / [`search_root_128_ab`], written through
+/// [`crate::tile::write_inter_block_128_rect`]). **Off by default**
+/// (`EC_AV1_RECTRES=1` turns it on): OFF is today's behavior bit for bit --
+/// no rect/AB piece can come out non-skip, so the writer's refusal is never
+/// reached. The residual shape is the whole 128 block's, halved or quartered
+/// per piece: one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
+/// mu chunk, var-tx depth 0 (exactly what the decoder's mu-chunk loop reads
+/// for any inter partition shape).
+fn rectres() -> bool {
+ static ENV: std::sync::LazyLock > = std::sync::LazyLock::new(|| {
+ crate::envflags::var("EC_AV1_RECTRES")
+ .ok()
+ .map(|v| v != "0")
+ });
+ ENV.unwrap_or(false) || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed)
+}
+
+/// Test-only: take the rect/AB pieces' residual arm whatever it costs, so a
+/// witness clip codes the shape rather than waiting for content on which the
+/// RD picks it (the same role [`FORCE_B128_RESIDUAL`] plays at the NONE
+/// root). Never read outside `#[cfg(test)]` builds.
+static FORCE_B128_RECTRES: std::sync::atomic::AtomicBool =
+ std::sync::atomic::AtomicBool::new(false);
+
+/// Arms [`FORCE_B128_RECTRES`] for the rest of the process.
+#[cfg(test)]
+pub(crate) fn force_b128_rectres(on: bool) {
+ FORCE_B128_RECTRES.store(on, std::sync::atomic::Ordering::Relaxed);
+}
+
+/// How many rect/AB pieces the search left WITH a residual rather than
+/// skipped, since the last [`take_b128_rectres_hits`] (class
+/// `gate-blind-to-feature`).
+static B128_RECTRES_HITS: std::sync::atomic::AtomicUsize =
+ std::sync::atomic::AtomicUsize::new(0);
+
+/// The rect/AB-piece-residual count since the last call, and zero it.
+pub fn take_b128_rectres_hits() -> usize {
+ B128_RECTRES_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
+}
/// lane-b128r: whether the 128 root offers the COMPOUND candidates the 64
/// root already does (`NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`,
@@ -9929,11 +9970,124 @@ fn search_root_128(
))
}
+/// lane-rectres: one rect/AB piece's REAL residual, priced against the skip
+/// arm the caller's [`search_skip_64`] just committed to the planes (which
+/// IS the winner's prediction, sample for sample -- the same rule
+/// [`search_root_128`]'s residual arm runs at the NONE root). The piece's
+/// residual is one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
+/// mu chunk (two chunks for a 128x64 / 64x128 half, one for a 64x64 square),
+/// each trial at sides the forward network already reaches, never a
+/// rectangular transform; var-tx depth 0 only -- the units ARE the tree's
+/// leaves, exactly what `decode_inter_block`'s mu-chunk loop reads.
+///
+/// The depth-0 `txfm_partition` symbols the writer codes for the units are
+/// not priced, exactly as [`search_root_128`] does not price its four (their
+/// contexts are only known at write time); at two symbols a half this is
+/// under a bit against residuals of hundreds. On a win (or under the witness
+/// force) the trials are committed to the planes, `block` is flipped to
+/// carry the packed level grids [`crate::tile::write_inter_block_128_rect`]
+/// slices back out, and the new cost is returned; otherwise `cost` passes
+/// through untouched. Counts [`take_b128_rectres_hits`] on a win.
+#[allow(clippy::too_many_arguments)]
+fn search_rect_residual(
+ luma: &mut Plane,
+ chroma: &mut [Plane; 2],
+ // The piece's own top-left, in luma samples.
+ (px, py): (usize, usize),
+ // Its true footprint: (128, 64) HORZ, (64, 128) VERT, (64, 64) square.
+ (w, h): (usize, usize),
+ cost: f64,
+ lambda: f64,
+ search: &Search<'_>,
+ // The piece's own mv stack, for the skip symbol's cost either way.
+ stack: &crate::mvstack::MvStack,
+ block: &mut BlockCoeffs,
+) -> f64 {
+ /// The 64x64 "mu" chunk side, luma; chroma halves it.
+ const MU: usize = SUPERBLOCK;
+ let chunks: [(usize, usize); 2] = match (w, h) {
+ (128, 64) => [(0, 0), (0, 1)],
+ (64, 128) => [(0, 0), (1, 0)],
+ _ => [(0, 0), (0, 0)],
+ };
+ let n = if w.max(h) > MU { 2 } else { 1 };
+ // Every unit's coded level grid is 32x32 (a 64-point transform codes
+ // only its top-left corner), packed per plane into one 64-wide grid with
+ // chunk (cr, cc) at (cr * 32, cc * 32) -- the layout the writer slices
+ // back out in the same chunk order.
+ let mut packed = [vec![0i32; 64 * 64], vec![0i32; 64 * 64], vec![0i32; 64 * 64]];
+ let mut sse_skip = 0.0f64;
+ let mut sse_res = 0.0f64;
+ let mut coeff_bits = 0.0f64;
+ let mut trials_per_chunk: Vec<[Trial; 3]> = Vec::with_capacity(n);
+ for &(cr, cc) in &chunks[..n] {
+ let (cxx, cyy) = (px + cc * MU, py + cr * MU);
+ let (cx, cy) = (cxx / 2, cyy / 2);
+ let half = MU / 2;
+ let pred_y = rows_of(&luma.reconstruction, luma.width, cxx, cyy, MU);
+ let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
+ let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
+ sse_skip += luma.block_sse(cxx, cyy, MU, &pred_y)
+ + chroma[0].block_sse(cx, cy, half, &pred_u)
+ + chroma[1].block_sse(cx, cy, half, &pred_v);
+ let trials = [
+ luma.code_from_prediction(
+ cxx, cyy, MU, &pred_y, false, search.base_q_idx, search.deadzone,
+ TxbSet::Luma64,
+ ),
+ chroma[0].code_from_prediction(
+ cx, cy, half, &pred_u, false, search.base_q_idx, search.deadzone,
+ TxbSet::Chroma32,
+ ),
+ chroma[1].code_from_prediction(
+ cx, cy, half, &pred_v, false, search.base_q_idx, search.deadzone,
+ TxbSet::Chroma32,
+ ),
+ ];
+ for (plane, trial) in trials.iter().enumerate() {
+ sse_res += trial.sse;
+ coeff_bits += trial.bits;
+ for row in 0..32 {
+ packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
+ .copy_from_slice(&trial.levels[row * 32..][..32]);
+ }
+ }
+ trials_per_chunk.push(trials);
+ }
+ // `cost` is the skip arm's own `sse + lambda * syntax`; the residual arm
+ // pays the same syntax with `skip` coded 0 instead of 1, plus its
+ // coefficients.
+ let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
+ let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
+ if res_cost < cost || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed) {
+ for (trials, &(cr, cc)) in trials_per_chunk.iter().zip(&chunks[..n]) {
+ let (cxx, cyy) = (px + cc * MU, py + cr * MU);
+ let (cx, cy) = (cxx / 2, cyy / 2);
+ let half = MU / 2;
+ luma.commit(cxx, cyy, MU, &trials[0]);
+ chroma[0].commit(cx, cy, half, &trials[1]);
+ chroma[1].commit(cx, cy, half, &trials[2]);
+ }
+ block.skip = false;
+ block.tx_depth = 0;
+ block.luma_tx_types = Vec::new();
+ block.luma = coeffs(&packed[0], 64);
+ block.u = coeffs(&packed[1], 64);
+ block.v = coeffs(&packed[2], 64);
+ B128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ res_cost
+ } else {
+ cost
+ }
+}
+
/// lane-b128hv: the `PARTITION_HORZ` / `PARTITION_VERT` candidate for a whole
/// 128 superblock root -- two 128x64 (`horz`) or 64x128 inter blocks, the
-/// shipped NONE machinery halved. Skip only, single reference or compound,
-/// exactly what `crate::tile::write_inter_block_128_rect` codes and
-/// `decode_inter_block` reads at `sb128_rect`.
+/// shipped NONE machinery halved. Skip-only by default, single reference or
+/// compound; under `EC_AV1_RECTRES` each half also prices a REAL residual
+/// ([`search_rect_residual`]) -- exactly what
+/// `crate::tile::write_inter_block_128_rect` codes and `decode_inter_block`
+/// reads at `sb128_rect`.
///
/// The FIRST half is published into `grid` before the second is searched --
/// the writer publishes it too, so a second half searched against the stale
@@ -10065,7 +10219,23 @@ fn search_root_128_rect(
fctx,
);
match found {
- Some((c, block)) => {
+ Some((mut c, mut block)) => {
+ // lane-rectres: the same prediction with a REAL residual,
+ // priced against the skip arm the search just committed to
+ // the planes -- two 64x64 mu chunks for a half.
+ if rectres() && block.skip {
+ c = search_rect_residual(
+ luma,
+ chroma,
+ (mc * 4, mr * 4),
+ (w, h),
+ c,
+ root_search.lambda,
+ &root_search,
+ &stack,
+ &mut block,
+ );
+ }
cost += c;
record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
halves.push(block);
@@ -10105,8 +10275,9 @@ fn search_root_128_rect(
/// `encoder-grid-drift-invisible-to-pixel-gate`). The grid and both planes
/// are put back before returning; the caller re-applies the winner.
///
-/// SKIP only, for the reason [`search_root_128_rect`] gives: the 128 residual
-/// arm the pieces would share is itself parked behind `EC_AV1_B128RES`.
+/// Skip-only by default; under `EC_AV1_RECTRES` each piece also prices a
+/// REAL residual ([`search_rect_residual`]) -- the 64x64 squares are where
+/// libaom's own AB shapes earn their keep.
///
/// Returns `(cost, lambda, the three pieces, reconstruction)`, the cost
/// already carrying the root's own partition symbol so it ranks against the
@@ -10221,7 +10392,25 @@ fn search_root_128_ab(
fctx,
);
match found {
- Some((c, block)) => {
+ Some((mut c, mut block)) => {
+ // lane-rectres: the same prediction with a REAL residual,
+ // priced against the skip arm the search just committed to
+ // the planes -- one mu chunk for a 64x64 square, two for a
+ // half. The 64x64 squares are where libaom's own AB shapes
+ // earn their keep.
+ if rectres() && block.skip {
+ c = search_rect_residual(
+ luma,
+ chroma,
+ (mc * 4, mr * 4),
+ (w, h),
+ c,
+ root_search.lambda,
+ &root_search,
+ &stack,
+ &mut block,
+ );
+ }
cost += c;
record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
pieces.push(block);
@@ -17286,6 +17475,227 @@ mod tests {
}
}
+ /// lane-rectres: a `PARTITION_HORZ` 128 root whose two 128x64 halves
+ /// CARRY A RESIDUAL -- the mu-chunk shape (one TX_64X64 luma unit plus a
+ /// TX_32X32 chroma pair per chunk) `write_inter_block_128_rect` now
+ /// codes under `EC_AV1_RECTRES`, at the footprint the decoder's own
+ /// mu-chunk loop reads. The arm is FORCED ([`force_b128_rectres`], the
+ /// rect partition with [`force_b128_rect`]) so every inter root of the
+ /// clip goes through it; the `coded > 0` assert is the guard that catches
+ /// the next fixture drift (the whole-128 twin of this witness went RED
+ /// twice that way).
+ ///
+ /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
+ /// encode::tests::a_rect128_half_with_a_real_residual --nocapture
+ #[test]
+ #[ignore = "sets the process-global superblock size: run it alone"]
+ fn a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders() {
+ let _knobs = crate::speed::knob_write();
+ if !have_ffmpeg() {
+ eprintln!("SKIP: no ffmpeg");
+ return;
+ }
+ force_sb128(true);
+ let dir = std::env::temp_dir().join(format!("ec-av1-rectres-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let clip = dir.join("smpte-pan-1280x768.y4m");
+ let ok = Command::new("ffmpeg")
+ .args(["-v", "error", "-y", "-f", "lavfi"])
+ .args(["-i", "smptebars=size=1600x768:rate=24"])
+ .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
+ .args(["-pix_fmt", "yuv420p"])
+ .arg(&clip)
+ .status()
+ .expect("ffmpeg failed to run")
+ .success();
+ assert!(ok, "ffmpeg could not write the synthetic clip");
+ let (width, height) = (1280usize, 768usize);
+ let pictures =
+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
+ force_b128_rect(1);
+ force_b128_rectres(true);
+ let _ = take_b128_rectres_hits();
+ let _ = crate::tile::take_sb128_rectres_hits();
+ let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
+ let (won, coded) =
+ (take_b128_rectres_hits(), crate::tile::take_sb128_rectres_hits());
+ eprintln!("rect halves WITH a residual: search won {won}, writer coded {coded}");
+ assert!(
+ coded > 0,
+ "no 128x64 half carried a residual on this clip, so it cannot witness the arm",
+ );
+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
+ let recon = &frame.reconstruction;
+ for (plane, got, want) in [
+ ("luma", &dec.y, &recon.y),
+ ("U", &dec.u, &recon.u),
+ ("V", &dec.v, &recon.v),
+ ] {
+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
+ assert_eq!(
+ differ, 0,
+ "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
+ own reconstruction",
+ got.len()
+ );
+ }
+ }
+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
+ assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
+ assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
+ assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
+ }
+ }
+
+ /// lane-rectres: an AB shape (`PARTITION_HORZ_A` forced) whose THREE
+ /// pieces carry residuals -- the 128x64 half through the two-chunk arm,
+ /// the two 64x64 squares through the one-chunk arm (the shape libaom's
+ /// own AB partitions earn their keep with). testsrc2 at 12 frames, the
+ /// shipped AB witness's own recipe: an 8-frame clip parks an ARF whose
+ /// reference picture the GOP has not produced yet, which refuses before
+ /// any AB root is coded.
+ ///
+ /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
+ /// encode::tests::an_ab128_piece_with_a_real_residual --nocapture
+ #[test]
+ #[ignore = "sets the process-global superblock size: run it alone"]
+ fn an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders() {
+ let _knobs = crate::speed::knob_write();
+ if !have_ffmpeg() {
+ eprintln!("SKIP: no ffmpeg");
+ return;
+ }
+ force_sb128(true);
+ let dir = std::env::temp_dir().join(format!("ec-av1-rectres-ab-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let clip = dir.join("testsrc2-1280x768.y4m");
+ let ok = Command::new("ffmpeg")
+ .args(["-v", "error", "-y", "-f", "lavfi"])
+ .args(["-i", "testsrc2=size=1280x768:rate=24"])
+ .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
+ .arg(&clip)
+ .status()
+ .expect("ffmpeg failed to run")
+ .success();
+ assert!(ok, "ffmpeg could not write the synthetic clip");
+ let (width, height) = (1280usize, 768usize);
+ let pictures =
+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
+ force_b128_ab(4);
+ force_b128_rectres(true);
+ let _ = take_b128_rectres_hits();
+ let _ = crate::tile::take_sb128_rectres_hits();
+ let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
+ let (won, coded) =
+ (take_b128_rectres_hits(), crate::tile::take_sb128_rectres_hits());
+ eprintln!("AB pieces WITH a residual: search won {won}, writer coded {coded}");
+ assert!(
+ coded > 0,
+ "no AB piece carried a residual on this clip, so it cannot witness the arm",
+ );
+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
+ let recon = &frame.reconstruction;
+ for (plane, got, want) in [
+ ("luma", &dec.y, &recon.y),
+ ("U", &dec.u, &recon.u),
+ ("V", &dec.v, &recon.v),
+ ] {
+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
+ assert_eq!(
+ differ, 0,
+ "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
+ own reconstruction",
+ got.len()
+ );
+ }
+ }
+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
+ assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
+ assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
+ assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
+ }
+ }
+
+ /// lane-rectres, lane-edge128's interaction on the rect shapes: a HORZ
+ /// half WITH a residual under a clip whose CDEF search codes a
+ /// per-64x64 `cdef_idx` list. The half codes ONE literal at its origin
+ /// and the decoder stamps BOTH units it spans with it, so the owner map
+ /// ([`crate::tile::cdef_unit_owner`], now extended past Whole128) has to
+ /// collapse the pair -- exactly the bug class that broke bars 2160p at
+ /// the whole-128 root. RED before this lane by construction: no rect
+ /// piece could carry a residual, so no such literal existed.
+ ///
+ /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
+ /// encode::tests::a_rect128_residual_half_under_a_per_unit_cdef --nocapture
+ #[test]
+ #[ignore = "sets the process-global superblock size: run it alone"]
+ fn a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact() {
+ let _knobs = crate::speed::knob_write();
+ if !have_ffmpeg() {
+ eprintln!("SKIP: no ffmpeg");
+ return;
+ }
+ force_sb128(true);
+ let dir = std::env::temp_dir().join(format!("ec-av1-rectres-cdef-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let clip = dir.join("testsrc2-1280x768.y4m");
+ // Detailed synthetic content: its CDEF search spends more than one
+ // strength pair, which is what puts a `cdef_idx` literal in the tile.
+ let ok = Command::new("ffmpeg")
+ .args(["-v", "error", "-y", "-f", "lavfi"])
+ .args(["-i", "testsrc2=size=1280x768:rate=24"])
+ .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
+ .arg(&clip)
+ .status()
+ .expect("ffmpeg failed to run")
+ .success();
+ assert!(ok, "ffmpeg could not write the synthetic clip");
+ let (width, height) = (1280usize, 768usize);
+ let pictures =
+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
+ force_b128_rect(1);
+ force_b128_rectres(true);
+ let _ = crate::tile::take_sb128_rectres_hits();
+ let _ = crate::filter_search::take_cdef_covered_units();
+ let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
+ let coded = crate::tile::take_sb128_rectres_hits();
+ let covered = crate::filter_search::take_cdef_covered_units();
+ eprintln!(
+ "rect halves WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
+ another unit's literal: {covered}"
+ );
+ assert!(coded > 0, "no 128x64 half carried a residual on this clip");
+ assert!(
+ covered > 0,
+ "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
+ cannot witness the rule",
+ );
+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
+ for (plane, got, want) in [
+ ("luma", &dec.y, &frame.reconstruction.y),
+ ("U", &dec.u, &frame.reconstruction.u),
+ ("V", &dec.v, &frame.reconstruction.v),
+ ] {
+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
+ assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
+ }
+ }
+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
+ assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
+ assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
+ assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
+ }
+ }
+
/// lane-b128r: the COMPOUND arm at the 128 root -- one 128x128 block
/// naming `LAST` plus `GOLDEN`/`ALTREF`, through the same
/// `write_compound_block` chain every smaller compound block takes, at a
@@ -20283,11 +20693,14 @@ mod tests {
);
eprintln!(
"{name}: 128x128 roots {} (search) / {} (writer), with a residual \
+ {} (search) / {} (writer); rect/AB pieces with a residual \
{} (search) / {} (writer)",
take_b128_none_hits(),
crate::tile::take_sb128_none_hits(),
take_b128_residual_hits(),
crate::tile::take_sb128_residual_hits(),
+ take_b128_rectres_hits(),
+ crate::tile::take_sb128_rectres_hits(),
);
eprintln!(
"{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})",
diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs
index 8e41d1a8..a6d13640 100644
--- a/crates/ec-av1/src/tile.rs
+++ b/crates/ec-av1/src/tile.rs
@@ -473,13 +473,18 @@ fn write_inter_block_128(
/// block's true footprint governs only its mv-stack window, its mi/grid stamp
/// and its neighbour bands (decode.rs' own `write_w`/`write_h` split).
///
-/// SKIP only: the decoder reads a rect half's residual through the mu-chunk
-/// loop, but the 128 NONE residual arm it would share is itself parked
-/// (`EC_AV1_B128RES`), so offering one here would buy the same open filter
-/// mismatch for a candidate the RD takes 0-2 times a frame.
+/// lane-ab128: also the two 64x64 squares an AB shape codes (the `w == h`
+/// arm below) and its 128x64 / 64x128 half.
+///
+/// lane-rectres: a piece may CARRY A RESIDUAL -- the search only ever hands
+/// one over under `EC_AV1_RECTRES` ([`crate::encode::rectres`]), and then it
+/// is coded here exactly as `decode_inter_block` reads it: one TX_64X64 luma
+/// unit plus a TX_32X32 chroma pair per 64x64 mu chunk (two chunks for a
+/// half, one for a square), each depth-0 in the var-tx tree (a half codes
+/// two `txfm_partition` flags under `TxMode::Select`, a square one).
///
/// # Errors
-/// A block that is intra or that is not skipped.
+/// A block that is intra.
#[allow(clippy::too_many_arguments)]
fn write_inter_block_128_rect(
enc: &mut SymbolEncoder,
@@ -498,12 +503,6 @@ fn write_inter_block_128_rect(
let info = block.inter.ok_or_else(|| {
Error::unsupported("AV1 tile", "a 128-root rectangular half is coded inter")
})?;
- if !block.skip {
- return Err(Error::unsupported(
- "AV1 tile",
- "a 128-root rectangular half carries a residual",
- ));
- }
let (mi_r, mi_c) = at_mi;
let (w_mi, h_mi) = (w / MI, h / MI);
let has_above = neighbours.has_above(mi_r);
@@ -598,10 +597,46 @@ fn write_inter_block_128_rect(
block.motion_mode,
)?;
}
+ // The 64x64 mu chunks the residual is coded in, raster order -- the
+ // decoder's own walk: two for a half, one for a square piece.
+ let chunks: &[(usize, usize)] = match (w, h) {
+ (128, 64) => &[(0, 0), (0, 1)],
+ (64, 128) => &[(0, 0), (1, 0)],
+ _ => &[(0, 0)],
+ };
+ // A half's uv plane block (64x32 / 32x64) is wider or taller than its
+ // 32x32 unit, so the unit's `txb_skip_ctx` takes `get_txb_ctx`'s
+ // offset-10 rows (+3 here); a 64x64 piece's uv block IS the unit and
+ // takes none. The half is also the only shape whose chroma is re-stamped
+ // per mu chunk at the end (decode.rs' `mu_chroma`).
+ let is_half = w.max(h) > 64;
if tx_select {
- // `read_block_tx_size_rect`'s skip arm: `txfm_partition_update_rect`
- // with the BLOCK's own size in both bands, no symbol.
- neighbours.record_txfm_rect((mi_r, mi_c), (w, h), (w, h));
+ if block.skip {
+ // `read_block_tx_size_rect`'s skip arm: `txfm_partition_update_rect`
+ // with the BLOCK's own size in both bands, no symbol.
+ neighbours.record_txfm_rect((mi_r, mi_c), (w, h), (w, h));
+ } else if is_half {
+ // The var-tx tree of a 128x64 / 64x128 block enters at TX_64X64
+ // once per mu chunk (`read_block_tx_size_rect`'s `max_tx = 64`
+ // loop), so it is two depth-0 `txfm_split` flags of zero, each
+ // read against the bands the chunks before it published.
+ for &(cr, cc) in chunks {
+ let unit = (mi_r + cr * 16, mi_c + cc * 16);
+ let ctx = txfm_partition_ctx_rect(
+ neighbours.above_txfm[unit.1],
+ neighbours.left_txfm[unit.0],
+ w.max(h),
+ 64,
+ 64,
+ );
+ enc.symbol(0, &mut cdfs.txfm_partition[ctx]);
+ neighbours.record_txfm(unit, 64, 64, 64);
+ }
+ } else {
+ // A 64x64 piece is one whole TX_64X64: the single depth-0 flag
+ // the 64 root's own writer codes (`write_tx_syntax_inter`).
+ write_tx_syntax_inter(enc, cdfs, neighbours, (mi_r, mi_c), SB, true, false, 0);
+ }
}
let zero_grids = [
vec![0i32; TX32 * TX32],
@@ -612,7 +647,94 @@ fn write_inter_block_128_rect(
// side bands are named by the same SUB-grid origin every square block
// uses.
let at_sub = (mi_r / (SUB / MI), mi_c / (SUB / MI));
- neighbours.record_planes_rect(at_sub, (w, h), 0, &zero_grids, true);
+ if !block.skip {
+ // lane-rectres: the packed 64-wide level grids the search hands over,
+ // one plane each (the same layout `write_inter_block_128` slices for
+ // the whole block, here with the piece's own chunk list).
+ let packed = [
+ level_grid(&block.luma, 64)?,
+ level_grid(&block.u, 64)?,
+ level_grid(&block.v, 64)?,
+ ];
+ let scan32 = default_scan(TX32);
+ let unit_of = |plane: usize, cr: usize, cc: usize| -> Vec {
+ (0..32)
+ .flat_map(|row| {
+ packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32].to_vec()
+ })
+ .collect()
+ };
+ let mut chroma_units: Vec<((usize, usize), [Vec; 2])> = Vec::new();
+ for &(cr, cc) in chunks {
+ let unit_mi = (mi_r + cr * 16, mi_c + cc * 16);
+ // The luma unit, and the context its all-zero flag reads: a
+ // HALF's unit is smaller than its block (neighbour magnitude
+ // table), a square's IS the whole plane block (fixed zero --
+ // `read_inter_plane`'s `luma_skip_ctx.unwrap_or(0)`, the 64
+ // root's own writer rule). It publishes its context before the
+ // next chunk reads it.
+ let luma = unit_of(0, cr, cc);
+ let skip_ctx = if is_half {
+ neighbours.luma_skip_ctx(unit_mi, 64 / MI)
+ } else {
+ 0
+ };
+ let around = neighbours.around_mi(unit_mi, 64);
+ write_coeffs(
+ enc,
+ &mut cdfs.txb(TxbSet::Luma64, 0),
+ &luma,
+ &scan32,
+ skip_ctx,
+ dc_sign_ctx(around[0].dc_vote),
+ Some(0),
+ TxType::DctDct,
+ );
+ neighbours.record_mi_luma(unit_mi, 64, &luma);
+ // Then this chunk's chroma pair, before the next chunk's luma:
+ // libaom codes every plane of a mu chunk before moving on.
+ let mut pair = [Vec::new(), Vec::new()];
+ for plane in 1..3usize {
+ let grid = unit_of(plane, cr, cc);
+ let around = neighbours.around_mi(unit_mi, 64)[plane];
+ write_coeffs(
+ enc,
+ &mut cdfs.txb(TxbSet::Chroma32, 0),
+ &grid,
+ &scan32,
+ usize::from(around.above_coded) + usize::from(around.left_coded)
+ + 3 * usize::from(is_half),
+ dc_sign_ctx(around.dc_vote),
+ Some(plane),
+ TxType::DctDct,
+ );
+ neighbours.record_mi_chroma(unit_mi, 64, plane, &grid);
+ pair[plane - 1] = grid;
+ }
+ chroma_units.push((unit_mi, pair));
+ }
+ // decode.rs' own tail (`record_split_luma_rect_mi` then, on a half,
+ // the per-chunk chroma re-stamp): the block-level write off the
+ // whole assembled chroma plane grid, luma kept because each unit
+ // already published its own, and then the per-unit chroma writes
+ // replayed over it -- last writer wins, so the next block reads the
+ // units.
+ let block_grids = [
+ vec![0i32; TX32 * TX32],
+ packed[1].clone(),
+ packed[2].clone(),
+ ];
+ neighbours.record_planes_rect(at_sub, (w, h), 0, &block_grids, false);
+ if is_half {
+ for (unit_mi, pair) in &chroma_units {
+ neighbours.record_mi_chroma(*unit_mi, 64, 1, &pair[0]);
+ neighbours.record_mi_chroma(*unit_mi, 64, 2, &pair[1]);
+ }
+ }
+ SB128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ } else {
+ neighbours.record_planes_rect(at_sub, (w, h), 0, &zero_grids, true);
+ }
neighbours.record_inter_rect_mi((mi_r, mi_c), (w, h), block.skip, true, block_ref(block));
if let Some(r1) = info.ref1 {
neighbours.record_compound_rect_mi((mi_r, mi_c), (w, h), r1, 0, 1);
@@ -666,6 +788,17 @@ static SB128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize =
pub fn take_sb128_residual_hits() -> usize {
SB128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
}
+/// lane-rectres: how many RECT/AB pieces (the halves and 64x64 squares
+/// [`write_inter_block_128_rect`] codes) carried a REAL residual rather than
+/// being skipped, since the last [`take_sb128_rectres_hits`] -- the writer
+/// side of [`crate::encode::take_b128_rectres_hits`]'s search count.
+static SB128_RECTRES_HITS: std::sync::atomic::AtomicUsize =
+ std::sync::atomic::AtomicUsize::new(0);
+
+/// The rect/AB-piece-with-residual count since the last call, and zero it.
+pub fn take_sb128_rectres_hits() -> usize {
+ SB128_RECTRES_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
+}
/// lane-b128r: how many of those blocks named a SECOND reference (the
/// compound arm at the 128 root), since the last
@@ -874,25 +1007,80 @@ impl TileLayout {
/// That is the shape this map exists to collapse
/// ([`crate::filter_search::pick_filters`]).
///
-/// Identity everywhere else: every block this writer codes at 64x64 or below
-/// covers exactly one unit.
+/// lane-rectres: the same holds for a Rect128 half or an Ab128 half that
+/// carries a residual (`EC_AV1_RECTRES`) -- it codes one literal at its own
+/// origin and the decoder stamps BOTH units it spans with it, so its pair is
+/// collapsed onto the origin unit too. Its 64x64 squares cover exactly one
+/// unit each, and a SKIP-ONLY rect/AB piece codes no literal at all (the
+/// decoder's per-piece `cdef_transmitted` reset never fires), so neither
+/// touches this map -- only pieces the writer really codes a residual for.
pub(crate) fn cdef_unit_owner(blocks: &[Quadrant], mi_cols: u32, mi_rows: u32) -> Vec {
let (cols, rows) = block_grid(mi_cols, mi_rows);
let (sb_cols, sb_rows) = (cols.div_ceil(2) as usize, rows.div_ceil(2) as usize);
let mut owner: Vec = (0..(sb_cols * sb_rows) as u32).collect();
+ // Collapses every 64x64 unit `(ur, uc) ..` a residual piece at unit
+ // `(ur, uc)` with footprint `(w, h)` spans onto the piece's origin --
+ // [`crate::encode::write_inter_block_128_rect`]'s one `write_cdef_idx`
+ // is what the decoder copies over all of them.
+ let collapse = |owner: &mut Vec, (ur, uc): (usize, usize), (w, h): (usize, usize)| {
+ let origin = (ur * sb_cols + uc) as u32;
+ for r in ur..(ur + (h / 64).max(1)).min(sb_rows) {
+ for c in uc..(uc + (w / 64).max(1)).min(sb_cols) {
+ owner[r * sb_cols + c] = origin;
+ }
+ }
+ };
for sb_r in (0..sb_rows).step_by(2) {
for sb_c in (0..sb_cols).step_by(2) {
- let root = ((sb_r * 2) < rows as usize && (sb_c * 2) < cols as usize)
+ let Some(root) = ((sb_r * 2) < rows as usize && (sb_c * 2) < cols as usize)
.then(|| &blocks[(sb_r * 2) * cols as usize + sb_c * 2])
- .is_some_and(|q| matches!(q, Quadrant::Whole128(_)));
- if !root {
+ else {
continue;
- }
- let origin = (sb_r * sb_cols + sb_c) as u32;
- for r in sb_r..(sb_r + 2).min(sb_rows) {
- for c in sb_c..(sb_c + 2).min(sb_cols) {
- owner[r * sb_cols + c] = origin;
+ };
+ match root {
+ Quadrant::Whole128(_) => {
+ let origin = (sb_r * sb_cols + sb_c) as u32;
+ for r in sb_r..(sb_r + 2).min(sb_rows) {
+ for c in sb_c..(sb_c + 2).min(sb_cols) {
+ owner[r * sb_cols + c] = origin;
+ }
+ }
+ }
+ // lane-rectres: the two halves of a HORZ/VERT root sit in
+ // different unit rows (HORZ) / columns (VERT); each
+ // non-skip half collapses its own pair.
+ Quadrant::Rect128(horz, halves) => {
+ for (i, half) in halves.iter().enumerate() {
+ if half.skip {
+ continue;
+ }
+ let (ur, uc) = if *horz {
+ (sb_r + i, sb_c)
+ } else {
+ (sb_r, sb_c + i)
+ };
+ let (w, h) = if *horz { (128, 64) } else { (64, 128) };
+ collapse(&mut owner, (ur, uc), (w, h));
+ }
+ }
+ // lane-rectres: the AB half is the only multi-unit piece
+ // (its two squares are one unit each); only a non-skip one
+ // codes a literal, so only it fires.
+ Quadrant::Ab128(symbol, pieces) => {
+ for (piece, ((mi_r, mi_c), (w, h))) in
+ pieces.iter().zip(crate::encode::ab128_pieces(
+ usize::from(*symbol),
+ (0, 0),
+ ))
+ {
+ if piece.skip {
+ continue;
+ }
+ let (ur, uc) = (sb_r + mi_r / 16, sb_c + mi_c / 16);
+ collapse(&mut owner, (ur, uc), (w, h));
+ }
}
+ _ => {}
}
}
}
@@ -2605,8 +2793,9 @@ pub enum Quadrant {
/// Carried by the top-left 32x32 entry of the root's sixteen, exactly as
/// [`Whole128`](Quadrant::Whole128) is.
///
- /// SKIP only ([`crate::tile::write_inter_block_128_rect`] refuses a
- /// residual), single reference or compound.
+ /// Skip-only by default; a piece carries a real residual under
+ /// `EC_AV1_RECTRES` (`crate::encode::rectres`), single reference or
+ /// compound either way.
Rect128(bool, Vec),
/// lane-ab128: the THREE inter blocks an AB shape at a 128 superblock
/// root carries -- two 64x64 pieces and one 128x64 / 64x128 half -- in
@@ -2616,8 +2805,8 @@ pub enum Quadrant {
/// top-left 32x32 entry of the root's sixteen, exactly as
/// [`Rect128`](Quadrant::Rect128) is.
///
- /// SKIP only, same writer ([`crate::tile::write_inter_block_128_rect`])
- /// and same reason.
+ /// Skip-only by default, same writer; under `EC_AV1_RECTRES` any of the
+ /// three pieces may carry a real residual.
Ab128(u8, Vec),
/// A quadrant a [`Whole64`](Quadrant::Whole64) at its superblock's
/// top-left already coded; it carries no block of its own.
diff --git a/lanes/rectres.charter.md b/lanes/rectres.charter.md
new file mode 100644
index 00000000..dff1bc5e
--- /dev/null
+++ b/lanes/rectres.charter.md
@@ -0,0 +1,92 @@
+# lane-rectres — non-skip residual on Rect128/Ab128 pieces
+
+GOAL: the Whole128 residual arm (`EC_AV1_B128RES`) is exact but INERT
+(0.4-1.9 writer fires/frame, re-measured lane-b128res on 3b4673fe) —
+whole 128 roots almost never win RD. The 128 root's rectangular pieces
+DO win: lane-b128hv ships HORZ/VERT skip halves and lane-ab128 ships the
+four AB shapes (`EC_AV1_B128AB=1` default ON). But those pieces are
+skip-only: `write_inter_block_128_rect` refuses a rect half carrying a
+residual, and `crate::tile::cdef_unit_owner` (tile.rs) is Whole128-only.
+This lane turns Rect128 and Ab128 pieces into residual carriers and
+measures whether RD taking them moves BD.
+
+Work ONLY in this worktree (`lane-rectres`,
+`/home/user/Documents/Code/Rust/edith_codecs-rectres`). Absolute paths
+only. Never touch main's checkout, never push, never `git checkout
+`, never repo-wide `cargo fmt`. `export
+CARGO_TARGET_DIR=$HOME/.cache/cargo-target-rectres` on every cargo
+command. Logs under `~/.cache/rectres/`. TMPDIR only on gate command
+lines, not on the sccache server. Gates: `systemd-run --user -p
+MemoryMax=14G`, `--ignored --exact` on both BD tests (they are
+`#[ignore]`; without `--ignored` they measure nothing). One gate at a
+time; record LOADAVG before AND after. Pins 8291 / 33227. Keep rule: one
+film row ≥0.5 BD down on a column, the other flat within ±0.3, screen
+not worse by 0.3, wall ≤+15%. Sign: BD-rate, lower better.
+
+## 1. Write residual on rect/AB pieces
+
+- Lift the refusal in `write_inter_block_128_rect`: a Rect128 half
+ (HORZ/VERT) or an Ab128 shape piece with a real residual codes its
+ coefficients like any inter block of that w×h. The decoder side is
+ spec — `decode_stream` and ffmpeg both already read residual on any
+ inter partition shape; the burden is on the ENCODER writer and the
+ encoder reconstruction path being identical.
+- Knob in the `EC_AV1_*` convention (e.g. `EC_AV1_RECTRES`), default
+ OFF, gated next to `b128_residual` in encode.rs. OFF = today's
+ behavior bit-exact.
+- INVARIANT (lane-edge128's bug class): a 128-wide piece that writes a
+ residual also codes `cdef_idx` per the syntax it carries, while
+ `read_cdef` copies ONE literal over every 64x64 unit the piece spans.
+ Extend `cdef_unit_owner` past Whole128 to the rect/AB shapes so the
+ CDEF search prices the ONE index the syntax carries, not one per unit.
+ Skip-only pieces still write no `cdef_idx` — owner map must not fire
+ for them.
+- RD side: let the rect/AB search arm price non-skip outcomes (residual
+ cost) instead of skip-only, under the knob.
+
+## 2. Witnesses FIRST (before any BD gate)
+
+Add witnesses in the standing pattern (see
+`a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders`
+and `a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact`,
+both `--ignored`, fixture q=60 after lane-b128res re-vitalization):
+
+- a Rect128 half with a real residual decodes sample-exact through
+ ffmpeg AND `decode_stream`, with a `coded > 0` assert as the guard.
+- same for at least one Ab128 shape.
+- a rect/AB residual piece spanning multiple CDEF units takes the owner
+ unit's literal, byte-exact through both decoders (the edge128
+ interaction, now on rect shapes).
+
+If any witness shows an encoder-reconstruction mismatch: STOP, do not
+ship, report class + path:line, default stays OFF.
+
+## 3. Measure
+
+Control = default (knob off) on this HEAD. Arm = knob on.
+
+- `cargo test -p ec-av1 --release --lib -- --ignored --exact --nocapture
+ encode::tests::bd_rate_film_long_gop` (deciding). Both films.
+- 12-frame guard: `encode::tests::bd_rate_screen_native`, all five rows,
+ control and arm.
+- Fire census: extend the standing native-arm census line so rect/AB
+ residual fires (search won / writer coded) print next to the 128-root
+ census, and report fires/frame per clip like lane-b128res §4. If the
+ writer still codes ~0 rect/AB residuals, the arm is inert — say so.
+
+Keep rule met → default ON, drop the refusal comment. Inert + exact →
+leave OFF, document fires. Mismatch → OFF, report (see §2).
+
+## 4. Pins / suite (only if you change the default)
+
+Pins at default and `EC_AV1_SPEED=6`. Workspace check `timeout 900 cargo
+check --workspace --all-targets -j4` (0 ec-av1 warnings). Do NOT run the
+full lib suite unless you change the default; if you do, three lanes:
+`--skip stream::` / `stream:: --skip 10bit` / `10bit`.
+
+## DONE
+
+Commit on `lane-rectres` + `lanes/rectres.report.md` with EVIDENCE lines
+(`EVIDENCE: | | `), fire counts, BD
+tables, witness results, disposition `ships-on | stays-off | stopped`.
+Never merge or push.
diff --git a/lanes/rectres.report.md b/lanes/rectres.report.md
new file mode 100644
index 00000000..52217b94
--- /dev/null
+++ b/lanes/rectres.report.md
@@ -0,0 +1,185 @@
+# lane-rectres — non-skip residual on Rect128/Ab128 pieces
+
+Base: `3b4673fe` (lane-rectres worktree). Disposition: **stays-off**
+(ACTIVE but BD-neutral + exact — under the knob the RD does take
+non-skip rect/AB pieces on every gate clip (up to 4.5 writer
+fires/frame on film A long-GOP), and the BD table moves at most 0.1
+anywhere). `EC_AV1_RECTRES` keeps its default (off): OFF is today's
+behavior bit for bit — the search never flips a rect/AB piece to
+non-skip, so the writer's lifted refusal is never reached. Pins
+untouched at 8291 / 33227 (no default change, so no pin run, no lib
+suite). Never merged, never pushed.
+
+## 1. What shipped (commit `26a9b79e`)
+
+- `write_inter_block_128_rect` (tile.rs): the skip-only refusal is lifted.
+ A residual piece codes one TX_64X64 luma unit plus a TX_32X32 chroma pair
+ per 64x64 mu chunk (two chunks for a 128x64/64x128 half, one for a 64x64
+ square), var-tx depth 0; under `TxMode::Select` a half codes two depth-0
+ `txfm_partition` flags (ctx rect at `w.max(h)=128`), a square one (via
+ `write_tx_syntax_inter`). A half's chroma unit takes the +3
+ `get_txb_ctx` offset; a square's takes none. Luma `txb_skip_ctx`: the
+ neighbour magnitude table on a half, fixed 0 on a square (the transform
+ IS the whole plane block — `read_inter_plane`'s
+ `luma_skip_ctx.unwrap_or(0)`, the 64 root's own writer rule). Tail =
+ `record_planes_rect(luma=false)` off the assembled chroma grids, then the
+ per-chunk chroma re-stamp on halves only (`mu_chroma` mirror).
+- `search_rect_residual` (encode.rs): prices the non-skip outcome against
+ the skip arm the search just committed (per-chunk
+ `code_from_prediction` trials, `unskip` skip-symbol delta, packed 64-wide
+ level grids), commits + flips `block` on a win; wired into
+ `search_root_128_rect` and `search_root_128_ab` behind
+ `rectres()` (`EC_AV1_RECTRES`, default OFF, test force
+ `force_b128_rectres`).
+- `cdef_unit_owner` (tile.rs) extends past Whole128: a non-skip Rect128
+ half collapses its 2 units onto its origin; an Ab128 half likewise (its
+ 64x64 squares are 1 unit each). Skip-only pieces never touch the map —
+ they code no literal and the decoder's per-piece `cdef_transmitted`
+ reset never fires. This is the lane-edge128 bug class, priced for the
+ ONE index the syntax carries.
+- Census: the native arm's standing line now prints "rect/AB pieces with a
+ residual N (search) / M (writer)" and zeroes both counters per clip.
+- A defect found and fixed during witnessing (would have been the lane's
+ own bug class): the first draft priced the 64x64 square's luma
+ all-zero flag off the neighbour table; the decoder fixes it at 0 for a
+ whole-block transform, and the desync surfaced as an empty-slot
+ reference refusal mid-stream (encode.rs witness fixture), not a pixel
+ miss. Fixed before any gate measured anything.
+
+## 2. Witnesses (all `--ignored --exact`, standalone, all PASS)
+
+- `a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders`
+ (smpte pan 1280x768, 8 frames, q=60, HORZ forced + residual forced):
+ search won 840, writer coded 840; `coded > 0` guard; whole stream
+ sample-exact through `decode_stream` AND ffmpeg, all planes/frames.
+ EVIDENCE: ~/.cache/rectres/wit1.log | forced HORZ + rectres, q=60, 8
+ frames | "search won 840, writer coded 840", ok, both decoders exact.
+ LOADAVG 118.48/98.99/57.92 before, 118.48/98.99/57.92 after (sibling
+ lane storm; 3.6s run).
+- `an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders`
+ (testsrc2 1280x768, 12 frames, q=60, HORZ_A forced + residual forced):
+ search won 4620, writer coded 5760 (writer counts include the filter
+ search's winning re-code); exercises the two-chunk half AND both
+ one-chunk squares; byte-exact through both decoders.
+ EVIDENCE: ~/.cache/rectres/wit2.log | forced HORZ_A + rectres, q=60, 12
+ frames | "search won 4620, writer coded 5760", ok. LOADAVG
+ 107.04/97.41/58.06 before, 104.55/100.35/63.37 after.
+- `a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact`
+ (testsrc2, 12 frames, q=90, HORZ forced + residual forced): writer coded
+ 2760 non-skip halves; 62 64x64 CDEF units took another unit's literal
+ (owner-map collapse firing on rect pieces); byte-exact through both
+ decoders. EVIDENCE: ~/.cache/rectres/wit3.log | --ignored --exact run |
+ "writer coded 2760; 64x64 CDEF units taking another unit's literal: 62",
+ ok. LOADAVG 7.90/7.85/9.32 before, 9.39/8.16/9.37 after.
+
+## 3. BD measurement (server-2, per Main's recipe)
+
+The worktree has no `fixtures/`, so all four gates ran on server-2
+(user@host-a, 4 vCPU, MemoryMax=5G units, ffmpeg PATH shim). The
+sanity gate PASSED before drawing any conclusion: the control run
+reproduces the standing table (b128res.report §2/§3) to the digit —
+long-GOP film A +20.9/-9.0 and film B +70.4/-2.2, and all five native
+rows identical (±0.0 per cell, requirement was ±0.2).
+
+### 3a. Long-GOP BD (deciding; 48 pictures, gop=48, both films)
+
+Control = default (off), arm = `EC_AV1_RECTRES=1`, same HEAD. BD-rate,
+lower better:
+
+| row | off vs libaom | off vs rav1e | on vs libaom | on vs rav1e |
+|---|---|---|---|---|
+| film A (1080p) 1920x768 | +20.9% | -9.0% | +20.9% | -9.0% |
+| film B (2160p HDR) 1920x1024 | +70.4% | -2.2% | +70.5% | -2.1% |
+
+Wall ours: film A 1394.1s -> 1417.6s (+1.7%), film B 1076.6s -> 1118.3s
+(+3.9%).
+
+EVIDENCE: ~/.cache/rectres/longgop-control.log | server-2 gate, MemoryMax=5G,
+ffmpeg shim PATH | film A +20.9%/-9.0%, film B +70.4%/-2.2%; three-way
+exactness assertion held at every clip x q x frame. LOADAVG 0.15/0.17/0.18
+before, 1.08/1.09/1.09 after.
+EVIDENCE: ~/.cache/rectres/longgop-arm.log | server-2 gate, EC_AV1_RECTRES=1,
+MemoryMax=5G | film A +20.9%/-9.0%, film B +70.5%/-2.1%. LOADAVG
+0.14/0.23/0.58 before, 1.05/1.08/1.08 after.
+
+### 3b. 12-frame native guard (all five rows)
+
+| row | off vs libaom | off vs rav1e | on vs libaom | on vs rav1e | wall ours off->on |
+|---|---|---|---|---|---|
+| bars 1080p | -3.3% | -19.0% | -3.4% | -19.0% | 424.8s -> 435.7s |
+| bars 2160p | +8.4% | -13.9% | +8.5% | -13.9% | 365.0s -> 372.8s |
+| film A | +17.9% | -6.3% | +17.8% | -6.4% | 369.4s -> 376.9s |
+| film B | +22.6% | -3.8% | +22.5% | -3.9% | 311.9s -> 318.4s |
+| screen capture | +14.4% | -33.2% | +14.4% | -33.2% | 246.4s -> 249.2s |
+
+EVIDENCE: ~/.cache/rectres/native-control.log | server-2 gate, five rows,
+MemoryMax=5G | table above, "off" columns; matches the standing table to
+the digit. LOADAVG 0.09/0.20/0.56 before, 1.14/1.15/1.09 after.
+EVIDENCE: ~/.cache/rectres/native-arm.log | server-2 gate, five rows,
+EC_AV1_RECTRES=1 | table above, "on" columns. LOADAVG 0.08/0.42/0.77
+before, 1.07/1.10/1.09 after.
+
+| clip | rect/AB residual fires (search / writer) | writer per frame |
+|---|---|---|
+| film A long-GOP (192 frames) | 34794 / 873 | 4.5 |
+| film B long-GOP (192 frames) | 20098 / 186 | 1.0 |
+| bars 1080p (48 frames) | 4915 / 105 | 2.2 |
+| bars 2160p (48 frames) | 3144 / 25 | 0.5 |
+| film A 12f (48 frames) | 7719 / 197 | 4.1 |
+| film B 12f (48 frames) | 6067 / 75 | 1.6 |
+| screen capture (48 frames) | 1056 / 85 | 1.8 |
+
+The arm FIRES for real — an order of magnitude above the parked
+whole-128 residual arm (0.4-1.9 writer fires/frame) — and the BD table
+still moves at most 0.1 in either direction on every row of both gates.
+The RD finds non-skip rect/AB pieces worth taking; taking them buys
+nothing measured. The wall deltas (+1-4%) are the extra trial cost.
+
+These numbers are the POST-FIX census (commit `8cf40077`): the first
+arm runs printed structurally-guaranteed zeros because two drain
+statements zeroed the counters immediately before the census line read
+them (class `drain-then-read counter` — reviewer catch). Both arm gates
+were re-run with the fix; the BD tables were byte-identical to the
+pre-fix arm runs (the fix touches only the census print). The drains
+inside the witness tests are pre-run hygiene and stay.
+EVIDENCE: ~/.cache/rectres/longgop-arm2.log | server-2, EC_AV1_RECTRES=1,
+post-8cf40077 | film A 34794/873, film B 20098/186; BD +20.9/-9.0,
++70.5/-2.1 (== pre-fix arm). exit=0, 3121.8s.
+EVIDENCE: ~/.cache/rectres/native-arm2.log | server-2, EC_AV1_RECTRES=1,
+post-8cf40077 | five rows: 4915/105, 3144/25, 7719/197, 6067/75,
+1056/85; BD rows == pre-fix arm to the digit. exit=0, 2121.8s.
+LOADAVG 0.18/0.17/0.44 before, 1.16/1.18/1.07 after.
+
+## 4. Keep rule — NOT met; disposition
+
+One film row >=0.5 BD down on a column: best delta anywhere is -0.1.
+Other film row flat within +/-0.3: yes. Screen not worse by 0.3: yes.
+Wall <= +15%: yes. The deciding column fails — with the arm now known
+to fire for real, 'BD-neutral on real fires' is the measured verdict,
+not inertness — the charter's stays-off branch. Default stays OFF; no
+pins, no suite (default did not flip). `fix-now | deferred()
+| accepted`: nothing deferred — the measurement asked by the charter is
+complete; the arm itself stays parked behind `EC_AV1_RECTRES`, witnessed
+exact, and the census says the pieces ARE taken — a future cost-model
+change re-measures BD, not fire counts.
+
+## 5. Procedure notes (server-2 gates)
+
+Three setup snags hit and solved, for the next lane running gates there:
+`systemd-run --user` units start in $HOME, not the caller's cwd — put the
+`cd` inside the unit (`--pipe bash -lc 'cd ... && cargo ...'`); the
+rsync'd worktree's `.git` FILE (a worktree pointer, not covered by
+`--exclude /.git/`) must be `rm -f .git && git init -q .` on the server or
+the repo's memguard test-runner (`git rev-parse --show-toplevel`) refuses
+every test binary; and a failed unit needs
+`systemctl --user reset-failed ` before the name is reusable.
+`pkill -f` with the unit name in the pattern kills your own ssh session.
+
+## 6. Non-goals respected
+
+Main checkout untouched, never pushed/merged, no repo-wide formatters (a
+scoped rustfmt reflow of the two edited files was fully reverted by
+restoring HEAD bytes and replaying the semantic edits — the committed diff
+is semantic-only, 643+/39-), media files read-only, one gate at a time
+(both locally and on server-2), logs under ~/.cache/rectres/ and
+/home/user/gates/logs/.