diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index c617077f..d31fdfd5 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -165,6 +165,24 @@ 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. Set from the +/// lane report's measurement. +const EXTRA_REF_NEW_MV: bool = false; + +/// 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 (see the lane report) -- `0.0` never skips. +const EXTRA_NEW_SKIP_MARGIN: f64 = 0.0; + +/// [`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() { @@ -2317,6 +2335,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, @@ -2328,6 +2347,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); @@ -3318,6 +3338,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 @@ -3611,19 +3693,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![ ( @@ -3668,6 +3738,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( @@ -3681,6 +3752,7 @@ fn search_inter_block( BLOCK, BLOCK, stack.pred_mv, + &seeds[..seed_n], search.lambda, fctx, ); #[cfg(test)] @@ -3689,20 +3761,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, @@ -3715,7 +3774,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(( @@ -3741,6 +3800,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 @@ -7507,6 +7627,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) = our_ladder(&source, width, height, fctx); // How often the inter split actually fired over this clip's four // encodes, against the whole 32x32 that was the only outcome @@ -7528,6 +7649,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, );