diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 1c6b027c..868f9f56 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -42,7 +42,8 @@ use crate::tile::{ }; use crate::transform::{ TxType, dequant_and_inverse_typed_wh, forward_and_quantize, - forward_and_quantize_typed, + forward_and_quantize_scaled, forward_and_quantize_typed, + forward_and_quantize_typed_scaled, }; /// The side of the larger of the two luma blocks this encoder codes, in @@ -428,6 +429,41 @@ pub fn take_b64_root_hits() -> usize { B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) } +/// Rate-distortion optimised quantisation ([`crate::tile::rdoq`], lane-rdoq). +/// Preset-gated: it re-prices the block once per candidate level, so it buys +/// bits with wall (see `crate::speed::RDOQ` for the per-preset table). +/// +/// `EC_AV1_RDOQ=0` in any build restores the plain deadzone quantiser -- +/// which is what the byte pins are taken under when they name it. +fn rdoq_on() -> bool { + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_RDOQ").ok().map(|v| v != "0") + }); + ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::RDOQ)) +} + +/// The rate weight [`crate::tile::rdoq`] trades bits for squared error at, in +/// units of one squared AC quantiser step -- the search's own +/// [`LAMBDA_SCALE`], so the quantiser and the mode search speak one currency. +/// +/// The per-frame factors the search multiplies onto it ([`key_lambda_factor`], +/// [`hidden_lambda_factor`], both 1.0 as shipped) and the per-superblock +/// temporal map ([`tpl_lambda_factors`]) are NOT threaded down here: +/// corner-cut, ceiling = a superblock the temporal map weighs away from the +/// frame average has its coefficients optimised at the frame's weight. The +/// upgrade is one `lambda` field on the trial call sites, which is the whole +/// mode-search argument list. +/// `EC_AV1_RDOQ_LAMBDA` multiplies it (the rate-term calibration sweep). +fn rdoq_lambda() -> f64 { + static MULT: std::sync::LazyLock = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_RDOQ_LAMBDA") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1.0) + }); + lambda_scale() * *MULT +} + /// [`B64_ROOT`], or what `EC_AV1_B64` names. fn b64_root() -> bool { static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { @@ -1836,8 +1872,26 @@ impl Plane<'_> { } #[cfg(test)] let t = stage_start(); - let levels = - forward_and_quantize_typed(residual, side, 8, i32::from(base_q_idx), deadzone, tx_type); + // lane-rdoq: the levels the writer takes are the RDOQ pass's, so the + // reconstruction below and the price further down are both of the + // grid this trial would really code. + let (levels, rdoq_bits) = if rdoq_on() { + let (mut levels, scaled) = forward_and_quantize_typed_scaled( + residual, side, 8, i32::from(base_q_idx), deadzone, tx_type, + ); + let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set); + let bits = crate::tile::rdoq( + &mut levels, &scaled, side, base_q_idx, at.set, skip_ctx, sign_ctx, rdoq_lambda(), + ); + (levels, Some(bits)) + } else { + ( + forward_and_quantize_typed( + residual, side, 8, i32::from(base_q_idx), deadzone, tx_type, + ), + None, + ) + }; // lane-av1speed2: 60% of the transform units of an inter stream carry // no coefficient at all, and the square entry point re-inflates that // case into `side * side` zeros (one allocate-and-memset per trial) @@ -1876,6 +1930,9 @@ impl Plane<'_> { .filter(|&&level| level != 0) .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) .sum() + } else if let Some(bits) = rdoq_bits { + // Already priced, against the grid the pass settled on. + bits } else { { let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set); @@ -1948,7 +2005,21 @@ impl Plane<'_> { } #[cfg(test)] let t = stage_start(); - let levels = forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone); + // lane-rdoq, as in [`Self::trial_typed`]. + let (levels, rdoq_bits) = if rdoq_on() { + let (mut levels, scaled) = + forward_and_quantize_scaled(residual, side, 8, i32::from(base_q_idx), deadzone); + let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set); + let bits = crate::tile::rdoq( + &mut levels, &scaled, side, base_q_idx, set, skip_ctx, sign_ctx, rdoq_lambda(), + ); + (levels, Some(bits)) + } else { + ( + forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone), + None, + ) + }; // The same all-zero shortcut [`Self::trial_typed`] takes. let coded = dequant_and_inverse_typed_wh( &levels, @@ -1990,6 +2061,8 @@ impl Plane<'_> { .filter(|&&level| level != 0) .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) .sum() + } else if let Some(bits) = rdoq_bits { + bits } else { { let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set); @@ -14812,6 +14885,27 @@ mod tests { // the real side, a screen clip none of them. let (price_default, price_real) = crate::tile::take_pricing_hits(); eprintln!("{name}: pricer armings default={price_default} real={price_real}"); + // lane-rdoq, under `EC_AV1_RDOQ_CENSUS=1` only (it costs a scan + // of every priced block): what the deadzone quantiser handed the + // RDOQ pass and what the pass changed, over every TRIAL block of + // this row's four encodes -- not over the coded stream, so it is + // the bits AT STAKE in the search, not in the bitstream. + let rq = crate::tile::take_rdoq_stats(); + if rq[0] > 0 { + eprintln!( + "{name}: rdoq blocks={} coeffs={} (+-1 {:.1}%, trailing +-1 {:.1}%) \ + zeroed={} lowered={} trial bits {:.0} -> {:.0} ({:+.2}%)", + rq[0], + rq[1], + 100.0 * rq[2] as f64 / rq[1].max(1) as f64, + 100.0 * rq[3] as f64 / rq[1].max(1) as f64, + rq[4], + rq[5], + rq[7] as f64 / 64.0, + rq[6] as f64 / 64.0, + 100.0 * (rq[6] as f64 - rq[7] as f64) / rq[7].max(1) as f64, + ); + } // lane-av1obmc2: the same motion_mode census the 640x384 gate // prints (class `gate-blind-to-feature`) -- how many blocks coded // the symbol at each footprint and how many took OBMC. Without it diff --git a/crates/ec-av1/src/speed.rs b/crates/ec-av1/src/speed.rs index e772520f..b3f81ef7 100644 --- a/crates/ec-av1/src/speed.rs +++ b/crates/ec-av1/src/speed.rs @@ -169,6 +169,13 @@ pub(crate) fn at(table: &[T; 11]) -> T { /// (screen). So it is on at every preset. pub(crate) const B64_ROOT: [bool; 11] = [crate::encode::B64_ROOT; 11]; +/// `encode::rdoq_on`: rate-distortion optimised quantisation +/// ([`crate::tile::rdoq`], lane-rdoq). Provisional table -- the wall/BD +/// measurement per preset is in `lanes/rdoq.report.md`. +pub(crate) const RDOQ: [bool; 11] = [ + true, true, true, false, false, false, false, false, false, false, false, +]; + /// `encode::SPLIT_RD_THRESHOLD`: how cheap a block has to be before its split /// trial is withheld. The single biggest wall lever in the tile search. pub(crate) const SPLIT_RD: [f64; 11] = [ diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 0bd17b4c..a6d99d05 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -13,7 +13,7 @@ use std::cell::RefCell; #[cfg(test)] use std::collections::BTreeMap; use std::sync::LazyLock; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use ec_core::{Error, Result}; @@ -4428,6 +4428,26 @@ pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 { /// blocks mostly code nothing narrows `txb_skip` far below where it started. /// A whole-block luma transform still reads context 0 -- that is what the /// writer codes (`write_luma_tus`, `n == 1`), not an approximation. +/// The default scan of one transform size, built once per size: the search +/// prices thirteen modes for every block, and the scan is the same table +/// every time. +fn scan_of(side: usize) -> &'static Vec { + static SCANS: LazyLock<[Vec; 4]> = LazyLock::new(|| { + [ + default_scan(TX4), + default_scan(TX8), + default_scan(TX16), + default_scan(TX32), + ] + }); + match side { + TX4 => &SCANS[0], + TX8 => &SCANS[1], + TX16 => &SCANS[2], + _ => &SCANS[3], + } +} + pub(crate) fn coeff_bits( grid: &[i32], set: TxbSet, @@ -4441,16 +4461,6 @@ pub(crate) fn coeff_bits( 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(|| { - [ - default_scan(TX4), - default_scan(TX8), - default_scan(TX16), - default_scan(TX32), - ] - }); // `Cdfs::new` builds every table a tile writer adapts -- tens of // kilobytes -- and this function is called once per priced candidate: // together with the copy behind it that was 9% of the encoder's profile @@ -4483,12 +4493,7 @@ pub(crate) fn coeff_bits( if let (Some(dst), Some(src)) = (coding.tx_type.as_mut(), src.tx_type) { dst.copy_from_slice(src); } - let scan = match coding.side { - TX4 => &SCANS[0], - TX8 => &SCANS[1], - TX16 => &SCANS[2], - _ => &SCANS[3], - }; + let scan = scan_of(coding.side); let mut enc = SymbolEncoder::pricer(); write_coeffs(&mut enc, &mut coding, grid, scan, skip_ctx, sign_ctx, None); enc.bits() @@ -4520,6 +4525,152 @@ pub(crate) fn coeff_bits( }) } +/// Rate-distortion optimised quantisation (lane-rdoq): the pass every +/// reference encoder runs after the quantiser and this one did not have. +/// +/// The deadzone quantiser rounds each coefficient on its own, blind to what +/// the coded level costs. Every reference decides that per coefficient +/// against the entropy coder (libaom `av1_optimize_txb`, rav1e +/// `optimize_txb`): a level is lowered toward zero when the bits it gives +/// back are worth more than the squared error it adds, which also shortens +/// the eob when the tail levels go to zero. +/// +/// Mirroring rav1e's shape without its incremental cost model: the candidate +/// set per coefficient is `{level, level - 1, .., 0}` walked one step at a +/// time in REVERSE scan order (the tail first, so a dropped tail is retried +/// against the shorter eob it leaves), and each candidate is priced by +/// re-coding the whole block through [`coeff_bits`] -- the same CDFs, the +/// same neighbour contexts and the same writer the search already prices +/// with, so no second cost model can drift from the writer (class +/// `table-and-reader-move-together`). That costs one `write_coeffs` per +/// candidate instead of rav1e's table lookup, which is why this is a preset +/// lever (`crate::speed::RDOQ`) and not unconditional. +/// +/// `levels` is the side-strided grid the inverse transform and the writer +/// will read, `scaled` the pre-rounding `coeff / q` of each position +/// (`crate::transform::forward_and_quantize_scaled`). `lambda` is the rate +/// weight in units of ONE SQUARED AC QUANTISER STEP: the search's own +/// `sse + lambda * bits` is `step^2 * (sum (scaled - level)^2 + LAMBDA_SCALE +/// * bits)` once the pixel-domain error of a level is written through the +/// orthonormal transform (`(coeff - level * q) / 8`, `INVERSE_GAIN_RECIPROCAL`), +/// so `step^2` divides out of every comparison here and the DC's different +/// quantiser is the only per-position weight left. +/// +/// Returns what the block's levels cost after the pass, so the caller prices +/// the tile it will actually write and never the pre-RDOQ grid. +#[allow(clippy::too_many_arguments)] +pub(crate) fn rdoq( + levels: &mut [i32], + scaled: &[f32], + side: usize, + base_q_idx: u8, + set: TxbSet, + skip_ctx: usize, + sign_ctx: usize, + lambda: f64, +) -> f64 { + // A 64-point transform carries its top-left 32x32 alone, and that corner + // is what the writer and the pricer take (`coded_corner`). + let coded = side.min(TX32); + let q_ctx = crate::decode::q_ctx_of(base_q_idx); + let mut dense = if coded == side { Vec::new() } else { vec![0i32; coded * coded] }; + fn price( + levels: &[i32], + dense: &mut [i32], + side: usize, + coded: usize, + set: TxbSet, + q_ctx: usize, + skip_ctx: usize, + sign_ctx: usize, + ) -> f64 { + if dense.is_empty() { + return coeff_bits(levels, set, q_ctx, skip_ctx, sign_ctx); + } + for row in 0..coded { + dense[row * coded..][..coded].copy_from_slice(&levels[row * side..][..coded]); + } + coeff_bits(dense, set, q_ctx, skip_ctx, sign_ctx) + } + let mut bits = price(levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx); + // The DC has its own quantiser, so its squared error per unit of level is + // `(dc_q / ac_q)^2` of an AC coefficient's. + let dc = f64::from(crate::quant::dc_q(8, i32::from(base_q_idx))); + let ac = f64::from(crate::quant::ac_q(8, i32::from(base_q_idx))); + let dc_weight = (dc / ac) * (dc / ac); + let census = crate::envflags::env_flag!("EC_AV1_RDOQ_CENSUS"); + if census { + census_block(levels, scaled, side, coded, bits); + } + for &position in scan_of(coded).iter().rev() { + let (row, col) = (usize::from(position) / coded, usize::from(position) % coded); + let i = row * side + col; + if levels[i] == 0 { + continue; + } + let s = f64::from(scaled[i]); + let weight = if i == 0 { dc_weight } else { 1.0 }; + loop { + let level = levels[i]; + let candidate = level - level.signum(); + levels[i] = candidate; + let after = price(levels, &mut dense, side, coded, set, q_ctx, skip_ctx, sign_ctx); + let distortion = weight + * ((s - f64::from(candidate)).powi(2) - (s - f64::from(level)).powi(2)); + if distortion + lambda * (after - bits) < 0.0 { + bits = after; + if census { + RDOQ_STATS[if candidate == 0 { 4 } else { 5 }].fetch_add(1, Ordering::Relaxed); + } + if candidate == 0 { + break; + } + } else { + levels[i] = level; + break; + } + } + } + if census { + RDOQ_STATS[6].fetch_add((bits * 64.0) as u64, Ordering::Relaxed); + } + bits +} + +/// blocks, coded coefficients, +-1 levels, trailing +-1 levels (a run of them +/// at the end of the scan), zeroed coefficients, lowered coefficients, bits +/// after the pass * 64, bits before the pass * 64. +pub(crate) static RDOQ_STATS: [AtomicU64; 8] = [ + AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), + AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0), +]; + +/// The pre-pass half of [`RDOQ_STATS`] (`EC_AV1_RDOQ_CENSUS`): what the +/// quantiser handed the pass, which is the instrument for how much is at +/// stake before any decision is taken. +fn census_block(levels: &[i32], _scaled: &[f32], side: usize, coded: usize, bits: f64) { + let scan = scan_of(coded); + let at = |p: u16| levels[usize::from(p) / coded * side + usize::from(p) % coded]; + let nonzero = scan.iter().filter(|&&p| at(p) != 0).count(); + let ones = scan.iter().filter(|&&p| at(p).abs() == 1).count(); + let trailing = scan + .iter() + .rev() + .skip_while(|&&p| at(p) == 0) + .take_while(|&&p| at(p).abs() == 1) + .count(); + RDOQ_STATS[0].fetch_add(1, Ordering::Relaxed); + RDOQ_STATS[1].fetch_add(nonzero as u64, Ordering::Relaxed); + RDOQ_STATS[2].fetch_add(ones as u64, Ordering::Relaxed); + RDOQ_STATS[3].fetch_add(trailing as u64, Ordering::Relaxed); + RDOQ_STATS[7].fetch_add((bits * 64.0) as u64, Ordering::Relaxed); +} + +/// Reads and clears [`RDOQ_STATS`]. +pub fn take_rdoq_stats() -> [u64; 8] { + std::array::from_fn(|i| RDOQ_STATS[i].swap(0, Ordering::Relaxed)) +} + 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). diff --git a/crates/ec-av1/src/transform.rs b/crates/ec-av1/src/transform.rs index 643e59e3..e6c056bf 100644 --- a/crates/ec-av1/src/transform.rs +++ b/crates/ec-av1/src/transform.rs @@ -1554,6 +1554,35 @@ pub fn forward_and_quantize_typed( quantize(&coeffs, side, bit_depth, q_idx, deadzone) } +/// [`forward_and_quantize_typed`] that also hands back each coded position's +/// pre-rounding scaled coefficient (`coeff / q`, the exact real-valued level +/// the quantiser rounded). The RDOQ pass ([`crate::tile::rdoq`]) prices +/// `level - 1` against `level` and needs the distance to both, which the +/// levels alone no longer carry. +pub fn forward_and_quantize_typed_scaled( + residual: &[i32], + side: usize, + bit_depth: u8, + q_idx: i32, + deadzone: f64, + tx_type: TxType, +) -> (Vec, Vec) { + let coeffs = forward_transform_2d_typed(residual, side, tx_type); + let dc = f64::from(crate::quant::dc_q(bit_depth, q_idx)); + let ac = f64::from(crate::quant::ac_q(bit_depth, q_idx)); + let mut scaled = vec![0f32; side * side]; + let coded = side.min(32); + for row in 0..coded { + for col in 0..coded { + let i = row * side + col; + scaled[i] = (coeffs[i] / if i == 0 { dc } else { ac }) as f32; + } + } + // Same levels as the plain entry point: this is the same division the + // quantiser does, and the levels come from the quantiser itself. + (quantize(&coeffs, side, bit_depth, q_idx, deadzone), scaled) +} + /// How much the decoder's inverse transform shrinks an orthonormal DCT. /// /// Measured, not asserted: feeding a single dequantized coefficient through @@ -1997,6 +2026,34 @@ pub fn forward_and_quantize( bit_depth: u8, q_idx: i32, deadzone: f64, +) -> Vec { + forward_and_quantize_into(residual, side, bit_depth, q_idx, deadzone, None) +} + +/// [`forward_and_quantize`] plus the pre-rounding scaled coefficients, for the +/// same reason [`forward_and_quantize_typed_scaled`] exists. The levels are +/// bit-identical: it is the one loop below, with the value it rounds also +/// written out. +pub fn forward_and_quantize_scaled( + residual: &[i32], + side: usize, + bit_depth: u8, + q_idx: i32, + deadzone: f64, +) -> (Vec, Vec) { + let mut scaled = vec![0f32; side * side]; + let levels = + forward_and_quantize_into(residual, side, bit_depth, q_idx, deadzone, Some(&mut scaled)); + (levels, scaled) +} + +fn forward_and_quantize_into( + residual: &[i32], + side: usize, + bit_depth: u8, + q_idx: i32, + deadzone: f64, + mut scaled_out: Option<&mut [f32]>, ) -> Vec { // 72% of this encoder's forward DCTs are of an all-zero residual // (measured over the BD gate's own ladder, lane-av1fwd): every row and @@ -2023,6 +2080,9 @@ pub fn forward_and_quantize( } for u in 0..coded { let scaled = f64::from(t[u]) * if u == 0 && v == 0 { dc } else { ac }; + if let Some(out) = scaled_out.as_deref_mut() { + out[u * side + v] = scaled as f32; + } let magnitude = scaled.abs() + deadzone; let level = if magnitude < 1.0 { 0 diff --git a/lanes/rdoq-arm.sh b/lanes/rdoq-arm.sh new file mode 100755 index 00000000..c5d2beeb --- /dev/null +++ b/lanes/rdoq-arm.sh @@ -0,0 +1,7 @@ +#!/bin/bash +# lane-rdoq: one native-gate arm (all five rows) under a named env set. +# usage: rdoq-arm.sh +name=$1; shift +B=$HOME/.cache/cargo-target-rdoq/release/deps/ec_av1-8fef0196ab10338d +systemd-run --user --unit rq-$name -p MemoryMax=8G --collect --working-directory=$PWD \ + bash -c "env EC_AV1_NATIVE_FILM=1 EC_AV1_NATIVE_FILM4K=1 EC_AV1_NATIVE_SCREEN=1 $* $B --ignored --nocapture --test-threads 1 bd_rate_screen_native > lanes/rdoq-$name.log 2>&1; echo RC=\$? >> lanes/rdoq-$name.log" diff --git a/lanes/rdoq-ctl.log b/lanes/rdoq-ctl.log new file mode 100644 index 00000000..5d647e9f --- /dev/null +++ b/lanes/rdoq-ctl.log @@ -0,0 +1,6 @@ + +running 1 test +test encode::tests::bd_rate_screen_native ... +native crop, 12 frames, gop=12; tiles (0, 0), tile threads 1, intrabc false, palette maxcolors 128 +| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) | +|---|---|---|---|---| diff --git a/lanes/rdoq-r1.log b/lanes/rdoq-r1.log new file mode 100644 index 00000000..5d647e9f --- /dev/null +++ b/lanes/rdoq-r1.log @@ -0,0 +1,6 @@ + +running 1 test +test encode::tests::bd_rate_screen_native ... +native crop, 12 frames, gop=12; tiles (0, 0), tile threads 1, intrabc false, palette maxcolors 128 +| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) | +|---|---|---|---|---|