diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index e9a2fe62..37f27c23 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -206,7 +206,7 @@ pub(crate) fn take_predicted_bits() -> Vec { } /// Whether a 16x16 inter leaf may split into four 8x8 ones of its own. -const SPLIT_INTER_8: bool = true; +pub(crate) const SPLIT_INTER_8: bool = true; /// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build. /// Whether a key frame codes `tx_mode == TxMode::Select` and searches each @@ -223,41 +223,39 @@ const SPLIT_INTER_8: bool = true; /// third, for 13% encode wall. `EC_AV1_TX_SELECT_INTER=0` turns it off for an /// A/B on one build. fn tx_select_inter() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| { - !matches!( - std::env::var("EC_AV1_TX_SELECT_INTER").as_deref(), - Ok("0") | Ok("off") - ) - }) + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_TX_SELECT_INTER") + .ok() + .map(|v| !matches!(v.as_str(), "0" | "off")) + }); + ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_INTER)) } fn tx_select() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| { - !matches!( - std::env::var("EC_AV1_TX_SELECT").as_deref(), - Ok("0") | Ok("off") - ) - }) + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_TX_SELECT") + .ok() + .map(|v| !matches!(v.as_str(), "0" | "off")) + }); + ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_KEY)) } fn split_inter_8() -> bool { match std::env::var("EC_AV1_SPLIT_INTER8").ok() { Some(v) if cfg!(test) => v != "0", - _ => SPLIT_INTER_8, + _ => crate::speed::at(&crate::speed::SPLIT_8), } } /// Whether a 16x16 (or 8x8) leaf runs a motion search of its own beside the /// NEARESTMV candidate it always had. -const LEAF_NEW_MV: bool = true; +pub(crate) const LEAF_NEW_MV: bool = true; /// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the /// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0 /// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion /// searches (the census `bd_rate_vs_libaom_and_rav1e` prints). -const EXTRA_REF_NEW_MV: bool = true; +pub(crate) const EXTRA_REF_NEW_MV: bool = true; /// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's /// own best vector before that reference's `NEWMV` search is skipped: a @@ -334,7 +332,7 @@ fn leaf_second_new_margin() -> f64 { fn leaf_second_new_mv() -> bool { match std::env::var("EC_AV1_LEAF_SECOND_NEWMV").ok() { Some(v) => v != "0", - None => true, + None => crate::speed::at(&crate::speed::LEAF_SECOND), } } @@ -343,13 +341,13 @@ fn leaf_second_new_mv() -> bool { /// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both /// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what /// was missing was the encoder ever forming one below 32x32. -const LEAF_COMPOUND: bool = true; +pub(crate) const LEAF_COMPOUND: bool = true; /// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build. fn leaf_compound() -> bool { match std::env::var("EC_AV1_LEAF_COMPOUND").ok() { Some(v) => v != "0", - None => LEAF_COMPOUND, + None => crate::speed::at(&crate::speed::LEAF_COMPOUND), } } @@ -366,7 +364,7 @@ fn leaf_new_mv() -> bool { /// the true frame edge cut through was ever split there; inside the frame /// every block was coded whole, which left the partition decision the key /// frame already makes unmade for eleven frames out of twelve. -const SPLIT_INTER_BLOCKS: bool = true; +pub(crate) const SPLIT_INTER_BLOCKS: bool = true; /// [`SPLIT_INTER_BLOCKS`], or what `EC_AV1_SPLIT_INTER` names when the /// measurement that keeps it is running (test builds only, like @@ -374,7 +372,7 @@ const SPLIT_INTER_BLOCKS: bool = true; fn split_inter_blocks() -> bool { match std::env::var("EC_AV1_SPLIT_INTER").ok() { Some(v) if cfg!(test) => v != "0", - _ => SPLIT_INTER_BLOCKS, + _ => crate::speed::at(&crate::speed::SPLIT_INTER), } } @@ -382,13 +380,13 @@ fn split_inter_blocks() -> bool { /// Wiener filter per 64x64 luma restoration unit, picked from /// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a /// test build, like [`lambda_scale`]. -const RESTORATION: bool = true; +pub(crate) const RESTORATION: bool = true; /// [`RESTORATION`], or what `EC_AV1_LR` names in a test build. fn restoration_enabled() -> bool { match std::env::var("EC_AV1_LR").ok() { Some(v) if cfg!(test) => v != "0", - _ => RESTORATION, + _ => crate::speed::at(&crate::speed::RESTORATION), } } @@ -405,7 +403,7 @@ fn restoration_enabled() -> bool { /// +31.7/+40.6/+27.8, for barely more speed. The split trial is where this /// encoder's inter quality lives, so `0` ships and the knob stays for a /// future explicit speed preset. -const SPLIT_BREAKOUT_COEFFS: usize = 0; +pub(crate) 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 @@ -431,17 +429,14 @@ const SPLIT_BREAKOUT_COEFFS: usize = 0; /// +51.3/-14.2 (the 1080p film 0.2 worse for a finer search) and 0.25 is /// +16.6/-0.6, +46.9/+19.1, +51.6/-14.5 (screen 0.3 worse vs libaom, 3s off /// the screen wall). Neither clears the keep rule; 0.125 stays. -const SPLIT_RD_THRESHOLD: f64 = 0.125; +pub(crate) 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) - }) + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_SPLIT_RD").ok().and_then(|v| v.parse().ok()) + }); + ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::SPLIT_RD)) } /// 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 { fn split_breakout_coeffs() -> usize { match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() { Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS), - _ => SPLIT_BREAKOUT_COEFFS, + _ => crate::speed::at(&crate::speed::SPLIT_BREAKOUT), } } @@ -2811,10 +2806,10 @@ impl Reach { /// [`warp_prediction`]); `EC_AV1_WARP=0` turns the tool -- and the two header /// bits -- back off for an A/B on one build. pub(crate) fn warp_on() -> bool { - static ON: std::sync::LazyLock = std::sync::LazyLock::new(|| { - !matches!(crate::envflags::var("EC_AV1_WARP").as_deref(), Ok("0") | Ok("off")) + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_WARP").ok().map(|v| !matches!(v.as_str(), "0" | "off")) }); - *ON + ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::WARP)) } /// 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] = /// residual to reach there -- the tool was being judged on content that /// cannot pay for it (class `gate-blind-to-feature`). `EC_AV1_TX32_DEPTH`. fn tx32_depth_search() -> bool { - static ON: std::sync::LazyLock = std::sync::LazyLock::new(|| { - !matches!(crate::envflags::var("EC_AV1_TX32_DEPTH").as_deref(), Ok("0") | Ok("off")) + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_TX32_DEPTH").ok().map(|v| !matches!(v.as_str(), "0" | "off")) }); - *ON + ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX32_DEPTH)) } /// Whether a COMPOUND inter winner is offered the var-tx split at all: its @@ -3139,10 +3134,10 @@ fn tx32_depth_search() -> bool { /// 32x32 depth search); `EC_AV1_COMP_VARTX=0` turns it off. /// `EC_AV1_COMP_VARTX`. fn compound_var_tx() -> bool { - static ON: std::sync::LazyLock = std::sync::LazyLock::new(|| { - !matches!(crate::envflags::var("EC_AV1_COMP_VARTX").as_deref(), Ok("0") | Ok("off")) + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_COMP_VARTX").ok().map(|v| !matches!(v.as_str(), "0" | "off")) }); - *ON + ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::COMPOUND_VAR_TX)) } /// 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] { /// Whether the luma search refines a directional winner's `angle_delta_y` /// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair). fn angle_delta_on() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("EC_AV1_ANGLE").as_deref() != Ok("0")) + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0") + }); + ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE)) } /// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0` /// switches it off, which is how the lane measured its own on/off pair). fn cfl_on() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("EC_AV1_CFL").as_deref() != Ok("0")) + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_CFL").ok().map(|v| v != "0") + }); + ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CFL)) } /// 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] { /// 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, - }) + static ENV: std::sync::LazyLock>> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_CHROMA_K") + .ok() + .map(|v| v.parse::().ok().filter(|&k| k > 0)) + }); + ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CHROMA_K)) } /// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD @@ -4170,7 +4170,7 @@ fn chroma_top_k() -> Option { /// RE-MEASURED on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on: /// K=4 is +17.1/-0.1, +47.1/+19.2, +51.6/-13.8 against the base's /// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3 -- every row worse. Still `None`. -const CHROMA_TOP_K: Option = None; +pub(crate) const CHROMA_TOP_K: Option = None; fn search_chroma( chroma: &mut [Plane; 2], @@ -5458,7 +5458,7 @@ fn prune_top_k() -> Option { .and_then(|v| v.parse::().ok()); match swept { Some(k) if cfg!(test) => Some(k), - _ => PRUNE_TOP_K, + _ => crate::speed::at(&crate::speed::PRUNE_K), } } @@ -5478,7 +5478,7 @@ fn set_test_top_k_override(value: Option) { /// The default: unpruned, thirteen full trials per block, same as before this /// lever. Set from the sweep in the lane report if the quality gate clears it. -const PRUNE_TOP_K: Option = None; +pub(crate) const PRUNE_TOP_K: Option = None; /// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop -- /// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths' @@ -5497,7 +5497,7 @@ fn prune_top_k_inter() -> Option { .and_then(|v| v.parse::().ok()); match swept { Some(k) if cfg!(test) => Some(k), - _ => INTER_PRUNE_TOP_K, + _ => crate::speed::at(&crate::speed::PRUNE_K_INTER), } } @@ -5521,7 +5521,7 @@ fn set_test_top_k_override_inter(value: Option) { /// `K=3`, ships as default. Unlike the key-frame path (still `None`), an /// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so /// pruning them costs less quality here. -const INTER_PRUNE_TOP_K: Option = Some(3); +pub(crate) const INTER_PRUNE_TOP_K: Option = Some(3); // Per-thread nanosecond counters `stage_timing_breakdown_inter` (and // [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an @@ -6835,7 +6835,7 @@ fn mv_component_bits(diff: i32) -> Option { fn extra_ref_new_mv() -> bool { match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() { Some(v) if cfg!(test) => v != "0", - _ => EXTRA_REF_NEW_MV, + _ => crate::speed::at(&crate::speed::EXTRA_REF_NEW), } } @@ -6861,13 +6861,13 @@ pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) /// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate /// runs as), and every block still codes SINGLE, so the only cost is one /// `comp_mode` symbol per inter block. -const REFERENCE_SELECT: bool = true; +pub(crate) const REFERENCE_SELECT: bool = true; /// [`REFERENCE_SELECT`], with the test-build environment override. pub(crate) fn reference_select() -> bool { match std::env::var("EC_AV1_COMPOUND").ok() { Some(v) if cfg!(test) => v != "0", - _ => REFERENCE_SELECT, + _ => crate::speed::at(&crate::speed::COMPOUND), } } @@ -8040,7 +8040,7 @@ fn tpl_strength() -> f64 { /// The streaming facade holds `depth - 1` pictures back so it feeds /// `encode_inter_frame` the same window `encode_sequence` does; both read /// THIS function, so the two paths cannot disagree about the window. -const TPL_DEPTH: usize = 8; +pub(crate) const TPL_DEPTH: usize = 8; /// The exponent the dependence ratio is read through ([`tpl_lambda_factors`]). /// 0.5 is libaom's own square-root compression of its dependence ratio. @@ -8112,7 +8112,7 @@ pub(crate) fn tpl_depth() -> usize { .ok() .and_then(|v| v.parse::().ok()) .filter(|d| *d >= 1) - .unwrap_or(TPL_DEPTH) + .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_DEPTH)) .max(1) } diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index caf72aa3..89c8a34b 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -659,6 +659,24 @@ const _: fn() = || { }; impl Av1Encoder { + /// [`Av1Encoder::new`] at a SPEED PRESET (`speed` 0..=10, rav1e's scale: + /// 0 is the full search this encoder has always run and is byte for byte + /// identical to [`Av1Encoder::new`]; higher presets switch search levers + /// off, [`crate::speed::levers`] naming which). + /// + /// The preset is process-global (the tile search reads it from worker + /// threads -- see [`crate::speed`]), so it is set here for every encode + /// that follows on this process, and two encoders at different speeds + /// must not run concurrently. `EC_AV1_SPEED=` is the same knob for a + /// caller that does not construct the encoder itself. + /// + /// # Errors + /// [`Av1Encoder::new`]'s. + pub fn with_speed(config: EncoderConfig, speed: u8) -> Result { + crate::speed::set_speed(speed); + Self::new(config) + } + /// # Errors /// Returns an error when `config.width`/`config.height` are zero, odd, /// or larger than the 16-bit frame size an AV1 sequence header carries, diff --git a/crates/ec-av1/src/filter_search.rs b/crates/ec-av1/src/filter_search.rs index d2e94a5d..0e398bae 100644 --- a/crates/ec-av1/src/filter_search.rs +++ b/crates/ec-av1/src/filter_search.rs @@ -291,15 +291,29 @@ pub(crate) fn pick_filters( .filter_map(|d| u8::try_from(i32::from(best.lf.0) + d).ok()) .filter(|&l| l <= 63) .collect(); - stage(&mut best, &refine, |c, v| c.lf = (v, v), |t| t.sse_y, &mut st)?; + // Which of these stages run is the SPEED PRESET's filter-search lever + // (`crate::speed`): each stage costs one whole-frame decode per candidate + // it has not seen, and the filter search is 19-28% of the encoder's wall. + // At speed 0 every table below reads its shipped value, so the sequence is + // the one this function always ran. + if crate::speed::at(&crate::speed::DEBLOCK_REFINE) { + stage(&mut best, &refine, |c, v| c.lf = (v, v), |t| t.sse_y, &mut st)?; + } // Deblocking chroma, three points around the luma winner. - let chroma_levels = [0, best.lf.0 / 2, best.lf.0]; - stage(&mut best, &chroma_levels, |c, v| c.lf.1 = v, |t| t.sse_uv, &mut st)?; + if crate::speed::at(&crate::speed::DEBLOCK_CHROMA) { + let chroma_levels = [0, best.lf.0 / 2, best.lf.0]; + stage(&mut best, &chroma_levels, |c, v| c.lf.1 = v, |t| t.sse_uv, &mut st)?; + } // CDEF, primary then secondary, luma on luma error and chroma on chroma. - stage(&mut best, &CDEF_PRI, |c, v| c.y.0 = v, |t| t.sse_y, &mut st)?; - stage(&mut best, &CDEF_SEC, |c, v| c.y.1 = v, |t| t.sse_y, &mut st)?; - stage(&mut best, &CDEF_PRI, |c, v| c.uv.0 = v, |t| t.sse_uv, &mut st)?; - stage(&mut best, &CDEF_SEC, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut st)?; + // `n == 0` leaves every strength at 0, i.e. deblocking only. + let n = crate::speed::at(&crate::speed::CDEF_STRENGTHS); + if n > 0 { + let (pri, sec) = (&CDEF_PRI[..n.min(CDEF_PRI.len())], &CDEF_SEC[..n.min(CDEF_SEC.len())]); + stage(&mut best, pri, |c, v| c.y.0 = v, |t| t.sse_y, &mut st)?; + stage(&mut best, sec, |c, v| c.y.1 = v, |t| t.sse_y, &mut st)?; + stage(&mut best, pri, |c, v| c.uv.0 = v, |t| t.sse_uv, &mut st)?; + stage(&mut best, sec, |c, v| c.uv.1 = v, |t| t.sse_uv, &mut st)?; + } CHOSEN.with(|c| c.borrow_mut().push(best)); let trials = st.trials; @@ -342,7 +356,12 @@ pub(crate) fn pick_filters( } let mut order: Vec = (0..pool.len()).collect(); order.sort_by_key(|&i| std::cmp::Reverse(counts[i])); - presets.extend(order.iter().take(7).map(|&i| pool[i])); + presets.extend( + order + .iter() + .take(crate::speed::at(&crate::speed::CDEF_PRESETS)) + .map(|&i| pool[i]), + ); // The cheapest list length: `bits` costs one literal per superblock plus // twelve header bits per extra pair, and buys whatever per-unit error the // wider choice removes. diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index 4ff9d097..37bea30a 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -46,6 +46,7 @@ pub mod obu; mod par; pub mod quant; mod refusal_inventory; +pub mod speed; mod restoration; pub mod sequence; mod superres; diff --git a/crates/ec-av1/src/speed.rs b/crates/ec-av1/src/speed.rs new file mode 100644 index 00000000..add28ff4 --- /dev/null +++ b/crates/ec-av1/src/speed.rs @@ -0,0 +1,284 @@ +//! The encoder's SPEED PRESET axis (lane-av1fast): one number, 0..=10 like +//! rav1e's `--speed`, that picks a default for every search lever this crate +//! already has a knob for. +//! +//! Speed 0 is today's search, byte for byte -- every table below reads its +//! shipped default at index 0, so `encoder::tests`' byte pins are the pin on +//! that. Higher speeds trade BD-rate for wall by switching off the levers in +//! [`levers`], each of which was already measured on its own (the doc comment +//! on each knob in [`crate::encode`] carries its sweep). +//! +//! The value is PROCESS-GLOBAL, the same shape [`crate::par`]'s thread counts +//! use, because the levers are read from the tile-search worker threads -- +//! a thread-local would not reach them. One speed per process at a time: +//! [`crate::encoder::Av1Encoder::with_speed`] sets it at construction, so two +//! encoders at different speeds must not run concurrently in one process. +//! `EC_AV1_SPEED=` is the environment form the gates and `ec-bench` use. +//! Every individual `EC_AV1_*` lever override still wins over the preset. + +use std::sync::atomic::{AtomicU8, Ordering}; + +/// The highest preset. 10 is the fastest, as in rav1e. +pub const MAX_SPEED: u8 = 10; + +/// 255 = "not read yet"; the env read happens once and the value is a plain +/// atomic afterwards, so a caller can set it without touching the process +/// environment. +static SPEED: AtomicU8 = AtomicU8::new(u8::MAX); + +/// This process's speed preset, 0..=[`MAX_SPEED`]. +#[must_use] +pub fn speed() -> u8 { + match SPEED.load(Ordering::Relaxed) { + u8::MAX => { + let n = crate::envflags::var("EC_AV1_SPEED") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(0) + .min(MAX_SPEED); + SPEED.store(n, Ordering::Relaxed); + n + } + n => n, + } +} + +/// Sets the preset for everything encoded afterwards in this process. +pub fn set_speed(n: u8) { + SPEED.store(n.min(MAX_SPEED), Ordering::Relaxed); +} + +/// `TABLE[speed()]`, the shape every lever below is read through. +pub(crate) fn at(table: &[T; 11]) -> T { + table[speed() as usize] +} + +// --------------------------------------------------------------------------- +// The lever tables. Index 0 of each is the shipped default of the constant +// named in the comment; the rest is this lane's composition (see the report +// table for what each step measured). +// --------------------------------------------------------------------------- + +/// `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] = + [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]; + +/// `encode::SPLIT_BREAKOUT_COEFFS`: libaom's coefficient-count breakout. +pub(crate) const SPLIT_BREAKOUT: [usize; 11] = [crate::encode::SPLIT_BREAKOUT_COEFFS, 0, 0, 0, 0, 0, 1, 1, 2, 4, 4]; + +/// `encode::SPLIT_INTER_8`: a 16x16 leaf may split into four 8x8 ones. +pub(crate) const SPLIT_8: [bool; 11] = + [crate::encode::SPLIT_INTER_8, true, true, true, false, false, false, false, false, false, false]; + +/// `encode::SPLIT_INTER_BLOCKS`: a 32x32 inter block may split at all +/// (`false` = 32x32-only partitioning). +pub(crate) const SPLIT_INTER: [bool; 11] = + [crate::encode::SPLIT_INTER_BLOCKS, true, true, true, true, true, true, true, false, false, false]; + +/// `encode::leaf_second_new_mv`: a leaf searches its SECOND reference. +pub(crate) const LEAF_SECOND: [bool; 11] = + [true, true, true, false, false, false, false, false, false, false, false]; + +/// `encode::EXTRA_REF_NEW_MV`: GOLDEN/ALTREF get a `NEWMV` search of their own. +pub(crate) const EXTRA_REF_NEW: [bool; 11] = + [crate::encode::EXTRA_REF_NEW_MV, true, true, true, false, false, false, false, false, false, false]; + +/// `encode::LEAF_COMPOUND`: a leaf is offered compound candidates. +pub(crate) const LEAF_COMPOUND: [bool; 11] = + [crate::encode::LEAF_COMPOUND, true, false, false, false, false, false, false, false, false, false]; + +/// `encode::REFERENCE_SELECT`: compound prediction at all. +pub(crate) const COMPOUND: [bool; 11] = + [crate::encode::REFERENCE_SELECT, true, true, true, true, true, false, false, false, false, false]; + +/// `encode::warp_on`: local warped motion. +pub(crate) const WARP: [bool; 11] = + [true, true, true, false, false, false, false, false, false, false, false]; + +/// `encode::tx_select_inter`: var-tx / tx-depth search inside inter frames. +pub(crate) const TX_SELECT_INTER: [bool; 11] = + [true, true, true, true, true, false, false, false, false, false, false]; + +/// `encode::tx32_depth_search`. +pub(crate) const TX32_DEPTH: [bool; 11] = + [true, true, true, true, false, false, false, false, false, false, false]; + +/// `encode::compound_var_tx`. +pub(crate) const COMPOUND_VAR_TX: [bool; 11] = + [true, true, true, false, false, false, false, false, false, false, false]; + +/// `encode::tx_select`: the KEY frame's transform-depth search. +pub(crate) const TX_SELECT_KEY: [bool; 11] = + [true, true, true, true, true, true, true, false, false, false, false]; + +/// `encode::PRUNE_TOP_K`: intra luma modes fully tried on a key frame. +pub(crate) const PRUNE_K: [Option; 11] = [ + crate::encode::PRUNE_TOP_K, + None, + Some(4), + Some(4), + Some(3), + Some(3), + Some(2), + Some(2), + Some(2), + Some(1), + Some(1), +]; + +/// `encode::INTER_PRUNE_TOP_K`: the same for intra candidates inside an inter +/// frame. +pub(crate) const PRUNE_K_INTER: [Option; 11] = [ + crate::encode::INTER_PRUNE_TOP_K, + Some(3), + Some(3), + Some(2), + Some(2), + Some(2), + Some(1), + Some(1), + Some(1), + Some(1), + Some(1), +]; + +/// `encode::CHROMA_TOP_K`: chroma modes fully tried. +pub(crate) const CHROMA_K: [Option; 11] = [ + crate::encode::CHROMA_TOP_K, + Some(4), + Some(3), + Some(3), + Some(2), + Some(2), + Some(2), + Some(1), + Some(1), + Some(1), + Some(1), +]; + +/// `encode::angle_delta_on`: refining a directional intra winner's delta. +pub(crate) const ANGLE: [bool; 11] = + [true, true, true, true, false, false, false, false, false, false, false]; + +/// `encode::cfl_on`: chroma-from-luma in the chroma search. +pub(crate) const CFL: [bool; 11] = + [true, true, true, true, true, false, false, false, false, false, false]; + +/// `encode::RESTORATION`: the loop-restoration (Wiener) search. +pub(crate) const RESTORATION: [bool; 11] = + [crate::encode::RESTORATION, true, true, true, true, false, false, false, false, false, false]; + +/// `encode::TPL_DEPTH`: lookahead pictures the lambda map reads (1 = off). +pub(crate) const TPL_DEPTH: [usize; 11] = [crate::encode::TPL_DEPTH, 8, 8, 4, 4, 2, 1, 1, 1, 1, 1]; + +/// `filter_search`: whether the deblock ladder's +-1/+-2 refinement stage runs. +pub(crate) const DEBLOCK_REFINE: [bool; 11] = + [true, true, true, true, true, false, false, false, false, false, false]; + +/// `filter_search`: whether chroma gets a deblock stage of its own. +pub(crate) const DEBLOCK_CHROMA: [bool; 11] = + [true, true, true, true, true, true, false, false, false, false, false]; + +/// `filter_search`: how many of `CDEF_PRI` / `CDEF_SEC` each CDEF stage tries +/// (0 = no CDEF search at all, the frame keeps strength 0 = deblock only). +pub(crate) const CDEF_STRENGTHS: [usize; 11] = [5, 5, 5, 5, 3, 3, 3, 2, 2, 0, 0]; + +/// `filter_search`: how many extra per-superblock CDEF presets the header may +/// carry beyond the frame winner (0 = `cdef_bits` 0). +pub(crate) const CDEF_PRESETS: [usize; 11] = [7, 7, 7, 7, 7, 3, 3, 0, 0, 0, 0]; + +/// What preset `n` switches off relative to speed 0, for a gate or a bench row +/// to print (class `gate-blind-to-feature`: a preset that silently disables +/// nothing is a preset that buys nothing). +#[must_use] +pub fn levers(n: u8) -> Vec { + let n = usize::from(n.min(MAX_SPEED)); + let mut out = Vec::new(); + let mut flag = |name: &str, t: &[bool; 11]| { + if !t[n] { + out.push(format!("no {name}")); + } + }; + flag("8x8 split", &SPLIT_8); + flag("32x32 split (32x32-only partitions)", &SPLIT_INTER); + flag("leaf second-reference search", &LEAF_SECOND); + flag("extra-reference NEWMV", &EXTRA_REF_NEW); + flag("leaf compound", &LEAF_COMPOUND); + flag("compound", &COMPOUND); + flag("warp", &WARP); + flag("inter var-tx/tx-depth", &TX_SELECT_INTER); + flag("32x32 tx depth", &TX32_DEPTH); + flag("compound var-tx", &COMPOUND_VAR_TX); + flag("key tx-depth", &TX_SELECT_KEY); + flag("angle delta", &ANGLE); + flag("CfL", &CFL); + flag("loop restoration", &RESTORATION); + flag("deblock refine", &DEBLOCK_REFINE); + flag("chroma deblock stage", &DEBLOCK_CHROMA); + if SPLIT_RD[n] > SPLIT_RD[0] { + out.push(format!("split-RD breakout {}", SPLIT_RD[n])); + } + if SPLIT_BREAKOUT[n] > 0 { + out.push(format!("coeff breakout {}", SPLIT_BREAKOUT[n])); + } + if PRUNE_K[n] != PRUNE_K[0] { + out.push(format!("intra top-{}", PRUNE_K[n].unwrap_or(13))); + } + if PRUNE_K_INTER[n] != PRUNE_K_INTER[0] { + out.push(format!("inter-intra top-{}", PRUNE_K_INTER[n].unwrap_or(13))); + } + if CHROMA_K[n] != CHROMA_K[0] { + out.push(format!("chroma top-{}", CHROMA_K[n].unwrap_or(7))); + } + if TPL_DEPTH[n] != TPL_DEPTH[0] { + out.push(if TPL_DEPTH[n] <= 1 { + "no tpl".to_string() + } else { + format!("tpl depth {}", TPL_DEPTH[n]) + }); + } + if CDEF_STRENGTHS[n] == 0 { + out.push("no CDEF search".to_string()); + } else if CDEF_STRENGTHS[n] != CDEF_STRENGTHS[0] { + out.push(format!("CDEF {} strengths", CDEF_STRENGTHS[n])); + } + if CDEF_PRESETS[n] != CDEF_PRESETS[0] { + out.push(format!("CDEF presets {}", CDEF_PRESETS[n])); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Speed 0 must be every lever's shipped default -- the byte pins are the + /// pin on that, and this is the cheap statement of the same rule. + #[test] + fn speed_zero_disables_nothing() { + assert!(levers(0).is_empty(), "{:?}", levers(0)); + assert_eq!(SPLIT_RD[0], 0.125); + assert_eq!(SPLIT_BREAKOUT[0], 0); + assert_eq!(TPL_DEPTH[0], 8); + assert_eq!(PRUNE_K[0], None); + assert_eq!(PRUNE_K_INTER[0], Some(3)); + assert_eq!(CHROMA_K[0], None); + assert_eq!(CDEF_STRENGTHS[0], 5); + } + + /// Every preset switches off something the one below it did not, and the + /// monotone levers never come back on. + #[test] + fn presets_are_monotone_in_speed() { + for n in 1..=MAX_SPEED { + let (a, b) = (levers(n - 1), levers(n)); + assert!(b.len() >= a.len(), "speed {n} loosens: {a:?} -> {b:?}"); + assert!(SPLIT_RD[n as usize] >= SPLIT_RD[n as usize - 1]); + assert!(TPL_DEPTH[n as usize] <= TPL_DEPTH[n as usize - 1]); + assert!(CDEF_STRENGTHS[n as usize] <= CDEF_STRENGTHS[n as usize - 1]); + } + assert!(!levers(MAX_SPEED).is_empty()); + } +} diff --git a/lanes/bd-speed0.log b/lanes/bd-speed0.log new file mode 100644 index 00000000..d055b39b --- /dev/null +++ b/lanes/bd-speed0.log @@ -0,0 +1,11 @@ + +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) | +|---|---|---|---|---| +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 }) +bars 1080p: pricer armings default=17 real=183 +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) +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) +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) diff --git a/lanes/bd-speed3.log b/lanes/bd-speed3.log new file mode 100644 index 00000000..2ccdef68 --- /dev/null +++ b/lanes/bd-speed3.log @@ -0,0 +1,11 @@ + +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) | +|---|---|---|---|---| +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 }) +bars 1080p: pricer armings default=16 real=170 +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) +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) +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) diff --git a/lanes/bd-speed6.log b/lanes/bd-speed6.log new file mode 100644 index 00000000..32a44a93 --- /dev/null +++ b/lanes/bd-speed6.log @@ -0,0 +1,11 @@ + +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) | +|---|---|---|---|---| +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 }) +bars 1080p: pricer armings default=12 real=141 +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) +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) +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) diff --git a/tools/ec-bench/src/main.rs b/tools/ec-bench/src/main.rs index 9ca14014..ac899377 100644 --- a/tools/ec-bench/src/main.rs +++ b/tools/ec-bench/src/main.rs @@ -524,6 +524,15 @@ fn bench_av1_encode(rows: &mut Vec) { Some((cols, f.next().and_then(|v| v.parse().ok()).unwrap_or(0))) }) .unwrap_or((0, 0)); + // One row per SPEED PRESET (`ec_av1::speed`): 0 is the full search every + // byte pin carries, 10 the fastest. `EC_AV1_SPEED=` benches a single + // preset instead of the ladder. + let presets: Vec = match std::env::var("EC_AV1_SPEED").ok().and_then(|v| v.parse().ok()) { + Some(n) => vec![n], + None => vec![0, 3, 6, 10], + }; + let mut first_stream = Vec::new(); + for &speed in &presets { let cfg = Av1Config { width: w as usize, height: h as usize, @@ -540,8 +549,9 @@ fn bench_av1_encode(rows: &mut Vec) { // shape of it. The `hidden` column below is how many frames of the row // were coded ahead of their display position. let pyramid = Pyramid::from_env(); + ec_av1::speed::set_speed(speed); let mut enc = match pyramid { - None => Av1Encoder::new(cfg).expect("av1 encoder"), + None => Av1Encoder::with_speed(cfg, speed).expect("av1 encoder"), Some(p) => Av1Encoder::with_pyramid(cfg, p).expect("av1 encoder"), }; 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) { (None, None) => "flat".to_string(), }; let media_s = n as f64 / 30.0; + let levers = match ec_av1::speed::levers(speed) { + v if v.is_empty() => "full search".to_string(), + v => v.join(", "), + }; let fps = if wall > 0.0 { f64::from(n) / wall } else { 0.0 }; let bytes_per_frame = stream.len() as f64 / f64::from(n); rows.push(Row { component: "ec-av1", direction: "encode", content: format!( - "{w}x{h}, {n} frames, gop=10, {coded_under}, {hidden} hidden, {fps:.1} fps, \ - {bytes_per_frame:.0} B/frame" + "speed {speed} [{levers}], {w}x{h}, {n} frames, gop=10, {coded_under}, \ + {hidden} hidden, {fps:.1} fps, {bytes_per_frame:.0} B/frame" ), media: format!("{media_s:.1}s"), wall_ms: wall * 1000.0, rtf: (wall > 0.0).then_some(media_s / wall), }); - + if first_stream.is_empty() { + first_stream = stream; + } + } + // The decode row reads the FIRST preset's stream, so the number stays + // comparable across runs of this bench. + ec_av1::speed::set_speed(0); + let stream = first_stream; + let media_s = n as f64 / 30.0; let start = Instant::now(); let pictures = ec_av1::stream::decode_stream(&stream).expect("av1 decode_stream"); let wall = start.elapsed().as_secs_f64();