From 93429cb5f55047a0bd1f01ef2a58e784aa68cd36 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 07:32:46 +0300 Subject: [PATCH] feat(av1): the encoder codes one CDEF strength per 64x64 superblock The filter search only ever wrote `cdef_bits = 0`: one strength pair for the whole frame, because a per-unit choice needs a `cdef_idx` literal in the tile payload and the whole-frame re-decode the search runs cannot reach one. It can. Every candidate the coordinate search already decodes carries its own error PER 64x64 unit, so the pool of strength pairs tried under the winning deblocking levels doubles as libaom `av1_cdef_search`'s preset list: the units vote, the list grows by that histogram, and the cheapest list length wins on error plus lambda times the literals it costs. The tile is then written a second time with those literals (`tile::arm_cdef_idx`, mirroring the decoder's own `cdef_transmitted` slot) and the winner re-decoded from it, so the encoder's reference frame is still exactly what a decoder reconstructs. The BD gate prints the per-clip `cdef_bits` distribution and how many 64x64 units left the default preset. --- crates/ec-av1/src/encode.rs | 95 ++++++++++++++++--- crates/ec-av1/src/filter_search.rs | 145 ++++++++++++++++++++++++++++- crates/ec-av1/src/tile.rs | 88 ++++++++++++++++- 3 files changed, 310 insertions(+), 18 deletions(-) diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 60dce54e..9a48c010 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -3024,9 +3024,10 @@ pub(crate) fn encode_key_frame_inner( #[cfg(test)] record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx)); - let tile = crate::tile::sb_coeff_key_frame_tile_tx( - header.mi_cols, - header.mi_rows, + let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); + let mut tile = crate::tile::sb_coeff_key_frame_tile_tx( + mi_cols, + mi_rows, base_q_idx, &superblocks, tx_select, @@ -3042,9 +3043,21 @@ pub(crate) fn encode_key_frame_inner( &mut chroma, [&picture_y8, &picture_u8, &picture_v8], true, - |lf, cdef, h| { + &mut tile, + search.lambda, + |bits, sb_cols, grid| { + crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); + crate::tile::sb_coeff_key_frame_tile_tx( + mi_cols, + mi_rows, + base_q_idx, + &superblocks, + tx_select, + ) + }, + |lf, cdef, h, tile| { crate::decode::decode_key_frame_tile( - &tile, + tile, h.mi_cols, h.mi_rows, base_q_idx, @@ -3107,7 +3120,14 @@ fn pick_and_apply_filters( chroma: &mut [Plane<'_>; 2], source: [&[u8]; 3], search: bool, - decode: impl Fn(&LoopFilterParams, &CdefParams, &FrameHeader) -> Result, + // The coded tile, replaced in place when the search chooses a per-64x64 + // `cdef_idx` list (`cdef_bits > 0`): those literals live in the tile + // payload, so the tile is written a second time under `recode` and the + // winner re-decoded from it. + tile: &mut Vec, + lambda: f64, + recode: impl Fn(u8, usize, &[u8]) -> Result>, + decode: impl Fn(&LoopFilterParams, &CdefParams, &FrameHeader, &[u8]) -> Result, ) -> Result<()> { if !search { return Ok(()); @@ -3117,15 +3137,27 @@ fn pick_and_apply_filters( // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`: // `cdef_damping = 3 + (base_qindex >> 6)`, never searched. let damping = 3 + (header.quantization.base_q_idx >> 6); - let (lf, cdef, filtered) = crate::filter_search::pick_filters( - |lf, cdef| decode(lf, cdef, &hdr), + let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows); + let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize); + let (lf, cdef, idx_grid, picture) = crate::filter_search::pick_filters( + |lf, cdef| decode(lf, cdef, &hdr, tile), source, luma.width, (fw, fh), damping, + (sb_cols, sb_rows), + lambda, )?; header.loop_filter = lf; header.cdef = cdef; + let filtered = if idx_grid.is_empty() { + picture + } else { + let coded = recode(cdef.bits, sb_cols, &idx_grid)?; + let picture = decode(&lf, &cdef, &hdr, &coded)?; + *tile = coded; + picture + }; let dec_cw = filtered.width.div_ceil(2); let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh); @@ -4194,9 +4226,10 @@ pub(crate) fn encode_inter_frame( / modes.len() as f64; #[cfg(test)] record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx)); - let tile = crate::tile::sb_coeff_inter_frame_tile_tx( - header.mi_cols, - header.mi_rows, + let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); + let mut tile = crate::tile::sb_coeff_inter_frame_tile_tx( + mi_cols, + mi_rows, base_q_idx, &blocks, tx_select, @@ -4234,9 +4267,21 @@ pub(crate) fn encode_inter_frame( // `TxMode::Select` too (it used to skip and leave every inter frame // unfiltered once Select became the default). true, - |lf, cdef, h| { + &mut tile, + search.lambda, + |bits, sb_cols, grid| { + crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); + crate::tile::sb_coeff_inter_frame_tile_tx( + mi_cols, + mi_rows, + base_q_idx, + &blocks, + tx_select, + ) + }, + |lf, cdef, h, tile| { crate::decode::decode_inter_frame_tile( - &tile, + tile, h.mi_cols, h.mi_rows, base_q_idx, @@ -7218,6 +7263,30 @@ mod tests { mean(|l| l.2.0), mean(|l| l.2.1), ); + // How many strength presets each frame's CDEF list carried and + // how the 64x64 units spread over them (lane-av1lr): `bits 0` + // everywhere would mean the per-unit choice never fires. + let presets = crate::filter_search::take_cdef_presets(); + let mut by_bits = [0usize; 4]; + for (b, _) in &presets { + by_bits[usize::from(*b)] += 1; + } + let units: usize = presets.iter().flat_map(|(_, c)| c).sum(); + let on_extra: usize = presets + .iter() + .flat_map(|(_, c)| c.iter().skip(1)) + .sum(); + eprintln!( + "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \ + on a non-default preset ({:.1}%)", + by_bits[0], + by_bits[1], + by_bits[2], + by_bits[3], + on_extra, + units, + 100.0 * on_extra as f64 / units.max(1) as f64 + ); // Which chroma modes the search actually wins with, against the // unconditional DC_PRED that was the only outcome before // (gate-blind-to-feature). diff --git a/crates/ec-av1/src/filter_search.rs b/crates/ec-av1/src/filter_search.rs index 7a40e1b9..65067b91 100644 --- a/crates/ec-av1/src/filter_search.rs +++ b/crates/ec-av1/src/filter_search.rs @@ -40,6 +40,20 @@ pub(crate) fn take_chosen_levels() -> Vec<((u8, u8), (u8, u8), (u8, u8))> { }) } +thread_local! { + /// Per frame, in coding order: the `cdef_bits` chosen and how many 64x64 + /// superblocks ended up on each strength preset -- the BD gate prints the + /// distribution once per clip (gate-blind-to-feature). + static PRESET_COUNTS: std::cell::RefCell)>> = + const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Takes and clears [`PRESET_COUNTS`]. +#[allow(dead_code)] // read from the `#[cfg(test)]` BD gate +pub(crate) fn take_cdef_presets() -> Vec<(u8, Vec)> { + PRESET_COUNTS.with(|c| std::mem::take(&mut *c.borrow_mut())) +} + /// Squared error between a decoded plane and the source it was coded from, /// over the frame's own cropped `w x h` (the two planes have different /// strides: the source is the encoder's padded coding surface). @@ -55,6 +69,31 @@ fn plane_sse(dec: &[u16], dec_w: usize, src: &[u8], src_w: usize, w: usize, h: u sse } +/// [`plane_sse`], accumulated per CDEF unit instead of over the frame: `out` +/// is one entry per 64x64 SUPERBLOCK (stride `sb_cols`) and `unit` is the +/// unit side in this plane's own samples (64 for luma, 32 for 4:2:0 chroma), +/// which is what makes the luma and chroma sums land in the same slot. +fn unit_sse( + dec: &[u16], + dec_w: usize, + src: &[u8], + src_w: usize, + w: usize, + h: usize, + unit: usize, + sb_cols: usize, + out: &mut [u64], +) { + for row in 0..h { + let base = (row / unit) * sb_cols; + let (d, s) = (&dec[row * dec_w..][..w], &src[row * src_w..][..w]); + for (col, (&a, &b)) in d.iter().zip(s).enumerate() { + let diff = i64::from(a) - i64::from(b); + out[base + col / unit] += (diff * diff) as u64; + } + } +} + /// CDEF primary strengths tried (libaom's own range is 0..15 for 8-bit /// content) and the secondary ladder, whose only legal values are 0, 1, 2 /// and 4 -- 3 is not codeable (spec 5.9.19 codes a secondary strength of 4 @@ -82,6 +121,10 @@ struct Trial { picture: Picture, sse_y: u64, sse_uv: u64, + /// Luma + chroma error per 64x64 CDEF unit, in the tile writer's own + /// superblock raster order -- what the per-unit `cdef_idx` choice below + /// is made on. + sse64: Vec, } /// Picks this frame's deblocking levels and CDEF strengths and hands back @@ -111,8 +154,11 @@ pub(crate) fn pick_filters( src_w: usize, (fw, fh): (usize, usize), damping: u8, -) -> Result<(LoopFilterParams, CdefParams, Picture)> { + (sb_cols, sb_rows): (usize, usize), + lambda: f64, +) -> Result<(LoopFilterParams, CdefParams, Vec, Picture)> { let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); + let nsb = sb_cols * sb_rows; let mut trials: Vec = Vec::new(); let eval = |cand: Cand, trials: &mut Vec| -> Result { if let Some(i) = trials.iter().position(|t| t.cand == cand) { @@ -123,7 +169,11 @@ pub(crate) fn pick_filters( let sse_y = plane_sse(&picture.y, picture.width, source[0], src_w, fw, fh); let sse_uv = plane_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch) + plane_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch); - trials.push(Trial { cand, picture, sse_y, sse_uv }); + let mut sse64 = vec![0u64; nsb]; + unit_sse(&picture.y, picture.width, source[0], src_w, fw, fh, 64, sb_cols, &mut sse64); + unit_sse(&picture.u, dec_cw, source[1], src_w / 2, cw, ch, 32, sb_cols, &mut sse64); + unit_sse(&picture.v, dec_cw, source[2], src_w / 2, cw, ch, 32, sb_cols, &mut sse64); + trials.push(Trial { cand, picture, sse_y, sse_uv, sse64 }); Ok(trials.len() - 1) }; // One stage of the coordinate search: try `values` in the slot `set` @@ -168,11 +218,100 @@ pub(crate) fn pick_filters( stage(&mut best, &CDEF_SEC, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut trials)?; CHOSEN.with(|c| c.borrow_mut().push(best)); + + // libaom `av1_cdef_search`'s shape, on the candidates this coordinate + // search already decoded: every trial that ran under the WINNING + // deblocking levels is a legal strength pair for this frame, and each + // one already carries its own per-64x64 error. Pick up to eight of them + // as the header's strength list and give every superblock the one that + // costs it least -- the `cdef_idx` literal the tile writer then codes + // (`crate::tile::arm_cdef_idx`). + let mut presets: Vec = vec![best]; + let pool: Vec = trials + .iter() + .map(|t| t.cand) + .filter(|c| c.lf == best.lf && *c != best) + .collect(); + // How often each pool candidate would win a superblock outright, which + // is the order the list is grown in (libaom picks its presets by the + // same per-unit histogram, not by frame-level error). + let sse_of = |c: &Cand| -> &Vec { + &trials + .iter() + .find(|t| t.cand == *c) + .expect("every pool candidate was evaluated") + .sse64 + }; + let mut counts = vec![0usize; pool.len()]; + let best_sse = sse_of(&best).clone(); + for sb in 0..nsb { + let mut winner = (best_sse[sb], usize::MAX); + for (i, c) in pool.iter().enumerate() { + if sse_of(c)[sb] < winner.0 { + winner = (sse_of(c)[sb], i); + } + } + if winner.1 != usize::MAX { + counts[winner.1] += 1; + } + } + let mut order: Vec = (0..pool.len()).collect(); + order.sort_by_key(|&i| std::cmp::Reverse(counts[i])); + presets.extend(order.iter().take(7).map(|&i| pool[i])); + // The cheapest list length: `bits` costs one literal per superblock plus + // twelve header bits per extra pair, and buys whatever per-unit error the + // wider choice removes. + let unit_min = |n: usize, sb: usize| -> u64 { + presets[..n].iter().map(|c| sse_of(c)[sb]).min().unwrap_or(0) + }; + let mut bits = 0u8; + let mut cost = best_sse.iter().sum::() as f64; + for b in 1..=3u8 { + let n = 1usize << b; + if n > presets.len() { + break; + } + let sse: u64 = (0..nsb).map(|sb| unit_min(n, sb)).sum(); + let c = sse as f64 + lambda * ((b as usize * nsb) as f64 + 12.0 * (n - 1) as f64); + if c < cost { + cost = c; + bits = b; + } + } + let grid: Vec = if bits == 0 { + Vec::new() + } else { + let n = 1usize << bits; + (0..nsb) + .map(|sb| { + (0..n) + .min_by_key(|&i| sse_of(&presets[i])[sb]) + .expect("at least one preset") as u8 + }) + .collect() + }; + let mut params = cdef(best, damping); + params.bits = bits; + for (i, c) in presets.iter().take(1usize << bits).enumerate() { + params.y_pri_strength[i] = c.y.0; + params.y_sec_strength[i] = c.y.1; + params.uv_pri_strength[i] = c.uv.0; + params.uv_sec_strength[i] = c.uv.1; + } + let mut counts_used = vec![0usize; 1usize << bits]; + for &g in &grid { + counts_used[usize::from(g)] += 1; + } + if grid.is_empty() { + counts_used = vec![nsb]; + } + PRESET_COUNTS.with(|c| c.borrow_mut().push((bits, counts_used))); + let win = trials .into_iter() .find(|t| t.cand == best) .expect("the winning candidate was evaluated"); - Ok((loop_filter(best), cdef(best, damping), win.picture)) + Ok((loop_filter(best), params, grid, win.picture)) } /// The header's `loop_filter_params` for one candidate. diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 8a495fd0..0b222923 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -19,6 +19,78 @@ use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect}; use crate::msac::SymbolEncoder; use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16, single_ref_ctx}; +// --------------------------------------------------------------------------- +// lane-av1lr: per-64x64 `cdef_idx` (spec 5.11.56, `read_cdef`). The decoder +// reads ONE `cdef_idx` literal per 64x64 superblock, at that superblock's +// first non-skip block, and only when the frame header's `cdef_bits > 0` +// (`crate::decode::maybe_read_cdef_idx`). The writers below mirror that from +// a plan the filter search hands over, kept in a thread-local rather than +// threaded through every `write_*` signature -- the same shape the decoder's +// own `FrameCtx::cdef_transmitted` uses, and the encoder codes one tile at a +// time on one thread. The plan is CONSUMED by the tile writer that runs next +// ([`CdefIdxGuard`] clears it on every exit path, error included), so a frame +// that arms nothing writes no literals. + +/// One frame's per-superblock `cdef_idx` plan (see [`arm_cdef_idx`]). +struct CdefIdxPlan { + /// The header's `cdef_bits`; never 0 while armed. + bits: u8, + /// Superblocks per row, the stride of `grid`. + sb_cols: usize, + /// One index per 64x64 superblock, in raster order. + grid: Vec, + /// The superblock whose literal was already written -- the decoder's + /// `cdef_transmitted`, which resets at every superblock and which coding + /// order (each superblock's blocks are contiguous) makes a single slot. + last: Option, +} + +thread_local! { + static CDEF_IDX: std::cell::RefCell> = + const { std::cell::RefCell::new(None) }; +} + +/// Arms the next tile write with one `cdef_idx` per 64x64 superblock. +/// `bits == 0` disarms (the header codes a single strength pair, so the tile +/// carries no literal at all). +pub(crate) fn arm_cdef_idx(bits: u8, sb_cols: usize, grid: Vec) { + CDEF_IDX.with(|c| { + *c.borrow_mut() = (bits > 0).then(|| CdefIdxPlan { bits, sb_cols, grid, last: None }); + }); +} + +/// Clears the armed plan when the tile writer that consumed it returns. +struct CdefIdxGuard; + +impl Drop for CdefIdxGuard { + fn drop(&mut self) { + CDEF_IDX.with(|c| *c.borrow_mut() = None); + } +} + +/// `read_cdef`'s write side, called right after every block's `skip` symbol: +/// writes this superblock's `cdef_idx` literal the first time a non-skip +/// block of it is coded. `mi` is the block's own position in 4x4 mode-info +/// units. +fn write_cdef_idx(enc: &mut SymbolEncoder, mi: (usize, usize), skip: bool) { + if skip { + return; + } + CDEF_IDX.with(|c| { + let mut plan = c.borrow_mut(); + let Some(plan) = plan.as_mut() else { return }; + let sb = (mi.0 / 16) * plan.sb_cols + (mi.1 / 16); + if plan.last == Some(sb) { + return; + } + plan.last = Some(sb); + enc.literal( + u32::from(plan.grid.get(sb).copied().unwrap_or(0)), + u32::from(plan.bits), + ); + }); +} + /// round-4 av1-truesize debugging aid: prints `msg()` to stderr when the /// `EC_RNG` environment variable is set, mirroring the `EC_PART`/`EC_TOK` /// trace `/tmp/libaom-src`'s debug `aomdec` build already emits under the @@ -1040,6 +1112,8 @@ pub fn sb_coeff_key_frame_tile_tx( superblocks: &[Superblock], tx_select: bool, ) -> Result> { + // Consumes whatever `arm_cdef_idx` armed, on every exit path. + let _cdef_idx = CdefIdxGuard; check_blocks(mi_cols, mi_rows)?; let (cols, rows) = block_grid(mi_cols, mi_rows); let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); @@ -1490,9 +1564,13 @@ fn write_intra_mode( above_mode: usize, left_mode: usize, cfl: bool, + // This block's own position in 4x4 mode-info units, for the `cdef_idx` + // literal that follows the `skip` symbol (see [`write_cdef_idx`]). + mi: (usize, usize), ) -> usize { let mode = usize::from(block.mode); enc.symbol(0, &mut cdfs.skip[0]); + write_cdef_idx(enc, mi, false); enc.symbol( mode, &mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]], @@ -1540,6 +1618,7 @@ fn write_block( all_scans: &[Vec; 4], ) -> Result<()> { let (r, c) = at; + let at_mi = (r * (SUB / MI), c * (SUB / MI)); let mode = write_intra_mode( enc, cdfs, @@ -1547,8 +1626,8 @@ fn write_block( neighbours.above_mode[c], neighbours.left_mode[r], cfl, + at_mi, ); - let at_mi = (r * (SUB / MI), c * (SUB / MI)); let split = if tx_select { let tx = write_luma_select( enc, @@ -1622,7 +1701,7 @@ fn write_leaf8( // true first divergence (a differently-sized alphabet under the same // DC_PRED decision desyncs the coder even though the decoded mode is // unchanged). - let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true); + let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true, leaf_mi); let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4]; let split = if tx_select { let tx = write_luma_select( @@ -2685,6 +2764,8 @@ pub fn sb_coeff_inter_frame_tile_tx( blocks: &[Quadrant], tx_select: bool, ) -> Result> { + // Consumes whatever `arm_cdef_idx` armed, on every exit path. + let _cdef_idx = CdefIdxGuard; check_blocks(mi_cols, mi_rows)?; // `block_grid`'s ceiling, not a plain division: a true frame size that is // not a whole number of 32x32 blocks (or of 64x64 superblocks) still has @@ -3002,6 +3083,7 @@ pub fn sb_coeff_inter_frame_tile_tx( 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(&mut enc, (mi_r, mi_c), block.skip); let is_inter = block.inter.is_some(); let (above_inter, left_inter) = @@ -3237,6 +3319,7 @@ fn write_inter_frame_leaf( 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]); + write_cdef_idx(enc, (mi_r, mi_c), block.skip); let (has_above, has_left) = (r > 0, c > 0); let (above_inter, left_inter) = (neighbours.above_inter[mi_c], neighbours.left_inter[mi_r]); @@ -3458,6 +3541,7 @@ fn write_inter_frame_leaf8( 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]); + write_cdef_idx(enc, leaf_mi, block.skip); let (has_above, has_left) = (leaf_mi.0 > 0, leaf_mi.1 > 0); let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter, left_inter);