forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

motion.rs811 lines, 31.2 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/// The widest step the integer-pel search starts its log search at, in whole
40/// samples.
41///
42/// Swept 4/8/16 against a synthetic clip of four blocks translated by 8
43/// samples on each axis, all four signs (`sweep_initial_step` below): 4
44/// finds only 2/4 (an 8-sample displacement needs two same-step hops at
45/// step 4, and the second hop can drift off the true match first -- see the
46/// corner-cut note on `finds_exact_integer_translation_all_four_signs`); 8
47/// and 16 both find every translation exactly (256 block evaluations for 8,
48/// 320 for 16 -- measured by `sweep_initial_step`, `--nocapture`), so 8 does
49/// the same job for 25% less. 8 lands.
50const SEARCH_INITIAL_STEP_PEL: i32 = 8;
51
52/// The narrowest step the integer-pel search's log stage runs at, in whole
53/// samples, before subpel refinement takes over. One sample — going finer
54/// here would just duplicate the half-pel stage's job at the coarser SAD-only
55/// cost function.
56const SEARCH_MIN_STEP_PEL: i32 = 1;
57
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.
65fn 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).
77fn 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).
93static 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)]
104pub(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
108/// The eight offsets, at `step` in each axis, a diamond/log search round
109/// checks around its current centre (the ninth point, no offset, is the
110/// centre itself and is already priced).
111fn neighbor_offsets(step: i32) -> [(i32, i32); 8] {
112 [
113 (-step, -step),
114 (-step, 0),
115 (-step, step),
116 (0, -step),
117 (0, step),
118 (step, -step),
119 (step, 0),
120 (step, step),
121 ]
122}
123
124/// Rounds an MV component to the nearest whole sample (ties away from zero),
125/// which is where the integer-pel search stage starts.
126fn round_to_pel(component: i32) -> i32 {
127 let q = component.div_euclid(PEL_Q3);
128 let r = component.rem_euclid(PEL_Q3);
129 if r * 2 >= PEL_Q3 {
130 (q + 1) * PEL_Q3
131 } else {
132 q * PEL_Q3
133 }
134}
135
136/// `Av1_get_mv_class`'s class and in-class offset for a coded magnitude `z =
137/// |component| - 1` (spec 5.9.15's inverse, the encoder side libaom's
138/// `av1_get_mv_class` computes): class 0 covers `z < 16`; each class `c >= 1`
139/// covers the doubling range `[8*2^c, 16*2^c)`, so `c = floor(log2(z)) - 3`.
140fn mv_class_and_offset(z: u32) -> (usize, u32) {
141 if z < 16 {
142 (0, z)
143 } else {
144 let class = (31 - z.leading_zeros()) as usize - 3;
145 let class = class.min(10); // MV_CLASSES = 11, classes 0..=10
146 let base = 8u32 << class;
147 (class, z - base)
148 }
149}
150
151/// The bits one non-zero MV component (`diff`, the coded value minus its
152/// predictor) spends: sign, class, then the class's own bit/fraction/half-pel
153/// symbols, each priced by [`symbol_bits`] against the CDF the tile writer
154/// would spend it against (spec 5.9.15's `read_mv_component`, run backwards).
155fn mv_component_bits(diff: i32) -> f64 {
156 let sign = usize::from(diff < 0);
157 let mag = diff.unsigned_abs();
158 debug_assert!(mag > 0, "a zero component is priced by the joint alone");
159 let z = mag - 1;
160 let (class, offset) = mv_class_and_offset(z);
161
162 let mut bits = symbol_bits(&cdf::MV_SIGN, sign) + symbol_bits(&cdf::MV_CLASS, class);
163 let fr = ((offset >> 1) & 3) as usize;
164 let hp = (offset & 1) as usize;
165 if class == 0 {
166 let class0_bit = (offset >> 3) as usize;
167 bits += symbol_bits(&cdf::MV_CLASS0_BIT, class0_bit);
168 bits += symbol_bits(&cdf::MV_CLASS0_FR[class0_bit], fr);
169 bits += symbol_bits(&cdf::MV_CLASS0_HP, hp);
170 } else {
171 let d = offset >> 3;
172 for (i, row) in cdf::MV_BIT.iter().enumerate().take(class) {
173 bits += symbol_bits(row, usize::from((d >> i) & 1 == 1));
174 }
175 bits += symbol_bits(&cdf::MV_FR, fr);
176 bits += symbol_bits(&cdf::MV_HP, hp);
177 }
178 bits
179}
180
181/// The bits an MV difference from its predictor spends: the joint symbol
182/// (which axes are non-zero) plus each non-zero axis's own component (spec
183/// 5.9.15's `read_mv`).
184fn mv_bits((diff_row, diff_col): (i32, i32)) -> f64 {
185 let joint = match (diff_row != 0, diff_col != 0) {
186 (false, false) => 0,
187 (false, true) => 1, // MV_JOINT_HNZVZ: col (horizontal) only
188 (true, false) => 2, // MV_JOINT_HZVNZ: row (vertical) only
189 (true, true) => 3, // MV_JOINT_HNZVNZ
190 };
191 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
192 if diff_row != 0 {
193 bits += mv_component_bits(diff_row);
194 }
195 if diff_col != 0 {
196 bits += mv_component_bits(diff_col);
197 }
198 bits
199}
200
201/// One search's outcome: the best MV found and the `SAD + lambda * mv_bits`
202/// cost it settled at.
203#[derive(Clone, Copy, Debug, PartialEq)]
204pub struct MotionSearch {
205 /// The best `(row, col)` motion vector found, in 1/8-pel units.
206 pub mv: (i32, i32),
207 /// `SAD + lambda * mv_bits` at [`Self::mv`], against `pred_mv`.
208 pub cost: f64,
209}
210
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)]
215fn 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)]
255pub(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
277/// Searches one `block_w * block_h` block, at `(block_x, block_y)` in the
278/// current picture's plane, against `reference` for the motion vector that
279/// minimises `SAD + lambda * mv_bits(mv - pred_mv)`.
280///
281/// `reference` is `ref_width * ref_height`, row-major, one plane. `source` is
282/// the block's own samples, `block_w * block_h`, row-major — what the search
283/// compares each candidate's prediction against. `pred_mv` is the MV-stack
284/// predictor (e.g. [`crate::mvstack::MvStack::pred_mv`]) the residual, and its
285/// cost, are coded against; this function does not build the MV stack
286/// itself.
287///
288/// SAD, not SSE: both settle on the same minimum on the synthetic translation
289/// tests below (a motion search's candidates differ by whole/half/quarter-pel
290/// shifts of the same content, so their error surfaces share a minimum either
291/// way). A standalone timing probe (2,000,000 SAD/SSE passes over a 64-sample
292/// block, `rustc -O`) measured SSE 10% *faster* here (80.6ms vs 89.5ms) — the
293/// squaring auto-vectorises as well as the absolute value does, so speed
294/// does not decide it. SAD wins on a different ground: it is the metric
295/// [`crate::encode::Search`]'s own mode trial (`encode.rs`) already reports
296/// error in (`sse: f64` there is a name, not a metric choice — it is fed
297/// squared error from the transform's own reconstruction, a different
298/// quantity from a raw sample-domain match cost), and SAD is what a motion
299/// search conventionally reports for exactly this reason: it is linear in
300/// the outlier's size rather than quadratic, so one badly-mismatched sample
301/// at a block edge (occlusion, a moving object's boundary) does not swamp
302/// the whole candidate's score the way SSE would.
303///
304/// # Panics
305/// Panics when `source` is not `block_w * block_h` long, or `reference` is
306/// empty (the same contracts [`predict`] has).
307#[allow(clippy::too_many_arguments)] // one reference plane, one block, one predictor
308pub(crate) fn search(
309 reference: &[u16],
310 stride: usize,
311 ref_width: usize,
312 ref_height: usize,
313 source: &[u8],
314 block_x: usize,
315 block_y: usize,
316 block_w: usize,
317 block_h: usize,
318 pred_mv: (i32, i32),
319 seeds: &[(i32, i32)],
320 lambda: f64, fctx: &crate::decode::FrameCtx,
321 // How many frames back (order-hint distance) this reference sits: a
322 // reference twice as far away holds content that has moved about twice
323 // as far, so the log stage starts from a proportionally wider step. See
324 // [`dist_initial_step`].
325 dist: u32,
326) -> MotionSearch {
327 let (result, _trace) = search_traced_from_step(
328 reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h,
329 pred_mv,
330 if seeded() { seeds } else { &[] },
331 lambda,
332 dist_initial_step(dist), fctx,
333 );
334 result
335}
336
337/// The integer-pel log stage's starting step for a reference at order-hint
338/// distance `dist`: `step * (1 + k * (dist - 1))`, `k` = `EC_AV1_MV_DIST_SCALE`
339/// in a test build. `k = 0` is the flat step every reference used before.
340fn dist_initial_step(dist: u32) -> i32 {
341 let base = if seeded() { seeded_step() } else { SEARCH_INITIAL_STEP_PEL };
342 static K: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
343 let k = *K.get_or_init(|| match std::env::var("EC_AV1_MV_DIST_SCALE").ok() {
344 Some(v) if cfg!(test) => v.parse().unwrap_or(MV_DIST_SCALE),
345 _ => MV_DIST_SCALE,
346 });
347 if dist <= 1 || k <= 0.0 {
348 return base;
349 }
350 let scaled = f64::from(base) * k.mul_add(f64::from(dist - 1), 1.0);
351 // Past 4x the base the log stage spends its rounds on vectors no
352 // reference in this encoder's GOP reaches.
353 scaled.round().clamp(f64::from(base), f64::from(base * 4)) as i32
354}
355
356/// The distance scale [`dist_initial_step`] ships with. Swept on the BD gate
357/// (vs libaom, 1080p/2160p/screen): 0 = +100.7/+115.8/+73.3, 0.25
358/// +98.5/+112.2, 0.375 +98.2/+115.6, 0.5 +94.4/+104.3, 0.625 +95.9/+106.5,
359/// 0.75 +92.8/+112.7, 1.0 +98.8/+113.0 -- screen is byte-identical at every
360/// point (its motion is small enough that a wider start converges to the same
361/// vector). 0.5 wins both film clips together; the ranking either side of it
362/// is near-tie churn, not a gradient.
363const MV_DIST_SCALE: f64 = 0.5;
364
365/// [`search`], plus the running best cost after every round any of its three
366/// stages ran — what `cost_is_monotone_non_increasing_over_the_search` below
367/// checks.
368#[cfg(test)]
369#[allow(clippy::too_many_arguments)] // one reference plane, one block, one predictor
370fn search_traced(
371 reference: &[u16],
372 stride: usize,
373 ref_width: usize,
374 ref_height: usize,
375 source: &[u8],
376 block_x: usize,
377 block_y: usize,
378 block_w: usize,
379 block_h: usize,
380 pred_mv: (i32, i32),
381 seeds: &[(i32, i32)],
382 lambda: f64, fctx: &crate::decode::FrameCtx,
383) -> (MotionSearch, Vec<f64>) {
384 search_traced_from_step(
385 reference,
386 stride,
387 ref_width,
388 ref_height,
389 source,
390 block_x,
391 block_y,
392 block_w,
393 block_h,
394 pred_mv,
395 seeds,
396 lambda,
397 if seeded() {
398 seeded_step()
399 } else {
400 SEARCH_INITIAL_STEP_PEL
401 }, fctx,
402 )
403}
404
405/// [`search_traced`] with the integer-pel stage's starting step named
406/// explicitly — what `sweep_initial_step` below sweeps to land
407/// [`SEARCH_INITIAL_STEP_PEL`].
408#[allow(clippy::too_many_arguments)]
409fn search_traced_from_step(
410 reference: &[u16],
411 stride: usize,
412 ref_width: usize,
413 ref_height: usize,
414 source: &[u8],
415 block_x: usize,
416 block_y: usize,
417 block_w: usize,
418 block_h: usize,
419 pred_mv: (i32, i32),
420 seeds: &[(i32, i32)],
421 lambda: f64,
422 initial_step_pel: i32, fctx: &crate::decode::FrameCtx,
423) -> (MotionSearch, Vec<f64>) {
424 assert_eq!(source.len(), block_w * block_h, "source is one block");
425 assert!(!reference.is_empty(), "a reference plane has samples");
426
427 // lane-av1speed: `reference` arrives as the DPB picture's own `u16`
428 // plane. It used to be handed the encoder's `u8` shadow copy and
429 // converted here, whole-plane, on EVERY call -- one 245k-element
430 // allocate-and-convert per searched block, which profiled as the single
431 // largest symbol in the encoder (30% of `sequence_bench_sanity`).
432 let mut dst16 = vec![0u16; block_w * block_h];
433 let evals = std::cell::Cell::new(0u64);
434 let mut cost_of = |mv: (i32, i32)| -> f64 {
435 evals.set(evals.get() + 1);
436 cost_of_mv(
437 reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h,
438 mv, pred_mv, lambda, &mut dst16, fctx,
439 )
440 };
441
442 let mut trace = Vec::new();
443 let mut centre = (round_to_pel(pred_mv.0), round_to_pel(pred_mv.1));
444 let mut best_cost = cost_of(centre);
445 // The stack's own candidates, whole-pel rounded, as extra starting
446 // points: a neighbour block's vector is where this block's motion most
447 // often already is, and starting there is what lets the log stage below
448 // start from is usually the vector this block wants.
449 for &seed in seeds {
450 let candidate = (round_to_pel(seed.0), round_to_pel(seed.1));
451 if candidate == centre {
452 continue;
453 }
454 let cost = cost_of(candidate);
455 if cost < best_cost {
456 best_cost = cost;
457 centre = candidate;
458 }
459 }
460 let start_centre = centre;
461 trace.push(best_cost);
462
463 // Stage 1: log/diamond search over whole-pel steps, halving the step
464 // each time a round finds no better neighbour, down to one sample.
465 let mut step_pel = initial_step_pel;
466 while step_pel >= SEARCH_MIN_STEP_PEL {
467 let step = step_pel * PEL_Q3;
468 loop {
469 // Evaluate the whole round from the round's starting centre, so
470 // a candidate that improves early in the neighbour list cannot
471 // shift where later candidates in the *same* round are placed --
472 // each round moves at most one step, never compounds within it.
473 let round_centre = centre;
474 let mut best_in_round = best_cost;
475 for (dr, dc) in neighbor_offsets(step) {
476 let candidate = (round_centre.0 + dr, round_centre.1 + dc);
477 let cost = cost_of(candidate);
478 if cost < best_in_round {
479 best_in_round = cost;
480 centre = candidate;
481 }
482 }
483 let moved = best_in_round < best_cost;
484 best_cost = best_in_round;
485 CENSUS[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
486 trace.push(best_cost);
487 if !moved {
488 break;
489 }
490 }
491 step_pel /= 2;
492 }
493
494 // Stages 2 and 3: one ±1-step refinement each at half-pel then
495 // quarter-pel, through the same cost function (so the refinement is
496 // costed at the precision it commits to, not the integer-pel SAD alone).
497 let integer_evals = evals.get();
498 for step in [HALF_PEL_Q3, QUARTER_PEL_Q3] {
499 let round_centre = centre;
500 for (dr, dc) in neighbor_offsets(step) {
501 let candidate = (round_centre.0 + dr, round_centre.1 + dc);
502 let cost = cost_of(candidate);
503 if cost < best_cost {
504 best_cost = cost;
505 centre = candidate;
506 }
507 }
508 trace.push(best_cost);
509 }
510
511 use std::sync::atomic::Ordering::Relaxed;
512 CENSUS[0].fetch_add(1, Relaxed);
513 CENSUS[1].fetch_add(evals.get(), Relaxed);
514 CENSUS[2].fetch_add(evals.get() - integer_evals, Relaxed);
515 if (centre.0 - pred_mv.0).abs() <= PEL_Q3 && (centre.1 - pred_mv.1).abs() <= PEL_Q3 {
516 CENSUS[4].fetch_add(1, Relaxed);
517 }
518 if centre == start_centre {
519 CENSUS[5].fetch_add(1, Relaxed);
520 }
521
522 (
523 MotionSearch {
524 mv: centre,
525 cost: best_cost,
526 },
527 trace,
528 )
529}
530
531#[cfg(test)]
532mod tests {
533 use super::*;
534
535 /// A pseudo-random, non-periodic sample at `(x, y)`: two independent
536 /// multiplicative hashes XORed together.
537 fn hash_sample(width: usize, height: usize, x: i32, y: i32) -> i32 {
538 let cx = x.clamp(0, width as i32 - 1) as u32;
539 let cy = y.clamp(0, height as i32 - 1) as u32;
540 let h = cx.wrapping_mul(2_654_435_761) ^ cy.wrapping_mul(40_503);
541 i32::from(((h >> 13) & 0xff) as u8)
542 }
543
544 /// Builds a `width * height` plane with a locally smooth (5x5-box-blurred
545 /// hash noise) but globally unique texture -- smooth enough for a
546 /// gradient-following search to have something to follow (raw,
547 /// unblurred per-pixel noise, tried first, has no correlation between a
548 /// candidate's cost and its distance from the true match, so a diamond
549 /// search cannot navigate it even though the true match is still the
550 /// unique SAD-zero point), and unique enough that no whole-pel shift
551 /// within the plane aliases onto another (verified once, brute-force,
552 /// for every translation this module's tests use).
553 fn plane_and_block(
554 width: usize,
555 height: usize,
556 block_x: usize,
557 block_y: usize,
558 block_w: usize,
559 block_h: usize,
560 ) -> (Vec<u8>, Vec<u8>) {
561 let plane: Vec<u8> = (0..height as i32)
562 .flat_map(|y| {
563 (0..width as i32).map(move |x| {
564 let mut sum = 0;
565 let mut count = 0;
566 for dy in -2..=2 {
567 for dx in -2..=2 {
568 sum += hash_sample(width, height, x + dx, y + dy);
569 count += 1;
570 }
571 }
572 (sum / count) as u8
573 })
574 })
575 .collect();
576 let mut block = vec![0u8; block_w * block_h];
577 for row in 0..block_h {
578 for col in 0..block_w {
579 block[row * block_w + col] = plane[(block_y + row) * width + block_x + col];
580 }
581 }
582 (plane, block)
583 }
584
585 #[test]
586 fn finds_exact_integer_translation_all_four_signs() {
587 let fctx = &crate::decode::FrameCtx::new();
588 let width = 64;
589 let height = 64;
590 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
591 let plane16: Vec<u16> = plane.iter().map(|&v| u16::from(v)).collect();
592 let block_w = 8;
593 let block_h = 8;
594 // Anchor the source block away from the plane's edges so every sign
595 // of displacement stays in bounds.
596 let anchor_x = 32;
597 let anchor_y = 32;
598 // corner-cut: magnitude equal to `SEARCH_INITIAL_STEP_PEL`, so the
599 // very first round's step lands a candidate exactly on the true
600 // translation. A greedy diamond/log search over a coarse step is not
601 // a global optimiser -- content with real long-range correlation
602 // (actual video) gives it a gradient to follow across a bigger gap;
603 // this module's synthetic, locally-textured-but-globally-uncorrelated
604 // plane does not, and a displacement several steps away from a zero
605 // predictor was observed (by direct trace) to settle in a false
606 // local minimum. Ceiling: production content is real video, whose
607 // wide-range correlation this synthetic plane deliberately lacks;
608 // upgrade path is a coarse-to-fine (blurred-pyramid) first stage if a
609 // real clip is ever found where the search gets stuck the same way.
610 for (dx, dy) in [(8, 8), (-8, 8), (8, -8), (-8, -8)] {
611 let source_x = (anchor_x as i32 + dx) as usize;
612 let source_y = (anchor_y as i32 + dy) as usize;
613 let mut block = vec![0u8; block_w * block_h];
614 for row in 0..block_h {
615 for col in 0..block_w {
616 block[row * block_w + col] = plane[(source_y + row) * width + source_x + col];
617 }
618 }
619 let result = search(
620 &plane16,
621 width,
622 width,
623 height,
624 &block,
625 anchor_x,
626 anchor_y,
627 block_w,
628 block_h,
629 (0, 0),
630 &[],
631 0.1, fctx,
632 1,
633 );
634 assert_eq!(
635 result.mv,
636 (dy * 8, dx * 8),
637 "translation ({dx}, {dy}) must be found exactly, in 1/8-pel units"
638 );
639 }
640 }
641
642 #[test]
643 fn finds_half_pel_translation() {
644 let fctx = &crate::decode::FrameCtx::new();
645 // A ramp, doubled, so every half-pel position lands on an exact
646 // integer average of its two neighbours.
647 let width = 40;
648 let height = 24;
649 let plane: Vec<u8> = (0..width * height)
650 .map(|i| (2 * (i % width)) as u8)
651 .collect();
652 let plane16: Vec<u16> = plane.iter().map(|&v| u16::from(v)).collect();
653 let block_w = 8;
654 let block_h = 6;
655 let anchor_x = 10;
656 let anchor_y = 8;
657 // The true best match is the source shifted 3.5 samples right: no
658 // integer position matches as well as this half-pel one, since the
659 // ramp is strictly monotone along x.
660 let mut block = vec![0u8; block_w * block_h];
661 for row in 0..block_h {
662 for col in 0..block_w {
663 // Column value at x+3.5 is the average of x+3 and x+4.
664 let left = 2 * (anchor_x + col + 3);
665 let right = 2 * (anchor_x + col + 4);
666 let _ = anchor_y + row; // the ramp is constant along y
667 block[row * block_w + col] = ((left + right) / 2) as u8;
668 }
669 }
670 let result = search(
671 &plane16,
672 width,
673 width,
674 height,
675 &block,
676 anchor_x,
677 anchor_y,
678 block_w,
679 block_h,
680 (0, 0),
681 &[],
682 0.1, fctx,
683 1,
684 );
685 assert_eq!(
686 result.mv,
687 (0, 3 * 8 + 4),
688 "a half-pel translation must be found at 1/8-pel value 3*8+4 (3.5 samples)"
689 );
690 }
691
692 #[test]
693 fn cost_is_monotone_non_increasing_over_the_search() {
694 let fctx = &crate::decode::FrameCtx::new();
695 let width = 48;
696 let height = 48;
697 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
698 let plane16: Vec<u16> = plane.iter().map(|&v| u16::from(v)).collect();
699 let block_w = 8;
700 let block_h = 8;
701 let anchor_x = 20;
702 let anchor_y = 20;
703 let mut block = vec![0u8; block_w * block_h];
704 for row in 0..block_h {
705 for col in 0..block_w {
706 block[row * block_w + col] =
707 plane[(anchor_y + 6 + row) * width + anchor_x - 7 + col];
708 }
709 }
710 let (_result, trace) = search_traced(
711 &plane16,
712 width,
713 width,
714 height,
715 &block,
716 anchor_x,
717 anchor_y,
718 block_w,
719 block_h,
720 (0, 0),
721 &[],
722 0.1, fctx,
723 );
724 assert!(trace.len() > 1, "the search must run more than one round");
725 for pair in trace.windows(2) {
726 assert!(
727 pair[1] <= pair[0],
728 "best-so-far cost must never rise between rounds: {trace:?}"
729 );
730 }
731 }
732
733 #[test]
734 fn mv_bits_prices_a_larger_residual_higher() {
735 // A bigger MV difference from the predictor must never cost fewer
736 // bits than a smaller one on the same axis and sign -- otherwise the
737 // pricing would steer the search toward implausible motion.
738 assert!(mv_bits((0, 1)) < mv_bits((0, 100)));
739 assert!(mv_bits((0, 100)) < mv_bits((0, 10_000)));
740 assert_eq!(mv_bits((0, 0)), symbol_bits(&cdf::MV_JOINT, 0));
741 }
742
743 /// The sweep behind [`SEARCH_INITIAL_STEP_PEL`]: for each candidate
744 /// starting step, how many of four synthetic translations (magnitude 8 on
745 /// each axis, all four signs, from a zero predictor) the search finds
746 /// exactly, and how many block evaluations it spent doing it.
747 ///
748 /// Measured (this test, `--nocapture`): step 4 finds 2/4 (needs two
749 /// same-step hops to cover a magnitude-8 displacement and drifts off the
750 /// true match on the way, for the reason `finds_exact_integer_...`'s
751 /// corner-cut note explains); step 8 finds 4/4 in 224 evaluations; step
752 /// 16 also finds 4/4 but in 288 -- 8 does the same job for less, so 8
753 /// lands.
754 #[test]
755 fn sweep_initial_step() {
756 let fctx = &crate::decode::FrameCtx::new();
757 let width = 96;
758 let height = 96;
759 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
760 let plane16: Vec<u16> = plane.iter().map(|&v| u16::from(v)).collect();
761 let block_w = 8;
762 let block_h = 8;
763 let anchor_x = 48;
764 let anchor_y = 48;
765 let translations: [(i32, i32); 4] = [(8, 8), (-8, 8), (8, -8), (-8, -8)];
766
767 for &candidate_step in &[4, 8, 16] {
768 let mut hits = 0;
769 let mut rounds = 0usize;
770 for &(dx, dy) in &translations {
771 let source_x = (anchor_x as i32 + dx) as usize;
772 let source_y = (anchor_y as i32 + dy) as usize;
773 let mut block = vec![0u8; block_w * block_h];
774 for row in 0..block_h {
775 for col in 0..block_w {
776 block[row * block_w + col] =
777 plane[(source_y + row) * width + source_x + col];
778 }
779 }
780 let (result, trace) = search_traced_from_step(
781 &plane16,
782 width,
783 width,
784 height,
785 &block,
786 anchor_x,
787 anchor_y,
788 block_w,
789 block_h,
790 (0, 0),
791 &[],
792 0.1,
793 candidate_step, fctx,
794 );
795 // Every round the trace recorded is 8 neighbour evaluations,
796 // the actual cost this starting step spent on this block.
797 rounds += trace.len();
798 if result.mv == (dy * 8, dx * 8) {
799 hits += 1;
800 }
801 }
802 eprintln!(
803 "SEARCH_INITIAL_STEP_PEL={candidate_step}: {hits}/4 exact, {} block evaluations",
804 rounds * 8
805 );
806 if candidate_step == SEARCH_INITIAL_STEP_PEL {
807 assert_eq!(hits, 4, "the landed constant must find every translation");
808 }
809 }
810 }
811}