forge
Explore
Log in

Don't you dare go Hollow

merge: main (lane-av1mv motion search, lane-av1price msac pricer) into lane-av1pyr

Browse files at this commit

a802372bd3e1e34b2fee2fd46c93e4066821b9d5Ahmet Kaan GümüşParent: 006a259e6e02af
crates/ec-av1/src/encode.rsmodified+199 -46
@@ -165,6 +165,31 @@ fn split_inter_8() -> bool {
165165 /// NEARESTMV candidate it always had.
166166 const LEAF_NEW_MV: bool = true;
167167
168+/// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the
169+/// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0
170+/// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion
171+/// searches (the census `bd_rate_vs_libaom_and_rav1e` prints).
172+const EXTRA_REF_NEW_MV: bool = true;
173+
174+/// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's
175+/// own best vector before that reference's `NEWMV` search is skipped: a
176+/// factor on the search cost scale, `1.0` meaning "as good or better".
177+/// Swept on the BD gate over 0.15/0.25/0.35/0.5/0.8/1.0/1.5 and off (`0.0`,
178+/// never skip): the whole BD gain survives down to 0.35 (+124.8/+150.4/+80.9
179+/// vs libaom, against +124.9/+150.3/+81.0 with no early-out at all) while the
180+/// extra searches drop from +27% to +4% of the base count -- and on screen
181+/// capture, where an extra reference's NEWMV wins nothing, it skips 99.7% of
182+/// them. Below 0.35 the gain starts eroding (0.15: +125.3/+151.7).
183+const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35;
184+
185+/// [`EXTRA_NEW_SKIP_MARGIN`], swept by `EC_AV1_MV_SKIP_MARGIN`.
186+fn extra_new_skip_margin() -> f64 {
187+ match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() {
188+ Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN),
189+ _ => EXTRA_NEW_SKIP_MARGIN,
190+ }
191+}
192+
168193 /// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build.
169194 fn leaf_new_mv() -> bool {
170195 match std::env::var("EC_AV1_LEAF_NEWMV").ok() {
@@ -2351,6 +2376,7 @@ fn code_square_inter(
23512376 let mut best = (inter_cost, None);
23522377 if leaf_new_mv() {
23532378 let source_block = luma.source_block(x, y, side);
2379+ let (seeds, seed_n) = mv_seeds(stack);
23542380 let found = motion::search(
23552381 ref_luma.0,
23562382 ref_luma.1,
@@ -2362,6 +2388,7 @@ fn code_square_inter(
23622388 side,
23632389 side,
23642390 stack.pred_mv,
2391+ &seeds[..seed_n],
23652392 search.lambda, fctx,
23662393 );
23672394 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
@@ -3461,6 +3488,68 @@ fn mv_component_bits(diff: i32) -> Option<f64> {
34613488 Some(bits)
34623489 }
34633490
3491+/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its
3492+/// own -- a second motion search per block against that reference's picture,
3493+/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it
3494+/// off in a test build (what the lane measured both arms with).
3495+fn extra_ref_new_mv() -> bool {
3496+ match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() {
3497+ Some(v) if cfg!(test) => v != "0",
3498+ _ => EXTRA_REF_NEW_MV,
3499+ }
3500+}
3501+
3502+/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol
3503+/// per entry past `start`, `1` to advance and `0` to stop, at most two.
3504+fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 {
3505+ let mut bits = 0.0;
3506+ let mut idx = start;
3507+ while idx < start + 2 && stack.entries.len() > idx + 1 {
3508+ let advance = idx < target;
3509+ bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
3510+ if !advance {
3511+ break;
3512+ }
3513+ idx += 1;
3514+ }
3515+ bits
3516+}
3517+
3518+/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off
3519+/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10
3520+/// `assign_mv`), so the same vector costs a different residual from each.
3521+fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> {
3522+ let mut best: Option<(f64, u8)> = None;
3523+ for idx in 0..3usize {
3524+ if idx > 0 && stack.entries.len() <= idx {
3525+ break;
3526+ }
3527+ let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
3528+ if let Some(b) = mv_residual_bits(mv, base) {
3529+ let total = b + drl_bits_for(stack, 0, idx);
3530+ if best.is_none_or(|(t, _)| total < t) {
3531+ best = Some((total, idx as u8));
3532+ }
3533+ }
3534+ }
3535+ best
3536+}
3537+
3538+/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the
3539+/// zero vector and the stack's own candidates. A neighbour block's vector is
3540+/// where this block's motion most often already is, which is what pays for
3541+/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points
3542+/// vs libaom for 0.2 s off a 6 s ladder).
3543+fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) {
3544+ let mut seeds = [(0, 0); 4];
3545+ let mut n = 1;
3546+ for e in stack.entries.iter().take(3) {
3547+ seeds[n] = e.mv;
3548+ n += 1;
3549+ }
3550+ (seeds, n)
3551+}
3552+
34643553 /// What [`crate::tile::write_mv`] (private to that module) would spend
34653554 /// coding `mv` as a residual against `pred`: the joint symbol naming which
34663555 /// components differ, then each differing component. `None` under the same
@@ -3754,19 +3843,7 @@ fn search_inter_block(
37543843 // past `start`, `1` to advance and `0` to stop, at most two. A `target`
37553844 // the loop cannot reach is never offered below -- every candidate's
37563845 // index is one this same loop walks to.
3757- let drl_bits = |start: usize, target: usize| {
3758- let mut bits = 0.0;
3759- let mut idx = start;
3760- while idx < start + 2 && stack.entries.len() > idx + 1 {
3761- let advance = idx < target;
3762- bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
3763- if !advance {
3764- break;
3765- }
3766- idx += 1;
3767- }
3768- bits
3769- };
3846+ let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target);
37703847 let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME);
37713848 let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
37723849 (
@@ -3811,6 +3888,7 @@ fn search_inter_block(
38113888 }
38123889
38133890 let source_block = luma.source_block(x, y, BLOCK);
3891+ let (seeds, seed_n) = mv_seeds(stack);
38143892 #[cfg(test)]
38153893 let t = std::time::Instant::now();
38163894 let found = motion::search(
@@ -3824,6 +3902,7 @@ fn search_inter_block(
38243902 BLOCK,
38253903 BLOCK,
38263904 stack.pred_mv,
3905+ &seeds[..seed_n],
38273906 search.lambda, fctx,
38283907 );
38293908 #[cfg(test)]
@@ -3832,20 +3911,7 @@ fn search_inter_block(
38323911 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
38333912 // the same vector costs a different residual from each: take the index
38343913 // whose residual plus DRL bits is cheapest, not entry 0 by default.
3835- let mut best_new: Option<(f64, u8)> = None;
3836- for idx in 0..3usize {
3837- if idx > 0 && stack.entries.len() <= idx {
3838- break;
3839- }
3840- let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
3841- if let Some(b) = mv_residual_bits(mv, base) {
3842- let total = b + drl_bits(0, idx);
3843- if best_new.is_none_or(|(t, _)| total < t) {
3844- best_new = Some((total, idx as u8));
3845- }
3846- }
3847- }
3848- if let Some((bits, ref_mv_idx)) = best_new {
3914+ if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
38493915 cands.push((
38503916 mv,
38513917 last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits,
@@ -3858,7 +3924,7 @@ fn search_inter_block(
38583924 ));
38593925 }
38603926
3861- for &(ref_frame, _, gstack) in extra {
3927+ for &(ref_frame, g, gstack) in extra {
38623928 let g_ref_bits = single_ref_bits(ref_frame);
38633929 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
38643930 cands.push((
@@ -3884,6 +3950,67 @@ fn search_inter_block(
38843950 ref_mv_idx: 0,
38853951 },
38863952 ));
3953+ // A motion search of this reference's own: without it, GOLDEN/ALTREF
3954+ // can only be coded at a vector some neighbour already found, which
3955+ // is why they carried a third of the inter blocks at their two
3956+ // search-free modes alone.
3957+ // The search is skipped when this reference's own NEARESTMV already
3958+ // prices out `margin` times better than LAST's best vector does --
3959+ // one candidate evaluation (`motion::cost_at`) standing in for a
3960+ // whole search of ~50.
3961+ let margin = extra_new_skip_margin();
3962+ let skip_search = extra_ref_new_mv()
3963+ && margin > 0.0
3964+ && motion::cost_at(
3965+ &g.y,
3966+ g.width,
3967+ luma.true_width,
3968+ luma.true_height,
3969+ &source_block,
3970+ x,
3971+ y,
3972+ BLOCK,
3973+ BLOCK,
3974+ gstack.nearest_mv,
3975+ gstack.pred_mv,
3976+ search.lambda,
3977+ fctx,
3978+ ) * margin
3979+ <= found.cost;
3980+ if extra_ref_new_mv() && !skip_search {
3981+ let (gseeds, gn) = mv_seeds(gstack);
3982+ #[cfg(test)]
3983+ let t = std::time::Instant::now();
3984+ let gfound = motion::search(
3985+ &g.y,
3986+ g.width,
3987+ luma.true_width,
3988+ luma.true_height,
3989+ &source_block,
3990+ x,
3991+ y,
3992+ BLOCK,
3993+ BLOCK,
3994+ gstack.pred_mv,
3995+ &gseeds[..gn],
3996+ search.lambda, fctx,
3997+ );
3998+ #[cfg(test)]
3999+ stage_add(0, t.elapsed());
4000+ let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
4001+ if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
4002+ cands.push((
4003+ gmv,
4004+ g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
4005+ InterInfo {
4006+ ref_frame,
4007+ mode: InterMode::NewMv,
4008+ mv: gmv,
4009+ ref_mv_idx,
4010+ },
4011+ ));
4012+ }
4013+ }
38874014 }
38884015
38894016 // One trial set per distinct (reference, vector) pair: sort, cheapest
@@ -6768,11 +6895,18 @@ mod tests {
67686895 assert_eq!(predicted.len(), encoded.frames.len());
67696896
67706897 eprintln!("frame predicted bits written bits drift");
6771- let mut worst: f64 = 0.0;
6898+ // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
6899+ // defect this gate exists to catch), a positive one is the written
6900+ // side carrying syntax the coefficient sum leaves out -- and since
6901+ // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
6902+ // on that side, so the two directions no longer share a bound.
6903+ let mut worst_over: f64 = 0.0;
6904+ let mut worst_under: f64 = 0.0;
67726905 for (i, (frame, &bits)) in encoded.frames.iter().zip(&predicted).enumerate() {
67736906 let written = frame.tile.len() as f64 * 8.0;
67746907 let drift = (written - bits) / written;
6775- worst = worst.max(drift.abs());
6908+ worst_over = worst_over.max(-drift);
6909+ worst_under = worst_under.max(drift);
67766910 eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0);
67776911 }
67786912 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
@@ -6784,9 +6918,18 @@ mod tests {
67846918 // set just above the worst measured point -- a widening drift is the
67856919 // thing this gate exists to catch.
67866920 assert!(
6787- worst <= 0.16,
6788- "the search's rate term drifted {:.2}% from the bits the writer spent",
6789- worst * 100.0
6921+ worst_over <= 0.16,
6922+ "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
6923+ worst_over * 100.0
6924+ );
6925+ // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
6926+ // the worst inter frame, where nearly every block now codes an MV
6927+ // residual and a reference the coefficient sum never counts.
6928+ assert!(
6929+ worst_under <= 0.22,
6930+ "the writer spent {:.2}% more than the search priced -- more than \
6931+ the mode/mv syntax outside the coefficient sum explains",
6932+ worst_under * 100.0
67906933 );
67916934 }
67926935
@@ -7631,18 +7774,11 @@ mod tests {
76317774 ///
76327775 /// The BD gate above measures quality, which a speed lane can move by a
76337776 /// hair without failing anything; this pins the streams themselves.
7634- /// Re-measured on the lane-av1lr merge with main d5fc99e0: the per-64x64
7635- /// `cdef_idx` literals and the per-unit loop restoration syntax are new
7636- /// bits in the tile, so the streams move (q=150 7416 -> 7458 bytes,
7637- /// q=60 27927 -> 27807 -- the low-rate frame pays for the syntax, the
7638- /// high-rate one more than earns it back).
7639- ///
7640- /// Every number below was measured 2026-09-06: first on lane-av1fwd
7641- /// (whose three speed steps left them identical to `a6649c4e`'s), then
7642- /// re-measured on the lane-av1lr merge, which legitimately moves them --
7643- /// per-64x64 `cdef_idx` literals and the per-unit loop restoration
7644- /// syntax are new bits in the tile, and both streams came out SMALLER
7645- /// (7823 -> 7796, 28189 -> 28182 bytes) for it.
7777+ /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
7778+ /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
7779+ /// in the tile) and again on lane-av1mv's merge of it: an extra
7780+ /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
7781+ /// above, not by this pin.
76467782 #[test]
76477783 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
76487784 if !have_ffmpeg() {
@@ -7664,7 +7800,7 @@ mod tests {
76647800 })
76657801 };
76667802 let pins: [(u8, usize, u64); 2] =
7667- [(150, 7458, 0x7eb2_33c6_bd96_3baf), (60, 27807, 0xeee0_f1e5_e099_46bd)];
7803+ [(150, 7444, 0x76eb980832d719f1), (60, 27692, 0x8c88f7e73455d439)];
76687804 for (q, bytes, hash) in pins {
76697805 let encoded = encode_sequence(&source, q, 0.5).unwrap();
76707806 assert_eq!(
@@ -7828,6 +7964,7 @@ mod tests {
78287964 let _ = crate::tile::take_inter_mode_hits();
78297965 let _ = crate::tile::take_drl_hits();
78307966 let _ = crate::tile::take_ref_hits();
7967+ let _ = crate::motion::take_census();
78317968 let (ours, ours_wall) = match pyramid_from_env() {
78327969 None => our_ladder(&source, width, height, fctx),
78337970 Some(pyramid) => {
@@ -7862,6 +7999,22 @@ mod tests {
78627999 100.0 * global as f64 / modes_total as f64,
78638000 100.0 * new as f64 / modes_total as f64,
78648001 );
8002+ // Where the wall-owning stage actually goes: how many candidate
8003+ // evaluations (one `mc::predict` + SAD each) a search spends, how
8004+ // many of them are subpel, and how often the winner is the seed
8005+ // it started from -- the census the seeded search is judged by.
8006+ let [calls, evals, subpel, rounds, near_pred, unmoved] = crate::motion::take_census();
8007+ let per = |n: u64| n as f64 / calls.max(1) as f64;
8008+ eprintln!(
8009+ "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
8010+ {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \
8011+ +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%",
8012+ per(evals),
8013+ 100.0 * subpel as f64 / evals.max(1) as f64,
8014+ per(rounds),
8015+ 100.0 * near_pred as f64 / calls.max(1) as f64,
8016+ 100.0 * unmoved as f64 / calls.max(1) as f64,
8017+ );
78658018 eprintln!(
78668019 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
78678020 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
crates/ec-av1/src/motion.rsmodified+167 -20
@@ -55,6 +55,56 @@ const SEARCH_INITIAL_STEP_PEL: i32 = 8;
5555 /// cost function.
5656 const SEARCH_MIN_STEP_PEL: i32 = 1;
5757
58+/// [`SEARCH_INITIAL_STEP_PEL`], swept by `EC_AV1_MV_STEP` in a test build.
59+/// Swept 1/2/4/8 on the BD gate with the stack seeds below in place: the
60+/// narrow seeded shape a predictor-seeded search is supposed to allow costs
61+/// far more rate than it saves wall (step 1 +145.2/+219.4/+81.1 vs libaom,
62+/// step 2 +134.2/+196.1/+81.1, step 4 +126.0/+161.2/+81.1 against 8's
63+/// +125.6/+152.1/+80.9) for 0.2 s of a 6 s ladder -- the wide log stage is
64+/// what finds the 2160p clip's motion, and the search is not the wall.
65+fn seeded_step() -> i32 {
66+ static STEP: std::sync::OnceLock<i32> = std::sync::OnceLock::new();
67+ *STEP.get_or_init(|| match std::env::var("EC_AV1_MV_STEP").ok() {
68+ Some(v) if cfg!(test) => v.parse().unwrap_or(SEARCH_INITIAL_STEP_PEL),
69+ _ => SEARCH_INITIAL_STEP_PEL,
70+ })
71+}
72+
73+/// Whether [`search`] starts from the best of the MV-stack's own candidates
74+/// (libaom's shape) as well as `pred_mv`. `EC_AV1_MV_SEEDED=0` restores the
75+/// `pred_mv`-only start in a test build (what the lane measured both arms
76+/// with).
77+fn seeded() -> bool {
78+ // Read once: this is on the per-block search path, and `std::env::var`
79+ // allocates and locks.
80+ static SEEDED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
81+ *SEEDED.get_or_init(|| match std::env::var("EC_AV1_MV_SEEDED").ok() {
82+ Some(v) if cfg!(test) => v != "0",
83+ _ => true,
84+ })
85+}
86+
87+/// How the search spends itself since the last [`take_census`]: 0 calls,
88+/// 1 total candidate evaluations (one `predict` + SAD each), 2 of which in
89+/// the two subpel stages, 3 integer-stage rounds, 4 calls whose winner is
90+/// within one whole sample of `pred_mv`, 5 calls whose winner is the
91+/// starting centre itself. A gate prints these rather than assume where the
92+/// wall-owning stage goes (gate-blind-to-feature).
93+static CENSUS: [std::sync::atomic::AtomicU64; 6] = [
94+ std::sync::atomic::AtomicU64::new(0),
95+ std::sync::atomic::AtomicU64::new(0),
96+ std::sync::atomic::AtomicU64::new(0),
97+ std::sync::atomic::AtomicU64::new(0),
98+ std::sync::atomic::AtomicU64::new(0),
99+ std::sync::atomic::AtomicU64::new(0),
100+];
101+
102+/// Takes (and clears) the census.
103+#[cfg(test)]
104+pub(crate) fn take_census() -> [u64; 6] {
105+ [0, 1, 2, 3, 4, 5].map(|i| CENSUS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
106+}
107+
58108 /// The eight offsets, at `step` in each axis, a diamond/log search round
59109 /// checks around its current centre (the ninth point, no offset, is the
60110 /// centre itself and is already priced).
@@ -158,6 +208,72 @@ pub struct MotionSearch {
158208 pub cost: f64,
159209 }
160210
211+/// One candidate's `SAD + lambda * mv_bits(mv - pred_mv)`, predicted into the
212+/// caller's `dst16` scratch (`block_w * block_h`) so a whole search allocates
213+/// once.
214+#[allow(clippy::too_many_arguments)]
215+fn cost_of_mv(
216+ reference: &[u16],
217+ stride: usize,
218+ ref_width: usize,
219+ ref_height: usize,
220+ source: &[u8],
221+ block_x: usize,
222+ block_y: usize,
223+ block_w: usize,
224+ block_h: usize,
225+ mv: (i32, i32),
226+ pred_mv: (i32, i32),
227+ lambda: f64,
228+ dst16: &mut [u16],
229+ fctx: &crate::decode::FrameCtx,
230+) -> f64 {
231+ let x_q4 = (block_x as i32) * 16 + mv.1 * Q4_PER_Q3;
232+ let y_q4 = (block_y as i32) * 16 + mv.0 * Q4_PER_Q3;
233+ predict(
234+ reference, stride, ref_width, ref_height, x_q4, y_q4, block_w, block_h, dst16, fctx,
235+ );
236+ // lane-av1speed: accumulated as an integer (a block is at most
237+ // 32x32 samples of at most 255 each, nowhere near `u32`, and an
238+ // integer sum this small is exact in `f64` whatever order it is
239+ // summed in) instead of one `f64` conversion and dependent add per
240+ // sample. Same value, several times the throughput.
241+ let sad: u32 = source
242+ .iter()
243+ .zip(dst16.iter())
244+ .map(|(&a, &b)| (i32::from(a) - i32::from(b)).unsigned_abs())
245+ .sum();
246+ let diff = (mv.0 - pred_mv.0, mv.1 - pred_mv.1);
247+ f64::from(sad) + lambda * mv_bits(diff)
248+}
249+
250+/// [`cost_of_mv`] for one vector, on its own scratch -- what a caller uses to
251+/// price a single candidate (an extra reference's `NEARESTMV`, say) on the
252+/// same scale [`search`] reports its own cost on, for one evaluation instead
253+/// of a whole search.
254+#[allow(clippy::too_many_arguments)]
255+pub(crate) fn cost_at(
256+ reference: &[u16],
257+ stride: usize,
258+ ref_width: usize,
259+ ref_height: usize,
260+ source: &[u8],
261+ block_x: usize,
262+ block_y: usize,
263+ block_w: usize,
264+ block_h: usize,
265+ mv: (i32, i32),
266+ pred_mv: (i32, i32),
267+ lambda: f64,
268+ fctx: &crate::decode::FrameCtx,
269+) -> f64 {
270+ let mut dst16 = vec![0u16; block_w * block_h];
271+ cost_of_mv(
272+ reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h, mv,
273+ pred_mv, lambda, &mut dst16, fctx,
274+ )
275+}
276+
161277 /// Searches one `block_w * block_h` block, at `(block_x, block_y)` in the
162278 /// current picture's plane, against `reference` for the motion vector that
163279 /// minimises `SAD + lambda * mv_bits(mv - pred_mv)`.
@@ -200,11 +316,14 @@ pub(crate) fn search(
200316 block_w: usize,
201317 block_h: usize,
202318 pred_mv: (i32, i32),
319+ seeds: &[(i32, i32)],
203320 lambda: f64, fctx: &crate::decode::FrameCtx,
204321 ) -> MotionSearch {
205322 let (result, _trace) = search_traced(
206323 reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h,
207- pred_mv, lambda, fctx,
324+ pred_mv,
325+ if seeded() { seeds } else { &[] },
326+ lambda, fctx,
208327 );
209328 result
210329 }
@@ -224,6 +343,7 @@ fn search_traced(
224343 block_w: usize,
225344 block_h: usize,
226345 pred_mv: (i32, i32),
346+ seeds: &[(i32, i32)],
227347 lambda: f64, fctx: &crate::decode::FrameCtx,
228348 ) -> (MotionSearch, Vec<f64>) {
229349 search_traced_from_step(
@@ -237,8 +357,13 @@ fn search_traced(
237357 block_w,
238358 block_h,
239359 pred_mv,
360+ seeds,
240361 lambda,
241- SEARCH_INITIAL_STEP_PEL, fctx,
362+ if seeded() {
363+ seeded_step()
364+ } else {
365+ SEARCH_INITIAL_STEP_PEL
366+ }, fctx,
242367 )
243368 }
244369
@@ -257,6 +382,7 @@ fn search_traced_from_step(
257382 block_w: usize,
258383 block_h: usize,
259384 pred_mv: (i32, i32),
385+ seeds: &[(i32, i32)],
260386 lambda: f64,
261387 initial_step_pel: i32, fctx: &crate::decode::FrameCtx,
262388 ) -> (MotionSearch, Vec<f64>) {
@@ -269,30 +395,34 @@ fn search_traced_from_step(
269395 // allocate-and-convert per searched block, which profiled as the single
270396 // largest symbol in the encoder (30% of `sequence_bench_sanity`).
271397 let mut dst16 = vec![0u16; block_w * block_h];
398+ let evals = std::cell::Cell::new(0u64);
272399 let mut cost_of = |mv: (i32, i32)| -> f64 {
273- let x_q4 = (block_x as i32) * 16 + mv.1 * Q4_PER_Q3;
274- let y_q4 = (block_y as i32) * 16 + mv.0 * Q4_PER_Q3;
275- predict(
276- reference, stride, ref_width, ref_height, x_q4, y_q4, block_w, block_h,
277- &mut dst16, fctx,
278- );
279- // lane-av1speed: accumulated as an integer (a block is at most
280- // 32x32 samples of at most 255 each, nowhere near `u32`, and an
281- // integer sum this small is exact in `f64` whatever order it is
282- // summed in) instead of one `f64` conversion and dependent add per
283- // sample. Same value, several times the throughput.
284- let sad: u32 = source
285- .iter()
286- .zip(dst16.iter())
287- .map(|(&a, &b)| (i32::from(a) - i32::from(b)).unsigned_abs())
288- .sum();
289- let diff = (mv.0 - pred_mv.0, mv.1 - pred_mv.1);
290- f64::from(sad) + lambda * mv_bits(diff)
400+ evals.set(evals.get() + 1);
401+ cost_of_mv(
402+ reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h,
403+ mv, pred_mv, lambda, &mut dst16, fctx,
404+ )
291405 };
292406
293407 let mut trace = Vec::new();
294408 let mut centre = (round_to_pel(pred_mv.0), round_to_pel(pred_mv.1));
295409 let mut best_cost = cost_of(centre);
410+ // The stack's own candidates, whole-pel rounded, as extra starting
411+ // points: a neighbour block's vector is where this block's motion most
412+ // often already is, and starting there is what lets the log stage below
413+ // start from is usually the vector this block wants.
414+ for &seed in seeds {
415+ let candidate = (round_to_pel(seed.0), round_to_pel(seed.1));
416+ if candidate == centre {
417+ continue;
418+ }
419+ let cost = cost_of(candidate);
420+ if cost < best_cost {
421+ best_cost = cost;
422+ centre = candidate;
423+ }
424+ }
425+ let start_centre = centre;
296426 trace.push(best_cost);
297427
298428 // Stage 1: log/diamond search over whole-pel steps, halving the step
@@ -317,6 +447,7 @@ fn search_traced_from_step(
317447 }
318448 let moved = best_in_round < best_cost;
319449 best_cost = best_in_round;
450+ CENSUS[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
320451 trace.push(best_cost);
321452 if !moved {
322453 break;
@@ -328,6 +459,7 @@ fn search_traced_from_step(
328459 // Stages 2 and 3: one ±1-step refinement each at half-pel then
329460 // quarter-pel, through the same cost function (so the refinement is
330461 // costed at the precision it commits to, not the integer-pel SAD alone).
462+ let integer_evals = evals.get();
331463 for step in [HALF_PEL_Q3, QUARTER_PEL_Q3] {
332464 let round_centre = centre;
333465 for (dr, dc) in neighbor_offsets(step) {
@@ -341,6 +473,17 @@ fn search_traced_from_step(
341473 trace.push(best_cost);
342474 }
343475
476+ use std::sync::atomic::Ordering::Relaxed;
477+ CENSUS[0].fetch_add(1, Relaxed);
478+ CENSUS[1].fetch_add(evals.get(), Relaxed);
479+ CENSUS[2].fetch_add(evals.get() - integer_evals, Relaxed);
480+ if (centre.0 - pred_mv.0).abs() <= PEL_Q3 && (centre.1 - pred_mv.1).abs() <= PEL_Q3 {
481+ CENSUS[4].fetch_add(1, Relaxed);
482+ }
483+ if centre == start_centre {
484+ CENSUS[5].fetch_add(1, Relaxed);
485+ }
486+
344487 (
345488 MotionSearch {
346489 mv: centre,
@@ -449,6 +592,7 @@ mod tests {
449592 block_w,
450593 block_h,
451594 (0, 0),
595+ &[],
452596 0.1, fctx,
453597 );
454598 assert_eq!(
@@ -498,6 +642,7 @@ mod tests {
498642 block_w,
499643 block_h,
500644 (0, 0),
645+ &[],
501646 0.1, fctx,
502647 );
503648 assert_eq!(
@@ -536,6 +681,7 @@ mod tests {
536681 block_w,
537682 block_h,
538683 (0, 0),
684+ &[],
539685 0.1, fctx,
540686 );
541687 assert!(trace.len() > 1, "the search must run more than one round");
@@ -605,6 +751,7 @@ mod tests {
605751 block_w,
606752 block_h,
607753 (0, 0),
754+ &[],
608755 0.1,
609756 candidate_step, fctx,
610757 );
crates/ec-av1/src/msac.rsmodified+44 -11
@@ -47,11 +47,22 @@ pub struct SymbolEncoder {
4747 /// Flushed bytes before carry propagation: each entry can exceed `0xff` by
4848 /// the carry it owes the byte before it, which [`Self::finish`] adds in.
4949 precarry: Vec<u16>,
50- /// What every symbol written so far cost against the CDF it was written
51- /// with, in bits. The arithmetic coder spends `-log2(p)` on a symbol of
52- /// probability `p` to within the rounding of its interval, so this is what
53- /// a search may price a decision with without coding it twice.
54- bits: f64,
50+ /// `log2` of the interval width the bit account started from — the coder's
51+ /// width at [`Self::new`] or at the last [`Self::reset_bits`].
52+ bits_base: f64,
53+ /// How many bits the renormalisation has shifted `rng` up by since the
54+ /// account started. A symbol costs `log2(r) - log2(rng)` for the widths it
55+ /// narrows between, and the next symbol's `r` is this symbol's `rng`
56+ /// shifted left by the renormalisation, so the whole string's cost
57+ /// telescopes to `bits_base + shifts - log2(rng)` — one `log2` per price
58+ /// asked for, instead of one per symbol (libaom's `od_ec_enc_tell_frac`
59+ /// reads its account the same way).
60+ shifts: u32,
61+ /// Whether this coder only prices: the bit account depends on nothing but
62+ /// how far each symbol narrows `rng`, so a pricer keeps the interval width
63+ /// and drops the value bookkeeping (`low`, `cnt`, `precarry`) whose only
64+ /// consumer is [`Self::finish`].
65+ pricing: bool,
5566 }
5667
5768 impl Default for SymbolEncoder {
@@ -69,13 +80,25 @@ impl SymbolEncoder {
6980 rng: 0x8000,
7081 cnt: -9,
7182 precarry: Vec::new(),
72- bits: 0.0,
83+ bits_base: 15.0,
84+ shifts: 0,
85+ pricing: false,
86+ }
87+ }
88+
89+ /// A coder that only prices, for a search that wants [`Self::bits`] and
90+ /// will never ask for the bytes. Every symbol narrows `rng` exactly as it
91+ /// would in a writing coder, so the account is the same to the bit.
92+ pub fn pricer() -> SymbolEncoder {
93+ SymbolEncoder {
94+ pricing: true,
95+ ..SymbolEncoder::new()
7396 }
7497 }
7598
7699 /// What the symbols written so far cost, in bits.
77100 pub fn bits(&self) -> f64 {
78- self.bits
101+ self.bits_base + f64::from(self.shifts) - f64::from(self.rng).log2()
79102 }
80103
81104 /// The coder's current interval width — libaom's `od_ec_enc_rng` /
@@ -91,13 +114,15 @@ impl SymbolEncoder {
91114 /// holds one `u16` per byte already flushed. Pairs with the decoder's
92115 /// `aom_reader_tell`, which counts the same bits consumed.
93116 pub fn tell(&self) -> i32 {
117+ debug_assert!(!self.pricing, "a pricer keeps no byte position");
94118 self.cnt + 10 + self.precarry.len() as i32 * 8
95119 }
96120
97121 /// Forgets the cost accumulated so far, so that the next stretch of
98122 /// symbols can be priced on its own.
99123 pub fn reset_bits(&mut self) {
100- self.bits = 0.0;
124+ self.bits_base = f64::from(self.rng).log2();
125+ self.shifts = 0;
101126 }
102127
103128 /// Writes `symbol` against `cdf` and adapts `cdf` exactly as the decoder
@@ -145,9 +170,15 @@ impl SymbolEncoder {
145170 // which is not quite its nominal probability: the coder works the
146171 // range through an eight-bit multiply and hands every symbol above
147172 // this one a floor of `EC_MIN_PROB`. Pricing the narrowing rather than
148- // the table entry is what makes the account match the bytes.
149- self.bits -= (f64::from(rng) / f64::from(r)).log2();
150- self.normalize(low, rng);
173+ // the table entry is what makes the account match the bytes; the
174+ // narrowing itself is read off `rng` and `shifts` by [`Self::bits`].
175+ if self.pricing {
176+ let d = 16 - (32 - rng.leading_zeros());
177+ self.rng = rng << d;
178+ self.shifts += d;
179+ } else {
180+ self.normalize(low, rng);
181+ }
151182 }
152183
153184 /// Writes `bits` raw bits of `value`, most significant first — the `L(n)`
@@ -169,6 +200,7 @@ impl SymbolEncoder {
169200 /// inside it however the decoder pads the string, which is what lets a tile
170201 /// payload end on a byte boundary with no terminator.
171202 pub fn finish(mut self) -> Vec<u8> {
203+ assert!(!self.pricing, "a pricer holds no bytes to flush");
172204 // Round the interval's low end up to a value with 14 low zero bits,
173205 // then set bit 14: the result is inside the interval (the interval is
174206 // at least 2^15 wide before normalisation) and its tail bits are all
@@ -223,6 +255,7 @@ impl SymbolEncoder {
223255 self.low = low << d;
224256 self.rng = rng << d;
225257 self.cnt = s;
258+ self.shifts += d as u32;
226259 }
227260 }
228261
crates/ec-av1/src/tile.rsmodified+39 -14
@@ -2395,8 +2395,7 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 {
23952395 TX16 => &SCANS[2],
23962396 _ => &SCANS[3],
23972397 };
2398- let mut enc = SymbolEncoder::new();
2399- enc.reset_bits();
2398+ let mut enc = SymbolEncoder::pricer();
24002399 write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None);
24012400 enc.bits()
24022401 })
@@ -2449,10 +2448,19 @@ fn write_coeffs(
24492448 ec_rng_trace(|| format!("EC_PLANE plane={plane} tell_before={}", enc.tell()));
24502449 }
24512450 let side = coding.side;
2452- let eob = scan
2453- .iter()
2454- .rposition(|&pos| grid[pos as usize] != 0)
2455- .map_or(0, |i| i + 1);
2451+ // The scan-order search reads the grid in scan order, one dependent load
2452+ // per position, and an all-zero block makes it walk every one of them --
2453+ // which the pricer does for candidate after candidate. A straight-line
2454+ // pass settles that case first: it vectorises, and a block that codes
2455+ // anything at all almost always codes its DC, so it stops at the first
2456+ // element.
2457+ let eob = if grid.iter().all(|&level| level == 0) {
2458+ 0
2459+ } else {
2460+ scan.iter()
2461+ .rposition(|&pos| grid[pos as usize] != 0)
2462+ .map_or(0, |i| i + 1)
2463+ };
24562464 enc.symbol(usize::from(eob == 0), &mut coding.txb_skip[skip_ctx]);
24572465 if plane.is_some() {
24582466 ec_rng_trace(|| {
@@ -2656,10 +2664,22 @@ fn base_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize {
26562664 if row == 0 && col == 0 {
26572665 return 0;
26582666 }
2659- let mag: i32 = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)]
2660- .iter()
2661- .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
2662- .sum();
2667+ // A coefficient two rows and two columns clear of the far edges reaches
2668+ // all five neighbours, so the gather is five loads off one index with no
2669+ // per-neighbour edge test -- which is where this writer spends a third of
2670+ // its coefficient loop.
2671+ let p = row * side + col;
2672+ let mag: i32 = if row + 2 < side && col + 2 < side {
2673+ [p + side, p + 1, p + side + 1, p + 2 * side, p + 2]
2674+ .iter()
2675+ .map(|&i| grid[i].abs().min(3))
2676+ .sum()
2677+ } else {
2678+ [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)]
2679+ .iter()
2680+ .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
2681+ .sum()
2682+ };
26632683 let offset = cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize;
26642684 (((mag + 1) >> 1).min(4) as usize) + offset
26652685 }
@@ -2668,10 +2688,15 @@ fn base_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize {
26682688 /// of its three closest neighbours below and to the right, uncapped, and a
26692689 /// term separating the DC, the corner of the transform, and the rest.
26702690 fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize {
2671- let mag: i32 = [(1, 0), (0, 1), (1, 1)]
2672- .iter()
2673- .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs())
2674- .sum();
2691+ let p = row * side + col;
2692+ let mag: i32 = if row + 1 < side && col + 1 < side {
2693+ grid[p + side].abs() + grid[p + 1].abs() + grid[p + side + 1].abs()
2694+ } else {
2695+ [(1, 0), (0, 1), (1, 1)]
2696+ .iter()
2697+ .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs())
2698+ .sum()
2699+ };
26752700 let mag = (((mag + 1) >> 1).min(6)) as usize;
26762701 if row == 0 && col == 0 {
26772702 mag