diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 46ff6993..237e7d99 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -786,6 +786,46 @@ pub fn take_b128_compound_hits() -> usize { B128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) } +/// lane-b128hv: whether the 128 superblock root offers its `PARTITION_HORZ` +/// and `PARTITION_VERT` candidates -- two 128x64 / 64x128 inter blocks, the +/// same skip-only single-reference/compound machinery the NONE arm ships, +/// halved ([`search_root_128_rect`], `crate::tile::write_inter_block_128_rect`). +/// `EC_AV1_B128HV=0` is this arm's attribution control. +fn b128_rect() -> bool { + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_B128HV").ok().map(|v| v != "0") + }); + ENV.unwrap_or(true) && b128_root() +} + +/// How many 128 roots the search left as two 128x64 (HORZ) / 64x128 (VERT) +/// halves since the last take (class `gate-blind-to-feature`). +static B128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// The VERT twin of [`B128_HORZ_HITS`]. +static B128_VERT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// The HORZ-128-root count since the last call, and zero it. +pub fn take_b128_horz_hits() -> usize { + B128_HORZ_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) +} + +/// The VERT-128-root count since the last call, and zero it. +pub fn take_b128_vert_hits() -> usize { + B128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) +} + +/// Test-only: force the 128 root's rect partition whatever it costs -- 0 off, +/// 1 `PARTITION_HORZ`, 2 `PARTITION_VERT`. The witness needs it because +/// synthetic content is where the shape is cheapest to decode-check and the +/// RD there prefers one whole block; the gate census is the unforced count. +static FORCE_B128_RECT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +/// Arms [`FORCE_B128_RECT`] for the rest of the process (0 / 1 HORZ / 2 VERT). +#[cfg(test)] +pub(crate) fn force_b128_rect(which: u8) { + FORCE_B128_RECT.store(which, std::sync::atomic::Ordering::Relaxed); +} + /// 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). @@ -3079,6 +3119,17 @@ impl Plane<'_> { rows_of(self.source, self.width, x, y, side) } + /// lane-b128hv: [`Self::source_block`] over a rectangle, for the 128 + /// root's own HORZ/VERT motion search. + fn source_block_rect(&self, x: usize, y: usize, w: usize, h: usize) -> Vec { + let mut out = vec![0u8; w * h]; + for row in 0..h { + out[row * w..][..w] + .copy_from_slice(&self.source[(y + row) * self.width + x..][..w]); + } + out + } + /// The reconstructed samples of one square, so that a partition trial can /// be undone. /// The reconstructed samples of one square AND the coefficient contexts @@ -7368,6 +7419,31 @@ fn record_mi( } } +/// lane-b128hv: [`record_mi`] for a RECTANGULAR block -- the mi stamp the +/// writer's own `write_inter_block_128_rect` makes, so the second half of a +/// HORZ/VERT 128 root searches against the stack the writer will rebuild. +fn record_mi_rect( + grid: &mut MiGrid, + mi_row: usize, + mi_col: usize, + (w_mi, h_mi): (usize, usize), + inter: Option, + skip: bool, +) { + record_mi(grid, mi_row, mi_col, w_mi.min(h_mi) as u8, inter, skip); + // `record_mi` stamped the square corner; widen it to the true footprint, + // with the block's own (rect) size fields. + let mut info = grid.get_frame(mi_row, mi_col).expect("just recorded"); + info.size = w_mi as u8; + info.size_h = h_mi as u8; + for dr in 0..h_mi { + for dc in 0..w_mi { + grid.set(mi_row + dr, mi_col + dc, info); + grid.set_skip(mi_row + dr, mi_col + dc, skip); + } + } +} + /// The reconstructed samples one 32x32 square covers in all three planes, so /// that a partition trial can be undone. /// One square of a plane, row-major, the inverse of [`Plane::restore`]. @@ -9557,7 +9633,7 @@ fn search_root_128( luma, chroma, (x128, y128), - SIDE, + (SIDE, SIDE), &root_search, false, reference, @@ -9656,6 +9732,165 @@ fn search_root_128( )) } +/// lane-b128hv: the `PARTITION_HORZ` / `PARTITION_VERT` candidate for a whole +/// 128 superblock root -- two 128x64 (`horz`) or 64x128 inter blocks, the +/// shipped NONE machinery halved. Skip only, single reference or compound, +/// exactly what `crate::tile::write_inter_block_128_rect` codes and +/// `decode_inter_block` reads at `sb128_rect`. +/// +/// The FIRST half is published into `grid` before the second is searched -- +/// the writer publishes it too, so a second half searched against the 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. +/// +/// Returns `(cost, lambda, the two halves, reconstruction)`, the cost already +/// carrying the root's own partition symbol so it ranks against +/// [`search_root_128`] and against the four superblocks below. +#[allow(clippy::too_many_arguments)] +fn search_root_128_rect( + 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, + // The `LAST` + extra-reference pairs offered at this root; only the + // reference and its picture are read here, since each HALF derives its + // own compound stack at its own rectangular window. + compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], + horz: bool, + fctx: &crate::decode::FrameCtx, +) -> Option<(f64, f64, [BlockCoeffs; 2], [(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 the three root candidates and + // the four-superblock arm are all 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 (w, h) = if horz { (SIDE, SUPERBLOCK) } else { (SUPERBLOCK, SIDE) }; + let (w_mi, h_mi) = (w / 4, h / 4); + 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 halves: Vec = Vec::with_capacity(2); + for i in 0..2usize { + let (mr, mc) = if horz { + (mi_row + i * 16, mi_col) + } else { + (mi_row, mi_col + i * 16) + }; + let stack = find_mv_stack( + grid, + mr, + mc, + w_mi, + h_mi, + LAST_FRAME, + mi_cols as usize, + mi_rows as usize, + ); + let half_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, + &half_compound, + fctx, + ); + match found { + Some((c, block)) => { + cost += c; + record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip); + halves.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 symbol = if horz { 1 } else { 2 }; + let [b0, b1] = <[BlockCoeffs; 2]>::try_from(halves).ok()?; + Some(( + cost + lambda * crate::tile::partition_bits_sym(SIDE, symbol), + lambda, + [b0, b1], + 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 @@ -9670,12 +9905,14 @@ 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 + // The root's footprint in samples: [`SUPERBLOCK`] square at a 64 root, + // twice that at the 128 one [`search_root_128`] drives (lane-b128), and + // 128x64 / 64x128 at the rect halves of [`search_root_128_rect`] + // (lane-b128hv). Every trial below tiles it into squares of its SHORTER + // side (one square when it is square, two otherwise), 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, + (bw, bh): (usize, usize), search: &Search, // Whether the non-skip arm is priced at all ([`b64_residual`], and off on // screen content -- see that function's doc). @@ -9688,7 +9925,23 @@ fn search_skip_64( compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], fctx: &crate::decode::FrameCtx, ) -> Option<(f64, BlockCoeffs)> { - debug_assert!(side == SUPERBLOCK || !residual, "a 128 root has no residual arm"); + debug_assert!( + (bw, bh) == (SUPERBLOCK, SUPERBLOCK) || !residual, + "only a 64 root has a residual arm" + ); + // The square units every trial below is taken on: the block itself when + // it is square, its two halves otherwise. Luma first (in raster order), + // then each chroma plane over the same tiling at half the side -- which is + // exactly `[(0, x, y, side), (1, ..), (2, ..)]` at bw == bh. + let sq = bw.min(bh); + let units: Vec<(usize, usize, usize, usize, bool)> = (0..3usize) + .flat_map(|plane| { + let (ox, oy, s) = if plane == 0 { (x, y, sq) } else { (x / 2, y / 2, sq / 2) }; + (0..bh / sq).flat_map(move |j| { + (0..bw / sq).map(move |i| (plane, ox + i * s, oy + j * s, s, plane == 0)) + }) + }) + .collect(); 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); @@ -9726,7 +9979,7 @@ fn search_skip_64( // candidate below to pair with the second reference's NEAREST half. let mut last_new_mv: Option<(i32, i32)> = None; if leaf_new_mv() { - let source_block = luma.source_block(x, y, side); + let source_block = luma.source_block_rect(x, y, bw, bh); let (seeds, seed_n) = mv_seeds(stack); let found = motion::search( &reference.y, @@ -9736,8 +9989,8 @@ fn search_skip_64( &source_block, x, y, - side, - side, + bw, + bh, stack.pred_mv, &seeds[..seed_n], search.lambda, @@ -9754,14 +10007,11 @@ fn search_skip_64( } } - let mut best: Option<(f64, f64, InterInfo, [Trial; 3])> = None; + let mut best: Option<(f64, f64, InterInfo, Vec)> = None; for (bits, info) in cands { - let trials = [ - (0usize, x, y, side, true), - (1, x / 2, y / 2, side / 2, false), - (2, x / 2, y / 2, side / 2, false), - ] - .map(|(plane, px, py, s, is_luma)| { + let trials: Vec = units + .iter() + .map(|&(plane, px, py, s, is_luma)| { let (samples, stride, w, h) = match plane { 0 => (&reference.y, reference.width, luma.true_width, luma.true_height), 1 => ( @@ -9792,11 +10042,10 @@ fn search_skip_64( search.deadzone, TxbSet::Luma32Inter, ) - }); - let cost = trials[0].sse - + trials[1].sse - + trials[2].sse - + search.lambda * (fixed + bits); + }) + .collect(); + let cost = + trials.iter().map(|t| t.sse).sum::() + search.lambda * (fixed + bits); if best.as_ref().is_none_or(|b| cost < b.0) { best = Some((cost, fixed + bits, info, trials)); } @@ -9855,12 +10104,9 @@ fn search_skip_64( ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); ccands.dedup_by_key(|c| c.0); for (mvs, bits, info) in ccands { - let trials = [ - (0usize, x, y, side, true), - (1, x / 2, y / 2, side / 2, false), - (2, x / 2, y / 2, side / 2, false), - ] - .map(|(plane, px, py, s, is_luma)| { + let trials: Vec = units + .iter() + .map(|&(plane, px, py, s, is_luma)| { let (r0, r1) = match plane { 0 => ( (reference.y.as_slice(), reference.width, luma.true_width, luma.true_height), @@ -9898,10 +10144,10 @@ fn search_skip_64( search.deadzone, TxbSet::Luma32Inter, ) - }); + }) + .collect(); let syntax = fixed - ref_bits + bits; - let cost = - trials[0].sse + trials[1].sse + trials[2].sse + search.lambda * syntax; + let cost = trials.iter().map(|t| t.sse).sum::() + search.lambda * syntax; if best.as_ref().is_none_or(|b| cost < b.0) { best = Some((cost, syntax, info, trials)); } @@ -9931,11 +10177,13 @@ fn search_skip_64( let mut luma_levels: Option<(Vec, u8, Vec)> = None; if residual { let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32]; + // Square by construction (the `debug_assert` above), so `units` is + // one entry per plane and `chosen.2[plane]` is that plane's trial. let residual_trials = [0usize, 1, 2].map(|plane| { let (target, px, py, s) = if plane == 0 { - (&*luma, x, y, side) + (&*luma, x, y, bw) } else { - (&chroma[plane - 1], x / 2, y / 2, side / 2) + (&chroma[plane - 1], x / 2, y / 2, bw / 2) }; target.code_from_prediction( px, @@ -9967,7 +10215,7 @@ fn search_skip_64( commit_inter_luma( luma, (x, y), - side, + bw, info.mv, (&reference.y, reference.width, luma.true_width, luma.true_height), search, @@ -9988,18 +10236,20 @@ fn search_skip_64( B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } luma_levels = Some((levels, depth, tx_types)); - chosen = (cost, false, residual_trials); + chosen = (cost, false, residual_trials.to_vec()); } } let (cost, skip, trials) = chosen; // `commit_inter_luma` already wrote the residual arm's luma (its four // split units are not one 64-sided trial); a skip winner overwrites it. - if skip || !luma_committed { - luma.commit(x, y, side, &trials[0]); + for (&(plane, px, py, s, _), trial) in units.iter().zip(&trials) { + match plane { + 0 if skip || !luma_committed => luma.commit(px, py, s, trial), + 0 => {} + _ => chroma[plane - 1].commit(px, py, s, trial), + } } - chroma[0].commit(x / 2, y / 2, side / 2, &trials[1]); - chroma[1].commit(x / 2, y / 2, side / 2, &trials[2]); Some(( cost, BlockCoeffs { @@ -10019,8 +10269,8 @@ fn search_skip_64( (false, Some((levels, _, _))) => coeffs(levels, BLOCK), (false, None) => coeffs(&trials[0].levels, BLOCK), }, - u: if skip { Vec::new() } else { coeffs(&trials[1].levels, side / 2) }, - v: if skip { Vec::new() } else { coeffs(&trials[2].levels, side / 2) }, + u: if skip { Vec::new() } else { coeffs(&trials[1].levels, bw / 2) }, + v: if skip { Vec::new() } else { coeffs(&trials[2].levels, bw / 2) }, ..BlockCoeffs::default() }, )) @@ -12371,6 +12621,44 @@ pub(crate) fn encode_inter_frame( fctx, )) .flatten(); + // lane-b128hv: the same root as two 128x64 / 64x128 halves. Both cuts + // are priced; the cheaper one competes with the NONE block and with + // the four superblocks below. + let forced_rect = FORCE_B128_RECT.load(std::sync::atomic::Ordering::Relaxed); + let root_rect = (sb128_search && b128_rect() && cells.len() == 4) + .then(|| { + let mut best: Option<(bool, _)> = None; + for horz in [true, false] { + if forced_rect != 0 && forced_rect != u8::from(horz) + u8::from(!horz) * 2 { + continue; + } + let Some(found) = search_root_128_rect( + &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, + horz, + fctx, + ) else { + continue; + }; + if best.as_ref().is_none_or(|b: &(bool, (f64, f64, _, _))| found.0 < b.1.0) { + best = Some((horz, 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 @@ -12470,7 +12758,7 @@ pub(crate) fn encode_inter_frame( &mut luma, &mut chroma, (x64, y64), - SUPERBLOCK, + (SUPERBLOCK, SUPERBLOCK), &sb_search, b64_residual() && !screen, reference, @@ -12949,18 +13237,56 @@ 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. - if let Some((cost128, lambda128, block, after)) = root128 + // lane-b128hv: `None` is the NONE arm, `Some(horz)` a rect cut. + let mut cands: Vec<(f64, f64, Option, Vec, _)> = Vec::new(); + if let Some((c, l, b, a)) = root128 { + cands.push((c, l, None, vec![b], a)); + } + if let Some((horz, (c, l, halves, a))) = root_rect { + cands.push((c, l, Some(horz), halves.to_vec(), a)); + } + // The rect witness knob drops the NONE 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.sort_by(|a, b| a.0.total_cmp(&b.0)); + if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next() && (cost128 < root_cost + lambda128 * crate::tile::partition_bits(128, true) - // The witness knob takes the root whatever it costs, so the - // forced residual block really reaches the writer. - || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed)) + // 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) { - 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))); + let at = (root_r * 2) * cols + root_c * 2; + match shape { + None => { + 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) => { + if horz { + B128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } else { + B128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + let (w_mi, h_mi) = if horz { (32usize, 16usize) } else { (16, 32) }; + for (i, half) in halves.iter().enumerate() { + let (mr, mc) = if horz { + (root_r * 16 + i * 16, root_c * 16) + } else { + (root_r * 16, root_c * 16 + i * 16) + }; + record_mi_rect(&mut grid, mr, mc, (w_mi, h_mi), half.inter, half.skip); + } + blocks.push((at, Quadrant::Rect128(horz, halves))); + } + } 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)); @@ -13018,10 +13344,28 @@ pub(crate) fn encode_inter_frame( matches!(q, Quadrant::Whole128(b) if b.inter.is_some_and(|i| i.ref1.is_some())) }) .count(); + // lane-b128hv: and how many roots took a rect cut instead, per shape + // -- the HORZ/VERT fire count the gate rows are read against. + let horz = blocks + .iter() + .filter(|q| matches!(q, Quadrant::Rect128(true, _))) + .count(); + let vert = blocks + .iter() + .filter(|q| matches!(q, Quadrant::Rect128(false, _))) + .count(); + let rect_compound = blocks + .iter() + .filter(|q| { + matches!(q, Quadrant::Rect128(_, hs) + if hs.iter().any(|b| b.inter.is_some_and(|i| i.ref1.is_some()))) + }) + .count(); eprintln!( "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \ - {compound} compound), {roots} coded blocks ({:.1}% of the frame's area at 128)", - 100.0 * (whole * 16) as f64 / blocks.len().max(1) as f64, + {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, ); } let modes = blocks @@ -16536,6 +16880,102 @@ mod tests { } } + /// lane-b128hv: the 128 root's `PARTITION_HORZ` and `PARTITION_VERT` + /// arms -- two 128x64 / 64x128 inter blocks where the NONE arm codes one + /// square. Three passes over one `testsrc2` clip: + /// + /// * HORZ forced at every root ([`force_b128_rect`]), so every context + /// the 128x64 shape reads is exercised rather than the handful the RD + /// would pick; + /// * VERT forced the same way; + /// * UNFORCED, which is the count the gate rows are read against -- the + /// same clip with the RD free to choose among NONE / HORZ / VERT / + /// four superblocks. + /// + /// 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 + /// `PARTITION_NONE` or `PARTITION_SPLIT`, so the count was 0 on all three. + /// + /// cargo test -p ec-av1 --release --lib -- --ignored \ + /// a_128_root_horz_and_vert --nocapture + #[test] + #[ignore = "sets the process-global superblock size: run it alone"] + fn a_128_root_horz_and_vert_halves_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-b128hv-{}", 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 mut unforced = (0usize, 0usize); + for (label, force) in [("HORZ", 1u8), ("VERT", 2), ("unforced", 0)] { + force_b128_rect(force); + let _ = take_b128_horz_hits(); + let _ = take_b128_vert_hits(); + let _ = crate::tile::take_sb128_horz_hits(); + let _ = crate::tile::take_sb128_vert_hits(); + let encoded = encode_sequence(&pictures, 150, 0.5).unwrap(); + let (won_h, won_v) = (take_b128_horz_hits(), take_b128_vert_hits()); + let (coded_h, coded_v) = ( + crate::tile::take_sb128_horz_hits(), + crate::tile::take_sb128_vert_hits(), + ); + eprintln!( + "{label}: search won {won_h} HORZ + {won_v} VERT roots, writer coded \ + {coded_h} 128x64 + {coded_v} 64x128 halves" + ); + match force { + 1 => assert!(coded_h > 0, "no 128x64 half was coded with HORZ forced"), + 2 => assert!(coded_v > 0, "no 64x128 half was coded with VERT forced"), + // The unforced count is REPORTED, not asserted: it is the + // number the gate is read against, and a zero here would be + // an RD result, not a defect (the forced passes already prove + // the writer and the reader agree on the shape). + _ => unforced = (won_h, won_v), + } + 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_rect(0); + eprintln!( + "unforced on testsrc2: {} HORZ + {} VERT roots over 12 frames", + unforced.0, unforced.1 + ); + } + #[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() { @@ -17987,7 +18427,13 @@ mod tests { // 33017 at q=60 (the same LENGTH, different bytes). // Re-taken at the merge of lane-arftf (ARF filter strength 2) and // lane-rlclamp onto the 128 compound default. - let pins: [(u8, usize, u64); 2] = [(150, 8290, 0x92cb11033d1f5813), (60, 33227, 0x57ee6b1f8eacd881)]; + // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ + // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks, + // so every inter frame whose RD takes one codes a different partition + // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that + // quantizer the rect cut never wins its own comparison on this clip. + // `EC_AV1_B128HV=0` restores 8290 exactly. + let pins: [(u8, usize, u64); 2] = [(150, 8291, 0x1f00bb0eb099a27f), (60, 33227, 0x57ee6b1f8eacd881)]; let coded: Vec<(u8, usize, u64)> = pins .iter() .map(|&(q, _, _)| { diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index 342c7935..c3421099 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -372,6 +372,49 @@ impl MiGrid { } } + /// lane-b128hv: the raw cells and skip flags of one rect region, and the + /// write-back that undoes a trial that published into it -- the 128 + /// root's HORZ/VERT search stamps its FIRST half so that the second + /// half's mv stack is the one the writer will rebuild, then puts the grid + /// back for the four-superblock arm it is weighed against. + pub fn snapshot_rect( + &self, + row: usize, + col: usize, + h: usize, + w: usize, + ) -> (Vec>, Vec) { + let mut cells = Vec::with_capacity(h * w); + let mut skips = Vec::with_capacity(h * w); + for r in row..(row + h).min(self.rows) { + let c1 = (col + w).min(self.cols); + cells.extend_from_slice(&self.cells[r * self.cols + col..r * self.cols + c1]); + skips.extend_from_slice(&self.skips[r * self.cols + col..r * self.cols + c1]); + } + (cells, skips) + } + + /// Puts a [`Self::snapshot_rect`] back. + pub fn restore_rect( + &mut self, + row: usize, + col: usize, + h: usize, + w: usize, + snap: &(Vec>, Vec), + ) { + let mut i = 0; + for r in row..(row + h).min(self.rows) { + let c1 = (col + w).min(self.cols); + let n = c1 - col; + self.cells[r * self.cols + col..r * self.cols + c1] + .copy_from_slice(&snap.0[i..i + n]); + self.skips[r * self.cols + col..r * self.cols + c1] + .copy_from_slice(&snap.1[i..i + n]); + i += n; + } + } + /// The unit at `(row, col)`, or `None` when it is outside the grid, hasn't /// been coded, or sits outside the current tile's own bounds ([`Self::set_tile_bounds`]). pub fn get(&self, row: usize, col: usize) -> Option { diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 86081a95..3db6175a 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -464,6 +464,184 @@ fn write_inter_block_128( Ok(()) } +/// lane-b128hv: one 128x64 (HORZ) or 64x128 (VERT) inter block, the two +/// halves a `PARTITION_HORZ`/`PARTITION_VERT` 128 superblock root carries -- +/// the syntax `decode_inter_block` reads for `sb128_rect` (decode.rs ~35343): +/// the same chain [`write_inter_block_128`] writes, at the block's own +/// rectangular window. Every CDF/context decision is taken at the enclosing +/// square `side` of 128 (what the decoder's `inter_piece!` passes), and the +/// block's true footprint governs only its mv-stack window, its mi/grid stamp +/// and its neighbour bands (decode.rs' own `write_w`/`write_h` split). +/// +/// SKIP only: the decoder reads a rect half's residual through the mu-chunk +/// loop, but the 128 NONE residual arm it would share is itself parked +/// (`EC_AV1_B128RES`), so offering one here would buy the same open filter +/// mismatch for a candidate the RD takes 0-2 times a frame. +/// +/// # Errors +/// A block that is intra or that is not skipped. +#[allow(clippy::too_many_arguments)] +fn write_inter_block_128_rect( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + grid: &mut MiGrid, + // The half's own top-left position in mode-info (4x4) units. + at_mi: (usize, usize), + // Its true footprint in samples: (128, 64) at HORZ, (64, 128) at VERT. + (w, h): (usize, usize), + block: &BlockCoeffs, + mi_cols: u32, + mi_rows: u32, + tx_select: bool, +) -> Result<()> { + let info = block.inter.ok_or_else(|| { + Error::unsupported("AV1 tile", "a 128-root rectangular half is coded inter") + })?; + if !block.skip { + return Err(Error::unsupported( + "AV1 tile", + "a 128-root rectangular half carries a residual", + )); + } + let (mi_r, mi_c) = at_mi; + let (w_mi, h_mi) = (w / MI, h / 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(usize::from(block.skip), &mut cdfs.skip[skip_ctx]); + write_cdef_idx(enc, (mi_r, mi_c), block.skip); + // NOT a whole superblock: decode.rs' `whole_sb` is `write_w == write_h == + // sb_px`, so a rect half reads its `delta_q` group even when skipped. + write_delta_q(enc, cdfs, (mi_r, mi_c), false, block.skip); + 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), + (w_mi, h_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, + w_mi, + h_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..h_mi { + for dc in 0..w_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: w_mi as u8, + size_h: h_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), + (w_mi, h_mi), + (w, h), + (mi_cols as usize, mi_rows as usize), + info.ref_frame, + block.motion_mode, + )?; + } + if tx_select { + // `read_block_tx_size_rect`'s skip arm: `txfm_partition_update_rect` + // with the BLOCK's own size in both bands, no symbol. + neighbours.record_txfm_rect((mi_r, mi_c), (w, h), (w, h)); + } + let zero_grids = [ + vec![0i32; TX32 * TX32], + vec![0i32; TX32 * TX32], + vec![0i32; TX32 * TX32], + ]; + // A 128 root's half is always SUB (16 px) aligned, so the coarse mode / + // side bands are named by the same SUB-grid origin every square block + // uses. + let at_sub = (mi_r / (SUB / MI), mi_c / (SUB / MI)); + neighbours.record_planes_rect(at_sub, (w, h), 0, &zero_grids, true); + neighbours.record_inter_rect_mi((mi_r, mi_c), (w, h), block.skip, true, block_ref(block)); + if let Some(r1) = info.ref1 { + neighbours.record_compound_rect_mi((mi_r, mi_c), (w, h), r1, 0, 1); + } + if w > h { + SB128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } else { + SB128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + Ok(()) +} + +/// lane-b128hv: how many 128x64 / 64x128 halves the inter writer has coded +/// since the last [`take_sb128_horz_hits`] / [`take_sb128_vert_hits`] (class +/// `gate-blind-to-feature`). +static SB128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// The VERT twin of [`SB128_HORZ_HITS`]. +static SB128_VERT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// The 128x64-half count since the last call, and zero it. +pub fn take_sb128_horz_hits() -> usize { + SB128_HORZ_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) +} + +/// The 64x128-half count since the last call, and zero it. +pub fn take_sb128_vert_hits() -> usize { + SB128_VERT_HITS.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`]. @@ -1672,6 +1850,10 @@ fn ec_rng_trace(msg: impl FnOnce() -> String) { /// `PARTITION_NONE` (spec 6.10.4): the whole block, undivided. const PARTITION_NONE: usize = 0; +/// `PARTITION_HORZ` (spec 6.10.4): the block cut into a top and a bottom half. +const PARTITION_HORZ: usize = 1; +/// `PARTITION_VERT` (spec 6.10.4): the block cut into a left and a right half. +const PARTITION_VERT: usize = 2; /// `PARTITION_SPLIT` (spec 6.10.4): the block cut into four quadrants. const PARTITION_SPLIT: usize = 3; @@ -2403,6 +2585,15 @@ pub enum Quadrant { /// 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), + /// lane-b128hv: the two 128x64 (`true`) or 64x128 (`false`) inter blocks a + /// `PARTITION_HORZ` / `PARTITION_VERT` 128 superblock root carries, in the + /// order the decoder reads them (top then bottom, left then right). + /// Carried by the top-left 32x32 entry of the root's sixteen, exactly as + /// [`Whole128`](Quadrant::Whole128) is. + /// + /// SKIP only ([`crate::tile::write_inter_block_128_rect`] refuses a + /// residual), single reference or compound. + Rect128(bool, Vec), /// A quadrant a [`Whole64`](Quadrant::Whole64) at its superblock's /// top-left already coded; it carries no block of its own. Covered, @@ -2415,7 +2606,7 @@ impl Quadrant { Quadrant::Whole(block) | Quadrant::Whole64(block) | Quadrant::Whole128(block) => { std::slice::from_ref(block) } - Quadrant::Split(blocks) => blocks.as_slice(), + Quadrant::Split(blocks) | Quadrant::Rect128(_, blocks) => blocks.as_slice(), Quadrant::Covered => &[], } } @@ -2760,14 +2951,18 @@ impl Neighbours { /// [`Self::record_palette_y`] for the chroma bands (decode.rs /// `record_palette_uv_rect`) -- `size == 0` clears stale state the same /// way, and the span is in LUMA pixels for both planes' bands alike. - fn record_palette_uv(&mut self, (r, c): (usize, usize), side: usize, size: u8, colors: [u16; 8]) { - for cell in 0..(side / MI).max(1) { + fn record_palette_uv(&mut self, (r, c): (usize, usize), (w, h): (usize, usize), size: u8, colors: [u16; 8]) { + // lane-b128hv: the above band spans the block's WIDTH and the left + // band its HEIGHT; identical to the one loop this replaces at w == h. + for cell in 0..(w / MI).max(1) { if let Some(e) = self.above_palette_uv_size.get_mut(c + cell) { *e = size; if size > 0 { self.above_palette_uv_colors[c + cell] = colors; } } + } + for cell in 0..(h / MI).max(1) { if let Some(e) = self.left_palette_uv_size.get_mut(r + cell) { *e = size; if size > 0 { @@ -2780,14 +2975,18 @@ impl Neighbours { /// What a just-written block leaves in the palette bands (decode.rs /// `record_palette_y_rect`): its size and colours over every 4x4 unit it /// spans, `0` for a block that took no palette. - fn record_palette_y(&mut self, (r, c): (usize, usize), side: usize, size: u8, colors: [u16; 8]) { - for cell in 0..(side / MI).max(1) { + fn record_palette_y(&mut self, (r, c): (usize, usize), (w, h): (usize, usize), size: u8, colors: [u16; 8]) { + // lane-b128hv: the above band spans the block's WIDTH and the left + // band its HEIGHT; identical to the one loop this replaces at w == h. + for cell in 0..(w / MI).max(1) { if let Some(e) = self.above_palette_size.get_mut(c + cell) { *e = size; if size > 0 { self.above_palette_colors[c + cell] = colors; } } + } + for cell in 0..(h / MI).max(1) { if let Some(e) = self.left_palette_size.get_mut(r + cell) { *e = size; if size > 0 { @@ -2814,6 +3013,27 @@ impl Neighbours { } } + /// lane-b128hv: decode.rs `txfm_partition_update_rect` -- the two bands + /// take the transform's own HEIGHT (left) and WIDTH (above), over the + /// txb's own rect span. [`Self::record_txfm`] is this at `tx_w == tx_h`. + fn record_txfm_rect( + &mut self, + (mi_r, mi_c): (usize, usize), + (tx_w, tx_h): (usize, usize), + (txb_w, txb_h): (usize, usize), + ) { + for i in 0..txb_h / MI { + if let Some(cell) = self.left_txfm.get_mut(mi_r + i) { + *cell = tx_h as u8; + } + } + for i in 0..txb_w / MI { + if let Some(cell) = self.above_txfm.get_mut(mi_c + i) { + *cell = tx_w as u8; + } + } + } + /// `get_tx_size_context` as libaom writes it for a block inside an INTER /// frame (decode.rs `tx_size_context_txfm_rect`): the `TXFM_CONTEXT` /// bands, except that an *inter* neighbour contributes its own BLOCK size. @@ -2935,15 +3155,31 @@ impl Neighbours { mode: usize, grids: &[Vec; 3], luma: bool, + ) { + self.record_planes_rect(at, (side, side), mode, grids, luma); + } + + /// lane-b128hv: [`Self::record_planes`] with independent above (width) / + /// left (height) extents, decode.rs `record_rect_mi`'s own split -- the + /// 128 root's HORZ/VERT halves are the writer's first rect blocks. + fn record_planes_rect( + &mut self, + at: (usize, usize), + (w, h): (usize, usize), + mode: usize, + grids: &[Vec; 3], + luma: bool, ) { let (r, c) = at; - for cell in 0..side / SUB { + for cell in 0..w / SUB { self.above_mode[c + cell] = mode; + self.above_side[c + cell] = w; + } + for cell in 0..h / SUB { self.left_mode[r + cell] = mode; - self.above_side[c + cell] = side; - self.left_side[r + cell] = side; + self.left_side[r + cell] = h; } - self.record_mi_planes((r * (SUB / MI), c * (SUB / MI)), side, grids, luma); + self.record_mi_planes_rect((r * (SUB / MI), c * (SUB / MI)), (w, h), grids, luma); } /// The coefficient-context half of [`Self::record`], taking the block's @@ -2964,19 +3200,33 @@ impl Neighbours { side: usize, grids: &[Vec; 3], luma: bool, + ) { + self.record_mi_planes_rect(at_mi, (side, side), grids, luma); + } + + /// [`Self::record_mi_planes`] with independent above (width) / left + /// (height) extents (lane-b128hv, decode.rs `record_mi_rect`). + fn record_mi_planes_rect( + &mut self, + at_mi: (usize, usize), + (w, h): (usize, usize), + grids: &[Vec; 3], + luma: bool, ) { let (mi_r, mi_c) = at_mi; if screen_armed() { let (size, colors) = self.pending_palette.take().unwrap_or((0, [0u16; 8])); - self.record_palette_y(at_mi, side, size, colors); + self.record_palette_y(at_mi, (w, h), size, colors); let (uv_size, uv_colors) = self.pending_palette_uv.take().unwrap_or((0, [0u16; 8])); - self.record_palette_uv(at_mi, side, uv_size, uv_colors); + self.record_palette_uv(at_mi, (w, h), uv_size, uv_colors); } let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane])); - let side_mi = side / MI; - for cell in 0..side_mi { - self.left_side_mi[mi_r + cell] = side; - self.above_side_mi[mi_c + cell] = side; + let (w_mi, h_mi) = (w / MI, h / MI); + for cell in 0..h_mi { + self.left_side_mi[mi_r + cell] = h; + } + for cell in 0..w_mi { + self.above_side_mi[mi_c + cell] = w; } // libaom rounds the luma edge up to the plane's own 4x4 unit before // clamping a subsampled plane (`ROUND_POWER_OF_TWO(max_blocks_high, @@ -2995,25 +3245,29 @@ impl Neighbours { round_up_even(self.mi_cols), round_up_even(self.mi_cols), ]; - for cell in 0..side_mi { + for cell in 0..h_mi { let keep_left = self.left[mi_r + cell][0]; - let keep_above = self.above[mi_c + cell][0]; self.left[mi_r + cell] = std::array::from_fn(|plane| { - if cell < side_mi.min(bound_h[plane].saturating_sub(mi_r)) { + if cell < h_mi.min(bound_h[plane].saturating_sub(mi_r)) { states[plane] } else { Default::default() } }); + if !luma { + self.left[mi_r + cell][0] = keep_left; + } + } + for cell in 0..w_mi { + let keep_above = self.above[mi_c + cell][0]; self.above[mi_c + cell] = std::array::from_fn(|plane| { - if cell < side_mi.min(bound_w[plane].saturating_sub(mi_c)) { + if cell < w_mi.min(bound_w[plane].saturating_sub(mi_c)) { states[plane] } else { Default::default() } }); if !luma { - self.left[mi_r + cell][0] = keep_left; self.above[mi_c + cell][0] = keep_above; } } @@ -3027,6 +3281,56 @@ impl Neighbours { self.record_inter_mi((r * (SUB / MI), c * (SUB / MI)), side, skip, is_inter, ref_frame); } + /// lane-b128hv: [`Self::record_inter_mi`] with independent above (width) + /// / left (height) spans, decode.rs `record_inter_rect_mi`'s own split. + fn record_inter_rect_mi( + &mut self, + (mi_r, mi_c): (usize, usize), + (w, h): (usize, usize), + skip: bool, + is_inter: bool, + ref_frame: i8, + ) { + let altref = is_inter && ref_frame == crate::mvstack::ALTREF_FRAME; + for cell in 0..h / MI { + self.left_skip[mi_r + cell] = skip; + self.left_inter[mi_r + cell] = is_inter; + self.left_ref[mi_r + cell] = ref_frame; + self.left_ref1[mi_r + cell] = None; + self.left_comp_group_idx[mi_r + cell] = if altref { 3 } else { 0 }; + self.left_compound_idx[mi_r + cell] = u8::from(altref); + } + for cell in 0..w / MI { + self.above_skip[mi_c + cell] = skip; + self.above_inter[mi_c + cell] = is_inter; + self.above_ref[mi_c + cell] = ref_frame; + self.above_ref1[mi_c + cell] = None; + self.above_comp_group_idx[mi_c + cell] = if altref { 3 } else { 0 }; + self.above_compound_idx[mi_c + cell] = u8::from(altref); + } + } + + /// [`Self::record_compound_mi`] over a rect block's own two spans. + fn record_compound_rect_mi( + &mut self, + (mi_r, mi_c): (usize, usize), + (w, h): (usize, usize), + ref1: i8, + comp_group_idx: u8, + compound_idx: u8, + ) { + for cell in 0..h / MI { + self.left_ref1[mi_r + cell] = Some(ref1); + self.left_comp_group_idx[mi_r + cell] = comp_group_idx; + self.left_compound_idx[mi_r + cell] = compound_idx; + } + for cell in 0..w / MI { + self.above_ref1[mi_c + cell] = Some(ref1); + self.above_comp_group_idx[mi_c + cell] = comp_group_idx; + self.above_compound_idx[mi_c + cell] = compound_idx; + } + } + /// [`Self::record_inter_mi`]'s compound half (decode.rs /// `Neighbours::record_compound_ctx_rect_mi`): overwrites the ALTREF /// single-reference default with a real compound block's own second @@ -3435,7 +3739,10 @@ 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::Whole128(_) | Quadrant::Covered => { + Quadrant::Whole64(_) + | Quadrant::Whole128(_) + | Quadrant::Rect128(..) + | Quadrant::Covered => { return Err(Error::unsupported( "AV1 tile", "a key frame codes a 64x64 block as `Superblock::Whole`", @@ -5103,7 +5410,7 @@ 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(_) => return 0.0, + Quadrant::Whole128(_) | Quadrant::Rect128(..) => return 0.0, Quadrant::Whole(_) => 32, Quadrant::Split(_) => 16, // lane-tx64: a 64x64 root that codes a residual pays for one @@ -5725,6 +6032,22 @@ pub(crate) fn partition_bits(side: usize, split: bool) -> f64 { crate::encode::symbol_bits(cdf, symbol) } +/// lane-b128hv: [`partition_bits`] for any partition symbol, at the same +/// fixed (round-2) tables -- what the 128 root's HORZ/VERT candidate is priced +/// with (`PARTITION_HORZ` = 1, `PARTITION_VERT` = 2). +pub(crate) fn partition_bits_sym(side: usize, symbol: usize) -> f64 { + static CDFS: LazyLock = LazyLock::new(|| Cdfs::new(2)); + let cdfs = &*CDFS; + let cdf: &[u16] = match side { + 128 => &cdfs.partition_w128[0], + SB => &cdfs.partition_w64[0], + BLOCK => &cdfs.partition_w32[0], + TX8 => &cdfs.partition_w8[0], + _ => &cdfs.partition_w16[0], + }; + crate::encode::symbol_bits(cdf, symbol) +} + /// coeffs() for one plane's transform block of any coefficients the base and /// base-range syntax reach (spec 5.11.39). /// @@ -6807,12 +7130,17 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( if sb128 && sb_start { // 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, - }); + let root_entry = ((sb_r & !1) * 2 < rows && (sb_c & !1) * 2 < cols) + .then(|| &blocks[(((sb_r & !1) * 2) * cols + (sb_c & !1) * 2) as usize]); + let root_block = root_entry.and_then(|q| match q { + Quadrant::Whole128(block) => Some(block), + _ => None, + }); + // lane-b128hv: the two rectangular halves a HORZ/VERT root carries. + let root_rect = root_entry.and_then(|q| match q { + Quadrant::Rect128(horz, halves) => Some((*horz, halves)), + _ => None, + }); write_sb128_root( &mut enc, &mut cdfs, @@ -6821,7 +7149,12 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( sb_c, mi_cols, mi_rows, - if root_block.is_some() { PARTITION_NONE } else { PARTITION_SPLIT }, + match (root_block.is_some(), root_rect) { + (true, _) => PARTITION_NONE, + (_, Some((true, _))) => PARTITION_HORZ, + (_, Some((false, _))) => PARTITION_VERT, + _ => PARTITION_SPLIT, + }, ); if let Some(block) = root_block { let at128 = ((sb_r & !1) as usize * 4, (sb_c & !1) as usize * 4); @@ -6839,6 +7172,35 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs( sb128_none = true; continue; } + if let Some((horz, halves)) = root_rect { + // libaom `decode_partition` at BLOCK_128X128: `subsize` at + // (mi_row, mi_col) and a second one at + hbs (16 mi) along the + // cut axis, the second only when it is inside the frame -- the + // search only offers a root wholly inside, so both are. + let base_mi = ((sb_r & !1) as usize * SB_MI as usize, (sb_c & !1) as usize * SB_MI as usize); + let (w, h) = if horz { (128usize, 64usize) } else { (64, 128) }; + for (i, half) in halves.iter().enumerate() { + let at_mi = if horz { + (base_mi.0 + i * 16, base_mi.1) + } else { + (base_mi.0, base_mi.1 + i * 16) + }; + write_inter_block_128_rect( + &mut enc, + &mut cdfs, + &mut neighbours, + &mut grid, + at_mi, + (w, h), + half, + mi_cols, + mi_rows, + tx_select, + )?; + } + sb128_none = true; + continue; + } } { if !sb128 { @@ -7084,7 +7446,10 @@ 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::Whole128(_) | Quadrant::Covered => { + Quadrant::Whole64(_) + | Quadrant::Whole128(_) + | Quadrant::Rect128(..) + | Quadrant::Covered => { return Err(Error::unsupported( "AV1 tile", "a `Whole64`/`Covered` quadrant needs its superblock's \ diff --git a/lanes/b128hv.report.md b/lanes/b128hv.report.md new file mode 100644 index 00000000..2a9f7687 --- /dev/null +++ b/lanes/b128hv.report.md @@ -0,0 +1,205 @@ +# lane-b128hv — HORZ and VERT at the 128 superblock root + +The partition lane-b128 deferred and lane-b128r deferred again: a +`PARTITION_HORZ` / `PARTITION_VERT` 128x128 root, two 128x64 / 64x128 inter +blocks where the NONE arm codes one square. Written, witnessed on both cuts +through both decoders, measured on all five 12-frame rows and both long-GOP +rows, and **shipped on** (`EC_AV1_B128HV=0` is the attribution control). + +## 1. What the deferral actually cost + +Both earlier reports name the blocker as "rect neighbour recording in the +writer and rect trials in the search". That is exactly right and it was the +whole of the work: **this writer had no rectangular block of any size**. +`record` / `record_planes` / `record_mi_planes` / `record_inter_mi` / +`record_txfm` and both palette bands each took ONE side and stamped it into +the above band AND the left band. Every one of them now has an +(above = width, left = height) twin, with the square entry point delegating to +it — decode.rs' own `record_rect` / `record_inter_rect_mi` / +`txfm_partition_update_rect` split, mirrored on the writer side. + +> **Stale premise in the charter**: "the 64 root's rect machinery +> (64x32/32x64 in `code_square`/`code_rect` paths) is the model". There is no +> such machinery: `grep PARTITION_HORZ crates/ec-av1/src/tile.rs` was empty +> before this lane. The tile writer has only ever coded `PARTITION_NONE` and +> `PARTITION_SPLIT` at every level. decode.rs' `sb128_rect` arm +> (decode.rs:35343) was the only model, and it is the one this mirrors. + +## 2. The writer + +`write_inter_block_128_rect` codes one half: `skip`, `cdef_idx`, `delta_q`, +`intra_inter`, `comp_mode`, the reference/mode chain, the motion mode and the +transform syntax — the same chain `write_inter_block_128` writes, with every +CDF/context decision taken at the enclosing **square** side of 128 (what the +decoder's `inter_piece!` passes as `side`) and only the mv-stack window, the +mi/grid stamp and the neighbour bands taking the block's true `128x64` / +`64x128` footprint. Two details the square arm does not have: + +- **`delta_q` is coded.** decode.rs' `whole_sb` is `side == write_w == + write_h == sb_px`, so a rect half is NOT the whole superblock and its + `delta_q` group is read even when the block is skipped — where a skipped + NONE root writes none. A writer passing `is_whole_sb = true` here would drop + a symbol group the reader reads. +- **`record_txfm_rect`**, since `read_block_tx_size_rect`'s skip arm records + the BLOCK's own width above and height left, not one square side. + +SKIP only. The decoder reads a rect half's residual (it is in +`rect_inter_residual_supported`), but the residual arm it would share is the +128 NONE one, which is parked behind `EC_AV1_B128RES=1` over an open +filter-stage mismatch (lane-b128r) — an inert candidate does not buy a live +mismatch, and the same holds here. + +`Quadrant::Rect128(horz, halves)` carries the pair on the root's top-left +32x32 entry, exactly as `Whole128` does. + +## 3. The search + +`search_root_128_rect` prices the root as two halves, single reference or +compound, through the same `search_skip_64` the NONE arm uses — which now +takes a `(w, h)` footprint and tiles it into squares of its SHORTER side (one +square when it is square, so the square path is byte-identical; two 64x64 +luma + two 32x32 chroma squares per half otherwise). Both cuts are priced and +the cheaper one competes with the NONE block and with the four superblocks, +all four candidates carrying their own partition symbol +(`tile::partition_bits_sym`). + +**The first half is published into the mi grid before the second is +searched.** The writer publishes it (`grid.set` over the half's footprint), so +a second half searched against the stale grid would be priced — and its mv +predicted — off a stack the decoder never derives (class +*encoder-grid-drift-invisible-to-pixel-gate*). `MiGrid::snapshot_rect` / +`restore_rect` put the root's 32x32-mi window back before the four-superblock +arm is measured against it. + +## 4. Witness (red before / green after) + +`encode::tests::a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders` +(`--ignored`, it moves the process-global superblock size), three passes over +one 12-frame `testsrc2` clip at 1280x768: + + HORZ: search won 660 HORZ + 0 VERT roots, writer coded 2640 128x64 + 0 64x128 halves + VERT: search won 0 HORZ + 660 VERT roots, writer coded 0 128x64 + 2640 64x128 halves + unforced: search won 17 HORZ + 9 VERT roots, writer coded 68 128x64 + 36 64x128 halves + test ... ok + +(the writer counts are 4x the search counts because the filter search re-codes +each tile). Every pass sample-exact against the encoder's own reconstruction +through `decode_stream` **and** through ffmpeg. RED before this lane by +construction: `write_sb128_root` could only name `PARTITION_NONE` or +`PARTITION_SPLIT`, so all three counts were 0 and no such block existed to +decode. It was green on the first draft — no bisect was needed. + +The **unforced** row is the point: 17 HORZ + 9 VERT roots over 12 frames of +film-like content, with no knob set. + +## 5. Census on real content (`EC_AV1_B128_CENSUS=1`) + +Extended with the two shapes; the 4K 12-frame gate, 88 inter frames: + +| shape | per frame | total | +|---|---|---| +| whole 128x128 NONE roots | 89-102 | — | +| **HORZ roots** | 0-3 | **175** | +| **VERT roots** | 0-1 | **119** | + +On the long-GOP film A rows the 128 root fires far less often overall (3-8 +whole roots a frame, 2-7% of the frame's area) and the rect cut fires 0 there +— the lever is a 4K/quiet-content one. + +## 6. Gates + +`bd_rate_screen_native`, 12 frames, four quantizers, BD-rate vs libaom +`cpu-used 6` / rav1e `speed 6` (lower is better). Control = the same binary at +`EC_AV1_B128HV=0`, which is byte-identical to the merge base (pin evidence +below). + +| row | control | + HORZ/VERT | +|---|---|---| +| bars 1080p | -3.5 / -19.0 | -3.4 / -19.0 | +| film A (1080p) | +17.9 / -6.4 | +18.0 / -6.3 | +| bars 2160p | +8.6 / -13.7 | **+8.4 / -14.0** | +| film B (2160p) | +22.9 / -3.6 | +23.0 / -3.5 | +| screen capture | +14.4 / -33.2 | +14.4 / -33.2 | + +The two film rows move +0.1 on both columns — WORSE, inside the ±0.3 flat +band but not an improvement; bars 2160p is 0.2/0.3 better; screen is +unchanged to the digit. + +`bd_rate_film_long_gop`, 48 pictures, one key frame and 47 inter: + +| row | control | + HORZ/VERT | +|---|---|---| +| film A | +22.0 / -8.4 | **+21.9 / -8.6** | +| film B | +76.5 / +1.2 | **+75.8 / +0.8** | + +**Both films down on both columns**, film B by 0.7 / 0.4. This is where the +arm pays and it is the arm his exports are: a 48-picture GOP has the long +reference chains whose 128-wide regions split cleanly along one axis. + +Wall on the long-GOP arm: film A 537.6s -> 594.0s (+10.5%), film B 434.2s -> +446.7s (+2.9%) — both under the +15% ceiling. (The gate's own `ours:rav1e` +ratios are noisier than the raw walls here: rav1e's own column moved 50.3s vs +55.8s between the two runs.) + +**Verdict: ships on.** Both long-GOP film rows improve on both columns, the +12-frame film rows are flat at ±0.1 (inside the band the compound arm shipped +under), screen is unchanged and bars 2160p improves. + +## 7. Pins + +`encode::tests::the_encoders_own_streams_are_byte_identical_to_their_pins` +re-taken: **`(150, 8291, 0x1f00bb0eb099a27f)`** — was `(150, 8290, +0x92cb11033d1f5813)`. The **q=60 pin does NOT move** (`(60, 33227, +0x57ee6b1f8eacd881)` stands): at that quantizer the rect cut never wins its +own comparison on the pin clip, which is itself the cheapest possible +statement of how sparse the arm is. `EC_AV1_B128HV=0` restores 8290 exactly — +the proof that nothing else in this lane touches the shipped stream. Green at +the default and at `EC_AV1_SPEED=6`. No other byte pin moved. + +## 8. Suite / checks (the shipped state) + + cargo check --workspace --all-targets -j4 0 errors, 0 ec-av1 warnings + s1 --skip stream:: 345 passed; 0 failed; 38 ignored RC=0 + s2 stream:: --skip 10bit 202 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_root_horz_and_vert_halves_decode_exact_through_both_decoders ok + the_encoders_own_streams_are_byte_identical_to_their_pins ok, and ok at EC_AV1_SPEED=6 + +`encoder::tests::bitrate_target_lands_within_5_percent_over_48_frames` (it is +NOT `--ignored`; it runs inside s1). Its numbers on this tree, tolerance ±5%: + +| target | flat | pyramid | +|---|---|---| +| 384 kbit/s | -1.9% | +2.0% | +| 768 kbit/s | -2.6% | -0.0% | +| 1536 kbit/s | **-2.8%** | +0.1% | +| 2000 kbit/s | -1.7% | +0.0% | + +Worst arm -2.8%, and the arm the test's own doc calls its ceiling (the 2 +Mbit/s pyramid, -4.4% when the tolerance was cut) now lands at +0.0%. It is +not sitting near its bound on this tree. + +## 9. Disposition + +- `open`: **the rect root's `delta_q` group is not priced.** A rect 128 root + codes a `delta_q` symbol group that a SKIPPED NONE root omits (section 2), + and `search_root_128_rect`'s cost does not charge for it — so the arm is + under-priced by a few bits per root. This is the most likely reason the two + 12-frame film rows read +0.1 instead of flat-or-better while the long-GOP + rows gain. Next step: add `delta_q`'s own symbol cost to the rect candidate + and re-run the 12-frame film rows; if they go flat-or-down the arm is a + clean win on both arms of the gate. +- `deferred`: **the rect halves' RESIDUAL.** The decoder already reads it + (`rect_inter_residual_supported` lists (128,64)/(64,128) and + `read_block_tx_size_rect` codes two TX_64X64 units per half), but the arm it + would share is the 128 NONE residual, parked behind `EC_AV1_B128RES=1` over + an open filter-stage mismatch at a 128 block's own edge (lane-b128r). + Unblocked by root-causing that mismatch. +- `deferred`: **the AB shapes at the 128 root** (`PARTITION_HORZ_A/_B`, + `VERT_A/_B` — one 128x64/64x128 half plus two 64x64 quadrants). The decoder + reads them (`sb128_ab`, decode.rs:35330); the writer now has the rect + half it needs, so this is the cheapest remaining partition lever at the + root. +- `open` (inherited): search-time vs write-time mv stacks still differ + (lane-sb128b's second open item).