diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index dd402ca8..60d85406 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -826,6 +826,80 @@ pub(crate) fn force_b128_rect(which: u8) { FORCE_B128_RECT.store(which, std::sync::atomic::Ordering::Relaxed); } +/// lane-ab128: whether the 128 superblock root offers its four AB shapes -- +/// `PARTITION_HORZ_A` (two 64x64 on top, one 128x64 below), `_HORZ_B` (one +/// 128x64 on top, two 64x64 below), `_VERT_A` (two 64x64 left, one 64x128 +/// right) and `_VERT_B` (one 64x128 left, two 64x64 right). Every piece is +/// the same skip-only single-reference/compound block the NONE and HORZ/VERT +/// arms ship, at its own footprint ([`search_root_128_ab`], +/// `crate::tile::write_inter_block_128_rect`). `EC_AV1_B128AB=0` is this +/// arm's attribution control. +/// +/// **Off by default** (`EC_AV1_B128AB=1` turns it on): measured on both gates +/// and it does not pay. The shapes fire 0-2 roots a frame against ~1000 coded +/// blocks (`EC_AV1_B128_CENSUS`), and every row is flat or 0.1 worse -- +/// long-GOP film A +22.0/-8.5 against a +21.9/-8.6 control, film B +75.8/+0.8 +/// against the same, 12-frame film A +18.1/-6.2 against +18.0/-6.3, film B +/// +23.1/-3.3 against +23.0/-3.5, screen byte-identical (lane-ab128). The +/// machinery is written, witnessed sample-exact through both decoders on all +/// four shapes, and kept for the arm that makes it pay: a non-skip piece (the +/// 64x64 pieces could carry the 64 root's residual, which is where libaom's +/// AB shapes earn their keep) or a cheaper partition price. +fn b128_ab() -> bool { + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_B128AB").ok().map(|v| v != "0") + }); + ENV.unwrap_or(false) && b128_root() +} + +/// How many 128 roots the search left as each AB shape since the last take, +/// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order (class +/// `gate-blind-to-feature`). +static B128_AB_HITS: [std::sync::atomic::AtomicUsize; 4] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 4]; + +/// The four per-shape AB-root counts since the last call, and zero them. +pub fn take_b128_ab_hits() -> [usize; 4] { + std::array::from_fn(|i| B128_AB_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// Test-only: force the 128 root's AB shape whatever it costs -- 0 off, then +/// 4..=7, the partition symbol itself ([`force_b128_rect`]'s twin; synthetic +/// content is where the shapes are cheapest to decode-check and the RD there +/// prefers one whole block). +static FORCE_B128_AB: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +/// Arms [`FORCE_B128_AB`] for the rest of the process (0 off, else 4..=7). +#[cfg(test)] +pub(crate) fn force_b128_ab(which: u8) { + FORCE_B128_AB.store(which, std::sync::atomic::Ordering::Relaxed); +} + +/// lane-ab128: the three pieces of an AB shape at a 128 root, in the order +/// libaom's `decode_partition` codes them and decode.rs' `sb128_ab` arm +/// reads them (decode.rs ~35269) -- HORZ_A = TL, TR, bottom half; HORZ_B = +/// top half, BL, BR; VERT_A = TL, BL, right half; VERT_B = left half, TR, BR. +/// Each entry is the piece's own top-left in mode-info units and its +/// footprint in samples. +pub(crate) fn ab128_pieces( + symbol: usize, + (mi_row, mi_col): (usize, usize), +) -> [((usize, usize), (usize, usize)); 3] { + const S: usize = SUPERBLOCK; + let (r, c) = (mi_row, mi_col); + let (r1, c1) = (mi_row + 16, mi_col + 16); + match symbol { + // PARTITION_HORZ_A + 4 => [((r, c), (S, S)), ((r, c1), (S, S)), ((r1, c), (S * 2, S))], + // PARTITION_HORZ_B + 5 => [((r, c), (S * 2, S)), ((r1, c), (S, S)), ((r1, c1), (S, S))], + // PARTITION_VERT_A + 6 => [((r, c), (S, S)), ((r1, c), (S, S)), ((r, c1), (S, S * 2))], + // PARTITION_VERT_B + _ => [((r, c), (S, S * 2)), ((r, c1), (S, S)), ((r1, c1), (S, S))], + } +} + /// Test-only: take the 128 root's residual arm whatever it costs, so a /// witness clip codes the shape rather than waiting for content on which the /// RD picks it (the same role [`force_sb128`] plays for the superblock size). @@ -9891,6 +9965,156 @@ fn search_root_128_rect( )) } +/// lane-ab128: one AB shape at a 128 superblock root -- two 64x64 blocks and +/// one 128x64 / 64x128 half, in the order [`ab128_pieces`] gives (the +/// decoder's own). Each piece is priced through the same `search_skip_64` +/// the NONE and HORZ/VERT arms use, at its own footprint, and is published +/// into `grid` before the next is searched -- the writer publishes it too, so +/// a later piece searched against a stale grid would be priced (and its mv +/// predicted) off a stack the decoder never derives (class +/// `encoder-grid-drift-invisible-to-pixel-gate`). The grid and both planes +/// are put back before returning; the caller re-applies the winner. +/// +/// SKIP only, for the reason [`search_root_128_rect`] gives: the 128 residual +/// arm the pieces would share is itself parked behind `EC_AV1_B128RES`. +/// +/// Returns `(cost, lambda, the three pieces, reconstruction)`, the cost +/// already carrying the root's own partition symbol so it ranks against the +/// other root candidates and against the four superblocks below. +#[allow(clippy::too_many_arguments)] +fn search_root_128_ab( + luma: &mut Plane, + chroma: &mut [Plane; 2], + grid: &mut crate::mvstack::MiGrid, + (root_r, root_c): (usize, usize), + (rows, cols): (usize, usize), + (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, + compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], + // The partition symbol, 4..=7. + symbol: usize, + fctx: &crate::decode::FrameCtx, +) -> Option<(f64, f64, [BlockCoeffs; 3], [(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; + } + // The root's own lambda, the mean of its four superblocks' -- the same one + // [`search_root_128`] prices with, so every root candidate and the + // four-superblock arm are comparable. + 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, + ..match sb_q { + Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search), + None => search, + } + }; + let base = snapshot(luma, chroma, (x128, y128), SIDE); + let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI); + let mut cost = 0.0f64; + let mut pieces: Vec = Vec::with_capacity(3); + for ((mr, mc), (w, h)) in ab128_pieces(symbol, (mi_row, mi_col)) { + let (w_mi, h_mi) = (w / 4, h / 4); + let stack = find_mv_stack( + grid, + mr, + mc, + w_mi, + h_mi, + LAST_FRAME, + mi_cols as usize, + mi_rows as usize, + ); + let piece_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound + .iter() + .map(|&(r, pic, _)| { + ( + r, + pic, + crate::mvstack::find_mv_stack_compound( + grid, + mr, + mc, + w_mi, + h_mi, + (LAST_FRAME, r), + mi_cols as usize, + mi_rows as usize, + grid.sign_bias_table(), + &[(0, 0); 7], + None, + ), + ) + }) + .collect(); + let found = search_skip_64( + luma, + chroma, + (mc * 4, mr * 4), + (w, h), + &root_search, + false, + reference, + &stack, + &piece_compound, + fctx, + ); + match found { + Some((c, block)) => { + cost += c; + record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip); + pieces.push(block); + } + None => { + restore(luma, chroma, (x128, y128), SIDE, &base); + grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base); + return None; + } + } + } + let after = snapshot(luma, chroma, (x128, y128), SIDE); + restore(luma, chroma, (x128, y128), SIDE, &base); + grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base); + let [b0, b1, b2] = <[BlockCoeffs; 3]>::try_from(pieces).ok()?; + Some(( + cost + lambda * crate::tile::partition_bits_sym(SIDE, symbol), + lambda, + [b0, b1, b2], + 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 @@ -12660,6 +12884,47 @@ pub(crate) fn encode_inter_frame( best }) .flatten(); + // lane-ab128: and the same root as one of the four AB shapes -- two + // 64x64 pieces plus one 128x64 / 64x128 half. All four are priced; + // the cheapest joins the candidate list below. + let forced_ab = FORCE_B128_AB.load(std::sync::atomic::Ordering::Relaxed); + let root_ab = (sb128_search + && (b128_ab() || forced_ab != 0) + && cells.len() == 4 + && forced_rect == 0) + .then(|| { + let mut best: Option<(usize, _)> = None; + for symbol in 4..=7usize { + if forced_ab != 0 && usize::from(forced_ab) != symbol { + continue; + } + let Some(found) = search_root_128_ab( + &mut luma, + &mut chroma, + &mut 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, + &root_compound, + symbol, + fctx, + ) else { + continue; + }; + if best.as_ref().is_none_or(|b: &(usize, (f64, f64, _, _))| found.0 < b.1.0) { + best = Some((symbol, found)); + } + } + best + }) + .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 @@ -13238,18 +13503,26 @@ pub(crate) fn encode_inter_frame( // `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. - // lane-b128hv: `None` is the NONE arm, `Some(horz)` a rect cut. - let mut cands: Vec<(f64, f64, Option, Vec, _)> = Vec::new(); + // The root candidates, each tagged with the PARTITION symbol its + // writer codes: 0 NONE, 1 HORZ, 2 VERT (lane-b128hv), 4..=7 the AB + // shapes (lane-ab128). + let mut cands: Vec<(f64, f64, usize, Vec, _)> = Vec::new(); if let Some((c, l, b, a)) = root128 { - cands.push((c, l, None, vec![b], a)); + cands.push((c, l, 0, vec![b], a)); } if let Some((horz, (c, l, halves, a))) = root_rect { - cands.push((c, l, Some(horz), halves.to_vec(), a)); + cands.push((c, l, usize::from(!horz) + 1, halves.to_vec(), a)); + } + if let Some((symbol, (c, l, pieces, a))) = root_ab { + cands.push((c, l, symbol, pieces.to_vec(), a)); } - // The rect witness knob drops the NONE arm outright: on synthetic + // The witness knobs drop every other arm outright: on synthetic // content the whole block always wins its own comparison. if forced_rect != 0 { - cands.retain(|c| c.2.is_some()); + cands.retain(|c| c.2 == 1 || c.2 == 2); + } + if forced_ab != 0 { + cands.retain(|c| c.2 == usize::from(forced_ab)); } cands.sort_by(|a, b| a.0.total_cmp(&b.0)); if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next() @@ -13257,20 +13530,40 @@ pub(crate) fn encode_inter_frame( // The witness knobs take the root whatever it costs, so the // forced block really reaches the writer. || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed) - || forced_rect != 0) + || forced_rect != 0 + || forced_ab != 0) { let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK); blocks.truncate(mark128); restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after); let at = (root_r * 2) * cols + root_c * 2; match shape { - None => { + 0 => { B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let block = halves.into_iter().next().expect("the NONE arm's block"); record_mi(&mut grid, root_r * 16, root_c * 16, 32, block.inter, block.skip); blocks.push((at, Quadrant::Whole128(block))); } - Some(horz) => { + // lane-ab128: three pieces, published at their own footprints + // in the writer's own order ([`ab128_pieces`]). + symbol @ 4..=7 => { + B128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + for (((mr, mc), (w, h)), piece) in + ab128_pieces(symbol, (root_r * 16, root_c * 16)).iter().zip(&halves) + { + record_mi_rect( + &mut grid, + *mr, + *mc, + (w / 4, h / 4), + piece.inter, + piece.skip, + ); + } + blocks.push((at, Quadrant::Ab128(symbol as u8, halves))); + } + symbol => { + let horz = symbol == 1; if horz { B128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } else { @@ -13362,11 +13655,26 @@ pub(crate) fn encode_inter_frame( if hs.iter().any(|b| b.inter.is_some_and(|i| i.ref1.is_some()))) }) .count(); + // lane-ab128: and how many took each AB shape, in PARTITION_HORZ_A + // .. _VERT_B order -- the per-shape fire count its gate rows are read + // against. + let ab: [usize; 4] = std::array::from_fn(|i| { + blocks + .iter() + .filter(|q| matches!(q, Quadrant::Ab128(s, _) if *s as usize == i + 4)) + .count() + }); eprintln!( "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \ {compound} compound), {horz} HORZ + {vert} VERT roots ({rect_compound} with a \ - compound half), {roots} coded blocks ({:.1}% of the frame's area at 128)", - 100.0 * ((whole + horz + vert) * 16) as f64 / blocks.len().max(1) as f64, + compound half), AB roots {}/{}/{}/{} (HORZ_A/HORZ_B/VERT_A/VERT_B), \ + {roots} coded blocks ({:.1}% of the frame's area at 128)", + ab[0], + ab[1], + ab[2], + ab[3], + 100.0 * ((whole + horz + vert + ab.iter().sum::()) * 16) as f64 + / blocks.len().max(1) as f64, ); } let modes = blocks @@ -16977,6 +17285,97 @@ mod tests { ); } + /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two + /// 64x64 on top, one 128x64 below), `_HORZ_B`, `_VERT_A`, `_VERT_B`. + /// Five passes over the same `testsrc2` clip + /// `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders` + /// uses: each shape forced at every root ([`force_b128_ab`]), so every + /// context and every visit order the shape reads is exercised rather than + /// the handful the RD would pick, and then an UNFORCED pass whose + /// per-shape count is REPORTED (it is the number the gate rows are read + /// against). + /// + /// Each pass is sample-exact against the encoder's own reconstruction + /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch + /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED + /// before this lane by construction: `write_sb128_root` could only name + /// NONE / HORZ / VERT / SPLIT, so all four counts were 0. + /// + /// cargo test -p ec-av1 --release --lib -- --ignored \ + /// a_128_root_ab_shapes --nocapture + #[test] + #[ignore = "sets the process-global superblock size: run it alone"] + fn a_128_root_ab_shapes_decode_exact_through_both_decoders() { + let _knobs = crate::speed::knob_write(); + if !have_ffmpeg() { + eprintln!("SKIP: no ffmpeg"); + return; + } + force_sb128(true); + let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let clip = dir.join("testsrc2-1280x768.y4m"); + let ok = Command::new("ffmpeg") + .args(["-v", "error", "-y", "-f", "lavfi"]) + .args(["-i", "testsrc2=size=1280x768:rate=24"]) + .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) + .arg(&clip) + .status() + .expect("ffmpeg failed to run") + .success(); + assert!(ok, "ffmpeg could not write the synthetic clip"); + let (width, height) = (1280usize, 768usize); + let pictures = + crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12); + let names = ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"]; + let mut unforced = [0usize; 4]; + for force in [4u8, 5, 6, 7, 0] { + force_b128_ab(force); + let label = if force == 0 { "unforced" } else { names[usize::from(force) - 4] }; + let _ = take_b128_ab_hits(); + let _ = crate::tile::take_sb128_ab_hits(); + let encoded = encode_sequence(&pictures, 150, 0.5).unwrap(); + let won = take_b128_ab_hits(); + let coded = crate::tile::take_sb128_ab_hits(); + eprintln!( + "{label}: search won {won:?} AB roots, writer coded {coded:?} \ + (HORZ_A/HORZ_B/VERT_A/VERT_B)" + ); + if force == 0 { + // The unforced counts are REPORTED, not asserted: a zero here + // would be an RD result, not a defect (the four forced passes + // already prove the writer and the reader agree on the shape). + unforced = won; + } else { + let i = usize::from(force) - 4; + assert!(coded[i] > 0, "no {label} root was coded with {label} forced"); + } + let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); + assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count"); + for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { + for (plane, got, want) in [ + ("luma", &dec.y, &frame.reconstruction.y), + ("U", &dec.u, &frame.reconstruction.u), + ("V", &dec.v, &frame.reconstruction.v), + ] { + let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count(); + assert_eq!(differ, 0, "{label} frame {i}: {plane} -- {differ} samples differ"); + } + } + let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len()); + for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() { + assert_eq!(dec.y, frame.reconstruction.y, "{label} frame {i}: ffmpeg luma"); + assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U"); + assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V"); + } + } + force_b128_ab(0); + eprintln!( + "unforced on testsrc2 over 12 frames: {} HORZ_A + {} HORZ_B + {} VERT_A + {} VERT_B", + unforced[0], unforced[1], unforced[2], unforced[3], + ); + } + #[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() { diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 3db6175a..e1293230 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -617,9 +617,12 @@ fn write_inter_block_128_rect( if let Some(r1) = info.ref1 { neighbours.record_compound_rect_mi((mi_r, mi_c), (w, h), r1, 0, 1); } + // lane-ab128: an AB shape codes its two 64x64 pieces through this same + // function, and they are neither a 128x64 nor a 64x128 half -- the + // witness reads these two counters for the HORZ/VERT shape alone. if w > h { SB128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - } else { + } else if h > w { SB128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } Ok(()) @@ -642,6 +645,17 @@ pub fn take_sb128_vert_hits() -> usize { SB128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) } +/// lane-ab128: how many AB-shape roots the inter writer has coded since the +/// last [`take_sb128_ab_hits`], in `PARTITION_HORZ_A` .. `_VERT_B` order +/// (class `gate-blind-to-feature`). +static SB128_AB_HITS: [std::sync::atomic::AtomicUsize; 4] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 4]; + +/// The four per-shape AB-root counts since the last call, and zero them. +pub fn take_sb128_ab_hits() -> [usize; 4] { + std::array::from_fn(|i| SB128_AB_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + /// lane-b128r: how many of those blocks carried a REAL residual (four /// TX_64X64 luma units plus their per-chunk chroma pair) rather than being /// skipped, since the last [`take_sb128_residual_hits`]. @@ -2594,6 +2608,17 @@ pub enum Quadrant { /// SKIP only ([`crate::tile::write_inter_block_128_rect`] refuses a /// residual), single reference or compound. Rect128(bool, Vec), + /// lane-ab128: the THREE inter blocks an AB shape at a 128 superblock + /// root carries -- two 64x64 pieces and one 128x64 / 64x128 half -- in + /// the order the decoder reads them + /// ([`crate::encode::ab128_pieces`]). The `u8` is the partition symbol + /// itself (4 `PARTITION_HORZ_A` .. 7 `PARTITION_VERT_B`). Carried by the + /// top-left 32x32 entry of the root's sixteen, exactly as + /// [`Rect128`](Quadrant::Rect128) is. + /// + /// SKIP only, same writer ([`crate::tile::write_inter_block_128_rect`]) + /// and same reason. + Ab128(u8, Vec), /// A quadrant a [`Whole64`](Quadrant::Whole64) at its superblock's /// top-left already coded; it carries no block of its own. Covered, @@ -2606,7 +2631,9 @@ impl Quadrant { Quadrant::Whole(block) | Quadrant::Whole64(block) | Quadrant::Whole128(block) => { std::slice::from_ref(block) } - Quadrant::Split(blocks) | Quadrant::Rect128(_, blocks) => blocks.as_slice(), + Quadrant::Split(blocks) + | Quadrant::Rect128(_, blocks) + | Quadrant::Ab128(_, blocks) => blocks.as_slice(), Quadrant::Covered => &[], } } @@ -3742,6 +3769,7 @@ pub(crate) fn sb_coeff_key_frame_tile_cdfs( Quadrant::Whole64(_) | Quadrant::Whole128(_) | Quadrant::Rect128(..) + | Quadrant::Ab128(..) | Quadrant::Covered => { return Err(Error::unsupported( "AV1 tile", @@ -5410,7 +5438,9 @@ pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 { // 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(_) | Quadrant::Rect128(..) => return 0.0, + Quadrant::Whole128(_) | Quadrant::Rect128(..) | Quadrant::Ab128(..) => { + return 0.0; + } Quadrant::Whole(_) => 32, Quadrant::Split(_) => 16, // lane-tx64: a 64x64 root that codes a residual pays for one @@ -7141,6 +7171,12 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( Quadrant::Rect128(horz, halves) => Some((*horz, halves)), _ => None, }); + // lane-ab128: the three pieces an AB-shape root carries, and the + // partition symbol it is coded under. + let root_ab = root_entry.and_then(|q| match q { + Quadrant::Ab128(symbol, pieces) => Some((*symbol as usize, pieces)), + _ => None, + }); write_sb128_root( &mut enc, &mut cdfs, @@ -7149,10 +7185,11 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( sb_c, mi_cols, mi_rows, - match (root_block.is_some(), root_rect) { - (true, _) => PARTITION_NONE, - (_, Some((true, _))) => PARTITION_HORZ, - (_, Some((false, _))) => PARTITION_VERT, + match (root_block.is_some(), root_rect, root_ab) { + (true, ..) => PARTITION_NONE, + (_, Some((true, _)), _) => PARTITION_HORZ, + (_, Some((false, _)), _) => PARTITION_VERT, + (_, _, Some((symbol, _))) => symbol, _ => PARTITION_SPLIT, }, ); @@ -7201,6 +7238,38 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( sb128_none = true; continue; } + if let Some((symbol, pieces)) = root_ab { + // libaom `decode_partition` at BLOCK_128X128, AB arm: two + // 64x64 blocks and one 128x64 / 64x128 half, in the order + // decode.rs' `sb128_ab` reads them + // ([`crate::encode::ab128_pieces`]). An AB shape only comes + // from the full alphabet symbol (both halves in frame), so + // there is no edge break to mirror -- the search offers one + // only at a root wholly inside. + let base_mi = ( + (sb_r & !1) as usize * SB_MI as usize, + (sb_c & !1) as usize * SB_MI as usize, + ); + for (((mi_r, mi_c), (w, h)), piece) in + crate::encode::ab128_pieces(symbol, base_mi).iter().zip(pieces) + { + write_inter_block_128_rect( + &mut enc, + &mut cdfs, + &mut neighbours, + &mut grid, + (*mi_r, *mi_c), + (*w, *h), + piece, + mi_cols, + mi_rows, + tx_select, + )?; + } + SB128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + sb128_none = true; + continue; + } } { if !sb128 { @@ -7449,6 +7518,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( Quadrant::Whole64(_) | Quadrant::Whole128(_) | Quadrant::Rect128(..) + | Quadrant::Ab128(..) | Quadrant::Covered => { return Err(Error::unsupported( "AV1 tile", diff --git a/lanes/ab128.report.md b/lanes/ab128.report.md new file mode 100644 index 00000000..2131f431 --- /dev/null +++ b/lanes/ab128.report.md @@ -0,0 +1,156 @@ +# lane-ab128 — the four AB shapes at the 128 superblock root + +`PARTITION_HORZ_A` (two 64x64 on top, one 128x64 below), `_HORZ_B` (one +128x64 on top, two 64x64 below), `_VERT_A` (two 64x64 left, one 64x128 +right), `_VERT_B` (one 64x128 left, two 64x64 right) are written, witnessed +sample-exact through `decode_stream` AND ffmpeg on all four shapes, and +measured on both gates. **They ship OFF** (`EC_AV1_B128AB=1` turns them on): +every gate row is flat or 0.1 worse. The lane's value is the measurement and +the machinery, not a shipped default. + +## 1. What was built + +* `crate::encode::ab128_pieces(symbol, (mi_row, mi_col))` — the three pieces + of a shape, position and footprint, in libaom's `decode_partition` order + and decode.rs' `sb128_ab` order (decode.rs ~35269): HORZ_A = TL, TR, bottom + half; HORZ_B = top half, BL, BR; VERT_A = TL, BL, right half; VERT_B = left + half, TR, BR. One table, read by the search, by the writer and by the + winner's grid publication, so the three cannot drift (class + *table and reader move together*). +* `search_root_128_ab` — the three pieces priced through the same + `search_skip_64` the NONE and HORZ/VERT arms use, each at its own + footprint, each published into the mi grid (`record_mi_rect`) before the + next is searched and the whole 32x32-mi window restored with + `MiGrid::snapshot_rect`/`restore_rect` before returning (class + *encoder-grid-drift-invisible-to-pixel-gate*). The cost carries the root's + own `partition_bits_sym(128, symbol)`. +* `Quadrant::Ab128(symbol, pieces)` on the root's top-left 32x32 entry, the + fifteen others `Covered` — exactly as `Rect128` does. +* The writer needed **no new block function**: a 64x64 AB piece is one inter + block coded at side 64 with `write_w == write_h == 64`, and a half is the + 128x64/64x128 `write_inter_block_128_rect` already codes. All three go + through `write_inter_block_128_rect` at their own `(w, h)`. +* `EC_AV1_B128AB` (default off), `force_b128_ab` (test knob, 0 or the + partition symbol 4..=7), per-shape search and writer counters, and the + `EC_AV1_B128_CENSUS` line extended with `AB roots a/b/c/d`. + +## 2. Charter premises checked against the code + +* **"decide whether the 64 pieces of an AB shape run the full 64-root search + or the skip-64 search, and justify by measurement; the full search is what + libaom does" — refuted by the syntax, so nothing to measure.** decode.rs' + `sb128_ab` codes each 64x64 piece as ONE `decode_inter_block` at + `side = SB` with no partition symbol of its own (`square64_inter!`), which + is libaom's own AB shape: an AB piece is a whole block, never a + further-partitionable root. A "full 64-root search" candidate could not be + written at all. The pieces are `search_skip_64` at (64, 64), skip-only, for + the same reason `search_root_128_rect`'s halves are: the 128 residual arm + they would share is parked behind `EC_AV1_B128RES`. +* **"Extend `cdef_unit_owner` for the two-unit shape and the four-way + `pick_filters` grouping" — not needed, and NOT done (rung 1: it would be + dead code).** `write_cdef_idx` writes a literal only for a NON-SKIP block; + every AB piece and every HORZ/VERT half is skip, so such a root puts no + `cdef_idx` in the stream at all and CDEF filters none of its (all-skip) + units. `cdef_unit_owner` collapses units only for `Whole128`, which is the + one 128-wide shape that can carry a residual (`EC_AV1_B128RES`). The same + reasoning covers `Rect128`, which lane-b128hv also left out of the map — + swept and confirmed inert, not a sibling defect. The day a piece carries a + residual, `cdef_unit_owner` must learn `Rect128` and `Ab128` in the SAME + diff; that is named as the constraint below. +* `write_delta_q` needed no change: it already gates on the block's own + position within the (128-wide) superblock, and no AB piece is the whole + superblock, so `is_whole_sb = false` — what `write_inter_block_128_rect` + passes — is right for all three. `intrabc_dv_pred` is intra-frame only and + this is the inter writer. +* The charter's witness fixtures ("4K bars + film B 12-frame fixtures used by + `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders`") are + stale: that test encodes ONE synthetic `testsrc2` 1280x768 12-frame clip. + The AB witness mirrors it exactly. + +## 3. Witness + +`encode::tests::a_128_root_ab_shapes_decode_exact_through_both_decoders` +(`--ignored`), five passes over the same clip — each shape forced at every +root, then unforced: + + HORZ_A: search won [660, 0, 0, 0] writer coded [1320, 0, 0, 0] + HORZ_B: search won [0, 660, 0, 0] writer coded [0, 1320, 0, 0] + VERT_A: search won [0, 0, 660, 0] writer coded [0, 0, 1320, 0] + VERT_B: search won [0, 0, 0, 660] writer coded [0, 0, 0, 660*2] + unforced: search won [0, 0, 1, 1] writer coded [0, 0, 2, 2] + +Every pass sample-exact against the encoder's own reconstruction through +`decode_stream` and through ffmpeg, first run, no bisect needed. RED before +this lane by construction: `write_sb128_root` could name only NONE / HORZ / +VERT / SPLIT. + +## 4. Census on real content (`EC_AV1_B128_CENSUS=1`, long-GOP films) + +171 inter frames: a typical frame is `7 whole 128 roots, 0-1 HORZ + 0-1 VERT, +AB roots 0/0/0/1`, out of ~1050-1900 coded blocks. 44 of 171 frames took no +AB root at all; the modal non-zero frame takes exactly one. The shapes are +real but rare — which is the whole BD result below. + +## 5. Gates (arm = default-on build, control = `EC_AV1_B128AB=0`; lower is better) + +12-frame `bd_rate_screen_native` (`~/.cache/ab128/12arm.log`, `12ctl.log`): + +| row | arm vs libaom | ctl vs libaom | arm vs rav1e | ctl vs rav1e | +| --- | --- | --- | --- | --- | +| bars 1080p | -3.4% | -3.4% | -19.0% | -19.0% | +| bars 2160p | +8.4% | +8.4% | -14.0% | -14.0% | +| film A | +18.1% | +18.0% | -6.2% | -6.3% | +| film B | +23.1% | +23.0% | -3.3% | -3.5% | +| screen | +14.4% | +14.4% | -33.2% | -33.2% | + +Long-GOP `bd_rate_film_long_gop` — the deciding gate (`lgarm.log`, +`lgctl.log`): + +| row | arm vs libaom | ctl vs libaom | arm vs rav1e | ctl vs rav1e | +| --- | --- | --- | --- | --- | +| film A | +22.0% | +21.9% | -8.5% | -8.6% | +| film B | +75.8% | +75.8% | +0.8% | +0.8% | + +Wall (both arms run concurrently, so the contention is shared): long-GOP +706.6 + 520.0 = 1226.6 s arm against 665.0 + 463.5 = 1128.5 s control, +**+8.7%** — inside the +15% ceiling, but bought for nothing. + +**Keep rule: FAILED.** It asks for both film rows down on both columns, or +one >= 0.5 down with the other flat. Film A is 0.1 WORSE on both columns, +film B is unchanged to the decimal. The candidate costs a partition symbol on +every root it wins and buys back less than it spends. Shipped off. + +Known under-pricing shared with lane-b128hv (unchanged by this lane): a +non-origin AB piece codes no `delta_q` group, but the piece AT the superblock +origin does, and nothing here prices it — lane-rectdq is adding the +`delta_q_bits` pricer. The mispricing is under a bit per root and is the same +for the rect arm, so it cannot explain a 0.1 BD miss on its own. + +## 6. Suite, pins, checks + +* Pins: `encode::tests::the_encoders_own_streams_are_byte_identical_to_their_pins` + green at default and at `EC_AV1_SPEED=6`, **unmoved** (`pins2.log`) — the + arm is off by default, so the default encoder is byte-identical to main's. +* `--ignored --exact encoder::tests::every_speed_preset_decodes_sample_exact_through_both_decoders`: ok. +* `--ignored` HORZ/VERT witness (lane-b128hv's): ok, unaffected by the + counter split (a 64x64 piece no longer counts as a "64x128 half"). +* Suite in three lanes, all green: `-- --skip stream::` 345 passed / 0 + failed / 40 ignored; `-- stream:: --skip 10bit` 202 / 0 / 15; `-- 10bit` + 42 / 0 / 1. +* `timeout 900 cargo check --workspace --all-targets -j4`: 0 errors, 0 + ec-av1 warnings (the 22 warnings in the log are pre-existing ec-opus / + ec-vorbis ones). + +## 7. Disposition + +* `deferred: a non-skip AB piece` — the 64x64 pieces could carry the 64 + root's own residual (`b64_residual`), which is where libaom's AB shapes + earn their keep; the skip-only pieces here can only ever move the partition + price. Unblocked by nothing but a lane: the residual writer at 64 exists + (`Whole64`), it is the piece's `search_skip_64(.., residual = true)` call + and the `write_inter_block_128_rect` refusal that would have to move — + together with `cdef_unit_owner` learning `Rect128` and `Ab128` in the SAME + diff, since a non-skip piece writes a `cdef_idx` literal that covers two + units for a half. +* `accepted: the delta_q under-pricing` — shared with lane-b128hv, under a + bit per root, lane-rectdq owns the pricer.