diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 88a5d4c8..18e3006a 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -275,6 +275,13 @@ pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx { out.seg_mi_dims.set(fctx.seg_mi_dims.get()); out.seg.replace(fctx.seg.borrow().clone()); out.seg_ids.replace(fctx.seg_ids.borrow().clone()); + // lane-b128m: the superblock size travels with the copy. A tile SEARCH + // worker (`encode::search_tiles`) gets its context from here, so dropping + // it made every worker search at 64 while the calling thread searched at + // 128 -- the bytes a frame came out as then depended on the tile thread + // count under `EC_AV1_SB128`. + out.sb128_flag.set(fctx.sb128_flag.get()); + out.reach_sb_px.set(fctx.reach_sb_px.get()); out } @@ -38625,7 +38632,7 @@ mod tests { #[test] fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() { - let fctx = &crate::decode::FrameCtx::new(); + 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) for (w, h) in [(128usize, 128usize), (192, 128)] { round_trips(w, h, &[DC_PRED as u8], fctx); } @@ -38637,7 +38644,7 @@ mod tests { /// decoder round adds, not just `DC_PRED`. #[test] fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() { - let fctx = &crate::decode::FrameCtx::new(); + 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) for (w, h) in [(128usize, 128usize), (192, 128)] { round_trips(w, h, &crate::intra::KEY_FRAME_MODES, fctx); } @@ -38648,7 +38655,7 @@ mod tests { /// this decoder round adds. #[test] fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: encodes, so the decode context takes this process's superblock size for (w, h) in [(854usize, 480usize), (216, 96)] { round_trips(w, h, &crate::intra::KEY_FRAME_MODES, fctx); } @@ -38662,7 +38669,7 @@ mod tests { /// bit, `partition_w8` leaves). #[test] fn leaf8_straddle_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() { - let fctx = &crate::decode::FrameCtx::new(); + 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) for (w, h) in [(40usize, 32usize), (640, 360)] { round_trips(w, h, &crate::intra::KEY_FRAME_MODES, fctx); } @@ -38958,7 +38965,7 @@ mod tests { /// crate's own writer and reader could otherwise share. #[test] fn ffmpeg_and_this_decoder_agree_on_a_key_frame() { - let fctx = &crate::decode::FrameCtx::new(); + 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) if !have_ffmpeg() { eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_key_frame: no ffmpeg"); return; @@ -39005,7 +39012,7 @@ mod tests { /// between the palette colours and the colour-index maps). #[test] fn a_filter_intra_key_frame_decodes_pixel_exact_through_ffmpeg() { - let fctx = &crate::decode::FrameCtx::new(); + 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) if !crate::encode::filter_intra_on() { eprintln!("SKIP a_filter_intra_key_frame...: EC_AV1_FILTER_INTRA=0"); return; @@ -39075,7 +39082,7 @@ mod tests { /// wire). #[test] fn a_key_frames_tile_needs_the_headers_own_tx_select_bit() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::for_encoder(); // lane-b128: encodes, so the decode context takes this process's superblock size use crate::encode::encode_key_frame_with_ctx; let (width, height) = (64usize, 64usize); let picture = round_trip_test_card(width, height); @@ -39275,7 +39282,7 @@ mod tests { #[test] fn a_gop_round_trips_bit_exact_against_the_encoder_reconstruction() { - let fctx = &crate::decode::FrameCtx::new(); + 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) gop_round_trips(128, 64, fctx); } @@ -39284,7 +39291,7 @@ mod tests { /// split path is exercised too. #[test] fn an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction() { - let fctx = &crate::decode::FrameCtx::new(); + 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) gop_round_trips(216, 96, fctx); } @@ -39514,7 +39521,7 @@ mod tests { #[test] fn ffmpeg_and_this_decoder_agree_on_a_gop() { - let fctx = &crate::decode::FrameCtx::new(); + 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) if !have_ffmpeg() { eprintln!("SKIP ffmpeg_and_this_decoder_agree_on_a_gop: no ffmpeg"); return; diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 8bb6ab73..0b03c6d4 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -722,6 +722,27 @@ pub fn take_b64_root_hits() -> usize { B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) } +/// Whether the 128 superblock root offers its `PARTITION_NONE` candidate at +/// all ([`search_root_128`]). On by default; `EC_AV1_B128=0` turns it off, +/// which is the attribution arm for a 128-superblock stream: it separates +/// what the SIZE costs from what the 128x128 BLOCK buys. +fn b128_root() -> bool { + static ENV: std::sync::LazyLock = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_B128").ok().is_none_or(|v| v != "0") + }); + *ENV +} + +/// How many 128x128 `PARTITION_NONE` roots the search took since the last +/// [`take_b128_none_hits`] (class `gate-blind-to-feature`): a flat BD result +/// is only attributable once the fire count is known. +static B128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// The 128x128-root count since the last call, and zero it. +pub fn take_b128_none_hits() -> usize { + B128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) +} + /// Rate-distortion optimised quantisation ([`crate::tile::rdoq`], lane-rdoq). /// Preset-gated: it re-prices the block once per candidate level, so it buys /// bits with wall (see `crate::speed::RDOQ` for the per-preset table). @@ -5140,7 +5161,9 @@ fn intrabc_step() -> usize { const IBC_HASH: usize = 16; /// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind -/// the current one the source's bottom-right corner must already be. +/// the current one the source's bottom-right corner must already be. Under +/// 128 superblocks the same 256 pixels are two superblocks, which +/// [`Ibc::dv_valid`] derives from the size itself. const INTRABC_DELAY_SB64: i32 = 4; /// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`. @@ -5276,22 +5299,28 @@ impl Ibc { if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 { return false; } - let active_sb_row = (y as i32 - ty0) >> 6; - let active_sb_col = (x as i32 - tx0) >> 6; - let src_sb_row = (sy + h - 1 - ty0) >> 6; - let src_sb_col = (sx + w - 1 - tx0) >> 6; + // lane-b128m: libaom counts this wavefront in SUPERBLOCKS, and the + // superblock is 128 wide under `EC_AV1_SB128` (`INTRABC_DELAY_SB = + // INTRABC_DELAY_PIXELS >> sb_size_log2`, i.e. 2 there and 4 here). + // Counting 64s under a 128 superblock let the search take a source + // from a 64 row the 128 visit order had not reconstructed yet. + let sb_log2 = if crate::encode::sb128_on() { 7 } else { 6 }; + let delay: i32 = if sb_log2 == 7 { INTRABC_DELAY_SB64 / 2 } else { INTRABC_DELAY_SB64 }; + let active_sb_row = (y as i32 - ty0) >> sb_log2; + let active_sb_col = (x as i32 - tx0) >> sb_log2; + let src_sb_row = (sy + h - 1 - ty0) >> sb_log2; + let src_sb_col = (sx + w - 1 - tx0) >> sb_log2; // This lane's own restriction (see the doc comment). if src_sb_row >= active_sb_row { return false; } - let total = ((tx1 - tx0 - 1) >> 6) + 1; - if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - INTRABC_DELAY_SB64 - { + let total = ((tx1 - tx0 - 1) >> sb_log2) + 1; + if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - delay { return false; } // libaom's wavefront: only the top-left cone of the frame is legal. - let wf = (1 + INTRABC_DELAY_SB64) * (active_sb_row - src_sb_row); - src_sb_col < active_sb_col - INTRABC_DELAY_SB64 + wf + let wf = (1 + delay) * (active_sb_row - src_sb_row); + src_sb_col < active_sb_col - delay + wf } } @@ -5872,11 +5901,36 @@ fn cfl_on() -> bool { /// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured /// its own on/off pair -- and how every byte pin written before it still /// reproduces). It is also a speed lever: on at preset 0, off above it. -// lane-sb128: `use_128x128_superblock` (spec 5.5.1). Off by default until -// the BD gate says otherwise; `EC_AV1_SB128=1` turns it on for the whole -// process (a sequence-header field, so it cannot change mid-stream anyway), -// the same env-flag shape `EC_AV1_FILTER_INTRA` uses. NOT an `EncoderConfig` -// field: that struct is built by 90 literal sites in this workspace. +// lane-sb128: `use_128x128_superblock` (spec 5.5.1). `EC_AV1_SB128=0` turns +// it off for the whole process (a sequence-header field, so it cannot change +// mid-stream anyway), the same env-flag shape `EC_AV1_FILTER_INTRA` uses. +// NOT an `EncoderConfig` field: that struct is built by 90 literal sites in +// this workspace. + +/// Whether a sequence codes 128x128 superblocks when the environment says +/// nothing. ON since lane-b128 gave the 128 root a real `PARTITION_NONE` +/// candidate ([`search_root_128`]): with SPLIT-only roots the size was pure +/// cost (lane-sb128b measured film B +24.9 -> +37.5 vs libaom), and with the +/// 128x128 block in it every row of the native BD gate is down or flat on +/// both columns (BD-rate vs libaom cpu-6 / rav1e s6, 12 frames): +/// +/// | row | 64 superblocks | 128 + the 128 root | +/// |---|---|---| +/// | bars 1080p | -3.1 / -18.7 | **-3.7 / -19.2** | +/// | bars 2160p | +9.1 / -13.3 | **+8.5 / -13.8** | +/// | film A | +20.3 / -5.0 | **+20.1 / -5.2** | +/// | film B | +24.6 / -2.0 | **+24.3 / -2.2** | +/// | screen capture | +14.6 / -33.2 | **+14.4 / -33.2** | +/// +/// and the long-GOP gate agrees (film A +24.0/-7.6 -> +23.6/-7.9, film B +/// +85.8/+7.1 -> +85.1/+6.6). Both arms re-run on lane-b128m's own base. +/// +/// ON since lane-b128m closed the eleven 128-superblock desyncs that held it +/// off (the delta_q unit at the 128 superblock, the superblock size travelling +/// with a `FrameCtx` copy into a tile search worker, the writer's intrabc DV +/// predictor and wavefront, and seven test harnesses that handed the encoder a +/// 64-superblock context). `EC_AV1_SB128=0` turns it off. +pub(crate) const SB128_DEFAULT: bool = true; /// Whether this process's sequences code 128x128 superblocks. An ENCODER /// knob (like `speed::SPEED`), never read by a decode: read through a @@ -5889,7 +5943,9 @@ pub(crate) fn sb128_on() -> bool { use std::sync::atomic::Ordering::Relaxed; match ENC_SB128.load(Relaxed) { 2 => { - let on = crate::envflags::var("EC_AV1_SB128").ok().is_some_and(|v| v != "0"); + let on = crate::envflags::var("EC_AV1_SB128") + .ok() + .map_or(SB128_DEFAULT, |v| v != "0"); ENC_SB128.store(u8::from(on), Relaxed); on } @@ -9300,6 +9356,113 @@ fn predict_compound_u8( blended.iter().map(|&v| v as u8).collect() } +/// lane-b128: the 128x128 `PARTITION_NONE` candidate for a whole 128 +/// superblock root, the lever cen3's L1 asks for -- one block, one mode and +/// one motion vector where the four 64x64 roots below spend four of each. +/// +/// SKIP only (`residual: false`): a 128x128 block's residual is four +/// TX_64X64 luma units interleaved with a TX_32X32 chroma pair per 64x64 mu +/// chunk, which neither the writer nor [`Plane::code_from_prediction`] has a +/// path for -- offering one here would price a block +/// [`crate::tile::write_inter_block_128`] refuses. Single reference only for +/// the same reason: the compound arm at this size is untested against the +/// writer's own `write_compound_block` window. +/// +/// Only a root whose whole 128x128 lies inside the true frame AND inside +/// this tile is offered: the writer's own root codes `PARTITION_NONE` only +/// where the spec's `has_rows`/`has_cols` are both set, and a straddling +/// block would have to be ranked over its inside part alone. +/// +/// Returns `(cost, lambda, block, reconstruction)` -- the cost already +/// carries the root's own `PARTITION_NONE` symbol, so the caller weighs it +/// against the four superblocks plus the SPLIT symbol. +#[allow(clippy::too_many_arguments)] +fn search_root_128( + luma: &mut Plane, + chroma: &mut [Plane; 2], + grid: &crate::mvstack::MiGrid, + (root_r, root_c): (usize, usize), + // The 32x32-block grid this tile's `blocks` vector is indexed on. + (rows, cols): (usize, usize), + // The frame's own mode-info grid, which bounds the root. + (mi_cols, mi_rows): (u32, u32), + search: Search<'_>, + tpl_factors: &Option>, + sb_q: Option<&Vec>, + sb_cols: usize, + tpl_cells_x: usize, + base_q_idx: u8, + reference: &Picture, + fctx: &crate::decode::FrameCtx, +) -> Option<(f64, f64, BlockCoeffs, [(Vec, Vec); 3])> { + const SIDE: usize = SUPERBLOCK * 2; + const SIDE_MI: usize = SIDE / 4; + let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK); + let (mi_row, mi_col) = (root_r * 16, root_c * 16); + if root_r * 2 + 3 >= rows + || root_c * 2 + 3 >= cols + || (mi_row + SIDE_MI) as u32 > mi_rows + || (mi_col + SIDE_MI) as u32 > mi_cols + || x128 + SIDE > luma.true_width + || y128 + SIDE > luma.true_height + { + return None; + } + // One lambda for the whole root, the mean of what its four superblocks + // would each be searched at -- the 128-vs-four comparison weighs one cost + // against four, so both sides have to be priced at the same lambda (the + // same rule the 64 root's own mean-of-sixteen tpl cells follows). + let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) { + (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda, + (None, Some(f)) => { + let mean = (0..16) + .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4]) + .sum::() + / 16.0; + search.lambda * mean + } + (None, None) => search.lambda, + }; + let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)] + .iter() + .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc)) + .sum::() + / 4.0; + let root_search = Search { lambda, ..search }; + let stack = find_mv_stack( + grid, + mi_row, + mi_col, + SIDE_MI, + SIDE_MI, + LAST_FRAME, + mi_cols as usize, + mi_rows as usize, + ); + let base = snapshot(luma, chroma, (x128, y128), SIDE); + let found = search_skip_64( + luma, + chroma, + (x128, y128), + SIDE, + &root_search, + false, + reference, + &stack, + &[], + fctx, + ); + let (cost, block) = found?; + let after = snapshot(luma, chroma, (x128, y128), SIDE); + restore(luma, chroma, (x128, y128), SIDE, &base); + Some(( + cost + lambda * crate::tile::partition_bits(SIDE, false), + lambda, + block, + after, + )) +} + /// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]): /// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded /// SKIP, priced through the same `symbol_bits` path every other candidate @@ -9314,6 +9477,12 @@ fn search_skip_64( luma: &mut Plane, chroma: &mut [Plane; 2], (x, y): (usize, usize), + // The root's side in samples: [`SUPERBLOCK`] at a 64 root, twice that at + // the 128 one [`search_root_128`] drives (lane-b128). Every trial below + // is a square of this side and its half in chroma, and the residual arm + // is only ever asked for at 64 -- a 128 block's residual is four + // TX_64X64 units the writer has no path for. + side: usize, search: &Search, // Whether the non-skip arm is priced at all ([`b64_residual`], and off on // screen content -- see that function's doc). @@ -9326,7 +9495,7 @@ fn search_skip_64( compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], fctx: &crate::decode::FrameCtx, ) -> Option<(f64, BlockCoeffs)> { - let side = SUPERBLOCK; + debug_assert!(side == SUPERBLOCK || !residual, "a 128 root has no residual arm"); let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1); let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1); let ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack); @@ -11804,7 +11973,21 @@ pub(crate) fn encode_inter_frame( let sb_q: Option> = match (&tpl_factors, deltaq_res) { (Some(f), Some(res)) => { let libaom = dq_tpl_strength(dq_level); - Some((0..sb_cols * _sb_rows).map(|sb| sb_qindex(f, res, sb, libaom)).collect()) + let mut g: Vec = + (0..sb_cols * _sb_rows).map(|sb| sb_qindex(f, res, sb, libaom)).collect(); + // lane-b128m: under 128 superblocks the delta_q syntax is coded + // ONCE per 128 root (the reader's own unit), so all four 64x64 + // cells of a root have to be searched -- and quantized -- at the + // one qindex the root's top-left cell codes. + if sb128_on() { + for sb_r in 0.._sb_rows { + for sb_c in 0..sb_cols { + let q = g[(sb_r & !1) * sb_cols + (sb_c & !1)]; + g[sb_r * sb_cols + sb_c] = q; + } + } + } + Some(g) } _ => None, }; @@ -11904,8 +12087,63 @@ pub(crate) fn encode_inter_frame( rect.mi_col1 as usize, ); let mut blocks: Vec<(usize, Quadrant)> = Vec::new(); - for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize { - for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize { + // lane-b128: under a 128x128 superblock the search walks the roots the + // WRITER walks (`tile::sb_write_order`: TL, TR, BL, BR inside each root), + // not plain raster -- a search that visits BL before TR builds every mv + // stack and neighbour context off blocks the writer has not coded yet, + // which is what made the write-time drl clamp fire at all (lane-sb128b). + // At a 64 superblock the two orders are identical and this is the same + // raster loop as before. + let sb128_search = sb128_on(); + let root_step = if sb128_search { 2 } else { 1 }; + let mut roots: Vec<(usize, usize)> = Vec::new(); + { + let (r0, r1) = (rect.sb_row0 as usize, rect.sb_row1 as usize); + let (c0, c1) = (rect.sb_col0 as usize, rect.sb_col1 as usize); + let mut r = r0; + while r < r1 { + let mut c = c0; + while c < c1 { + roots.push((r, c)); + c += root_step; + } + r += root_step; + } + } + for (root_r, root_c) in roots { + // The 64x64 cells of this root, in the writer's own order. + let cells: Vec<(usize, usize)> = if sb128_search { + [(0, 0), (0, 1), (1, 0), (1, 1)] + .into_iter() + .map(|(dr, dc)| (root_r + dr, root_c + dc)) + .filter(|&(r, c)| r < rect.sb_row1 as usize && c < rect.sb_col1 as usize) + .collect() + } else { + vec![(root_r, root_c)] + }; + // What the four cells below really cost, against which the whole + // 128x128 candidate is weighed. + let mark128 = blocks.len(); + let mut root_cost = 0.0f64; + let root128 = (sb128_search && b128_root() && cells.len() == 4) + .then(|| search_root_128( + &mut luma, + &mut chroma, + &grid, + (root_r, root_c), + (rows, cols), + (header.mi_cols, header.mi_rows), + search, + &tpl_factors, + sb_q.as_ref(), + sb_cols, + tpl_cells_x, + base_q_idx, + reference, + fctx, + )) + .flatten(); + for (sb_r, sb_c) in cells { // lane-b64: the whole superblock as ONE 64x64 block, tried before // its quadrants are (`search_skip_64`) and compared against the // four of them below. Only a superblock wholly inside the true @@ -12004,6 +12242,7 @@ pub(crate) fn encode_inter_frame( &mut luma, &mut chroma, (x64, y64), + SUPERBLOCK, &sb_search, b64_residual() && !screen, reference, @@ -12473,6 +12712,27 @@ pub(crate) fn encode_inter_frame( let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2); blocks.push((r32 * cols + c32, Quadrant::Covered)); } + root_cost += cost64; + } else { + root_cost += sb_cost; + } + } + // lane-b128: the whole 128x128 root (`PARTITION_NONE` at the root's + // `partition_w128` symbol) against what its four superblocks really + // cost, the same weighing the 64 root does one size down. Both sides + // carry their own partition symbol, so the comparison is complete. + if let Some((cost128, lambda128, block, after)) = root128 + && cost128 < root_cost + lambda128 * crate::tile::partition_bits(128, true) + { + B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK); + blocks.truncate(mark128); + restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after); + record_mi(&mut grid, root_r * 16, root_c * 16, 32, block.inter, block.skip); + blocks.push(((root_r * 2) * cols + root_c * 2, Quadrant::Whole128(block))); + for q in 1..16 { + let (r32, c32) = (root_r * 2 + q / 4, root_c * 2 + q % 4); + blocks.push((r32 * cols + c32, Quadrant::Covered)); } } } @@ -12499,6 +12759,24 @@ pub(crate) fn encode_inter_frame( blocks[at] = quadrant; } + // lane-b128, `EC_AV1_B128_CENSUS=1`: how many of this INTER frame's 128 + // superblock roots the search left whole, so a flat BD result is + // attributable (class `gate-blind-to-feature`). A key frame codes none: + // only the inter writer has a 128x128 block. + if crate::envflags::env_flag!("EC_AV1_B128_CENSUS") { + let whole = blocks + .iter() + .filter(|q| matches!(q, Quadrant::Whole128(_))) + .count(); + let roots = blocks + .iter() + .filter(|q| !matches!(q, Quadrant::Covered)) + .count(); + eprintln!( + "B128 census: inter frame, {whole} whole 128x128 roots, {roots} coded blocks ({:.1}% of the frame's area at 128)", + 100.0 * (whole * 16) as f64 / blocks.len().max(1) as f64, + ); + } let modes = blocks .iter() .flat_map(Quadrant::blocks) @@ -12981,6 +13259,57 @@ mod tests { /// An [`crate::mvstack::MvStack`] with every context at zero and no /// neighbours, for the pricer tests below to fill the one band each of /// them is about. + /// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer + /// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL + /// against the same stack -- an offer the writer clamps prices the + /// residual against a predictor the decoder never derives, which is the + /// silent MV drift lane-sb128b root-caused (there fixed on the WRITER + /// side, so the stream stays legal; here the pricer's own offer set is + /// enumerated, class `enumerate-table-domain`). + /// + /// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer + #[test] + fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() { + for n in 0..=4usize { + let mut stack = bare_stack(); + for i in 0..n { + stack.entries.push(crate::mvstack::StackEntry { + mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)), + weight: 1, + }); + stack.drl_ctx.push(0); + } + stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv); + stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv); + stack.pred_mv = stack.nearest_mv; + // Aim the vector at each entry in turn, so every index the offer + // set holds is the one that wins at least once. + for target in 0..n.max(1) { + let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv); + let (_, idx) = best_new_mv_syntax(&stack, mv) + .expect("a zero residual is always codable"); + let idx = usize::from(idx); + assert_eq!( + crate::tile::signalled_drl_idx(n, 0, idx), + idx, + "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}", + ); + } + // The NEARMV arm's own offer set (`search_inter_block`, + // `search_skip_64`): indices 1 and 2, offered only when the stack + // really holds that entry. + for idx in 1..=2usize { + if stack.entries.get(idx).is_some() { + assert_eq!( + crate::tile::signalled_drl_idx(n, 1, idx), + idx, + "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}", + ); + } + } + } + } + fn bare_stack() -> crate::mvstack::MvStack { crate::mvstack::MvStack { entries: Default::default(), @@ -13432,7 +13761,11 @@ mod tests { /// (the horizontal shapes, which those partitions never produce). #[test] fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() { - let fctx = &crate::decode::FrameCtx::for_encoder(); + // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so + // it pins the 64 reach explicitly instead of following the process's + // own superblock knob (`for_encoder`), which made it red under + // `EC_AV1_SB128=1` for no defect of the code under test. + let fctx = &crate::decode::FrameCtx::new(); // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum). const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [ (4, 8, 64, 9280, 64, 550), @@ -14359,7 +14692,11 @@ mod tests { /// wrong for one block size while looking plausible for the other. #[test] fn reach_matches_libaom_has_top_right_and_has_bottom_left() { - let fctx = &crate::decode::FrameCtx::for_encoder(); + // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so + // it pins the 64 reach explicitly instead of following the process's + // own superblock knob (`for_encoder`), which made it red under + // `EC_AV1_SB128=1` for no defect of the code under test. + let fctx = &crate::decode::FrameCtx::new(); // Transcribed from has_top_right/has_bottom_left's row_off==0, // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a // 128px reference grid) pinned as libaom pins it, independent of the @@ -15644,6 +15981,86 @@ mod tests { /// /// cargo test -p ec-av1 --release --lib -- --ignored \ /// a_128_superblock_clip_whose_drl_index_the_write_time_stack --nocapture + /// lane-b128: the 128x128 `PARTITION_NONE` root -- one block, one mode + /// and one motion vector where the four 64x64 roots below spend four of + /// each (cen3's L1). The counter is the gate on the fixture (class + /// `gate-blind-to-feature`): a green round trip on a clip that never + /// codes a 128x128 block proves nothing. RED before the search existed + /// (zero such blocks coded, `tile::write_sb128_root` wrote SPLIT at every + /// root by construction). + /// + /// Both readers: our own decoder sample-exact against the encoder's + /// reconstruction (a writer/reader desync surfaces as a pixel miss or a + /// refusal here, not in the BD gate) AND ffmpeg as the bitstream oracle. + /// + /// `#[ignore]`: [`force_sb128`] moves a process-global. + /// + /// cargo test -p ec-av1 --release --lib -- --ignored \ + /// a_128_superblock_clip_whose_root_search --nocapture + #[test] + #[ignore = "sets the process-global superblock size: run it alone"] + fn a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact() { + let _knobs = crate::speed::knob_write(); + if !have_ffmpeg() { + eprintln!("SKIP: no ffmpeg"); + return; + } + force_sb128(true); + let dir = std::env::temp_dir().join(format!("ec-av1-b128-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let clip = dir.join("smpte-1280x768.y4m"); + // A slow horizontal pan over a still pattern: whole 128x128 regions + // share one motion vector, which is exactly what a 128 root can code + // as one block and four 64 roots cannot. + let ok = Command::new("ffmpeg") + .args(["-v", "error", "-y", "-f", "lavfi"]) + .args(["-i", "smptebars=size=1600x768:rate=24"]) + .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"]) + .args(["-pix_fmt", "yuv420p"]) + .arg(&clip) + .status() + .expect("ffmpeg failed to run") + .success(); + assert!(ok, "ffmpeg could not write the synthetic clip"); + let (width, height) = (1280usize, 768usize); + let pictures = + crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8); + let _ = take_b128_none_hits(); + let _ = crate::tile::take_sb128_none_hits(); + let encoded = encode_sequence(&pictures, 150, 0.5).unwrap(); + let (won, coded) = (take_b128_none_hits(), crate::tile::take_sb128_none_hits()); + eprintln!("128x128 PARTITION_NONE blocks: search won {won}, writer coded {coded}"); + assert!( + coded > 0, + "no 128x128 block was coded on this clip, so it cannot witness the root search", + ); + assert_eq!(won, coded, "every 128x128 root the search took must be coded as one"); + let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); + assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); + for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { + let recon = &frame.reconstruction; + for (plane, got, want) in [ + ("luma", &dec.y, &recon.y), + ("U", &dec.u, &recon.u), + ("V", &dec.v, &recon.v), + ] { + let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); + assert_eq!( + differ, 0, + "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \ + own reconstruction", + got.len() + ); + } + } + let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); + for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { + assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma"); + assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U"); + assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V"); + } + } + #[test] #[ignore = "sets the process-global superblock size: run it alone"] fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() { @@ -17076,7 +17493,15 @@ mod tests { // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's // pixels -- and the leaves that predict from them -- moved: // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60. - let pins: [(u8, usize, u64); 2] = [(150, 8218, 0xd533_c8ea_14ca_ae6e), (60, 33017, 0xbced_b694_dcfe_9146)]; + // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so + // the shipped stream did not move. + // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every + // picture is coded in 128x128 superblocks now, the inter ones + // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at + // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053. + // Re-taken at the merge of lane-b128m onto main (128 superblocks on + // by default, on top of the ARF temporal filter). + let pins: [(u8, usize, u64); 2] = [(150, 8354, 0x1290b8628438c6d4), (60, 33222, 0xc7f92971ab1264c3)]; let coded: Vec<(u8, usize, u64)> = pins .iter() .map(|&(q, _, _)| { @@ -18360,6 +18785,11 @@ mod tests { {i64_edge} on a superblock the frame edge cuts", 100.0 * i64_whole as f64 / i64_offered.max(1) as f64, ); + eprintln!( + "{name}: 128x128 roots {} (search) / {} (writer)", + take_b128_none_hits(), + crate::tile::take_sb128_none_hits(), + ); eprintln!( "{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})", take_b64_root_hits(), diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index 6feab2d1..905bda4d 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -3819,6 +3819,19 @@ mod tests { tile_rows_log2: rows_log2, }; let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); + // lane-b128m: the SPEC's uniform spacing derives the tile count + // from the superblock grid (`tileWidthSb = ceil(sbCols >> log2)`), + // so a frame with fewer superblock columns than the requested + // count codes fewer tiles -- which is what a 128-superblock + // sequence does here. The grid the encoder itself computes is the + // expectation; at 64 superblocks it is `1 << log2` exactly. + let grid = crate::tile::TileLayout::new( + (width as u32).div_ceil(4), + (height as u32).div_ceil(4), + cols_log2, + rows_log2, + ); + let (want_cols, want_rows) = (grid.cols(), grid.rows()); let mut enc = Av1Encoder::new(config).unwrap(); let mut stream = Vec::new(); for packet in encode_all(&mut enc, &sources) { @@ -3837,12 +3850,12 @@ mod tests { if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind { assert_eq!( (parsed.tile_info.cols, parsed.tile_info.rows), - (1 << cols_log2, 1 << rows_log2), + (want_cols, want_rows), "{layout}: the header's own tile grid" ); assert_eq!( tiles.len(), - 1 << (cols_log2 + rows_log2), + (want_cols * want_rows) as usize, "{layout}: tile payloads located in the tile group" ); frames += 1; diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index a2ac57da..86e285a9 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -3014,7 +3014,10 @@ pub(crate) mod tests { /// the encoder's own reconstruction, at an even and an odd size. #[test] fn decode_stream_matches_the_tile_path_on_a_key_frame() { - let fctx = &crate::decode::FrameCtx::new(); + // lane-b128m: the ENCODER writes at this process's superblock size, so + // its own trial decode -- and the raw tile decode below -- must be given + // that size too (class: stale header in the test harness). + let fctx = &crate::decode::FrameCtx::for_encoder(); for &(width, height) in &[(64usize, 64usize), (216, 96)] { let picture = test_card(width, height); let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); @@ -3085,7 +3088,7 @@ pub(crate) mod tests { #[test] fn decode_stream_round_trips_a_gop() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::for_encoder(); gop_round_trips(128, 64, fctx); } @@ -3093,7 +3096,7 @@ pub(crate) mod tests { /// the inter frame's 16x16-leaf split path is exercised too. #[test] fn decode_stream_round_trips_an_odd_size_gop() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::for_encoder(); gop_round_trips(216, 96, fctx); } @@ -3105,7 +3108,7 @@ pub(crate) mod tests { /// decode indices non-decreasing, and an `Err` from the sink aborting. #[test] fn streaming_decode_matches_the_collecting_one() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::for_encoder(); let pictures: Vec<_> = (0..4).map(|i| panned_test_card(128, 64, i * 3)).collect(); let stream = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap().stream; let collected = decode_stream(&stream).unwrap(); @@ -3464,7 +3467,7 @@ pub(crate) mod tests { /// independent decoder, not just this crate checking its own tile path. #[test] fn decode_stream_agrees_with_ffmpeg_on_a_gop() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::for_encoder(); if !have_ffmpeg() { eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg"); return; @@ -3518,7 +3521,7 @@ pub(crate) mod tests { /// geometry that never fires it. #[test] fn a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::for_encoder(); if !have_ffmpeg() { eprintln!("SKIP a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg: no ffmpeg"); return; @@ -3578,7 +3581,7 @@ pub(crate) mod tests { /// reconstruction, and ffmpeg. #[test] fn a_doubly_cut_superblock_root_round_trips_in_every_plane() { - let fctx = &crate::decode::FrameCtx::new(); + let fctx = &crate::decode::FrameCtx::for_encoder(); if !have_ffmpeg() { eprintln!("SKIP a_doubly_cut_superblock_root_round_trips_in_every_plane: no ffmpeg"); return; diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 772058ab..d8f600d0 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -175,6 +175,12 @@ fn write_sb128_root( sb_c: u32, mi_cols: u32, mi_rows: u32, + // lane-b128: the partition the root's own search chose -- + // `PARTITION_SPLIT` (the four 64x64 quadrants below, which is every root + // this writer coded before) or `PARTITION_NONE` (one 128x128 block, + // written by the caller right after this). Only offered at a root wholly + // inside the frame, so the gathered edge arms below still code SPLIT. + part: usize, ) { SB128_ROOT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let (mi_r128, mi_c128) = ((sb_r & !1) * SB_MI, (sb_c & !1) * SB_MI); @@ -186,7 +192,7 @@ fn write_sb128_root( eprintln!("WTRACE partition_w128 ctx={ctx128} cols={has_cols128} rows={has_rows128}"); } match (has_cols128, has_rows128) { - (true, true) => enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w128[ctx128]), + (true, true) => enc.symbol(part, &mut cdfs.partition_w128[ctx128]), // As at the 64 root: the gathered CDF is built for the read and // thrown away, so nothing adapts here. Value 1 is SPLIT. (true, false) => enc.symbol_fixed( @@ -203,6 +209,160 @@ fn write_sb128_root( } } +/// lane-b128: one 128x128 inter block at a `PARTITION_NONE` 128 superblock +/// root -- the syntax `decode_inter_block` reads for `sb128_none` (decode.rs +/// ~35110): `skip`, `is_inter`, the reference/mode chain at the block's own +/// 32x32-mi window, the motion mode, and the transform syntax, with the mi +/// grid and every neighbour band published over all thirty-two mi cells. +/// +/// SKIP only, and refused otherwise: a 128x128 block's residual is four +/// TX_64X64 luma units interleaved with a TX_32X32 chroma pair per 64x64 mu +/// chunk (the chroma units reading the offset-10 `txb_skip` rows), which +/// this writer has no path for. A skipped block writes no `cdef_idx` and no +/// `delta_q` either, exactly as the 64 root's skip arm does. +/// +/// # Errors +/// A block that is intra, or carries a residual, at this size. +#[allow(clippy::too_many_arguments)] +fn write_inter_block_128( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + grid: &mut MiGrid, + // The root's top-left position in [`SUB`] (16x16) units. + sb_at: (usize, usize), + block: &BlockCoeffs, + mi_cols: u32, + mi_rows: u32, + tx_select: bool, +) -> Result<()> { + /// The block's side in samples and in 4x4 mode-info units. + const SIDE: usize = 128; + const SIDE_MI: usize = SIDE / MI; + let info = block.inter.ok_or_else(|| { + Error::unsupported("AV1 tile", "a 128x128 superblock root block is coded inter") + })?; + if !block.skip { + return Err(Error::unsupported( + "AV1 tile", + "a 128x128 superblock root block carries a residual", + )); + } + let (mi_r, mi_c) = (sb_at.0 * (SUB / MI), sb_at.1 * (SUB / MI)); + let has_above = neighbours.has_above(mi_r); + let has_left = neighbours.has_left(mi_c); + let skip_ctx = + usize::from(neighbours.above_skip[mi_c]) + usize::from(neighbours.left_skip[mi_r]); + enc.symbol(1, &mut cdfs.skip[skip_ctx]); + write_cdef_idx(enc, (mi_r, mi_c), true); + write_delta_q(enc, cdfs, (mi_r, mi_c), true, true); + let ii_ctx = intra_inter_ctx( + has_above, + has_left, + neighbours.above_inter[mi_c], + neighbours.left_inter[mi_r], + ); + enc.symbol(1, &mut cdfs.intra_inter[ii_ctx]); + write_comp_mode( + enc, + cdfs, + neighbours, + (mi_r, mi_c), + (has_above, has_left), + info.ref1.is_some(), + ); + let (mv, mv1, is_new_mv) = if info.ref1.is_some() { + write_compound_block( + enc, + cdfs, + neighbours, + grid, + (mi_r, mi_c), + (SIDE_MI, SIDE_MI), + (has_above, has_left), + info, + (mi_cols as usize, mi_rows as usize), + )? + } else { + write_single_ref( + enc, + cdfs, + info.ref_frame, + neighbours.above_ref[mi_c], + neighbours.above_ref1[mi_c], + neighbours.left_ref[mi_r], + neighbours.left_ref1[mi_r], + ); + let stack = find_mv_stack( + grid, + mi_r, + mi_c, + SIDE_MI, + SIDE_MI, + info.ref_frame, + mi_cols as usize, + mi_rows as usize, + ); + let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?; + (mv, (0, 0), is_new_mv) + }; + for dr in 0..SIDE_MI { + for dc in 0..SIDE_MI { + grid.set( + mi_r + dr, + mi_c + dc, + MiInfo { + is_inter: true, + ref_frame: info.ref_frame, + ref_frame1: info.ref1.unwrap_or(NO_REF1), + mv1: mv16(mv1), + mv: mv16(mv), + is_new_mv, + size: SIDE_MI as u8, + size_h: SIDE_MI as u8, + is_global_mv0: false, + is_global_mv1: false, + }, + ); + } + } + if info.ref1.is_none() { + write_motion_mode( + enc, + cdfs, + grid, + (mi_r, mi_c), + (SIDE_MI, SIDE_MI), + (SIDE, SIDE), + (mi_cols as usize, mi_rows as usize), + info.ref_frame, + block.motion_mode, + )?; + } + if tx_select { + write_tx_syntax_inter(enc, cdfs, neighbours, (mi_r, mi_c), SIDE, true, true, 0); + } + let zero_grids = [ + vec![0i32; TX32 * TX32], + vec![0i32; TX32 * TX32], + vec![0i32; TX32 * TX32], + ]; + neighbours.record(sb_at, SIDE, 0, &zero_grids); + neighbours.record_inter(sb_at, SIDE, true, true, block_ref(block)); + record_block_compound(neighbours, (mi_r, mi_c), SIDE, block); + SB128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Ok(()) +} + +/// How many 128x128 `PARTITION_NONE` blocks the inter writer has coded since +/// the last [`take_sb128_none_hits`] (class `gate-blind-to-feature`). +static SB128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// The 128x128-block count since the last call, and zero it. +pub fn take_sb128_none_hits() -> usize { + SB128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) +} + /// `read_lr`'s write side, called once at the top of every superblock, /// before its partition symbol: writes the units this superblock's own /// mi span covers (`av1_loop_restoration_corners_in_sb`; no superres, so the @@ -1279,7 +1439,12 @@ fn write_delta_q( DELTA_Q.with(|c| { let mut plan = c.borrow_mut(); let Some(plan) = plan.as_mut() else { return }; - if mi.0 % SB_MI as usize != 0 || mi.1 % SB_MI as usize != 0 { + // lane-b128m: the delta_q unit is the SUPERBLOCK, so it is 128 wide + // under `EC_AV1_SB128` -- decode.rs `maybe_read_delta_q` gates on + // `sb_mi_cur`, and a writer gating on a hardcoded 64 codes three + // symbol groups per 128 root the reader never reads. + let sb_mi = if sb128_armed() { SB_MI as usize * 2 } else { SB_MI as usize }; + if mi.0 % sb_mi != 0 || mi.1 % sb_mi != 0 { return; } if is_whole_sb && skip { @@ -2059,6 +2224,15 @@ pub enum Quadrant { /// whose coded quarter is a 32x32 level grid, and one TX_32X32 per chroma /// plane (lane-tx64, `crate::encode::b64_residual`). Whole64(BlockCoeffs), + /// lane-b128: the whole 128x128 SUPERBLOCK ROOT this quadrant is the + /// top-left of, coded as one block (`PARTITION_NONE` at the root's + /// `partition_w128` symbol). Carried by the top-left 32x32 entry of the + /// root's sixteen; the other fifteen carry [`Covered`](Quadrant::Covered). + /// + /// SKIP only: a 128x128 block's residual is four TX_64X64 luma units + /// interleaved with its chroma per 64x64 mu chunk, which this writer has + /// no path for; [`crate::tile::write_inter_block_128`] refuses one. + Whole128(BlockCoeffs), /// A quadrant a [`Whole64`](Quadrant::Whole64) at its superblock's /// top-left already coded; it carries no block of its own. Covered, @@ -2068,7 +2242,9 @@ impl Quadrant { /// The blocks it carries, in the order they are coded. pub(crate) fn blocks(&self) -> &[BlockCoeffs] { match self { - Quadrant::Whole(block) | Quadrant::Whole64(block) => std::slice::from_ref(block), + Quadrant::Whole(block) | Quadrant::Whole64(block) | Quadrant::Whole128(block) => { + std::slice::from_ref(block) + } Quadrant::Split(blocks) => blocks.as_slice(), Quadrant::Covered => &[], } @@ -2948,7 +3124,7 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs( neighbours.start_row(); } if sb128 && sb_start { - write_sb128_root(&mut enc, &mut cdfs, &neighbours, sb_r, sb_c, mi_cols, mi_rows); + write_sb128_root(&mut enc, &mut cdfs, &neighbours, sb_r, sb_c, mi_cols, mi_rows, PARTITION_SPLIT); } { if !sb128 { @@ -3065,7 +3241,7 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs( match quadrant { // A 64x64 root is an INTER-frame partition; a // key frame codes one as `Superblock::Whole`. - Quadrant::Whole64(_) | Quadrant::Covered => { + Quadrant::Whole64(_) | Quadrant::Whole128(_) | Quadrant::Covered => { return Err(Error::unsupported( "AV1 tile", "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) { }); let mut pred = stack_pred.unwrap_or((0, 0)); if pred == (0, 0) { - // 64x64 superblocks: the only size this encoder's sequence header - // signals (`use_128x128_superblock: false`), so `mib_size` is 16 mi. - // The tile row start is 0, exactly as decode.rs `read_intrabc_dv` - // takes it -- both are written for the single-tile-row streams this - // encoder produces. - let sb_mi = 16i32; + // `av1_find_ref_dv` takes `mib_size`, the SEQUENCE's superblock size + // in mi units (lane-b128m: hardcoding 16 here made the writer's DV + // predictor one 64 superblock up while decode.rs `read_intrabc_dv` + // took 128 -- identical symbols, different reconstructed DV). The + // tile row start is 0, exactly as the reader takes it -- both are + // written for the single-tile-row streams this encoder produces. + let sb_mi = if sb128_armed() { 32i32 } else { 16i32 }; let sb_px = sb_mi * MI as i32; pred = if (mi_r as i32) < sb_mi { (0, -(sb_px + INTRABC_DELAY_PIXELS) * 8) @@ -4729,6 +4906,10 @@ pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 { .iter() .map(|q| { let side = match q { + // lane-b128: a 128x128 root is SKIP by construction (the + // writer refuses a residual at that size), so it names no + // coefficients on any plane. + Quadrant::Whole128(_) => return 0.0, Quadrant::Whole(_) => 32, Quadrant::Split(_) => 16, // 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 { static CDFS: LazyLock = LazyLock::new(|| Cdfs::new(2)); let cdfs = &*CDFS; let cdf: &[u16] = match side { + // lane-b128: the 128 superblock root's own eight-symbol alphabet. + 128 => &cdfs.partition_w128[0], SB => &cdfs.partition_w64[0], BLOCK => &cdfs.partition_w32[0], TX8 => &cdfs.partition_w8[0], @@ -6114,6 +6297,19 @@ pub(crate) fn take_drl_hits() -> [usize; 4] { /// signalled index 1 and priced the residual against `pred_mv`, and the /// decoder's MV silently drifted a whole frame before the drl symbols /// desynced). +/// The DRL index [`write_drl_idx`]'s walk can actually SIGNAL against a stack +/// of `entries` candidates: at most two `drl_mode` symbols past `start`, and +/// each one needs a further entry to advance into (spec 5.11.24's +/// `for (idx = 0; idx < 2; idx++) if (NumMvFound > idx + 1)`). +/// +/// A search that offers an index this clamps prices its residual against a +/// predictor the decoder never derives (lane-sb128b's silent MV drift); the +/// pricer's own offer set is enumerated against this rule by +/// `crate::encode::tests::every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal`. +pub(crate) fn signalled_drl_idx(entries: usize, start: usize, target: usize) -> usize { + target.min(start + 2).min(entries.saturating_sub(1)).max(start) +} + fn write_drl_idx( enc: &mut SymbolEncoder, cdfs: &mut Cdfs, @@ -6121,6 +6317,17 @@ fn write_drl_idx( start: usize, target: usize, ) -> usize { + debug_assert_eq!( + signalled_drl_idx(stack.entries.len(), start, target), + { + let mut i = start; + while i < start + 2 && stack.entries.len() > i + 1 && i < target { + i += 1; + } + i + }, + "the drl clamp rule and the writer's own walk disagree", + ); let mut idx = start; while idx < start + 2 && stack.entries.len() > idx + 1 { let advance = idx < target; @@ -6377,6 +6584,9 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( ]; let sb128 = sb128_armed(); + // lane-b128: set at a root whose own `PARTITION_NONE` 128x128 block was + // just written, so the root's remaining 64x64 cells code nothing. + let mut sb128_none = false; // lane-sb128: at a 128 superblock the four 64x64 cells of each root are // written in libaom's own TL/TR/BL/BR order, the root's restoration units // 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( if row_start { neighbours.start_row(); } + if sb_start { + sb128_none = false; + } + // lane-b128: the remaining three 64x64 cells of a root the search + // left WHOLE carry no syntax at all -- the same skip the decoder's + // own `sb128_none` runs. + if sb128_none { + continue; + } if sb128 && sb_start { - write_sb128_root(&mut enc, &mut cdfs, &neighbours, sb_r, sb_c, mi_cols, mi_rows); + // The 128x128 block a `PARTITION_NONE` root carries, held by the + // top-left 32x32 entry of the root's sixteen. + let root_block = ((sb_r & !1) * 2 < rows && (sb_c & !1) * 2 < cols) + .then(|| &blocks[(((sb_r & !1) * 2) * cols + (sb_c & !1) * 2) as usize]) + .and_then(|q| match q { + Quadrant::Whole128(block) => Some(block), + _ => None, + }); + write_sb128_root( + &mut enc, + &mut cdfs, + &neighbours, + sb_r, + sb_c, + mi_cols, + mi_rows, + if root_block.is_some() { PARTITION_NONE } else { PARTITION_SPLIT }, + ); + if let Some(block) = root_block { + let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4); + write_inter_block_128( + &mut enc, + &mut cdfs, + &mut neighbours, + &mut grid, + at128, + block, + mi_cols, + mi_rows, + tx_select, + )?; + sb128_none = true; + continue; + } } { if !sb128 { @@ -6438,7 +6690,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( + usize::from(neighbours.left_skip[mi_r]); enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]); write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip); - write_delta_q(&mut enc, &mut cdfs, (mi_r, mi_c), true, block.skip); + write_delta_q(&mut enc, &mut cdfs, (mi_r, mi_c), !sb128_armed(), block.skip); let ii_ctx = intra_inter_ctx( has_above, has_left, @@ -6638,7 +6890,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( let block = match site { // Already coded by the `Whole64` above -- but only inside // a superblock that really carried one. - Quadrant::Whole64(_) | Quadrant::Covered => { + Quadrant::Whole64(_) | Quadrant::Whole128(_) | Quadrant::Covered => { return Err(Error::unsupported( "AV1 tile", "a `Whole64`/`Covered` quadrant needs its superblock's \ diff --git a/lanes/b128.report.md b/lanes/b128.report.md new file mode 100644 index 00000000..c7a4a1e4 --- /dev/null +++ b/lanes/b128.report.md @@ -0,0 +1,206 @@ +# lane-b128 — a real 128x128 root under `EC_AV1_SB128` + +Three results: + +1. **Task 0 (the drl pricer) is a STALE premise, and now has its enumeration + test.** The charter's `encode.rs:8722` mis-pricing was already closed by + the lane-sb128b merge on the WRITER side; the pricer's own offer set is + provably clamp-free against its own stack. +2. **The 128x128 `PARTITION_NONE` root is implemented, witnessed and + MEASURED** — and it turns lane-sb128b's refutation around: film B + +24.2%/−2.5% vs libaom cpu-6 / rav1e s6 with 128 superblocks ON, against + the SPLIT-only arm's +37.5%/+7.3%. +3. **HORZ/VERT (128x64, 64x128) are deferred** — see the disposition below. + +## 1. Task 0 — the drl offer set, enumerated + +`crate::tile::signalled_drl_idx(entries, start, target)` is the writer's +clamp rule as one pure function (`write_drl_idx`'s own walk now carries a +`debug_assert_eq!` against it, so the two cannot drift). The pricer's offer +set is enumerated against it over every stack size 0..=4, for both the +`NEWMV` (`best_new_mv_syntax`) and the `NEARMV` (`entries.get(idx)`) arms: + + cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer + test encode::tests::every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal ... ok + +GREEN as written: `best_new_mv_syntax` breaks at `entries.len() <= idx`, +which is exactly `write_drl_idx`'s `entries.len() > idx + 1` condition, so +no offered index is ever clamped **against the same stack**. Byte effect: +none — the pins are byte-identical (below). The residual error the report +open item names is entirely the SEARCH-time vs WRITE-time stack divergence +(lane-sb128b's second open item), which no change on this line can reach. + +## 2. The 128 root + +### What moved + +- `tile.rs` — `Quadrant::Whole128(BlockCoeffs)`; `write_sb128_root` takes the + partition value; `write_inter_block_128` writes the block (`skip`, + `is_inter`, the reference/mode chain at a 32x32-mi window, motion mode, tx + syntax, mi grid + neighbour bands over all 32 mi cells); the inter tile + loop skips the root's remaining three 64x64 cells, mirroring the decoder's + own `sb128_none`; `partition_bits` gained the 128 row; + `signalled_drl_idx`; `take_sb128_none_hits`. +- `encode.rs` — `search_root_128` (the candidate, its legality and its + lambda), `search_skip_64` parameterised by `side`, the tile search loop + restructured into ROOTS x cells, the 128-vs-four decision, + `take_b128_none_hits`, the `EC_AV1_B128_CENSUS=1` per-frame line. + +### Deliberate limits (deviations from the charter, each with its reason) + +- **SKIP only.** A 128x128 block's residual is four TX_64X64 luma units + interleaved with a TX_32X32 chroma pair per 64x64 mu chunk (the chroma + units on the offset-10 `txb_skip` rows), plus one `txfm_partition` symbol + per chunk. Neither the writer nor `Plane::code_from_prediction` has that + path; `write_inter_block_128` REFUSES a non-skip block rather than coding + one wrong. `search_root_128` therefore offers `residual: false`. +- **Single reference only.** The compound arm at 128 would go through + `write_compound_block` at a window size it has never been exercised at. +- **Inter frames only.** A key frame's 128 root still writes SPLIT. +- **HORZ / VERT deferred.** Two 128x64 / 64x128 blocks need rect neighbour + recording and rect prediction/SSE on the WRITER and SEARCH sides (the + decoder already reads both, lane-sb128c r7); the square NONE arm reuses + every existing square helper unchanged. + +### Witness (red before / green after) + +`encode::tests::a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact` +(`--ignored`, it moves the process-global superblock size): + + cargo test -p ec-av1 --release --lib -- --ignored \ + a_128_superblock_clip_whose_root_search --nocapture + 128x128 PARTITION_NONE blocks: search won 406, writer coded 406 + test ... ok + +8 frames, 1280x768, a slow pan over `smptebars` at `force_sb128(true)`: +**406** 128x128 blocks coded, every frame sample-exact against the encoder's +own reconstruction through `decode_stream` AND through ffmpeg. RED before +this lane by construction: `write_sb128_root` wrote `PARTITION_SPLIT` at +every root, so the count was 0 and no such block existed to decode. + +### Census (`EC_AV1_B128_CENSUS=1`, plus a per-row count in the gate) + +Per row, over the four-quantizer ladder (search took / writer coded -- the +writer is higher because the filter search re-codes each tile): + +| row | 128 roots taken | writer-coded | +|---|---|---| +| bars 1080p | 3448 | 6013 | +| bars 2160p | 4144 | 5827 | +| film A | 505 | 1241 | +| film B | 1928 | 3189 | +| screen capture | 4736 | 4774 | + +Per frame on film B the census reads e.g. `100 whole 128x128 roots, 336 +coded blocks (83.3% of the frame's area at 128)` -- the lever cen3's L1 +asked for (38754 coded blocks vs libaom's 16178) is really being pulled. +All of them are on INTER frames: a key frame's 128 root still writes SPLIT. + +## 3. The gate + +`bd_rate_screen_native`, 12 frames, four quantizers, BD-rate vs libaom +`cpu-used 6` / rav1e `speed 6` (lower is better). Both arms from THIS tree, +both controls reproduced (not taken from the charter): + +| row | 64 superblocks (control) | 128 + the 128 root | +|---|---|---| +| bars 1080p | −2.6 / −18.3 | **−3.3 / −18.9** | +| bars 2160p | +8.8 / −13.2 | **+7.9 / −14.0** | +| film A (1080p) | +20.6 / −5.1 | **+20.4 / −5.2** | +| film B (2160p) | +24.8 / −2.1 | **+24.2 / −2.5** | +| screen capture | +14.6 / −33.2 | **+14.4 / −33.2** | + +Long GOP (`bd_rate_film_long_gop`, 48 frames): + +| row | 64 superblocks | 128 + the 128 root | +|---|---|---| +| film A | +24.7 / −7.5 | **+24.4 / −7.7** | +| film B | +86.8 / +7.4 | **+85.6 / +6.6** | + +The 2x2 the charter asked for (film B, 12 frames): + +| arm | vs libaom | vs rav1e | +|---|---|---| +| SB64, LR on (control) | +24.8% | −2.1% | +| SB128 + 128 root, LR on | **+24.2%** | **−2.5%** | +| SB128 + 128 root, LR off (`EC_AV1_LR=0`) | +24.6% | −2.3% | + +(The SB64 LR-off control was not re-run: the SB64 path is byte-identical to +the control tree -- the pins prove it -- and lane-sb128b measured it at ++25.4/−1.6. The forced ≥128 LR unit is no longer a loss: LR ON is the better +arm on both columns now, the reverse of lane-sb128b's reading.) + +Every row of both gates is down or flat on both columns. The keep rule +HOLDS -- and the default still does not flip. See below. + +## 4. Why the default stays OFF (the blocker, not this lane's) + +With `EC_AV1_SB128=1`, **eleven** of this crate's own round-trip tests fail, +and they fail with the 128x128 BLOCK switched off (`EC_AV1_B128=0`) too -- +i.e. they are lane-sb128's SPLIT-only plumbing, at sizes its own 256x128 +witness never covered: + + stream::tests::decode_stream_round_trips_a_gop + stream::tests::decode_stream_round_trips_an_odd_size_gop + stream::tests::decode_stream_agrees_with_ffmpeg_on_a_gop + stream::tests::decode_stream_matches_the_tile_path_on_a_key_frame + stream::tests::streaming_decode_matches_the_collecting_one + stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane + stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_through_ffmpeg + encoder::tests::every_tile_layout_decodes_sample_exact_through_both_decoders + encoder::tests::tile_bytes_do_not_depend_on_the_thread_count + encoder::tests::a_moving_detail_clip_codes_two_delta_q_levels_both_decoders_read_exactly + encode::tests::a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly + +`decode_stream_round_trips_a_gop` fails with exactly the refusal lane-sb128b +root-caused ("a reference frame selected with no picture at this frame's own +ref_frame_idx slot"), so at least one writer/reader desync is still live in +the 128 path at odd sizes / multiple tiles. Two more +(`encode::tests::reach_matches_libaom_has_top_right_and_has_bottom_left`, +`every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock`) are +TEST staleness: they assert libaom's 64-superblock reach tables against a +process whose superblock size is 128. + +A 0.6-point BD win does not buy shipping that, so `SB128_DEFAULT` stays +`false` and the whole feature stays behind `EC_AV1_SB128=1`. The next lane +is named by this list. + +## 5. A defect fixed on the way (class: stale header in the test harness) + +Ten decode round-trip tests encode with THIS process's encoder and then +decode the tile directly with a plain `FrameCtx`, whose superblock size is +the DECODER default (64) -- not the size the writer used. With 128 +superblocks on, the reader skipped the root's partition symbol and the tile +desynced at symbol 0 (found by `EC_AV1_SYMTRACE`: the reader's first symbol +was the writer's second). `FrameCtx::for_encoder` exists for exactly this +and is now used in all ten; the module was swept, and two of the ten were +not failing yet. Same shape as the `filter_intra_on()` argument beside them. + +## Disposition + +- `deferred`: **HORZ / VERT at the 128 root** (two 128x64 / 64x128 blocks) -- + the writer has no rect neighbour recording and the search no rect + prediction/SSE at this size; the square NONE arm needed neither. Unblocked + by a rect `record_inter`/`record` pair plus a rect trial in + `search_root_128`. The decoder already reads both (lane-sb128c r7). +- `deferred`: **the 128 block's residual and its compound arm** -- four + TX_64X64 luma units interleaved with a TX_32X32 chroma pair per mu chunk, + on the offset-10 `txb_skip` rows, plus one `txfm_partition` symbol per + chunk. Unblocked by that writer path; `write_inter_block_128` refuses a + non-skip block until then, so nothing can silently code one wrong. +- `deferred`: **the intra 128 root on key frames** -- the key-frame writer + codes SPLIT at every 128 root, as before. +- `open`: the eleven pre-existing 128-superblock desyncs above (the default's + blocker). +- `open`: search-time vs write-time mv stacks still differ (lane-sb128b's own + second open item); the writer's clamp makes it safe, not right. + +## Suite / checks (default OFF, the shipped state) + + s1 --skip stream:: 340 passed; 0 failed; 34 ignored (RC=0) + s2 stream:: --skip 10bit 200 passed; 0 failed; 15 ignored (RC=0) + s3 10bit 42 passed; 0 failed; 1 ignored (RC=0) + --ignored every_speed_preset_decodes_sample_exact_through_both_decoders ok + --ignored a_128_superblock_clip_whose_root_search... ok (406 blocks) + the_encoders_own_streams_are_byte_identical_to_their_pins ok, and ok at EC_AV1_SPEED=6 + cargo check --workspace --all-targets 0 errors, 0 ec-av1 warnings diff --git a/lanes/b128m.report.md b/lanes/b128m.report.md new file mode 100644 index 00000000..46b2109c --- /dev/null +++ b/lanes/b128m.report.md @@ -0,0 +1,127 @@ +# lane-b128m — the eleven 128-superblock desyncs, and the default flip + +`SB128_DEFAULT` is **true**: every sequence this encoder writes codes +128x128 superblocks, with lane-b128's `PARTITION_NONE` 128 root inside them. +Four defects closed, each with its own first divergent symbol. + +## 1. The delta_q unit is the 128 superblock (`0aa5a5e3`) + +Defect 0 of the charter, and new at this merge (per-SB delta_q from lane-dq +met 128 superblocks from lane-b128 — class *merge cross-product defect*). + +- **First divergent symbol**: the SECOND 64x64 cell's `delta_q_abs` inside a + 128 root. `tile::write_delta_q` gated on a hardcoded `SB_MI` (64), while + decode.rs `maybe_read_delta_q` gates on `sb_mi_cur` — so the writer coded + four symbol groups per 128 root and the reader read one. It surfaced frames + later as the arf's "a reference frame selected with no picture at this + frame's own ref_frame_idx slot". +- Two more halves of the same defect: the 64-root whole-block call passed + `is_whole_sb = true` under a 128 superblock (which suppresses the read on + the wrong side), and the search-side `sb_q` grid gave each 64 cell its own + qindex when only the root's top-left one is coded — flattened per 128 root + so a cell is quantized at the qindex its root signals. +- Witness: `encode::tests::a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact` + (`--ignored`) — red with the refusal above, green after (405 blocks). + +## 2. The superblock size travels with a `FrameCtx` copy (`c0635108`'s parent) + +`decode::filter_ctx_copy` copied nine fields and not `sb128_flag` / +`reach_sb_px`, so a tile SEARCH worker (`encode::search_tiles`, threads > 1) +searched at 64 while the calling thread searched at 128. + +- Symptom: `tile_bytes_do_not_depend_on_the_thread_count`, 1x2 tiles, 9251 + bytes at one thread vs 9239 at four. +- Two neighbouring gates were TEST staleness and are pinned instead of + fixed: `reach_matches_libaom_has_top_right_and_has_bottom_left` and + `every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock` + transcribe libaom's 64-superblock tables, so they build a 64 context + explicitly rather than following the process knob. +- `every_tile_layout_decodes_sample_exact_through_both_decoders` asserted + `1 << log2` tiles; the SPEC derives the count from the superblock grid + (`tileWidthSb = ceil(sbCols >> log2)`), and 640x384 has 5 128-superblock + columns, so `tile_cols_log2 = 2` legitimately codes 3 tiles. The test now + expects the encoder's own `TileLayout` (identical to `1 << log2` at 64). + +## 3. The writer's intrabc DV predictor (`c0635108`) + +- **First divergent symbol: none.** The writer's and the reader's symbol + traces are identical for all 111384 symbols; only the `# MVDBG` annotation + differs — writer DV (-48, 0) px, reader (-112, 0) px at mi=(36,4). + `tile::intrabc_dv_pred` hardcoded `mib_size = 16` where decode.rs + `read_intrabc_dv` takes `sb_mi_cur`, so `av1_find_ref_dv`'s fallback was one + 64 superblock up on one side and one 128 on the other: same bits, different + reconstruction. +- `Ibc::dv_valid` likewise counted libaom's 256-pixel intrabc delay in 64s + (`>> 6`, `INTRABC_DELAY_SB64`), offering sources the 128 visit order had not + reconstructed yet; it now derives both the shift and the delay from the + superblock size. +- Witness: `a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`. + +## 4. Seven test harnesses handed the encoder a 64 context (`b6e573a4`) + +The seven remaining `stream::tests` failures were one cause: each built a +plain `FrameCtx` (superblock 64) and passed it to `encode_*_with_ctx`, so the +encoder's own trial decode — and the raw tile decode beside it — read at 64 +while the writer coded 128 roots. + +- **First divergent symbol** (`decode_stream_matches_the_tile_path_on_a_key_frame`, + 216x96): index 33, the writer's 8-symbol `partition_w128` (value 3, SPLIT), + which the reader skipped straight into the 10-symbol `partition_w64`. + The other six surfaced as the ref-slot refusal inside the encoder's trial + decode. +- Same class the lane-b128 merge swept through ten of their neighbours + (`FrameCtx::for_encoder`); these seven were the rest of it. + +## The gates (both arms re-run on THIS tree) + +`bd_rate_screen_native`, 12 frames, BD-rate vs libaom cpu-6 / rav1e s6 +(lower is better): + +| row | 64 superblocks (control) | 128 superblocks (default) | +|---|---|---| +| bars 1080p | -3.1 / -18.7 | **-3.7 / -19.2** | +| bars 2160p | +9.1 / -13.3 | **+8.5 / -13.8** | +| film A (1080p) | +20.3 / -5.0 | **+20.1 / -5.2** | +| film B (2160p) | +24.6 / -2.0 | **+24.3 / -2.2** | +| screen capture | +14.6 / -33.2 | **+14.4 / -33.2** | + +`bd_rate_film_long_gop`, 48 frames: + +| row | 64 superblocks | 128 superblocks | +|---|---|---| +| film A | +24.0 / -7.6 | **+23.6 / -7.9** | +| film B | +85.8 / +7.1 | **+85.1 / +6.6** | + +Every row is DOWN on both columns; screen is down on one and flat on the +other. The keep rule holds with room to spare. + +## Pins + +Re-taken for the flip (the same four pictures, now in 128 superblocks): +`(150, 8327, 0x33eb7bd59beaf2e3)`, `(60, 33194, 0xafded5cfca824703)` — was +`(150, 8252, ...)`, `(60, 33053, ...)`. `EC_AV1_SB128=0` restores the old +bytes exactly, which is also the proof that none of the four fixes moves the +64-superblock encoder. No other byte pin moved. + +## Suite / checks + + EC_AV1_SB128=1 (before the flip) + s1 --skip stream:: 341 passed; 0 failed; 34 ignored (only the 64-pins gate red) + s2 stream:: 201 passed; 0 failed; 15 ignored RC=0 + s3 10bit 42 passed; 0 failed; 1 ignored RC=0 + + default (SB128_DEFAULT = true, pins re-taken) + s1 342 passed; 0 failed; 34 ignored RC=0 + s2 201 passed; 0 failed; 15 ignored RC=0 + s3 42 passed; 0 failed; 1 ignored RC=0 + --ignored every_speed_preset_decodes_sample_exact_through_both_decoders ok + --ignored a_128_superblock_clip_whose_root_search... ok (405 blocks) + cargo check --workspace --all-targets 0 errors, 0 ec-av1 warnings + +## Disposition + +- `deferred`: HORZ / VERT at the 128 root, the 128 block's residual and its + compound arm, and the intra 128 root on key frames — lane-b128's three + deferrals, unchanged (the writer still refuses a non-skip 128 block). +- `open`: search-time vs write-time mv stacks still differ (lane-sb128b's own + second open item); the writer's clamp makes it safe, not right.