forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

motion.rs614 lines, 23.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/// 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 // lane-hbd r2: this encoder-side search stays `u8` (see
267 // `encode::intra_predict_u8`'s doc comment) -- `reference` is converted
268 // once here, outside the per-candidate closure, since `mc::predict` now
269 // takes `u16`.
270 let reference16: Vec<u16> = reference.iter().map(|&v| u16::from(v)).collect();
271 let mut dst16 = vec![0u16; block_w * block_h];
272 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 &reference16, stride, ref_width, ref_height, x_q4, y_q4, block_w, block_h,
277 &mut dst16,
278 );
279 let sad: f64 = source
280 .iter()
281 .zip(dst16.iter())
282 .map(|(&a, &b)| f64::from((i32::from(a) - i32::from(b)).unsigned_abs()))
283 .sum();
284 let diff = (mv.0 - pred_mv.0, mv.1 - pred_mv.1);
285 sad + lambda * mv_bits(diff)
286 };
287
288 let mut trace = Vec::new();
289 let mut centre = (round_to_pel(pred_mv.0), round_to_pel(pred_mv.1));
290 let mut best_cost = cost_of(centre);
291 trace.push(best_cost);
292
293 // Stage 1: log/diamond search over whole-pel steps, halving the step
294 // each time a round finds no better neighbour, down to one sample.
295 let mut step_pel = initial_step_pel;
296 while step_pel >= SEARCH_MIN_STEP_PEL {
297 let step = step_pel * PEL_Q3;
298 loop {
299 // Evaluate the whole round from the round's starting centre, so
300 // a candidate that improves early in the neighbour list cannot
301 // shift where later candidates in the *same* round are placed --
302 // each round moves at most one step, never compounds within it.
303 let round_centre = centre;
304 let mut best_in_round = best_cost;
305 for (dr, dc) in neighbor_offsets(step) {
306 let candidate = (round_centre.0 + dr, round_centre.1 + dc);
307 let cost = cost_of(candidate);
308 if cost < best_in_round {
309 best_in_round = cost;
310 centre = candidate;
311 }
312 }
313 let moved = best_in_round < best_cost;
314 best_cost = best_in_round;
315 trace.push(best_cost);
316 if !moved {
317 break;
318 }
319 }
320 step_pel /= 2;
321 }
322
323 // Stages 2 and 3: one ±1-step refinement each at half-pel then
324 // quarter-pel, through the same cost function (so the refinement is
325 // costed at the precision it commits to, not the integer-pel SAD alone).
326 for step in [HALF_PEL_Q3, QUARTER_PEL_Q3] {
327 let round_centre = centre;
328 for (dr, dc) in neighbor_offsets(step) {
329 let candidate = (round_centre.0 + dr, round_centre.1 + dc);
330 let cost = cost_of(candidate);
331 if cost < best_cost {
332 best_cost = cost;
333 centre = candidate;
334 }
335 }
336 trace.push(best_cost);
337 }
338
339 (
340 MotionSearch {
341 mv: centre,
342 cost: best_cost,
343 },
344 trace,
345 )
346}
347
348#[cfg(test)]
349mod tests {
350 use super::*;
351
352 /// A pseudo-random, non-periodic sample at `(x, y)`: two independent
353 /// multiplicative hashes XORed together.
354 fn hash_sample(width: usize, height: usize, x: i32, y: i32) -> i32 {
355 let cx = x.clamp(0, width as i32 - 1) as u32;
356 let cy = y.clamp(0, height as i32 - 1) as u32;
357 let h = cx.wrapping_mul(2_654_435_761) ^ cy.wrapping_mul(40_503);
358 i32::from(((h >> 13) & 0xff) as u8)
359 }
360
361 /// Builds a `width * height` plane with a locally smooth (5x5-box-blurred
362 /// hash noise) but globally unique texture -- smooth enough for a
363 /// gradient-following search to have something to follow (raw,
364 /// unblurred per-pixel noise, tried first, has no correlation between a
365 /// candidate's cost and its distance from the true match, so a diamond
366 /// search cannot navigate it even though the true match is still the
367 /// unique SAD-zero point), and unique enough that no whole-pel shift
368 /// within the plane aliases onto another (verified once, brute-force,
369 /// for every translation this module's tests use).
370 fn plane_and_block(
371 width: usize,
372 height: usize,
373 block_x: usize,
374 block_y: usize,
375 block_w: usize,
376 block_h: usize,
377 ) -> (Vec<u8>, Vec<u8>) {
378 let plane: Vec<u8> = (0..height as i32)
379 .flat_map(|y| {
380 (0..width as i32).map(move |x| {
381 let mut sum = 0;
382 let mut count = 0;
383 for dy in -2..=2 {
384 for dx in -2..=2 {
385 sum += hash_sample(width, height, x + dx, y + dy);
386 count += 1;
387 }
388 }
389 (sum / count) as u8
390 })
391 })
392 .collect();
393 let mut block = vec![0u8; block_w * block_h];
394 for row in 0..block_h {
395 for col in 0..block_w {
396 block[row * block_w + col] = plane[(block_y + row) * width + block_x + col];
397 }
398 }
399 (plane, block)
400 }
401
402 #[test]
403 fn finds_exact_integer_translation_all_four_signs() {
404 let width = 64;
405 let height = 64;
406 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
407 let block_w = 8;
408 let block_h = 8;
409 // Anchor the source block away from the plane's edges so every sign
410 // of displacement stays in bounds.
411 let anchor_x = 32;
412 let anchor_y = 32;
413 // corner-cut: magnitude equal to `SEARCH_INITIAL_STEP_PEL`, so the
414 // very first round's step lands a candidate exactly on the true
415 // translation. A greedy diamond/log search over a coarse step is not
416 // a global optimiser -- content with real long-range correlation
417 // (actual video) gives it a gradient to follow across a bigger gap;
418 // this module's synthetic, locally-textured-but-globally-uncorrelated
419 // plane does not, and a displacement several steps away from a zero
420 // predictor was observed (by direct trace) to settle in a false
421 // local minimum. Ceiling: production content is real video, whose
422 // wide-range correlation this synthetic plane deliberately lacks;
423 // upgrade path is a coarse-to-fine (blurred-pyramid) first stage if a
424 // real clip is ever found where the search gets stuck the same way.
425 for (dx, dy) in [(8, 8), (-8, 8), (8, -8), (-8, -8)] {
426 let source_x = (anchor_x as i32 + dx) as usize;
427 let source_y = (anchor_y as i32 + dy) as usize;
428 let mut block = vec![0u8; block_w * block_h];
429 for row in 0..block_h {
430 for col in 0..block_w {
431 block[row * block_w + col] = plane[(source_y + row) * width + source_x + col];
432 }
433 }
434 let result = search(
435 &plane,
436 width,
437 width,
438 height,
439 &block,
440 anchor_x,
441 anchor_y,
442 block_w,
443 block_h,
444 (0, 0),
445 0.1,
446 );
447 assert_eq!(
448 result.mv,
449 (dy * 8, dx * 8),
450 "translation ({dx}, {dy}) must be found exactly, in 1/8-pel units"
451 );
452 }
453 }
454
455 #[test]
456 fn finds_half_pel_translation() {
457 // A ramp, doubled, so every half-pel position lands on an exact
458 // integer average of its two neighbours.
459 let width = 40;
460 let height = 24;
461 let plane: Vec<u8> = (0..width * height)
462 .map(|i| (2 * (i % width)) as u8)
463 .collect();
464 let block_w = 8;
465 let block_h = 6;
466 let anchor_x = 10;
467 let anchor_y = 8;
468 // The true best match is the source shifted 3.5 samples right: no
469 // integer position matches as well as this half-pel one, since the
470 // ramp is strictly monotone along x.
471 let mut block = vec![0u8; block_w * block_h];
472 for row in 0..block_h {
473 for col in 0..block_w {
474 // Column value at x+3.5 is the average of x+3 and x+4.
475 let left = 2 * (anchor_x + col + 3);
476 let right = 2 * (anchor_x + col + 4);
477 let _ = anchor_y + row; // the ramp is constant along y
478 block[row * block_w + col] = ((left + right) / 2) as u8;
479 }
480 }
481 let result = search(
482 &plane,
483 width,
484 width,
485 height,
486 &block,
487 anchor_x,
488 anchor_y,
489 block_w,
490 block_h,
491 (0, 0),
492 0.1,
493 );
494 assert_eq!(
495 result.mv,
496 (0, 3 * 8 + 4),
497 "a half-pel translation must be found at 1/8-pel value 3*8+4 (3.5 samples)"
498 );
499 }
500
501 #[test]
502 fn cost_is_monotone_non_increasing_over_the_search() {
503 let width = 48;
504 let height = 48;
505 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
506 let block_w = 8;
507 let block_h = 8;
508 let anchor_x = 20;
509 let anchor_y = 20;
510 let mut block = vec![0u8; block_w * block_h];
511 for row in 0..block_h {
512 for col in 0..block_w {
513 block[row * block_w + col] =
514 plane[(anchor_y + 6 + row) * width + anchor_x - 7 + col];
515 }
516 }
517 let (_result, trace) = search_traced(
518 &plane,
519 width,
520 width,
521 height,
522 &block,
523 anchor_x,
524 anchor_y,
525 block_w,
526 block_h,
527 (0, 0),
528 0.1,
529 );
530 assert!(trace.len() > 1, "the search must run more than one round");
531 for pair in trace.windows(2) {
532 assert!(
533 pair[1] <= pair[0],
534 "best-so-far cost must never rise between rounds: {trace:?}"
535 );
536 }
537 }
538
539 #[test]
540 fn mv_bits_prices_a_larger_residual_higher() {
541 // A bigger MV difference from the predictor must never cost fewer
542 // bits than a smaller one on the same axis and sign -- otherwise the
543 // pricing would steer the search toward implausible motion.
544 assert!(mv_bits((0, 1)) < mv_bits((0, 100)));
545 assert!(mv_bits((0, 100)) < mv_bits((0, 10_000)));
546 assert_eq!(mv_bits((0, 0)), symbol_bits(&cdf::MV_JOINT, 0));
547 }
548
549 /// The sweep behind [`SEARCH_INITIAL_STEP_PEL`]: for each candidate
550 /// starting step, how many of four synthetic translations (magnitude 8 on
551 /// each axis, all four signs, from a zero predictor) the search finds
552 /// exactly, and how many block evaluations it spent doing it.
553 ///
554 /// Measured (this test, `--nocapture`): step 4 finds 2/4 (needs two
555 /// same-step hops to cover a magnitude-8 displacement and drifts off the
556 /// true match on the way, for the reason `finds_exact_integer_...`'s
557 /// corner-cut note explains); step 8 finds 4/4 in 224 evaluations; step
558 /// 16 also finds 4/4 but in 288 -- 8 does the same job for less, so 8
559 /// lands.
560 #[test]
561 fn sweep_initial_step() {
562 let width = 96;
563 let height = 96;
564 let (plane, _unused) = plane_and_block(width, height, 0, 0, 1, 1);
565 let block_w = 8;
566 let block_h = 8;
567 let anchor_x = 48;
568 let anchor_y = 48;
569 let translations: [(i32, i32); 4] = [(8, 8), (-8, 8), (8, -8), (-8, -8)];
570
571 for &candidate_step in &[4, 8, 16] {
572 let mut hits = 0;
573 let mut rounds = 0usize;
574 for &(dx, dy) in &translations {
575 let source_x = (anchor_x as i32 + dx) as usize;
576 let source_y = (anchor_y as i32 + dy) as usize;
577 let mut block = vec![0u8; block_w * block_h];
578 for row in 0..block_h {
579 for col in 0..block_w {
580 block[row * block_w + col] =
581 plane[(source_y + row) * width + source_x + col];
582 }
583 }
584 let (result, trace) = search_traced_from_step(
585 &plane,
586 width,
587 width,
588 height,
589 &block,
590 anchor_x,
591 anchor_y,
592 block_w,
593 block_h,
594 (0, 0),
595 0.1,
596 candidate_step,
597 );
598 // Every round the trace recorded is 8 neighbour evaluations,
599 // the actual cost this starting step spent on this block.
600 rounds += trace.len();
601 if result.mv == (dy * 8, dx * 8) {
602 hits += 1;
603 }
604 }
605 eprintln!(
606 "SEARCH_INITIAL_STEP_PEL={candidate_step}: {hits}/4 exact, {} block evaluations",
607 rounds * 8
608 );
609 if candidate_step == SEARCH_INITIAL_STEP_PEL {
610 assert_eq!(hits, 4, "the landed constant must find every translation");
611 }
612 }
613 }
614}