From 710cb11ccd7b8806434ba5b629eebcfb15ea6628 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 6 Sep 2026 06:14:01 +0300 Subject: [PATCH] feat(av1): inter blocks search the var-tx tree one halving deep With the inter frame at TxMode::Select an inter block now codes its residual either as one transform over the whole block or as the four transforms of half the side, chosen by RD against the txfm_split symbols both arms spend. The writer codes the split root plus one unsplit flag per child off the interleaved TXFM_CONTEXT bands, and the split units read the inter coefficient tables. Blocks touching the true frame edge stay flat: the reader skips var-tx units past the edge. Still behind EC_AV1_TX_SELECT_INTER=1. --- crates/ec-av1/src/encode.rs | 134 +++++++++++++++++++++++++++++++++--- crates/ec-av1/src/tile.rs | 63 +++++++++++++---- 2 files changed, 177 insertions(+), 20 deletions(-) diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 3dffb14e..a493fd1b 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1790,6 +1790,111 @@ pub(crate) fn take_tx_depth_hits() -> [usize; 3] { std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed)) } +/// How many inter blocks resolved to each var-tx depth (0 = one transform +/// over the whole block, 1 = its four halves), the fire count a gate prints +/// to see the split search reach its candidates at all. +static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 2] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; + +/// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it. +#[cfg(test)] +pub(crate) fn take_inter_tx_split_hits() -> [usize; 2] { + std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// What the `txfm_split` symbols of one inter block cost at `depth`, priced +/// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0 +/// is one flag, depth 1 is a split root plus one unsplit flag per child +/// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH` +/// or a 4x4 sub-size). +fn txfm_split_bits(side: usize, depth: usize) -> f64 { + let max_tx = side.min(64); + let ctx = |tx: usize| { + crate::decode::txfm_partition_ctx_rect( + crate::decode::TXFM_CTX_INIT, + crate::decode::TXFM_CTX_INIT, + side, + tx, + tx, + ) + }; + if depth == 0 { + return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0); + } + symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1) + + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0) +} + +/// The inter block's own var-tx decision, once its motion vector is settled: +/// its residual as ONE transform over the whole block, or as the four +/// transforms of half the side the tree's first halving names. The prediction +/// is the same motion compensation either way, so the split trial +/// re-transforms the identical residual in four pieces -- it wins where four +/// small transforms carry a locally varying residual cheaper than one big +/// one. Commits the winner into `luma` and hands back its block-coordinate +/// levels, the depth the writer codes and the cost the winner adds to (or +/// takes off) the caller's already-computed flat cost. +/// +/// Only for a block wholly inside the frame: past the true edge the reader's +/// var-tx recursion skips the units that fall outside +/// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would +/// leave the residual units this writes unpaired. +#[allow(clippy::too_many_arguments)] +fn commit_inter_luma( + luma: &mut Plane, + (x, y): (usize, usize), + side: usize, + mv: (i32, i32), + reference: (&[u16], usize, usize, usize), + search: &Search, + flat: &Trial, + skip: bool, fctx: &crate::decode::FrameCtx, +) -> (Vec, u8, f64) { + let eligible = tx_select() + && tx_select_inter() + && !skip + && side >= 16 + && x + side <= luma.true_width + && y + side <= luma.true_height; + if !eligible { + luma.commit(x, y, side, flat); + return (flat.levels.clone(), 0, 0.0); + } + let tx = side / 2; + let set = if tx >= 16 { TxbSet::Luma16Inter } else { TxbSet::Luma8Inter }; + let mut levels = vec![0i32; side * side]; + let (mut sse, mut bits) = (0.0, 0.0); + let mut units = Vec::with_capacity(4); + for tu_row in 0..2 { + for tu_col in 0..2 { + let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx); + let trial = mc_trial( + luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2, + reference.3, false, search.base_q_idx, search.deadzone, set, fctx, + ); + sse += trial.sse; + bits += trial.bits; + for row in 0..tx { + levels[(tu_row * tx + row) * side + tu_col * tx..][..tx] + .copy_from_slice(&trial.levels[row * tx..][..tx]); + } + units.push((tu_x, tu_y, trial)); + } + } + let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1)); + let flat_cost = flat.sse + search.lambda * (flat.bits + txfm_split_bits(side, 0)); + if split_cost < flat_cost { + for (tu_x, tu_y, trial) in &units { + luma.commit(*tu_x, *tu_y, tx, trial); + } + INTER_TX_SPLIT_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + return (levels, 1, split_cost - flat_cost); + } + INTER_TX_SPLIT_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + luma.commit(x, y, side, flat); + (flat.levels.clone(), 0, 0.0) +} + #[allow(clippy::too_many_arguments)] fn code_square( luma: &mut Plane, @@ -2187,47 +2292,51 @@ fn code_square_inter( } if let (cost, Some((luma_new, u_new, v_new, skip_new, new_mv))) = best { if cost < intra_cost { - luma.commit(x, y, side, &luma_new); + let (levels, tx_depth, dcost) = commit_inter_luma( + luma, (x, y), side, new_mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_new, skip_new, fctx, + ); chroma[0].commit(x / 2, y / 2, side / 2, &u_new); chroma[1].commit(x / 2, y / 2, side / 2, &v_new); return ( BlockCoeffs { - luma: coeffs(&luma_new.levels, side), + luma: coeffs(&levels, side), u: coeffs(&u_new.levels, side / 2), v: coeffs(&v_new.levels, side / 2), mode: DC_PRED as u8, uv_mode: DC_PRED, skip: skip_new, eight: None, - tx_depth: 0, + tx_depth, inter: Some(InterInfo { mode: InterMode::NewMv, mv: new_mv, }), }, - cost, + cost + dcost, ); } } if inter_cost < intra_cost { - luma.commit(x, y, side, &luma_trial); + let (levels, tx_depth, dcost) = commit_inter_luma( + luma, (x, y), side, mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_trial, skip, fctx, + ); chroma[0].commit(x / 2, y / 2, side / 2, &u); chroma[1].commit(x / 2, y / 2, side / 2, &v); (BlockCoeffs { - luma: coeffs(&luma_trial.levels, side), + luma: coeffs(&levels, side), u: coeffs(&u.levels, side / 2), v: coeffs(&v.levels, side / 2), mode: DC_PRED as u8, uv_mode: DC_PRED, skip, eight: None, - tx_depth: 0, + tx_depth, inter: Some(InterInfo { mode: InterMode::NearestMv, mv, }), - }, inter_cost) + }, inter_cost + dcost) } else { (intra_block, intra_cost) } @@ -5905,7 +6014,16 @@ mod tests { let (width, height) = (128usize, 64usize); let pictures: Vec = (0..5).map(|i| panned_test_card(width, height, i * 3)).collect(); + let _ = take_inter_tx_split_hits(); let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); + let split = take_inter_tx_split_hits(); + eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]); + // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this + // content splits -- a green round trip in which the split never fires + // would prove only the flat path. + if tx_select() && tx_select_inter() { + assert!(split[1] > 0, "the inter var-tx split never fired"); + } let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 8fd63395..8a495fd0 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -1717,6 +1717,9 @@ fn write_luma_tus( grid: &[i32], mode: usize, scans: &[Vec; 4], + // lane-av1tx2 r2: an INTER block's split units read the inter coefficient + // tables, not the intra ones (`TxbSet::Luma*Inter`). + inter: bool, ) -> Result<()> { if tx < side && side > 32 { // A 64x64 block's own levels reach the writer as the 32x32 corner a @@ -1729,11 +1732,15 @@ fn write_luma_tus( } let coeff_side = tx.min(32); let n = side / tx; - let set = match tx { - 32 => TxbSet::Luma32, - 16 => TxbSet::Luma16, - 8 => TxbSet::Luma8, - 4 => TxbSet::Luma4, + let set = match (tx, inter) { + (32, false) => TxbSet::Luma32, + (16, false) => TxbSet::Luma16, + (8, false) => TxbSet::Luma8, + (4, false) => TxbSet::Luma4, + (32, true) => TxbSet::Luma32Inter, + (16, true) => TxbSet::Luma16Inter, + (8, true) => TxbSet::Luma8Inter, + (4, true) => TxbSet::Luma4Inter, _ => TxbSet::Luma64, }; let scan = match coeff_side { @@ -1819,7 +1826,7 @@ fn write_luma_select( } } let tx = max_tx >> depth; - write_luma_tus(enc, cdfs, neighbours, at_mi, side, tx, grid, mode, scans)?; + write_luma_tus(enc, cdfs, neighbours, at_mi, side, tx, grid, mode, scans, false)?; neighbours.record_tx(at_mi, side, tx); Ok(tx) } @@ -1860,11 +1867,42 @@ fn write_tx_syntax_inter( max_tx, max_tx, ); - enc.symbol(0, &mut cdfs.txfm_partition[ctx]); - neighbours.record_txfm(at_mi, max_tx, max_tx, max_tx); - } else { - neighbours.record_txfm(at_mi, side, side, side); + enc.symbol(usize::from(depth != 0), &mut cdfs.txfm_partition[ctx]); + if depth == 0 { + neighbours.record_txfm(at_mi, max_tx, max_tx, max_tx); + return max_tx; + } + // lane-av1tx2 r2: one halving of the var-tx tree. Each child of a + // split root codes its own `txfm_split` (decode.rs + // `read_var_tx_size` only stops symbol-free at `MAX_VARTX_DEPTH` + // or at a 4x4 sub-size), off the bands the children before it + // published -- so the context read and the update interleave per + // unit, exactly as the reader's recursion does. + let tx = max_tx / 2; + for row in (0..max_tx / MI).step_by(tx / MI) { + for col in (0..max_tx / MI).step_by(tx / MI) { + let unit = (mi_r + row, mi_c + col); + // The encoder only picks depth 1 for a block wholly + // inside the frame; the reader skips a unit past the true + // edge, which would leave the residual units unpaired. + debug_assert!( + unit.0 < neighbours.mi_rows && unit.1 < neighbours.mi_cols, + "a split inter transform unit past the frame edge" + ); + let ctx = txfm_partition_ctx_rect( + neighbours.above_txfm[unit.1], + neighbours.left_txfm[unit.0], + side, + tx, + tx, + ); + enc.symbol(0, &mut cdfs.txfm_partition[ctx]); + neighbours.record_txfm(unit, tx, tx, tx); + } + } + return tx; } + neighbours.record_txfm(at_mi, side, side, side); return max_tx; } let ctx = neighbours.tx_size_ctx_txfm(at_mi, max_tx); @@ -3128,6 +3166,7 @@ pub fn sb_coeff_inter_frame_tile_tx( &grids[0], mode_for_tx, &all_scans, + is_inter, )?; } write_block_planes( @@ -3336,7 +3375,7 @@ fn write_inter_frame_leaf( ]; if split { write_luma_tus( - enc, cdfs, neighbours, at_mi, SUB, tx, &grids[0], mode_for_tx, all_scans, + enc, cdfs, neighbours, at_mi, SUB, tx, &grids[0], mode_for_tx, all_scans, is_inter, )?; } write_block_planes( @@ -3561,7 +3600,7 @@ fn write_inter_frame_leaf8( ]; if split { write_luma_tus( - enc, cdfs, neighbours, leaf_mi, 8, tx, &grids[0], mode_for_tx, all_scans, + enc, cdfs, neighbours, leaf_mi, 8, tx, &grids[0], mode_for_tx, all_scans, is_inter, )?; } write_block_planes(