From 5e19f1af98c5783008c159f89691b4e995665189 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 13 Sep 2026 05:29:44 +0300 Subject: [PATCH] perf(av1): the top ARF's leaf offer set behind EC_AV1_ARFMODE -- 1 no intra candidate at the 16x16/8x8 leaves (the intra trial's commit was always overwritten by the inter winner's, so the planes never change), 2 no RD-optional 8x8 split (16x16 is the leaf floor; the spec-forced 8x8s at straddling 16x16s are a different site), 4 no compound candidates at the leaves; the 32x32 whole keeps its full set as the scene-cut hatch; default 0 is bit-exact (pins 8291/33227 hold at the default and EC_AV1_SPEED=6); witness proves per-arm engagement counters, stream movement on a level-ramp fixture (middle group's ARF sits between its two anchors), coding-order stability and sample-exact decode through decode_stream AND ffmpeg --- crates/ec-av1/src/encode.rs | 117 +++++++++++++++++++++++++++++++++-- crates/ec-av1/src/encoder.rs | 93 ++++++++++++++++++++++++++++ crates/ec-av1/src/speed.rs | 20 ++++++ 3 files changed, 226 insertions(+), 4 deletions(-) diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index d50779a6..8845496d 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -6862,7 +6862,14 @@ fn code_square_inter( refs: &[Option<&Picture>; 8], fctx: &crate::decode::FrameCtx, ) -> (BlockCoeffs, f64) { - let (intra_block, intra_cost) = + // lane-arfmode: at the top ARF (arm 1) the leaf offers no intra + // candidate at all -- `intra_cost` stays at infinity, so every + // comparison below takes an inter candidate and the fallback arm at the + // tail is unreachable. The planes hold what the caller snapshotted until + // the winner commits: the intra trial used to commit here and be + // overwritten by the inter commit, so skipping it changes no committed + // sample, only work. + let (intra_block, intra_cost) = if search.arf_leaf_intra { code_square( luma, chroma, @@ -6874,7 +6881,11 @@ fn code_square_inter( None, false, fctx, - ); + ) + } else { + arfmode_hit(0); + (BlockCoeffs::default(), f64::INFINITY) + }; let luma_set = if side == 8 { TxbSet::Luma8Inter } else { @@ -7129,7 +7140,13 @@ fn code_square_inter( // SECOND-reference search of its own -- `NEAREST_NEWMV` and `NEW_NEWMV` // too. Priced with the same static-CDF approximation, plus the // compound-only syntax the writer emits. - for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound()) { + if leaf_compound() && !search.arf_leaf_compound && !compound.is_empty() { + // lane-arfmode: arm 4 drops this leaf's compound set (counted once + // per leaf, not once per pair); the single-reference candidates + // above stay. + arfmode_hit(2); + } + for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound() && search.arf_leaf_compound) { let (ref1, g) = (*ref1, *g); // The whole `comp_mode` + reference-pair tree at the writer's own // contexts, for THIS pair (lane-ctx). @@ -7762,6 +7779,72 @@ struct Search<'a> { /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every /// mode through full RD, unchanged from before this lever. top_k: Option, + /// lane-arfmode: the top ARF's leaf offer set ([`crate::speed::ARFMODE`]) + /// -- `false` cuts the named candidate group from the 16x16/8x8 LEAF + /// search ([`code_square_inter`]) and the 8x8 split offer at the top ARF + /// ([`DqLevel::TopArf`] frames only). `true` everywhere else, which is + /// the pre-lane behaviour: the key frame never reaches + /// [`code_square_inter`], the 32x32 whole keeps its full set, and the + /// straddling-edge 8x8s are only mode-gated, never partition-gated. + arf_leaf_intra: bool, + arf_leaf8: bool, + arf_leaf_compound: bool, +} + +/// [`Search`]'s ARF fields' source: [`crate::speed::ARFMODE`], or what +/// `EC_AV1_ARFMODE` names on one build (a missing or broken value keeps the +/// shipped table -- 0, bit-exact with the pre-lane encoder). +fn arfmode() -> u8 { + match ARFMODE_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { + u8::MAX => {} + n => return n, + } + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_ARFMODE").ok().and_then(|v| v.parse().ok()) + }); + ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ARFMODE)) +} + +/// [`ARFMODE_OVERRIDE`]: `u8::MAX` clears it. +static ARFMODE_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX); + +/// Sets [`ARFMODE_OVERRIDE`]; `None` clears it. Test-only: the env is a +/// process constant ([`crate::envflags`]), so an in-process witness needs +/// this to arm the lever. +#[allow(dead_code)] // set only from the `#[cfg(test)]` witness +pub(crate) fn set_arfmode(n: Option) { + ARFMODE_OVERRIDE.store(n.unwrap_or(u8::MAX), std::sync::atomic::Ordering::Relaxed); +} + +/// How often each armed [`crate::speed::ARFMODE`] arm actually fired since +/// the last take (class `gate-blind-to-feature`): 0 = a top-ARF leaf coded +/// with its intra candidate skipped, 1 = a top-ARF 16x16 leaf whose 8x8 +/// split the search would have offered and the arm refused, 2 = a top-ARF +/// leaf whose compound set was dropped. A green gate over counts of zero +/// proves nothing about the lever. +static ARFMODE_HITS: [std::sync::atomic::AtomicUsize; 3] = [ + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), +]; + +/// Records one such hit. +fn arfmode_hit(which: usize) { + ARFMODE_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed); +} + +/// [`arfmode_hit`]`(1)` and "no": the `||` arm of the top ARF's 8x8-offer +/// condition, so the counter only runs when every other prune let the split +/// through and the arm alone refuses it. +fn arfmode_hit_and_no() -> bool { + arfmode_hit(1); + false +} + +/// Takes (and clears) the counts. +#[cfg(test)] +pub(crate) fn take_arfmode_hits() -> [usize; 3] { + [0, 1, 2].map(|i| ARFMODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) } /// [`Search::top_k`]'s value: `None` keeps every mode's search unchanged @@ -8419,6 +8502,9 @@ pub(crate) fn encode_key_frame_inner( modes, top_k: prune_top_k(), screen, + arf_leaf_intra: true, + arf_leaf8: true, + arf_leaf_compound: true, }; // The block grid this frame is coded over: [`crate::tile::block_grid`]'s @@ -12863,6 +12949,11 @@ pub(crate) fn encode_inter_frame( ]; let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0; + let top_arf = matches!( + pyramid, + Some(p) if p.dq_level == DqLevel::TopArf + ); + let arfmode_v = arfmode(); let search = Search { base_q_idx, deadzone, @@ -12876,6 +12967,14 @@ pub(crate) fn encode_inter_frame( modes: &KEY_FRAME_MODES, top_k: prune_top_k_inter(), screen, + // lane-arfmode: the group's own anchor ([`DqLevel::TopArf`], whose + // offset is the pyramid's own `arf_q_offset`) reads its leaf offer + // set from [`crate::speed::ARFMODE`]; every other frame -- the mid + // and quarter hidden frames, the leaves, the flat path -- keeps the + // full set. + arf_leaf_intra: !top_arf || arfmode_v & 1 == 0, + arf_leaf8: !top_arf || arfmode_v & 2 == 0, + arf_leaf_compound: !top_arf || arfmode_v & 4 == 0, }; let mode_bits_table = inter_mode_bits(); // lane-av1tpl: one lambda factor per 64x64 superblock, from how much of @@ -13586,7 +13685,17 @@ pub(crate) fn encode_inter_frame( let eight = (!leaf.skip && !split_rd_breakout(leaf_cost, SUB, search.lambda) && (breakout == 0 || leaf.luma.len() > breakout) - && split_inter_8()) + && split_inter_8() + // lane-arfmode: arm 2 makes 16x16 the top + // ARF's leaf floor -- the RD-optional 8x8 + // comparison is not offered. Counted only + // when every other prune let it through, + // so the counter means "refused", not + // "never considered". The spec-forced 8x8s + // at a straddling 16x16 (the + // `sub_positions` path below) are a + // different site and stay. + && (search.arf_leaf8 || arfmode_hit_and_no())) .then(|| { restore( &mut luma, &mut chroma, (lx, ly), SUB, &leaf_base, diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index 57da7296..b0aac9f4 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -3971,6 +3971,99 @@ mod tests { crate::speed::set_speed(was); } + /// lane-arfmode: the top ARF's leaf offer set. Three guards in one + /// witness, over 17 pictures at gop 32 (three groups, so several top + /// ARFs) at q=60 -- the lookahead witness's lesson: at a fine q the + /// anchor carries real coefficients, so a cut that moves only the + /// hidden frame's internal decisions cannot hide behind "everything + /// quantized to the same bytes": + /// + /// 1. OFF (default and explicit `Some(0)`) is byte-identical -- the + /// shipped table is 0 and the lever is bit-exact when off; + /// 2. each armed mode (1 no intra, 2 no 8x8, 4 no compound) really + /// FIRES -- its own [`crate::encode::take_arfmode_hits`] counter + /// moves (class `gate-blind-to-feature`) -- and MOVES THE STREAM; + /// 3. the coding order and levels never change, and every armed stream + /// decodes sample-exact through `decode_stream` AND ffmpeg. + #[test] + fn the_arf_leaf_offer_set_fires_moves_the_stream_and_decodes_sample_exact() { + let _knobs = crate::speed::knob_write(); + let was = crate::speed::speed(); + crate::speed::set_speed(0); + crate::encode::force_screen(Some(false)); + let (width, height) = (128usize, 128usize); + let run = |mode: Option| -> (Vec, Vec) { + crate::encode::set_arfmode(mode); + let _ = crate::encode::take_arfmode_hits(); + let config = EncoderConfig { + base_q_idx: 60, + width, + height, + gop: 32, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); + // Groups at three luma LEVELS (the base ramp 40/110/180): the + // middle group's top ARF sits halfway between the two dark/light + // anchors its slots hold, which is exactly where neither + // single-reference prediction nor intra wins by default -- the + // AVERAGE of two references (compound) and the DC of the new + // level (intra) do. Without this the synthetic cards' noise + // quantizes to skip and no arm can move anything (measured: + // 516 intra trials skipped, zero won, stream identical). + let sources: Vec = (0..17) + .map(|t| { + let mut p = noisy_card(width, height, t); + let shift = 70i32 * (t / 8) as i32; + for v in p.y.iter_mut() { + *v = (i32::from(*v) + shift).clamp(0, 255) as u16; + } + p + }) + .collect(); + let packets = encode_all(&mut enc, &sources); + (concat(&packets), packets) + }; + let (off, off_packets) = run(None); + let (explicit_off, _) = run(Some(0)); + assert_eq!(off, explicit_off, "mode 0 is not bit-exact with the default"); + for (mode, arm) in [(1u8, 0usize), (2, 1), (4, 2)] { + let (on, packets) = run(Some(mode)); + let hits = crate::encode::take_arfmode_hits(); + assert_eq!( + packets.iter().map(|p| (p.order, p.key, p.level)).collect::>(), + off_packets.iter().map(|p| (p.order, p.key, p.level)).collect::>(), + "mode {mode}: coding order/levels moved" + ); + assert!( + hits[arm] > 0, + "mode {mode}: its counter never fired ({hits:?}) -- the lever is \ + gate-blind on this fixture", + ); + assert_ne!( + off, on, + "mode {mode} left the stream byte-identical despite {} firing hits", + hits[arm], + ); + eprintln!("mode {mode}: {} -> {} B, hits {hits:?}", off.len(), on.len()); + let ours = crate::stream::decode_stream(&on).expect("our decoder"); + assert_eq!(ours.len(), 17, "mode {mode}: our decoder's picture count"); + if !have_ffmpeg() { + continue; + } + let theirs = ffmpeg_decode_luma(&on, width, height); + assert_eq!(theirs.len(), 17, "mode {mode}: ffmpeg's picture count"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + assert!(got == *b, "mode {mode}, frame {i}: ours differs from ffmpeg"); + } + } + crate::encode::set_arfmode(None); + crate::speed::set_speed(was); + } + fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) { let (width, height) = (128usize, 128usize); let config = EncoderConfig { diff --git a/crates/ec-av1/src/speed.rs b/crates/ec-av1/src/speed.rs index b4bf6f68..e609502d 100644 --- a/crates/ec-av1/src/speed.rs +++ b/crates/ec-av1/src/speed.rs @@ -460,6 +460,26 @@ pub(crate) const ARF_TF_WIN: [usize; 11] = [3; 11]; /// so [`ARF_TF`] stays where lane-arftf put it. pub(crate) const ARF_TF_WIN_FUT: [usize; 11] = [3; 11]; +/// lane-arfmode: the top ARF's LEAF offer set, as a bitmask -- `1` the 16x16 +/// and 8x8 leaves of the group's own anchor ([`crate::encode::DqLevel:: +/// TopArf`]) offer no INTRA candidate, `2` a 16x16 leaf under it is not +/// offered the 8x8 split, `4` the leaves offer no compound candidates; +/// combinations OR, `0` (the default) is bit-exact with the pre-lane +/// encoder. `EC_AV1_ARFMODE=` overrides it. The 32x32 whole keeps its +/// full offer set (the scene-cut hatch), and the spec-forced 8x8s at +/// straddling edges are untouched -- only RD-optional offers are cut. +/// +/// The census it answers to (lanes/arfmode.charter.md, at 0d81d6c5): the top +/// ARF's syntax gap against rav1e's own ARF at the same position is +/// film A +1337 / film B +971 B a frame across mode+mv+partition, and the +/// mode family is carried by syntax rav1e does not spend there -- an intra +/// fallback whose 4-15% area share de-optimizes the shared `intra_inter` +/// CDF (ours 138 B/frame against its 10 on film B), compound at 19-24% of +/// the area against its 0%, and an 8x8 split rate 2.4x its own. CAUTION the +/// same census records: on the grain film even rav1e keeps 12.3% intra area +/// at its ARF, so arm 1's residual risk is concentrated exactly there. +pub(crate) const ARFMODE: [u8; 11] = [0; 11]; + /// lane-lookahead: whether [`crate::encoder::Av1Encoder`] holds one whole /// mini-GOP of lookahead -- the next group's sources are buffered before the /// current group's top ARF is coded, so that ARF has display-FUTURE pictures