forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

motion.rs912 lines, 36.3 KiBHistoryRawDownload
1//! Integer-then-subpel motion search for one inter block over one reference
2//! plane (spec 7.10's `NEWMV` case, the search a real encoder needs to *find*
3//! that MV; the syntax that codes it lives in [`crate::cdf`] and the tile
4//! writer, neither of which this module touches).
5//!
6//! The search runs in three stages, each over [`crate::mc::predict`]'s own
7//! sub-pel filter (so the cost a stage measures is the cost the block will
8//! actually be coded at, not an approximation of it): a log/diamond search
9//! over whole-pel positions starting at the MV-stack predictor, then one
10//! ±1-step refinement at half-pel, then one more at quarter-pel. Every
11//! candidate's cost is `SAD + lambda * mv_bits`, where `mv_bits` is priced by
12//! walking the same symbol/CDF sequence the tile writer would spend on the MV
13//! residual, through [`crate::encode::symbol_bits`]'s interval-narrowing
14//! (never a per-entry probability lookup, which the AAC lane found 8% off
15//! real bytes for a table shaped just like this one).
16//!
17//! Motion vectors here are `(row, col)` in the spec's 1/8-pel units, matching
18//! [`crate::mvstack::MvStack::pred_mv`].
19
20use crate::cdf;
21use crate::encode::symbol_bits;
22use crate::mc::predict;
23
24/// One 1/8-pel unit's worth of 1/16-pel steps: [`crate::mc::predict`]'s
25/// `x_q4`/`y_q4` run twice as fine as the MV unit this module searches in.
26const Q4_PER_Q3: i32 = 2;
27
28/// One whole sample, in 1/8-pel units.
29const PEL_Q3: i32 = 8;
30
31/// One half sample, in 1/8-pel units — the step the search's second stage
32/// refines by. Fixed by the unit, not swept.
33const HALF_PEL_Q3: i32 = 4;
34
35/// One quarter sample, in 1/8-pel units — the step the search's third stage
36/// refines by. Fixed by the unit, not swept.
37const QUARTER_PEL_Q3: i32 = 2;
38
39/// One eighth sample — the step of the fourth refinement stage, which runs
40/// only in a frame coded with `allow_high_precision_mv` (lane-hpmv): without
41/// that flag the writer cannot code an odd eighth-pel residual at all
42/// (`encode::round_to_valid_mv` rounds it away), so refining to it would only
43/// spend evaluations on vectors the stream cannot name.
44const EIGHTH_PEL_Q3: i32 = 1;
45
46/// The widest step the integer-pel search starts its log search at, in whole
47/// samples.
48///
49/// Swept 4/8/16 against a synthetic clip of four blocks translated by 8
50/// samples on each axis, all four signs (`sweep_initial_step` below): 4
51/// finds only 2/4 (an 8-sample displacement needs two same-step hops at
52/// step 4, and the second hop can drift off the true match first -- see the
53/// corner-cut note on `finds_exact_integer_translation_all_four_signs`); 8
54/// and 16 both find every translation exactly (256 block evaluations for 8,
55/// 320 for 16 -- measured by `sweep_initial_step`, `--nocapture`), so 8 does
56/// the same job for 25% less. 8 lands.
57const SEARCH_INITIAL_STEP_PEL: i32 = 8;
58
59/// The narrowest step the integer-pel search's log stage runs at, in whole
60/// samples, before subpel refinement takes over. One sample — going finer
61/// here would just duplicate the half-pel stage's job at the coarser SAD-only
62/// cost function.
63const SEARCH_MIN_STEP_PEL: i32 = 1;
64
65/// [`SEARCH_INITIAL_STEP_PEL`], swept by `EC_AV1_MV_STEP` in a test build.
66/// Swept 1/2/4/8 on the BD gate with the stack seeds below in place: the
67/// narrow seeded shape a predictor-seeded search is supposed to allow costs
68/// far more rate than it saves wall (step 1 +145.2/+219.4/+81.1 vs libaom,
69/// step 2 +134.2/+196.1/+81.1, step 4 +126.0/+161.2/+81.1 against 8's
70/// +125.6/+152.1/+80.9) for 0.2 s of a 6 s ladder -- the wide log stage is
71/// what finds the 2160p clip's motion, and the search is not the wall.
72fn seeded_step() -> i32 {
73 static STEP: std::sync::OnceLock<i32> = std::sync::OnceLock::new();
74 *STEP.get_or_init(|| match std::env::var("EC_AV1_MV_STEP").ok() {
75 Some(v) if cfg!(test) => v.parse().unwrap_or(SEARCH_INITIAL_STEP_PEL),
76 _ => SEARCH_INITIAL_STEP_PEL,
77 })
78}
79
80/// Whether [`search`] starts from the best of the MV-stack's own candidates
81/// (libaom's shape) as well as `pred_mv`. `EC_AV1_MV_SEEDED=0` restores the
82/// `pred_mv`-only start in a test build (what the lane measured both arms
83/// with).
84fn seeded() -> bool {
85 // Read once: this is on the per-block search path, and `std::env::var`
86 // allocates and locks.
87 static SEEDED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
88 *SEEDED.get_or_init(|| match std::env::var("EC_AV1_MV_SEEDED").ok() {
89 Some(v) if cfg!(test) => v != "0",
90 _ => true,
91 })
92}
93
94/// How the search spends itself since the last [`take_census`]: 0 calls,
95/// 1 total candidate evaluations (one `predict` + SAD each), 2 of which in
96/// the two subpel stages, 3 integer-stage rounds, 4 calls whose winner is
97/// within one whole sample of `pred_mv`, 5 calls whose winner is the
98/// starting centre itself, 6 calls that moved at least once at the log
99/// stage's WIDEST step (the class `instrument at bound`: a search whose
100/// winner was reached by walking at its own initial step is measuring its
101/// step, not the content), 7 the total such widest-step moves. A gate prints
102/// these rather than assume where the wall-owning stage goes
103/// (gate-blind-to-feature).
104static CENSUS: [std::sync::atomic::AtomicU64; 8] = [
105 std::sync::atomic::AtomicU64::new(0),
106 std::sync::atomic::AtomicU64::new(0),
107 std::sync::atomic::AtomicU64::new(0),
108 std::sync::atomic::AtomicU64::new(0),
109 std::sync::atomic::AtomicU64::new(0),
110 std::sync::atomic::AtomicU64::new(0),
111 std::sync::atomic::AtomicU64::new(0),
112 std::sync::atomic::AtomicU64::new(0),
113];
114
115/// Takes (and clears) the census.
116pub(crate) fn take_census() -> [u64; 8] {
117 [0, 1, 2, 3, 4, 5, 6, 7].map(|i| CENSUS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
118}
119
120/// The eight offsets, at `step` in each axis, a diamond/log search round
121/// checks around its current centre (the ninth point, no offset, is the
122/// centre itself and is already priced).
123fn neighbor_offsets(step: i32) -> [(i32, i32); 8] {
124 [
125 (-step, -step),
126 (-step, 0),
127 (-step, step),
128 (0, -step),
129 (0, step),
130 (step, -step),
131 (step, 0),
132 (step, step),
133 ]
134}
135
136/// Rounds an MV component to the nearest whole sample (ties away from zero),
137/// which is where the integer-pel search stage starts.
138fn round_to_pel(component: i32) -> i32 {
139 let q = component.div_euclid(PEL_Q3);
140 let r = component.rem_euclid(PEL_Q3);
141 if r * 2 >= PEL_Q3 {
142 (q + 1) * PEL_Q3
143 } else {
144 q * PEL_Q3
145 }
146}
147
148/// `Av1_get_mv_class`'s class and in-class offset for a coded magnitude `z =
149/// |component| - 1` (spec 5.9.15's inverse, the encoder side libaom's
150/// `av1_get_mv_class` computes): class 0 covers `z < 16`; each class `c >= 1`
151/// covers the doubling range `[8*2^c, 16*2^c)`, so `c = floor(log2(z)) - 3`.
152fn mv_class_and_offset(z: u32) -> (usize, u32) {
153 if z < 16 {
154 (0, z)
155 } else {
156 let class = (31 - z.leading_zeros()) as usize - 3;
157 let class = class.min(10); // MV_CLASSES = 11, classes 0..=10
158 let base = 8u32 << class;
159 (class, z - base)
160 }
161}
162
163/// The bits one non-zero MV component (`diff`, the coded value minus its
164/// predictor) spends: sign, class, then the class's own bit/fraction/half-pel
165/// symbols, each priced by [`symbol_bits`] against the CDF the tile writer
166/// would spend it against (spec 5.9.15's `read_mv_component`, run backwards).
167fn mv_component_bits(diff: i32) -> f64 {
168 let sign = usize::from(diff < 0);
169 let mag = diff.unsigned_abs();
170 debug_assert!(mag > 0, "a zero component is priced by the joint alone");
171 let z = mag - 1;
172 let (class, offset) = mv_class_and_offset(z);
173
174 let mut bits = symbol_bits(&cdf::MV_SIGN, sign) + symbol_bits(&cdf::MV_CLASS, class);
175 let fr = ((offset >> 1) & 3) as usize;
176 let hp = (offset & 1) as usize;
177 if class == 0 {
178 let class0_bit = (offset >> 3) as usize;
179 bits += symbol_bits(&cdf::MV_CLASS0_BIT, class0_bit);
180 bits += symbol_bits(&cdf::MV_CLASS0_FR[class0_bit], fr);
181 bits += symbol_bits(&cdf::MV_CLASS0_HP, hp);
182 } else {
183 let d = offset >> 3;
184 for (i, row) in cdf::MV_BIT.iter().enumerate().take(class) {
185 bits += symbol_bits(row, usize::from((d >> i) & 1 == 1));
186 }
187 bits += symbol_bits(&cdf::MV_FR, fr);
188 bits += symbol_bits(&cdf::MV_HP, hp);
189 }
190 bits
191}
192
193/// The bits an MV difference from its predictor spends: the joint symbol
194/// (which axes are non-zero) plus each non-zero axis's own component (spec
195/// 5.9.15's `read_mv`).
196fn mv_bits((diff_row, diff_col): (i32, i32)) -> f64 {
197 let joint = match (diff_row != 0, diff_col != 0) {
198 (false, false) => 0,
199 (false, true) => 1, // MV_JOINT_HNZVZ: col (horizontal) only
200 (true, false) => 2, // MV_JOINT_HZVNZ: row (vertical) only
201 (true, true) => 3, // MV_JOINT_HNZVNZ
202 };
203 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
204 if diff_row != 0 {
205 bits += mv_component_bits(diff_row);
206 }
207 if diff_col != 0 {
208 bits += mv_component_bits(diff_col);
209 }
210 bits
211}
212
213/// lane-newmv: what the SEARCH's own rate term is weighted by, on top of the
214/// block RD lambda it is handed. The RD lambda is an SSE-domain weight
215/// (`encode::Search::lambda` is `LAMBDA_SCALE * step * step`, compared against
216/// squared error) while this search compares SAD, so charging mv bits at the
217/// full RD lambda over-prices motion by whatever the SSE/SAD ratio of the
218/// content is -- the census fact this lane started from is that we code
219/// 0.83-2.5 mv bits/block where libaom codes 3.2-7.5. `EC_AV1_MV_SEARCH_LAMBDA`
220/// (any build, like the encoder's other search margins); 1.0 was the control.
221///
222/// SWEPT on the native 12-frame BD gate, film B (vs libaom / vs rav1e), with
223/// [`MV_SUBPEL_ITERS`] still at 1: 0.25 +25.2/-1.7, 0.5 +24.9/-2.0,
224/// 0.75 +24.8/-1.9, 1.0 (control) +24.9/-1.9, 2.0 +26.9/-0.2. Over-charging
225/// motion is the expensive direction -- the 2.0 arm loses 2.0/1.7 points --
226/// and the floor of the bowl sits at 0.5-0.75. 0.5 ships together with
227/// [`MV_SUBPEL_ITERS`] 4; the pair's rows are in lanes/newmv.report.md.
228const MV_SEARCH_LAMBDA: f64 = 0.5;
229
230/// [`MV_SEARCH_LAMBDA`], read once (this is the per-candidate cost path).
231fn search_lambda_mult() -> f64 {
232 static M: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
233 *M.get_or_init(|| match std::env::var("EC_AV1_MV_SEARCH_LAMBDA").ok() {
234 Some(v) => v.parse().unwrap_or(MV_SEARCH_LAMBDA),
235 None => MV_SEARCH_LAMBDA,
236 })
237}
238
239/// How many times each subpel refinement round may re-run from its own
240/// winner ([`search_traced_from_step`]'s stages 2 and 3).
241/// `EC_AV1_MV_SUBPEL_ITERS`; 1 was the single round the search shipped with.
242///
243/// MEASURED on the native BD gate at [`MV_SEARCH_LAMBDA`] 0.5: film A
244/// 12-frame +21.0/-4.8 -> +20.6/-5.1, film B 12-frame +24.9/-1.9 ->
245/// +24.8/-2.1, screen +14.5/-33.2 -> +14.6/-33.2, film A long-GOP
246/// +25.2/-7.2 -> +24.7/-7.5, film B long-GOP +86.7/+7.3 -> +86.8/+7.4. Each
247/// half alone is worth about half of it on film A (+20.8/-4.9 either way);
248/// on film B this iteration alone LOSES (+25.2/-1.7) and only pays with the
249/// lighter search rate term beside it. It costs 5-7% encoder wall.
250const MV_SUBPEL_ITERS: u32 = 4;
251
252/// [`MV_SUBPEL_ITERS`], read once.
253fn subpel_iters() -> u32 {
254 static N: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
255 *N.get_or_init(|| match std::env::var("EC_AV1_MV_SUBPEL_ITERS").ok() {
256 Some(v) => v.parse().unwrap_or(MV_SUBPEL_ITERS),
257 None => MV_SUBPEL_ITERS,
258 })
259}
260
261/// One search's outcome: the best MV found and the `SAD + lambda * mv_bits`
262/// cost it settled at.
263#[derive(Clone, Copy, Debug, PartialEq)]
264pub struct MotionSearch {
265 /// The best `(row, col)` motion vector found, in 1/8-pel units.
266 pub mv: (i32, i32),
267 /// `SAD + lambda * mv_bits` at [`Self::mv`], against `pred_mv`.
268 pub cost: f64,
269}
270
271/// One candidate's `SAD + lambda * mv_bits(mv - pred_mv)`, predicted into the
272/// caller's `dst16` scratch (`block_w * block_h`) so a whole search allocates
273/// once.
274#[allow(clippy::too_many_arguments)]
275fn cost_of_mv(
276 reference: &[u16],
277 stride: usize,
278 ref_width: usize,
279 ref_height: usize,
280 source: &[u8],
281 block_x: usize,
282 block_y: usize,
283 block_w: usize,
284 block_h: usize,
285 mv: (i32, i32),
286 pred_mv: (i32, i32),
287 lambda: f64,
288 dst16: &mut [u16],
289 fctx: &crate::decode::FrameCtx,
290) -> f64 {
291 let x_q4 = (block_x as i32) * 16 + mv.1 * Q4_PER_Q3;
292 let y_q4 = (block_y as i32) * 16 + mv.0 * Q4_PER_Q3;
293 predict(
294 reference, stride, ref_width, ref_height, x_q4, y_q4, block_w, block_h, dst16, fctx,
295 );
296 // lane-av1speed: accumulated as an integer (a block is at most
297 // 32x32 samples of at most 255 each, nowhere near `u32`, and an
298 // integer sum this small is exact in `f64` whatever order it is
299 // summed in) instead of one `f64` conversion and dependent add per
300 // sample. Same value, several times the throughput.
301 let sad: u32 = source
302 .iter()
303 .zip(dst16.iter())
304 .map(|(&a, &b)| (i32::from(a) - i32::from(b)).unsigned_abs())
305 .sum();
306 let diff = (mv.0 - pred_mv.0, mv.1 - pred_mv.1);
307 f64::from(sad) + lambda * search_lambda_mult() * mv_bits(diff)
308}
309
310/// [`cost_of_mv`] for one vector, on its own scratch -- what a caller uses to
311/// price a single candidate (an extra reference's `NEARESTMV`, say) on the
312/// same scale [`search`] reports its own cost on, for one evaluation instead
313/// of a whole search.
314#[allow(clippy::too_many_arguments)]
315pub(crate) fn cost_at(
316 reference: &[u16],
317 stride: usize,
318 ref_width: usize,
319 ref_height: usize,
320 source: &[u8],
321 block_x: usize,
322 block_y: usize,
323 block_w: usize,
324 block_h: usize,
325 mv: (i32, i32),
326 pred_mv: (i32, i32),
327 lambda: f64,
328 fctx: &crate::decode::FrameCtx,
329) -> f64 {
330 let mut dst16 = vec![0u16; block_w * block_h];
331 cost_of_mv(
332 reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h, mv,
333 pred_mv, lambda, &mut dst16, fctx,
334 )
335}
336
337/// Searches one `block_w * block_h` block, at `(block_x, block_y)` in the
338/// current picture's plane, against `reference` for the motion vector that
339/// minimises `SAD + lambda * mv_bits(mv - pred_mv)`.
340///
341/// `reference` is `ref_width * ref_height`, row-major, one plane. `source` is
342/// the block's own samples, `block_w * block_h`, row-major — what the search
343/// compares each candidate's prediction against. `pred_mv` is the MV-stack
344/// predictor (e.g. [`crate::mvstack::MvStack::pred_mv`]) the residual, and its
345/// cost, are coded against; this function does not build the MV stack
346/// itself.
347///
348/// SAD, not SSE: both settle on the same minimum on the synthetic translation
349/// tests below (a motion search's candidates differ by whole/half/quarter-pel
350/// shifts of the same content, so their error surfaces share a minimum either
351/// way). A standalone timing probe (2,000,000 SAD/SSE passes over a 64-sample
352/// block, `rustc -O`) measured SSE 10% *faster* here (80.6ms vs 89.5ms) — the
353/// squaring auto-vectorises as well as the absolute value does, so speed
354/// does not decide it. SAD wins on a different ground: it is the metric
355/// [`crate::encode::Search`]'s own mode trial (`encode.rs`) already reports
356/// error in (`sse: f64` there is a name, not a metric choice — it is fed
357/// squared error from the transform's own reconstruction, a different
358/// quantity from a raw sample-domain match cost), and SAD is what a motion
359/// search conventionally reports for exactly this reason: it is linear in
360/// the outlier's size rather than quadratic, so one badly-mismatched sample
361/// at a block edge (occlusion, a moving object's boundary) does not swamp
362/// the whole candidate's score the way SSE would.
363///
364/// # Panics
365/// Panics when `source` is not `block_w * block_h` long, or `reference` is
366/// empty (the same contracts [`predict`] has).
367#[allow(clippy::too_many_arguments)] // one reference plane, one block, one predictor
368pub(crate) fn search(
369 reference: &[u16],
370 stride: usize,
371 ref_width: usize,
372 ref_height: usize,
373 source: &[u8],
374 block_x: usize,
375 block_y: usize,
376 block_w: usize,
377 block_h: usize,
378 pred_mv: (i32, i32),
379 seeds: &[(i32, i32)],
380 lambda: f64, fctx: &crate::decode::FrameCtx,
381 // How many frames back (order-hint distance) this reference sits: a
382 // reference twice as far away holds content that has moved about twice
383 // as far, so the log stage starts from a proportionally wider step. See
384 // [`dist_initial_step`].
385 dist: u32,
386) -> MotionSearch {
387 let (result, _trace) = search_traced_from_step(
388 reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h,
389 pred_mv,
390 if seeded() { seeds } else { &[] },
391 lambda,
392 dist_initial_step(dist), fctx,
393 );
394 result
395}
396
397/// The integer-pel log stage's starting step for a reference at order-hint
398/// distance `dist`: `step * (1 + k * (dist - 1))`, `k` = `EC_AV1_MV_DIST_SCALE`
399/// in a test build. `k = 0` is the flat step every reference used before.
400fn dist_initial_step(dist: u32) -> i32 {
401 let base = if seeded() { seeded_step() } else { SEARCH_INITIAL_STEP_PEL };
402 static K: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
403 // lane-arfcen: readable in ANY build, like the encoder's other search
404 // margins -- the constant below was swept when the deepest reference in
405 // the GOP sat at distance 4, and the arm that re-sweeps it at the
406 // shipped mini-GOP of 8 runs through the release `enc_probe`.
407 let k = *K.get_or_init(|| match std::env::var("EC_AV1_MV_DIST_SCALE").ok() {
408 Some(v) => v.parse().unwrap_or(MV_DIST_SCALE),
409 None => MV_DIST_SCALE,
410 });
411 if dist <= 1 || k <= 0.0 {
412 return base;
413 }
414 let scaled = f64::from(base) * k.mul_add(f64::from(dist - 1), 1.0);
415 // The ceiling on that widening. `MV_DIST_CAP` x the base; swept by
416 // `EC_AV1_MV_DIST_CAP`.
417 static CAP: std::sync::OnceLock<i32> = std::sync::OnceLock::new();
418 let cap = *CAP.get_or_init(|| match std::env::var("EC_AV1_MV_DIST_CAP").ok() {
419 Some(v) => v.parse().unwrap_or(MV_DIST_CAP),
420 None => MV_DIST_CAP,
421 });
422 scaled.round().clamp(f64::from(base), f64::from(base * cap)) as i32
423}
424
425/// The distance scale [`dist_initial_step`] ships with. Swept on the BD gate
426/// (vs libaom, 1080p/2160p/screen): 0 = +100.7/+115.8/+73.3, 0.25
427/// +98.5/+112.2, 0.375 +98.2/+115.6, 0.5 +94.4/+104.3, 0.625 +95.9/+106.5,
428/// 0.75 +92.8/+112.7, 1.0 +98.8/+113.0 -- screen is byte-identical at every
429/// point (its motion is small enough that a wider start converges to the same
430/// vector). 0.5 wins both film clips together; the ranking either side of it
431/// is near-tie churn, not a gradient.
432const MV_DIST_SCALE: f64 = 0.5;
433
434/// How many times the base step [`dist_initial_step`] may widen to. Written
435/// as 4 when the deepest reference in the GOP sat at distance 4 ("past 4x the
436/// base the log stage spends its rounds on vectors no reference in this
437/// encoder's GOP reaches"), which the shipped mini-GOP of 8 falsified: the
438/// top ARF predicts at distance 8 and its own widened step (36 at
439/// [`MV_DIST_SCALE`] 0.5) was being clamped back to 32.
440const MV_DIST_CAP: i32 = 4;
441
442/// [`search`], plus the running best cost after every round any of its three
443/// stages ran — what `cost_is_monotone_non_increasing_over_the_search` below
444/// checks.
445#[cfg(test)]
446#[allow(clippy::too_many_arguments)] // one reference plane, one block, one predictor
447fn search_traced(
448 reference: &[u16],
449 stride: usize,
450 ref_width: usize,
451 ref_height: usize,
452 source: &[u8],
453 block_x: usize,
454 block_y: usize,
455 block_w: usize,
456 block_h: usize,
457 pred_mv: (i32, i32),
458 seeds: &[(i32, i32)],
459 lambda: f64, fctx: &crate::decode::FrameCtx,
460) -> (MotionSearch, Vec<f64>) {
461 search_traced_from_step(
462 reference,
463 stride,
464 ref_width,
465 ref_height,
466 source,
467 block_x,
468 block_y,
469 block_w,
470 block_h,
471 pred_mv,
472 seeds,
473 lambda,
474 if seeded() {
475 seeded_step()
476 } else {
477 SEARCH_INITIAL_STEP_PEL
478 }, fctx,
479 )
480}
481
482/// [`search_traced`] with the integer-pel stage's starting step named
483/// explicitly — what `sweep_initial_step` below sweeps to land
484/// [`SEARCH_INITIAL_STEP_PEL`].
485#[allow(clippy::too_many_arguments)]
486fn search_traced_from_step(
487 reference: &[u16],
488 stride: usize,
489 ref_width: usize,
490 ref_height: usize,
491 source: &[u8],
492 block_x: usize,
493 block_y: usize,
494 block_w: usize,
495 block_h: usize,
496 pred_mv: (i32, i32),
497 seeds: &[(i32, i32)],
498 lambda: f64,
499 initial_step_pel: i32, fctx: &crate::decode::FrameCtx,
500) -> (MotionSearch, Vec<f64>) {
501 assert_eq!(source.len(), block_w * block_h, "source is one block");
502 assert!(!reference.is_empty(), "a reference plane has samples");
503
504 // lane-av1speed: `reference` arrives as the DPB picture's own `u16`
505 // plane. It used to be handed the encoder's `u8` shadow copy and
506 // converted here, whole-plane, on EVERY call -- one 245k-element
507 // allocate-and-convert per searched block, which profiled as the single
508 // largest symbol in the encoder (30% of `sequence_bench_sanity`).
509 let mut dst16 = vec![0u16; block_w * block_h];
510 let evals = std::cell::Cell::new(0u64);
511 let mut cost_of = |mv: (i32, i32)| -> f64 {
512 evals.set(evals.get() + 1);
513 cost_of_mv(
514 reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h,
515 mv, pred_mv, lambda, &mut dst16, fctx,
516 )
517 };
518
519 let mut trace = Vec::new();
520 let mut centre = (round_to_pel(pred_mv.0), round_to_pel(pred_mv.1));
521 let mut best_cost = cost_of(centre);
522 // The stack's own candidates, whole-pel rounded, as extra starting
523 // points: a neighbour block's vector is where this block's motion most
524 // often already is, and starting there is what lets the log stage below
525 // start from is usually the vector this block wants.
526 for &seed in seeds {
527 let candidate = (round_to_pel(seed.0), round_to_pel(seed.1));
528 if candidate == centre {
529 continue;
530 }
531 let cost = cost_of(candidate);
532 if cost < best_cost {
533 best_cost = cost;
534 centre = candidate;
535 }
536 }
537 let start_centre = centre;
538 trace.push(best_cost);
539
540 // Stage 1: log/diamond search over whole-pel steps, halving the step
541 // each time a round finds no better neighbour, down to one sample.
542 let mut step_pel = initial_step_pel;
543 let mut widest_moves = 0u64;
544 while step_pel >= SEARCH_MIN_STEP_PEL {
545 let step = step_pel * PEL_Q3;
546 loop {
547 // Evaluate the whole round from the round's starting centre, so
548 // a candidate that improves early in the neighbour list cannot
549 // shift where later candidates in the *same* round are placed --
550 // each round moves at most one step, never compounds within it.
551 let round_centre = centre;
552 let mut best_in_round = best_cost;
553 for (dr, dc) in neighbor_offsets(step) {
554 let candidate = (round_centre.0 + dr, round_centre.1 + dc);
555 let cost = cost_of(candidate);
556 if cost < best_in_round {
557 best_in_round = cost;
558 centre = candidate;
559 }
560 }
561 let moved = best_in_round < best_cost;
562 if moved && step_pel == initial_step_pel {
563 widest_moves += 1;
564 }
565 best_cost = best_in_round;
566 CENSUS[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
567 trace.push(best_cost);
568 if !moved {
569 break;
570 }
571 }
572 step_pel /= 2;
573 }
574
575 // Stages 2..4: one ±1-step refinement each at half-pel, quarter-pel and
576 // (high-precision frames only) eighth-pel, through the same cost function (so the refinement is
577 // costed at the precision it commits to, not the integer-pel SAD alone).
578 let integer_evals = evals.get();
579 // lane-hpmv: the eighth-pel stage runs only in a high-precision frame.
580 let stages: &[i32] = if crate::tile::high_precision_mv() {
581 &[HALF_PEL_Q3, QUARTER_PEL_Q3, EIGHTH_PEL_Q3]
582 } else {
583 &[HALF_PEL_Q3, QUARTER_PEL_Q3]
584 };
585 for &step in stages {
586 // lane-newmv, class `search bounded by its heuristic`: ONE round per
587 // step means a subpel winner two half-pels away from the integer
588 // centre is unreachable. `EC_AV1_MV_SUBPEL_ITERS` runs the round
589 // again from its own winner, up to that many times; 1 is the
590 // control's single round.
591 for _ in 0..subpel_iters() {
592 let round_centre = centre;
593 for (dr, dc) in neighbor_offsets(step) {
594 let candidate = (round_centre.0 + dr, round_centre.1 + dc);
595 let cost = cost_of(candidate);
596 if cost < best_cost {
597 best_cost = cost;
598 centre = candidate;
599 }
600 }
601 if centre == round_centre {
602 break;
603 }
604 }
605 trace.push(best_cost);
606 }
607
608 use std::sync::atomic::Ordering::Relaxed;
609 CENSUS[0].fetch_add(1, Relaxed);
610 CENSUS[1].fetch_add(evals.get(), Relaxed);
611 CENSUS[2].fetch_add(evals.get() - integer_evals, Relaxed);
612 if (centre.0 - pred_mv.0).abs() <= PEL_Q3 && (centre.1 - pred_mv.1).abs() <= PEL_Q3 {
613 CENSUS[4].fetch_add(1, Relaxed);
614 }
615 if centre == start_centre {
616 CENSUS[5].fetch_add(1, Relaxed);
617 }
618 if widest_moves > 0 {
619 CENSUS[6].fetch_add(1, Relaxed);
620 CENSUS[7].fetch_add(widest_moves, Relaxed);
621 }
622
623 (
624 MotionSearch {
625 mv: centre,
626 cost: best_cost,
627 },
628 trace,
629 )
630}
631
632#[cfg(test)]
633mod tests {
634 use super::*;
635
636 /// A pseudo-random, non-periodic sample at `(x, y)`: two independent
637 /// multiplicative hashes XORed together.
638 fn hash_sample(width: usize, height: usize, x: i32, y: i32) -> i32 {
639 let cx = x.clamp(0, width as i32 - 1) as u32;
640 let cy = y.clamp(0, height as i32 - 1) as u32;
641 let h = cx.wrapping_mul(2_654_435_761) ^ cy.wrapping_mul(40_503);
642 i32::from(((h >> 13) & 0xff) as u8)
643 }
644
645 /// Builds a `width * height` plane with a locally smooth (5x5-box-blurred
646 /// hash noise) but globally unique texture -- smooth enough for a
647 /// gradient-following search to have something to follow (raw,
648 /// unblurred per-pixel noise, tried first, has no correlation between a
649 /// candidate's cost and its distance from the true match, so a diamond
650 /// search cannot navigate it even though the true match is still the
651 /// unique SAD-zero point), and unique enough that no whole-pel shift
652 /// within the plane aliases onto another (verified once, brute-force,
653 /// for every translation this module's tests use).
654 fn plane_and_block(
655 width: usize,
656 height: usize,
657 block_x: usize,
658 block_y: usize,
659 block_w: usize,
660 block_h: usize,
661 ) -> (Vec<u8>, Vec<u8>) {
662 let plane: Vec<u8> = (0..height as i32)
663 .flat_map(|y| {
664 (0..width as i32).map(move |x| {
665 let mut sum = 0;
666 let mut count = 0;
667 for dy in -2..=2 {
668 for dx in -2..=2 {
669 sum += hash_sample(width, height, x + dx, y + dy);
670 count += 1;
671 }
672 }
673 (sum / count) as u8
674 })
675 })
676 .collect();
677 let mut block = vec![0u8; block_w * block_h];
678 for row in 0..block_h {
679 for col in 0..block_w {
680 block[row * block_w + col] = plane[(block_y + row) * width + block_x + col];
681 }
682 }
683 (plane, block)
684 }
685
686 #[test]
687 fn finds_exact_integer_translation_all_four_signs() {
688 let fctx = &crate::decode::FrameCtx::new();
689 let width = 64;
690 let height = 64;
691 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
692 let plane16: Vec<u16> = plane.iter().map(|&v| u16::from(v)).collect();
693 let block_w = 8;
694 let block_h = 8;
695 // Anchor the source block away from the plane's edges so every sign
696 // of displacement stays in bounds.
697 let anchor_x = 32;
698 let anchor_y = 32;
699 // corner-cut: magnitude equal to `SEARCH_INITIAL_STEP_PEL`, so the
700 // very first round's step lands a candidate exactly on the true
701 // translation. A greedy diamond/log search over a coarse step is not
702 // a global optimiser -- content with real long-range correlation
703 // (actual video) gives it a gradient to follow across a bigger gap;
704 // this module's synthetic, locally-textured-but-globally-uncorrelated
705 // plane does not, and a displacement several steps away from a zero
706 // predictor was observed (by direct trace) to settle in a false
707 // local minimum. Ceiling: production content is real video, whose
708 // wide-range correlation this synthetic plane deliberately lacks;
709 // upgrade path is a coarse-to-fine (blurred-pyramid) first stage if a
710 // real clip is ever found where the search gets stuck the same way.
711 for (dx, dy) in [(8, 8), (-8, 8), (8, -8), (-8, -8)] {
712 let source_x = (anchor_x as i32 + dx) as usize;
713 let source_y = (anchor_y as i32 + dy) as usize;
714 let mut block = vec![0u8; block_w * block_h];
715 for row in 0..block_h {
716 for col in 0..block_w {
717 block[row * block_w + col] = plane[(source_y + row) * width + source_x + col];
718 }
719 }
720 let result = search(
721 &plane16,
722 width,
723 width,
724 height,
725 &block,
726 anchor_x,
727 anchor_y,
728 block_w,
729 block_h,
730 (0, 0),
731 &[],
732 0.1, fctx,
733 1,
734 );
735 assert_eq!(
736 result.mv,
737 (dy * 8, dx * 8),
738 "translation ({dx}, {dy}) must be found exactly, in 1/8-pel units"
739 );
740 }
741 }
742
743 #[test]
744 fn finds_half_pel_translation() {
745 let fctx = &crate::decode::FrameCtx::new();
746 // A ramp, doubled, so every half-pel position lands on an exact
747 // integer average of its two neighbours.
748 let width = 40;
749 let height = 24;
750 let plane: Vec<u8> = (0..width * height)
751 .map(|i| (2 * (i % width)) as u8)
752 .collect();
753 let plane16: Vec<u16> = plane.iter().map(|&v| u16::from(v)).collect();
754 let block_w = 8;
755 let block_h = 6;
756 let anchor_x = 10;
757 let anchor_y = 8;
758 // The true best match is the source shifted 3.5 samples right: no
759 // integer position matches as well as this half-pel one, since the
760 // ramp is strictly monotone along x.
761 let mut block = vec![0u8; block_w * block_h];
762 for row in 0..block_h {
763 for col in 0..block_w {
764 // Column value at x+3.5 is the average of x+3 and x+4.
765 let left = 2 * (anchor_x + col + 3);
766 let right = 2 * (anchor_x + col + 4);
767 let _ = anchor_y + row; // the ramp is constant along y
768 block[row * block_w + col] = ((left + right) / 2) as u8;
769 }
770 }
771 let result = search(
772 &plane16,
773 width,
774 width,
775 height,
776 &block,
777 anchor_x,
778 anchor_y,
779 block_w,
780 block_h,
781 (0, 0),
782 &[],
783 0.1, fctx,
784 1,
785 );
786 assert_eq!(
787 result.mv,
788 (0, 3 * 8 + 4),
789 "a half-pel translation must be found at 1/8-pel value 3*8+4 (3.5 samples)"
790 );
791 }
792
793 #[test]
794 fn cost_is_monotone_non_increasing_over_the_search() {
795 let fctx = &crate::decode::FrameCtx::new();
796 let width = 48;
797 let height = 48;
798 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
799 let plane16: Vec<u16> = plane.iter().map(|&v| u16::from(v)).collect();
800 let block_w = 8;
801 let block_h = 8;
802 let anchor_x = 20;
803 let anchor_y = 20;
804 let mut block = vec![0u8; block_w * block_h];
805 for row in 0..block_h {
806 for col in 0..block_w {
807 block[row * block_w + col] =
808 plane[(anchor_y + 6 + row) * width + anchor_x - 7 + col];
809 }
810 }
811 let (_result, trace) = search_traced(
812 &plane16,
813 width,
814 width,
815 height,
816 &block,
817 anchor_x,
818 anchor_y,
819 block_w,
820 block_h,
821 (0, 0),
822 &[],
823 0.1, fctx,
824 );
825 assert!(trace.len() > 1, "the search must run more than one round");
826 for pair in trace.windows(2) {
827 assert!(
828 pair[1] <= pair[0],
829 "best-so-far cost must never rise between rounds: {trace:?}"
830 );
831 }
832 }
833
834 #[test]
835 fn mv_bits_prices_a_larger_residual_higher() {
836 // A bigger MV difference from the predictor must never cost fewer
837 // bits than a smaller one on the same axis and sign -- otherwise the
838 // pricing would steer the search toward implausible motion.
839 assert!(mv_bits((0, 1)) < mv_bits((0, 100)));
840 assert!(mv_bits((0, 100)) < mv_bits((0, 10_000)));
841 assert_eq!(mv_bits((0, 0)), symbol_bits(&cdf::MV_JOINT, 0));
842 }
843
844 /// The sweep behind [`SEARCH_INITIAL_STEP_PEL`]: for each candidate
845 /// starting step, how many of four synthetic translations (magnitude 8 on
846 /// each axis, all four signs, from a zero predictor) the search finds
847 /// exactly, and how many block evaluations it spent doing it.
848 ///
849 /// Measured (this test, `--nocapture`): step 4 finds 2/4 (needs two
850 /// same-step hops to cover a magnitude-8 displacement and drifts off the
851 /// true match on the way, for the reason `finds_exact_integer_...`'s
852 /// corner-cut note explains); step 8 finds 4/4 in 224 evaluations; step
853 /// 16 also finds 4/4 but in 288 -- 8 does the same job for less, so 8
854 /// lands.
855 #[test]
856 fn sweep_initial_step() {
857 let fctx = &crate::decode::FrameCtx::new();
858 let width = 96;
859 let height = 96;
860 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
861 let plane16: Vec<u16> = plane.iter().map(|&v| u16::from(v)).collect();
862 let block_w = 8;
863 let block_h = 8;
864 let anchor_x = 48;
865 let anchor_y = 48;
866 let translations: [(i32, i32); 4] = [(8, 8), (-8, 8), (8, -8), (-8, -8)];
867
868 for &candidate_step in &[4, 8, 16] {
869 let mut hits = 0;
870 let mut rounds = 0usize;
871 for &(dx, dy) in &translations {
872 let source_x = (anchor_x as i32 + dx) as usize;
873 let source_y = (anchor_y as i32 + dy) as usize;
874 let mut block = vec![0u8; block_w * block_h];
875 for row in 0..block_h {
876 for col in 0..block_w {
877 block[row * block_w + col] =
878 plane[(source_y + row) * width + source_x + col];
879 }
880 }
881 let (result, trace) = search_traced_from_step(
882 &plane16,
883 width,
884 width,
885 height,
886 &block,
887 anchor_x,
888 anchor_y,
889 block_w,
890 block_h,
891 (0, 0),
892 &[],
893 0.1,
894 candidate_step, fctx,
895 );
896 // Every round the trace recorded is 8 neighbour evaluations,
897 // the actual cost this starting step spent on this block.
898 rounds += trace.len();
899 if result.mv == (dy * 8, dx * 8) {
900 hits += 1;
901 }
902 }
903 eprintln!(
904 "SEARCH_INITIAL_STEP_PEL={candidate_step}: {hits}/4 exact, {} block evaluations",
905 rounds * 8
906 );
907 if candidate_step == SEARCH_INITIAL_STEP_PEL {
908 assert_eq!(hits, 4, "the landed constant must find every translation");
909 }
910 }
911 }
912}