forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-rectres' (16a625c7): Rect128/Ab128 pieces can carry a real residual behind EC_AV1_RECTRES (writer + search arms + cdef_unit_owner extended past Whole128 + 3 three-way-exact witnesses); the post-fix census shows the arm ACTIVE but BD-neutral (film A long-GOP 34794/873 fires, every gate row within 0.1) so the default stays OFF; the 64x64-square luma txb_skip_ctx=0 writer fix and the census double-take fix ride along; pins unmoved at 8291 / 33227

Browse files at this commit

3a3d4123b15f28343a2ea9d98ea617506c4866c9Ahmet Kaan GümüşParent: f56f3971c33b9f
crates/ec-av1/src/encode.rsmodified+423 -10
@@ -755,9 +755,7 @@ fn b128_root() -> bool {
755755 /// the decoder derives, and on this HEAD the same row re-measures three-way
756756 /// EXACT (encoder reconstruction == ffmpeg == `decode_stream`, every frame,
757757 /// every plane, both gates). The knob stays as the arm's gate, not as a
758-/// defect flag; the residual arm is also what
759-/// [`crate::tile::write_inter_block_128_rect`]'s skip-only halves would
760-/// share if they ever carry one.
758+/// defect flag.
761759 fn b128_residual() -> bool {
762760 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
763761 crate::envflags::var("EC_AV1_B128RES").ok().map(|v| v != "0")
@@ -765,6 +763,49 @@ fn b128_residual() -> bool {
765763 (ENV.unwrap_or(false) || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed))
766764 && b128_root()
767765 }
766+/// lane-rectres: whether the 128 root's RECTANGULAR pieces -- the two
767+/// HORZ/VERT halves and the four AB shapes' three pieces (two 64x64 squares
768+/// plus one half) -- price a REAL residual in the RD as well as the skip arm
769+/// ([`search_root_128_rect`] / [`search_root_128_ab`], written through
770+/// [`crate::tile::write_inter_block_128_rect`]). **Off by default**
771+/// (`EC_AV1_RECTRES=1` turns it on): OFF is today's behavior bit for bit --
772+/// no rect/AB piece can come out non-skip, so the writer's refusal is never
773+/// reached. The residual shape is the whole 128 block's, halved or quartered
774+/// per piece: one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
775+/// mu chunk, var-tx depth 0 (exactly what the decoder's mu-chunk loop reads
776+/// for any inter partition shape).
777+fn rectres() -> bool {
778+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
779+ crate::envflags::var("EC_AV1_RECTRES")
780+ .ok()
781+ .map(|v| v != "0")
782+ });
783+ ENV.unwrap_or(false) || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed)
784+}
785+
786+/// Test-only: take the rect/AB pieces' residual arm whatever it costs, so a
787+/// witness clip codes the shape rather than waiting for content on which the
788+/// RD picks it (the same role [`FORCE_B128_RESIDUAL`] plays at the NONE
789+/// root). Never read outside `#[cfg(test)]` builds.
790+static FORCE_B128_RECTRES: std::sync::atomic::AtomicBool =
791+ std::sync::atomic::AtomicBool::new(false);
792+
793+/// Arms [`FORCE_B128_RECTRES`] for the rest of the process.
794+#[cfg(test)]
795+pub(crate) fn force_b128_rectres(on: bool) {
796+ FORCE_B128_RECTRES.store(on, std::sync::atomic::Ordering::Relaxed);
797+}
798+
799+/// How many rect/AB pieces the search left WITH a residual rather than
800+/// skipped, since the last [`take_b128_rectres_hits`] (class
801+/// `gate-blind-to-feature`).
802+static B128_RECTRES_HITS: std::sync::atomic::AtomicUsize =
803+ std::sync::atomic::AtomicUsize::new(0);
804+
805+/// The rect/AB-piece-residual count since the last call, and zero it.
806+pub fn take_b128_rectres_hits() -> usize {
807+ B128_RECTRES_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
808+}
768809
769810 /// lane-b128r: whether the 128 root offers the COMPOUND candidates the 64
770811 /// root already does (`NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`,
@@ -9929,11 +9970,124 @@ fn search_root_128(
99299970 ))
99309971 }
99319972
9973+/// lane-rectres: one rect/AB piece's REAL residual, priced against the skip
9974+/// arm the caller's [`search_skip_64`] just committed to the planes (which
9975+/// IS the winner's prediction, sample for sample -- the same rule
9976+/// [`search_root_128`]'s residual arm runs at the NONE root). The piece's
9977+/// residual is one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
9978+/// mu chunk (two chunks for a 128x64 / 64x128 half, one for a 64x64 square),
9979+/// each trial at sides the forward network already reaches, never a
9980+/// rectangular transform; var-tx depth 0 only -- the units ARE the tree's
9981+/// leaves, exactly what `decode_inter_block`'s mu-chunk loop reads.
9982+///
9983+/// The depth-0 `txfm_partition` symbols the writer codes for the units are
9984+/// not priced, exactly as [`search_root_128`] does not price its four (their
9985+/// contexts are only known at write time); at two symbols a half this is
9986+/// under a bit against residuals of hundreds. On a win (or under the witness
9987+/// force) the trials are committed to the planes, `block` is flipped to
9988+/// carry the packed level grids [`crate::tile::write_inter_block_128_rect`]
9989+/// slices back out, and the new cost is returned; otherwise `cost` passes
9990+/// through untouched. Counts [`take_b128_rectres_hits`] on a win.
9991+#[allow(clippy::too_many_arguments)]
9992+fn search_rect_residual(
9993+ luma: &mut Plane,
9994+ chroma: &mut [Plane; 2],
9995+ // The piece's own top-left, in luma samples.
9996+ (px, py): (usize, usize),
9997+ // Its true footprint: (128, 64) HORZ, (64, 128) VERT, (64, 64) square.
9998+ (w, h): (usize, usize),
9999+ cost: f64,
10000+ lambda: f64,
10001+ search: &Search<'_>,
10002+ // The piece's own mv stack, for the skip symbol's cost either way.
10003+ stack: &crate::mvstack::MvStack,
10004+ block: &mut BlockCoeffs,
10005+) -> f64 {
10006+ /// The 64x64 "mu" chunk side, luma; chroma halves it.
10007+ const MU: usize = SUPERBLOCK;
10008+ let chunks: [(usize, usize); 2] = match (w, h) {
10009+ (128, 64) => [(0, 0), (0, 1)],
10010+ (64, 128) => [(0, 0), (1, 0)],
10011+ _ => [(0, 0), (0, 0)],
10012+ };
10013+ let n = if w.max(h) > MU { 2 } else { 1 };
10014+ // Every unit's coded level grid is 32x32 (a 64-point transform codes
10015+ // only its top-left corner), packed per plane into one 64-wide grid with
10016+ // chunk (cr, cc) at (cr * 32, cc * 32) -- the layout the writer slices
10017+ // back out in the same chunk order.
10018+ let mut packed = [vec![0i32; 64 * 64], vec![0i32; 64 * 64], vec![0i32; 64 * 64]];
10019+ let mut sse_skip = 0.0f64;
10020+ let mut sse_res = 0.0f64;
10021+ let mut coeff_bits = 0.0f64;
10022+ let mut trials_per_chunk: Vec<[Trial; 3]> = Vec::with_capacity(n);
10023+ for &(cr, cc) in &chunks[..n] {
10024+ let (cxx, cyy) = (px + cc * MU, py + cr * MU);
10025+ let (cx, cy) = (cxx / 2, cyy / 2);
10026+ let half = MU / 2;
10027+ let pred_y = rows_of(&luma.reconstruction, luma.width, cxx, cyy, MU);
10028+ let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
10029+ let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
10030+ sse_skip += luma.block_sse(cxx, cyy, MU, &pred_y)
10031+ + chroma[0].block_sse(cx, cy, half, &pred_u)
10032+ + chroma[1].block_sse(cx, cy, half, &pred_v);
10033+ let trials = [
10034+ luma.code_from_prediction(
10035+ cxx, cyy, MU, &pred_y, false, search.base_q_idx, search.deadzone,
10036+ TxbSet::Luma64,
10037+ ),
10038+ chroma[0].code_from_prediction(
10039+ cx, cy, half, &pred_u, false, search.base_q_idx, search.deadzone,
10040+ TxbSet::Chroma32,
10041+ ),
10042+ chroma[1].code_from_prediction(
10043+ cx, cy, half, &pred_v, false, search.base_q_idx, search.deadzone,
10044+ TxbSet::Chroma32,
10045+ ),
10046+ ];
10047+ for (plane, trial) in trials.iter().enumerate() {
10048+ sse_res += trial.sse;
10049+ coeff_bits += trial.bits;
10050+ for row in 0..32 {
10051+ packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
10052+ .copy_from_slice(&trial.levels[row * 32..][..32]);
10053+ }
10054+ }
10055+ trials_per_chunk.push(trials);
10056+ }
10057+ // `cost` is the skip arm's own `sse + lambda * syntax`; the residual arm
10058+ // pays the same syntax with `skip` coded 0 instead of 1, plus its
10059+ // coefficients.
10060+ let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
10061+ let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
10062+ if res_cost < cost || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed) {
10063+ for (trials, &(cr, cc)) in trials_per_chunk.iter().zip(&chunks[..n]) {
10064+ let (cxx, cyy) = (px + cc * MU, py + cr * MU);
10065+ let (cx, cy) = (cxx / 2, cyy / 2);
10066+ let half = MU / 2;
10067+ luma.commit(cxx, cyy, MU, &trials[0]);
10068+ chroma[0].commit(cx, cy, half, &trials[1]);
10069+ chroma[1].commit(cx, cy, half, &trials[2]);
10070+ }
10071+ block.skip = false;
10072+ block.tx_depth = 0;
10073+ block.luma_tx_types = Vec::new();
10074+ block.luma = coeffs(&packed[0], 64);
10075+ block.u = coeffs(&packed[1], 64);
10076+ block.v = coeffs(&packed[2], 64);
10077+ B128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10078+ res_cost
10079+ } else {
10080+ cost
10081+ }
10082+}
10083+
993210084 /// lane-b128hv: the `PARTITION_HORZ` / `PARTITION_VERT` candidate for a whole
993310085 /// 128 superblock root -- two 128x64 (`horz`) or 64x128 inter blocks, the
9934-/// shipped NONE machinery halved. Skip only, single reference or compound,
9935-/// exactly what `crate::tile::write_inter_block_128_rect` codes and
9936-/// `decode_inter_block` reads at `sb128_rect`.
10086+/// shipped NONE machinery halved. Skip-only by default, single reference or
10087+/// compound; under `EC_AV1_RECTRES` each half also prices a REAL residual
10088+/// ([`search_rect_residual`]) -- exactly what
10089+/// `crate::tile::write_inter_block_128_rect` codes and `decode_inter_block`
10090+/// reads at `sb128_rect`.
993710091 ///
993810092 /// The FIRST half is published into `grid` before the second is searched --
993910093 /// the writer publishes it too, so a second half searched against the stale
@@ -10065,7 +10219,23 @@ fn search_root_128_rect(
1006510219 fctx,
1006610220 );
1006710221 match found {
10068- Some((c, block)) => {
10222+ Some((mut c, mut block)) => {
10223+ // lane-rectres: the same prediction with a REAL residual,
10224+ // priced against the skip arm the search just committed to
10225+ // the planes -- two 64x64 mu chunks for a half.
10226+ if rectres() && block.skip {
10227+ c = search_rect_residual(
10228+ luma,
10229+ chroma,
10230+ (mc * 4, mr * 4),
10231+ (w, h),
10232+ c,
10233+ root_search.lambda,
10234+ &root_search,
10235+ &stack,
10236+ &mut block,
10237+ );
10238+ }
1006910239 cost += c;
1007010240 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
1007110241 halves.push(block);
@@ -10105,8 +10275,9 @@ fn search_root_128_rect(
1010510275 /// `encoder-grid-drift-invisible-to-pixel-gate`). The grid and both planes
1010610276 /// are put back before returning; the caller re-applies the winner.
1010710277 ///
10108-/// SKIP only, for the reason [`search_root_128_rect`] gives: the 128 residual
10109-/// arm the pieces would share is itself parked behind `EC_AV1_B128RES`.
10278+/// Skip-only by default; under `EC_AV1_RECTRES` each piece also prices a
10279+/// REAL residual ([`search_rect_residual`]) -- the 64x64 squares are where
10280+/// libaom's own AB shapes earn their keep.
1011010281 ///
1011110282 /// Returns `(cost, lambda, the three pieces, reconstruction)`, the cost
1011210283 /// already carrying the root's own partition symbol so it ranks against the
@@ -10221,7 +10392,25 @@ fn search_root_128_ab(
1022110392 fctx,
1022210393 );
1022310394 match found {
10224- Some((c, block)) => {
10395+ Some((mut c, mut block)) => {
10396+ // lane-rectres: the same prediction with a REAL residual,
10397+ // priced against the skip arm the search just committed to
10398+ // the planes -- one mu chunk for a 64x64 square, two for a
10399+ // half. The 64x64 squares are where libaom's own AB shapes
10400+ // earn their keep.
10401+ if rectres() && block.skip {
10402+ c = search_rect_residual(
10403+ luma,
10404+ chroma,
10405+ (mc * 4, mr * 4),
10406+ (w, h),
10407+ c,
10408+ root_search.lambda,
10409+ &root_search,
10410+ &stack,
10411+ &mut block,
10412+ );
10413+ }
1022510414 cost += c;
1022610415 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
1022710416 pieces.push(block);
@@ -17286,6 +17475,227 @@ mod tests {
1728617475 }
1728717476 }
1728817477
17478+ /// lane-rectres: a `PARTITION_HORZ` 128 root whose two 128x64 halves
17479+ /// CARRY A RESIDUAL -- the mu-chunk shape (one TX_64X64 luma unit plus a
17480+ /// TX_32X32 chroma pair per chunk) `write_inter_block_128_rect` now
17481+ /// codes under `EC_AV1_RECTRES`, at the footprint the decoder's own
17482+ /// mu-chunk loop reads. The arm is FORCED ([`force_b128_rectres`], the
17483+ /// rect partition with [`force_b128_rect`]) so every inter root of the
17484+ /// clip goes through it; the `coded > 0` assert is the guard that catches
17485+ /// the next fixture drift (the whole-128 twin of this witness went RED
17486+ /// twice that way).
17487+ ///
17488+ /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17489+ /// encode::tests::a_rect128_half_with_a_real_residual --nocapture
17490+ #[test]
17491+ #[ignore = "sets the process-global superblock size: run it alone"]
17492+ fn a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders() {
17493+ let _knobs = crate::speed::knob_write();
17494+ if !have_ffmpeg() {
17495+ eprintln!("SKIP: no ffmpeg");
17496+ return;
17497+ }
17498+ force_sb128(true);
17499+ let dir = std::env::temp_dir().join(format!("ec-av1-rectres-{}", std::process::id()));
17500+ std::fs::create_dir_all(&dir).unwrap();
17501+ let clip = dir.join("smpte-pan-1280x768.y4m");
17502+ let ok = Command::new("ffmpeg")
17503+ .args(["-v", "error", "-y", "-f", "lavfi"])
17504+ .args(["-i", "smptebars=size=1600x768:rate=24"])
17505+ .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
17506+ .args(["-pix_fmt", "yuv420p"])
17507+ .arg(&clip)
17508+ .status()
17509+ .expect("ffmpeg failed to run")
17510+ .success();
17511+ assert!(ok, "ffmpeg could not write the synthetic clip");
17512+ let (width, height) = (1280usize, 768usize);
17513+ let pictures =
17514+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
17515+ force_b128_rect(1);
17516+ force_b128_rectres(true);
17517+ let _ = take_b128_rectres_hits();
17518+ let _ = crate::tile::take_sb128_rectres_hits();
17519+ let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
17520+ let (won, coded) =
17521+ (take_b128_rectres_hits(), crate::tile::take_sb128_rectres_hits());
17522+ eprintln!("rect halves WITH a residual: search won {won}, writer coded {coded}");
17523+ assert!(
17524+ coded > 0,
17525+ "no 128x64 half carried a residual on this clip, so it cannot witness the arm",
17526+ );
17527+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17528+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17529+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17530+ let recon = &frame.reconstruction;
17531+ for (plane, got, want) in [
17532+ ("luma", &dec.y, &recon.y),
17533+ ("U", &dec.u, &recon.u),
17534+ ("V", &dec.v, &recon.v),
17535+ ] {
17536+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17537+ assert_eq!(
17538+ differ, 0,
17539+ "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17540+ own reconstruction",
17541+ got.len()
17542+ );
17543+ }
17544+ }
17545+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17546+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17547+ assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17548+ assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17549+ assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17550+ }
17551+ }
17552+
17553+ /// lane-rectres: an AB shape (`PARTITION_HORZ_A` forced) whose THREE
17554+ /// pieces carry residuals -- the 128x64 half through the two-chunk arm,
17555+ /// the two 64x64 squares through the one-chunk arm (the shape libaom's
17556+ /// own AB partitions earn their keep with). testsrc2 at 12 frames, the
17557+ /// shipped AB witness's own recipe: an 8-frame clip parks an ARF whose
17558+ /// reference picture the GOP has not produced yet, which refuses before
17559+ /// any AB root is coded.
17560+ ///
17561+ /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17562+ /// encode::tests::an_ab128_piece_with_a_real_residual --nocapture
17563+ #[test]
17564+ #[ignore = "sets the process-global superblock size: run it alone"]
17565+ fn an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders() {
17566+ let _knobs = crate::speed::knob_write();
17567+ if !have_ffmpeg() {
17568+ eprintln!("SKIP: no ffmpeg");
17569+ return;
17570+ }
17571+ force_sb128(true);
17572+ let dir = std::env::temp_dir().join(format!("ec-av1-rectres-ab-{}", std::process::id()));
17573+ std::fs::create_dir_all(&dir).unwrap();
17574+ let clip = dir.join("testsrc2-1280x768.y4m");
17575+ let ok = Command::new("ffmpeg")
17576+ .args(["-v", "error", "-y", "-f", "lavfi"])
17577+ .args(["-i", "testsrc2=size=1280x768:rate=24"])
17578+ .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17579+ .arg(&clip)
17580+ .status()
17581+ .expect("ffmpeg failed to run")
17582+ .success();
17583+ assert!(ok, "ffmpeg could not write the synthetic clip");
17584+ let (width, height) = (1280usize, 768usize);
17585+ let pictures =
17586+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17587+ force_b128_ab(4);
17588+ force_b128_rectres(true);
17589+ let _ = take_b128_rectres_hits();
17590+ let _ = crate::tile::take_sb128_rectres_hits();
17591+ let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
17592+ let (won, coded) =
17593+ (take_b128_rectres_hits(), crate::tile::take_sb128_rectres_hits());
17594+ eprintln!("AB pieces WITH a residual: search won {won}, writer coded {coded}");
17595+ assert!(
17596+ coded > 0,
17597+ "no AB piece carried a residual on this clip, so it cannot witness the arm",
17598+ );
17599+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17600+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17601+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17602+ let recon = &frame.reconstruction;
17603+ for (plane, got, want) in [
17604+ ("luma", &dec.y, &recon.y),
17605+ ("U", &dec.u, &recon.u),
17606+ ("V", &dec.v, &recon.v),
17607+ ] {
17608+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17609+ assert_eq!(
17610+ differ, 0,
17611+ "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17612+ own reconstruction",
17613+ got.len()
17614+ );
17615+ }
17616+ }
17617+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17618+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17619+ assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17620+ assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17621+ assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17622+ }
17623+ }
17624+
17625+ /// lane-rectres, lane-edge128's interaction on the rect shapes: a HORZ
17626+ /// half WITH a residual under a clip whose CDEF search codes a
17627+ /// per-64x64 `cdef_idx` list. The half codes ONE literal at its origin
17628+ /// and the decoder stamps BOTH units it spans with it, so the owner map
17629+ /// ([`crate::tile::cdef_unit_owner`], now extended past Whole128) has to
17630+ /// collapse the pair -- exactly the bug class that broke bars 2160p at
17631+ /// the whole-128 root. RED before this lane by construction: no rect
17632+ /// piece could carry a residual, so no such literal existed.
17633+ ///
17634+ /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17635+ /// encode::tests::a_rect128_residual_half_under_a_per_unit_cdef --nocapture
17636+ #[test]
17637+ #[ignore = "sets the process-global superblock size: run it alone"]
17638+ fn a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact() {
17639+ let _knobs = crate::speed::knob_write();
17640+ if !have_ffmpeg() {
17641+ eprintln!("SKIP: no ffmpeg");
17642+ return;
17643+ }
17644+ force_sb128(true);
17645+ let dir = std::env::temp_dir().join(format!("ec-av1-rectres-cdef-{}", std::process::id()));
17646+ std::fs::create_dir_all(&dir).unwrap();
17647+ let clip = dir.join("testsrc2-1280x768.y4m");
17648+ // Detailed synthetic content: its CDEF search spends more than one
17649+ // strength pair, which is what puts a `cdef_idx` literal in the tile.
17650+ let ok = Command::new("ffmpeg")
17651+ .args(["-v", "error", "-y", "-f", "lavfi"])
17652+ .args(["-i", "testsrc2=size=1280x768:rate=24"])
17653+ .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17654+ .arg(&clip)
17655+ .status()
17656+ .expect("ffmpeg failed to run")
17657+ .success();
17658+ assert!(ok, "ffmpeg could not write the synthetic clip");
17659+ let (width, height) = (1280usize, 768usize);
17660+ let pictures =
17661+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17662+ force_b128_rect(1);
17663+ force_b128_rectres(true);
17664+ let _ = crate::tile::take_sb128_rectres_hits();
17665+ let _ = crate::filter_search::take_cdef_covered_units();
17666+ let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
17667+ let coded = crate::tile::take_sb128_rectres_hits();
17668+ let covered = crate::filter_search::take_cdef_covered_units();
17669+ eprintln!(
17670+ "rect halves WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
17671+ another unit's literal: {covered}"
17672+ );
17673+ assert!(coded > 0, "no 128x64 half carried a residual on this clip");
17674+ assert!(
17675+ covered > 0,
17676+ "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
17677+ cannot witness the rule",
17678+ );
17679+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17680+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17681+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17682+ for (plane, got, want) in [
17683+ ("luma", &dec.y, &frame.reconstruction.y),
17684+ ("U", &dec.u, &frame.reconstruction.u),
17685+ ("V", &dec.v, &frame.reconstruction.v),
17686+ ] {
17687+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17688+ assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
17689+ }
17690+ }
17691+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17692+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17693+ assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17694+ assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17695+ assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17696+ }
17697+ }
17698+
1728917699 /// lane-b128r: the COMPOUND arm at the 128 root -- one 128x128 block
1729017700 /// naming `LAST` plus `GOLDEN`/`ALTREF`, through the same
1729117701 /// `write_compound_block` chain every smaller compound block takes, at a
@@ -20283,11 +20693,14 @@ mod tests {
2028320693 );
2028420694 eprintln!(
2028520695 "{name}: 128x128 roots {} (search) / {} (writer), with a residual \
20696+ {} (search) / {} (writer); rect/AB pieces with a residual \
2028620697 {} (search) / {} (writer)",
2028720698 take_b128_none_hits(),
2028820699 crate::tile::take_sb128_none_hits(),
2028920700 take_b128_residual_hits(),
2029020701 crate::tile::take_sb128_residual_hits(),
20702+ take_b128_rectres_hits(),
20703+ crate::tile::take_sb128_rectres_hits(),
2029120704 );
2029220705 eprintln!(
2029320706 "{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})",
crates/ec-av1/src/tile.rsmodified+218 -29
@@ -473,13 +473,18 @@ fn write_inter_block_128(
473473 /// block's true footprint governs only its mv-stack window, its mi/grid stamp
474474 /// and its neighbour bands (decode.rs' own `write_w`/`write_h` split).
475475 ///
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.
476+/// lane-ab128: also the two 64x64 squares an AB shape codes (the `w == h`
477+/// arm below) and its 128x64 / 64x128 half.
478+///
479+/// lane-rectres: a piece may CARRY A RESIDUAL -- the search only ever hands
480+/// one over under `EC_AV1_RECTRES` ([`crate::encode::rectres`]), and then it
481+/// is coded here exactly as `decode_inter_block` reads it: one TX_64X64 luma
482+/// unit plus a TX_32X32 chroma pair per 64x64 mu chunk (two chunks for a
483+/// half, one for a square), each depth-0 in the var-tx tree (a half codes
484+/// two `txfm_partition` flags under `TxMode::Select`, a square one).
480485 ///
481486 /// # Errors
482-/// A block that is intra or that is not skipped.
487+/// A block that is intra.
483488 #[allow(clippy::too_many_arguments)]
484489 fn write_inter_block_128_rect(
485490 enc: &mut SymbolEncoder,
@@ -498,12 +503,6 @@ fn write_inter_block_128_rect(
498503 let info = block.inter.ok_or_else(|| {
499504 Error::unsupported("AV1 tile", "a 128-root rectangular half is coded inter")
500505 })?;
501- if !block.skip {
502- return Err(Error::unsupported(
503- "AV1 tile",
504- "a 128-root rectangular half carries a residual",
505- ));
506- }
507506 let (mi_r, mi_c) = at_mi;
508507 let (w_mi, h_mi) = (w / MI, h / MI);
509508 let has_above = neighbours.has_above(mi_r);
@@ -598,10 +597,46 @@ fn write_inter_block_128_rect(
598597 block.motion_mode,
599598 )?;
600599 }
600+ // The 64x64 mu chunks the residual is coded in, raster order -- the
601+ // decoder's own walk: two for a half, one for a square piece.
602+ let chunks: &[(usize, usize)] = match (w, h) {
603+ (128, 64) => &[(0, 0), (0, 1)],
604+ (64, 128) => &[(0, 0), (1, 0)],
605+ _ => &[(0, 0)],
606+ };
607+ // A half's uv plane block (64x32 / 32x64) is wider or taller than its
608+ // 32x32 unit, so the unit's `txb_skip_ctx` takes `get_txb_ctx`'s
609+ // offset-10 rows (+3 here); a 64x64 piece's uv block IS the unit and
610+ // takes none. The half is also the only shape whose chroma is re-stamped
611+ // per mu chunk at the end (decode.rs' `mu_chroma`).
612+ let is_half = w.max(h) > 64;
601613 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));
614+ if block.skip {
615+ // `read_block_tx_size_rect`'s skip arm: `txfm_partition_update_rect`
616+ // with the BLOCK's own size in both bands, no symbol.
617+ neighbours.record_txfm_rect((mi_r, mi_c), (w, h), (w, h));
618+ } else if is_half {
619+ // The var-tx tree of a 128x64 / 64x128 block enters at TX_64X64
620+ // once per mu chunk (`read_block_tx_size_rect`'s `max_tx = 64`
621+ // loop), so it is two depth-0 `txfm_split` flags of zero, each
622+ // read against the bands the chunks before it published.
623+ for &(cr, cc) in chunks {
624+ let unit = (mi_r + cr * 16, mi_c + cc * 16);
625+ let ctx = txfm_partition_ctx_rect(
626+ neighbours.above_txfm[unit.1],
627+ neighbours.left_txfm[unit.0],
628+ w.max(h),
629+ 64,
630+ 64,
631+ );
632+ enc.symbol(0, &mut cdfs.txfm_partition[ctx]);
633+ neighbours.record_txfm(unit, 64, 64, 64);
634+ }
635+ } else {
636+ // A 64x64 piece is one whole TX_64X64: the single depth-0 flag
637+ // the 64 root's own writer codes (`write_tx_syntax_inter`).
638+ write_tx_syntax_inter(enc, cdfs, neighbours, (mi_r, mi_c), SB, true, false, 0);
639+ }
605640 }
606641 let zero_grids = [
607642 vec![0i32; TX32 * TX32],
@@ -612,7 +647,94 @@ fn write_inter_block_128_rect(
612647 // side bands are named by the same SUB-grid origin every square block
613648 // uses.
614649 let at_sub = (mi_r / (SUB / MI), mi_c / (SUB / MI));
615- neighbours.record_planes_rect(at_sub, (w, h), 0, &zero_grids, true);
650+ if !block.skip {
651+ // lane-rectres: the packed 64-wide level grids the search hands over,
652+ // one plane each (the same layout `write_inter_block_128` slices for
653+ // the whole block, here with the piece's own chunk list).
654+ let packed = [
655+ level_grid(&block.luma, 64)?,
656+ level_grid(&block.u, 64)?,
657+ level_grid(&block.v, 64)?,
658+ ];
659+ let scan32 = default_scan(TX32);
660+ let unit_of = |plane: usize, cr: usize, cc: usize| -> Vec<i32> {
661+ (0..32)
662+ .flat_map(|row| {
663+ packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32].to_vec()
664+ })
665+ .collect()
666+ };
667+ let mut chroma_units: Vec<((usize, usize), [Vec<i32>; 2])> = Vec::new();
668+ for &(cr, cc) in chunks {
669+ let unit_mi = (mi_r + cr * 16, mi_c + cc * 16);
670+ // The luma unit, and the context its all-zero flag reads: a
671+ // HALF's unit is smaller than its block (neighbour magnitude
672+ // table), a square's IS the whole plane block (fixed zero --
673+ // `read_inter_plane`'s `luma_skip_ctx.unwrap_or(0)`, the 64
674+ // root's own writer rule). It publishes its context before the
675+ // next chunk reads it.
676+ let luma = unit_of(0, cr, cc);
677+ let skip_ctx = if is_half {
678+ neighbours.luma_skip_ctx(unit_mi, 64 / MI)
679+ } else {
680+ 0
681+ };
682+ let around = neighbours.around_mi(unit_mi, 64);
683+ write_coeffs(
684+ enc,
685+ &mut cdfs.txb(TxbSet::Luma64, 0),
686+ &luma,
687+ &scan32,
688+ skip_ctx,
689+ dc_sign_ctx(around[0].dc_vote),
690+ Some(0),
691+ TxType::DctDct,
692+ );
693+ neighbours.record_mi_luma(unit_mi, 64, &luma);
694+ // Then this chunk's chroma pair, before the next chunk's luma:
695+ // libaom codes every plane of a mu chunk before moving on.
696+ let mut pair = [Vec::new(), Vec::new()];
697+ for plane in 1..3usize {
698+ let grid = unit_of(plane, cr, cc);
699+ let around = neighbours.around_mi(unit_mi, 64)[plane];
700+ write_coeffs(
701+ enc,
702+ &mut cdfs.txb(TxbSet::Chroma32, 0),
703+ &grid,
704+ &scan32,
705+ usize::from(around.above_coded) + usize::from(around.left_coded)
706+ + 3 * usize::from(is_half),
707+ dc_sign_ctx(around.dc_vote),
708+ Some(plane),
709+ TxType::DctDct,
710+ );
711+ neighbours.record_mi_chroma(unit_mi, 64, plane, &grid);
712+ pair[plane - 1] = grid;
713+ }
714+ chroma_units.push((unit_mi, pair));
715+ }
716+ // decode.rs' own tail (`record_split_luma_rect_mi` then, on a half,
717+ // the per-chunk chroma re-stamp): the block-level write off the
718+ // whole assembled chroma plane grid, luma kept because each unit
719+ // already published its own, and then the per-unit chroma writes
720+ // replayed over it -- last writer wins, so the next block reads the
721+ // units.
722+ let block_grids = [
723+ vec![0i32; TX32 * TX32],
724+ packed[1].clone(),
725+ packed[2].clone(),
726+ ];
727+ neighbours.record_planes_rect(at_sub, (w, h), 0, &block_grids, false);
728+ if is_half {
729+ for (unit_mi, pair) in &chroma_units {
730+ neighbours.record_mi_chroma(*unit_mi, 64, 1, &pair[0]);
731+ neighbours.record_mi_chroma(*unit_mi, 64, 2, &pair[1]);
732+ }
733+ }
734+ SB128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
735+ } else {
736+ neighbours.record_planes_rect(at_sub, (w, h), 0, &zero_grids, true);
737+ }
616738 neighbours.record_inter_rect_mi((mi_r, mi_c), (w, h), block.skip, true, block_ref(block));
617739 if let Some(r1) = info.ref1 {
618740 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 =
666788 pub fn take_sb128_residual_hits() -> usize {
667789 SB128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
668790 }
791+/// lane-rectres: how many RECT/AB pieces (the halves and 64x64 squares
792+/// [`write_inter_block_128_rect`] codes) carried a REAL residual rather than
793+/// being skipped, since the last [`take_sb128_rectres_hits`] -- the writer
794+/// side of [`crate::encode::take_b128_rectres_hits`]'s search count.
795+static SB128_RECTRES_HITS: std::sync::atomic::AtomicUsize =
796+ std::sync::atomic::AtomicUsize::new(0);
797+
798+/// The rect/AB-piece-with-residual count since the last call, and zero it.
799+pub fn take_sb128_rectres_hits() -> usize {
800+ SB128_RECTRES_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
801+}
669802
670803 /// lane-b128r: how many of those blocks named a SECOND reference (the
671804 /// compound arm at the 128 root), since the last
@@ -874,25 +1007,80 @@ impl TileLayout {
8741007 /// That is the shape this map exists to collapse
8751008 /// ([`crate::filter_search::pick_filters`]).
8761009 ///
877-/// Identity everywhere else: every block this writer codes at 64x64 or below
878-/// covers exactly one unit.
1010+/// lane-rectres: the same holds for a Rect128 half or an Ab128 half that
1011+/// carries a residual (`EC_AV1_RECTRES`) -- it codes one literal at its own
1012+/// origin and the decoder stamps BOTH units it spans with it, so its pair is
1013+/// collapsed onto the origin unit too. Its 64x64 squares cover exactly one
1014+/// unit each, and a SKIP-ONLY rect/AB piece codes no literal at all (the
1015+/// decoder's per-piece `cdef_transmitted` reset never fires), so neither
1016+/// touches this map -- only pieces the writer really codes a residual for.
8791017 pub(crate) fn cdef_unit_owner(blocks: &[Quadrant], mi_cols: u32, mi_rows: u32) -> Vec<u32> {
8801018 let (cols, rows) = block_grid(mi_cols, mi_rows);
8811019 let (sb_cols, sb_rows) = (cols.div_ceil(2) as usize, rows.div_ceil(2) as usize);
8821020 let mut owner: Vec<u32> = (0..(sb_cols * sb_rows) as u32).collect();
1021+ // Collapses every 64x64 unit `(ur, uc) ..` a residual piece at unit
1022+ // `(ur, uc)` with footprint `(w, h)` spans onto the piece's origin --
1023+ // [`crate::encode::write_inter_block_128_rect`]'s one `write_cdef_idx`
1024+ // is what the decoder copies over all of them.
1025+ let collapse = |owner: &mut Vec<u32>, (ur, uc): (usize, usize), (w, h): (usize, usize)| {
1026+ let origin = (ur * sb_cols + uc) as u32;
1027+ for r in ur..(ur + (h / 64).max(1)).min(sb_rows) {
1028+ for c in uc..(uc + (w / 64).max(1)).min(sb_cols) {
1029+ owner[r * sb_cols + c] = origin;
1030+ }
1031+ }
1032+ };
8831033 for sb_r in (0..sb_rows).step_by(2) {
8841034 for sb_c in (0..sb_cols).step_by(2) {
885- let root = ((sb_r * 2) < rows as usize && (sb_c * 2) < cols as usize)
1035+ let Some(root) = ((sb_r * 2) < rows as usize && (sb_c * 2) < cols as usize)
8861036 .then(|| &blocks[(sb_r * 2) * cols as usize + sb_c * 2])
887- .is_some_and(|q| matches!(q, Quadrant::Whole128(_)));
888- if !root {
1037+ else {
8891038 continue;
890- }
891- let origin = (sb_r * sb_cols + sb_c) as u32;
892- for r in sb_r..(sb_r + 2).min(sb_rows) {
893- for c in sb_c..(sb_c + 2).min(sb_cols) {
894- owner[r * sb_cols + c] = origin;
1039+ };
1040+ match root {
1041+ Quadrant::Whole128(_) => {
1042+ let origin = (sb_r * sb_cols + sb_c) as u32;
1043+ for r in sb_r..(sb_r + 2).min(sb_rows) {
1044+ for c in sb_c..(sb_c + 2).min(sb_cols) {
1045+ owner[r * sb_cols + c] = origin;
1046+ }
1047+ }
1048+ }
1049+ // lane-rectres: the two halves of a HORZ/VERT root sit in
1050+ // different unit rows (HORZ) / columns (VERT); each
1051+ // non-skip half collapses its own pair.
1052+ Quadrant::Rect128(horz, halves) => {
1053+ for (i, half) in halves.iter().enumerate() {
1054+ if half.skip {
1055+ continue;
1056+ }
1057+ let (ur, uc) = if *horz {
1058+ (sb_r + i, sb_c)
1059+ } else {
1060+ (sb_r, sb_c + i)
1061+ };
1062+ let (w, h) = if *horz { (128, 64) } else { (64, 128) };
1063+ collapse(&mut owner, (ur, uc), (w, h));
1064+ }
1065+ }
1066+ // lane-rectres: the AB half is the only multi-unit piece
1067+ // (its two squares are one unit each); only a non-skip one
1068+ // codes a literal, so only it fires.
1069+ Quadrant::Ab128(symbol, pieces) => {
1070+ for (piece, ((mi_r, mi_c), (w, h))) in
1071+ pieces.iter().zip(crate::encode::ab128_pieces(
1072+ usize::from(*symbol),
1073+ (0, 0),
1074+ ))
1075+ {
1076+ if piece.skip {
1077+ continue;
1078+ }
1079+ let (ur, uc) = (sb_r + mi_r / 16, sb_c + mi_c / 16);
1080+ collapse(&mut owner, (ur, uc), (w, h));
1081+ }
8951082 }
1083+ _ => {}
8961084 }
8971085 }
8981086 }
@@ -2605,8 +2793,9 @@ pub enum Quadrant {
26052793 /// Carried by the top-left 32x32 entry of the root's sixteen, exactly as
26062794 /// [`Whole128`](Quadrant::Whole128) is.
26072795 ///
2608- /// SKIP only ([`crate::tile::write_inter_block_128_rect`] refuses a
2609- /// residual), single reference or compound.
2796+ /// Skip-only by default; a piece carries a real residual under
2797+ /// `EC_AV1_RECTRES` (`crate::encode::rectres`), single reference or
2798+ /// compound either way.
26102799 Rect128(bool, Vec<BlockCoeffs>),
26112800 /// lane-ab128: the THREE inter blocks an AB shape at a 128 superblock
26122801 /// root carries -- two 64x64 pieces and one 128x64 / 64x128 half -- in
@@ -2616,8 +2805,8 @@ pub enum Quadrant {
26162805 /// top-left 32x32 entry of the root's sixteen, exactly as
26172806 /// [`Rect128`](Quadrant::Rect128) is.
26182807 ///
2619- /// SKIP only, same writer ([`crate::tile::write_inter_block_128_rect`])
2620- /// and same reason.
2808+ /// Skip-only by default, same writer; under `EC_AV1_RECTRES` any of the
2809+ /// three pieces may carry a real residual.
26212810 Ab128(u8, Vec<BlockCoeffs>),
26222811 /// A quadrant a [`Whole64`](Quadrant::Whole64) at its superblock's
26232812 /// top-left already coded; it carries no block of its own.
lanes/rectres.charter.mdadded+92 -0
@@ -0,0 +1,92 @@
1+# lane-rectres — non-skip residual on Rect128/Ab128 pieces
2+
3+GOAL: the Whole128 residual arm (`EC_AV1_B128RES`) is exact but INERT
4+(0.4-1.9 writer fires/frame, re-measured lane-b128res on 3b4673fe) —
5+whole 128 roots almost never win RD. The 128 root's rectangular pieces
6+DO win: lane-b128hv ships HORZ/VERT skip halves and lane-ab128 ships the
7+four AB shapes (`EC_AV1_B128AB=1` default ON). But those pieces are
8+skip-only: `write_inter_block_128_rect` refuses a rect half carrying a
9+residual, and `crate::tile::cdef_unit_owner` (tile.rs) is Whole128-only.
10+This lane turns Rect128 and Ab128 pieces into residual carriers and
11+measures whether RD taking them moves BD.
12+
13+Work ONLY in this worktree (`lane-rectres`,
14+`/home/user/Documents/Code/Rust/edith_codecs-rectres`). Absolute paths
15+only. Never touch main's checkout, never push, never `git checkout
16+<file>`, never repo-wide `cargo fmt`. `export
17+CARGO_TARGET_DIR=$HOME/.cache/cargo-target-rectres` on every cargo
18+command. Logs under `~/.cache/rectres/`. TMPDIR only on gate command
19+lines, not on the sccache server. Gates: `systemd-run --user -p
20+MemoryMax=14G`, `--ignored --exact` on both BD tests (they are
21+`#[ignore]`; without `--ignored` they measure nothing). One gate at a
22+time; record LOADAVG before AND after. Pins 8291 / 33227. Keep rule: one
23+film row ≥0.5 BD down on a column, the other flat within ±0.3, screen
24+not worse by 0.3, wall ≤+15%. Sign: BD-rate, lower better.
25+
26+## 1. Write residual on rect/AB pieces
27+
28+- Lift the refusal in `write_inter_block_128_rect`: a Rect128 half
29+ (HORZ/VERT) or an Ab128 shape piece with a real residual codes its
30+ coefficients like any inter block of that w×h. The decoder side is
31+ spec — `decode_stream` and ffmpeg both already read residual on any
32+ inter partition shape; the burden is on the ENCODER writer and the
33+ encoder reconstruction path being identical.
34+- Knob in the `EC_AV1_*` convention (e.g. `EC_AV1_RECTRES`), default
35+ OFF, gated next to `b128_residual` in encode.rs. OFF = today's
36+ behavior bit-exact.
37+- INVARIANT (lane-edge128's bug class): a 128-wide piece that writes a
38+ residual also codes `cdef_idx` per the syntax it carries, while
39+ `read_cdef` copies ONE literal over every 64x64 unit the piece spans.
40+ Extend `cdef_unit_owner` past Whole128 to the rect/AB shapes so the
41+ CDEF search prices the ONE index the syntax carries, not one per unit.
42+ Skip-only pieces still write no `cdef_idx` — owner map must not fire
43+ for them.
44+- RD side: let the rect/AB search arm price non-skip outcomes (residual
45+ cost) instead of skip-only, under the knob.
46+
47+## 2. Witnesses FIRST (before any BD gate)
48+
49+Add witnesses in the standing pattern (see
50+`a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders`
51+and `a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact`,
52+both `--ignored`, fixture q=60 after lane-b128res re-vitalization):
53+
54+- a Rect128 half with a real residual decodes sample-exact through
55+ ffmpeg AND `decode_stream`, with a `coded > 0` assert as the guard.
56+- same for at least one Ab128 shape.
57+- a rect/AB residual piece spanning multiple CDEF units takes the owner
58+ unit's literal, byte-exact through both decoders (the edge128
59+ interaction, now on rect shapes).
60+
61+If any witness shows an encoder-reconstruction mismatch: STOP, do not
62+ship, report class + path:line, default stays OFF.
63+
64+## 3. Measure
65+
66+Control = default (knob off) on this HEAD. Arm = knob on.
67+
68+- `cargo test -p ec-av1 --release --lib -- --ignored --exact --nocapture
69+ encode::tests::bd_rate_film_long_gop` (deciding). Both films.
70+- 12-frame guard: `encode::tests::bd_rate_screen_native`, all five rows,
71+ control and arm.
72+- Fire census: extend the standing native-arm census line so rect/AB
73+ residual fires (search won / writer coded) print next to the 128-root
74+ census, and report fires/frame per clip like lane-b128res §4. If the
75+ writer still codes ~0 rect/AB residuals, the arm is inert — say so.
76+
77+Keep rule met → default ON, drop the refusal comment. Inert + exact →
78+leave OFF, document fires. Mismatch → OFF, report (see §2).
79+
80+## 4. Pins / suite (only if you change the default)
81+
82+Pins at default and `EC_AV1_SPEED=6`. Workspace check `timeout 900 cargo
83+check --workspace --all-targets -j4` (0 ec-av1 warnings). Do NOT run the
84+full lib suite unless you change the default; if you do, three lanes:
85+`--skip stream::` / `stream:: --skip 10bit` / `10bit`.
86+
87+## DONE
88+
89+Commit on `lane-rectres` + `lanes/rectres.report.md` with EVIDENCE lines
90+(`EVIDENCE: <artifact> | <steps> | <measurement>`), fire counts, BD
91+tables, witness results, disposition `ships-on | stays-off | stopped`.
92+Never merge or push.
lanes/rectres.report.mdadded+185 -0
@@ -0,0 +1,185 @@
1+# lane-rectres — non-skip residual on Rect128/Ab128 pieces
2+
3+Base: `3b4673fe` (lane-rectres worktree). Disposition: **stays-off**
4+(ACTIVE but BD-neutral + exact — under the knob the RD does take
5+non-skip rect/AB pieces on every gate clip (up to 4.5 writer
6+fires/frame on film A long-GOP), and the BD table moves at most 0.1
7+anywhere). `EC_AV1_RECTRES` keeps its default (off): OFF is today's
8+behavior bit for bit — the search never flips a rect/AB piece to
9+non-skip, so the writer's lifted refusal is never reached. Pins
10+untouched at 8291 / 33227 (no default change, so no pin run, no lib
11+suite). Never merged, never pushed.
12+
13+## 1. What shipped (commit `26a9b79e`)
14+
15+- `write_inter_block_128_rect` (tile.rs): the skip-only refusal is lifted.
16+ A residual piece codes one TX_64X64 luma unit plus a TX_32X32 chroma pair
17+ per 64x64 mu chunk (two chunks for a 128x64/64x128 half, one for a 64x64
18+ square), var-tx depth 0; under `TxMode::Select` a half codes two depth-0
19+ `txfm_partition` flags (ctx rect at `w.max(h)=128`), a square one (via
20+ `write_tx_syntax_inter`). A half's chroma unit takes the +3
21+ `get_txb_ctx` offset; a square's takes none. Luma `txb_skip_ctx`: the
22+ neighbour magnitude table on a half, fixed 0 on a square (the transform
23+ IS the whole plane block — `read_inter_plane`'s
24+ `luma_skip_ctx.unwrap_or(0)`, the 64 root's own writer rule). Tail =
25+ `record_planes_rect(luma=false)` off the assembled chroma grids, then the
26+ per-chunk chroma re-stamp on halves only (`mu_chroma` mirror).
27+- `search_rect_residual` (encode.rs): prices the non-skip outcome against
28+ the skip arm the search just committed (per-chunk
29+ `code_from_prediction` trials, `unskip` skip-symbol delta, packed 64-wide
30+ level grids), commits + flips `block` on a win; wired into
31+ `search_root_128_rect` and `search_root_128_ab` behind
32+ `rectres()` (`EC_AV1_RECTRES`, default OFF, test force
33+ `force_b128_rectres`).
34+- `cdef_unit_owner` (tile.rs) extends past Whole128: a non-skip Rect128
35+ half collapses its 2 units onto its origin; an Ab128 half likewise (its
36+ 64x64 squares are 1 unit each). Skip-only pieces never touch the map —
37+ they code no literal and the decoder's per-piece `cdef_transmitted`
38+ reset never fires. This is the lane-edge128 bug class, priced for the
39+ ONE index the syntax carries.
40+- Census: the native arm's standing line now prints "rect/AB pieces with a
41+ residual N (search) / M (writer)" and zeroes both counters per clip.
42+- A defect found and fixed during witnessing (would have been the lane's
43+ own bug class): the first draft priced the 64x64 square's luma
44+ all-zero flag off the neighbour table; the decoder fixes it at 0 for a
45+ whole-block transform, and the desync surfaced as an empty-slot
46+ reference refusal mid-stream (encode.rs witness fixture), not a pixel
47+ miss. Fixed before any gate measured anything.
48+
49+## 2. Witnesses (all `--ignored --exact`, standalone, all PASS)
50+
51+- `a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders`
52+ (smpte pan 1280x768, 8 frames, q=60, HORZ forced + residual forced):
53+ search won 840, writer coded 840; `coded > 0` guard; whole stream
54+ sample-exact through `decode_stream` AND ffmpeg, all planes/frames.
55+ EVIDENCE: ~/.cache/rectres/wit1.log | forced HORZ + rectres, q=60, 8
56+ frames | "search won 840, writer coded 840", ok, both decoders exact.
57+ LOADAVG 118.48/98.99/57.92 before, 118.48/98.99/57.92 after (sibling
58+ lane storm; 3.6s run).
59+- `an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders`
60+ (testsrc2 1280x768, 12 frames, q=60, HORZ_A forced + residual forced):
61+ search won 4620, writer coded 5760 (writer counts include the filter
62+ search's winning re-code); exercises the two-chunk half AND both
63+ one-chunk squares; byte-exact through both decoders.
64+ EVIDENCE: ~/.cache/rectres/wit2.log | forced HORZ_A + rectres, q=60, 12
65+ frames | "search won 4620, writer coded 5760", ok. LOADAVG
66+ 107.04/97.41/58.06 before, 104.55/100.35/63.37 after.
67+- `a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact`
68+ (testsrc2, 12 frames, q=90, HORZ forced + residual forced): writer coded
69+ 2760 non-skip halves; 62 64x64 CDEF units took another unit's literal
70+ (owner-map collapse firing on rect pieces); byte-exact through both
71+ decoders. EVIDENCE: ~/.cache/rectres/wit3.log | --ignored --exact run |
72+ "writer coded 2760; 64x64 CDEF units taking another unit's literal: 62",
73+ ok. LOADAVG 7.90/7.85/9.32 before, 9.39/8.16/9.37 after.
74+
75+## 3. BD measurement (server-2, per Main's recipe)
76+
77+The worktree has no `fixtures/`, so all four gates ran on server-2
78+(user@host-a, 4 vCPU, MemoryMax=5G units, ffmpeg PATH shim). The
79+sanity gate PASSED before drawing any conclusion: the control run
80+reproduces the standing table (b128res.report §2/§3) to the digit —
81+long-GOP film A +20.9/-9.0 and film B +70.4/-2.2, and all five native
82+rows identical (±0.0 per cell, requirement was ±0.2).
83+
84+### 3a. Long-GOP BD (deciding; 48 pictures, gop=48, both films)
85+
86+Control = default (off), arm = `EC_AV1_RECTRES=1`, same HEAD. BD-rate,
87+lower better:
88+
89+| row | off vs libaom | off vs rav1e | on vs libaom | on vs rav1e |
90+|---|---|---|---|---|
91+| film A (1080p) 1920x768 | +20.9% | -9.0% | +20.9% | -9.0% |
92+| film B (2160p HDR) 1920x1024 | +70.4% | -2.2% | +70.5% | -2.1% |
93+
94+Wall ours: film A 1394.1s -> 1417.6s (+1.7%), film B 1076.6s -> 1118.3s
95+(+3.9%).
96+
97+EVIDENCE: ~/.cache/rectres/longgop-control.log | server-2 gate, MemoryMax=5G,
98+ffmpeg shim PATH | film A +20.9%/-9.0%, film B +70.4%/-2.2%; three-way
99+exactness assertion held at every clip x q x frame. LOADAVG 0.15/0.17/0.18
100+before, 1.08/1.09/1.09 after.
101+EVIDENCE: ~/.cache/rectres/longgop-arm.log | server-2 gate, EC_AV1_RECTRES=1,
102+MemoryMax=5G | film A +20.9%/-9.0%, film B +70.5%/-2.1%. LOADAVG
103+0.14/0.23/0.58 before, 1.05/1.08/1.08 after.
104+
105+### 3b. 12-frame native guard (all five rows)
106+
107+| row | off vs libaom | off vs rav1e | on vs libaom | on vs rav1e | wall ours off->on |
108+|---|---|---|---|---|---|
109+| bars 1080p | -3.3% | -19.0% | -3.4% | -19.0% | 424.8s -> 435.7s |
110+| bars 2160p | +8.4% | -13.9% | +8.5% | -13.9% | 365.0s -> 372.8s |
111+| film A | +17.9% | -6.3% | +17.8% | -6.4% | 369.4s -> 376.9s |
112+| film B | +22.6% | -3.8% | +22.5% | -3.9% | 311.9s -> 318.4s |
113+| screen capture | +14.4% | -33.2% | +14.4% | -33.2% | 246.4s -> 249.2s |
114+
115+EVIDENCE: ~/.cache/rectres/native-control.log | server-2 gate, five rows,
116+MemoryMax=5G | table above, "off" columns; matches the standing table to
117+the digit. LOADAVG 0.09/0.20/0.56 before, 1.14/1.15/1.09 after.
118+EVIDENCE: ~/.cache/rectres/native-arm.log | server-2 gate, five rows,
119+EC_AV1_RECTRES=1 | table above, "on" columns. LOADAVG 0.08/0.42/0.77
120+before, 1.07/1.10/1.09 after.
121+
122+| clip | rect/AB residual fires (search / writer) | writer per frame |
123+|---|---|---|
124+| film A long-GOP (192 frames) | 34794 / 873 | 4.5 |
125+| film B long-GOP (192 frames) | 20098 / 186 | 1.0 |
126+| bars 1080p (48 frames) | 4915 / 105 | 2.2 |
127+| bars 2160p (48 frames) | 3144 / 25 | 0.5 |
128+| film A 12f (48 frames) | 7719 / 197 | 4.1 |
129+| film B 12f (48 frames) | 6067 / 75 | 1.6 |
130+| screen capture (48 frames) | 1056 / 85 | 1.8 |
131+
132+The arm FIRES for real — an order of magnitude above the parked
133+whole-128 residual arm (0.4-1.9 writer fires/frame) — and the BD table
134+still moves at most 0.1 in either direction on every row of both gates.
135+The RD finds non-skip rect/AB pieces worth taking; taking them buys
136+nothing measured. The wall deltas (+1-4%) are the extra trial cost.
137+
138+These numbers are the POST-FIX census (commit `8cf40077`): the first
139+arm runs printed structurally-guaranteed zeros because two drain
140+statements zeroed the counters immediately before the census line read
141+them (class `drain-then-read counter` — reviewer catch). Both arm gates
142+were re-run with the fix; the BD tables were byte-identical to the
143+pre-fix arm runs (the fix touches only the census print). The drains
144+inside the witness tests are pre-run hygiene and stay.
145+EVIDENCE: ~/.cache/rectres/longgop-arm2.log | server-2, EC_AV1_RECTRES=1,
146+post-8cf40077 | film A 34794/873, film B 20098/186; BD +20.9/-9.0,
147++70.5/-2.1 (== pre-fix arm). exit=0, 3121.8s.
148+EVIDENCE: ~/.cache/rectres/native-arm2.log | server-2, EC_AV1_RECTRES=1,
149+post-8cf40077 | five rows: 4915/105, 3144/25, 7719/197, 6067/75,
150+1056/85; BD rows == pre-fix arm to the digit. exit=0, 2121.8s.
151+LOADAVG 0.18/0.17/0.44 before, 1.16/1.18/1.07 after.
152+
153+## 4. Keep rule — NOT met; disposition
154+
155+One film row >=0.5 BD down on a column: best delta anywhere is -0.1.
156+Other film row flat within +/-0.3: yes. Screen not worse by 0.3: yes.
157+Wall <= +15%: yes. The deciding column fails — with the arm now known
158+to fire for real, 'BD-neutral on real fires' is the measured verdict,
159+not inertness — the charter's stays-off branch. Default stays OFF; no
160+pins, no suite (default did not flip). `fix-now | deferred(<unblock>)
161+| accepted`: nothing deferred — the measurement asked by the charter is
162+complete; the arm itself stays parked behind `EC_AV1_RECTRES`, witnessed
163+exact, and the census says the pieces ARE taken — a future cost-model
164+change re-measures BD, not fire counts.
165+
166+## 5. Procedure notes (server-2 gates)
167+
168+Three setup snags hit and solved, for the next lane running gates there:
169+`systemd-run --user` units start in $HOME, not the caller's cwd — put the
170+`cd` inside the unit (`--pipe bash -lc 'cd ... && cargo ...'`); the
171+rsync'd worktree's `.git` FILE (a worktree pointer, not covered by
172+`--exclude /.git/`) must be `rm -f .git && git init -q .` on the server or
173+the repo's memguard test-runner (`git rev-parse --show-toplevel`) refuses
174+every test binary; and a failed unit needs
175+`systemctl --user reset-failed <unit>` before the name is reusable.
176+`pkill -f` with the unit name in the pattern kills your own ssh session.
177+
178+## 6. Non-goals respected
179+
180+Main checkout untouched, never pushed/merged, no repo-wide formatters (a
181+scoped rustfmt reflow of the two edited files was fully reverted by
182+restoring HEAD bytes and replaying the semantic edits — the committed diff
183+is semantic-only, 643+/39-), media files read-only, one gate at a time
184+(both locally and on server-2), logs under ~/.cache/rectres/ and
185+/home/user/gates/logs/.