forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

motion.rs608 lines, 22.9 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/// The eight offsets, at `step` in each axis, a diamond/log search round
59/// checks around its current centre (the ninth point, no offset, is the
60/// centre itself and is already priced).
61fn neighbor_offsets(step: i32) -> [(i32, i32); 8] {
62 [
63 (-step, -step),
64 (-step, 0),
65 (-step, step),
66 (0, -step),
67 (0, step),
68 (step, -step),
69 (step, 0),
70 (step, step),
71 ]
72}
73
74/// Rounds an MV component to the nearest whole sample (ties away from zero),
75/// which is where the integer-pel search stage starts.
76fn round_to_pel(component: i32) -> i32 {
77 let q = component.div_euclid(PEL_Q3);
78 let r = component.rem_euclid(PEL_Q3);
79 if r * 2 >= PEL_Q3 {
80 (q + 1) * PEL_Q3
81 } else {
82 q * PEL_Q3
83 }
84}
85
86/// `Av1_get_mv_class`'s class and in-class offset for a coded magnitude `z =
87/// |component| - 1` (spec 5.9.15's inverse, the encoder side libaom's
88/// `av1_get_mv_class` computes): class 0 covers `z < 16`; each class `c >= 1`
89/// covers the doubling range `[8*2^c, 16*2^c)`, so `c = floor(log2(z)) - 3`.
90fn mv_class_and_offset(z: u32) -> (usize, u32) {
91 if z < 16 {
92 (0, z)
93 } else {
94 let class = (31 - z.leading_zeros()) as usize - 3;
95 let class = class.min(10); // MV_CLASSES = 11, classes 0..=10
96 let base = 8u32 << class;
97 (class, z - base)
98 }
99}
100
101/// The bits one non-zero MV component (`diff`, the coded value minus its
102/// predictor) spends: sign, class, then the class's own bit/fraction/half-pel
103/// symbols, each priced by [`symbol_bits`] against the CDF the tile writer
104/// would spend it against (spec 5.9.15's `read_mv_component`, run backwards).
105fn mv_component_bits(diff: i32) -> f64 {
106 let sign = usize::from(diff < 0);
107 let mag = diff.unsigned_abs();
108 debug_assert!(mag > 0, "a zero component is priced by the joint alone");
109 let z = mag - 1;
110 let (class, offset) = mv_class_and_offset(z);
111
112 let mut bits = symbol_bits(&cdf::MV_SIGN, sign) + symbol_bits(&cdf::MV_CLASS, class);
113 let fr = ((offset >> 1) & 3) as usize;
114 let hp = (offset & 1) as usize;
115 if class == 0 {
116 let class0_bit = (offset >> 3) as usize;
117 bits += symbol_bits(&cdf::MV_CLASS0_BIT, class0_bit);
118 bits += symbol_bits(&cdf::MV_CLASS0_FR[class0_bit], fr);
119 bits += symbol_bits(&cdf::MV_CLASS0_HP, hp);
120 } else {
121 let d = offset >> 3;
122 for (i, row) in cdf::MV_BIT.iter().enumerate().take(class) {
123 bits += symbol_bits(row, usize::from((d >> i) & 1 == 1));
124 }
125 bits += symbol_bits(&cdf::MV_FR, fr);
126 bits += symbol_bits(&cdf::MV_HP, hp);
127 }
128 bits
129}
130
131/// The bits an MV difference from its predictor spends: the joint symbol
132/// (which axes are non-zero) plus each non-zero axis's own component (spec
133/// 5.9.15's `read_mv`).
134fn mv_bits((diff_row, diff_col): (i32, i32)) -> f64 {
135 let joint = match (diff_row != 0, diff_col != 0) {
136 (false, false) => 0,
137 (false, true) => 1, // MV_JOINT_HNZVZ: col (horizontal) only
138 (true, false) => 2, // MV_JOINT_HZVNZ: row (vertical) only
139 (true, true) => 3, // MV_JOINT_HNZVNZ
140 };
141 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
142 if diff_row != 0 {
143 bits += mv_component_bits(diff_row);
144 }
145 if diff_col != 0 {
146 bits += mv_component_bits(diff_col);
147 }
148 bits
149}
150
151/// One search's outcome: the best MV found and the `SAD + lambda * mv_bits`
152/// cost it settled at.
153#[derive(Clone, Copy, Debug, PartialEq)]
154pub struct MotionSearch {
155 /// The best `(row, col)` motion vector found, in 1/8-pel units.
156 pub mv: (i32, i32),
157 /// `SAD + lambda * mv_bits` at [`Self::mv`], against `pred_mv`.
158 pub cost: f64,
159}
160
161/// Searches one `block_w * block_h` block, at `(block_x, block_y)` in the
162/// current picture's plane, against `reference` for the motion vector that
163/// minimises `SAD + lambda * mv_bits(mv - pred_mv)`.
164///
165/// `reference` is `ref_width * ref_height`, row-major, one plane. `source` is
166/// the block's own samples, `block_w * block_h`, row-major — what the search
167/// compares each candidate's prediction against. `pred_mv` is the MV-stack
168/// predictor (e.g. [`crate::mvstack::MvStack::pred_mv`]) the residual, and its
169/// cost, are coded against; this function does not build the MV stack
170/// itself.
171///
172/// SAD, not SSE: both settle on the same minimum on the synthetic translation
173/// tests below (a motion search's candidates differ by whole/half/quarter-pel
174/// shifts of the same content, so their error surfaces share a minimum either
175/// way). A standalone timing probe (2,000,000 SAD/SSE passes over a 64-sample
176/// block, `rustc -O`) measured SSE 10% *faster* here (80.6ms vs 89.5ms) — the
177/// squaring auto-vectorises as well as the absolute value does, so speed
178/// does not decide it. SAD wins on a different ground: it is the metric
179/// [`crate::encode::Search`]'s own mode trial (`encode.rs`) already reports
180/// error in (`sse: f64` there is a name, not a metric choice — it is fed
181/// squared error from the transform's own reconstruction, a different
182/// quantity from a raw sample-domain match cost), and SAD is what a motion
183/// search conventionally reports for exactly this reason: it is linear in
184/// the outlier's size rather than quadratic, so one badly-mismatched sample
185/// at a block edge (occlusion, a moving object's boundary) does not swamp
186/// the whole candidate's score the way SSE would.
187///
188/// # Panics
189/// Panics when `source` is not `block_w * block_h` long, or `reference` is
190/// empty (the same contracts [`predict`] has).
191#[allow(clippy::too_many_arguments)] // one reference plane, one block, one predictor
192pub fn search(
193 reference: &[u8],
194 stride: usize,
195 ref_width: usize,
196 ref_height: usize,
197 source: &[u8],
198 block_x: usize,
199 block_y: usize,
200 block_w: usize,
201 block_h: usize,
202 pred_mv: (i32, i32),
203 lambda: f64,
204) -> MotionSearch {
205 let (result, _trace) = search_traced(
206 reference, stride, ref_width, ref_height, source, block_x, block_y, block_w, block_h,
207 pred_mv, lambda,
208 );
209 result
210}
211
212/// [`search`], plus the running best cost after every round any of its three
213/// stages ran — what `cost_is_monotone_non_increasing_over_the_search` below
214/// checks.
215#[allow(clippy::too_many_arguments)] // one reference plane, one block, one predictor
216fn search_traced(
217 reference: &[u8],
218 stride: usize,
219 ref_width: usize,
220 ref_height: usize,
221 source: &[u8],
222 block_x: usize,
223 block_y: usize,
224 block_w: usize,
225 block_h: usize,
226 pred_mv: (i32, i32),
227 lambda: f64,
228) -> (MotionSearch, Vec<f64>) {
229 search_traced_from_step(
230 reference,
231 stride,
232 ref_width,
233 ref_height,
234 source,
235 block_x,
236 block_y,
237 block_w,
238 block_h,
239 pred_mv,
240 lambda,
241 SEARCH_INITIAL_STEP_PEL,
242 )
243}
244
245/// [`search_traced`] with the integer-pel stage's starting step named
246/// explicitly — what `sweep_initial_step` below sweeps to land
247/// [`SEARCH_INITIAL_STEP_PEL`].
248#[allow(clippy::too_many_arguments)]
249fn search_traced_from_step(
250 reference: &[u8],
251 stride: usize,
252 ref_width: usize,
253 ref_height: usize,
254 source: &[u8],
255 block_x: usize,
256 block_y: usize,
257 block_w: usize,
258 block_h: usize,
259 pred_mv: (i32, i32),
260 lambda: f64,
261 initial_step_pel: i32,
262) -> (MotionSearch, Vec<f64>) {
263 assert_eq!(source.len(), block_w * block_h, "source is one block");
264 assert!(!reference.is_empty(), "a reference plane has samples");
265
266 let mut dst = vec![0u8; block_w * block_h];
267 let mut cost_of = |mv: (i32, i32)| -> f64 {
268 let x_q4 = (block_x as i32) * 16 + mv.1 * Q4_PER_Q3;
269 let y_q4 = (block_y as i32) * 16 + mv.0 * Q4_PER_Q3;
270 predict(
271 reference, stride, ref_width, ref_height, x_q4, y_q4, block_w, block_h, &mut dst,
272 );
273 let sad: f64 = source
274 .iter()
275 .zip(dst.iter())
276 .map(|(&a, &b)| f64::from((i32::from(a) - i32::from(b)).unsigned_abs()))
277 .sum();
278 let diff = (mv.0 - pred_mv.0, mv.1 - pred_mv.1);
279 sad + lambda * mv_bits(diff)
280 };
281
282 let mut trace = Vec::new();
283 let mut centre = (round_to_pel(pred_mv.0), round_to_pel(pred_mv.1));
284 let mut best_cost = cost_of(centre);
285 trace.push(best_cost);
286
287 // Stage 1: log/diamond search over whole-pel steps, halving the step
288 // each time a round finds no better neighbour, down to one sample.
289 let mut step_pel = initial_step_pel;
290 while step_pel >= SEARCH_MIN_STEP_PEL {
291 let step = step_pel * PEL_Q3;
292 loop {
293 // Evaluate the whole round from the round's starting centre, so
294 // a candidate that improves early in the neighbour list cannot
295 // shift where later candidates in the *same* round are placed --
296 // each round moves at most one step, never compounds within it.
297 let round_centre = centre;
298 let mut best_in_round = best_cost;
299 for (dr, dc) in neighbor_offsets(step) {
300 let candidate = (round_centre.0 + dr, round_centre.1 + dc);
301 let cost = cost_of(candidate);
302 if cost < best_in_round {
303 best_in_round = cost;
304 centre = candidate;
305 }
306 }
307 let moved = best_in_round < best_cost;
308 best_cost = best_in_round;
309 trace.push(best_cost);
310 if !moved {
311 break;
312 }
313 }
314 step_pel /= 2;
315 }
316
317 // Stages 2 and 3: one ±1-step refinement each at half-pel then
318 // quarter-pel, through the same cost function (so the refinement is
319 // costed at the precision it commits to, not the integer-pel SAD alone).
320 for step in [HALF_PEL_Q3, QUARTER_PEL_Q3] {
321 let round_centre = centre;
322 for (dr, dc) in neighbor_offsets(step) {
323 let candidate = (round_centre.0 + dr, round_centre.1 + dc);
324 let cost = cost_of(candidate);
325 if cost < best_cost {
326 best_cost = cost;
327 centre = candidate;
328 }
329 }
330 trace.push(best_cost);
331 }
332
333 (
334 MotionSearch {
335 mv: centre,
336 cost: best_cost,
337 },
338 trace,
339 )
340}
341
342#[cfg(test)]
343mod tests {
344 use super::*;
345
346 /// A pseudo-random, non-periodic sample at `(x, y)`: two independent
347 /// multiplicative hashes XORed together.
348 fn hash_sample(width: usize, height: usize, x: i32, y: i32) -> i32 {
349 let cx = x.clamp(0, width as i32 - 1) as u32;
350 let cy = y.clamp(0, height as i32 - 1) as u32;
351 let h = cx.wrapping_mul(2_654_435_761) ^ cy.wrapping_mul(40_503);
352 i32::from(((h >> 13) & 0xff) as u8)
353 }
354
355 /// Builds a `width * height` plane with a locally smooth (5x5-box-blurred
356 /// hash noise) but globally unique texture -- smooth enough for a
357 /// gradient-following search to have something to follow (raw,
358 /// unblurred per-pixel noise, tried first, has no correlation between a
359 /// candidate's cost and its distance from the true match, so a diamond
360 /// search cannot navigate it even though the true match is still the
361 /// unique SAD-zero point), and unique enough that no whole-pel shift
362 /// within the plane aliases onto another (verified once, brute-force,
363 /// for every translation this module's tests use).
364 fn plane_and_block(
365 width: usize,
366 height: usize,
367 block_x: usize,
368 block_y: usize,
369 block_w: usize,
370 block_h: usize,
371 ) -> (Vec<u8>, Vec<u8>) {
372 let plane: Vec<u8> = (0..height as i32)
373 .flat_map(|y| {
374 (0..width as i32).map(move |x| {
375 let mut sum = 0;
376 let mut count = 0;
377 for dy in -2..=2 {
378 for dx in -2..=2 {
379 sum += hash_sample(width, height, x + dx, y + dy);
380 count += 1;
381 }
382 }
383 (sum / count) as u8
384 })
385 })
386 .collect();
387 let mut block = vec![0u8; block_w * block_h];
388 for row in 0..block_h {
389 for col in 0..block_w {
390 block[row * block_w + col] = plane[(block_y + row) * width + block_x + col];
391 }
392 }
393 (plane, block)
394 }
395
396 #[test]
397 fn finds_exact_integer_translation_all_four_signs() {
398 let width = 64;
399 let height = 64;
400 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
401 let block_w = 8;
402 let block_h = 8;
403 // Anchor the source block away from the plane's edges so every sign
404 // of displacement stays in bounds.
405 let anchor_x = 32;
406 let anchor_y = 32;
407 // corner-cut: magnitude equal to `SEARCH_INITIAL_STEP_PEL`, so the
408 // very first round's step lands a candidate exactly on the true
409 // translation. A greedy diamond/log search over a coarse step is not
410 // a global optimiser -- content with real long-range correlation
411 // (actual video) gives it a gradient to follow across a bigger gap;
412 // this module's synthetic, locally-textured-but-globally-uncorrelated
413 // plane does not, and a displacement several steps away from a zero
414 // predictor was observed (by direct trace) to settle in a false
415 // local minimum. Ceiling: production content is real video, whose
416 // wide-range correlation this synthetic plane deliberately lacks;
417 // upgrade path is a coarse-to-fine (blurred-pyramid) first stage if a
418 // real clip is ever found where the search gets stuck the same way.
419 for (dx, dy) in [(8, 8), (-8, 8), (8, -8), (-8, -8)] {
420 let source_x = (anchor_x as i32 + dx) as usize;
421 let source_y = (anchor_y as i32 + dy) as usize;
422 let mut block = vec![0u8; block_w * block_h];
423 for row in 0..block_h {
424 for col in 0..block_w {
425 block[row * block_w + col] = plane[(source_y + row) * width + source_x + col];
426 }
427 }
428 let result = search(
429 &plane,
430 width,
431 width,
432 height,
433 &block,
434 anchor_x,
435 anchor_y,
436 block_w,
437 block_h,
438 (0, 0),
439 0.1,
440 );
441 assert_eq!(
442 result.mv,
443 (dy * 8, dx * 8),
444 "translation ({dx}, {dy}) must be found exactly, in 1/8-pel units"
445 );
446 }
447 }
448
449 #[test]
450 fn finds_half_pel_translation() {
451 // A ramp, doubled, so every half-pel position lands on an exact
452 // integer average of its two neighbours.
453 let width = 40;
454 let height = 24;
455 let plane: Vec<u8> = (0..width * height)
456 .map(|i| (2 * (i % width)) as u8)
457 .collect();
458 let block_w = 8;
459 let block_h = 6;
460 let anchor_x = 10;
461 let anchor_y = 8;
462 // The true best match is the source shifted 3.5 samples right: no
463 // integer position matches as well as this half-pel one, since the
464 // ramp is strictly monotone along x.
465 let mut block = vec![0u8; block_w * block_h];
466 for row in 0..block_h {
467 for col in 0..block_w {
468 // Column value at x+3.5 is the average of x+3 and x+4.
469 let left = 2 * (anchor_x + col + 3);
470 let right = 2 * (anchor_x + col + 4);
471 let _ = anchor_y + row; // the ramp is constant along y
472 block[row * block_w + col] = ((left + right) / 2) as u8;
473 }
474 }
475 let result = search(
476 &plane,
477 width,
478 width,
479 height,
480 &block,
481 anchor_x,
482 anchor_y,
483 block_w,
484 block_h,
485 (0, 0),
486 0.1,
487 );
488 assert_eq!(
489 result.mv,
490 (0, 3 * 8 + 4),
491 "a half-pel translation must be found at 1/8-pel value 3*8+4 (3.5 samples)"
492 );
493 }
494
495 #[test]
496 fn cost_is_monotone_non_increasing_over_the_search() {
497 let width = 48;
498 let height = 48;
499 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
500 let block_w = 8;
501 let block_h = 8;
502 let anchor_x = 20;
503 let anchor_y = 20;
504 let mut block = vec![0u8; block_w * block_h];
505 for row in 0..block_h {
506 for col in 0..block_w {
507 block[row * block_w + col] =
508 plane[(anchor_y + 6 + row) * width + anchor_x - 7 + col];
509 }
510 }
511 let (_result, trace) = search_traced(
512 &plane,
513 width,
514 width,
515 height,
516 &block,
517 anchor_x,
518 anchor_y,
519 block_w,
520 block_h,
521 (0, 0),
522 0.1,
523 );
524 assert!(trace.len() > 1, "the search must run more than one round");
525 for pair in trace.windows(2) {
526 assert!(
527 pair[1] <= pair[0],
528 "best-so-far cost must never rise between rounds: {trace:?}"
529 );
530 }
531 }
532
533 #[test]
534 fn mv_bits_prices_a_larger_residual_higher() {
535 // A bigger MV difference from the predictor must never cost fewer
536 // bits than a smaller one on the same axis and sign -- otherwise the
537 // pricing would steer the search toward implausible motion.
538 assert!(mv_bits((0, 1)) < mv_bits((0, 100)));
539 assert!(mv_bits((0, 100)) < mv_bits((0, 10_000)));
540 assert_eq!(mv_bits((0, 0)), symbol_bits(&cdf::MV_JOINT, 0));
541 }
542
543 /// The sweep behind [`SEARCH_INITIAL_STEP_PEL`]: for each candidate
544 /// starting step, how many of four synthetic translations (magnitude 8 on
545 /// each axis, all four signs, from a zero predictor) the search finds
546 /// exactly, and how many block evaluations it spent doing it.
547 ///
548 /// Measured (this test, `--nocapture`): step 4 finds 2/4 (needs two
549 /// same-step hops to cover a magnitude-8 displacement and drifts off the
550 /// true match on the way, for the reason `finds_exact_integer_...`'s
551 /// corner-cut note explains); step 8 finds 4/4 in 224 evaluations; step
552 /// 16 also finds 4/4 but in 288 -- 8 does the same job for less, so 8
553 /// lands.
554 #[test]
555 fn sweep_initial_step() {
556 let width = 96;
557 let height = 96;
558 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
559 let block_w = 8;
560 let block_h = 8;
561 let anchor_x = 48;
562 let anchor_y = 48;
563 let translations: [(i32, i32); 4] = [(8, 8), (-8, 8), (8, -8), (-8, -8)];
564
565 for &candidate_step in &[4, 8, 16] {
566 let mut hits = 0;
567 let mut rounds = 0usize;
568 for &(dx, dy) in &translations {
569 let source_x = (anchor_x as i32 + dx) as usize;
570 let source_y = (anchor_y as i32 + dy) as usize;
571 let mut block = vec![0u8; block_w * block_h];
572 for row in 0..block_h {
573 for col in 0..block_w {
574 block[row * block_w + col] =
575 plane[(source_y + row) * width + source_x + col];
576 }
577 }
578 let (result, trace) = search_traced_from_step(
579 &plane,
580 width,
581 width,
582 height,
583 &block,
584 anchor_x,
585 anchor_y,
586 block_w,
587 block_h,
588 (0, 0),
589 0.1,
590 candidate_step,
591 );
592 // Every round the trace recorded is 8 neighbour evaluations,
593 // the actual cost this starting step spent on this block.
594 rounds += trace.len();
595 if result.mv == (dy * 8, dx * 8) {
596 hits += 1;
597 }
598 }
599 eprintln!(
600 "SEARCH_INITIAL_STEP_PEL={candidate_step}: {hits}/4 exact, {} block evaluations",
601 rounds * 8
602 );
603 if candidate_step == SEARCH_INITIAL_STEP_PEL {
604 assert_eq!(hits, 4, "the landed constant must find every translation");
605 }
606 }
607 }
608}