forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'main' into lane-av1tiles

Browse files at this commit

bbd803c86bd11fedc00e24a840f1b5cc5a13d609Ahmet Kaan GümüşParent: 1878642826851c
crates/ec-av1/examples/enc_probe.rsmodified+15 -0
@@ -51,6 +51,21 @@ fn main() {
5151 h = (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
5252 }
5353 println!("q={q} bytes={} fnv1a={h:016x}", e.stream.len());
54+ if ec_av1::encode::census_on() {
55+ let (kinds, luma_rank, chroma_rank) = ec_av1::encode::take_census();
56+ for (name, n) in ec_av1::encode::CENSUS_KINDS.iter().zip(kinds) {
57+ println!(" census {name}: {n}");
58+ }
59+ let pct = |h: &[usize]| {
60+ let total: usize = h.iter().sum::<usize>().max(1);
61+ h.iter()
62+ .map(|n| format!("{:.1}%", 100.0 * *n as f64 / total as f64))
63+ .collect::<Vec<_>>()
64+ .join(" ")
65+ };
66+ println!(" census luma SAD rank of RD winner: {}", pct(&luma_rank));
67+ println!(" census chroma SAD rank of RD winner: {}", pct(&chroma_rank));
68+ }
5469 }
5570 println!("wall {:.3}s", start.elapsed().as_secs_f64());
5671 }
crates/ec-av1/src/encode.rsmodified+221 -17
@@ -244,6 +244,45 @@ fn restoration_enabled() -> bool {
244244 /// future explicit speed preset.
245245 const SPLIT_BREAKOUT_COEFFS: usize = 0;
246246
247+/// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own
248+/// currency: a 32x32 inter block whose whole-block RD cost per pixel comes
249+/// out under `threshold * lambda` is not offered the split at all, and a
250+/// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both
251+/// always, as before this lever.
252+///
253+/// The census is what points here: the split trial runs on nearly every
254+/// non-skip block (15132 leaf searches per ladder point on the 1080p clip)
255+/// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient
256+/// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD
257+/// points, so the gate has to read the block's own RD cost, not its levels.
258+///
259+/// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of
260+/// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for
261+/// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and
262+/// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs
263+/// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships --
264+/// the largest threshold whose BD stays inside the +0.3 keep rule on every
265+/// clip.
266+const SPLIT_RD_THRESHOLD: f64 = 0.125;
267+
268+/// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build.
269+fn split_rd_threshold() -> f64 {
270+ static T: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
271+ *T.get_or_init(|| {
272+ std::env::var("EC_AV1_SPLIT_RD")
273+ .ok()
274+ .and_then(|v| v.parse().ok())
275+ .unwrap_or(SPLIT_RD_THRESHOLD)
276+ })
277+}
278+
279+/// Whether `cost` over a `side` x `side` block is cheap enough per pixel that
280+/// [`split_rd_threshold`] withholds the split trial.
281+fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool {
282+ let t = split_rd_threshold();
283+ t > 0.0 && cost < t * lambda * (side * side) as f64
284+}
285+
247286 /// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test
248287 /// build.
249288 fn split_breakout_coeffs() -> usize {
@@ -276,6 +315,76 @@ pub(crate) fn take_partition_hits() -> [usize; 4] {
276315 [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
277316 }
278317
318+/// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full
319+/// rate-distortion trials the block search actually runs, by kind, and where
320+/// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by
321+/// default, and a measurement build rather than a speed one -- the census
322+/// runs the SAD pre-pass the unpruned search otherwise skips.
323+pub fn census_on() -> bool {
324+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
325+ *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1")))
326+}
327+
328+/// What each [`CENSUS`] counter counts.
329+pub const CENSUS_KINDS: [&str; 11] = [
330+ "intra blocks searched (key frame + inter leaves)",
331+ "intra luma mode trials",
332+ "chroma searches",
333+ "chroma mode trials (each = 2 plane trials)",
334+ "tx-depth trials (transform units, depth >= 1)",
335+ "inter 32x32 blocks searched",
336+ "inter block intra-mode trials",
337+ "inter mv candidates (each = 3 mc trials)",
338+ "inter leaves searched (intra vs NEARESTMV/NEWMV)",
339+ " of those, intra won",
340+ " of those, the NEARESTMV trial coded no residual",
341+];
342+
343+/// The census counters themselves, indexed by [`CENSUS_KINDS`].
344+static CENSUS: [std::sync::atomic::AtomicUsize; 11] =
345+ [const { std::sync::atomic::AtomicUsize::new(0) }; 11];
346+
347+/// Where the RD winner sat in the SAD ranking, for the luma intra search and
348+/// the chroma mode search -- what says whether a top-N prune would have kept
349+/// the block the search actually chose.
350+static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] =
351+ [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
352+static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] =
353+ [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
354+
355+fn census_add(kind: usize, n: usize) {
356+ if census_on() {
357+ CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
358+ }
359+}
360+
361+/// Reads (and clears) the census, so a driver can attribute it to its own encode.
362+pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) {
363+ let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);
364+ (
365+ std::array::from_fn(|i| take(&CENSUS[i])),
366+ std::array::from_fn(|i| take(&LUMA_RANK[i])),
367+ std::array::from_fn(|i| take(&CHROMA_RANK[i])),
368+ )
369+}
370+
371+/// The rank of `winner` in `scored` ordered by its cheap score, cheapest
372+/// first -- the census's one shared rule, so the luma and chroma histograms
373+/// mean the same thing.
374+fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize {
375+ scored
376+ .iter()
377+ .filter(|&&(score, mode)| {
378+ mode != winner
379+ && score
380+ < scored
381+ .iter()
382+ .find(|&&(_, m)| m == winner)
383+ .map_or(f64::INFINITY, |&(s, _)| s)
384+ })
385+ .count()
386+}
387+
279388 /// Whether a 32x32 block may be split into four 16x16 ones when the trial says
280389 /// four cost less. Set from the measurement in the lane report.
281390 const SPLIT_BLOCKS: bool = true;
@@ -983,7 +1092,11 @@ impl Plane<'_> {
9831092 x, y, side, reach, ..
9841093 } = at;
9851094 let (above, left, corner) = self.edges(x, y, side, reach);
986- let mut prediction = vec![0u8; side * side];
1095+ // Per-candidate scratch on the search's hottest path, so both buffers
1096+ // live on the stack -- `side` is at most `BLOCK` -- rather than
1097+ // costing a malloc/free pair per trial (`mc_trial` already does this).
1098+ let mut prediction = [0u8; BLOCK * BLOCK];
1099+ let prediction = &mut prediction[..side * side];
9871100 intra_predict_u8(
9881101 mode,
9891102 0,
@@ -994,10 +1107,11 @@ impl Plane<'_> {
9941107 side,
9951108 false,
9961109 false,
997- &mut prediction, fctx,
1110+ prediction, fctx,
9981111 );
9991112
1000- let mut residual = vec![0i32; side * side];
1113+ let mut residual = [0i32; BLOCK * BLOCK];
1114+ let residual = &mut residual[..side * side];
10011115 for row in 0..side {
10021116 for col in 0..side {
10031117 residual[row * side + col] =
@@ -1008,7 +1122,7 @@ impl Plane<'_> {
10081122 #[cfg(test)]
10091123 let t = std::time::Instant::now();
10101124 let levels =
1011- forward_and_quantize_typed(&residual, side, 8, i32::from(base_q_idx), deadzone, tx_type);
1125+ forward_and_quantize_typed(residual, side, 8, i32::from(base_q_idx), deadzone, tx_type);
10121126 let coded =
10131127 dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), 0, 0, tx_type);
10141128 #[cfg(test)]
@@ -1091,7 +1205,8 @@ impl Plane<'_> {
10911205 bits: 0.0,
10921206 };
10931207 }
1094- let mut residual = vec![0i32; side * side];
1208+ let mut residual = [0i32; BLOCK * BLOCK];
1209+ let residual = &mut residual[..side * side];
10951210 for row in 0..side {
10961211 for col in 0..side {
10971212 residual[row * side + col] =
@@ -1101,7 +1216,7 @@ impl Plane<'_> {
11011216 }
11021217 #[cfg(test)]
11031218 let t = std::time::Instant::now();
1104- let levels = forward_and_quantize(&residual, side, 8, i32::from(base_q_idx), deadzone);
1219+ let levels = forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone);
11051220 let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));
11061221 #[cfg(test)]
11071222 stage_add(2, t.elapsed());
@@ -1164,6 +1279,7 @@ impl Plane<'_> {
11641279 _ => TxbSet::Luma4,
11651280 };
11661281 let mut levels = vec![0i32; side * side];
1282+ census_add(4, n * n);
11671283 let (mut sse, mut bits) = (0.0, 0.0);
11681284 for tu_row in 0..n {
11691285 for tu_col in 0..n {
@@ -1288,6 +1404,11 @@ impl Plane<'_> {
12881404 x, y, side, reach, ..
12891405 } = at;
12901406 let (above, left, corner) = self.edges(x, y, side, reach);
1407+ // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or
1408+ // the census reports it), so summing it under the default unpruned
1409+ // search is `side * side` absolute differences per mode spent on a
1410+ // number no one reads.
1411+ let want_sad = search.top_k.is_some() || census_on();
12911412 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
12921413 .modes
12931414 .iter()
@@ -1305,16 +1426,20 @@ impl Plane<'_> {
13051426 false,
13061427 &mut prediction, fctx,
13071428 );
1308- let sad: f64 = (0..side * side)
1309- .map(|i| {
1310- let (row, col) = (i / side, i % side);
1311- f64::from(
1312- (i32::from(self.source[(y + row) * self.width + x + col])
1313- - i32::from(prediction[i]))
1314- .abs(),
1315- )
1316- })
1317- .sum();
1429+ let sad: f64 = if want_sad {
1430+ (0..side * side)
1431+ .map(|i| {
1432+ let (row, col) = (i / side, i % side);
1433+ f64::from(
1434+ (i32::from(self.source[(y + row) * self.width + x + col])
1435+ - i32::from(prediction[i]))
1436+ .abs(),
1437+ )
1438+ })
1439+ .sum()
1440+ } else {
1441+ 0.0
1442+ };
13181443 (
13191444 sad + search.lambda * mode_bits[usize::from(mode)],
13201445 mode,
@@ -1337,6 +1462,13 @@ impl Plane<'_> {
13371462 }
13381463 }
13391464 }
1465+ let ranking: Vec<(f64, u8)> = if census_on() {
1466+ scored.iter().map(|&(score, mode, _)| (score, mode)).collect()
1467+ } else {
1468+ Vec::new()
1469+ };
1470+ census_add(0, 1);
1471+ census_add(1, scored.len());
13401472 let mut best: Option<(f64, u8, Trial)> = None;
13411473 for (_, mode, prediction) in scored {
13421474 let trial = self.code_from_prediction(
@@ -1358,6 +1490,10 @@ impl Plane<'_> {
13581490 }
13591491 }
13601492 let (cost, mode, trial) = best.expect("the search offers at least one mode");
1493+ if census_on() {
1494+ LUMA_RANK[sad_rank(&ranking, mode).min(12)]
1495+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1496+ }
13611497 self.commit(x, y, side, &trial);
13621498 (coeffs(&trial.levels, side), mode, cost)
13631499 }
@@ -2195,6 +2331,34 @@ pub(crate) fn take_uv_mode_hits() -> [usize; 13] {
21952331 /// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
21962332 /// writer then has to code.
21972333 #[allow(clippy::too_many_arguments)]
2334+/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on,
2335+/// ranked by the SAD of their predictions summed over both planes (`DC_PRED`
2336+/// always kept, the same rule [`prune_by_sad`] applies to luma). `None`
2337+/// trials all seven, as before this lever.
2338+///
2339+/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was
2340+/// the search's largest trial population by far -- seven modes times two
2341+/// planes for every intra block, against 3.7 luma trials -- and the RD
2342+/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
2343+/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
2344+fn chroma_top_k() -> Option<usize> {
2345+ static K: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
2346+ *K.get_or_init(|| match std::env::var("EC_AV1_CHROMA_K").ok() {
2347+ Some(v) => v.parse::<usize>().ok().filter(|&k| k > 0),
2348+ None => CHROMA_TOP_K,
2349+ })
2350+}
2351+
2352+/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
2353+/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3):
2354+/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/
2355+/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better)
2356+/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The
2357+/// BD swings by about a point in either direction as near-tie chroma modes
2358+/// flip, which is the measurement's own sensitivity, not a trend: nothing
2359+/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned.
2360+const CHROMA_TOP_K: Option<usize> = None;
2361+
21982362 fn search_chroma(
21992363 chroma: &mut [Plane; 2],
22002364 (x, y): (usize, usize),
@@ -2211,10 +2375,34 @@ fn search_chroma(
22112375 reach: Reach::none(),
22122376 set,
22132377 };
2378+ // The census's cheap proxy for a chroma mode: the SAD of its prediction
2379+ // summed over both planes, ranked by the same rule the luma histogram
2380+ // uses. Only built under `EC_AV1_CENSUS`.
2381+ // The SAD of each mode's prediction, summed over both planes -- the
2382+ // census's ranking rule, and what [`chroma_top_k`] prunes by.
2383+ let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> {
2384+ let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
2385+ let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
2386+ u.iter()
2387+ .zip(v.iter())
2388+ .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
2389+ .collect()
2390+ };
2391+ let modes: Vec<u8> = match chroma_top_k() {
2392+ Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k),
2393+ _ => CHROMA_MODES.to_vec(),
2394+ };
22142395 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
22152396 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
2397+ let ranking: Vec<(f64, u8)> = if census_on() {
2398+ sad_scores(chroma)
2399+ } else {
2400+ Vec::new()
2401+ };
2402+ census_add(2, 1);
2403+ census_add(3, modes.len());
22162404 let mut best: Option<(f64, u8, Trial, Trial)> = None;
2217- for mode in CHROMA_MODES {
2405+ for mode in modes {
22182406 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
22192407 if (V_PRED..=D67_PRED).contains(&mode) {
22202408 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
@@ -2228,6 +2416,10 @@ fn search_chroma(
22282416 }
22292417 }
22302418 let (cost, mode, u, v) = best.expect("CHROMA_MODES is not empty");
2419+ if census_on() {
2420+ CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
2421+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2422+ }
22312423 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
22322424 chroma[0].commit(at.x, at.y, at.side, &u);
22332425 chroma[1].commit(at.x, at.y, at.side, &v);
@@ -2494,6 +2686,13 @@ fn code_square_inter(
24942686 }
24952687 }
24962688
2689+ census_add(8, 1);
2690+ if skip {
2691+ census_add(10, 1);
2692+ }
2693+ if inter_cost >= intra_cost {
2694+ census_add(9, 1);
2695+ }
24972696 if inter_cost < intra_cost {
24982697 let (levels, tx_depth, dcost) = commit_inter_luma(
24992698 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(
39384137 }
39394138 _ => search.modes.to_vec(),
39404139 };
4140+ census_add(5, 1);
4141+ census_add(6, intra_modes.len());
39414142 for &mode in &intra_modes {
39424143 let luma_trial = luma.trial(
39434144 At {
@@ -4192,6 +4393,7 @@ fn search_inter_block(
41924393 .then(a.1.total_cmp(&b.1))
41934394 });
41944395 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
4396+ census_add(7, cands.len());
41954397 {
41964398 for (mv, mode_bits_inter, info) in cands {
41974399 let (ref_luma, ref_u, ref_v) = match extra
@@ -4614,6 +4816,7 @@ pub(crate) fn encode_inter_frame(
46144816 // nothing is not offered the split at all.
46154817 let breakout = split_breakout_coeffs();
46164818 let split = (!block.skip
4819+ && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
46174820 && (breakout == 0 || block.luma.len() > 4 * breakout)
46184821 && leaves_legal
46194822 && split_inter_blocks())
@@ -4648,6 +4851,7 @@ pub(crate) fn encode_inter_frame(
46484851 // at BLOCK_16X16 (lane-av1rd2). Same
46494852 // skipped-block prune as the level above.
46504853 let eight = (!leaf.skip
4854+ && !split_rd_breakout(leaf_cost, SUB, search.lambda)
46514855 && (breakout == 0 || leaf.luma.len() > breakout)
46524856 && split_inter_8())
46534857 .then(|| {