diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index cd6b0aeb..9cfb22eb 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -165,6 +165,31 @@ fn split_inter_8() -> bool { /// NEARESTMV candidate it always had. 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; + +/// 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 +/// factor on the search cost scale, `1.0` meaning "as good or better". +/// Swept on the BD gate over 0.15/0.25/0.35/0.5/0.8/1.0/1.5 and off (`0.0`, +/// never skip): the whole BD gain survives down to 0.35 (+124.8/+150.4/+80.9 +/// vs libaom, against +124.9/+150.3/+81.0 with no early-out at all) while the +/// extra searches drop from +27% to +4% of the base count -- and on screen +/// capture, where an extra reference's NEWMV wins nothing, it skips 99.7% of +/// them. Below 0.35 the gain starts eroding (0.15: +125.3/+151.7). +const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35; + +/// [`EXTRA_NEW_SKIP_MARGIN`], swept by `EC_AV1_MV_SKIP_MARGIN`. +fn extra_new_skip_margin() -> f64 { + match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() { + Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN), + _ => EXTRA_NEW_SKIP_MARGIN, + } +} + /// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build. fn leaf_new_mv() -> bool { match std::env::var("EC_AV1_LEAF_NEWMV").ok() { @@ -2351,6 +2376,7 @@ fn code_square_inter( let mut best = (inter_cost, None); if leaf_new_mv() { let source_block = luma.source_block(x, y, side); + let (seeds, seed_n) = mv_seeds(stack); let found = motion::search( ref_luma.0, ref_luma.1, @@ -2362,6 +2388,7 @@ fn code_square_inter( side, side, stack.pred_mv, + &seeds[..seed_n], search.lambda, fctx, ); let new_mv = round_to_valid_mv(found.mv, stack.pred_mv); @@ -3461,6 +3488,68 @@ fn mv_component_bits(diff: i32) -> Option { Some(bits) } +/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its +/// own -- a second motion search per block against that reference's picture, +/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it +/// off in a test build (what the lane measured both arms with). +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, + } +} + +/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol +/// per entry past `start`, `1` to advance and `0` to stop, at most two. +fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 { + let mut bits = 0.0; + let mut idx = start; + while idx < start + 2 && stack.entries.len() > idx + 1 { + let advance = idx < target; + bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance)); + if !advance { + break; + } + idx += 1; + } + bits +} + +/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off +/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10 +/// `assign_mv`), so the same vector costs a different residual from each. +fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> { + let mut best: Option<(f64, u8)> = None; + for idx in 0..3usize { + if idx > 0 && stack.entries.len() <= idx { + break; + } + let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); + if let Some(b) = mv_residual_bits(mv, base) { + let total = b + drl_bits_for(stack, 0, idx); + if best.is_none_or(|(t, _)| total < t) { + best = Some((total, idx as u8)); + } + } + } + best +} + +/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the +/// zero vector and the stack's own candidates. A neighbour block's vector is +/// where this block's motion most often already is, which is what pays for +/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points +/// vs libaom for 0.2 s off a 6 s ladder). +fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) { + let mut seeds = [(0, 0); 4]; + let mut n = 1; + for e in stack.entries.iter().take(3) { + seeds[n] = e.mv; + n += 1; + } + (seeds, n) +} + /// What [`crate::tile::write_mv`] (private to that module) would spend /// coding `mv` as a residual against `pred`: the joint symbol naming which /// components differ, then each differing component. `None` under the same @@ -3754,19 +3843,7 @@ fn search_inter_block( // past `start`, `1` to advance and `0` to stop, at most two. A `target` // the loop cannot reach is never offered below -- every candidate's // index is one this same loop walks to. - let drl_bits = |start: usize, target: usize| { - let mut bits = 0.0; - let mut idx = start; - while idx < start + 2 && stack.entries.len() > idx + 1 { - let advance = idx < target; - bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance)); - if !advance { - break; - } - idx += 1; - } - bits - }; + let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target); let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME); let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![ ( @@ -3811,6 +3888,7 @@ fn search_inter_block( } let source_block = luma.source_block(x, y, BLOCK); + let (seeds, seed_n) = mv_seeds(stack); #[cfg(test)] let t = std::time::Instant::now(); let found = motion::search( @@ -3824,6 +3902,7 @@ fn search_inter_block( BLOCK, BLOCK, stack.pred_mv, + &seeds[..seed_n], search.lambda, fctx, ); #[cfg(test)] @@ -3832,20 +3911,7 @@ fn search_inter_block( // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so // the same vector costs a different residual from each: take the index // whose residual plus DRL bits is cheapest, not entry 0 by default. - let mut best_new: Option<(f64, u8)> = None; - for idx in 0..3usize { - if idx > 0 && stack.entries.len() <= idx { - break; - } - let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); - if let Some(b) = mv_residual_bits(mv, base) { - let total = b + drl_bits(0, idx); - if best_new.is_none_or(|(t, _)| total < t) { - best_new = Some((total, idx as u8)); - } - } - } - if let Some((bits, ref_mv_idx)) = best_new { + if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) { cands.push(( mv, last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits, @@ -3858,7 +3924,7 @@ fn search_inter_block( )); } - for &(ref_frame, _, gstack) in extra { + for &(ref_frame, g, gstack) in extra { let g_ref_bits = single_ref_bits(ref_frame); let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1); cands.push(( @@ -3884,6 +3950,67 @@ fn search_inter_block( ref_mv_idx: 0, }, )); + // A motion search of this reference's own: without it, GOLDEN/ALTREF + // can only be coded at a vector some neighbour already found, which + // is why they carried a third of the inter blocks at their two + // search-free modes alone. + // The search is skipped when this reference's own NEARESTMV already + // prices out `margin` times better than LAST's best vector does -- + // one candidate evaluation (`motion::cost_at`) standing in for a + // whole search of ~50. + let margin = extra_new_skip_margin(); + let skip_search = extra_ref_new_mv() + && margin > 0.0 + && motion::cost_at( + &g.y, + g.width, + luma.true_width, + luma.true_height, + &source_block, + x, + y, + BLOCK, + BLOCK, + gstack.nearest_mv, + gstack.pred_mv, + search.lambda, + fctx, + ) * margin + <= found.cost; + if extra_ref_new_mv() && !skip_search { + let (gseeds, gn) = mv_seeds(gstack); + #[cfg(test)] + let t = std::time::Instant::now(); + let gfound = motion::search( + &g.y, + g.width, + luma.true_width, + luma.true_height, + &source_block, + x, + y, + BLOCK, + BLOCK, + gstack.pred_mv, + &gseeds[..gn], + search.lambda, fctx, + ); + #[cfg(test)] + stage_add(0, t.elapsed()); + let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv); + if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) { + cands.push(( + gmv, + g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits, + InterInfo { + ref_frame, + mode: InterMode::NewMv, + mv: gmv, + ref_mv_idx, + }, + )); + } + } } // One trial set per distinct (reference, vector) pair: sort, cheapest @@ -6768,11 +6895,18 @@ mod tests { assert_eq!(predicted.len(), encoded.frames.len()); eprintln!("frame predicted bits written bits drift"); - let mut worst: f64 = 0.0; + // Split by sign: a NEGATIVE drift is the search OVER-pricing (the + // defect this gate exists to catch), a positive one is the written + // side carrying syntax the coefficient sum leaves out -- and since + // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual + // on that side, so the two directions no longer share a bound. + let mut worst_over: f64 = 0.0; + let mut worst_under: f64 = 0.0; for (i, (frame, &bits)) in encoded.frames.iter().zip(&predicted).enumerate() { let written = frame.tile.len() as f64 * 8.0; let drift = (written - bits) / written; - worst = worst.max(drift.abs()); + worst_over = worst_over.max(-drift); + worst_under = worst_under.max(drift); eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0); } // Measured 2026-09-06 on this sequence: -13.5% at the key frame, @@ -6784,9 +6918,18 @@ mod tests { // set just above the worst measured point -- a widening drift is the // thing this gate exists to catch. assert!( - worst <= 0.16, - "the search's rate term drifted {:.2}% from the bits the writer spent", - worst * 100.0 + worst_over <= 0.16, + "the search's rate term OVER-priced by {:.2}% against the bits the writer spent", + worst_over * 100.0 + ); + // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at + // the worst inter frame, where nearly every block now codes an MV + // residual and a reference the coefficient sum never counts. + assert!( + worst_under <= 0.22, + "the writer spent {:.2}% more than the search priced -- more than \ + the mode/mv syntax outside the coefficient sum explains", + worst_under * 100.0 ); } @@ -7631,18 +7774,11 @@ mod tests { /// /// The BD gate above measures quality, which a speed lane can move by a /// hair without failing anything; this pins the streams themselves. - /// Re-measured on the lane-av1lr merge with main d5fc99e0: the per-64x64 - /// `cdef_idx` literals and the per-unit loop restoration syntax are new - /// bits in the tile, so the streams move (q=150 7416 -> 7458 bytes, - /// q=60 27927 -> 27807 -- the low-rate frame pays for the syntax, the - /// high-rate one more than earns it back). - /// - /// Every number below was measured 2026-09-06: first on lane-av1fwd - /// (whose three speed steps left them identical to `a6649c4e`'s), then - /// re-measured on the lane-av1lr merge, which legitimately moves them -- - /// per-64x64 `cdef_idx` literals and the per-unit loop restoration - /// syntax are new bits in the tile, and both streams came out SMALLER - /// (7823 -> 7796, 28189 -> 28182 bytes) for it. + /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64 + /// `cdef_idx` literals and per-unit loop restoration syntax are new bits + /// in the tile) and again on lane-av1mv's merge of it: an extra + /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate + /// above, not by this pin. #[test] fn the_encoders_own_streams_are_byte_identical_to_their_pins() { if !have_ffmpeg() { @@ -7664,7 +7800,7 @@ mod tests { }) }; let pins: [(u8, usize, u64); 2] = - [(150, 7458, 0x7eb2_33c6_bd96_3baf), (60, 27807, 0xeee0_f1e5_e099_46bd)]; + [(150, 7444, 0x76eb980832d719f1), (60, 27692, 0x8c88f7e73455d439)]; for (q, bytes, hash) in pins { let encoded = encode_sequence(&source, q, 0.5).unwrap(); assert_eq!( @@ -7828,6 +7964,7 @@ mod tests { let _ = crate::tile::take_inter_mode_hits(); let _ = crate::tile::take_drl_hits(); let _ = crate::tile::take_ref_hits(); + let _ = crate::motion::take_census(); let (ours, ours_wall) = match pyramid_from_env() { None => our_ladder(&source, width, height, fctx), Some(pyramid) => { @@ -7862,6 +7999,22 @@ mod tests { 100.0 * global as f64 / modes_total as f64, 100.0 * new as f64 / modes_total as f64, ); + // Where the wall-owning stage actually goes: how many candidate + // evaluations (one `mc::predict` + SAD each) a search spends, how + // many of them are subpel, and how often the winner is the seed + // it started from -- the census the seeded search is judged by. + let [calls, evals, subpel, rounds, near_pred, unmoved] = crate::motion::take_census(); + let per = |n: u64| n as f64 / calls.max(1) as f64; + eprintln!( + "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \ + {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \ + +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%", + per(evals), + 100.0 * subpel as f64 / evals.max(1) as f64, + per(rounds), + 100.0 * near_pred as f64 / calls.max(1) as f64, + 100.0 * unmoved as f64 / calls.max(1) as f64, + ); eprintln!( "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})", refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6] diff --git a/crates/ec-av1/src/motion.rs b/crates/ec-av1/src/motion.rs index e54094d6..d6314902 100644 --- a/crates/ec-av1/src/motion.rs +++ b/crates/ec-av1/src/motion.rs @@ -55,6 +55,56 @@ const SEARCH_INITIAL_STEP_PEL: i32 = 8; /// cost function. const SEARCH_MIN_STEP_PEL: i32 = 1; +/// [`SEARCH_INITIAL_STEP_PEL`], swept by `EC_AV1_MV_STEP` in a test build. +/// Swept 1/2/4/8 on the BD gate with the stack seeds below in place: the +/// narrow seeded shape a predictor-seeded search is supposed to allow costs +/// far more rate than it saves wall (step 1 +145.2/+219.4/+81.1 vs libaom, +/// step 2 +134.2/+196.1/+81.1, step 4 +126.0/+161.2/+81.1 against 8's +/// +125.6/+152.1/+80.9) for 0.2 s of a 6 s ladder -- the wide log stage is +/// what finds the 2160p clip's motion, and the search is not the wall. +fn seeded_step() -> i32 { + static STEP: std::sync::OnceLock = std::sync::OnceLock::new(); + *STEP.get_or_init(|| match std::env::var("EC_AV1_MV_STEP").ok() { + Some(v) if cfg!(test) => v.parse().unwrap_or(SEARCH_INITIAL_STEP_PEL), + _ => SEARCH_INITIAL_STEP_PEL, + }) +} + +/// Whether [`search`] starts from the best of the MV-stack's own candidates +/// (libaom's shape) as well as `pred_mv`. `EC_AV1_MV_SEEDED=0` restores the +/// `pred_mv`-only start in a test build (what the lane measured both arms +/// with). +fn seeded() -> bool { + // Read once: this is on the per-block search path, and `std::env::var` + // allocates and locks. + static SEEDED: std::sync::OnceLock = std::sync::OnceLock::new(); + *SEEDED.get_or_init(|| match std::env::var("EC_AV1_MV_SEEDED").ok() { + Some(v) if cfg!(test) => v != "0", + _ => true, + }) +} + +/// How the search spends itself since the last [`take_census`]: 0 calls, +/// 1 total candidate evaluations (one `predict` + SAD each), 2 of which in +/// the two subpel stages, 3 integer-stage rounds, 4 calls whose winner is +/// within one whole sample of `pred_mv`, 5 calls whose winner is the +/// starting centre itself. A gate prints these rather than assume where the +/// wall-owning stage goes (gate-blind-to-feature). +static CENSUS: [std::sync::atomic::AtomicU64; 6] = [ + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), + std::sync::atomic::AtomicU64::new(0), +]; + +/// Takes (and clears) the census. +#[cfg(test)] +pub(crate) fn take_census() -> [u64; 6] { + [0, 1, 2, 3, 4, 5].map(|i| CENSUS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + /// The eight offsets, at `step` in each axis, a diamond/log search round /// checks around its current centre (the ninth point, no offset, is the /// centre itself and is already priced). @@ -158,6 +208,72 @@ pub struct MotionSearch { pub cost: f64, } +/// One candidate's `SAD + lambda * mv_bits(mv - pred_mv)`, predicted into the +/// caller's `dst16` scratch (`block_w * block_h`) so a whole search allocates +/// once. +#[allow(clippy::too_many_arguments)] +fn cost_of_mv( + reference: &[u16], + stride: usize, + ref_width: usize, + ref_height: usize, + source: &[u8], + block_x: usize, + block_y: usize, + block_w: usize, + block_h: usize, + mv: (i32, i32), + pred_mv: (i32, i32), + lambda: f64, + dst16: &mut [u16], + fctx: &crate::decode::FrameCtx, +) -> f64 { + let x_q4 = (block_x as i32) * 16 + mv.1 * Q4_PER_Q3; + let y_q4 = (block_y as i32) * 16 + mv.0 * Q4_PER_Q3; + predict( + reference, stride, ref_width, ref_height, x_q4, y_q4, block_w, block_h, dst16, fctx, + ); + // lane-av1speed: accumulated as an integer (a block is at most + // 32x32 samples of at most 255 each, nowhere near `u32`, and an + // integer sum this small is exact in `f64` whatever order it is + // summed in) instead of one `f64` conversion and dependent add per + // sample. Same value, several times the throughput. + let sad: u32 = source + .iter() + .zip(dst16.iter()) + .map(|(&a, &b)| (i32::from(a) - i32::from(b)).unsigned_abs()) + .sum(); + let diff = (mv.0 - pred_mv.0, mv.1 - pred_mv.1); + f64::from(sad) + lambda * mv_bits(diff) +} + +/// [`cost_of_mv`] for one vector, on its own scratch -- what a caller uses to +/// price a single candidate (an extra reference's `NEARESTMV`, say) on the +/// same scale [`search`] reports its own cost on, for one evaluation instead +/// of a whole search. +#[allow(clippy::too_many_arguments)] +pub(crate) fn cost_at( + reference: &[u16], + stride: usize, + ref_width: usize, + ref_height: usize, + source: &[u8], + block_x: usize, + block_y: usize, + block_w: usize, + block_h: usize, + mv: (i32, i32), + pred_mv: (i32, i32), + lambda: f64, + fctx: &crate::decode::FrameCtx, +) -> f64 { + let mut dst16 = vec![0u16; block_w * block_h]; + cost_of_mv( + reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h, mv, + pred_mv, lambda, &mut dst16, fctx, + ) +} + /// Searches one `block_w * block_h` block, at `(block_x, block_y)` in the /// current picture's plane, against `reference` for the motion vector that /// minimises `SAD + lambda * mv_bits(mv - pred_mv)`. @@ -200,11 +316,14 @@ pub(crate) fn search( block_w: usize, block_h: usize, pred_mv: (i32, i32), + seeds: &[(i32, i32)], lambda: f64, fctx: &crate::decode::FrameCtx, ) -> MotionSearch { let (result, _trace) = search_traced( reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h, - pred_mv, lambda, fctx, + pred_mv, + if seeded() { seeds } else { &[] }, + lambda, fctx, ); result } @@ -224,6 +343,7 @@ fn search_traced( block_w: usize, block_h: usize, pred_mv: (i32, i32), + seeds: &[(i32, i32)], lambda: f64, fctx: &crate::decode::FrameCtx, ) -> (MotionSearch, Vec) { search_traced_from_step( @@ -237,8 +357,13 @@ fn search_traced( block_w, block_h, pred_mv, + seeds, lambda, - SEARCH_INITIAL_STEP_PEL, fctx, + if seeded() { + seeded_step() + } else { + SEARCH_INITIAL_STEP_PEL + }, fctx, ) } @@ -257,6 +382,7 @@ fn search_traced_from_step( block_w: usize, block_h: usize, pred_mv: (i32, i32), + seeds: &[(i32, i32)], lambda: f64, initial_step_pel: i32, fctx: &crate::decode::FrameCtx, ) -> (MotionSearch, Vec) { @@ -269,30 +395,34 @@ fn search_traced_from_step( // allocate-and-convert per searched block, which profiled as the single // largest symbol in the encoder (30% of `sequence_bench_sanity`). let mut dst16 = vec![0u16; block_w * block_h]; + let evals = std::cell::Cell::new(0u64); let mut cost_of = |mv: (i32, i32)| -> f64 { - let x_q4 = (block_x as i32) * 16 + mv.1 * Q4_PER_Q3; - let y_q4 = (block_y as i32) * 16 + mv.0 * Q4_PER_Q3; - predict( - reference, stride, ref_width, ref_height, x_q4, y_q4, block_w, block_h, - &mut dst16, fctx, - ); - // lane-av1speed: accumulated as an integer (a block is at most - // 32x32 samples of at most 255 each, nowhere near `u32`, and an - // integer sum this small is exact in `f64` whatever order it is - // summed in) instead of one `f64` conversion and dependent add per - // sample. Same value, several times the throughput. - let sad: u32 = source - .iter() - .zip(dst16.iter()) - .map(|(&a, &b)| (i32::from(a) - i32::from(b)).unsigned_abs()) - .sum(); - let diff = (mv.0 - pred_mv.0, mv.1 - pred_mv.1); - f64::from(sad) + lambda * mv_bits(diff) + evals.set(evals.get() + 1); + cost_of_mv( + reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h, + mv, pred_mv, lambda, &mut dst16, fctx, + ) }; let mut trace = Vec::new(); let mut centre = (round_to_pel(pred_mv.0), round_to_pel(pred_mv.1)); let mut best_cost = cost_of(centre); + // The stack's own candidates, whole-pel rounded, as extra starting + // points: a neighbour block's vector is where this block's motion most + // often already is, and starting there is what lets the log stage below + // start from is usually the vector this block wants. + for &seed in seeds { + let candidate = (round_to_pel(seed.0), round_to_pel(seed.1)); + if candidate == centre { + continue; + } + let cost = cost_of(candidate); + if cost < best_cost { + best_cost = cost; + centre = candidate; + } + } + let start_centre = centre; trace.push(best_cost); // Stage 1: log/diamond search over whole-pel steps, halving the step @@ -317,6 +447,7 @@ fn search_traced_from_step( } let moved = best_in_round < best_cost; best_cost = best_in_round; + CENSUS[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed); trace.push(best_cost); if !moved { break; @@ -328,6 +459,7 @@ fn search_traced_from_step( // Stages 2 and 3: one ±1-step refinement each at half-pel then // quarter-pel, through the same cost function (so the refinement is // costed at the precision it commits to, not the integer-pel SAD alone). + let integer_evals = evals.get(); for step in [HALF_PEL_Q3, QUARTER_PEL_Q3] { let round_centre = centre; for (dr, dc) in neighbor_offsets(step) { @@ -341,6 +473,17 @@ fn search_traced_from_step( trace.push(best_cost); } + use std::sync::atomic::Ordering::Relaxed; + CENSUS[0].fetch_add(1, Relaxed); + CENSUS[1].fetch_add(evals.get(), Relaxed); + CENSUS[2].fetch_add(evals.get() - integer_evals, Relaxed); + if (centre.0 - pred_mv.0).abs() <= PEL_Q3 && (centre.1 - pred_mv.1).abs() <= PEL_Q3 { + CENSUS[4].fetch_add(1, Relaxed); + } + if centre == start_centre { + CENSUS[5].fetch_add(1, Relaxed); + } + ( MotionSearch { mv: centre, @@ -449,6 +592,7 @@ mod tests { block_w, block_h, (0, 0), + &[], 0.1, fctx, ); assert_eq!( @@ -498,6 +642,7 @@ mod tests { block_w, block_h, (0, 0), + &[], 0.1, fctx, ); assert_eq!( @@ -536,6 +681,7 @@ mod tests { block_w, block_h, (0, 0), + &[], 0.1, fctx, ); assert!(trace.len() > 1, "the search must run more than one round"); @@ -605,6 +751,7 @@ mod tests { block_w, block_h, (0, 0), + &[], 0.1, candidate_step, fctx, ); diff --git a/crates/ec-av1/src/msac.rs b/crates/ec-av1/src/msac.rs index 695bc965..61b9cc17 100644 --- a/crates/ec-av1/src/msac.rs +++ b/crates/ec-av1/src/msac.rs @@ -47,11 +47,22 @@ pub struct SymbolEncoder { /// Flushed bytes before carry propagation: each entry can exceed `0xff` by /// the carry it owes the byte before it, which [`Self::finish`] adds in. precarry: Vec, - /// What every symbol written so far cost against the CDF it was written - /// with, in bits. The arithmetic coder spends `-log2(p)` on a symbol of - /// probability `p` to within the rounding of its interval, so this is what - /// a search may price a decision with without coding it twice. - bits: f64, + /// `log2` of the interval width the bit account started from — the coder's + /// width at [`Self::new`] or at the last [`Self::reset_bits`]. + bits_base: f64, + /// How many bits the renormalisation has shifted `rng` up by since the + /// account started. A symbol costs `log2(r) - log2(rng)` for the widths it + /// narrows between, and the next symbol's `r` is this symbol's `rng` + /// shifted left by the renormalisation, so the whole string's cost + /// telescopes to `bits_base + shifts - log2(rng)` — one `log2` per price + /// asked for, instead of one per symbol (libaom's `od_ec_enc_tell_frac` + /// reads its account the same way). + shifts: u32, + /// Whether this coder only prices: the bit account depends on nothing but + /// how far each symbol narrows `rng`, so a pricer keeps the interval width + /// and drops the value bookkeeping (`low`, `cnt`, `precarry`) whose only + /// consumer is [`Self::finish`]. + pricing: bool, } impl Default for SymbolEncoder { @@ -69,13 +80,25 @@ impl SymbolEncoder { rng: 0x8000, cnt: -9, precarry: Vec::new(), - bits: 0.0, + bits_base: 15.0, + shifts: 0, + pricing: false, + } + } + + /// A coder that only prices, for a search that wants [`Self::bits`] and + /// will never ask for the bytes. Every symbol narrows `rng` exactly as it + /// would in a writing coder, so the account is the same to the bit. + pub fn pricer() -> SymbolEncoder { + SymbolEncoder { + pricing: true, + ..SymbolEncoder::new() } } /// What the symbols written so far cost, in bits. pub fn bits(&self) -> f64 { - self.bits + self.bits_base + f64::from(self.shifts) - f64::from(self.rng).log2() } /// The coder's current interval width — libaom's `od_ec_enc_rng` / @@ -91,13 +114,15 @@ impl SymbolEncoder { /// holds one `u16` per byte already flushed. Pairs with the decoder's /// `aom_reader_tell`, which counts the same bits consumed. pub fn tell(&self) -> i32 { + debug_assert!(!self.pricing, "a pricer keeps no byte position"); self.cnt + 10 + self.precarry.len() as i32 * 8 } /// Forgets the cost accumulated so far, so that the next stretch of /// symbols can be priced on its own. pub fn reset_bits(&mut self) { - self.bits = 0.0; + self.bits_base = f64::from(self.rng).log2(); + self.shifts = 0; } /// Writes `symbol` against `cdf` and adapts `cdf` exactly as the decoder @@ -145,9 +170,15 @@ impl SymbolEncoder { // which is not quite its nominal probability: the coder works the // range through an eight-bit multiply and hands every symbol above // this one a floor of `EC_MIN_PROB`. Pricing the narrowing rather than - // the table entry is what makes the account match the bytes. - self.bits -= (f64::from(rng) / f64::from(r)).log2(); - self.normalize(low, rng); + // the table entry is what makes the account match the bytes; the + // narrowing itself is read off `rng` and `shifts` by [`Self::bits`]. + if self.pricing { + let d = 16 - (32 - rng.leading_zeros()); + self.rng = rng << d; + self.shifts += d; + } else { + self.normalize(low, rng); + } } /// Writes `bits` raw bits of `value`, most significant first — the `L(n)` @@ -169,6 +200,7 @@ impl SymbolEncoder { /// inside it however the decoder pads the string, which is what lets a tile /// payload end on a byte boundary with no terminator. pub fn finish(mut self) -> Vec { + assert!(!self.pricing, "a pricer holds no bytes to flush"); // Round the interval's low end up to a value with 14 low zero bits, // then set bit 14: the result is inside the interval (the interval is // at least 2^15 wide before normalisation) and its tail bits are all @@ -223,6 +255,7 @@ impl SymbolEncoder { self.low = low << d; self.rng = rng << d; self.cnt = s; + self.shifts += d as u32; } } diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 1785d492..54ace68e 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -2395,8 +2395,7 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 { TX16 => &SCANS[2], _ => &SCANS[3], }; - let mut enc = SymbolEncoder::new(); - enc.reset_bits(); + let mut enc = SymbolEncoder::pricer(); write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None); enc.bits() }) @@ -2449,10 +2448,19 @@ fn write_coeffs( ec_rng_trace(|| format!("EC_PLANE plane={plane} tell_before={}", enc.tell())); } let side = coding.side; - let eob = scan - .iter() - .rposition(|&pos| grid[pos as usize] != 0) - .map_or(0, |i| i + 1); + // The scan-order search reads the grid in scan order, one dependent load + // per position, and an all-zero block makes it walk every one of them -- + // which the pricer does for candidate after candidate. A straight-line + // pass settles that case first: it vectorises, and a block that codes + // anything at all almost always codes its DC, so it stops at the first + // element. + let eob = if grid.iter().all(|&level| level == 0) { + 0 + } else { + scan.iter() + .rposition(|&pos| grid[pos as usize] != 0) + .map_or(0, |i| i + 1) + }; enc.symbol(usize::from(eob == 0), &mut coding.txb_skip[skip_ctx]); if plane.is_some() { ec_rng_trace(|| { @@ -2656,10 +2664,22 @@ fn base_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize { if row == 0 && col == 0 { return 0; } - let mag: i32 = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] - .iter() - .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3)) - .sum(); + // A coefficient two rows and two columns clear of the far edges reaches + // all five neighbours, so the gather is five loads off one index with no + // per-neighbour edge test -- which is where this writer spends a third of + // its coefficient loop. + let p = row * side + col; + let mag: i32 = if row + 2 < side && col + 2 < side { + [p + side, p + 1, p + side + 1, p + 2 * side, p + 2] + .iter() + .map(|&i| grid[i].abs().min(3)) + .sum() + } else { + [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] + .iter() + .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3)) + .sum() + }; let offset = cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize; (((mag + 1) >> 1).min(4) as usize) + offset } @@ -2668,10 +2688,15 @@ fn base_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize { /// of its three closest neighbours below and to the right, uncapped, and a /// term separating the DC, the corner of the transform, and the rest. fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize { - let mag: i32 = [(1, 0), (0, 1), (1, 1)] - .iter() - .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs()) - .sum(); + let p = row * side + col; + let mag: i32 = if row + 1 < side && col + 1 < side { + grid[p + side].abs() + grid[p + 1].abs() + grid[p + side + 1].abs() + } else { + [(1, 0), (0, 1), (1, 1)] + .iter() + .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs()) + .sum() + }; let mag = (((mag + 1) >> 1).min(6)) as usize; if row == 0 && col == 0 { mag