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