diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 346c5ad3..2c1c1c0f 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -14,7 +14,7 @@ use crate::cdf; /// Which of the four coefficient table sets a transform block is coded with. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Debug)] pub(crate) enum TxbSet { /// The 32x32 luma transform of an intra 32x32 block. `get_tx_set` is /// DCT-only at this size for an intra block, so no `tx_type` symbol is @@ -303,6 +303,10 @@ pub(crate) struct TxbTables<'a> { /// Every table a key frame's tile writer adapts. #[derive(Clone)] pub(crate) struct Cdfs { + /// The coefficient q-context these tables were built for (spec 8.3.2's + /// `Get_Qctx`), so a writer can price a block against the same tables the + /// search did (`tile::coeff_bits`). + pub q_ctx: usize, /// The partition symbol of a 64x64 superblock. /// `partition_cdf`'s `BLOCK_128X128` rows (8 symbols). pub partition_w128: [[u16; 9]; 4], @@ -968,6 +972,7 @@ impl Cdfs { /// quantizer, so they are the same for every `q_ctx`. pub fn new(q_ctx: usize) -> Cdfs { Cdfs { + q_ctx, partition_w128: cdf::PARTITION_W128, partition_w64: cdf::PARTITION_W64, partition_w32: cdf::PARTITION_W32, diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index b89b7799..58997555 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -3821,7 +3821,14 @@ fn code_square_inter( // compound block's residual is small enough that the four extra // per-unit txb_skip/eob symbols cost more ladder bytes than this // encoder's static-CDF estimate prices them at, so the local RD - // win does not convert. The flat trial stays. + // win does not convert. lane-av1txbits REBUILT it on top of a + // search that prices against the tables the frame is really + // written with (`tile::arm_pricing_cdfs`, the estimate error on + // these very blocks measured down from +31% to +3%) and measured + // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/ + // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the + // same build without it. The static-CDF estimate was NOT what + // held the compound var-tx trial back. The flat trial stays. let (levels, tx_depth, dcost) = if info.ref1.is_some() { luma.commit(x, y, side, &luma_new); (luma_new.levels.clone(), 0, 0.0) @@ -4535,6 +4542,10 @@ pub(crate) fn encode_key_frame_inner( (picture.height).min(render.1), ); arm_seq_screen(screen); + // A key frame's writer really does start from the defaults, and a search + // worker may be carrying an inter frame's armed tables (lane-av1txbits): + // disarm, or a key frame's bits would depend on which thread searched it. + crate::tile::arm_pricing_cdfs(None); // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit // forces deblocking, CDEF and loop restoration OFF for this frame // (frame.rs:194/210/252/272), so it is only set when the source repeats @@ -4674,6 +4685,7 @@ pub(crate) fn encode_key_frame_inner( let search_tile = |index: usize, fctx: &crate::decode::FrameCtx| -> Result)>> { + crate::tile::arm_pricing_cdfs(None); let rect = layout.rect(index); let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height); let mut chroma = [ @@ -4951,6 +4963,7 @@ pub(crate) fn encode_key_frame_inner( let mut cdfs = start_cdfs.0.clone(); crate::tile::arm_screen(screen); crate::tile::arm_intrabc(allow_intrabc); + crate::tile::arm_pricing_cdfs(None); let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs( mi_cols, mi_rows, @@ -6227,6 +6240,15 @@ fn search_inter_block( } let best = best.expect("the search offers at least the intra modes"); + // lane-av1txbits BUILT the transform-depth search this path lacks -- a + // 32x32 single-reference winner offered `commit_inter_luma`'s four 16x16 + // units against its flat trial, exactly as a 16x16 winner is -- and + // MEASURED it flat to slightly worse: +78.7/+95.1/+54.6 vs libaom and + // +36.1/+56.2/+1.8 vs rav1e, against the +78.8/+95.1/+54.5 and + // +36.1/+56.4/+1.4 this code scores, while the split fired on 40.2% of + // the film's inter blocks and 17.6% of the screen's. The same shape as + // the compound trial set below: a local RD win that does not convert into + // ladder bytes. The flat 32x32 transform stays. luma.commit(x, y, BLOCK, &best.luma); chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u); chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v); @@ -6381,6 +6403,9 @@ pub(crate) fn encode_inter_frame( // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob // never reached the tool). crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); + // The search prices coefficients against the tables this frame's writer + // starts from, not against the defaults (lane-av1txbits). + crate::tile::arm_pricing_cdfs(start_cdfs); if let Some(p) = pyramid { header.show_frame = p.show_frame; header.showable_frame = !p.show_frame; @@ -6501,6 +6526,7 @@ pub(crate) fn encode_inter_frame( // search step) is read by the SEARCH, so every worker arms it or the // tile's bits depend on the thread count. crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); + crate::tile::arm_pricing_cdfs(start_cdfs); let rect = layout.rect(index); let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height); let mut chroma = [ @@ -6971,6 +6997,7 @@ pub(crate) fn encode_inter_frame( crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints); crate::tile::arm_screen(screen); let mut cdfs = start_cdfs.0.clone(); + crate::tile::arm_pricing_cdfs(Some(&cdfs)); // Each tile's own MV grid: a candidate scan never reaches past // the tile's bounds, so a grid holding only this tile's own // blocks reads exactly as the decoder's frame-wide one does @@ -9459,6 +9486,10 @@ mod tests { // (compound share 8.8% -> 11.5%): a compound block carries a second // reference tree, a compound mode symbol and -- for the half-new modes // -- an MV residual, none of which the coefficient sum counts. + // lane-av1txbits: under `EC_AV1_PRICE_FRAME_CDFS=1` this reads +32.6% + // instead -- pricing against the tables the frame's writer really + // starts from collapses the over-price above to nothing, so the whole + // remaining gap is the syntax the coefficient sum leaves out. assert!( worst_under <= 0.32, "the writer spent {:.2}% more than the search priced -- more than \ @@ -9467,6 +9498,49 @@ mod tests { ); } + /// The census behind step (1) of the pricer lane: for every transform + /// block the writer really codes, what the search priced those levels at + /// against what the writer spent on them, split by table set and non-zero + /// count. One average hides the interesting part -- the classes the + /// estimate is systematically wrong about (all-zero blocks, the + /// one-coefficient blocks the inter search lives on) -- so the split is + /// printed and only the total is asserted on. + #[test] + fn pricer_error_census_by_block_class() { + 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(); + crate::tile::pricer_census_on(); + let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); + let rows = crate::tile::take_pricer_census(); + assert!(!rows.is_empty(), "the census saw no transform block"); + + println!("| set | nz | blocks | priced bits | written bits | error |"); + println!("|---|---|---|---|---|---|"); + let (mut priced_all, mut written_all) = (0.0, 0.0); + for ((set, bucket), (blocks, priced, written)) in &rows { + priced_all += priced; + written_all += written; + println!( + "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |", + crate::tile::census_bucket_label(*bucket), + if *written > 0.0 { + (priced - written) / written * 100.0 + } else { + 0.0 + } + ); + } + println!( + "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |", + rows.values().map(|r| r.0).sum::(), + (priced_all - written_all) / written_all * 100.0 + ); + assert!(written_all > 0.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 -- diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index ecf795b9..14cd3f78 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -10,6 +10,8 @@ //! off as they arrive. use std::cell::RefCell; +#[cfg(test)] +use std::collections::BTreeMap; use std::sync::LazyLock; use ec_core::{Error, Result}; @@ -3513,6 +3515,10 @@ fn write_block_planes( } else { usize::from(around[plane].above_coded) + usize::from(around[plane].left_coded) }; + #[cfg(test)] + let before = enc.tell(); + #[cfg(test)] + let q_ctx = cdfs.q_ctx; write_coeffs( enc, &mut cdfs.txb(planes[plane], mode), @@ -3522,6 +3528,8 @@ fn write_block_planes( dc_sign_ctx(around[plane].dc_vote), Some(plane), ); + #[cfg(test)] + census_record(planes[plane], q_ctx, grid, f64::from(enc.tell() - before)); ec_rng_trace(|| { format!( "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}", @@ -3602,6 +3610,10 @@ fn write_luma_tus( neighbours.luma_skip_ctx(tu_mi, tx / MI) }; let around = neighbours.around_mi(tu_mi, tx)[0]; + #[cfg(test)] + let before = enc.tell(); + #[cfg(test)] + let q_ctx = cdfs.q_ctx; write_coeffs( enc, &mut cdfs.txb(set, mode), @@ -3611,6 +3623,8 @@ fn write_luma_tus( dc_sign_ctx(around.dc_vote), Some(0), ); + #[cfg(test)] + census_record(set, q_ctx, &unit, f64::from(enc.tell() - before)); if n > 1 { neighbours.record_mi_luma(tu_mi, tx, &unit); } @@ -3970,13 +3984,14 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 { // q-context per thread beside a pristine one and restore just those from // it. The state the price is taken against is identical to a fresh // `Cdfs::new(q_ctx)`, so every price is bit-identical. - thread_local! { - static PRICING: RefCell<[Option>; 4]> = - const { RefCell::new([None, None, None, None]) }; - } - PRICING.with_borrow_mut(|slots| { - let slot = slots[q_ctx.min(3)] - .get_or_insert_with(|| Box::new((Cdfs::new(q_ctx), Cdfs::new(q_ctx)))); + // lane-av1txbits: an inter frame's writer does NOT start from the + // defaults -- it starts from the tables the previous frame stored (spec + // 7.20, `start_cdfs` in `encode_inter_frame`) -- so pricing against the + // defaults charged the search for a narrowing the writer no longer pays. + // The census measured that at +31% on the one-coefficient inter blocks + // the search lives on. `arm_pricing_cdfs` puts the frame's own starting + // tables under the price; nothing armed keeps the old default behaviour. + let price = |slot: &mut (Cdfs, Cdfs)| { let (pristine, scratch) = (&mut slot.0, &mut slot.1); let src = pristine.txb(set, DC_PRED); let mut coding = scratch.txb(set, DC_PRED); @@ -4002,9 +4017,118 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 { let mut enc = SymbolEncoder::pricer(); write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None); enc.bits() + }; + PRICING_BASE.with_borrow_mut(|base| { + if let Some(slot) = base.as_deref_mut().filter(|s| s.0.q_ctx == q_ctx) { + return price(slot); + } + PRICING.with_borrow_mut(|slots| { + let slot = slots[q_ctx.min(3)] + .get_or_insert_with(|| Box::new((Cdfs::new(q_ctx), Cdfs::new(q_ctx)))); + price(slot) + }) }) } +thread_local! { + /// The default tables every price falls back to, one pristine/scratch + /// pair per q-context (see [`coeff_bits`] for why the pair is kept). + static PRICING: RefCell<[Option>; 4]> = + const { RefCell::new([None, None, None, None]) }; + /// The tables the frame being searched will really be written against, + /// armed per frame by the encoder ([`arm_pricing_cdfs`]) on every thread + /// that prices -- the search jobs re-arm their own worker, exactly like + /// the other tile thread-locals. + static PRICING_BASE: RefCell>> = const { RefCell::new(None) }; +} + +/// Arms the tables [`coeff_bits`] prices against on this thread: the state +/// this frame's tile writer starts from. `None` goes back to the per-q-context +/// defaults (a key frame, whose writer really does start there). +/// +/// OFF by default (`EC_AV1_PRICE_FRAME_CDFS=1`). It is the more accurate +/// estimate by measurement -- the pricer census +/// (`pricer_error_census_by_block_class`) goes from +7.6% to +4.8% over every +/// transform block, and the one- and two-coefficient inter blocks the search +/// lives on from +31.4%/+22.3% to +3.1%/+3.6% -- but the accuracy does not +/// convert into ladder bytes on every clip: on the 640x384 gate it scores +/// +78.8/+95.1/+54.5 vs libaom and +36.1/+56.4/+1.4 vs rav1e against the +/// +79.9/+94.6/+54.5 and +37.3/+55.7/+1.1 the defaults score (film 1080p +/// down 1.1, film 2160p up 0.5, screen flat), and on the native crops +/// +18.0/+47.3/+60.7 and +0.7/+19.2/-7.3 against +18.9/+48.2/+59.3 and +/// +1.5/+19.8/-10.0 (both film clips down against both references, screen up +/// 1.4/2.7). Two clips better, one worse: it does not meet this lane's keep +/// rule, so it ships as a knob rather than as the default. +pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>) { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = *ON.get_or_init(|| std::env::var("EC_AV1_PRICE_FRAME_CDFS").as_deref() == Ok("1")); + PRICING_BASE.with_borrow_mut(|slot| { + *slot = base.filter(|_| on).map(|c| Box::new((c.clone(), c.clone()))); + }); +} + +/// The pricer census (`pricer_census_on`): for every transform block the tile +/// writer really codes, the bits it spent against the bits [`coeff_bits`] +/// prices those very levels at -- the search's rate term measured against the +/// rate it is meant to predict. Keyed by (table set, non-zero bucket) so a +/// class that is systematically mispriced (all-zero blocks' `txb_skip`, the +/// eob of a one-coefficient block, a whole size) shows up on its own row +/// rather than inside one average. +/// Thread-local, so a census cannot pick up the blocks of another test's +/// encode running beside it; a multi-tile, multi-threaded encode would +/// therefore only census the tiles this thread wrote, which is every tile of +/// the one-tile-one-thread encodes the gates print it from. +#[cfg(test)] +type CensusRows = BTreeMap<(String, usize), (u64, f64, f64)>; +#[cfg(test)] +thread_local! { + static CENSUS: RefCell> = const { RefCell::new(None) }; +} + +/// Starts a census on this thread, discarding anything a previous one left. +#[cfg(test)] +pub(crate) fn pricer_census_on() { + CENSUS.with_borrow_mut(|c| *c = Some(BTreeMap::new())); +} + +/// Stops the census and hands back its rows: (set, non-zero bucket) -> +/// (blocks, priced bits, written bits). +#[cfg(test)] +pub(crate) fn take_pricer_census() -> CensusRows { + CENSUS.with_borrow_mut(|c| c.take()).unwrap_or_default() +} + +/// The label of a non-zero bucket, for the tables the gates print. +#[cfg(test)] +pub(crate) fn census_bucket_label(bucket: usize) -> &'static str { + ["0", "1", "2", "3-4", "5-8", "9-16", "17+"][bucket] +} + +#[cfg(test)] +fn census_record(set: TxbSet, q_ctx: usize, grid: &[i32], written: f64) { + if CENSUS.with_borrow(|c| c.is_none()) { + return; + } + let nz = grid.iter().filter(|&&l| l != 0).count(); + let bucket = match nz { + 0 => 0, + 1 => 1, + 2 => 2, + 3..=4 => 3, + 5..=8 => 4, + 9..=16 => 5, + _ => 6, + }; + let priced = coeff_bits(grid, set, q_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(); + row.0 += 1; + row.1 += priced; + row.2 += written; + }); +} + /// What the partition symbol of a block of `side` samples costs, in bits, when /// it says the block is split (or that it is not). ///