forge
Explore
Log in

Don't you dare go Hollow

A speed preset axis (0..=10), preset 0 the search we ship

Browse files at this commit

597c1a3db7040a08bd93ca2c9a2ab06972322786Ahmet Kaan GümüşParent: 9b5376d
  • feat
    • a speed preset axis (0..=10), preset 0 the search we ship
Show full message
feat(av1): a speed preset axis (0..=10), preset 0 the search we ship

Every search lever this crate already has an EC_AV1_* knob for reads its
default from a per-speed table in the new `speed` module, indexed by one
process-global preset (`Av1Encoder::with_speed`, `EC_AV1_SPEED`). Index 0
of every table IS the shipped constant, so preset 0 is byte-identical by
construction; `speed::levers` names what each preset switches off, and
ec-bench codes one row per preset {0,3,6,10}.
crates/ec-av1/src/encode.rsmodified+63 -63
@@ -206,7 +206,7 @@ pub(crate) fn take_predicted_bits() -> Vec<f64> {
206206 }
207207
208208 /// Whether a 16x16 inter leaf may split into four 8x8 ones of its own.
209-const SPLIT_INTER_8: bool = true;
209+pub(crate) const SPLIT_INTER_8: bool = true;
210210
211211 /// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build.
212212 /// Whether a key frame codes `tx_mode == TxMode::Select` and searches each
@@ -223,41 +223,39 @@ const SPLIT_INTER_8: bool = true;
223223 /// third, for 13% encode wall. `EC_AV1_TX_SELECT_INTER=0` turns it off for an
224224 /// A/B on one build.
225225 fn tx_select_inter() -> bool {
226- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
227- *ON.get_or_init(|| {
228- !matches!(
229- std::env::var("EC_AV1_TX_SELECT_INTER").as_deref(),
230- Ok("0") | Ok("off")
231- )
232- })
226+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
227+ crate::envflags::var("EC_AV1_TX_SELECT_INTER")
228+ .ok()
229+ .map(|v| !matches!(v.as_str(), "0" | "off"))
230+ });
231+ ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_INTER))
233232 }
234233
235234 fn tx_select() -> bool {
236- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
237- *ON.get_or_init(|| {
238- !matches!(
239- std::env::var("EC_AV1_TX_SELECT").as_deref(),
240- Ok("0") | Ok("off")
241- )
242- })
235+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
236+ crate::envflags::var("EC_AV1_TX_SELECT")
237+ .ok()
238+ .map(|v| !matches!(v.as_str(), "0" | "off"))
239+ });
240+ ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_KEY))
243241 }
244242
245243 fn split_inter_8() -> bool {
246244 match std::env::var("EC_AV1_SPLIT_INTER8").ok() {
247245 Some(v) if cfg!(test) => v != "0",
248- _ => SPLIT_INTER_8,
246+ _ => crate::speed::at(&crate::speed::SPLIT_8),
249247 }
250248 }
251249
252250 /// Whether a 16x16 (or 8x8) leaf runs a motion search of its own beside the
253251 /// NEARESTMV candidate it always had.
254-const LEAF_NEW_MV: bool = true;
252+pub(crate) const LEAF_NEW_MV: bool = true;
255253
256254 /// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the
257255 /// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0
258256 /// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion
259257 /// searches (the census `bd_rate_vs_libaom_and_rav1e` prints).
260-const EXTRA_REF_NEW_MV: bool = true;
258+pub(crate) const EXTRA_REF_NEW_MV: bool = true;
261259
262260 /// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's
263261 /// own best vector before that reference's `NEWMV` search is skipped: a
@@ -334,7 +332,7 @@ fn leaf_second_new_margin() -> f64 {
334332 fn leaf_second_new_mv() -> bool {
335333 match std::env::var("EC_AV1_LEAF_SECOND_NEWMV").ok() {
336334 Some(v) => v != "0",
337- None => true,
335+ None => crate::speed::at(&crate::speed::LEAF_SECOND),
338336 }
339337 }
340338
@@ -343,13 +341,13 @@ fn leaf_second_new_mv() -> bool {
343341 /// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both
344342 /// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what
345343 /// was missing was the encoder ever forming one below 32x32.
346-const LEAF_COMPOUND: bool = true;
344+pub(crate) const LEAF_COMPOUND: bool = true;
347345
348346 /// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build.
349347 fn leaf_compound() -> bool {
350348 match std::env::var("EC_AV1_LEAF_COMPOUND").ok() {
351349 Some(v) => v != "0",
352- None => LEAF_COMPOUND,
350+ None => crate::speed::at(&crate::speed::LEAF_COMPOUND),
353351 }
354352 }
355353
@@ -366,7 +364,7 @@ fn leaf_new_mv() -> bool {
366364 /// the true frame edge cut through was ever split there; inside the frame
367365 /// every block was coded whole, which left the partition decision the key
368366 /// frame already makes unmade for eleven frames out of twelve.
369-const SPLIT_INTER_BLOCKS: bool = true;
367+pub(crate) const SPLIT_INTER_BLOCKS: bool = true;
370368
371369 /// [`SPLIT_INTER_BLOCKS`], or what `EC_AV1_SPLIT_INTER` names when the
372370 /// measurement that keeps it is running (test builds only, like
@@ -374,7 +372,7 @@ const SPLIT_INTER_BLOCKS: bool = true;
374372 fn split_inter_blocks() -> bool {
375373 match std::env::var("EC_AV1_SPLIT_INTER").ok() {
376374 Some(v) if cfg!(test) => v != "0",
377- _ => SPLIT_INTER_BLOCKS,
375+ _ => crate::speed::at(&crate::speed::SPLIT_INTER),
378376 }
379377 }
380378
@@ -382,13 +380,13 @@ fn split_inter_blocks() -> bool {
382380 /// Wiener filter per 64x64 luma restoration unit, picked from
383381 /// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
384382 /// test build, like [`lambda_scale`].
385-const RESTORATION: bool = true;
383+pub(crate) const RESTORATION: bool = true;
386384
387385 /// [`RESTORATION`], or what `EC_AV1_LR` names in a test build.
388386 fn restoration_enabled() -> bool {
389387 match std::env::var("EC_AV1_LR").ok() {
390388 Some(v) if cfg!(test) => v != "0",
391- _ => RESTORATION,
389+ _ => crate::speed::at(&crate::speed::RESTORATION),
392390 }
393391 }
394392
@@ -405,7 +403,7 @@ fn restoration_enabled() -> bool {
405403 /// +31.7/+40.6/+27.8, for barely more speed. The split trial is where this
406404 /// encoder's inter quality lives, so `0` ships and the knob stays for a
407405 /// future explicit speed preset.
408-const SPLIT_BREAKOUT_COEFFS: usize = 0;
406+pub(crate) const SPLIT_BREAKOUT_COEFFS: usize = 0;
409407
410408 /// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own
411409 /// currency: a 32x32 inter block whose whole-block RD cost per pixel comes
@@ -431,17 +429,14 @@ const SPLIT_BREAKOUT_COEFFS: usize = 0;
431429 /// +51.3/-14.2 (the 1080p film 0.2 worse for a finer search) and 0.25 is
432430 /// +16.6/-0.6, +46.9/+19.1, +51.6/-14.5 (screen 0.3 worse vs libaom, 3s off
433431 /// the screen wall). Neither clears the keep rule; 0.125 stays.
434-const SPLIT_RD_THRESHOLD: f64 = 0.125;
432+pub(crate) const SPLIT_RD_THRESHOLD: f64 = 0.125;
435433
436434 /// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build.
437435 fn split_rd_threshold() -> f64 {
438- static T: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
439- *T.get_or_init(|| {
440- std::env::var("EC_AV1_SPLIT_RD")
441- .ok()
442- .and_then(|v| v.parse().ok())
443- .unwrap_or(SPLIT_RD_THRESHOLD)
444- })
436+ static ENV: std::sync::LazyLock<Option<f64>> = std::sync::LazyLock::new(|| {
437+ crate::envflags::var("EC_AV1_SPLIT_RD").ok().and_then(|v| v.parse().ok())
438+ });
439+ ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::SPLIT_RD))
445440 }
446441
447442 /// Whether `cost` over a `side` x `side` block is cheap enough per pixel that
@@ -456,7 +451,7 @@ fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool {
456451 fn split_breakout_coeffs() -> usize {
457452 match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() {
458453 Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS),
459- _ => SPLIT_BREAKOUT_COEFFS,
454+ _ => crate::speed::at(&crate::speed::SPLIT_BREAKOUT),
460455 }
461456 }
462457
@@ -2811,10 +2806,10 @@ impl Reach {
28112806 /// [`warp_prediction`]); `EC_AV1_WARP=0` turns the tool -- and the two header
28122807 /// bits -- back off for an A/B on one build.
28132808 pub(crate) fn warp_on() -> bool {
2814- static ON: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
2815- !matches!(crate::envflags::var("EC_AV1_WARP").as_deref(), Ok("0") | Ok("off"))
2809+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
2810+ crate::envflags::var("EC_AV1_WARP").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
28162811 });
2817- *ON
2812+ ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::WARP))
28182813 }
28192814
28202815 /// The smallest LEAF an OBMC candidate is offered for, so the census can
@@ -3124,10 +3119,10 @@ static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 8] =
31243119 /// residual to reach there -- the tool was being judged on content that
31253120 /// cannot pay for it (class `gate-blind-to-feature`). `EC_AV1_TX32_DEPTH`.
31263121 fn tx32_depth_search() -> bool {
3127- static ON: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
3128- !matches!(crate::envflags::var("EC_AV1_TX32_DEPTH").as_deref(), Ok("0") | Ok("off"))
3122+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
3123+ crate::envflags::var("EC_AV1_TX32_DEPTH").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
31293124 });
3130- *ON
3125+ ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX32_DEPTH))
31313126 }
31323127
31333128 /// Whether a COMPOUND inter winner is offered the var-tx split at all: its
@@ -3139,10 +3134,10 @@ fn tx32_depth_search() -> bool {
31393134 /// 32x32 depth search); `EC_AV1_COMP_VARTX=0` turns it off.
31403135 /// `EC_AV1_COMP_VARTX`.
31413136 fn compound_var_tx() -> bool {
3142- static ON: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
3143- !matches!(crate::envflags::var("EC_AV1_COMP_VARTX").as_deref(), Ok("0") | Ok("off"))
3137+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
3138+ crate::envflags::var("EC_AV1_COMP_VARTX").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
31443139 });
3145- *ON
3140+ ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::COMPOUND_VAR_TX))
31463141 }
31473142
31483143 /// How many 32x32-and-below inter blocks each reference frame won, indexed by
@@ -4098,15 +4093,19 @@ pub(crate) fn take_angle_delta_hits() -> [usize; 7] {
40984093 /// Whether the luma search refines a directional winner's `angle_delta_y`
40994094 /// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair).
41004095 fn angle_delta_on() -> bool {
4101- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4102- *ON.get_or_init(|| std::env::var("EC_AV1_ANGLE").as_deref() != Ok("0"))
4096+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
4097+ crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0")
4098+ });
4099+ ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE))
41034100 }
41044101
41054102 /// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
41064103 /// switches it off, which is how the lane measured its own on/off pair).
41074104 fn cfl_on() -> bool {
4108- static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4109- *ON.get_or_init(|| std::env::var("EC_AV1_CFL").as_deref() != Ok("0"))
4105+ static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
4106+ crate::envflags::var("EC_AV1_CFL").ok().map(|v| v != "0")
4107+ });
4108+ ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CFL))
41104109 }
41114110
41124111 /// Whether the intra search offers the five recursive filter-intra modes at
@@ -4152,11 +4151,12 @@ pub(crate) fn take_uv_mode_hits() -> [usize; 14] {
41524151 /// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
41534152 /// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
41544153 fn chroma_top_k() -> Option<usize> {
4155- static K: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
4156- *K.get_or_init(|| match std::env::var("EC_AV1_CHROMA_K").ok() {
4157- Some(v) => v.parse::<usize>().ok().filter(|&k| k > 0),
4158- None => CHROMA_TOP_K,
4159- })
4154+ static ENV: std::sync::LazyLock<Option<Option<usize>>> = std::sync::LazyLock::new(|| {
4155+ crate::envflags::var("EC_AV1_CHROMA_K")
4156+ .ok()
4157+ .map(|v| v.parse::<usize>().ok().filter(|&k| k > 0))
4158+ });
4159+ ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CHROMA_K))
41604160 }
41614161
41624162 /// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
@@ -4170,7 +4170,7 @@ fn chroma_top_k() -> Option<usize> {
41704170 /// RE-MEASURED on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on:
41714171 /// K=4 is +17.1/-0.1, +47.1/+19.2, +51.6/-13.8 against the base's
41724172 /// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3 -- every row worse. Still `None`.
4173-const CHROMA_TOP_K: Option<usize> = None;
4173+pub(crate) const CHROMA_TOP_K: Option<usize> = None;
41744174
41754175 fn search_chroma(
41764176 chroma: &mut [Plane; 2],
@@ -5458,7 +5458,7 @@ fn prune_top_k() -> Option<usize> {
54585458 .and_then(|v| v.parse::<usize>().ok());
54595459 match swept {
54605460 Some(k) if cfg!(test) => Some(k),
5461- _ => PRUNE_TOP_K,
5461+ _ => crate::speed::at(&crate::speed::PRUNE_K),
54625462 }
54635463 }
54645464
@@ -5478,7 +5478,7 @@ fn set_test_top_k_override(value: Option<usize>) {
54785478
54795479 /// The default: unpruned, thirteen full trials per block, same as before this
54805480 /// lever. Set from the sweep in the lane report if the quality gate clears it.
5481-const PRUNE_TOP_K: Option<usize> = None;
5481+pub(crate) const PRUNE_TOP_K: Option<usize> = None;
54825482
54835483 /// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop --
54845484 /// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths'
@@ -5497,7 +5497,7 @@ fn prune_top_k_inter() -> Option<usize> {
54975497 .and_then(|v| v.parse::<usize>().ok());
54985498 match swept {
54995499 Some(k) if cfg!(test) => Some(k),
5500- _ => INTER_PRUNE_TOP_K,
5500+ _ => crate::speed::at(&crate::speed::PRUNE_K_INTER),
55015501 }
55025502 }
55035503
@@ -5521,7 +5521,7 @@ fn set_test_top_k_override_inter(value: Option<usize>) {
55215521 /// `K=3`, ships as default. Unlike the key-frame path (still `None`), an
55225522 /// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so
55235523 /// pruning them costs less quality here.
5524-const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
5524+pub(crate) const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
55255525
55265526 // Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
55275527 // [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
@@ -6835,7 +6835,7 @@ fn mv_component_bits(diff: i32) -> Option<f64> {
68356835 fn extra_ref_new_mv() -> bool {
68366836 match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() {
68376837 Some(v) if cfg!(test) => v != "0",
6838- _ => EXTRA_REF_NEW_MV,
6838+ _ => crate::speed::at(&crate::speed::EXTRA_REF_NEW),
68396839 }
68406840 }
68416841
@@ -6861,13 +6861,13 @@ pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool)
68616861 /// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate
68626862 /// runs as), and every block still codes SINGLE, so the only cost is one
68636863 /// `comp_mode` symbol per inter block.
6864-const REFERENCE_SELECT: bool = true;
6864+pub(crate) const REFERENCE_SELECT: bool = true;
68656865
68666866 /// [`REFERENCE_SELECT`], with the test-build environment override.
68676867 pub(crate) fn reference_select() -> bool {
68686868 match std::env::var("EC_AV1_COMPOUND").ok() {
68696869 Some(v) if cfg!(test) => v != "0",
6870- _ => REFERENCE_SELECT,
6870+ _ => crate::speed::at(&crate::speed::COMPOUND),
68716871 }
68726872 }
68736873
@@ -8040,7 +8040,7 @@ fn tpl_strength() -> f64 {
80408040 /// The streaming facade holds `depth - 1` pictures back so it feeds
80418041 /// `encode_inter_frame` the same window `encode_sequence` does; both read
80428042 /// THIS function, so the two paths cannot disagree about the window.
8043-const TPL_DEPTH: usize = 8;
8043+pub(crate) const TPL_DEPTH: usize = 8;
80448044
80458045 /// The exponent the dependence ratio is read through ([`tpl_lambda_factors`]).
80468046 /// 0.5 is libaom's own square-root compression of its dependence ratio.
@@ -8112,7 +8112,7 @@ pub(crate) fn tpl_depth() -> usize {
81128112 .ok()
81138113 .and_then(|v| v.parse::<usize>().ok())
81148114 .filter(|d| *d >= 1)
8115- .unwrap_or(TPL_DEPTH)
8115+ .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_DEPTH))
81168116 .max(1)
81178117 }
81188118
crates/ec-av1/src/encoder.rsmodified+18 -0
@@ -659,6 +659,24 @@ const _: fn() = || {
659659 };
660660
661661 impl Av1Encoder {
662+ /// [`Av1Encoder::new`] at a SPEED PRESET (`speed` 0..=10, rav1e's scale:
663+ /// 0 is the full search this encoder has always run and is byte for byte
664+ /// identical to [`Av1Encoder::new`]; higher presets switch search levers
665+ /// off, [`crate::speed::levers`] naming which).
666+ ///
667+ /// The preset is process-global (the tile search reads it from worker
668+ /// threads -- see [`crate::speed`]), so it is set here for every encode
669+ /// that follows on this process, and two encoders at different speeds
670+ /// must not run concurrently. `EC_AV1_SPEED=<n>` is the same knob for a
671+ /// caller that does not construct the encoder itself.
672+ ///
673+ /// # Errors
674+ /// [`Av1Encoder::new`]'s.
675+ pub fn with_speed(config: EncoderConfig, speed: u8) -> Result<Self> {
676+ crate::speed::set_speed(speed);
677+ Self::new(config)
678+ }
679+
662680 /// # Errors
663681 /// Returns an error when `config.width`/`config.height` are zero, odd,
664682 /// or larger than the 16-bit frame size an AV1 sequence header carries,
crates/ec-av1/src/filter_search.rsmodified+27 -8
@@ -291,15 +291,29 @@ pub(crate) fn pick_filters(
291291 .filter_map(|d| u8::try_from(i32::from(best.lf.0) + d).ok())
292292 .filter(|&l| l <= 63)
293293 .collect();
294- stage(&mut best, &refine, |c, v| c.lf = (v, v), |t| t.sse_y, &mut st)?;
294+ // Which of these stages run is the SPEED PRESET's filter-search lever
295+ // (`crate::speed`): each stage costs one whole-frame decode per candidate
296+ // it has not seen, and the filter search is 19-28% of the encoder's wall.
297+ // At speed 0 every table below reads its shipped value, so the sequence is
298+ // the one this function always ran.
299+ if crate::speed::at(&crate::speed::DEBLOCK_REFINE) {
300+ stage(&mut best, &refine, |c, v| c.lf = (v, v), |t| t.sse_y, &mut st)?;
301+ }
295302 // Deblocking chroma, three points around the luma winner.
296- let chroma_levels = [0, best.lf.0 / 2, best.lf.0];
297- stage(&mut best, &chroma_levels, |c, v| c.lf.1 = v, |t| t.sse_uv, &mut st)?;
303+ if crate::speed::at(&crate::speed::DEBLOCK_CHROMA) {
304+ let chroma_levels = [0, best.lf.0 / 2, best.lf.0];
305+ stage(&mut best, &chroma_levels, |c, v| c.lf.1 = v, |t| t.sse_uv, &mut st)?;
306+ }
298307 // CDEF, primary then secondary, luma on luma error and chroma on chroma.
299- stage(&mut best, &CDEF_PRI, |c, v| c.y.0 = v, |t| t.sse_y, &mut st)?;
300- stage(&mut best, &CDEF_SEC, |c, v| c.y.1 = v, |t| t.sse_y, &mut st)?;
301- stage(&mut best, &CDEF_PRI, |c, v| c.uv.0 = v, |t| t.sse_uv, &mut st)?;
302- stage(&mut best, &CDEF_SEC, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut st)?;
308+ // `n == 0` leaves every strength at 0, i.e. deblocking only.
309+ let n = crate::speed::at(&crate::speed::CDEF_STRENGTHS);
310+ if n > 0 {
311+ let (pri, sec) = (&CDEF_PRI[..n.min(CDEF_PRI.len())], &CDEF_SEC[..n.min(CDEF_SEC.len())]);
312+ stage(&mut best, pri, |c, v| c.y.0 = v, |t| t.sse_y, &mut st)?;
313+ stage(&mut best, sec, |c, v| c.y.1 = v, |t| t.sse_y, &mut st)?;
314+ stage(&mut best, pri, |c, v| c.uv.0 = v, |t| t.sse_uv, &mut st)?;
315+ stage(&mut best, sec, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut st)?;
316+ }
303317
304318 CHOSEN.with(|c| c.borrow_mut().push(best));
305319 let trials = st.trials;
@@ -342,7 +356,12 @@ pub(crate) fn pick_filters(
342356 }
343357 let mut order: Vec<usize> = (0..pool.len()).collect();
344358 order.sort_by_key(|&i| std::cmp::Reverse(counts[i]));
345- presets.extend(order.iter().take(7).map(|&i| pool[i]));
359+ presets.extend(
360+ order
361+ .iter()
362+ .take(crate::speed::at(&crate::speed::CDEF_PRESETS))
363+ .map(|&i| pool[i]),
364+ );
346365 // The cheapest list length: `bits` costs one literal per superblock plus
347366 // twelve header bits per extra pair, and buys whatever per-unit error the
348367 // wider choice removes.
crates/ec-av1/src/lib.rsmodified+1 -0
@@ -46,6 +46,7 @@ pub mod obu;
4646 mod par;
4747 pub mod quant;
4848 mod refusal_inventory;
49+pub mod speed;
4950 mod restoration;
5051 pub mod sequence;
5152 mod superres;
crates/ec-av1/src/speed.rsadded+284 -0
@@ -0,0 +1,284 @@
1+//! The encoder's SPEED PRESET axis (lane-av1fast): one number, 0..=10 like
2+//! rav1e's `--speed`, that picks a default for every search lever this crate
3+//! already has a knob for.
4+//!
5+//! Speed 0 is today's search, byte for byte -- every table below reads its
6+//! shipped default at index 0, so `encoder::tests`' byte pins are the pin on
7+//! that. Higher speeds trade BD-rate for wall by switching off the levers in
8+//! [`levers`], each of which was already measured on its own (the doc comment
9+//! on each knob in [`crate::encode`] carries its sweep).
10+//!
11+//! The value is PROCESS-GLOBAL, the same shape [`crate::par`]'s thread counts
12+//! use, because the levers are read from the tile-search worker threads --
13+//! a thread-local would not reach them. One speed per process at a time:
14+//! [`crate::encoder::Av1Encoder::with_speed`] sets it at construction, so two
15+//! encoders at different speeds must not run concurrently in one process.
16+//! `EC_AV1_SPEED=<n>` is the environment form the gates and `ec-bench` use.
17+//! Every individual `EC_AV1_*` lever override still wins over the preset.
18+
19+use std::sync::atomic::{AtomicU8, Ordering};
20+
21+/// The highest preset. 10 is the fastest, as in rav1e.
22+pub const MAX_SPEED: u8 = 10;
23+
24+/// 255 = "not read yet"; the env read happens once and the value is a plain
25+/// atomic afterwards, so a caller can set it without touching the process
26+/// environment.
27+static SPEED: AtomicU8 = AtomicU8::new(u8::MAX);
28+
29+/// This process's speed preset, 0..=[`MAX_SPEED`].
30+#[must_use]
31+pub fn speed() -> u8 {
32+ match SPEED.load(Ordering::Relaxed) {
33+ u8::MAX => {
34+ let n = crate::envflags::var("EC_AV1_SPEED")
35+ .ok()
36+ .and_then(|v| v.trim().parse::<u8>().ok())
37+ .unwrap_or(0)
38+ .min(MAX_SPEED);
39+ SPEED.store(n, Ordering::Relaxed);
40+ n
41+ }
42+ n => n,
43+ }
44+}
45+
46+/// Sets the preset for everything encoded afterwards in this process.
47+pub fn set_speed(n: u8) {
48+ SPEED.store(n.min(MAX_SPEED), Ordering::Relaxed);
49+}
50+
51+/// `TABLE[speed()]`, the shape every lever below is read through.
52+pub(crate) fn at<T: Copy>(table: &[T; 11]) -> T {
53+ table[speed() as usize]
54+}
55+
56+// ---------------------------------------------------------------------------
57+// The lever tables. Index 0 of each is the shipped default of the constant
58+// named in the comment; the rest is this lane's composition (see the report
59+// table for what each step measured).
60+// ---------------------------------------------------------------------------
61+
62+/// `encode::SPLIT_RD_THRESHOLD`: how cheap a block has to be before its split
63+/// trial is withheld. The single biggest wall lever in the tile search.
64+pub(crate) const SPLIT_RD: [f64; 11] =
65+ [crate::encode::SPLIT_RD_THRESHOLD, 0.125, 0.25, 0.5, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0];
66+
67+/// `encode::SPLIT_BREAKOUT_COEFFS`: libaom's coefficient-count breakout.
68+pub(crate) const SPLIT_BREAKOUT: [usize; 11] = [crate::encode::SPLIT_BREAKOUT_COEFFS, 0, 0, 0, 0, 0, 1, 1, 2, 4, 4];
69+
70+/// `encode::SPLIT_INTER_8`: a 16x16 leaf may split into four 8x8 ones.
71+pub(crate) const SPLIT_8: [bool; 11] =
72+ [crate::encode::SPLIT_INTER_8, true, true, true, false, false, false, false, false, false, false];
73+
74+/// `encode::SPLIT_INTER_BLOCKS`: a 32x32 inter block may split at all
75+/// (`false` = 32x32-only partitioning).
76+pub(crate) const SPLIT_INTER: [bool; 11] =
77+ [crate::encode::SPLIT_INTER_BLOCKS, true, true, true, true, true, true, true, false, false, false];
78+
79+/// `encode::leaf_second_new_mv`: a leaf searches its SECOND reference.
80+pub(crate) const LEAF_SECOND: [bool; 11] =
81+ [true, true, true, false, false, false, false, false, false, false, false];
82+
83+/// `encode::EXTRA_REF_NEW_MV`: GOLDEN/ALTREF get a `NEWMV` search of their own.
84+pub(crate) const EXTRA_REF_NEW: [bool; 11] =
85+ [crate::encode::EXTRA_REF_NEW_MV, true, true, true, false, false, false, false, false, false, false];
86+
87+/// `encode::LEAF_COMPOUND`: a leaf is offered compound candidates.
88+pub(crate) const LEAF_COMPOUND: [bool; 11] =
89+ [crate::encode::LEAF_COMPOUND, true, false, false, false, false, false, false, false, false, false];
90+
91+/// `encode::REFERENCE_SELECT`: compound prediction at all.
92+pub(crate) const COMPOUND: [bool; 11] =
93+ [crate::encode::REFERENCE_SELECT, true, true, true, true, true, false, false, false, false, false];
94+
95+/// `encode::warp_on`: local warped motion.
96+pub(crate) const WARP: [bool; 11] =
97+ [true, true, true, false, false, false, false, false, false, false, false];
98+
99+/// `encode::tx_select_inter`: var-tx / tx-depth search inside inter frames.
100+pub(crate) const TX_SELECT_INTER: [bool; 11] =
101+ [true, true, true, true, true, false, false, false, false, false, false];
102+
103+/// `encode::tx32_depth_search`.
104+pub(crate) const TX32_DEPTH: [bool; 11] =
105+ [true, true, true, true, false, false, false, false, false, false, false];
106+
107+/// `encode::compound_var_tx`.
108+pub(crate) const COMPOUND_VAR_TX: [bool; 11] =
109+ [true, true, true, false, false, false, false, false, false, false, false];
110+
111+/// `encode::tx_select`: the KEY frame's transform-depth search.
112+pub(crate) const TX_SELECT_KEY: [bool; 11] =
113+ [true, true, true, true, true, true, true, false, false, false, false];
114+
115+/// `encode::PRUNE_TOP_K`: intra luma modes fully tried on a key frame.
116+pub(crate) const PRUNE_K: [Option<usize>; 11] = [
117+ crate::encode::PRUNE_TOP_K,
118+ None,
119+ Some(4),
120+ Some(4),
121+ Some(3),
122+ Some(3),
123+ Some(2),
124+ Some(2),
125+ Some(2),
126+ Some(1),
127+ Some(1),
128+];
129+
130+/// `encode::INTER_PRUNE_TOP_K`: the same for intra candidates inside an inter
131+/// frame.
132+pub(crate) const PRUNE_K_INTER: [Option<usize>; 11] = [
133+ crate::encode::INTER_PRUNE_TOP_K,
134+ Some(3),
135+ Some(3),
136+ Some(2),
137+ Some(2),
138+ Some(2),
139+ Some(1),
140+ Some(1),
141+ Some(1),
142+ Some(1),
143+ Some(1),
144+];
145+
146+/// `encode::CHROMA_TOP_K`: chroma modes fully tried.
147+pub(crate) const CHROMA_K: [Option<usize>; 11] = [
148+ crate::encode::CHROMA_TOP_K,
149+ Some(4),
150+ Some(3),
151+ Some(3),
152+ Some(2),
153+ Some(2),
154+ Some(2),
155+ Some(1),
156+ Some(1),
157+ Some(1),
158+ Some(1),
159+];
160+
161+/// `encode::angle_delta_on`: refining a directional intra winner's delta.
162+pub(crate) const ANGLE: [bool; 11] =
163+ [true, true, true, true, false, false, false, false, false, false, false];
164+
165+/// `encode::cfl_on`: chroma-from-luma in the chroma search.
166+pub(crate) const CFL: [bool; 11] =
167+ [true, true, true, true, true, false, false, false, false, false, false];
168+
169+/// `encode::RESTORATION`: the loop-restoration (Wiener) search.
170+pub(crate) const RESTORATION: [bool; 11] =
171+ [crate::encode::RESTORATION, true, true, true, true, false, false, false, false, false, false];
172+
173+/// `encode::TPL_DEPTH`: lookahead pictures the lambda map reads (1 = off).
174+pub(crate) const TPL_DEPTH: [usize; 11] = [crate::encode::TPL_DEPTH, 8, 8, 4, 4, 2, 1, 1, 1, 1, 1];
175+
176+/// `filter_search`: whether the deblock ladder's +-1/+-2 refinement stage runs.
177+pub(crate) const DEBLOCK_REFINE: [bool; 11] =
178+ [true, true, true, true, true, false, false, false, false, false, false];
179+
180+/// `filter_search`: whether chroma gets a deblock stage of its own.
181+pub(crate) const DEBLOCK_CHROMA: [bool; 11] =
182+ [true, true, true, true, true, true, false, false, false, false, false];
183+
184+/// `filter_search`: how many of `CDEF_PRI` / `CDEF_SEC` each CDEF stage tries
185+/// (0 = no CDEF search at all, the frame keeps strength 0 = deblock only).
186+pub(crate) const CDEF_STRENGTHS: [usize; 11] = [5, 5, 5, 5, 3, 3, 3, 2, 2, 0, 0];
187+
188+/// `filter_search`: how many extra per-superblock CDEF presets the header may
189+/// carry beyond the frame winner (0 = `cdef_bits` 0).
190+pub(crate) const CDEF_PRESETS: [usize; 11] = [7, 7, 7, 7, 7, 3, 3, 0, 0, 0, 0];
191+
192+/// What preset `n` switches off relative to speed 0, for a gate or a bench row
193+/// to print (class `gate-blind-to-feature`: a preset that silently disables
194+/// nothing is a preset that buys nothing).
195+#[must_use]
196+pub fn levers(n: u8) -> Vec<String> {
197+ let n = usize::from(n.min(MAX_SPEED));
198+ let mut out = Vec::new();
199+ let mut flag = |name: &str, t: &[bool; 11]| {
200+ if !t[n] {
201+ out.push(format!("no {name}"));
202+ }
203+ };
204+ flag("8x8 split", &SPLIT_8);
205+ flag("32x32 split (32x32-only partitions)", &SPLIT_INTER);
206+ flag("leaf second-reference search", &LEAF_SECOND);
207+ flag("extra-reference NEWMV", &EXTRA_REF_NEW);
208+ flag("leaf compound", &LEAF_COMPOUND);
209+ flag("compound", &COMPOUND);
210+ flag("warp", &WARP);
211+ flag("inter var-tx/tx-depth", &TX_SELECT_INTER);
212+ flag("32x32 tx depth", &TX32_DEPTH);
213+ flag("compound var-tx", &COMPOUND_VAR_TX);
214+ flag("key tx-depth", &TX_SELECT_KEY);
215+ flag("angle delta", &ANGLE);
216+ flag("CfL", &CFL);
217+ flag("loop restoration", &RESTORATION);
218+ flag("deblock refine", &DEBLOCK_REFINE);
219+ flag("chroma deblock stage", &DEBLOCK_CHROMA);
220+ if SPLIT_RD[n] > SPLIT_RD[0] {
221+ out.push(format!("split-RD breakout {}", SPLIT_RD[n]));
222+ }
223+ if SPLIT_BREAKOUT[n] > 0 {
224+ out.push(format!("coeff breakout {}", SPLIT_BREAKOUT[n]));
225+ }
226+ if PRUNE_K[n] != PRUNE_K[0] {
227+ out.push(format!("intra top-{}", PRUNE_K[n].unwrap_or(13)));
228+ }
229+ if PRUNE_K_INTER[n] != PRUNE_K_INTER[0] {
230+ out.push(format!("inter-intra top-{}", PRUNE_K_INTER[n].unwrap_or(13)));
231+ }
232+ if CHROMA_K[n] != CHROMA_K[0] {
233+ out.push(format!("chroma top-{}", CHROMA_K[n].unwrap_or(7)));
234+ }
235+ if TPL_DEPTH[n] != TPL_DEPTH[0] {
236+ out.push(if TPL_DEPTH[n] <= 1 {
237+ "no tpl".to_string()
238+ } else {
239+ format!("tpl depth {}", TPL_DEPTH[n])
240+ });
241+ }
242+ if CDEF_STRENGTHS[n] == 0 {
243+ out.push("no CDEF search".to_string());
244+ } else if CDEF_STRENGTHS[n] != CDEF_STRENGTHS[0] {
245+ out.push(format!("CDEF {} strengths", CDEF_STRENGTHS[n]));
246+ }
247+ if CDEF_PRESETS[n] != CDEF_PRESETS[0] {
248+ out.push(format!("CDEF presets {}", CDEF_PRESETS[n]));
249+ }
250+ out
251+}
252+
253+#[cfg(test)]
254+mod tests {
255+ use super::*;
256+
257+ /// Speed 0 must be every lever's shipped default -- the byte pins are the
258+ /// pin on that, and this is the cheap statement of the same rule.
259+ #[test]
260+ fn speed_zero_disables_nothing() {
261+ assert!(levers(0).is_empty(), "{:?}", levers(0));
262+ assert_eq!(SPLIT_RD[0], 0.125);
263+ assert_eq!(SPLIT_BREAKOUT[0], 0);
264+ assert_eq!(TPL_DEPTH[0], 8);
265+ assert_eq!(PRUNE_K[0], None);
266+ assert_eq!(PRUNE_K_INTER[0], Some(3));
267+ assert_eq!(CHROMA_K[0], None);
268+ assert_eq!(CDEF_STRENGTHS[0], 5);
269+ }
270+
271+ /// Every preset switches off something the one below it did not, and the
272+ /// monotone levers never come back on.
273+ #[test]
274+ fn presets_are_monotone_in_speed() {
275+ for n in 1..=MAX_SPEED {
276+ let (a, b) = (levers(n - 1), levers(n));
277+ assert!(b.len() >= a.len(), "speed {n} loosens: {a:?} -> {b:?}");
278+ assert!(SPLIT_RD[n as usize] >= SPLIT_RD[n as usize - 1]);
279+ assert!(TPL_DEPTH[n as usize] <= TPL_DEPTH[n as usize - 1]);
280+ assert!(CDEF_STRENGTHS[n as usize] <= CDEF_STRENGTHS[n as usize - 1]);
281+ }
282+ assert!(!levers(MAX_SPEED).is_empty());
283+ }
284+}
lanes/bd-speed0.logadded+11 -0
@@ -0,0 +1,11 @@
1+
2+running 1 test
3+test encode::tests::bd_rate_screen_native ...
4+native crop, 12 frames, gop=12; tiles (0, 0), tile threads 1, intrabc false, palette maxcolors 128
5+| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |
6+|---|---|---|---|---|
7+bars 1080p: sequence, pyramid requested Some(Pyramid { mini_gop: 4, arf_q_offset: -16, leaf_q_offset: 8 }) effective Some(Pyramid { mini_gop: 4, arf_q_offset: -16, leaf_q_offset: 8 })
8+bars 1080p: pricer armings default=17 real=183
9+bars 1080p: motion_mode 32x32 SIMPLE=77834 OBMC=0 WARP=160 | 16x16 SIMPLE=3194 OBMC=0 WARP=261 | 8x8 SIMPLE=13280 OBMC=0 WARP=1286 (0.0% OBMC / 1.8% WARP of 96015 eligible)
10+bars 1080p: inter var-tx depths of 11770 blocks -- leaf single 0=1311 1=691 (34.5% split) | leaf compound 0=1242 1=694 (35.8% split) | 32x32 single 0=968 1=2080 (68.2% split) | 32x32 compound 0=2438 1=2346 (49.0% split)
11+bars 1080p: screen frames on=0 off=4 (0.0% on); palette blocks luma 0 chroma 0; intrabc blocks 0 (searched 0 / valid 0 / won 0)
lanes/bd-speed3.logadded+11 -0
@@ -0,0 +1,11 @@
1+
2+running 1 test
3+test encode::tests::bd_rate_screen_native ...
4+native crop, 12 frames, gop=12; tiles (0, 0), tile threads 1, intrabc false, palette maxcolors 128
5+| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |
6+|---|---|---|---|---|
7+bars 1080p: sequence, pyramid requested Some(Pyramid { mini_gop: 4, arf_q_offset: -16, leaf_q_offset: 8 }) effective Some(Pyramid { mini_gop: 4, arf_q_offset: -16, leaf_q_offset: 8 })
8+bars 1080p: pricer armings default=16 real=170
9+bars 1080p: motion_mode 32x32 SIMPLE=0 OBMC=0 WARP=0 | 16x16 SIMPLE=0 OBMC=0 WARP=0 | 8x8 SIMPLE=0 OBMC=0 WARP=0 (0.0% OBMC / 0.0% WARP of 0 eligible)
10+bars 1080p: inter var-tx depths of 5684 blocks -- leaf single 0=1423 1=794 (35.8% split) | leaf compound 0=0 1=0 (0.0% split) | 32x32 single 0=1099 1=2368 (68.3% split) | 32x32 compound 0=0 1=0 (0.0% split)
11+bars 1080p: screen frames on=0 off=4 (0.0% on); palette blocks luma 0 chroma 0; intrabc blocks 0 (searched 0 / valid 0 / won 0)
lanes/bd-speed6.logadded+11 -0
@@ -0,0 +1,11 @@
1+
2+running 1 test
3+test encode::tests::bd_rate_screen_native ...
4+native crop, 12 frames, gop=12; tiles (0, 0), tile threads 1, intrabc false, palette maxcolors 128
5+| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |
6+|---|---|---|---|---|
7+bars 1080p: sequence, pyramid requested Some(Pyramid { mini_gop: 4, arf_q_offset: -16, leaf_q_offset: 8 }) effective Some(Pyramid { mini_gop: 4, arf_q_offset: -16, leaf_q_offset: 8 })
8+bars 1080p: pricer armings default=12 real=141
9+bars 1080p: motion_mode 32x32 SIMPLE=0 OBMC=0 WARP=0 | 16x16 SIMPLE=0 OBMC=0 WARP=0 | 8x8 SIMPLE=0 OBMC=0 WARP=0 (0.0% OBMC / 0.0% WARP of 0 eligible)
10+bars 1080p: inter var-tx depths of 0 blocks -- leaf single 0=0 1=0 (0.0% split) | leaf compound 0=0 1=0 (0.0% split) | 32x32 single 0=0 1=0 (0.0% split) | 32x32 compound 0=0 1=0 (0.0% split)
11+bars 1080p: screen frames on=0 off=4 (0.0% on); palette blocks luma 0 chroma 0; intrabc blocks 0 (searched 0 / valid 0 / won 0)
tools/ec-bench/src/main.rsmodified+26 -4
@@ -524,6 +524,15 @@ fn bench_av1_encode(rows: &mut Vec<Row>) {
524524 Some((cols, f.next().and_then(|v| v.parse().ok()).unwrap_or(0)))
525525 })
526526 .unwrap_or((0, 0));
527+ // One row per SPEED PRESET (`ec_av1::speed`): 0 is the full search every
528+ // byte pin carries, 10 the fastest. `EC_AV1_SPEED=<n>` benches a single
529+ // preset instead of the ladder.
530+ let presets: Vec<u8> = match std::env::var("EC_AV1_SPEED").ok().and_then(|v| v.parse().ok()) {
531+ Some(n) => vec![n],
532+ None => vec![0, 3, 6, 10],
533+ };
534+ let mut first_stream = Vec::new();
535+ for &speed in &presets {
527536 let cfg = Av1Config {
528537 width: w as usize,
529538 height: h as usize,
@@ -540,8 +549,9 @@ fn bench_av1_encode(rows: &mut Vec<Row>) {
540549 // shape of it. The `hidden` column below is how many frames of the row
541550 // were coded ahead of their display position.
542551 let pyramid = Pyramid::from_env();
552+ ec_av1::speed::set_speed(speed);
543553 let mut enc = match pyramid {
544- None => Av1Encoder::new(cfg).expect("av1 encoder"),
554+ None => Av1Encoder::with_speed(cfg, speed).expect("av1 encoder"),
545555 Some(p) => Av1Encoder::with_pyramid(cfg, p).expect("av1 encoder"),
546556 };
547557 let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize;
@@ -579,20 +589,32 @@ fn bench_av1_encode(rows: &mut Vec<Row>) {
579589 (None, None) => "flat".to_string(),
580590 };
581591 let media_s = n as f64 / 30.0;
592+ let levers = match ec_av1::speed::levers(speed) {
593+ v if v.is_empty() => "full search".to_string(),
594+ v => v.join(", "),
595+ };
582596 let fps = if wall > 0.0 { f64::from(n) / wall } else { 0.0 };
583597 let bytes_per_frame = stream.len() as f64 / f64::from(n);
584598 rows.push(Row {
585599 component: "ec-av1",
586600 direction: "encode",
587601 content: format!(
588- "{w}x{h}, {n} frames, gop=10, {coded_under}, {hidden} hidden, {fps:.1} fps, \
589- {bytes_per_frame:.0} B/frame"
602+ "speed {speed} [{levers}], {w}x{h}, {n} frames, gop=10, {coded_under}, \
603+ {hidden} hidden, {fps:.1} fps, {bytes_per_frame:.0} B/frame"
590604 ),
591605 media: format!("{media_s:.1}s"),
592606 wall_ms: wall * 1000.0,
593607 rtf: (wall > 0.0).then_some(media_s / wall),
594608 });
595-
609+ if first_stream.is_empty() {
610+ first_stream = stream;
611+ }
612+ }
613+ // The decode row reads the FIRST preset's stream, so the number stays
614+ // comparable across runs of this bench.
615+ ec_av1::speed::set_speed(0);
616+ let stream = first_stream;
617+ let media_s = n as f64 / 30.0;
596618 let start = Instant::now();
597619 let pictures = ec_av1::stream::decode_stream(&stream).expect("av1 decode_stream");
598620 let wall = start.elapsed().as_secs_f64();