From 40e1d9474ec08e1debeffee903eab8382e8a9d80 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 04:02:18 +0300 Subject: [PATCH] feat(av1): price the search at the frame's own coefficient q-context, and measure the rate term's drift coeff_bits built its CDFs at a pinned q-context 2, so two of the four points of the BD ladder ranked modes against another quantizer's tables; it now takes the frame's own q_ctx_of(base_q_idx), the same one the tile writer hands Cdfs::new. Adds the instrument the rate work needs: predicted_coeff_bits(_sb) sums what the search paid for the coefficients each kept block carries, and predicted_coeff_bits_track_the_tile_the_writer_wrote compares that sum with the bytes the writer emitted. Measured: -13.5% at the key frame falling to +1.8% by the fifth frame -- the search over-prices, because its CDFs stay at the tile defaults while the writer's adapt. --- crates/ec-av1/src/encode.rs | 77 ++++++++++++++++++++++++++++++-- crates/ec-av1/src/tile.rs | 88 ++++++++++++++++++++++++++++++++++--- 2 files changed, 157 insertions(+), 8 deletions(-) diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index a11bb17b..5059572f 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -89,6 +89,27 @@ fn lambda_scale() -> f64 { } } +// Every frame's predicted coefficient bits since the last +// `take_predicted_bits`, in coding order -- the encoder half of +// `predicted_coeff_bits_track_the_tile_the_writer_wrote`'s drift measurement. +#[cfg(test)] +thread_local! { + static PREDICTED_BITS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Records one frame's predicted coefficient bits. +#[cfg(test)] +fn record_predicted_bits(bits: f64) { + PREDICTED_BITS.with(|p| p.borrow_mut().push(bits)); +} + +/// Takes (and clears) what the frames encoded on this thread were predicted to +/// spend on coefficients. +#[cfg(test)] +pub(crate) fn take_predicted_bits() -> Vec { + PREDICTED_BITS.with(|p| std::mem::take(&mut *p.borrow_mut())) +} + /// Whether a 32x32 block may be split into four 16x16 ones when the trial says /// four cost less. Set from the measurement in the lane report. const SPLIT_BLOCKS: bool = true; @@ -719,7 +740,7 @@ 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::tile::coeff_bits(&levels, at.set, crate::decode::q_ctx_of(base_q_idx)) }; #[cfg(test)] stage_add(3, t.elapsed()); @@ -803,7 +824,7 @@ impl Plane<'_> { .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) .sum() } else { - crate::tile::coeff_bits(&levels, set) + crate::tile::coeff_bits(&levels, set, crate::decode::q_ctx_of(base_q_idx)) }; #[cfg(test)] stage_add(3, t.elapsed()); @@ -2364,6 +2385,8 @@ pub(crate) fn encode_key_frame_inner( } } + #[cfg(test)] + record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx)); let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &superblocks)?; let mut stream = temporal_delimiter(); stream.extend_from_slice(&sequence_header_obu(&seq)?); @@ -3308,6 +3331,8 @@ pub(crate) fn encode_inter_frame( .filter(|b| b.inter.is_some()) .count() as f64 / modes.len() as f64; + #[cfg(test)] + record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx)); let tile = sb_coeff_inter_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &blocks)?; let mut stream = temporal_delimiter(); stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); @@ -5168,6 +5193,52 @@ mod tests { } } + /// The rate term the mode search ranks every decision by has to be the + /// rate the writer then spends. The search prices a block's coefficients + /// through `tile::coeff_bits` -- the writer's own symbol chain, but + /// against the default CDFs a tile starts from and the contexts of a + /// block whose neighbours coded nothing -- while the tile writer codes + /// them against a state that has been adapting all frame (the + /// price-the-narrowing class). This measures that drift: the sum of what + /// the search paid for the coefficients it kept, against the bytes the + /// writer actually emitted for the whole tile (which also carries the + /// partition/mode/skip/mv syntax the sum leaves out, so the writer is + /// expected to be the larger of the two). + #[test] + fn predicted_coeff_bits_track_the_tile_the_writer_wrote() { + let fctx = &crate::decode::FrameCtx::new(); + let (width, height) = (256usize, 128usize); + let pictures: Vec = (0..5) + .map(|i| panned_test_card(width, height, i * 2)) + .collect(); + let _ = take_predicted_bits(); + let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); + let predicted = take_predicted_bits(); + assert_eq!(predicted.len(), encoded.frames.len()); + + eprintln!("frame predicted bits written bits drift"); + let mut worst: f64 = 0.0; + for (i, (frame, &bits)) in encoded.frames.iter().zip(&predicted).enumerate() { + let written = frame.tile.len() as f64 * 8.0; + let drift = (written - bits) / written; + worst = worst.max(drift.abs()); + eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0); + } + // Measured 2026-09-06 on this sequence: -13.5% at the key frame, + // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search + // over-prices every frame but the last (its sum EXCLUDES the + // partition/mode/skip/mv syntax the written side carries, so the true + // coefficient over-price is larger still): the writer's CDFs adapt to + // the content while the search's stay at the defaults. The bound is + // set just above the worst measured point -- a widening drift is the + // thing this gate exists to catch. + assert!( + worst <= 0.16, + "the search's rate term drifted {:.2}% from the bits the writer spent", + worst * 100.0 + ); + } + /// Low motion has to actually buy something: at least one inter frame of /// a panning sequence has to cost fewer bytes than the key frame that /// starts it, and the inter-block share it prints has to be non-zero -- @@ -5289,7 +5360,7 @@ mod tests { }; let t = Instant::now(); for _ in 0..N { - std::hint::black_box(crate::tile::coeff_bits(&levels, set)); + std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2)); } let entropy_t = t.elapsed() / N; diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index d79cef34..12b95be3 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -1557,18 +1557,96 @@ fn default_scan(side: usize) -> Vec { /// so one table is all the search needs; a second block size would need its /// own entry point rather than a size argument, because the table and the scan /// have to agree. +/// What the search paid for every coefficient of `blocks`, in bits: the same +/// [`coeff_bits`] price the mode search ranked those blocks by, summed over +/// the blocks that were actually kept. +/// +/// The instrument behind `predicted_coeff_bits_track_the_tile_the_writer_wrote` +/// (lane-av1rd1): the writer codes these levels against a state that has +/// adapted away from the defaults `coeff_bits` prices with, and against real +/// neighbour contexts instead of the empty ones, so the sum here and the tile +/// the writer produced differ by exactly that drift plus the non-coefficient +/// syntax (partition/mode/skip/mv symbols) the sum leaves out. +#[cfg(test)] +fn dense(coeffs: &[Coeff], side: usize) -> Vec { + let mut grid = vec![0i32; side * side]; + for c in coeffs { + grid[usize::from(c.row) * side + usize::from(c.col)] = c.level; + } + grid +} + +#[cfg(test)] +pub(crate) fn predicted_coeff_bits_sb(superblocks: &[Superblock], base_q_idx: u8) -> f64 { + let q_ctx = crate::decode::q_ctx_of(base_q_idx); + superblocks + .iter() + .map(|sb| match sb { + // A whole 64x64 codes its luma through `TxbSet::Luma64` (only the + // 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) + } + Superblock::Whole(_) => 0.0, + Superblock::Split(quadrants) => predicted_coeff_bits(quadrants, base_q_idx), + }) + .sum() +} + +#[cfg(test)] +pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 { + let q_ctx = crate::decode::q_ctx_of(base_q_idx); + fn block_bits(block: &BlockCoeffs, side: usize, q_ctx: usize) -> f64 { + if let Some(leaves) = &block.eight { + return leaves.iter().map(|l| block_bits(l, 8, q_ctx)).sum(); + } + if block.skip { + return 0.0; + } + let inter = block.inter.is_some(); + let (luma, chroma) = match (side, inter) { + (32, false) => (TxbSet::Luma32, TxbSet::Chroma16), + (32, true) => (TxbSet::Luma32Inter, TxbSet::Chroma16), + (16, false) => (TxbSet::Luma16, TxbSet::Chroma8), + (16, true) => (TxbSet::Luma16Inter, TxbSet::Chroma8), + (_, 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) + } + blocks + .iter() + .map(|q| { + let side = match q { + Quadrant::Whole(_) => 32, + Quadrant::Split(_) => 16, + }; + q.blocks().iter().map(|b| block_bits(b, side, q_ctx)).sum::() + }) + .sum() +} + #[cfg(test)] pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 { - coeff_bits(grid, TxbSet::Luma32) + coeff_bits(grid, TxbSet::Luma32, 2) } /// What one transform block's levels cost through the CDFs of `set`, in bits. /// /// The search runs before the tile is written, so the adapted state the block /// will really be coded against does not exist yet: the price is taken against -/// the defaults every tile starts from, and against the contexts a block whose -/// neighbours coded nothing reads. -pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet) -> f64 { +/// the defaults every tile starts from, at the frame's own coefficient +/// q-context (`q_ctx_of(base_q_idx)`, what `Cdfs::new` is given at +/// `sb_coeff_*_tile` -- lane-av1rd1: this used to be pinned at 2, so two of +/// the four points of the BD ladder were priced against another quantizer's +/// tables), and against the contexts a block whose neighbours coded nothing +/// reads. +pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_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(|| { @@ -1579,7 +1657,7 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet) -> f64 { default_scan(TX32), ] }); - let mut cdfs = Cdfs::new(2); + let mut cdfs = Cdfs::new(q_ctx); let mut coding = cdfs.txb(set, DC_PRED); let scan = match coding.side { TX4 => &SCANS[0],