From 870ed18e458ed6d0912109a4ff1421d7206ab939 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 26 Aug 2026 02:38:20 +0300 Subject: [PATCH] feat(av1): the mode search prices its coefficients through the writer's CDFs The mode search costed the mode symbol exactly and the levels with a magnitude estimate. Now the levels go through write_coeffs on a throwaway encoder, so a trial is ranked by the bits the tile writer will really spend on it: end-of-block position, base levels, base range, signs and the Golomb tail, under the block's own contexts. The bit account prices the interval narrowing each symbol performs rather than its table entry, because the coder's eight-bit range multiply and its EC_MIN_PROB floor put the table entry 8% off the bytes actually written. Worth -1.19% BD-rate on a 1080p film frame and -0.20% on a screen capture against the estimate; LAMBDA_SCALE stays 0.1, re-swept. --- crates/ec-av1/src/encode.rs | 70 ++++++++++++++++++------ crates/ec-av1/src/msac.rs | 49 +++++++++++++++++ crates/ec-av1/src/tile.rs | 92 ++++++++++++++++++++++++++++++++ lanes/av1-coeffcost-r1.report.md | 86 +++++++++++++++++++++++++++++ 4 files changed, 282 insertions(+), 15 deletions(-) create mode 100644 lanes/av1-coeffcost-r1.report.md diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 6dc2b60e..92653b42 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -36,15 +36,27 @@ const BLOCK: usize = 32; /// How heavily the mode search weighs rate against squared error, in units of /// the quantizer's reconstruction step squared per bit. /// -/// Swept twice over three of his clips and three synthetic pictures -/// (`probe_lambda` and `probe_directional`, and the tables in the two lane -/// reports). The first sweep, before the mode symbol was costed, put the best -/// point at 0.05; costing it moved the point to 0.1, where the directional -/// modes stop costing rate on the pictures that do not want them (+0.05% on -/// screen capture against +0.19% at 0.05) without giving up any of what they -/// save on the pictures that do (-53.0% on a diagonal). +/// Swept three times over his clips and three synthetic pictures +/// (`probe_lambda`, `probe_directional` and `probe_ladder`, and the tables in +/// the three lane reports). The first sweep, before the mode symbol was +/// costed, put the best point at 0.05; costing it moved the point to 0.1. The +/// third sweep, after the levels were costed through the writer's own CDFs +/// too, left it there: against 0.2 the ladders are worth -1.19% against -0.98% +/// on film and -0.20% against -0.14% on screen capture. const LAMBDA_SCALE: f64 = 0.1; +/// [`LAMBDA_SCALE`], or whatever `EC_AV1_LAMBDA` names when the sweep that +/// picks it is the thing running. A release build has no such knob. +fn lambda_scale() -> f64 { + let swept = std::env::var("EC_AV1_LAMBDA") + .ok() + .and_then(|v| v.parse::().ok()); + match swept { + Some(scale) if cfg!(test) => scale, + _ => LAMBDA_SCALE, + } +} + /// One 8-bit planar 4:2:0 picture. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Picture { @@ -303,13 +315,25 @@ impl Plane<'_> { sse += error * error; } } - // What a level costs is close enough to its magnitude's width plus a - // sign and a run, which is all the search needs to rank modes. - let bits: f64 = levels - .iter() - .filter(|&&level| level != 0) - .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) - .sum(); + // What the levels cost is priced through the same CDFs the tile writer + // will code them with, so the search ranks modes by the bits they + // actually spend. Chroma blocks are not searched, so only the 32x32 + // luma table is asked for. + let bits = if side != BLOCK { + 0.0 + } else if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { + // What the search used before it could price a block exactly: a + // level costs its magnitude's width plus a sign and a run. Kept + // reachable from the sweep so the two rate terms can be compared + // on one build. + levels + .iter() + .filter(|&&level| level != 0) + .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) + .sum() + } else { + crate::tile::luma_32_coeff_bits(&levels) + }; Trial { levels, reconstruction, @@ -535,7 +559,7 @@ pub fn encode_key_frame_with_modes( let search = Search { base_q_idx, deadzone, - lambda: LAMBDA_SCALE * step * step, + lambda: lambda_scale() * step * step, modes, }; @@ -809,6 +833,22 @@ mod tests { } } + /// Prints the whole mode-search ladder, so two builds of the search can be + /// compared against each other rather than each against its own baseline. + #[test] + #[ignore = "a sweep, not a gate"] + fn probe_ladder() { + for (name, picture) in sweep_pictures() { + let all = ladder(&picture, &KEY_FRAME_MODES); + let points = all + .iter() + .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes))) + .collect::>() + .join(" "); + println!("ladder {name}: {points}"); + } + } + /// A striped picture, running one way or the other. The stripes are what /// separates a vertical predictor from a horizontal one: a mode search /// reading a transposed edge would pick the wrong one of the pair, which no diff --git a/crates/ec-av1/src/msac.rs b/crates/ec-av1/src/msac.rs index e02b2d27..81b4b35c 100644 --- a/crates/ec-av1/src/msac.rs +++ b/crates/ec-av1/src/msac.rs @@ -46,6 +46,11 @@ pub struct SymbolEncoder { /// Flushed bytes before carry propagation: each entry can exceed `0xff` by /// the carry it owes the byte before it, which [`Self::finish`] adds in. precarry: Vec, + /// What every symbol written so far cost against the CDF it was written + /// with, in bits. The arithmetic coder spends `-log2(p)` on a symbol of + /// probability `p` to within the rounding of its interval, so this is what + /// a search may price a decision with without coding it twice. + bits: f64, } impl Default for SymbolEncoder { @@ -63,9 +68,21 @@ impl SymbolEncoder { rng: 0x8000, cnt: -9, precarry: Vec::new(), + bits: 0.0, } } + /// What the symbols written so far cost, in bits. + pub fn bits(&self) -> f64 { + self.bits + } + + /// Forgets the cost accumulated so far, so that the next stretch of + /// symbols can be priced on its own. + pub fn reset_bits(&mut self) { + self.bits = 0.0; + } + /// Writes `symbol` against `cdf` and adapts `cdf` exactly as the decoder /// will after reading it (spec 8.3.2). /// @@ -107,6 +124,12 @@ impl SymbolEncoder { // Symbol 0 owns the top of the interval, so only its width moves. r - v }; + // What this symbol really cost is how far it narrowed the interval, + // which is not quite its nominal probability: the coder works the + // range through an eight-bit multiply and hands every symbol above + // this one a floor of `EC_MIN_PROB`. Pricing the narrowing rather than + // the table entry is what makes the account match the bytes. + self.bits -= (f64::from(rng) / f64::from(r)).log2(); self.normalize(low, rng); } @@ -431,6 +454,32 @@ pub(crate) mod tests { } } + /// The bit account is what a search prices decisions with, so it has to + /// agree with what the coder actually spends: over a long enough string the + /// two are within the coder's own rounding, a fraction of a percent. + #[test] + fn the_bit_account_matches_the_bytes_written() { + let mut enc = SymbolEncoder::new(); + let mut state: u32 = 0x1234_5678; + let mut next = || { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + state + }; + // A skewed CDF, so that the account has something to be wrong about: + // an equiprobable string costs one bit a symbol however it is priced. + let skewed: [u16; 3] = [29000, 1 << 15, 0]; + for _ in 0..20_000 { + let symbol = usize::from(next() % 100 < 12); + enc.symbol_fixed(symbol, &skewed); + } + let priced = enc.bits(); + let spent = (enc.finish().len() * 8) as f64; + assert!( + (priced - spent).abs() / spent < 0.01, + "priced {priced:.0} bits, spent {spent:.0}" + ); + } + #[test] fn empty_payload_is_short() { assert!(SymbolEncoder::new().finish().len() <= 2); diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index d83cb0d1..7d043e61 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -9,6 +9,8 @@ //! It is the skeleton the block modes, transform sizes and coefficients hang //! off as they arrive. +use std::sync::LazyLock; + use ec_core::{Error, Result}; use crate::cdf; @@ -857,6 +859,29 @@ fn default_scan(side: usize) -> Vec { scan } +/// What one 32x32 luma transform block's levels cost, in bits, priced through +/// the very CDFs [`write_coeffs`] will write them with -- end-of-block +/// position, base levels, base range, signs and the Golomb tail all included. +/// +/// The mode search calls this before the block's neighbours exist, so the two +/// neighbour-derived contexts (the block-skip context and the DC sign context) +/// are taken as zero. Every other context inside the block is exact, because +/// those are read from the block's own levels. +/// +/// The encoder codes 32x32 luma only -- every superblock it emits is split -- +/// 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. +pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 { + /// Built once: the search prices thirteen modes for every block, and the + /// scan is the same table every time. + static SCAN: LazyLock> = LazyLock::new(|| default_scan(TX32)); + let mut enc = SymbolEncoder::new(); + enc.reset_bits(); + write_coeffs(&mut enc, &LUMA_32, grid, &SCAN, 0, 0); + enc.bits() +} + /// coeffs() for one plane's transform block of any coefficients the base and /// base-range syntax reach (spec 5.11.39). /// @@ -1783,6 +1808,73 @@ mod tests { } } + /// The price the mode search pays for a block's levels has to be the price + /// the writer charges for them, or the search is ranking modes by a + /// fiction. Both halves are asked for the same grids under the same + /// neutral contexts, and the priced bits are compared against the bytes + /// the writer really spends. + #[test] + fn the_priced_coefficient_bits_match_the_bytes_written() { + let scan = default_scan(TX32); + // Three grids that reach different parts of the syntax: a lone DC, a + // sparse spread of small levels with both signs, and levels past the + // base-range alphabet so the Golomb tail runs. + let mut grids = vec![vec![0i32; TX32 * TX32]; 3]; + grids[0][0] = -7; + for (i, &pos) in scan.iter().enumerate().take(400) { + if i % 7 == 0 { + grids[1][pos as usize] = if i % 2 == 0 { 2 } else { -1 }; + } + } + grids[2][0] = 40; + for (i, &pos) in scan.iter().enumerate().take(64) { + grids[2][pos as usize] += i as i32 % 23 - 11; + } + + // A single block is too short for the coder's own flush to average + // out, so all three go through one encoder and one flush. + let mut enc = SymbolEncoder::new(); + let mut priced = 0.0; + for grid in &grids { + write_coeffs(&mut enc, &LUMA_32, grid, &scan, 0, 0); + priced += luma_32_coeff_bits(grid); + } + let spent = enc.finish().len() as f64 * 8.0; + assert!( + (priced - spent).abs() / spent < 0.02, + "priced {priced} bits, wrote {spent}" + ); + } + + /// A rate term the search can read as constant is a rate term that ranks + /// nothing, so the price is checked to move the way the levels move: an + /// empty block is the cheapest thing there is, one coefficient costs more + /// than none, and both spreading the coefficients and growing them costs + /// more again. + #[test] + fn the_price_grows_with_the_levels() { + let grid = |f: &dyn Fn(&mut Vec)| { + let mut g = vec![0i32; TX32 * TX32]; + f(&mut g); + luma_32_coeff_bits(&g) + }; + let empty = grid(&|_| {}); + let one = grid(&|g| g[0] = 1); + let bigger = grid(&|g| g[0] = 30); + let spread = grid(&|g| { + for i in 0..TX32 { + g[i * TX32 + i] = 1; + } + }); + assert!(empty < one, "{empty} {one}"); + assert!(one < bigger, "{one} {bigger}"); + assert!(one < spread, "{one} {spread}"); + // An empty block is one symbol -- an expensive one, because a block + // with no coefficients at all is the rarer of the two under the + // neutral context -- and nothing else. + assert!(empty < 6.0, "an empty block is one skip symbol, not {empty}"); + } + /// Neighbouring blocks that each carry coefficients read their DC sign /// context, their prediction and their own contexts off each other, so a /// frame whose four blocks all carry mixed-sign coefficients exercises what diff --git a/lanes/av1-coeffcost-r1.report.md b/lanes/av1-coeffcost-r1.report.md new file mode 100644 index 00000000..cf189d8e --- /dev/null +++ b/lanes/av1-coeffcost-r1.report.md @@ -0,0 +1,86 @@ +# lane-av1-coeffcost r1 — the mode search prices its coefficients exactly + +The directional lane closed with the mode half of the rate term costed through +the writer's own CDFs and the level half still an estimate +(`2 + 2*log2(|level|+1)` per non-zero coefficient). This lane replaces that +estimate: a trial's levels are now priced through the very syntax and the very +tables `write_coeffs` will code them with. + +## What landed + +- `crates/ec-av1/src/msac.rs`: `SymbolEncoder` keeps a bit account. + `symbol_fixed` prices *the interval narrowing it performs*, not the nominal + probability of the table entry — the coder works its range through an + eight-bit multiply and gives every symbol above the coded one a floor of + `EC_MIN_PROB`, so the table entry is 8% off the truth on real coefficient + data while the narrowing is exact. `bits()` and `reset_bits()` expose it. +- `crates/ec-av1/src/tile.rs`: `luma_32_coeff_bits()` — what one 32x32 luma + transform block's levels cost, run through `write_coeffs` on a throwaway + encoder: end-of-block group and offset, base levels, base range, DC sign, + raw signs and the Golomb tail. The two neighbour-derived contexts (block + skip, DC sign) are neutral because the search runs before the block's + neighbours exist; every context read from the block's own levels is exact. +- `crates/ec-av1/src/encode.rs`: `Trial::bits` calls it. Chroma is not + searched, so only the 32x32 luma table is asked for. +- `EC_AV1_LAMBDA` and `EC_AV1_ESTIMATE` sweep knobs, both `cfg!(test)`-only, + so the two rate terms and any weight can be compared on one build. + +## Gates + +| Gate | Result | +| --- | --- | +| `the_priced_coefficient_bits_match_the_bytes_written` | three grids (lone DC, sparse ±small spread, levels past the base-range alphabet) priced within 2% of the bytes one encoder really spends | +| `the_bit_account_matches_the_bytes_written` (msac) | 20 000 skewed symbols, within 1% | +| `the_price_grows_with_the_levels` | empty < one coefficient < a bigger one; empty < a spread of 32; an empty block costs one skip symbol | +| full `ec-av1` suite | 78 passed, 0 failed, 3 ignored | +| `cargo clippy --release -p ec-av1 --all-targets` | 0 warnings | + +## Mutation kills + +| Mutation | Killed by | +| --- | --- | +| the price counts non-zero coefficients at 4 bits each | `the_price_grows_with_the_levels`, `the_priced_coefficient_bits_match_the_bytes_written` | +| the price is zero | those two, plus `the_search_beats_dc_alone` and `the_search_picks_the_direction_the_picture_runs` | +| the account adds one bit per symbol instead of pricing the narrowing | `the_priced_coefficient_bits_match_the_bytes_written` | + +## What it is worth (`probe_ladder`, BD-rate against the merged estimate arm) + +Three-point ladder (base_q_idx 110/90/70), luma PSNR. Negative is better. + +| Picture | exact @ 0.1 | exact @ 0.2 | estimate @ 0.05 | +| --- | --- | --- | --- | +| ReelC, 1080p film frame @600s, 640x352 | **-1.19%** | -0.98% | -0.08% | +| OBS screen capture 2026-08-25 16-27-54 @5s, 640x352 | **-0.20%** | -0.14% | +0.21% | +| test card 160x96 | -2.09% | -2.10% | +0.16% | +| diagonal 160x96 | -3.93% | -3.93% | +0.06% | +| stripes 160x96 | +0.00% | +0.00% | +0.51% | + +`LAMBDA_SCALE` stays 0.1: it is the best point on both of his clips, and 0.2 +buys nothing on the synthetics. `probe_directional` at 0.1 with the exact term +reports the six directional modes worth -0.48% on the film frame and +0.06% on +screen capture against the seven non-directional ones (-53.0% → -54.90% on the +synthetic diagonal), with 43 of 220 and 14 of 220 blocks directional. + +Both clips are his own; no fixture-only claim in this table. + +## Dispositions + +- The block-skip and DC-sign contexts are neutral in the price while the writer + reads them from neighbours: **accepted**. They cost at most one symbol per + block and the search has no neighbour state to read at that point. +- Chroma trials are priced at zero bits: **accepted**. Chroma is coded DC-only + and is not searched, so no ranking depends on it. +- Only the 32x32 luma table is priced: **accepted** for as long as the encoder + emits split superblocks only. A whole-64x64 decision would need `LUMA_64`, + and the table and the scan have to agree, so it takes an entry point of its + own rather than a size argument. + +## Not in this lane + +- Block sizes below 32x32 and the partition decision (needs the luma-16 CDF + tables and `EOB_PT_256_LUMA`). +- Transform types beyond `DCT_DCT`, and transform-size selection. +- CDF adaptation: every symbol is still written against the pinned tables, so + the price is the price of a non-adaptive stream. +- Trellis or any rate-distortion optimisation of the levels themselves; this + lane prices the levels the quantizer already chose, it does not change them.