forge
Explore
Log in

Don't you dare go Hollow

The 128 root's rect/AB pieces price a real residual behind EC_AV1_RECTRES -- write_inter_block_128_rect lifts its skip-only refusal and codes one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64 mu chunk (halves and 64x64 squares alike), the rect/AB search arms price the non-skip outcome under the same knob, and cdef_unit_owner extends past Whole128 to the rect/AB pieces that carry a residual (skip-only pieces still write no cdef_idx and never touch the map)

Browse files at this commit

dc098a556353213bff6a238986861ede35f9e61aAhmet Kaan GümüşParent: fbd2ef1
  • feat
    • the 128 root's rect/AB pieces price a real residual behind EC_AV1_RECTRES -- write_inter_block_128_rect lifts its skip-only refusal and codes one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64 mu chunk (halves and 64x64 squares alike), the rect/AB search arms price the non-skip outcome under the same knob, and cdef_unit_owner extends past Whole128 to the rect/AB pieces that carry a residual (skip-only pieces still write no cdef_idx and never touch the map)
    • three forced witnesses run sample-exact through decode_stream AND ffmpeg -- a HORZ half at 840/840 fires, a forced HORZ_A shape at 4620 search / 5760 writer, and a rect half under a per-unit cdef list at 62 covered units, default OFF is today's behavior bit for bit
