forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-b128m' (14c23a84): 128x128 superblocks on by default; delta_q coded once per 128 root, filter context copy carries the superblock size, intrabc predictor by superblock size, encode-then-decode gates use the encoder context; pins re-taken at the merge 8354 / 33222

Browse files at this commit

a4a0871c008c4cac245ffefac80812b590d03f42Ahmet Kaan GümüşParent: 7c94ff1e7bbd0f
crates/ec-av1/src/decode.rsmodified+17 -10
@@ -275,6 +275,13 @@ pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx {
275275 out.seg_mi_dims.set(fctx.seg_mi_dims.get());
276276 out.seg.replace(fctx.seg.borrow().clone());
277277 out.seg_ids.replace(fctx.seg_ids.borrow().clone());
278+ // lane-b128m: the superblock size travels with the copy. A tile SEARCH
279+ // worker (`encode::search_tiles`) gets its context from here, so dropping
280+ // it made every worker search at 64 while the calling thread searched at
281+ // 128 -- the bytes a frame came out as then depended on the tile thread
282+ // count under `EC_AV1_SB128`.
283+ out.sb128_flag.set(fctx.sb128_flag.get());
284+ out.reach_sb_px.set(fctx.reach_sb_px.get());
278285 out
279286 }
280287
@@ -38625,7 +38632,7 @@ mod tests {
3862538632
3862638633 #[test]
3862738634 fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {
38628- let fctx = &crate::decode::FrameCtx::new();
38635+ let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below)
3862938636 for (w, h) in [(128usize, 128usize), (192, 128)] {
3863038637 round_trips(w, h, &[DC_PRED as u8], fctx);
3863138638 }
@@ -38637,7 +38644,7 @@ mod tests {
3863738644 /// decoder round adds, not just `DC_PRED`.
3863838645 #[test]
3863938646 fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() {
38640- let fctx = &crate::decode::FrameCtx::new();
38647+ let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below)
3864138648 for (w, h) in [(128usize, 128usize), (192, 128)] {
3864238649 round_trips(w, h, &crate::intra::KEY_FRAME_MODES, fctx);
3864338650 }
@@ -38648,7 +38655,7 @@ mod tests {
3864838655 /// this decoder round adds.
3864938656 #[test]
3865038657 fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
38651- let fctx = &crate::decode::FrameCtx::new();
38658+ let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: encodes, so the decode context takes this process's superblock size
3865238659 for (w, h) in [(854usize, 480usize), (216, 96)] {
3865338660 round_trips(w, h, &crate::intra::KEY_FRAME_MODES, fctx);
3865438661 }
@@ -38662,7 +38669,7 @@ mod tests {
3866238669 /// bit, `partition_w8` leaves).
3866338670 #[test]
3866438671 fn leaf8_straddle_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
38665- let fctx = &crate::decode::FrameCtx::new();
38672+ let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below)
3866638673 for (w, h) in [(40usize, 32usize), (640, 360)] {
3866738674 round_trips(w, h, &crate::intra::KEY_FRAME_MODES, fctx);
3866838675 }
@@ -38958,7 +38965,7 @@ mod tests {
3895838965 /// crate's own writer and reader could otherwise share.
3895938966 #[test]
3896038967 fn ffmpeg_and_this_decoder_agree_on_a_key_frame() {
38961- let fctx = &crate::decode::FrameCtx::new();
38968+ let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below)
3896238969 if !have_ffmpeg() {
3896338970 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg");
3896438971 return;
@@ -39005,7 +39012,7 @@ mod tests {
3900539012 /// between the palette colours and the colour-index maps).
3900639013 #[test]
3900739014 fn a_filter_intra_key_frame_decodes_pixel_exact_through_ffmpeg() {
39008- let fctx = &crate::decode::FrameCtx::new();
39015+ let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below)
3900939016 if !crate::encode::filter_intra_on() {
3901039017 eprintln!("SKIP a_filter_intra_key_frame...: EC_AV1_FILTER_INTRA=0");
3901139018 return;
@@ -39075,7 +39082,7 @@ mod tests {
3907539082 /// wire).
3907639083 #[test]
3907739084 fn a_key_frames_tile_needs_the_headers_own_tx_select_bit() {
39078- let fctx = &crate::decode::FrameCtx::new();
39085+ let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: encodes, so the decode context takes this process's superblock size
3907939086 use crate::encode::encode_key_frame_with_ctx;
3908039087 let (width, height) = (64usize, 64usize);
3908139088 let picture = round_trip_test_card(width, height);
@@ -39275,7 +39282,7 @@ mod tests {
3927539282
3927639283 #[test]
3927739284 fn a_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
39278- let fctx = &crate::decode::FrameCtx::new();
39285+ let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below)
3927939286 gop_round_trips(128, 64, fctx);
3928039287 }
3928139288
@@ -39284,7 +39291,7 @@ mod tests {
3928439291 /// split path is exercised too.
3928539292 #[test]
3928639293 fn an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction() {
39287- let fctx = &crate::decode::FrameCtx::new();
39294+ let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below)
3928839295 gop_round_trips(216, 96, fctx);
3928939296 }
3929039297
@@ -39514,7 +39521,7 @@ mod tests {
3951439521
3951539522 #[test]
3951639523 fn ffmpeg_and_this_decoder_agree_on_a_gop() {
39517- let fctx = &crate::decode::FrameCtx::new();
39524+ let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: this test ENCODES, so its decode context starts at the superblock size this process encodes at (stale-header class, as `filter_intra_on` below)
3951839525 if !have_ffmpeg() {
3951939526 eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg");
3952039527 return;
crates/ec-av1/src/encode.rsmodified+453 -23
@@ -722,6 +722,27 @@ pub fn take_b64_root_hits() -> usize {
722722 B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
723723 }
724724
725+/// Whether the 128 superblock root offers its `PARTITION_NONE` candidate at
726+/// all ([`search_root_128`]). On by default; `EC_AV1_B128=0` turns it off,
727+/// which is the attribution arm for a 128-superblock stream: it separates
728+/// what the SIZE costs from what the 128x128 BLOCK buys.
729+fn b128_root() -> bool {
730+ static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
731+ crate::envflags::var("EC_AV1_B128").ok().is_none_or(|v| v != "0")
732+ });
733+ *ENV
734+}
735+
736+/// How many 128x128 `PARTITION_NONE` roots the search took since the last
737+/// [`take_b128_none_hits`] (class `gate-blind-to-feature`): a flat BD result
738+/// is only attributable once the fire count is known.
739+static B128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
740+
741+/// The 128x128-root count since the last call, and zero it.
742+pub fn take_b128_none_hits() -> usize {
743+ B128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
744+}
745+
725746 /// Rate-distortion optimised quantisation ([`crate::tile::rdoq`], lane-rdoq).
726747 /// Preset-gated: it re-prices the block once per candidate level, so it buys
727748 /// bits with wall (see `crate::speed::RDOQ` for the per-preset table).
@@ -5140,7 +5161,9 @@ fn intrabc_step() -> usize {
51405161 const IBC_HASH: usize = 16;
51415162
51425163 /// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind
5143-/// the current one the source's bottom-right corner must already be.
5164+/// the current one the source's bottom-right corner must already be. Under
5165+/// 128 superblocks the same 256 pixels are two superblocks, which
5166+/// [`Ibc::dv_valid`] derives from the size itself.
51445167 const INTRABC_DELAY_SB64: i32 = 4;
51455168
51465169 /// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`.
@@ -5276,22 +5299,28 @@ impl Ibc {
52765299 if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 {
52775300 return false;
52785301 }
5279- let active_sb_row = (y as i32 - ty0) >> 6;
5280- let active_sb_col = (x as i32 - tx0) >> 6;
5281- let src_sb_row = (sy + h - 1 - ty0) >> 6;
5282- let src_sb_col = (sx + w - 1 - tx0) >> 6;
5302+ // lane-b128m: libaom counts this wavefront in SUPERBLOCKS, and the
5303+ // superblock is 128 wide under `EC_AV1_SB128` (`INTRABC_DELAY_SB =
5304+ // INTRABC_DELAY_PIXELS >> sb_size_log2`, i.e. 2 there and 4 here).
5305+ // Counting 64s under a 128 superblock let the search take a source
5306+ // from a 64 row the 128 visit order had not reconstructed yet.
5307+ let sb_log2 = if crate::encode::sb128_on() { 7 } else { 6 };
5308+ let delay: i32 = if sb_log2 == 7 { INTRABC_DELAY_SB64 / 2 } else { INTRABC_DELAY_SB64 };
5309+ let active_sb_row = (y as i32 - ty0) >> sb_log2;
5310+ let active_sb_col = (x as i32 - tx0) >> sb_log2;
5311+ let src_sb_row = (sy + h - 1 - ty0) >> sb_log2;
5312+ let src_sb_col = (sx + w - 1 - tx0) >> sb_log2;
52835313 // This lane's own restriction (see the doc comment).
52845314 if src_sb_row >= active_sb_row {
52855315 return false;
52865316 }
5287- let total = ((tx1 - tx0 - 1) >> 6) + 1;
5288- if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - INTRABC_DELAY_SB64
5289- {
5317+ let total = ((tx1 - tx0 - 1) >> sb_log2) + 1;
5318+ if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - delay {
52905319 return false;
52915320 }
52925321 // libaom's wavefront: only the top-left cone of the frame is legal.
5293- let wf = (1 + INTRABC_DELAY_SB64) * (active_sb_row - src_sb_row);
5294- src_sb_col < active_sb_col - INTRABC_DELAY_SB64 + wf
5322+ let wf = (1 + delay) * (active_sb_row - src_sb_row);
5323+ src_sb_col < active_sb_col - delay + wf
52955324 }
52965325 }
52975326
@@ -5872,11 +5901,36 @@ fn cfl_on() -> bool {
58725901 /// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured
58735902 /// its own on/off pair -- and how every byte pin written before it still
58745903 /// reproduces). It is also a speed lever: on at preset 0, off above it.
5875-// lane-sb128: `use_128x128_superblock` (spec 5.5.1). Off by default until
5876-// the BD gate says otherwise; `EC_AV1_SB128=1` turns it on for the whole
5877-// process (a sequence-header field, so it cannot change mid-stream anyway),
5878-// the same env-flag shape `EC_AV1_FILTER_INTRA` uses. NOT an `EncoderConfig`
5879-// field: that struct is built by 90 literal sites in this workspace.
5904+// lane-sb128: `use_128x128_superblock` (spec 5.5.1). `EC_AV1_SB128=0` turns
5905+// it off for the whole process (a sequence-header field, so it cannot change
5906+// mid-stream anyway), the same env-flag shape `EC_AV1_FILTER_INTRA` uses.
5907+// NOT an `EncoderConfig` field: that struct is built by 90 literal sites in
5908+// this workspace.
5909+
5910+/// Whether a sequence codes 128x128 superblocks when the environment says
5911+/// nothing. ON since lane-b128 gave the 128 root a real `PARTITION_NONE`
5912+/// candidate ([`search_root_128`]): with SPLIT-only roots the size was pure
5913+/// cost (lane-sb128b measured film B +24.9 -> +37.5 vs libaom), and with the
5914+/// 128x128 block in it every row of the native BD gate is down or flat on
5915+/// both columns (BD-rate vs libaom cpu-6 / rav1e s6, 12 frames):
5916+///
5917+/// | row | 64 superblocks | 128 + the 128 root |
5918+/// |---|---|---|
5919+/// | bars 1080p | -3.1 / -18.7 | **-3.7 / -19.2** |
5920+/// | bars 2160p | +9.1 / -13.3 | **+8.5 / -13.8** |
5921+/// | film A | +20.3 / -5.0 | **+20.1 / -5.2** |
5922+/// | film B | +24.6 / -2.0 | **+24.3 / -2.2** |
5923+/// | screen capture | +14.6 / -33.2 | **+14.4 / -33.2** |
5924+///
5925+/// and the long-GOP gate agrees (film A +24.0/-7.6 -> +23.6/-7.9, film B
5926+/// +85.8/+7.1 -> +85.1/+6.6). Both arms re-run on lane-b128m's own base.
5927+///
5928+/// ON since lane-b128m closed the eleven 128-superblock desyncs that held it
5929+/// off (the delta_q unit at the 128 superblock, the superblock size travelling
5930+/// with a `FrameCtx` copy into a tile search worker, the writer's intrabc DV
5931+/// predictor and wavefront, and seven test harnesses that handed the encoder a
5932+/// 64-superblock context). `EC_AV1_SB128=0` turns it off.
5933+pub(crate) const SB128_DEFAULT: bool = true;
58805934
58815935 /// Whether this process's sequences code 128x128 superblocks. An ENCODER
58825936 /// knob (like `speed::SPEED`), never read by a decode: read through a
@@ -5889,7 +5943,9 @@ pub(crate) fn sb128_on() -> bool {
58895943 use std::sync::atomic::Ordering::Relaxed;
58905944 match ENC_SB128.load(Relaxed) {
58915945 2 => {
5892- let on = crate::envflags::var("EC_AV1_SB128").ok().is_some_and(|v| v != "0");
5946+ let on = crate::envflags::var("EC_AV1_SB128")
5947+ .ok()
5948+ .map_or(SB128_DEFAULT, |v| v != "0");
58935949 ENC_SB128.store(u8::from(on), Relaxed);
58945950 on
58955951 }
@@ -9300,6 +9356,113 @@ fn predict_compound_u8(
93009356 blended.iter().map(|&v| v as u8).collect()
93019357 }
93029358
9359+/// lane-b128: the 128x128 `PARTITION_NONE` candidate for a whole 128
9360+/// superblock root, the lever cen3's L1 asks for -- one block, one mode and
9361+/// one motion vector where the four 64x64 roots below spend four of each.
9362+///
9363+/// SKIP only (`residual: false`): a 128x128 block's residual is four
9364+/// TX_64X64 luma units interleaved with a TX_32X32 chroma pair per 64x64 mu
9365+/// chunk, which neither the writer nor [`Plane::code_from_prediction`] has a
9366+/// path for -- offering one here would price a block
9367+/// [`crate::tile::write_inter_block_128`] refuses. Single reference only for
9368+/// the same reason: the compound arm at this size is untested against the
9369+/// writer's own `write_compound_block` window.
9370+///
9371+/// Only a root whose whole 128x128 lies inside the true frame AND inside
9372+/// this tile is offered: the writer's own root codes `PARTITION_NONE` only
9373+/// where the spec's `has_rows`/`has_cols` are both set, and a straddling
9374+/// block would have to be ranked over its inside part alone.
9375+///
9376+/// Returns `(cost, lambda, block, reconstruction)` -- the cost already
9377+/// carries the root's own `PARTITION_NONE` symbol, so the caller weighs it
9378+/// against the four superblocks plus the SPLIT symbol.
9379+#[allow(clippy::too_many_arguments)]
9380+fn search_root_128(
9381+ luma: &mut Plane,
9382+ chroma: &mut [Plane; 2],
9383+ grid: &crate::mvstack::MiGrid,
9384+ (root_r, root_c): (usize, usize),
9385+ // The 32x32-block grid this tile's `blocks` vector is indexed on.
9386+ (rows, cols): (usize, usize),
9387+ // The frame's own mode-info grid, which bounds the root.
9388+ (mi_cols, mi_rows): (u32, u32),
9389+ search: Search<'_>,
9390+ tpl_factors: &Option<Vec<f64>>,
9391+ sb_q: Option<&Vec<u8>>,
9392+ sb_cols: usize,
9393+ tpl_cells_x: usize,
9394+ base_q_idx: u8,
9395+ reference: &Picture,
9396+ fctx: &crate::decode::FrameCtx,
9397+) -> Option<(f64, f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> {
9398+ const SIDE: usize = SUPERBLOCK * 2;
9399+ const SIDE_MI: usize = SIDE / 4;
9400+ let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
9401+ let (mi_row, mi_col) = (root_r * 16, root_c * 16);
9402+ if root_r * 2 + 3 >= rows
9403+ || root_c * 2 + 3 >= cols
9404+ || (mi_row + SIDE_MI) as u32 > mi_rows
9405+ || (mi_col + SIDE_MI) as u32 > mi_cols
9406+ || x128 + SIDE > luma.true_width
9407+ || y128 + SIDE > luma.true_height
9408+ {
9409+ return None;
9410+ }
9411+ // One lambda for the whole root, the mean of what its four superblocks
9412+ // would each be searched at -- the 128-vs-four comparison weighs one cost
9413+ // against four, so both sides have to be priced at the same lambda (the
9414+ // same rule the 64 root's own mean-of-sixteen tpl cells follows).
9415+ let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
9416+ (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
9417+ (None, Some(f)) => {
9418+ let mean = (0..16)
9419+ .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
9420+ .sum::<f64>()
9421+ / 16.0;
9422+ search.lambda * mean
9423+ }
9424+ (None, None) => search.lambda,
9425+ };
9426+ let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
9427+ .iter()
9428+ .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
9429+ .sum::<f64>()
9430+ / 4.0;
9431+ let root_search = Search { lambda, ..search };
9432+ let stack = find_mv_stack(
9433+ grid,
9434+ mi_row,
9435+ mi_col,
9436+ SIDE_MI,
9437+ SIDE_MI,
9438+ LAST_FRAME,
9439+ mi_cols as usize,
9440+ mi_rows as usize,
9441+ );
9442+ let base = snapshot(luma, chroma, (x128, y128), SIDE);
9443+ let found = search_skip_64(
9444+ luma,
9445+ chroma,
9446+ (x128, y128),
9447+ SIDE,
9448+ &root_search,
9449+ false,
9450+ reference,
9451+ &stack,
9452+ &[],
9453+ fctx,
9454+ );
9455+ let (cost, block) = found?;
9456+ let after = snapshot(luma, chroma, (x128, y128), SIDE);
9457+ restore(luma, chroma, (x128, y128), SIDE, &base);
9458+ Some((
9459+ cost + lambda * crate::tile::partition_bits(SIDE, false),
9460+ lambda,
9461+ block,
9462+ after,
9463+ ))
9464+}
9465+
93039466 /// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):
93049467 /// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded
93059468 /// SKIP, priced through the same `symbol_bits` path every other candidate
@@ -9314,6 +9477,12 @@ fn search_skip_64(
93149477 luma: &mut Plane,
93159478 chroma: &mut [Plane; 2],
93169479 (x, y): (usize, usize),
9480+ // The root's side in samples: [`SUPERBLOCK`] at a 64 root, twice that at
9481+ // the 128 one [`search_root_128`] drives (lane-b128). Every trial below
9482+ // is a square of this side and its half in chroma, and the residual arm
9483+ // is only ever asked for at 64 -- a 128 block's residual is four
9484+ // TX_64X64 units the writer has no path for.
9485+ side: usize,
93179486 search: &Search,
93189487 // Whether the non-skip arm is priced at all ([`b64_residual`], and off on
93199488 // screen content -- see that function's doc).
@@ -9326,7 +9495,7 @@ fn search_skip_64(
93269495 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
93279496 fctx: &crate::decode::FrameCtx,
93289497 ) -> Option<(f64, BlockCoeffs)> {
9329- let side = SUPERBLOCK;
9498+ debug_assert!(side == SUPERBLOCK || !residual, "a 128 root has no residual arm");
93309499 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
93319500 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
93329501 let ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
@@ -11804,7 +11973,21 @@ pub(crate) fn encode_inter_frame(
1180411973 let sb_q: Option<Vec<u8>> = match (&tpl_factors, deltaq_res) {
1180511974 (Some(f), Some(res)) => {
1180611975 let libaom = dq_tpl_strength(dq_level);
11807- Some((0..sb_cols * _sb_rows).map(|sb| sb_qindex(f, res, sb, libaom)).collect())
11976+ let mut g: Vec<u8> =
11977+ (0..sb_cols * _sb_rows).map(|sb| sb_qindex(f, res, sb, libaom)).collect();
11978+ // lane-b128m: under 128 superblocks the delta_q syntax is coded
11979+ // ONCE per 128 root (the reader's own unit), so all four 64x64
11980+ // cells of a root have to be searched -- and quantized -- at the
11981+ // one qindex the root's top-left cell codes.
11982+ if sb128_on() {
11983+ for sb_r in 0.._sb_rows {
11984+ for sb_c in 0..sb_cols {
11985+ let q = g[(sb_r & !1) * sb_cols + (sb_c & !1)];
11986+ g[sb_r * sb_cols + sb_c] = q;
11987+ }
11988+ }
11989+ }
11990+ Some(g)
1180811991 }
1180911992 _ => None,
1181011993 };
@@ -11904,8 +12087,63 @@ pub(crate) fn encode_inter_frame(
1190412087 rect.mi_col1 as usize,
1190512088 );
1190612089 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
11907- for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize {
11908- for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize {
12090+ // lane-b128: under a 128x128 superblock the search walks the roots the
12091+ // WRITER walks (`tile::sb_write_order`: TL, TR, BL, BR inside each root),
12092+ // not plain raster -- a search that visits BL before TR builds every mv
12093+ // stack and neighbour context off blocks the writer has not coded yet,
12094+ // which is what made the write-time drl clamp fire at all (lane-sb128b).
12095+ // At a 64 superblock the two orders are identical and this is the same
12096+ // raster loop as before.
12097+ let sb128_search = sb128_on();
12098+ let root_step = if sb128_search { 2 } else { 1 };
12099+ let mut roots: Vec<(usize, usize)> = Vec::new();
12100+ {
12101+ let (r0, r1) = (rect.sb_row0 as usize, rect.sb_row1 as usize);
12102+ let (c0, c1) = (rect.sb_col0 as usize, rect.sb_col1 as usize);
12103+ let mut r = r0;
12104+ while r < r1 {
12105+ let mut c = c0;
12106+ while c < c1 {
12107+ roots.push((r, c));
12108+ c += root_step;
12109+ }
12110+ r += root_step;
12111+ }
12112+ }
12113+ for (root_r, root_c) in roots {
12114+ // The 64x64 cells of this root, in the writer's own order.
12115+ let cells: Vec<(usize, usize)> = if sb128_search {
12116+ [(0, 0), (0, 1), (1, 0), (1, 1)]
12117+ .into_iter()
12118+ .map(|(dr, dc)| (root_r + dr, root_c + dc))
12119+ .filter(|&(r, c)| r < rect.sb_row1 as usize && c < rect.sb_col1 as usize)
12120+ .collect()
12121+ } else {
12122+ vec![(root_r, root_c)]
12123+ };
12124+ // What the four cells below really cost, against which the whole
12125+ // 128x128 candidate is weighed.
12126+ let mark128 = blocks.len();
12127+ let mut root_cost = 0.0f64;
12128+ let root128 = (sb128_search && b128_root() && cells.len() == 4)
12129+ .then(|| search_root_128(
12130+ &mut luma,
12131+ &mut chroma,
12132+ &grid,
12133+ (root_r, root_c),
12134+ (rows, cols),
12135+ (header.mi_cols, header.mi_rows),
12136+ search,
12137+ &tpl_factors,
12138+ sb_q.as_ref(),
12139+ sb_cols,
12140+ tpl_cells_x,
12141+ base_q_idx,
12142+ reference,
12143+ fctx,
12144+ ))
12145+ .flatten();
12146+ for (sb_r, sb_c) in cells {
1190912147 // lane-b64: the whole superblock as ONE 64x64 block, tried before
1191012148 // its quadrants are (`search_skip_64`) and compared against the
1191112149 // four of them below. Only a superblock wholly inside the true
@@ -12004,6 +12242,7 @@ pub(crate) fn encode_inter_frame(
1200412242 &mut luma,
1200512243 &mut chroma,
1200612244 (x64, y64),
12245+ SUPERBLOCK,
1200712246 &sb_search,
1200812247 b64_residual() && !screen,
1200912248 reference,
@@ -12473,6 +12712,27 @@ pub(crate) fn encode_inter_frame(
1247312712 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
1247412713 blocks.push((r32 * cols + c32, Quadrant::Covered));
1247512714 }
12715+ root_cost += cost64;
12716+ } else {
12717+ root_cost += sb_cost;
12718+ }
12719+ }
12720+ // lane-b128: the whole 128x128 root (`PARTITION_NONE` at the root's
12721+ // `partition_w128` symbol) against what its four superblocks really
12722+ // cost, the same weighing the 64 root does one size down. Both sides
12723+ // carry their own partition symbol, so the comparison is complete.
12724+ if let Some((cost128, lambda128, block, after)) = root128
12725+ && cost128 < root_cost + lambda128 * crate::tile::partition_bits(128, true)
12726+ {
12727+ B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12728+ let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
12729+ blocks.truncate(mark128);
12730+ restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after);
12731+ record_mi(&mut grid, root_r * 16, root_c * 16, 32, block.inter, block.skip);
12732+ blocks.push(((root_r * 2) * cols + root_c * 2, Quadrant::Whole128(block)));
12733+ for q in 1..16 {
12734+ let (r32, c32) = (root_r * 2 + q / 4, root_c * 2 + q % 4);
12735+ blocks.push((r32 * cols + c32, Quadrant::Covered));
1247612736 }
1247712737 }
1247812738 }
@@ -12499,6 +12759,24 @@ pub(crate) fn encode_inter_frame(
1249912759 blocks[at] = quadrant;
1250012760 }
1250112761
12762+ // lane-b128, `EC_AV1_B128_CENSUS=1`: how many of this INTER frame's 128
12763+ // superblock roots the search left whole, so a flat BD result is
12764+ // attributable (class `gate-blind-to-feature`). A key frame codes none:
12765+ // only the inter writer has a 128x128 block.
12766+ if crate::envflags::env_flag!("EC_AV1_B128_CENSUS") {
12767+ let whole = blocks
12768+ .iter()
12769+ .filter(|q| matches!(q, Quadrant::Whole128(_)))
12770+ .count();
12771+ let roots = blocks
12772+ .iter()
12773+ .filter(|q| !matches!(q, Quadrant::Covered))
12774+ .count();
12775+ eprintln!(
12776+ "B128 census: inter frame, {whole} whole 128x128 roots, {roots} coded blocks ({:.1}% of the frame's area at 128)",
12777+ 100.0 * (whole * 16) as f64 / blocks.len().max(1) as f64,
12778+ );
12779+ }
1250212780 let modes = blocks
1250312781 .iter()
1250412782 .flat_map(Quadrant::blocks)
@@ -12981,6 +13259,57 @@ mod tests {
1298113259 /// An [`crate::mvstack::MvStack`] with every context at zero and no
1298213260 /// neighbours, for the pricer tests below to fill the one band each of
1298313261 /// them is about.
13262+ /// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer
13263+ /// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL
13264+ /// against the same stack -- an offer the writer clamps prices the
13265+ /// residual against a predictor the decoder never derives, which is the
13266+ /// silent MV drift lane-sb128b root-caused (there fixed on the WRITER
13267+ /// side, so the stream stays legal; here the pricer's own offer set is
13268+ /// enumerated, class `enumerate-table-domain`).
13269+ ///
13270+ /// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer
13271+ #[test]
13272+ fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() {
13273+ for n in 0..=4usize {
13274+ let mut stack = bare_stack();
13275+ for i in 0..n {
13276+ stack.entries.push(crate::mvstack::StackEntry {
13277+ mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)),
13278+ weight: 1,
13279+ });
13280+ stack.drl_ctx.push(0);
13281+ }
13282+ stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv);
13283+ stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv);
13284+ stack.pred_mv = stack.nearest_mv;
13285+ // Aim the vector at each entry in turn, so every index the offer
13286+ // set holds is the one that wins at least once.
13287+ for target in 0..n.max(1) {
13288+ let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv);
13289+ let (_, idx) = best_new_mv_syntax(&stack, mv)
13290+ .expect("a zero residual is always codable");
13291+ let idx = usize::from(idx);
13292+ assert_eq!(
13293+ crate::tile::signalled_drl_idx(n, 0, idx),
13294+ idx,
13295+ "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}",
13296+ );
13297+ }
13298+ // The NEARMV arm's own offer set (`search_inter_block`,
13299+ // `search_skip_64`): indices 1 and 2, offered only when the stack
13300+ // really holds that entry.
13301+ for idx in 1..=2usize {
13302+ if stack.entries.get(idx).is_some() {
13303+ assert_eq!(
13304+ crate::tile::signalled_drl_idx(n, 1, idx),
13305+ idx,
13306+ "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}",
13307+ );
13308+ }
13309+ }
13310+ }
13311+ }
13312+
1298413313 fn bare_stack() -> crate::mvstack::MvStack {
1298513314 crate::mvstack::MvStack {
1298613315 entries: Default::default(),
@@ -13432,7 +13761,11 @@ mod tests {
1343213761 /// (the horizontal shapes, which those partitions never produce).
1343313762 #[test]
1343413763 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
13435- let fctx = &crate::decode::FrameCtx::for_encoder();
13764+ // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
13765+ // it pins the 64 reach explicitly instead of following the process's
13766+ // own superblock knob (`for_encoder`), which made it red under
13767+ // `EC_AV1_SB128=1` for no defect of the code under test.
13768+ let fctx = &crate::decode::FrameCtx::new();
1343613769 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
1343713770 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
1343813771 (4, 8, 64, 9280, 64, 550),
@@ -14359,7 +14692,11 @@ mod tests {
1435914692 /// wrong for one block size while looking plausible for the other.
1436014693 #[test]
1436114694 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
14362- let fctx = &crate::decode::FrameCtx::for_encoder();
14695+ // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
14696+ // it pins the 64 reach explicitly instead of following the process's
14697+ // own superblock knob (`for_encoder`), which made it red under
14698+ // `EC_AV1_SB128=1` for no defect of the code under test.
14699+ let fctx = &crate::decode::FrameCtx::new();
1436314700 // Transcribed from has_top_right/has_bottom_left's row_off==0,
1436414701 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
1436514702 // 128px reference grid) pinned as libaom pins it, independent of the
@@ -15644,6 +15981,86 @@ mod tests {
1564415981 ///
1564515982 /// cargo test -p ec-av1 --release --lib -- --ignored \
1564615983 /// a_128_superblock_clip_whose_drl_index_the_write_time_stack --nocapture
15984+ /// lane-b128: the 128x128 `PARTITION_NONE` root -- one block, one mode
15985+ /// and one motion vector where the four 64x64 roots below spend four of
15986+ /// each (cen3's L1). The counter is the gate on the fixture (class
15987+ /// `gate-blind-to-feature`): a green round trip on a clip that never
15988+ /// codes a 128x128 block proves nothing. RED before the search existed
15989+ /// (zero such blocks coded, `tile::write_sb128_root` wrote SPLIT at every
15990+ /// root by construction).
15991+ ///
15992+ /// Both readers: our own decoder sample-exact against the encoder's
15993+ /// reconstruction (a writer/reader desync surfaces as a pixel miss or a
15994+ /// refusal here, not in the BD gate) AND ffmpeg as the bitstream oracle.
15995+ ///
15996+ /// `#[ignore]`: [`force_sb128`] moves a process-global.
15997+ ///
15998+ /// cargo test -p ec-av1 --release --lib -- --ignored \
15999+ /// a_128_superblock_clip_whose_root_search --nocapture
16000+ #[test]
16001+ #[ignore = "sets the process-global superblock size: run it alone"]
16002+ fn a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact() {
16003+ let _knobs = crate::speed::knob_write();
16004+ if !have_ffmpeg() {
16005+ eprintln!("SKIP: no ffmpeg");
16006+ return;
16007+ }
16008+ force_sb128(true);
16009+ let dir = std::env::temp_dir().join(format!("ec-av1-b128-{}", std::process::id()));
16010+ std::fs::create_dir_all(&dir).unwrap();
16011+ let clip = dir.join("smpte-1280x768.y4m");
16012+ // A slow horizontal pan over a still pattern: whole 128x128 regions
16013+ // share one motion vector, which is exactly what a 128 root can code
16014+ // as one block and four 64 roots cannot.
16015+ let ok = Command::new("ffmpeg")
16016+ .args(["-v", "error", "-y", "-f", "lavfi"])
16017+ .args(["-i", "smptebars=size=1600x768:rate=24"])
16018+ .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
16019+ .args(["-pix_fmt", "yuv420p"])
16020+ .arg(&clip)
16021+ .status()
16022+ .expect("ffmpeg failed to run")
16023+ .success();
16024+ assert!(ok, "ffmpeg could not write the synthetic clip");
16025+ let (width, height) = (1280usize, 768usize);
16026+ let pictures =
16027+ crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
16028+ let _ = take_b128_none_hits();
16029+ let _ = crate::tile::take_sb128_none_hits();
16030+ let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
16031+ let (won, coded) = (take_b128_none_hits(), crate::tile::take_sb128_none_hits());
16032+ eprintln!("128x128 PARTITION_NONE blocks: search won {won}, writer coded {coded}");
16033+ assert!(
16034+ coded > 0,
16035+ "no 128x128 block was coded on this clip, so it cannot witness the root search",
16036+ );
16037+ assert_eq!(won, coded, "every 128x128 root the search took must be coded as one");
16038+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
16039+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
16040+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
16041+ let recon = &frame.reconstruction;
16042+ for (plane, got, want) in [
16043+ ("luma", &dec.y, &recon.y),
16044+ ("U", &dec.u, &recon.u),
16045+ ("V", &dec.v, &recon.v),
16046+ ] {
16047+ let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
16048+ assert_eq!(
16049+ differ, 0,
16050+ "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
16051+ own reconstruction",
16052+ got.len()
16053+ );
16054+ }
16055+ }
16056+ let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
16057+ for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
16058+ assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
16059+ assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
16060+ assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
16061+ }
16062+ }
16063+
1564716064 #[test]
1564816065 #[ignore = "sets the process-global superblock size: run it alone"]
1564916066 fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {
@@ -17076,7 +17493,15 @@ mod tests {
1707617493 // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's
1707717494 // pixels -- and the leaves that predict from them -- moved:
1707817495 // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60.
17079- let pins: [(u8, usize, u64); 2] = [(150, 8218, 0xd533_c8ea_14ca_ae6e), (60, 33017, 0xbced_b694_dcfe_9146)];
17496+ // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so
17497+ // the shipped stream did not move.
17498+ // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every
17499+ // picture is coded in 128x128 superblocks now, the inter ones
17500+ // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at
17501+ // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053.
17502+ // Re-taken at the merge of lane-b128m onto main (128 superblocks on
17503+ // by default, on top of the ARF temporal filter).
17504+ let pins: [(u8, usize, u64); 2] = [(150, 8354, 0x1290b8628438c6d4), (60, 33222, 0xc7f92971ab1264c3)];
1708017505 let coded: Vec<(u8, usize, u64)> = pins
1708117506 .iter()
1708217507 .map(|&(q, _, _)| {
@@ -18360,6 +18785,11 @@ mod tests {
1836018785 {i64_edge} on a superblock the frame edge cuts",
1836118786 100.0 * i64_whole as f64 / i64_offered.max(1) as f64,
1836218787 );
18788+ eprintln!(
18789+ "{name}: 128x128 roots {} (search) / {} (writer)",
18790+ take_b128_none_hits(),
18791+ crate::tile::take_sb128_none_hits(),
18792+ );
1836318793 eprintln!(
1836418794 "{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})",
1836518795 take_b64_root_hits(),
crates/ec-av1/src/encoder.rsmodified+15 -2
@@ -3819,6 +3819,19 @@ mod tests {
38193819 tile_rows_log2: rows_log2,
38203820 };
38213821 let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2);
3822+ // lane-b128m: the SPEC's uniform spacing derives the tile count
3823+ // from the superblock grid (`tileWidthSb = ceil(sbCols >> log2)`),
3824+ // so a frame with fewer superblock columns than the requested
3825+ // count codes fewer tiles -- which is what a 128-superblock
3826+ // sequence does here. The grid the encoder itself computes is the
3827+ // expectation; at 64 superblocks it is `1 << log2` exactly.
3828+ let grid = crate::tile::TileLayout::new(
3829+ (width as u32).div_ceil(4),
3830+ (height as u32).div_ceil(4),
3831+ cols_log2,
3832+ rows_log2,
3833+ );
3834+ let (want_cols, want_rows) = (grid.cols(), grid.rows());
38223835 let mut enc = Av1Encoder::new(config).unwrap();
38233836 let mut stream = Vec::new();
38243837 for packet in encode_all(&mut enc, &sources) {
@@ -3837,12 +3850,12 @@ mod tests {
38373850 if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind {
38383851 assert_eq!(
38393852 (parsed.tile_info.cols, parsed.tile_info.rows),
3840- (1 << cols_log2, 1 << rows_log2),
3853+ (want_cols, want_rows),
38413854 "{layout}: the header's own tile grid"
38423855 );
38433856 assert_eq!(
38443857 tiles.len(),
3845- 1 << (cols_log2 + rows_log2),
3858+ (want_cols * want_rows) as usize,
38463859 "{layout}: tile payloads located in the tile group"
38473860 );
38483861 frames += 1;
crates/ec-av1/src/stream.rsmodified+10 -7
@@ -3014,7 +3014,10 @@ pub(crate) mod tests {
30143014 /// the encoder's own reconstruction, at an even and an odd size.
30153015 #[test]
30163016 fn decode_stream_matches_the_tile_path_on_a_key_frame() {
3017- let fctx = &crate::decode::FrameCtx::new();
3017+ // lane-b128m: the ENCODER writes at this process's superblock size, so
3018+ // its own trial decode -- and the raw tile decode below -- must be given
3019+ // that size too (class: stale header in the test harness).
3020+ let fctx = &crate::decode::FrameCtx::for_encoder();
30183021 for &(width, height) in &[(64usize, 64usize), (216, 96)] {
30193022 let picture = test_card(width, height);
30203023 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
@@ -3085,7 +3088,7 @@ pub(crate) mod tests {
30853088
30863089 #[test]
30873090 fn decode_stream_round_trips_a_gop() {
3088- let fctx = &crate::decode::FrameCtx::new();
3091+ let fctx = &crate::decode::FrameCtx::for_encoder();
30893092 gop_round_trips(128, 64, fctx);
30903093 }
30913094
@@ -3093,7 +3096,7 @@ pub(crate) mod tests {
30933096 /// the inter frame's 16x16-leaf split path is exercised too.
30943097 #[test]
30953098 fn decode_stream_round_trips_an_odd_size_gop() {
3096- let fctx = &crate::decode::FrameCtx::new();
3099+ let fctx = &crate::decode::FrameCtx::for_encoder();
30973100 gop_round_trips(216, 96, fctx);
30983101 }
30993102
@@ -3105,7 +3108,7 @@ pub(crate) mod tests {
31053108 /// decode indices non-decreasing, and an `Err` from the sink aborting.
31063109 #[test]
31073110 fn streaming_decode_matches_the_collecting_one() {
3108- let fctx = &crate::decode::FrameCtx::new();
3111+ let fctx = &crate::decode::FrameCtx::for_encoder();
31093112 let pictures: Vec<_> = (0..4).map(|i| panned_test_card(128, 64, i * 3)).collect();
31103113 let stream = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap().stream;
31113114 let collected = decode_stream(&stream).unwrap();
@@ -3464,7 +3467,7 @@ pub(crate) mod tests {
34643467 /// independent decoder, not just this crate checking its own tile path.
34653468 #[test]
34663469 fn decode_stream_agrees_with_ffmpeg_on_a_gop() {
3467- let fctx = &crate::decode::FrameCtx::new();
3470+ let fctx = &crate::decode::FrameCtx::for_encoder();
34683471 if !have_ffmpeg() {
34693472 eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg");
34703473 return;
@@ -3518,7 +3521,7 @@ pub(crate) mod tests {
35183521 /// geometry that never fires it.
35193522 #[test]
35203523 fn a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg() {
3521- let fctx = &crate::decode::FrameCtx::new();
3524+ let fctx = &crate::decode::FrameCtx::for_encoder();
35223525 if !have_ffmpeg() {
35233526 eprintln!("SKIP a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg: no ffmpeg");
35243527 return;
@@ -3578,7 +3581,7 @@ pub(crate) mod tests {
35783581 /// reconstruction, and ffmpeg.
35793582 #[test]
35803583 fn a_doubly_cut_superblock_root_round_trips_in_every_plane() {
3581- let fctx = &crate::decode::FrameCtx::new();
3584+ let fctx = &crate::decode::FrameCtx::for_encoder();
35823585 if !have_ffmpeg() {
35833586 eprintln!("SKIP a_doubly_cut_superblock_root_round_trips_in_every_plane: no ffmpeg");
35843587 return;
crates/ec-av1/src/tile.rsmodified+266 -14
@@ -175,6 +175,12 @@ fn write_sb128_root(
175175 sb_c: u32,
176176 mi_cols: u32,
177177 mi_rows: u32,
178+ // lane-b128: the partition the root's own search chose --
179+ // `PARTITION_SPLIT` (the four 64x64 quadrants below, which is every root
180+ // this writer coded before) or `PARTITION_NONE` (one 128x128 block,
181+ // written by the caller right after this). Only offered at a root wholly
182+ // inside the frame, so the gathered edge arms below still code SPLIT.
183+ part: usize,
178184 ) {
179185 SB128_ROOT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
180186 let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI);
@@ -186,7 +192,7 @@ fn write_sb128_root(
186192 eprintln!("WTRACE partition_w128 ctx={ctx128} cols={has_cols128} rows={has_rows128}");
187193 }
188194 match (has_cols128, has_rows128) {
189- (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w128[ctx128]),
195+ (true, true) => enc.symbol(part, &mut cdfs.partition_w128[ctx128]),
190196 // As at the 64 root: the gathered CDF is built for the read and
191197 // thrown away, so nothing adapts here. Value 1 is SPLIT.
192198 (true, false) => enc.symbol_fixed(
@@ -203,6 +209,160 @@ fn write_sb128_root(
203209 }
204210 }
205211
212+/// lane-b128: one 128x128 inter block at a `PARTITION_NONE` 128 superblock
213+/// root -- the syntax `decode_inter_block` reads for `sb128_none` (decode.rs
214+/// ~35110): `skip`, `is_inter`, the reference/mode chain at the block's own
215+/// 32x32-mi window, the motion mode, and the transform syntax, with the mi
216+/// grid and every neighbour band published over all thirty-two mi cells.
217+///
218+/// SKIP only, and refused otherwise: a 128x128 block's residual is four
219+/// TX_64X64 luma units interleaved with a TX_32X32 chroma pair per 64x64 mu
220+/// chunk (the chroma units reading the offset-10 `txb_skip` rows), which
221+/// this writer has no path for. A skipped block writes no `cdef_idx` and no
222+/// `delta_q` either, exactly as the 64 root's skip arm does.
223+///
224+/// # Errors
225+/// A block that is intra, or carries a residual, at this size.
226+#[allow(clippy::too_many_arguments)]
227+fn write_inter_block_128(
228+ enc: &mut SymbolEncoder,
229+ cdfs: &mut Cdfs,
230+ neighbours: &mut Neighbours,
231+ grid: &mut MiGrid,
232+ // The root's top-left position in [`SUB`] (16x16) units.
233+ sb_at: (usize, usize),
234+ block: &BlockCoeffs,
235+ mi_cols: u32,
236+ mi_rows: u32,
237+ tx_select: bool,
238+) -> Result<()> {
239+ /// The block's side in samples and in 4x4 mode-info units.
240+ const SIDE: usize = 128;
241+ const SIDE_MI: usize = SIDE / MI;
242+ let info = block.inter.ok_or_else(|| {
243+ Error::unsupported("AV1 tile", "a 128x128 superblock root block is coded inter")
244+ })?;
245+ if !block.skip {
246+ return Err(Error::unsupported(
247+ "AV1 tile",
248+ "a 128x128 superblock root block carries a residual",
249+ ));
250+ }
251+ let (mi_r, mi_c) = (sb_at.0 * (SUB / MI), sb_at.1 * (SUB / MI));
252+ let has_above = neighbours.has_above(mi_r);
253+ let has_left = neighbours.has_left(mi_c);
254+ let skip_ctx =
255+ usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]);
256+ enc.symbol(1, &mut cdfs.skip[skip_ctx]);
257+ write_cdef_idx(enc, (mi_r, mi_c), true);
258+ write_delta_q(enc, cdfs, (mi_r, mi_c), true, true);
259+ let ii_ctx = intra_inter_ctx(
260+ has_above,
261+ has_left,
262+ neighbours.above_inter[mi_c],
263+ neighbours.left_inter[mi_r],
264+ );
265+ enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]);
266+ write_comp_mode(
267+ enc,
268+ cdfs,
269+ neighbours,
270+ (mi_r, mi_c),
271+ (has_above, has_left),
272+ info.ref1.is_some(),
273+ );
274+ let (mv, mv1, is_new_mv) = if info.ref1.is_some() {
275+ write_compound_block(
276+ enc,
277+ cdfs,
278+ neighbours,
279+ grid,
280+ (mi_r, mi_c),
281+ (SIDE_MI, SIDE_MI),
282+ (has_above, has_left),
283+ info,
284+ (mi_cols as usize, mi_rows as usize),
285+ )?
286+ } else {
287+ write_single_ref(
288+ enc,
289+ cdfs,
290+ info.ref_frame,
291+ neighbours.above_ref[mi_c],
292+ neighbours.above_ref1[mi_c],
293+ neighbours.left_ref[mi_r],
294+ neighbours.left_ref1[mi_r],
295+ );
296+ let stack = find_mv_stack(
297+ grid,
298+ mi_r,
299+ mi_c,
300+ SIDE_MI,
301+ SIDE_MI,
302+ info.ref_frame,
303+ mi_cols as usize,
304+ mi_rows as usize,
305+ );
306+ let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?;
307+ (mv, (0, 0), is_new_mv)
308+ };
309+ for dr in 0..SIDE_MI {
310+ for dc in 0..SIDE_MI {
311+ grid.set(
312+ mi_r + dr,
313+ mi_c + dc,
314+ MiInfo {
315+ is_inter: true,
316+ ref_frame: info.ref_frame,
317+ ref_frame1: info.ref1.unwrap_or(NO_REF1),
318+ mv1: mv16(mv1),
319+ mv: mv16(mv),
320+ is_new_mv,
321+ size: SIDE_MI as u8,
322+ size_h: SIDE_MI as u8,
323+ is_global_mv0: false,
324+ is_global_mv1: false,
325+ },
326+ );
327+ }
328+ }
329+ if info.ref1.is_none() {
330+ write_motion_mode(
331+ enc,
332+ cdfs,
333+ grid,
334+ (mi_r, mi_c),
335+ (SIDE_MI, SIDE_MI),
336+ (SIDE, SIDE),
337+ (mi_cols as usize, mi_rows as usize),
338+ info.ref_frame,
339+ block.motion_mode,
340+ )?;
341+ }
342+ if tx_select {
343+ write_tx_syntax_inter(enc, cdfs, neighbours, (mi_r, mi_c), SIDE, true, true, 0);
344+ }
345+ let zero_grids = [
346+ vec![0i32; TX32 * TX32],
347+ vec![0i32; TX32 * TX32],
348+ vec![0i32; TX32 * TX32],
349+ ];
350+ neighbours.record(sb_at, SIDE, 0, &zero_grids);
351+ neighbours.record_inter(sb_at, SIDE, true, true, block_ref(block));
352+ record_block_compound(neighbours, (mi_r, mi_c), SIDE, block);
353+ SB128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
354+ Ok(())
355+}
356+
357+/// How many 128x128 `PARTITION_NONE` blocks the inter writer has coded since
358+/// the last [`take_sb128_none_hits`] (class `gate-blind-to-feature`).
359+static SB128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
360+
361+/// The 128x128-block count since the last call, and zero it.
362+pub fn take_sb128_none_hits() -> usize {
363+ SB128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
364+}
365+
206366 /// `read_lr`'s write side, called once at the top of every superblock,
207367 /// before its partition symbol: writes the units this superblock's own
208368 /// mi span covers (`av1_loop_restoration_corners_in_sb`; no superres, so the
@@ -1279,7 +1439,12 @@ fn write_delta_q(
12791439 DELTA_Q.with(|c| {
12801440 let mut plan = c.borrow_mut();
12811441 let Some(plan) = plan.as_mut() else { return };
1282- if mi.0 % SB_MI as usize != 0 || mi.1 % SB_MI as usize != 0 {
1442+ // lane-b128m: the delta_q unit is the SUPERBLOCK, so it is 128 wide
1443+ // under `EC_AV1_SB128` -- decode.rs `maybe_read_delta_q` gates on
1444+ // `sb_mi_cur`, and a writer gating on a hardcoded 64 codes three
1445+ // symbol groups per 128 root the reader never reads.
1446+ let sb_mi = if sb128_armed() { SB_MI as usize * 2 } else { SB_MI as usize };
1447+ if mi.0 % sb_mi != 0 || mi.1 % sb_mi != 0 {
12831448 return;
12841449 }
12851450 if is_whole_sb && skip {
@@ -2059,6 +2224,15 @@ pub enum Quadrant {
20592224 /// whose coded quarter is a 32x32 level grid, and one TX_32X32 per chroma
20602225 /// plane (lane-tx64, `crate::encode::b64_residual`).
20612226 Whole64(BlockCoeffs),
2227+ /// lane-b128: the whole 128x128 SUPERBLOCK ROOT this quadrant is the
2228+ /// top-left of, coded as one block (`PARTITION_NONE` at the root's
2229+ /// `partition_w128` symbol). Carried by the top-left 32x32 entry of the
2230+ /// root's sixteen; the other fifteen carry [`Covered`](Quadrant::Covered).
2231+ ///
2232+ /// SKIP only: a 128x128 block's residual is four TX_64X64 luma units
2233+ /// interleaved with its chroma per 64x64 mu chunk, which this writer has
2234+ /// no path for; [`crate::tile::write_inter_block_128`] refuses one.
2235+ Whole128(BlockCoeffs),
20622236 /// A quadrant a [`Whole64`](Quadrant::Whole64) at its superblock's
20632237 /// top-left already coded; it carries no block of its own.
20642238 Covered,
@@ -2068,7 +2242,9 @@ impl Quadrant {
20682242 /// The blocks it carries, in the order they are coded.
20692243 pub(crate) fn blocks(&self) -> &[BlockCoeffs] {
20702244 match self {
2071- Quadrant::Whole(block) | Quadrant::Whole64(block) => std::slice::from_ref(block),
2245+ Quadrant::Whole(block) | Quadrant::Whole64(block) | Quadrant::Whole128(block) => {
2246+ std::slice::from_ref(block)
2247+ }
20722248 Quadrant::Split(blocks) => blocks.as_slice(),
20732249 Quadrant::Covered => &[],
20742250 }
@@ -2948,7 +3124,7 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
29483124 neighbours.start_row();
29493125 }
29503126 if sb128 && sb_start {
2951- write_sb128_root(&mut enc, &mut cdfs, &neighbours, sb_r, sb_c, mi_cols, mi_rows);
3127+ write_sb128_root(&mut enc, &mut cdfs, &neighbours, sb_r, sb_c, mi_cols, mi_rows, PARTITION_SPLIT);
29523128 }
29533129 {
29543130 if !sb128 {
@@ -3065,7 +3241,7 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs(
30653241 match quadrant {
30663242 // A 64x64 root is an INTER-frame partition; a
30673243 // key frame codes one as `Superblock::Whole`.
3068- Quadrant::Whole64(_) | Quadrant::Covered => {
3244+ Quadrant::Whole64(_) | Quadrant::Whole128(_) | Quadrant::Covered => {
30693245 return Err(Error::unsupported(
30703246 "AV1 tile",
30713247 "a key frame codes a 64x64 block as `Superblock::Whole`",
@@ -3581,12 +3757,13 @@ fn intrabc_dv_pred(mi_r: usize, mi_c: usize, side: usize) -> (i32, i32) {
35813757 });
35823758 let mut pred = stack_pred.unwrap_or((0, 0));
35833759 if pred == (0, 0) {
3584- // 64x64 superblocks: the only size this encoder's sequence header
3585- // signals (`use_128x128_superblock: false`), so `mib_size` is 16 mi.
3586- // The tile row start is 0, exactly as decode.rs `read_intrabc_dv`
3587- // takes it -- both are written for the single-tile-row streams this
3588- // encoder produces.
3589- let sb_mi = 16i32;
3760+ // `av1_find_ref_dv` takes `mib_size`, the SEQUENCE's superblock size
3761+ // in mi units (lane-b128m: hardcoding 16 here made the writer's DV
3762+ // predictor one 64 superblock up while decode.rs `read_intrabc_dv`
3763+ // took 128 -- identical symbols, different reconstructed DV). The
3764+ // tile row start is 0, exactly as the reader takes it -- both are
3765+ // written for the single-tile-row streams this encoder produces.
3766+ let sb_mi = if sb128_armed() { 32i32 } else { 16i32 };
35903767 let sb_px = sb_mi * MI as i32;
35913768 pred = if (mi_r as i32) < sb_mi {
35923769 (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8)
@@ -4729,6 +4906,10 @@ pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 {
47294906 .iter()
47304907 .map(|q| {
47314908 let side = match q {
4909+ // lane-b128: a 128x128 root is SKIP by construction (the
4910+ // writer refuses a residual at that size), so it names no
4911+ // coefficients on any plane.
4912+ Quadrant::Whole128(_) => return 0.0,
47324913 Quadrant::Whole(_) => 32,
47334914 Quadrant::Split(_) => 16,
47344915 // lane-tx64: a 64x64 root that codes a residual pays for one
@@ -5335,6 +5516,8 @@ pub(crate) fn partition_bits(side: usize, split: bool) -> f64 {
53355516 static CDFS: LazyLock<Cdfs> = LazyLock::new(|| Cdfs::new(2));
53365517 let cdfs = &*CDFS;
53375518 let cdf: &[u16] = match side {
5519+ // lane-b128: the 128 superblock root's own eight-symbol alphabet.
5520+ 128 => &cdfs.partition_w128[0],
53385521 SB => &cdfs.partition_w64[0],
53395522 BLOCK => &cdfs.partition_w32[0],
53405523 TX8 => &cdfs.partition_w8[0],
@@ -6114,6 +6297,19 @@ pub(crate) fn take_drl_hits() -> [usize; 4] {
61146297 /// signalled index 1 and priced the residual against `pred_mv`, and the
61156298 /// decoder's MV silently drifted a whole frame before the drl symbols
61166299 /// desynced).
6300+/// The DRL index [`write_drl_idx`]'s walk can actually SIGNAL against a stack
6301+/// of `entries` candidates: at most two `drl_mode` symbols past `start`, and
6302+/// each one needs a further entry to advance into (spec 5.11.24's
6303+/// `for (idx = 0; idx < 2; idx++) if (NumMvFound > idx + 1)`).
6304+///
6305+/// A search that offers an index this clamps prices its residual against a
6306+/// predictor the decoder never derives (lane-sb128b's silent MV drift); the
6307+/// pricer's own offer set is enumerated against this rule by
6308+/// `crate::encode::tests::every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal`.
6309+pub(crate) fn signalled_drl_idx(entries: usize, start: usize, target: usize) -> usize {
6310+ target.min(start + 2).min(entries.saturating_sub(1)).max(start)
6311+}
6312+
61176313 fn write_drl_idx(
61186314 enc: &mut SymbolEncoder,
61196315 cdfs: &mut Cdfs,
@@ -6121,6 +6317,17 @@ fn write_drl_idx(
61216317 start: usize,
61226318 target: usize,
61236319 ) -> usize {
6320+ debug_assert_eq!(
6321+ signalled_drl_idx(stack.entries.len(), start, target),
6322+ {
6323+ let mut i = start;
6324+ while i < start + 2 && stack.entries.len() > i + 1 && i < target {
6325+ i += 1;
6326+ }
6327+ i
6328+ },
6329+ "the drl clamp rule and the writer's own walk disagree",
6330+ );
61246331 let mut idx = start;
61256332 while idx < start + 2 && stack.entries.len() > idx + 1 {
61266333 let advance = idx < target;
@@ -6377,6 +6584,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
63776584 ];
63786585
63796586 let sb128 = sb128_armed();
6587+ // lane-b128: set at a root whose own `PARTITION_NONE` 128x128 block was
6588+ // just written, so the root's remaining 64x64 cells code nothing.
6589+ let mut sb128_none = false;
63806590 // lane-sb128: at a 128 superblock the four 64x64 cells of each root are
63816591 // written in libaom's own TL/TR/BL/BR order, the root's restoration units
63826592 // and partition symbol first; at a 64 one this is plain raster and every
@@ -6391,8 +6601,50 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
63916601 if row_start {
63926602 neighbours.start_row();
63936603 }
6604+ if sb_start {
6605+ sb128_none = false;
6606+ }
6607+ // lane-b128: the remaining three 64x64 cells of a root the search
6608+ // left WHOLE carry no syntax at all -- the same skip the decoder's
6609+ // own `sb128_none` runs.
6610+ if sb128_none {
6611+ continue;
6612+ }
63946613 if sb128 && sb_start {
6395- write_sb128_root(&mut enc, &mut cdfs, &neighbours, sb_r, sb_c, mi_cols, mi_rows);
6614+ // The 128x128 block a `PARTITION_NONE` root carries, held by the
6615+ // top-left 32x32 entry of the root's sixteen.
6616+ let root_block = ((sb_r & !1) * 2 < rows && (sb_c & !1) * 2 < cols)
6617+ .then(|| &blocks[(((sb_r & !1) * 2) * cols + (sb_c & !1) * 2) as usize])
6618+ .and_then(|q| match q {
6619+ Quadrant::Whole128(block) => Some(block),
6620+ _ => None,
6621+ });
6622+ write_sb128_root(
6623+ &mut enc,
6624+ &mut cdfs,
6625+ &neighbours,
6626+ sb_r,
6627+ sb_c,
6628+ mi_cols,
6629+ mi_rows,
6630+ if root_block.is_some() { PARTITION_NONE } else { PARTITION_SPLIT },
6631+ );
6632+ if let Some(block) = root_block {
6633+ let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4);
6634+ write_inter_block_128(
6635+ &mut enc,
6636+ &mut cdfs,
6637+ &mut neighbours,
6638+ &mut grid,
6639+ at128,
6640+ block,
6641+ mi_cols,
6642+ mi_rows,
6643+ tx_select,
6644+ )?;
6645+ sb128_none = true;
6646+ continue;
6647+ }
63966648 }
63976649 {
63986650 if !sb128 {
@@ -6438,7 +6690,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
64386690 + usize::from(neighbours.left_skip[mi_r]);
64396691 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
64406692 write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
6441- write_delta_q(&mut enc, &mut cdfs, (mi_r, mi_c), true, block.skip);
6693+ write_delta_q(&mut enc, &mut cdfs, (mi_r, mi_c), !sb128_armed(), block.skip);
64426694 let ii_ctx = intra_inter_ctx(
64436695 has_above,
64446696 has_left,
@@ -6638,7 +6890,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
66386890 let block = match site {
66396891 // Already coded by the `Whole64` above -- but only inside
66406892 // a superblock that really carried one.
6641- Quadrant::Whole64(_) | Quadrant::Covered => {
6893+ Quadrant::Whole64(_) | Quadrant::Whole128(_) | Quadrant::Covered => {
66426894 return Err(Error::unsupported(
66436895 "AV1 tile",
66446896 "a `Whole64`/`Covered` quadrant needs its superblock's \
lanes/b128.report.mdadded+206 -0
@@ -0,0 +1,206 @@
1+# lane-b128 — a real 128x128 root under `EC_AV1_SB128`
2+
3+Three results:
4+
5+1. **Task 0 (the drl pricer) is a STALE premise, and now has its enumeration
6+ test.** The charter's `encode.rs:8722` mis-pricing was already closed by
7+ the lane-sb128b merge on the WRITER side; the pricer's own offer set is
8+ provably clamp-free against its own stack.
9+2. **The 128x128 `PARTITION_NONE` root is implemented, witnessed and
10+ MEASURED** — and it turns lane-sb128b's refutation around: film B
11+ +24.2%/−2.5% vs libaom cpu-6 / rav1e s6 with 128 superblocks ON, against
12+ the SPLIT-only arm's +37.5%/+7.3%.
13+3. **HORZ/VERT (128x64, 64x128) are deferred** — see the disposition below.
14+
15+## 1. Task 0 — the drl offer set, enumerated
16+
17+`crate::tile::signalled_drl_idx(entries, start, target)` is the writer's
18+clamp rule as one pure function (`write_drl_idx`'s own walk now carries a
19+`debug_assert_eq!` against it, so the two cannot drift). The pricer's offer
20+set is enumerated against it over every stack size 0..=4, for both the
21+`NEWMV` (`best_new_mv_syntax`) and the `NEARMV` (`entries.get(idx)`) arms:
22+
23+ cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer
24+ test encode::tests::every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal ... ok
25+
26+GREEN as written: `best_new_mv_syntax` breaks at `entries.len() <= idx`,
27+which is exactly `write_drl_idx`'s `entries.len() > idx + 1` condition, so
28+no offered index is ever clamped **against the same stack**. Byte effect:
29+none — the pins are byte-identical (below). The residual error the report
30+open item names is entirely the SEARCH-time vs WRITE-time stack divergence
31+(lane-sb128b's second open item), which no change on this line can reach.
32+
33+## 2. The 128 root
34+
35+### What moved
36+
37+- `tile.rs` — `Quadrant::Whole128(BlockCoeffs)`; `write_sb128_root` takes the
38+ partition value; `write_inter_block_128` writes the block (`skip`,
39+ `is_inter`, the reference/mode chain at a 32x32-mi window, motion mode, tx
40+ syntax, mi grid + neighbour bands over all 32 mi cells); the inter tile
41+ loop skips the root's remaining three 64x64 cells, mirroring the decoder's
42+ own `sb128_none`; `partition_bits` gained the 128 row;
43+ `signalled_drl_idx`; `take_sb128_none_hits`.
44+- `encode.rs` — `search_root_128` (the candidate, its legality and its
45+ lambda), `search_skip_64` parameterised by `side`, the tile search loop
46+ restructured into ROOTS x cells, the 128-vs-four decision,
47+ `take_b128_none_hits`, the `EC_AV1_B128_CENSUS=1` per-frame line.
48+
49+### Deliberate limits (deviations from the charter, each with its reason)
50+
51+- **SKIP only.** A 128x128 block's residual is four TX_64X64 luma units
52+ interleaved with a TX_32X32 chroma pair per 64x64 mu chunk (the chroma
53+ units on the offset-10 `txb_skip` rows), plus one `txfm_partition` symbol
54+ per chunk. Neither the writer nor `Plane::code_from_prediction` has that
55+ path; `write_inter_block_128` REFUSES a non-skip block rather than coding
56+ one wrong. `search_root_128` therefore offers `residual: false`.
57+- **Single reference only.** The compound arm at 128 would go through
58+ `write_compound_block` at a window size it has never been exercised at.
59+- **Inter frames only.** A key frame's 128 root still writes SPLIT.
60+- **HORZ / VERT deferred.** Two 128x64 / 64x128 blocks need rect neighbour
61+ recording and rect prediction/SSE on the WRITER and SEARCH sides (the
62+ decoder already reads both, lane-sb128c r7); the square NONE arm reuses
63+ every existing square helper unchanged.
64+
65+### Witness (red before / green after)
66+
67+`encode::tests::a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact`
68+(`--ignored`, it moves the process-global superblock size):
69+
70+ cargo test -p ec-av1 --release --lib -- --ignored \
71+ a_128_superblock_clip_whose_root_search --nocapture
72+ 128x128 PARTITION_NONE blocks: search won 406, writer coded 406
73+ test ... ok
74+
75+8 frames, 1280x768, a slow pan over `smptebars` at `force_sb128(true)`:
76+**406** 128x128 blocks coded, every frame sample-exact against the encoder's
77+own reconstruction through `decode_stream` AND through ffmpeg. RED before
78+this lane by construction: `write_sb128_root` wrote `PARTITION_SPLIT` at
79+every root, so the count was 0 and no such block existed to decode.
80+
81+### Census (`EC_AV1_B128_CENSUS=1`, plus a per-row count in the gate)
82+
83+Per row, over the four-quantizer ladder (search took / writer coded -- the
84+writer is higher because the filter search re-codes each tile):
85+
86+| row | 128 roots taken | writer-coded |
87+|---|---|---|
88+| bars 1080p | 3448 | 6013 |
89+| bars 2160p | 4144 | 5827 |
90+| film A | 505 | 1241 |
91+| film B | 1928 | 3189 |
92+| screen capture | 4736 | 4774 |
93+
94+Per frame on film B the census reads e.g. `100 whole 128x128 roots, 336
95+coded blocks (83.3% of the frame's area at 128)` -- the lever cen3's L1
96+asked for (38754 coded blocks vs libaom's 16178) is really being pulled.
97+All of them are on INTER frames: a key frame's 128 root still writes SPLIT.
98+
99+## 3. The gate
100+
101+`bd_rate_screen_native`, 12 frames, four quantizers, BD-rate vs libaom
102+`cpu-used 6` / rav1e `speed 6` (lower is better). Both arms from THIS tree,
103+both controls reproduced (not taken from the charter):
104+
105+| row | 64 superblocks (control) | 128 + the 128 root |
106+|---|---|---|
107+| bars 1080p | −2.6 / −18.3 | **−3.3 / −18.9** |
108+| bars 2160p | +8.8 / −13.2 | **+7.9 / −14.0** |
109+| film A (1080p) | +20.6 / −5.1 | **+20.4 / −5.2** |
110+| film B (2160p) | +24.8 / −2.1 | **+24.2 / −2.5** |
111+| screen capture | +14.6 / −33.2 | **+14.4 / −33.2** |
112+
113+Long GOP (`bd_rate_film_long_gop`, 48 frames):
114+
115+| row | 64 superblocks | 128 + the 128 root |
116+|---|---|---|
117+| film A | +24.7 / −7.5 | **+24.4 / −7.7** |
118+| film B | +86.8 / +7.4 | **+85.6 / +6.6** |
119+
120+The 2x2 the charter asked for (film B, 12 frames):
121+
122+| arm | vs libaom | vs rav1e |
123+|---|---|---|
124+| SB64, LR on (control) | +24.8% | −2.1% |
125+| SB128 + 128 root, LR on | **+24.2%** | **−2.5%** |
126+| SB128 + 128 root, LR off (`EC_AV1_LR=0`) | +24.6% | −2.3% |
127+
128+(The SB64 LR-off control was not re-run: the SB64 path is byte-identical to
129+the control tree -- the pins prove it -- and lane-sb128b measured it at
130++25.4/−1.6. The forced ≥128 LR unit is no longer a loss: LR ON is the better
131+arm on both columns now, the reverse of lane-sb128b's reading.)
132+
133+Every row of both gates is down or flat on both columns. The keep rule
134+HOLDS -- and the default still does not flip. See below.
135+
136+## 4. Why the default stays OFF (the blocker, not this lane's)
137+
138+With `EC_AV1_SB128=1`, **eleven** of this crate's own round-trip tests fail,
139+and they fail with the 128x128 BLOCK switched off (`EC_AV1_B128=0`) too --
140+i.e. they are lane-sb128's SPLIT-only plumbing, at sizes its own 256x128
141+witness never covered:
142+
143+ stream::tests::decode_stream_round_trips_a_gop
144+ stream::tests::decode_stream_round_trips_an_odd_size_gop
145+ stream::tests::decode_stream_agrees_with_ffmpeg_on_a_gop
146+ stream::tests::decode_stream_matches_the_tile_path_on_a_key_frame
147+ stream::tests::streaming_decode_matches_the_collecting_one
148+ stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane
149+ stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg
150+ encoder::tests::every_tile_layout_decodes_sample_exact_through_both_decoders
151+ encoder::tests::tile_bytes_do_not_depend_on_the_thread_count
152+ encoder::tests::a_moving_detail_clip_codes_two_delta_q_levels_both_decoders_read_exactly
153+ encode::tests::a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly
154+
155+`decode_stream_round_trips_a_gop` fails with exactly the refusal lane-sb128b
156+root-caused ("a reference frame selected with no picture at this frame's own
157+ref_frame_idx slot"), so at least one writer/reader desync is still live in
158+the 128 path at odd sizes / multiple tiles. Two more
159+(`encode::tests::reach_matches_libaom_has_top_right_and_has_bottom_left`,
160+`every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock`) are
161+TEST staleness: they assert libaom's 64-superblock reach tables against a
162+process whose superblock size is 128.
163+
164+A 0.6-point BD win does not buy shipping that, so `SB128_DEFAULT` stays
165+`false` and the whole feature stays behind `EC_AV1_SB128=1`. The next lane
166+is named by this list.
167+
168+## 5. A defect fixed on the way (class: stale header in the test harness)
169+
170+Ten decode round-trip tests encode with THIS process's encoder and then
171+decode the tile directly with a plain `FrameCtx`, whose superblock size is
172+the DECODER default (64) -- not the size the writer used. With 128
173+superblocks on, the reader skipped the root's partition symbol and the tile
174+desynced at symbol 0 (found by `EC_AV1_SYMTRACE`: the reader's first symbol
175+was the writer's second). `FrameCtx::for_encoder` exists for exactly this
176+and is now used in all ten; the module was swept, and two of the ten were
177+not failing yet. Same shape as the `filter_intra_on()` argument beside them.
178+
179+## Disposition
180+
181+- `deferred`: **HORZ / VERT at the 128 root** (two 128x64 / 64x128 blocks) --
182+ the writer has no rect neighbour recording and the search no rect
183+ prediction/SSE at this size; the square NONE arm needed neither. Unblocked
184+ by a rect `record_inter`/`record` pair plus a rect trial in
185+ `search_root_128`. The decoder already reads both (lane-sb128c r7).
186+- `deferred`: **the 128 block's residual and its compound arm** -- four
187+ TX_64X64 luma units interleaved with a TX_32X32 chroma pair per mu chunk,
188+ on the offset-10 `txb_skip` rows, plus one `txfm_partition` symbol per
189+ chunk. Unblocked by that writer path; `write_inter_block_128` refuses a
190+ non-skip block until then, so nothing can silently code one wrong.
191+- `deferred`: **the intra 128 root on key frames** -- the key-frame writer
192+ codes SPLIT at every 128 root, as before.
193+- `open`: the eleven pre-existing 128-superblock desyncs above (the default's
194+ blocker).
195+- `open`: search-time vs write-time mv stacks still differ (lane-sb128b's own
196+ second open item); the writer's clamp makes it safe, not right.
197+
198+## Suite / checks (default OFF, the shipped state)
199+
200+ s1 --skip stream:: 340 passed; 0 failed; 34 ignored (RC=0)
201+ s2 stream:: --skip 10bit 200 passed; 0 failed; 15 ignored (RC=0)
202+ s3 10bit 42 passed; 0 failed; 1 ignored (RC=0)
203+ --ignored every_speed_preset_decodes_sample_exact_through_both_decoders ok
204+ --ignored a_128_superblock_clip_whose_root_search... ok (406 blocks)
205+ the_encoders_own_streams_are_byte_identical_to_their_pins ok, and ok at EC_AV1_SPEED=6
206+ cargo check --workspace --all-targets 0 errors, 0 ec-av1 warnings
lanes/b128m.report.mdadded+127 -0
@@ -0,0 +1,127 @@
1+# lane-b128m — the eleven 128-superblock desyncs, and the default flip
2+
3+`SB128_DEFAULT` is **true**: every sequence this encoder writes codes
4+128x128 superblocks, with lane-b128's `PARTITION_NONE` 128 root inside them.
5+Four defects closed, each with its own first divergent symbol.
6+
7+## 1. The delta_q unit is the 128 superblock (`0aa5a5e3`)
8+
9+Defect 0 of the charter, and new at this merge (per-SB delta_q from lane-dq
10+met 128 superblocks from lane-b128 — class *merge cross-product defect*).
11+
12+- **First divergent symbol**: the SECOND 64x64 cell's `delta_q_abs` inside a
13+ 128 root. `tile::write_delta_q` gated on a hardcoded `SB_MI` (64), while
14+ decode.rs `maybe_read_delta_q` gates on `sb_mi_cur` — so the writer coded
15+ four symbol groups per 128 root and the reader read one. It surfaced frames
16+ later as the arf's "a reference frame selected with no picture at this
17+ frame's own ref_frame_idx slot".
18+- Two more halves of the same defect: the 64-root whole-block call passed
19+ `is_whole_sb = true` under a 128 superblock (which suppresses the read on
20+ the wrong side), and the search-side `sb_q` grid gave each 64 cell its own
21+ qindex when only the root's top-left one is coded — flattened per 128 root
22+ so a cell is quantized at the qindex its root signals.
23+- Witness: `encode::tests::a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact`
24+ (`--ignored`) — red with the refusal above, green after (405 blocks).
25+
26+## 2. The superblock size travels with a `FrameCtx` copy (`c0635108`'s parent)
27+
28+`decode::filter_ctx_copy` copied nine fields and not `sb128_flag` /
29+`reach_sb_px`, so a tile SEARCH worker (`encode::search_tiles`, threads > 1)
30+searched at 64 while the calling thread searched at 128.
31+
32+- Symptom: `tile_bytes_do_not_depend_on_the_thread_count`, 1x2 tiles, 9251
33+ bytes at one thread vs 9239 at four.
34+- Two neighbouring gates were TEST staleness and are pinned instead of
35+ fixed: `reach_matches_libaom_has_top_right_and_has_bottom_left` and
36+ `every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock`
37+ transcribe libaom's 64-superblock tables, so they build a 64 context
38+ explicitly rather than following the process knob.
39+- `every_tile_layout_decodes_sample_exact_through_both_decoders` asserted
40+ `1 << log2` tiles; the SPEC derives the count from the superblock grid
41+ (`tileWidthSb = ceil(sbCols >> log2)`), and 640x384 has 5 128-superblock
42+ columns, so `tile_cols_log2 = 2` legitimately codes 3 tiles. The test now
43+ expects the encoder's own `TileLayout` (identical to `1 << log2` at 64).
44+
45+## 3. The writer's intrabc DV predictor (`c0635108`)
46+
47+- **First divergent symbol: none.** The writer's and the reader's symbol
48+ traces are identical for all 111384 symbols; only the `# MVDBG` annotation
49+ differs — writer DV (-48, 0) px, reader (-112, 0) px at mi=(36,4).
50+ `tile::intrabc_dv_pred` hardcoded `mib_size = 16` where decode.rs
51+ `read_intrabc_dv` takes `sb_mi_cur`, so `av1_find_ref_dv`'s fallback was one
52+ 64 superblock up on one side and one 128 on the other: same bits, different
53+ reconstruction.
54+- `Ibc::dv_valid` likewise counted libaom's 256-pixel intrabc delay in 64s
55+ (`>> 6`, `INTRABC_DELAY_SB64`), offering sources the 128 visit order had not
56+ reconstructed yet; it now derives both the shift and the delay from the
57+ superblock size.
58+- Witness: `a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`.
59+
60+## 4. Seven test harnesses handed the encoder a 64 context (`b6e573a4`)
61+
62+The seven remaining `stream::tests` failures were one cause: each built a
63+plain `FrameCtx` (superblock 64) and passed it to `encode_*_with_ctx`, so the
64+encoder's own trial decode — and the raw tile decode beside it — read at 64
65+while the writer coded 128 roots.
66+
67+- **First divergent symbol** (`decode_stream_matches_the_tile_path_on_a_key_frame`,
68+ 216x96): index 33, the writer's 8-symbol `partition_w128` (value 3, SPLIT),
69+ which the reader skipped straight into the 10-symbol `partition_w64`.
70+ The other six surfaced as the ref-slot refusal inside the encoder's trial
71+ decode.
72+- Same class the lane-b128 merge swept through ten of their neighbours
73+ (`FrameCtx::for_encoder`); these seven were the rest of it.
74+
75+## The gates (both arms re-run on THIS tree)
76+
77+`bd_rate_screen_native`, 12 frames, BD-rate vs libaom cpu-6 / rav1e s6
78+(lower is better):
79+
80+| row | 64 superblocks (control) | 128 superblocks (default) |
81+|---|---|---|
82+| bars 1080p | -3.1 / -18.7 | **-3.7 / -19.2** |
83+| bars 2160p | +9.1 / -13.3 | **+8.5 / -13.8** |
84+| film A (1080p) | +20.3 / -5.0 | **+20.1 / -5.2** |
85+| film B (2160p) | +24.6 / -2.0 | **+24.3 / -2.2** |
86+| screen capture | +14.6 / -33.2 | **+14.4 / -33.2** |
87+
88+`bd_rate_film_long_gop`, 48 frames:
89+
90+| row | 64 superblocks | 128 superblocks |
91+|---|---|---|
92+| film A | +24.0 / -7.6 | **+23.6 / -7.9** |
93+| film B | +85.8 / +7.1 | **+85.1 / +6.6** |
94+
95+Every row is DOWN on both columns; screen is down on one and flat on the
96+other. The keep rule holds with room to spare.
97+
98+## Pins
99+
100+Re-taken for the flip (the same four pictures, now in 128 superblocks):
101+`(150, 8327, 0x33eb7bd59beaf2e3)`, `(60, 33194, 0xafded5cfca824703)` — was
102+`(150, 8252, ...)`, `(60, 33053, ...)`. `EC_AV1_SB128=0` restores the old
103+bytes exactly, which is also the proof that none of the four fixes moves the
104+64-superblock encoder. No other byte pin moved.
105+
106+## Suite / checks
107+
108+ EC_AV1_SB128=1 (before the flip)
109+ s1 --skip stream:: 341 passed; 0 failed; 34 ignored (only the 64-pins gate red)
110+ s2 stream:: 201 passed; 0 failed; 15 ignored RC=0
111+ s3 10bit 42 passed; 0 failed; 1 ignored RC=0
112+
113+ default (SB128_DEFAULT = true, pins re-taken)
114+ s1 342 passed; 0 failed; 34 ignored RC=0
115+ s2 201 passed; 0 failed; 15 ignored RC=0
116+ s3 42 passed; 0 failed; 1 ignored RC=0
117+ --ignored every_speed_preset_decodes_sample_exact_through_both_decoders ok
118+ --ignored a_128_superblock_clip_whose_root_search... ok (405 blocks)
119+ cargo check --workspace --all-targets 0 errors, 0 ec-av1 warnings
120+
121+## Disposition
122+
123+- `deferred`: HORZ / VERT at the 128 root, the 128 block's residual and its
124+ compound arm, and the intra 128 root on key frames — lane-b128's three
125+ deferrals, unchanged (the writer still refuses a non-skip 128 block).
126+- `open`: search-time vs write-time mv stacks still differ (lane-sb128b's own
127+ second open item); the writer's clamp makes it safe, not right.