diff --git a/crates/ec-av1/examples/enc_probe.rs b/crates/ec-av1/examples/enc_probe.rs index 6f44fc6b..637f3106 100644 --- a/crates/ec-av1/examples/enc_probe.rs +++ b/crates/ec-av1/examples/enc_probe.rs @@ -51,6 +51,21 @@ fn main() { h = (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3); } println!("q={q} bytes={} fnv1a={h:016x}", e.stream.len()); + if ec_av1::encode::census_on() { + let (kinds, luma_rank, chroma_rank) = ec_av1::encode::take_census(); + for (name, n) in ec_av1::encode::CENSUS_KINDS.iter().zip(kinds) { + println!(" census {name}: {n}"); + } + let pct = |h: &[usize]| { + let total: usize = h.iter().sum::().max(1); + h.iter() + .map(|n| format!("{:.1}%", 100.0 * *n as f64 / total as f64)) + .collect::>() + .join(" ") + }; + println!(" census luma SAD rank of RD winner: {}", pct(&luma_rank)); + println!(" census chroma SAD rank of RD winner: {}", pct(&chroma_rank)); + } } println!("wall {:.3}s", start.elapsed().as_secs_f64()); } diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 0621a971..de727b4d 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -244,6 +244,45 @@ fn restoration_enabled() -> bool { /// future explicit speed preset. const SPLIT_BREAKOUT_COEFFS: usize = 0; +/// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own +/// currency: a 32x32 inter block whose whole-block RD cost per pixel comes +/// out under `threshold * lambda` is not offered the split at all, and a +/// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both +/// always, as before this lever. +/// +/// The census is what points here: the split trial runs on nearly every +/// non-skip block (15132 leaf searches per ladder point on the 1080p clip) +/// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient +/// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD +/// points, so the gate has to read the block's own RD cost, not its levels. +/// +/// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of +/// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for +/// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and +/// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs +/// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships -- +/// the largest threshold whose BD stays inside the +0.3 keep rule on every +/// clip. +const SPLIT_RD_THRESHOLD: f64 = 0.125; + +/// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build. +fn split_rd_threshold() -> f64 { + static T: std::sync::OnceLock = std::sync::OnceLock::new(); + *T.get_or_init(|| { + std::env::var("EC_AV1_SPLIT_RD") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(SPLIT_RD_THRESHOLD) + }) +} + +/// Whether `cost` over a `side` x `side` block is cheap enough per pixel that +/// [`split_rd_threshold`] withholds the split trial. +fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool { + let t = split_rd_threshold(); + t > 0.0 && cost < t * lambda * (side * side) as f64 +} + /// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test /// build. fn split_breakout_coeffs() -> usize { @@ -276,6 +315,76 @@ pub(crate) fn take_partition_hits() -> [usize; 4] { [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) } +/// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full +/// rate-distortion trials the block search actually runs, by kind, and where +/// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by +/// default, and a measurement build rather than a speed one -- the census +/// runs the SAD pre-pass the unpruned search otherwise skips. +pub fn census_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1"))) +} + +/// What each [`CENSUS`] counter counts. +pub const CENSUS_KINDS: [&str; 11] = [ + "intra blocks searched (key frame + inter leaves)", + "intra luma mode trials", + "chroma searches", + "chroma mode trials (each = 2 plane trials)", + "tx-depth trials (transform units, depth >= 1)", + "inter 32x32 blocks searched", + "inter block intra-mode trials", + "inter mv candidates (each = 3 mc trials)", + "inter leaves searched (intra vs NEARESTMV/NEWMV)", + " of those, intra won", + " of those, the NEARESTMV trial coded no residual", +]; + +/// The census counters themselves, indexed by [`CENSUS_KINDS`]. +static CENSUS: [std::sync::atomic::AtomicUsize; 11] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 11]; + +/// Where the RD winner sat in the SAD ranking, for the luma intra search and +/// the chroma mode search -- what says whether a top-N prune would have kept +/// the block the search actually chose. +static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 13]; +static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 7]; + +fn census_add(kind: usize, n: usize) { + if census_on() { + CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Reads (and clears) the census, so a driver can attribute it to its own encode. +pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) { + let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed); + ( + std::array::from_fn(|i| take(&CENSUS[i])), + std::array::from_fn(|i| take(&LUMA_RANK[i])), + std::array::from_fn(|i| take(&CHROMA_RANK[i])), + ) +} + +/// The rank of `winner` in `scored` ordered by its cheap score, cheapest +/// first -- the census's one shared rule, so the luma and chroma histograms +/// mean the same thing. +fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize { + scored + .iter() + .filter(|&&(score, mode)| { + mode != winner + && score + < scored + .iter() + .find(|&&(_, m)| m == winner) + .map_or(f64::INFINITY, |&(s, _)| s) + }) + .count() +} + /// 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; @@ -983,7 +1092,11 @@ impl Plane<'_> { x, y, side, reach, .. } = at; let (above, left, corner) = self.edges(x, y, side, reach); - let mut prediction = vec![0u8; side * side]; + // Per-candidate scratch on the search's hottest path, so both buffers + // live on the stack -- `side` is at most `BLOCK` -- rather than + // costing a malloc/free pair per trial (`mc_trial` already does this). + let mut prediction = [0u8; BLOCK * BLOCK]; + let prediction = &mut prediction[..side * side]; intra_predict_u8( mode, 0, @@ -994,10 +1107,11 @@ impl Plane<'_> { side, false, false, - &mut prediction, fctx, + prediction, fctx, ); - let mut residual = vec![0i32; side * side]; + let mut residual = [0i32; BLOCK * BLOCK]; + let residual = &mut residual[..side * side]; for row in 0..side { for col in 0..side { residual[row * side + col] = @@ -1008,7 +1122,7 @@ impl Plane<'_> { #[cfg(test)] let t = std::time::Instant::now(); let levels = - forward_and_quantize_typed(&residual, side, 8, i32::from(base_q_idx), deadzone, tx_type); + forward_and_quantize_typed(residual, side, 8, i32::from(base_q_idx), deadzone, tx_type); let coded = dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), 0, 0, tx_type); #[cfg(test)] @@ -1091,7 +1205,8 @@ impl Plane<'_> { bits: 0.0, }; } - let mut residual = vec![0i32; side * side]; + let mut residual = [0i32; BLOCK * BLOCK]; + let residual = &mut residual[..side * side]; for row in 0..side { for col in 0..side { residual[row * side + col] = @@ -1101,7 +1216,7 @@ impl Plane<'_> { } #[cfg(test)] let t = std::time::Instant::now(); - let levels = forward_and_quantize(&residual, side, 8, i32::from(base_q_idx), deadzone); + let levels = forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone); let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx)); #[cfg(test)] stage_add(2, t.elapsed()); @@ -1164,6 +1279,7 @@ impl Plane<'_> { _ => TxbSet::Luma4, }; let mut levels = vec![0i32; side * side]; + census_add(4, n * n); let (mut sse, mut bits) = (0.0, 0.0); for tu_row in 0..n { for tu_col in 0..n { @@ -1288,6 +1404,11 @@ impl Plane<'_> { x, y, side, reach, .. } = at; let (above, left, corner) = self.edges(x, y, side, reach); + // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or + // the census reports it), so summing it under the default unpruned + // search is `side * side` absolute differences per mode spent on a + // number no one reads. + let want_sad = search.top_k.is_some() || census_on(); let mut scored: Vec<(f64, u8, Vec)> = search .modes .iter() @@ -1305,16 +1426,20 @@ impl Plane<'_> { false, &mut prediction, fctx, ); - let sad: f64 = (0..side * side) - .map(|i| { - let (row, col) = (i / side, i % side); - f64::from( - (i32::from(self.source[(y + row) * self.width + x + col]) - - i32::from(prediction[i])) - .abs(), - ) - }) - .sum(); + let sad: f64 = if want_sad { + (0..side * side) + .map(|i| { + let (row, col) = (i / side, i % side); + f64::from( + (i32::from(self.source[(y + row) * self.width + x + col]) + - i32::from(prediction[i])) + .abs(), + ) + }) + .sum() + } else { + 0.0 + }; ( sad + search.lambda * mode_bits[usize::from(mode)], mode, @@ -1337,6 +1462,13 @@ impl Plane<'_> { } } } + let ranking: Vec<(f64, u8)> = if census_on() { + scored.iter().map(|&(score, mode, _)| (score, mode)).collect() + } else { + Vec::new() + }; + census_add(0, 1); + census_add(1, scored.len()); let mut best: Option<(f64, u8, Trial)> = None; for (_, mode, prediction) in scored { let trial = self.code_from_prediction( @@ -1358,6 +1490,10 @@ impl Plane<'_> { } } let (cost, mode, trial) = best.expect("the search offers at least one mode"); + if census_on() { + LUMA_RANK[sad_rank(&ranking, mode).min(12)] + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } self.commit(x, y, side, &trial); (coeffs(&trial.levels, side), mode, cost) } @@ -2195,6 +2331,34 @@ pub(crate) fn take_uv_mode_hits() -> [usize; 13] { /// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the /// writer then has to code. #[allow(clippy::too_many_arguments)] +/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on, +/// ranked by the SAD of their predictions summed over both planes (`DC_PRED` +/// always kept, the same rule [`prune_by_sad`] applies to luma). `None` +/// trials all seven, as before this lever. +/// +/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was +/// the search's largest trial population by far -- seven modes times two +/// planes for every intra block, against 3.7 luma trials -- and the RD +/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three +/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build. +fn chroma_top_k() -> Option { + static K: std::sync::OnceLock> = std::sync::OnceLock::new(); + *K.get_or_init(|| match std::env::var("EC_AV1_CHROMA_K").ok() { + Some(v) => v.parse::().ok().filter(|&k| k > 0), + None => CHROMA_TOP_K, + }) +} + +/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD +/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3): +/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/ +/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better) +/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The +/// BD swings by about a point in either direction as near-tie chroma modes +/// flip, which is the measurement's own sensitivity, not a trend: nothing +/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned. +const CHROMA_TOP_K: Option = None; + fn search_chroma( chroma: &mut [Plane; 2], (x, y): (usize, usize), @@ -2211,10 +2375,34 @@ fn search_chroma( reach: Reach::none(), set, }; + // The census's cheap proxy for a chroma mode: the SAD of its prediction + // summed over both planes, ranked by the same rule the luma histogram + // uses. Only built under `EC_AV1_CENSUS`. + // The SAD of each mode's prediction, summed over both planes -- the + // census's ranking rule, and what [`chroma_top_k`] prunes by. + let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> { + let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx); + let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx); + u.iter() + .zip(v.iter()) + .map(|(&(us, mode), &(vs, _))| (us + vs, mode)) + .collect() + }; + let modes: Vec = match chroma_top_k() { + Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k), + _ => CHROMA_MODES.to_vec(), + }; let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)]; let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED)); + let ranking: Vec<(f64, u8)> = if census_on() { + sad_scores(chroma) + } else { + Vec::new() + }; + census_add(2, 1); + census_add(3, modes.len()); let mut best: Option<(f64, u8, Trial, Trial)> = None; - for mode in CHROMA_MODES { + for mode in modes { let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits; if (V_PRED..=D67_PRED).contains(&mode) { bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3); @@ -2228,6 +2416,10 @@ fn search_chroma( } } let (cost, mode, u, v) = best.expect("CHROMA_MODES is not empty"); + if census_on() { + CHROMA_RANK[sad_rank(&ranking, mode).min(6)] + .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); chroma[0].commit(at.x, at.y, at.side, &u); chroma[1].commit(at.x, at.y, at.side, &v); @@ -2494,6 +2686,13 @@ fn code_square_inter( } } + census_add(8, 1); + if skip { + census_add(10, 1); + } + if inter_cost >= intra_cost { + census_add(9, 1); + } if inter_cost < intra_cost { let (levels, tx_depth, dcost) = commit_inter_luma( luma, (x, y), side, mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_trial, skip, fctx, @@ -3938,6 +4137,8 @@ fn search_inter_block( } _ => search.modes.to_vec(), }; + census_add(5, 1); + census_add(6, intra_modes.len()); for &mode in &intra_modes { let luma_trial = luma.trial( At { @@ -4192,6 +4393,7 @@ fn search_inter_block( .then(a.1.total_cmp(&b.1)) }); cands.dedup_by_key(|c| (c.2.ref_frame, c.0)); + census_add(7, cands.len()); { for (mv, mode_bits_inter, info) in cands { let (ref_luma, ref_u, ref_v) = match extra @@ -4614,6 +4816,7 @@ pub(crate) fn encode_inter_frame( // nothing is not offered the split at all. let breakout = split_breakout_coeffs(); let split = (!block.skip + && !split_rd_breakout(cost_whole, BLOCK, search.lambda) && (breakout == 0 || block.luma.len() > 4 * breakout) && leaves_legal && split_inter_blocks()) @@ -4648,6 +4851,7 @@ pub(crate) fn encode_inter_frame( // at BLOCK_16X16 (lane-av1rd2). Same // skipped-block prune as the level above. let eight = (!leaf.skip + && !split_rd_breakout(leaf_cost, SUB, search.lambda) && (breakout == 0 || leaf.luma.len() > breakout) && split_inter_8()) .then(|| {