Show full message
feat(av1): the 128 root's rect/AB pieces price a real residual behind EC_AV1_RECTRES -- write_inter_block_128_rect lifts its skip-only refusal and codes one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64 mu chunk (halves and 64x64 squares alike), the rect/AB search arms price the non-skip outcome under the same knob, and cdef_unit_owner extends past Whole128 to the rect/AB pieces that carry a residual (skip-only pieces still write no cdef_idx and never touch the map); three forced witnesses run sample-exact through decode_stream AND ffmpeg -- a HORZ half at 840/840 fires, a forced HORZ_A shape at 4620 search / 5760 writer, and a rect half under a per-unit cdef list at 62 covered units, default OFF is today's behavior bit for bit
crates/ec-av1/src/encode.rsmodified+425 -10
@@ -752,9 +752,7 @@ fn b128_root() -> bool {
752752 /// the decoder derives, and on this HEAD the same row re-measures three-way
753753 /// EXACT (encoder reconstruction == ffmpeg == `decode_stream`, every frame,
754754 /// every plane, both gates). The knob stays as the arm's gate, not as a
755-/// defect flag; the residual arm is also what
756-/// [`crate::tile::write_inter_block_128_rect`]'s skip-only halves would
757-/// share if they ever carry one.
755+/// defect flag.
758756 fn b128_residual() -> bool {
759757 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
760758 crate::envflags::var("EC_AV1_B128RES").ok().map(|v| v != "0")
@@ -762,6 +760,49 @@ fn b128_residual() -> bool {
762760 (ENV.unwrap_or(false) || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed))
763761 && b128_root()
764762 }
763+/// lane-rectres: whether the 128 root's RECTANGULAR pieces -- the two
764+/// HORZ/VERT halves and the four AB shapes' three pieces (two 64x64 squares
765+/// plus one half) -- price a REAL residual in the RD as well as the skip arm
766+/// ([`search_root_128_rect`] / [`search_root_128_ab`], written through
767+/// [`crate::tile::write_inter_block_128_rect`]). **Off by default**
768+/// (`EC_AV1_RECTRES=1` turns it on): OFF is today's behavior bit for bit --
769+/// no rect/AB piece can come out non-skip, so the writer's refusal is never
770+/// reached. The residual shape is the whole 128 block's, halved or quartered
771+/// per piece: one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
772+/// mu chunk, var-tx depth 0 (exactly what the decoder's mu-chunk loop reads
773+/// for any inter partition shape).
774+fn rectres() -> bool {
775+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
776+ crate::envflags::var("EC_AV1_RECTRES")
777+ .ok()
778+ .map(|v| v != "0")
779+ });
780+ ENV.unwrap_or(false) || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed)
781+}
782+
783+/// Test-only: take the rect/AB pieces' residual arm whatever it costs, so a
784+/// witness clip codes the shape rather than waiting for content on which the
785+/// RD picks it (the same role [`FORCE_B128_RESIDUAL`] plays at the NONE
786+/// root). Never read outside `#[cfg(test)]` builds.
787+static FORCE_B128_RECTRES: std::sync::atomic::AtomicBool =
788+ std::sync::atomic::AtomicBool::new(false);
789+
790+/// Arms [`FORCE_B128_RECTRES`] for the rest of the process.
791+#[cfg(test)]
792+pub(crate) fn force_b128_rectres(on: bool) {
793+ FORCE_B128_RECTRES.store(on, std::sync::atomic::Ordering::Relaxed);
794+}
795+
796+/// How many rect/AB pieces the search left WITH a residual rather than
797+/// skipped, since the last [`take_b128_rectres_hits`] (class
798+/// `gate-blind-to-feature`).
799+static B128_RECTRES_HITS: std::sync::atomic::AtomicUsize =
800+ std::sync::atomic::AtomicUsize::new(0);
801+
802+/// The rect/AB-piece-residual count since the last call, and zero it.
803+pub fn take_b128_rectres_hits() -> usize {
804+ B128_RECTRES_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
805+}
765806
766807 /// lane-b128r: whether the 128 root offers the COMPOUND candidates the 64
767808 /// root already does (`NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`,
@@ -9905,11 +9946,124 @@ fn search_root_128(
99059946 ))
99069947 }
99079948
9949+/// lane-rectres: one rect/AB piece's REAL residual, priced against the skip
9950+/// arm the caller's [`search_skip_64`] just committed to the planes (which
9951+/// IS the winner's prediction, sample for sample -- the same rule
9952+/// [`search_root_128`]'s residual arm runs at the NONE root). The piece's
9953+/// residual is one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
9954+/// mu chunk (two chunks for a 128x64 / 64x128 half, one for a 64x64 square),
9955+/// each trial at sides the forward network already reaches, never a
9956+/// rectangular transform; var-tx depth 0 only -- the units ARE the tree's
9957+/// leaves, exactly what `decode_inter_block`'s mu-chunk loop reads.
9958+///
9959+/// The depth-0 `txfm_partition` symbols the writer codes for the units are
9960+/// not priced, exactly as [`search_root_128`] does not price its four (their
9961+/// contexts are only known at write time); at two symbols a half this is
9962+/// under a bit against residuals of hundreds. On a win (or under the witness
9963+/// force) the trials are committed to the planes, `block` is flipped to
9964+/// carry the packed level grids [`crate::tile::write_inter_block_128_rect`]
9965+/// slices back out, and the new cost is returned; otherwise `cost` passes
9966+/// through untouched. Counts [`take_b128_rectres_hits`] on a win.
9967+#[allow(clippy::too_many_arguments)]
9968+fn search_rect_residual(
9969+ luma: &mut Plane,
9970+ chroma: &mut [Plane; 2],
9971+ // The piece's own top-left, in luma samples.
9972+ (px, py): (usize, usize),
9973+ // Its true footprint: (128, 64) HORZ, (64, 128) VERT, (64, 64) square.
9974+ (w, h): (usize, usize),
9975+ cost: f64,
9976+ lambda: f64,
9977+ search: &Search<'_>,
9978+ // The piece's own mv stack, for the skip symbol's cost either way.
9979+ stack: &crate::mvstack::MvStack,
9980+ block: &mut BlockCoeffs,
9981+) -> f64 {
9982+ /// The 64x64 "mu" chunk side, luma; chroma halves it.
9983+ const MU: usize = SUPERBLOCK;
9984+ let chunks: [(usize, usize); 2] = match (w, h) {
9985+ (128, 64) => [(0, 0), (0, 1)],
9986+ (64, 128) => [(0, 0), (1, 0)],
9987+ _ => [(0, 0), (0, 0)],
9988+ };
9989+ let n = if w.max(h) > MU { 2 } else { 1 };
9990+ // Every unit's coded level grid is 32x32 (a 64-point transform codes
9991+ // only its top-left corner), packed per plane into one 64-wide grid with
9992+ // chunk (cr, cc) at (cr * 32, cc * 32) -- the layout the writer slices
9993+ // back out in the same chunk order.
9994+ let mut packed = [vec![0i32; 64 * 64], vec![0i32; 64 * 64], vec![0i32; 64 * 64]];
9995+ let mut sse_skip = 0.0f64;
9996+ let mut sse_res = 0.0f64;
9997+ let mut coeff_bits = 0.0f64;
9998+ let mut trials_per_chunk: Vec<[Trial; 3]> = Vec::with_capacity(n);
9999+ for &(cr, cc) in &chunks[..n] {
10000+ let (cxx, cyy) = (px + cc * MU, py + cr * MU);
10001+ let (cx, cy) = (cxx / 2, cyy / 2);
10002+ let half = MU / 2;
10003+ let pred_y = rows_of(&luma.reconstruction, luma.width, cxx, cyy, MU);
10004+ let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
10005+ let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
10006+ sse_skip += luma.block_sse(cxx, cyy, MU, &pred_y)
10007+ + chroma[0].block_sse(cx, cy, half, &pred_u)
10008+ + chroma[1].block_sse(cx, cy, half, &pred_v);
10009+ let trials = [
10010+ luma.code_from_prediction(
10011+ cxx, cyy, MU, &pred_y, false, search.base_q_idx, search.deadzone,
10012+ TxbSet::Luma64,
10013+ ),
10014+ chroma[0].code_from_prediction(
10015+ cx, cy, half, &pred_u, false, search.base_q_idx, search.deadzone,
10016+ TxbSet::Chroma32,
10017+ ),
10018+ chroma[1].code_from_prediction(
10019+ cx, cy, half, &pred_v, false, search.base_q_idx, search.deadzone,
10020+ TxbSet::Chroma32,
10021+ ),
10022+ ];
10023+ for (plane, trial) in trials.iter().enumerate() {
10024+ sse_res += trial.sse;
10025+ coeff_bits += trial.bits;
10026+ for row in 0..32 {
10027+ packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
10028+ .copy_from_slice(&trial.levels[row * 32..][..32]);
10029+ }
10030+ }
10031+ trials_per_chunk.push(trials);
10032+ }
10033+ // `cost` is the skip arm's own `sse + lambda * syntax`; the residual arm
10034+ // pays the same syntax with `skip` coded 0 instead of 1, plus its
10035+ // coefficients.
10036+ let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
10037+ let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
10038+ if res_cost < cost || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed) {
10039+ for (trials, &(cr, cc)) in trials_per_chunk.iter().zip(&chunks[..n]) {
10040+ let (cxx, cyy) = (px + cc * MU, py + cr * MU);
10041+ let (cx, cy) = (cxx / 2, cyy / 2);
10042+ let half = MU / 2;
10043+ luma.commit(cxx, cyy, MU, &trials[0]);
10044+ chroma[0].commit(cx, cy, half, &trials[1]);
10045+ chroma[1].commit(cx, cy, half, &trials[2]);
10046+ }
10047+ block.skip = false;
10048+ block.tx_depth = 0;
10049+ block.luma_tx_types = Vec::new();
10050+ block.luma = coeffs(&packed[0], 64);
10051+ block.u = coeffs(&packed[1], 64);
10052+ block.v = coeffs(&packed[2], 64);
10053+ B128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10054+ res_cost
10055+ } else {
10056+ cost
10057+ }
10058+}
10059+
990810060 /// lane-b128hv: the `PARTITION_HORZ` / `PARTITION_VERT` candidate for a whole
990910061 /// 128 superblock root -- two 128x64 (`horz`) or 64x128 inter blocks, the
9910-/// shipped NONE machinery halved. Skip only, single reference or compound,
9911-/// exactly what `crate::tile::write_inter_block_128_rect` codes and
9912-/// `decode_inter_block` reads at `sb128_rect`.
10062+/// shipped NONE machinery halved. Skip-only by default, single reference or
10063+/// compound; under `EC_AV1_RECTRES` each half also prices a REAL residual
10064+/// ([`search_rect_residual`]) -- exactly what
10065+/// `crate::tile::write_inter_block_128_rect` codes and `decode_inter_block`
10066+/// reads at `sb128_rect`.
991310067 ///
991410068 /// The FIRST half is published into `grid` before the second is searched --
991510069 /// the writer publishes it too, so a second half searched against the stale
@@ -10041,7 +10195,23 @@ fn search_root_128_rect(
1004110195 fctx,
1004210196 );
1004310197 match found {
10044- Some((c, block)) => {
10198+ Some((mut c, mut block)) => {
10199+ // lane-rectres: the same prediction with a REAL residual,
10200+ // priced against the skip arm the search just committed to
10201+ // the planes -- two 64x64 mu chunks for a half.
10202+ if rectres() && block.skip {
10203+ c = search_rect_residual(
10204+ luma,
10205+ chroma,
10206+ (mc * 4, mr * 4),
10207+ (w, h),
10208+ c,
10209+ root_search.lambda,
10210+ &root_search,
10211+ &stack,
10212+ &mut block,
10213+ );
10214+ }
1004510215 cost += c;
1004610216 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
1004710217 halves.push(block);
@@ -10081,8 +10251,9 @@ fn search_root_128_rect(
1008110251 /// `encoder-grid-drift-invisible-to-pixel-gate`). The grid and both planes
1008210252 /// are put back before returning; the caller re-applies the winner.
1008310253 ///
10084-/// SKIP only, for the reason [`search_root_128_rect`] gives: the 128 residual
10085-/// arm the pieces would share is itself parked behind `EC_AV1_B128RES`.
10254+/// Skip-only by default; under `EC_AV1_RECTRES` each piece also prices a
10255+/// REAL residual ([`search_rect_residual`]) -- the 64x64 squares are where
10256+/// libaom's own AB shapes earn their keep.
1008610257 ///
1008710258 /// Returns `(cost, lambda, the three pieces, reconstruction)`, the cost
1008810259 /// already carrying the root's own partition symbol so it ranks against the
@@ -10197,7 +10368,25 @@ fn search_root_128_ab(
1019710368 fctx,
1019810369 );
1019910370 match found {
10200- Some((c, block)) => {
10371+ Some((mut c, mut block)) => {
10372+ // lane-rectres: the same prediction with a REAL residual,
10373+ // priced against the skip arm the search just committed to
10374+ // the planes -- one mu chunk for a 64x64 square, two for a
10375+ // half. The 64x64 squares are where libaom's own AB shapes
10376+ // earn their keep.
10377+ if rectres() && block.skip {
10378+ c = search_rect_residual(
10379+ luma,
10380+ chroma,
10381+ (mc * 4, mr * 4),
10382+ (w, h),
10383+ c,
10384+ root_search.lambda,
10385+ &root_search,
10386+ &stack,
10387+ &mut block,
10388+ );
10389+ }
1020110390 cost += c;
1020210391 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
1020310392 pieces.push(block);
@@ -17253,6 +17442,227 @@ mod tests {
1725317442 }
1725417443 }
1725517444
17445+ /// lane-rectres: a `PARTITION_HORZ` 128 root whose two 128x64 halves
17446+ /// CARRY A RESIDUAL -- the mu-chunk shape (one TX_64X64 luma unit plus a
17447+ /// TX_32X32 chroma pair per chunk) `write_inter_block_128_rect` now
17448+ /// codes under `EC_AV1_RECTRES`, at the footprint the decoder's own
17449+ /// mu-chunk loop reads. The arm is FORCED ([`force_b128_rectres`], the
17450+ /// rect partition with [`force_b128_rect`]) so every inter root of the
17451+ /// clip goes through it; the `coded > 0` assert is the guard that catches
17452+ /// the next fixture drift (the whole-128 twin of this witness went RED
17453+ /// twice that way).
17454+ ///
17455+ /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17456+ /// encode::tests::a_rect128_half_with_a_real_residual --nocapture
17457+ #[test]
17458+ #[ignore = "sets the process-global superblock size: run it alone"]
17459+ fn a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders() {
17460+ let _knobs = crate::speed::knob_write();
17461+ if !have_ffmpeg() {
17462+ eprintln!("SKIP: no ffmpeg");
17463+ return;
17464+ }
17465+ force_sb128(true);
17466+ let dir = std::env::temp_dir().join(format!("ec-av1-rectres-{}", std::process::id()));
17467+ std::fs::create_dir_all(&dir).unwrap();
17468+ let clip = dir.join("smpte-pan-1280x768.y4m");
17469+ let ok = Command::new("ffmpeg")
17470+ .args(["-v", "error", "-y", "-f", "lavfi"])
17471+ .args(["-i", "smptebars=size=1600x768:rate=24"])
17472+ .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
17473+ .args(["-pix_fmt", "yuv420p"])
17474+ .arg(&clip)
17475+ .status()
17476+ .expect("ffmpeg failed to run")
17477+ .success();
17478+ assert!(ok, "ffmpeg could not write the synthetic clip");
17479+ let (width, height) = (1280usize, 768usize);
17480+ let pictures =
17481+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
17482+ force_b128_rect(1);
17483+ force_b128_rectres(true);
17484+ let _ = take_b128_rectres_hits();
17485+ let _ = crate::tile::take_sb128_rectres_hits();
17486+ let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
17487+ let (won, coded) =
17488+ (take_b128_rectres_hits(), crate::tile::take_sb128_rectres_hits());
17489+ eprintln!("rect halves WITH a residual: search won {won}, writer coded {coded}");
17490+ assert!(
17491+ coded > 0,
17492+ "no 128x64 half carried a residual on this clip, so it cannot witness the arm",
17493+ );
17494+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17495+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17496+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17497+ let recon = &frame.reconstruction;
17498+ for (plane, got, want) in [
17499+ ("luma", &dec.y, &recon.y),
17500+ ("U", &dec.u, &recon.u),
17501+ ("V", &dec.v, &recon.v),
17502+ ] {
17503+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17504+ assert_eq!(
17505+ differ, 0,
17506+ "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17507+ own reconstruction",
17508+ got.len()
17509+ );
17510+ }
17511+ }
17512+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17513+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17514+ assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17515+ assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17516+ assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17517+ }
17518+ }
17519+
17520+ /// lane-rectres: an AB shape (`PARTITION_HORZ_A` forced) whose THREE
17521+ /// pieces carry residuals -- the 128x64 half through the two-chunk arm,
17522+ /// the two 64x64 squares through the one-chunk arm (the shape libaom's
17523+ /// own AB partitions earn their keep with). testsrc2 at 12 frames, the
17524+ /// shipped AB witness's own recipe: an 8-frame clip parks an ARF whose
17525+ /// reference picture the GOP has not produced yet, which refuses before
17526+ /// any AB root is coded.
17527+ ///
17528+ /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17529+ /// encode::tests::an_ab128_piece_with_a_real_residual --nocapture
17530+ #[test]
17531+ #[ignore = "sets the process-global superblock size: run it alone"]
17532+ fn an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders() {
17533+ let _knobs = crate::speed::knob_write();
17534+ if !have_ffmpeg() {
17535+ eprintln!("SKIP: no ffmpeg");
17536+ return;
17537+ }
17538+ force_sb128(true);
17539+ let dir = std::env::temp_dir().join(format!("ec-av1-rectres-ab-{}", std::process::id()));
17540+ std::fs::create_dir_all(&dir).unwrap();
17541+ let clip = dir.join("testsrc2-1280x768.y4m");
17542+ let ok = Command::new("ffmpeg")
17543+ .args(["-v", "error", "-y", "-f", "lavfi"])
17544+ .args(["-i", "testsrc2=size=1280x768:rate=24"])
17545+ .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17546+ .arg(&clip)
17547+ .status()
17548+ .expect("ffmpeg failed to run")
17549+ .success();
17550+ assert!(ok, "ffmpeg could not write the synthetic clip");
17551+ let (width, height) = (1280usize, 768usize);
17552+ let pictures =
17553+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17554+ force_b128_ab(4);
17555+ force_b128_rectres(true);
17556+ let _ = take_b128_rectres_hits();
17557+ let _ = crate::tile::take_sb128_rectres_hits();
17558+ let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
17559+ let (won, coded) =
17560+ (take_b128_rectres_hits(), crate::tile::take_sb128_rectres_hits());
17561+ eprintln!("AB pieces WITH a residual: search won {won}, writer coded {coded}");
17562+ assert!(
17563+ coded > 0,
17564+ "no AB piece carried a residual on this clip, so it cannot witness the arm",
17565+ );
17566+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17567+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17568+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17569+ let recon = &frame.reconstruction;
17570+ for (plane, got, want) in [
17571+ ("luma", &dec.y, &recon.y),
17572+ ("U", &dec.u, &recon.u),
17573+ ("V", &dec.v, &recon.v),
17574+ ] {
17575+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17576+ assert_eq!(
17577+ differ, 0,
17578+ "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17579+ own reconstruction",
17580+ got.len()
17581+ );
17582+ }
17583+ }
17584+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17585+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17586+ assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17587+ assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17588+ assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17589+ }
17590+ }
17591+
17592+ /// lane-rectres, lane-edge128's interaction on the rect shapes: a HORZ
17593+ /// half WITH a residual under a clip whose CDEF search codes a
17594+ /// per-64x64 `cdef_idx` list. The half codes ONE literal at its origin
17595+ /// and the decoder stamps BOTH units it spans with it, so the owner map
17596+ /// ([`crate::tile::cdef_unit_owner`], now extended past Whole128) has to
17597+ /// collapse the pair -- exactly the bug class that broke bars 2160p at
17598+ /// the whole-128 root. RED before this lane by construction: no rect
17599+ /// piece could carry a residual, so no such literal existed.
17600+ ///
17601+ /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17602+ /// encode::tests::a_rect128_residual_half_under_a_per_unit_cdef --nocapture
17603+ #[test]
17604+ #[ignore = "sets the process-global superblock size: run it alone"]
17605+ fn a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact() {
17606+ let _knobs = crate::speed::knob_write();
17607+ if !have_ffmpeg() {
17608+ eprintln!("SKIP: no ffmpeg");
17609+ return;
17610+ }
17611+ force_sb128(true);
17612+ let dir = std::env::temp_dir().join(format!("ec-av1-rectres-cdef-{}", std::process::id()));
17613+ std::fs::create_dir_all(&dir).unwrap();
17614+ let clip = dir.join("testsrc2-1280x768.y4m");
17615+ // Detailed synthetic content: its CDEF search spends more than one
17616+ // strength pair, which is what puts a `cdef_idx` literal in the tile.
17617+ let ok = Command::new("ffmpeg")
17618+ .args(["-v", "error", "-y", "-f", "lavfi"])
17619+ .args(["-i", "testsrc2=size=1280x768:rate=24"])
17620+ .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17621+ .arg(&clip)
17622+ .status()
17623+ .expect("ffmpeg failed to run")
17624+ .success();
17625+ assert!(ok, "ffmpeg could not write the synthetic clip");
17626+ let (width, height) = (1280usize, 768usize);
17627+ let pictures =
17628+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17629+ force_b128_rect(1);
17630+ force_b128_rectres(true);
17631+ let _ = crate::tile::take_sb128_rectres_hits();
17632+ let _ = crate::filter_search::take_cdef_covered_units();
17633+ let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
17634+ let coded = crate::tile::take_sb128_rectres_hits();
17635+ let covered = crate::filter_search::take_cdef_covered_units();
17636+ eprintln!(
17637+ "rect halves WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
17638+ another unit's literal: {covered}"
17639+ );
17640+ assert!(coded > 0, "no 128x64 half carried a residual on this clip");
17641+ assert!(
17642+ covered > 0,
17643+ "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
17644+ cannot witness the rule",
17645+ );
17646+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17647+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17648+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17649+ for (plane, got, want) in [
17650+ ("luma", &dec.y, &frame.reconstruction.y),
17651+ ("U", &dec.u, &frame.reconstruction.u),
17652+ ("V", &dec.v, &frame.reconstruction.v),
17653+ ] {
17654+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17655+ assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
17656+ }
17657+ }
17658+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17659+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17660+ assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17661+ assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17662+ assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17663+ }
17664+ }
17665+
1725617666 /// lane-b128r: the COMPOUND arm at the 128 root -- one 128x128 block
1725717667 /// naming `LAST` plus `GOLDEN`/`ALTREF`, through the same
1725817668 /// `write_compound_block` chain every smaller compound block takes, at a
@@ -20248,13 +20658,18 @@ mod tests {
2024820658 {i64_edge} on a superblock the frame edge cuts",
2024920659 100.0 * i64_whole as f64 / i64_offered.max(1) as f64,
2025020660 );
20661+ let _ = take_b128_rectres_hits();
20662+ let _ = crate::tile::take_sb128_rectres_hits();
2025120663 eprintln!(
2025220664 "{name}: 128x128 roots {} (search) / {} (writer), with a residual \
20665+ {} (search) / {} (writer); rect/AB pieces with a residual \
2025320666 {} (search) / {} (writer)",
2025420667 take_b128_none_hits(),
2025520668 crate::tile::take_sb128_none_hits(),
2025620669 take_b128_residual_hits(),
2025720670 crate::tile::take_sb128_residual_hits(),
20671+ take_b128_rectres_hits(),
20672+ crate::tile::take_sb128_rectres_hits(),
2025820673 );
2025920674 eprintln!(
2026020675 "{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.