From 17448fad957f0c4c72caaa4a05bb6345b9959c96 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 05:00:10 +0300 Subject: [PATCH] feat(av1): a 16x16 inter leaf splits into four 8x8 ones on cost The quadtree now runs 32 -> 16 -> 8 inside an inter frame: a 16x16 leaf wholly inside the frame that carries `eight` is written as a real PARTITION_SPLIT at BLOCK_16X16 with four 8x8 leaves, where before only a leaf the true frame edge cut through was ever split (and then on geometry, with the edge's gathered flag). Same skipped-block prune one level up. The desync this first shipped with was the skip/intra-inter neighbour context: `Neighbours` kept it per 16x16 slot, so all four leaves read the slot's coarse state and left only the last leaf's behind. Under a real split the bottom-left leaf's above neighbour is the FIRST leaf and the bottom-right's above and left are two different ones -- the arrays are now per 4x4 mode-info unit, like `above_side_mi` already was, and each leaf reads and records its own cells (which also retires the single-previous- leaf override the straddling path used). BD-rate vs libaom / rav1e, same 12-frame recipe: 1080p +294.5 -> +234.0 | +215.8 -> +171.9 2160p +320.9 -> +260.3 | +253.2 -> +203.2 screen +395.6 -> +318.5 | +181.1 -> +155.3 The 8-way split fires on 5.4% / 4.4% / 7.8% of 16x16 leaves. --- crates/ec-av1/src/encode.rs | 136 +++++++++++++++++++++++++++++------- crates/ec-av1/src/tile.rs | 121 ++++++++++++++++++++++---------- 2 files changed, 193 insertions(+), 64 deletions(-) diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index b88312d0..7c11ce7e 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -110,6 +110,17 @@ pub(crate) fn take_predicted_bits() -> Vec { PREDICTED_BITS.with(|p| std::mem::take(&mut *p.borrow_mut())) } +/// Whether a 16x16 inter leaf may split into four 8x8 ones of its own. +const SPLIT_INTER_8: bool = true; + +/// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build. +fn split_inter_8() -> bool { + match std::env::var("EC_AV1_SPLIT_INTER8").ok() { + Some(v) if cfg!(test) => v != "0", + _ => SPLIT_INTER_8, + } +} + /// Whether a 16x16 (or 8x8) leaf runs a motion search of its own beside the /// NEARESTMV candidate it always had. const LEAF_NEW_MV: bool = true; @@ -142,9 +153,14 @@ fn split_inter_blocks() -> bool { /// How often each partition decision was taken since the last /// [`take_partition_hits`], so a gate can report how often a new partition /// fires rather than assume it does (gate-blind-to-feature). Index 0 is an -/// inter 32x32 block left whole, 1 one split into four 16x16 leaves. -static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 2] = - [std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0)]; +/// inter 32x32 block left whole, 1 one split into four 16x16 leaves; 2 is +/// such a leaf left whole, 3 one split into four 8x8 leaves of its own. +static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [ + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), +]; /// Records one such decision. fn partition_hit(which: usize) { @@ -153,8 +169,8 @@ fn partition_hit(which: usize) { /// Takes (and clears) the counts. #[cfg(test)] -pub(crate) fn take_partition_hits() -> [usize; 2] { - [0, 1].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +pub(crate) fn take_partition_hits() -> [usize; 4] { + [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) } /// Whether a 32x32 block may be split into four 16x16 ones when the trial says @@ -1965,11 +1981,16 @@ fn record_mi(grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: O /// The reconstructed samples one 32x32 square covers in all three planes, so /// that a partition trial can be undone. -fn snapshot(luma: &Plane, chroma: &[Plane; 2], (x, y): (usize, usize)) -> [Vec; 3] { +fn snapshot( + luma: &Plane, + chroma: &[Plane; 2], + (x, y): (usize, usize), + side: usize, +) -> [Vec; 3] { [ - luma.snapshot(x, y, BLOCK), - chroma[0].snapshot(x / 2, y / 2, BLOCK / 2), - chroma[1].snapshot(x / 2, y / 2, BLOCK / 2), + luma.snapshot(x, y, side), + chroma[0].snapshot(x / 2, y / 2, side / 2), + chroma[1].snapshot(x / 2, y / 2, side / 2), ] } @@ -1978,11 +1999,12 @@ fn restore( luma: &mut Plane, chroma: &mut [Plane; 2], (x, y): (usize, usize), + side: usize, saved: &[Vec; 3], ) { - luma.restore(x, y, BLOCK, &saved[0]); - chroma[0].restore(x / 2, y / 2, BLOCK / 2, &saved[1]); - chroma[1].restore(x / 2, y / 2, BLOCK / 2, &saved[2]); + luma.restore(x, y, side, &saved[0]); + chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]); + chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]); } /// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set @@ -2385,7 +2407,7 @@ pub(crate) fn encode_key_frame_inner( } let (x, y) = (col * BLOCK, row * BLOCK); let (c0, r0) = (col * 2, row * 2); - let base = snapshot(&luma, &chroma, (x, y)); + let base = snapshot(&luma, &chroma, (x, y), BLOCK); // spec `decode_partition`'s hasRows/hasCols recomputed at this // 32x32 block's own half (see `crate::tile::has_half`): the @@ -2459,11 +2481,11 @@ pub(crate) fn encode_key_frame_inner( &mode_bits(above_mode[c0], left_mode[r0]), fctx, ); cost_whole += search.lambda * partition_bits(BLOCK, false); - let after_whole = snapshot(&luma, &chroma, (x, y)); + let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); // What four 16x16 blocks cost instead, each searched against // the reconstruction the ones before it left. - restore(&mut luma, &mut chroma, (x, y), &base); + restore(&mut luma, &mut chroma, (x, y), BLOCK, &base); let mut split = Vec::with_capacity(4); let mut cost_split = search.lambda * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false)); @@ -2545,7 +2567,7 @@ pub(crate) fn encode_key_frame_inner( modes.extend_from_slice(&split_modes); blocks.push(Quadrant::Split(split)); } else { - restore(&mut luma, &mut chroma, (x, y), &after_whole); + restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole); for cell in 0..2 { above_mode[c0 + cell] = whole.mode; left_mode[r0 + cell] = whole.mode; @@ -3284,7 +3306,7 @@ pub(crate) fn encode_inter_frame( let stack = find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows); - let base = snapshot(&luma, &chroma, (x, y)); + let base = snapshot(&luma, &chroma, (x, y), BLOCK); let (block, mut cost_whole) = search_inter_block( &mut luma, &mut chroma, @@ -3296,7 +3318,7 @@ pub(crate) fn encode_inter_frame( &stack, fctx, ); cost_whole += search.lambda * partition_bits(BLOCK, false); - let after_whole = snapshot(&luma, &chroma, (x, y)); + let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); // What four 16x16 leaves cost instead (spec // PARTITION_SPLIT at BLOCK_32X32, which @@ -3326,20 +3348,20 @@ pub(crate) fn encode_inter_frame( }); let split = (!block.skip && leaves_legal && split_inter_blocks()) .then(|| { - restore(&mut luma, &mut chroma, (x, y), &base); - let mut cost = search.lambda - * (partition_bits(BLOCK, true) - + 4.0 * partition_bits(SUB, false)); + restore(&mut luma, &mut chroma, (x, y), BLOCK, &base); + let mut cost = search.lambda * partition_bits(BLOCK, true); let mut leaves = Vec::with_capacity(4); for &(sr, sc) in &leaf_positions { let (mi_row, mi_col) = (sr * 4, sc * 4); + let (lx, ly) = (sc * SUB, sr * SUB); + let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB); let stack = find_mv_stack( &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows, ); let (leaf, leaf_cost) = code_square_inter( &mut luma, &mut chroma, - (sc * SUB, sr * SUB), + (lx, ly), SUB, &search, &mode_bits_table, @@ -3347,6 +3369,63 @@ pub(crate) fn encode_inter_frame( &ref_y8, &stack, fctx, ); + let leaf_cost = leaf_cost + + search.lambda * partition_bits(SUB, false); + let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB); + + // And what four 8x8 leaves cost instead -- + // the same tree one step further down, which + // the writer codes as a real PARTITION_SPLIT + // at BLOCK_16X16 (lane-av1rd2). Same + // skipped-block prune as the level above. + let eight = (!leaf.skip && split_inter_8()) + .then(|| { + restore( + &mut luma, &mut chroma, (lx, ly), SUB, &leaf_base, + ); + let mut cost8 = search.lambda + * (partition_bits(SUB, true) + + 4.0 * partition_bits(8, false)); + let mut eight = Vec::with_capacity(4); + for i in 0..4 { + let (mr, mc) = + (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2); + let stack8 = find_mv_stack( + &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows, + ); + let (leaf8, cost) = code_square_inter( + &mut luma, + &mut chroma, + (lx + (i % 2) * 8, ly + (i / 2) * 8), + 8, + &search, + &mode_bits_table, + reference, + &ref_y8, + &stack8, fctx, + ); + cost8 += cost; + record_mi(&mut grid, mr, mc, 2, leaf8.inter); + eight.push(leaf8); + } + (eight, cost8) + }); + match eight { + Some((eight, cost8)) if cost8 < leaf_cost => { + partition_hit(3); + cost += cost8; + leaves.push(BlockCoeffs { + eight: Some(eight), + ..BlockCoeffs::default() + }); + continue; + } + Some(_) => restore( + &mut luma, &mut chroma, (lx, ly), SUB, &after_leaf, + ), + None => {} + } + partition_hit(2); cost += leaf_cost; record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter); leaves.push(leaf); @@ -3362,7 +3441,7 @@ pub(crate) fn encode_inter_frame( blocks[r32 * cols + c32] = Quadrant::Split(leaves); continue; } - restore(&mut luma, &mut chroma, (x, y), &after_whole); + restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole); } partition_hit(0); record_mi(&mut grid, mi_row, mi_col, 8, block.inter); @@ -6324,11 +6403,14 @@ mod tests { // How often the inter split actually fired over this clip's four // encodes, against the whole 32x32 that was the only outcome // before (gate-blind-to-feature). - let [whole32, split32] = take_partition_hits(); + let [whole32, split32, whole16, split16] = take_partition_hits(); eprintln!( - "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%)", + "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \ + 16x16 leaves split into 8s {split16} of {} ({:.1}%)", whole32 + split32, - 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64 + 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64, + whole16 + split16, + 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64 ); let (aom, aom_wall) = external_ladder(&source, width, height, "libaom-av1", &aom_points); diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 12b95be3..463b9cd4 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -629,6 +629,9 @@ struct Neighbours { left_side_mi: Vec, /// Whether the neighbour carried no residual, for [`sb_coeff_inter_frame_tile`]'s /// skip context. Unused (and left at its default) by the key frame writers. + /// Kept per 4x4 mode-info unit, like [`Self::above_side_mi`] and for the + /// same reason: under a real PARTITION_SPLIT to 8x8 the four leaves of a + /// 16x16 read (and leave) different contexts inside one [`SUB`] slot. above_skip: Vec, /// The same, down the left edge. left_skip: Vec, @@ -676,10 +679,10 @@ impl Neighbours { left_side: vec![SB; rows], above_side_mi: vec![SB; cols * (SUB / MI)], left_side_mi: vec![SB; rows * (SUB / MI)], - above_skip: vec![false; cols], - left_skip: vec![false; rows], - above_inter: vec![false; cols], - left_inter: vec![false; rows], + above_skip: vec![false; cols * (SUB / MI)], + left_skip: vec![false; rows * (SUB / MI)], + above_inter: vec![false; cols * (SUB / MI)], + left_inter: vec![false; rows * (SUB / MI)], mi_cols, mi_rows, } @@ -768,11 +771,17 @@ impl Neighbours { /// fills for the coefficient and mode state. fn record_inter(&mut self, at: (usize, usize), side: usize, skip: bool, is_inter: bool) { let (r, c) = at; - for cell in 0..side / SUB { - self.above_skip[c + cell] = skip; - self.left_skip[r + cell] = skip; - self.above_inter[c + cell] = is_inter; - self.left_inter[r + cell] = is_inter; + self.record_inter_mi((r * (SUB / MI), c * (SUB / MI)), side, skip, is_inter); + } + + /// [`Self::record_inter`] taking the block's position directly in 4x4 + /// mode-info units, for a block finer than one [`SUB`] slot. + fn record_inter_mi(&mut self, (mi_r, mi_c): (usize, usize), side: usize, skip: bool, is_inter: bool) { + for cell in 0..side / MI { + self.above_skip[mi_c + cell] = skip; + self.left_skip[mi_r + cell] = skip; + self.above_inter[mi_c + cell] = is_inter; + self.left_inter[mi_r + cell] = is_inter; } } @@ -1682,6 +1691,7 @@ pub(crate) fn partition_bits(side: usize, split: bool) -> f64 { let cdf: &[u16] = match side { SB => &cdfs.partition_w64[0], BLOCK => &cdfs.partition_w32[0], + TX8 => &cdfs.partition_w8[0], _ => &cdfs.partition_w16[0], }; let symbol = if split { @@ -2368,6 +2378,50 @@ pub fn sb_coeff_inter_frame_tile( let at16 = (sr, sc); if has_cols16 && has_rows16 { let ctx16 = neighbours.partition_ctx(at16, SUB); + // A 16x16 leaf wholly inside the frame that + // carries `eight` split itself further, on + // cost rather than on geometry (lane-av1rd2): + // spec PARTITION_SPLIT at BLOCK_16X16, then + // the same four 8x8 leaves the straddling + // branch below writes -- all four inside, so + // the partition symbol is a real one rather + // than the edge's gathered flag. + if let Some(leaves) = &leaf.eight { + if leaves.len() != 4 { + return Err(Error::unsupported( + "AV1 tile", + "a 16x16 inter-frame block inside the frame that splits needs all four 8x8 leaves", + )); + } + enc.symbol(PARTITION_SPLIT, &mut cdfs.partition_w16[ctx16]); + let (mi_row0, mi_col0) = + (sr as u32 * SUB_MI, sc as u32 * SUB_MI); + for (i, leaf8) in leaves.iter().enumerate() { + let leaf_mi = ( + (mi_row0 + (i as u32 / 2) * 2) as usize, + (mi_col0 + (i as u32 % 2) * 2) as usize, + ); + let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8); + enc.symbol( + PARTITION_NONE, + &mut cdfs.partition_w8[leaf_ctx], + ); + let (skip, is_inter) = write_inter_frame_leaf8( + &mut enc, + &mut cdfs, + &mut neighbours, + &mut grid, + mi_cols, + mi_rows, + leaf8, + leaf_mi, + &scan8, + &scan4, + )?; + let _ = (skip, is_inter); + } + continue; + } enc.symbol(PARTITION_NONE, &mut cdfs.partition_w16[ctx16]); write_inter_frame_leaf( &mut enc, @@ -2413,7 +2467,6 @@ pub fn sb_coeff_inter_frame_tile( `eight` entry per 8x8 leaf inside the true frame", )); } - let mut prev_leaf: Option<((usize, usize), bool, bool)> = None; for (leaf8, (mr, mc)) in leaves.iter().zip(leaf_positions) { let leaf_mi = (mr as usize, mc as usize); let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8); @@ -2426,22 +2479,18 @@ pub fn sb_coeff_inter_frame_tile( mi_cols, mi_rows, leaf8, - at16, leaf_mi, &scan8, &scan4, - prev_leaf, )?; - prev_leaf = Some((leaf_mi, skip, is_inter)); + let _ = (skip, is_inter); } // Same write-back-once-from-the-last-leaf rule // as the key frame search's `write_leaf8` // caller (r15): the SUB-grid skip/inter arrays // are otherwise left stale for the next // 16x16 slot. - if let Some((_, skip, is_inter)) = prev_leaf { - neighbours.record_inter(at16, SUB, skip, is_inter); - } + } } continue; @@ -2451,13 +2500,14 @@ pub fn sb_coeff_inter_frame_tile( let (r, c) = at; let has_above = r32 > 0; let has_left = c32 > 0; - let skip_ctx = - usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]); + let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); + 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]); let is_inter = block.inter.is_some(); let (above_inter, left_inter) = - (neighbours.above_inter[c], neighbours.left_inter[r]); + (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]); let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter); enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]); @@ -2649,11 +2699,12 @@ fn write_inter_frame_leaf( const LAST_FRAME: i8 = 1; let (r, c) = at; - let skip_ctx = usize::from(neighbours.above_skip[c]) + usize::from(neighbours.left_skip[r]); + let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); + 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]); let (has_above, has_left) = (r > 0, c > 0); - let (above_inter, left_inter) = (neighbours.above_inter[c], neighbours.left_inter[r]); + let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]); let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter); let is_inter = block.inter.is_some(); enc.symbol(usize::from(is_inter), &mut cdfs.intra_inter[ii_ctx]); @@ -2812,11 +2863,9 @@ fn write_inter_frame_leaf8( mi_cols: u32, mi_rows: u32, block: &BlockCoeffs, - outer_at: (usize, usize), leaf_mi: (usize, usize), scan8: &Vec, scan4: &Vec, - prev_leaf: Option<((usize, usize), bool, bool)>, ) -> Result<(bool, bool)> { if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES { return Err(Error::unsupported( @@ -2834,20 +2883,16 @@ fn write_inter_frame_leaf8( /// branches. const LAST_FRAME: i8 = 1; - let (r, c) = outer_at; - let mut above_skip = neighbours.above_skip[c]; - let mut left_skip = neighbours.left_skip[r]; - let mut above_inter = neighbours.above_inter[c]; - let mut left_inter = neighbours.left_inter[r]; - if let Some(((pr, pc), pskip, pinter)) = prev_leaf { - if pc == leaf_mi.1 && leaf_mi.0 == pr + 2 { - above_skip = pskip; - above_inter = pinter; - } else if pr == leaf_mi.0 && leaf_mi.1 == pc + 2 { - left_skip = pskip; - left_inter = pinter; - } - } + // This leaf's own 4x4 mode-info cells, not the enclosing 16x16 slot's: + // under a real PARTITION_SPLIT all four leaves are coded, so the + // bottom-left leaf's true above neighbour is the FIRST leaf and the + // bottom-right's above and left are two DIFFERENT ones (lane-av1rd2 -- + // reading the coarse slot desynced the stream, and so did an override + // that remembered only the previous leaf). + let above_skip = neighbours.above_skip[leaf_mi.1]; + let left_skip = neighbours.left_skip[leaf_mi.0]; + let above_inter = neighbours.above_inter[leaf_mi.1]; + let left_inter = neighbours.left_inter[leaf_mi.0]; let skip_ctx = usize::from(above_skip) + usize::from(left_skip); enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]); @@ -2964,6 +3009,7 @@ fn write_inter_frame_leaf8( vec![0i32; TX4 * TX4], ]; neighbours.record_mi(leaf_mi, 8, &zero_grids); + neighbours.record_inter_mi(leaf_mi, 8, block.skip, block.inter.is_some()); } else { let grids = [ level_grid(&block.luma, TX8)?, @@ -2980,6 +3026,7 @@ fn write_inter_frame_leaf8( mode_for_tx, ); neighbours.record_mi(leaf_mi, 8, &grids); + neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter); } Ok((block.skip, is_inter)) }