From 9afbc09b9d3759ba5b96fe39f65c3273a0db5237 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 16:25:02 +0300 Subject: [PATCH] feat(av1): the RD pricer reads the real neighbour txb_skip/dc_sign contexts The search priced every transform block at txb_skip context 0 and dc_sign context 0 -- exact for a luma transform covering its whole block, and the largest remaining row of the pricer census everywhere else: an all-zero chroma block was under-priced 41-81%, a one-coefficient Chroma8 over-priced 32%. Each plane now carries a per-4x4-cell map of what the blocks committed before it left behind (cul_level and DC sign, tile.rs neighbour_state), written by Plane::commit and undone with the pixels by Plane::restore, so a partition trial reads the parent's committed neighbours for its first child and the just-committed sibling for the later ones -- coding order inside the tree. Plane::coef_ctx mirrors the writer's own derivation: chroma reads whether the above/left neighbours coded anything (write_block_planes), luma context 0 for a whole-block transform and decode.rs SKIP_CONTEXTS for a smaller unit (write_luma_tus / Neighbours::luma_skip_ctx), both planes the neighbours' DC sign vote (dc_sign_ctx). Census, 6 frames of each clip at 640x384 q=100, priced vs written: screen total +10.3% -> +9.5%, Chroma8 nz=0 -73.0% -> -1.9%, Chroma16 nz=0 -48% -> -23.4%, Chroma4 nz=0 -74% -> -6.7%, Chroma8 nz=1 +32.2% -> +4.9%, nz=2 +26.2% -> +7.9%, Luma4 nz=0 +464% -> +89.5% film total +5.3% -> +1.5% --- crates/ec-av1/src/cdf_state.rs | 20 +++ crates/ec-av1/src/encode.rs | 215 +++++++++++++++++++++++++++++++-- crates/ec-av1/src/tile.rs | 63 ++++++++-- 3 files changed, 275 insertions(+), 23 deletions(-) diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 2c1c1c0f..59a5603b 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -300,6 +300,26 @@ pub(crate) struct TxbTables<'a> { pub tx_type: Option<&'a mut [u16]>, } +impl TxbSet { + /// Whether this set codes a CHROMA plane's transform, which is what + /// picks the `txb_skip` context rule the writer uses: chroma reads + /// "did the above/left neighbour code anything" (`write_block_planes`), + /// luma reads context 0 for a transform covering its whole block and + /// `SKIP_CONTEXTS` for a smaller unit (`write_luma_tus`). + pub(crate) fn is_chroma(self) -> bool { + matches!( + self, + Self::Chroma4 + | Self::Chroma8 + | Self::Chroma16 + | Self::Chroma32 + | Self::ChromaRect8x4 + | Self::ChromaRect16x8 + | Self::ChromaRect32x16 + ) + } +} + /// Every table a key frame's tile writer adapts. #[derive(Clone)] pub(crate) struct Cdfs { diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index ced2d7d6..70412e2f 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1180,6 +1180,45 @@ fn too_large() -> Error { /// One plane of the picture being coded, and the reconstruction being built /// beside it. +/// What one committed 4x4 cell left behind for the coefficient contexts of +/// the blocks that read it as a neighbour -- tile.rs `neighbour_state`, which +/// is the same state decode.rs records. +#[derive(Clone, Copy, Default, PartialEq, Eq)] +struct CoefCtx { + /// spec `cul_level`: the sum of the unit's coded magnitudes, clamped to 7. + level: u8, + /// The DC sign this cell votes with: `-1` negative, `1` positive, `0` when + /// the DC itself was zero (tile.rs `dc_vote`). + dc: i8, +} + +/// One plane's coefficient contexts, committed in CODING ORDER: the search +/// prices partition TREES, so the neighbour state a candidate reads has to be +/// whatever the blocks coded before it left -- the parent's committed +/// neighbours for a tree's first child, the just-committed sibling for the +/// later ones. Keeping the map as a full per-4x4-cell grid rather than the +/// writer's two running bands is what makes that fall out: a trial commits +/// over its own rectangle ([`Plane::commit`]) and a losing trial is undone +/// with the pixels ([`Plane::restore`]), so what a candidate reads above and +/// to its left is exactly what the tile writer's `Neighbours` bands will hold +/// when it gets there. +/// +/// Before this map the pricer took both contexts as zero, which is exact for +/// a luma transform covering its whole block and the largest remaining row of +/// the pricer census everywhere else (all-zero chroma under-priced 41-81%). +#[derive(Default)] +struct CoefCtxMap { + cells: Vec, + stride: usize, + /// Whether the transforms being priced right now are SMALLER than the + /// block they sit in -- a `TxMode::Select` depth split + /// ([`Plane::code_tx_depth`]) or an inter var-tx split + /// ([`commit_inter_luma`]). That is the one thing the (x, y, side) of a + /// trial cannot tell, and it is what decides whether luma reads context 0 + /// or `SKIP_CONTEXTS` (tile.rs `write_luma_tus`). + tu_split: bool, +} + struct Plane<'a> { source: &'a [u8], reconstruction: Vec, @@ -1207,6 +1246,11 @@ struct Plane<'a> { tile_y0: usize, tile_x1: usize, tile_y1: usize, + /// [`CoefCtxMap`]: what the blocks already committed left for the + /// coefficient contexts of the ones still being priced. Sized on the + /// first commit, so a plane literal does not have to know its own extent + /// twice. + ctx: CoefCtxMap, } impl Plane<'_> { @@ -1402,7 +1446,16 @@ impl Plane<'_> { .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) .sum() } else { - crate::tile::coeff_bits(&levels, at.set, crate::decode::q_ctx_of(base_q_idx)) + { + let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set); + crate::tile::coeff_bits( + &levels, + at.set, + crate::decode::q_ctx_of(base_q_idx), + skip_ctx, + sign_ctx, + ) + } }; #[cfg(test)] stage_add(3, t.elapsed()); @@ -1471,7 +1524,16 @@ impl Plane<'_> { .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) .sum() } else { - crate::tile::coeff_bits(&levels, set, crate::decode::q_ctx_of(base_q_idx)) + { + let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set); + crate::tile::coeff_bits( + &levels, + set, + crate::decode::q_ctx_of(base_q_idx), + skip_ctx, + sign_ctx, + ) + } }; #[cfg(test)] stage_add(3, t.elapsed()); @@ -1509,6 +1571,9 @@ impl Plane<'_> { }; let mut levels = vec![0i32; side * side]; census_add(4, n * n); + // A unit smaller than its block reads the neighbour magnitude table + // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]). + self.ctx.tu_split = n > 1; let (mut sse, mut bits) = (0.0, 0.0); for tu_row in 0..n { for tu_col in 0..n { @@ -1530,15 +1595,100 @@ impl Plane<'_> { } } } + self.ctx.tu_split = false; (levels, sse, bits) } - /// Writes a trial's reconstruction back into the plane. + /// Writes a trial's reconstruction back into the plane, and the + /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]). fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) { for row in 0..side { self.reconstruction[(y + row) * self.width + x..][..side] .copy_from_slice(&trial.reconstruction[row * side..][..side]); } + self.commit_ctx(x, y, side, &trial.levels); + } + + /// Publishes one committed transform's own context over every 4x4 cell it + /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`, + /// which is what the writer will read when it reaches the next block. + fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) { + if self.ctx.cells.is_empty() { + self.ctx.stride = self.width.div_ceil(4); + self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)]; + } + let cul = levels.iter().map(|l| l.unsigned_abs()).sum::().min(7) as u8; + let state = CoefCtx { + level: cul, + dc: match levels[0].signum() { + 0 => 0, + -1 => -1, + _ => 1, + }, + }; + let n = (side / 4).max(1); + for row in 0..n { + let start = (y / 4 + row) * self.ctx.stride + x / 4; + let end = (start + n).min(self.ctx.cells.len()); + if start < end { + self.ctx.cells[start..end].fill(state); + } + } + } + + /// A block committed without any residual at all ([`ibc_commit`]): the + /// cells it covers coded nothing, and leaving an earlier trial's state + /// there would price its neighbours off a block that was never coded. + fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) { + self.commit_ctx(x, y, side, &[0i32]); + } + + /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this + /// plane reads, off what the blocks before it in coding order committed + /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether + /// the above/left neighbours coded anything (tile.rs + /// `write_block_planes`), luma reads context 0 when its transform covers + /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour + /// magnitude tiers when it does not (tile.rs `write_luma_tus` / + /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of + /// the same neighbours (tile.rs `dc_sign_ctx`). + /// + /// A neighbour outside this plane's own TILE does not exist, exactly as + /// the writer's per-tile `Neighbours` bands start blank. + fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) { + if self.ctx.cells.is_empty() { + return (0, 0); + } + let n = (side / 4).max(1); + let (cx, cy) = (x / 4, y / 4); + let (mut top, mut left) = (0u8, 0u8); + let mut vote = 0i32; + if y > self.tile_y0 && cy > 0 { + for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] { + top |= cell.level; + vote += i32::from(cell.dc); + } + } + if x > self.tile_x0 && cx > 0 { + for row in 0..n { + let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1]; + left |= cell.level; + vote += i32::from(cell.dc); + } + } + let skip_ctx = if set.is_chroma() { + usize::from(top != 0) + usize::from(left != 0) + } else if self.ctx.tu_split { + crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)] + } else { + 0 + }; + let sign_ctx = match vote.signum() { + 0 => 0, + -1 => 1, + _ => 2, + }; + (skip_ctx, sign_ctx) } /// The source samples of one square, contiguous — what a motion search @@ -1551,15 +1701,46 @@ impl Plane<'_> { /// The reconstructed samples of one square, so that a partition trial can /// be undone. - fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec { - rows_of(&self.reconstruction, self.width, x, y, side) + /// The reconstructed samples of one square AND the coefficient contexts + /// its cells hold, so that a partition trial can be undone whole: a + /// losing trial that left its own nz/DC state behind would price the + /// blocks after it off a block the tile writer never codes. + fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec, Vec) { + ( + rows_of(&self.reconstruction, self.width, x, y, side), + self.ctx_rows(x, y, side), + ) + } + + fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec { + if self.ctx.cells.is_empty() { + return Vec::new(); + } + let n = (side / 4).max(1); + (0..n) + .flat_map(|row| { + let start = (y / 4 + row) * self.ctx.stride + x / 4; + self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec() + }) + .collect() } /// Puts a snapshot back. - fn restore(&mut self, x: usize, y: usize, side: usize, samples: &[u8]) { + fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec, Vec)) { for row in 0..side { self.reconstruction[(y + row) * self.width + x..][..side] - .copy_from_slice(&samples[row * side..][..side]); + .copy_from_slice(&saved.0[row * side..][..side]); + } + if saved.1.is_empty() { + return; + } + let n = (side / 4).max(1); + for row in 0..n { + let start = (y / 4 + row) * self.ctx.stride + x / 4; + let end = (start + n).min(self.ctx.cells.len()); + if start < end { + self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]); + } } } @@ -2381,6 +2562,10 @@ fn commit_inter_luma( let mut levels = vec![0i32; side * side]; let (mut sse, mut bits) = (0.0, 0.0); let mut units = Vec::with_capacity(4); + // The split units are smaller than their block, so their `txb_skip` + // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and + // each unit's own commit publishes what the next one reads, coding order. + luma.ctx.tu_split = true; 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); @@ -2397,6 +2582,7 @@ fn commit_inter_luma( units.push((tu_x, tu_y, trial)); } } + luma.ctx.tu_split = false; 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 { @@ -2874,7 +3060,9 @@ fn ibc_commit( let copied: Vec = plane.reconstruction[from..from + half].to_vec(); plane.reconstruction[to..to + half].copy_from_slice(&copied); } + plane.commit_ctx_zero(x / 2, y / 2, half); } + luma.commit_ctx_zero(x, y, side); } /// Searches this block's own DV: every hash-table position whose 16x16 luma @@ -3972,7 +4160,7 @@ fn snapshot( chroma: &[Plane; 2], (x, y): (usize, usize), side: usize, -) -> [Vec; 3] { +) -> [(Vec, Vec); 3] { [ luma.snapshot(x, y, side), chroma[0].snapshot(x / 2, y / 2, side / 2), @@ -3986,7 +4174,7 @@ fn restore( chroma: &mut [Plane; 2], (x, y): (usize, usize), side: usize, - saved: &[Vec; 3], + saved: &[(Vec, Vec); 3], ) { luma.restore(x, y, side, &saved[0]); chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]); @@ -4333,6 +4521,7 @@ fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, tr tile_y0: 0, tile_x1: width, tile_y1: height, + ctx: CoefCtxMap::default(), } } @@ -4604,6 +4793,7 @@ pub(crate) fn encode_key_frame_inner( tile_y0: 0, tile_x1: picture.width, tile_y1: picture.height, + ctx: CoefCtxMap::default(), }; let mut chroma = [ Plane { @@ -4617,6 +4807,7 @@ pub(crate) fn encode_key_frame_inner( tile_y0: 0, tile_x1: picture.width / 2, tile_y1: picture.height / 2, + ctx: CoefCtxMap::default(), }, Plane { source: &picture_v8, @@ -4629,6 +4820,7 @@ pub(crate) fn encode_key_frame_inner( tile_y0: 0, tile_x1: picture.width / 2, tile_y1: picture.height / 2, + ctx: CoefCtxMap::default(), }, ]; @@ -6447,6 +6639,7 @@ pub(crate) fn encode_inter_frame( tile_y0: 0, tile_x1: picture.width, tile_y1: picture.height, + ctx: CoefCtxMap::default(), }; let mut chroma = [ Plane { @@ -6460,6 +6653,7 @@ pub(crate) fn encode_inter_frame( tile_y0: 0, tile_x1: picture.width / 2, tile_y1: picture.height / 2, + ctx: CoefCtxMap::default(), }, Plane { source: &picture_v8, @@ -6472,6 +6666,7 @@ pub(crate) fn encode_inter_frame( tile_y0: 0, tile_x1: picture.width / 2, tile_y1: picture.height / 2, + ctx: CoefCtxMap::default(), }, ]; @@ -9739,7 +9934,7 @@ mod tests { }; let t = Instant::now(); for _ in 0..N { - std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2)); + std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0)); } let entropy_t = t.elapsed() / N; diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 4716428e..f53b7d2a 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -3530,7 +3530,14 @@ fn write_block_planes( Some(plane), ); #[cfg(test)] - census_record(planes[plane], q_ctx, grid, f64::from(enc.tell() - before)); + census_record( + planes[plane], + q_ctx, + grid, + f64::from(enc.tell() - before), + skip_ctx, + dc_sign_ctx(around[plane].dc_vote), + ); ec_rng_trace(|| { format!( "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}", @@ -3625,7 +3632,14 @@ fn write_luma_tus( Some(0), ); #[cfg(test)] - census_record(set, q_ctx, &unit, f64::from(enc.tell() - before)); + census_record( + set, + q_ctx, + &unit, + f64::from(enc.tell() - before), + skip_ctx, + dc_sign_ctx(around.dc_vote), + ); if n > 1 { neighbours.record_mi_luma(tu_mi, tx, &unit); } @@ -3906,9 +3920,9 @@ pub(crate) fn predicted_coeff_bits_sb(superblocks: &[Superblock], base_q_idx: u8 // top-left 32x32 carries coefficients) and each chroma plane at // 32x32; `predicted_coeff_bits` has no 64 arm, so price it here. Superblock::Whole(block) if !block.skip => { - coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx) - + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx) - + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx) + coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx, 0, 0) + + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx, 0, 0) + + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx, 0, 0) } Superblock::Whole(_) => 0.0, Superblock::Split(quadrants) => predicted_coeff_bits(quadrants, base_q_idx), @@ -3935,9 +3949,9 @@ pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 { (_, false) => (TxbSet::Luma8, TxbSet::Chroma4), (_, true) => (TxbSet::Luma8Inter, TxbSet::Chroma4), }; - coeff_bits(&dense(&block.luma, side), luma, q_ctx) - + coeff_bits(&dense(&block.u, side / 2), chroma, q_ctx) - + coeff_bits(&dense(&block.v, side / 2), chroma, q_ctx) + coeff_bits(&dense(&block.luma, side), luma, q_ctx, 0, 0) + + coeff_bits(&dense(&block.u, side / 2), chroma, q_ctx, 0, 0) + + coeff_bits(&dense(&block.v, side / 2), chroma, q_ctx, 0, 0) } blocks .iter() @@ -3953,7 +3967,7 @@ pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 { #[cfg(test)] pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 { - coeff_bits(grid, TxbSet::Luma32, 2) + coeff_bits(grid, TxbSet::Luma32, 2, 0, 0) } /// What one transform block's levels cost through the CDFs of `set`, in bits. @@ -3981,7 +3995,19 @@ pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 { /// are not yet decided; the map would have to be built per trial, not per /// block. Deferred with the numbers above rather than approximated by a /// fitted constant. -pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 { +pub(crate) fn coeff_bits( + grid: &[i32], + set: TxbSet, + q_ctx: usize, + // lane-av1skipctx: the two neighbour-derived contexts, mirrored from the + // writer's own (`write_block_planes`/`write_luma_tus`) off the search's + // coding-order-committed map ([`crate::encode::CoefCtxMap`]). `(0, 0)` is + // what every caller passed before the map existed -- exact for a luma + // transform covering its whole block, and the census row that was the + // largest remaining pricer error for every other block. + skip_ctx: usize, + sign_ctx: usize, +) -> f64 { /// Built once per size: the search prices thirteen modes for every block, /// and the scan is the same table every time. static SCANS: LazyLock<[Vec; 4]> = LazyLock::new(|| { @@ -4031,7 +4057,7 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 { _ => &SCANS[3], }; let mut enc = SymbolEncoder::pricer(); - write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None); + write_coeffs(&mut enc, &mut coding, grid, scan, skip_ctx, sign_ctx, None); enc.bits() }; PRICING_BASE.with_borrow_mut(|base| { @@ -4182,7 +4208,18 @@ pub(crate) fn census_bucket_label(bucket: usize) -> &'static str { } #[cfg(test)] -fn census_record(set: TxbSet, q_ctx: usize, grid: &[i32], written: f64) { +fn census_record( + set: TxbSet, + q_ctx: usize, + grid: &[i32], + written: f64, + // The writer's own neighbour contexts for this very transform block: the + // census prices the search's estimate the way the search now takes it + // (lane-av1skipctx), so a row's error is the table/adaptation drift that + // is left once the context is right. + skip_ctx: usize, + sign_ctx: usize, +) { if CENSUS.with_borrow(|c| c.is_none()) { return; } @@ -4196,7 +4233,7 @@ fn census_record(set: TxbSet, q_ctx: usize, grid: &[i32], written: f64) { 9..=16 => 5, _ => 6, }; - let priced = coeff_bits(grid, set, q_ctx); + let priced = coeff_bits(grid, set, q_ctx, skip_ctx, sign_ctx); CENSUS.with_borrow_mut(|rows| { let rows = rows.as_mut().expect("the census is on"); let row = rows.entry((format!("{set:?}"), bucket)).or_default();