forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

enc_me.rs731 lines, 26.7 KiBHistoryRawDownload
1//! Motion search for the P-picture encoder.
2//!
3//! The design is the one `ec-h264`'s `choose_inter` runs: candidate vectors
4//! seeded from the neighbourhood, a coarse-to-fine eight-neighbour pattern
5//! search at whole-sample steps, then sub-sample refinement at half and quarter
6//! steps. Every candidate is costed as `SAD + lambda * bits`, where the bits
7//! are the exp-Golomb length of the vector difference from the predictor.
8//!
9//! The search does not interpolate per candidate. [`RefPlanes`] holds the
10//! reference luma once per picture as four padded 8-bit planes (whole sample, and
11//! the three half-sample positions, filtered with the decoder's 8-tap filter);
12//! a quarter-sample vector is costed against one plane or the average of two
13//! (the way x264 costs its quarter positions), so every candidate is a plain
14//! sum of absolute differences. The estimate differs a little from the
15//! decoder's quarter-sample filter, but only picks the vector: the mode
16//! decision predicts with the decoder's own interpolation.
17
18#[cfg(target_arch = "x86_64")]
19use archmage::{SimdToken, X64V1Token, arcane};
20
21/// The weight on the vector's bits against the lambda (as in `ec-h264`).
22const MV_BITS_WEIGHT: f64 = 0.5;
23
24/// The eight neighbours a pattern step visits, in units of the current step.
25const PATTERN: [(i16, i16); 8] = [
26 (1, 0),
27 (-1, 0),
28 (0, 1),
29 (0, -1),
30 (1, 1),
31 (-1, -1),
32 (1, -1),
33 (-1, 1),
34];
35
36/// Search window half-width in whole luma samples around the predictor.
37const RANGE_SAMPLES: i32 = 32;
38
39/// Half-width, in whole samples, of the full integer search around the best seed,
40/// for a 32x32 block (the largest, which pays for it once per coding tree) and
41/// for smaller blocks, which search the neighbourhood of their parent's vector.
42pub(crate) const FULL_RANGE_LARGE: i16 = 24;
43pub(crate) const FULL_RANGE_SMALL: i16 = 12;
44
45/// Bits an `se(v)` codeword costs (9.3.2.3), for the vector cost.
46pub(crate) fn se_bits(v: i32) -> u32 {
47 let k = if v > 0 {
48 2 * i64::from(v) - 1
49 } else {
50 -2 * i64::from(v)
51 } as u64;
52 let len = 64 - (k + 1).leading_zeros();
53 2 * len - 1
54}
55
56/// Border, in whole samples, replicated around the reference planes. A candidate
57/// block (and the neighbour sample a quarter position averages with) must lie
58/// inside the padded planes; the search treats any other vector as not available.
59const PAD: usize = 48;
60
61/// The HEVC half-sample luma filter (8.5.3.3.3.1), `fL[2]`.
62const HALF: [i16; 8] = [-1, 4, -11, 40, 40, -11, 4, -1];
63
64/// The reference luma as padded 8-bit planes: the whole-sample plane and the
65/// half-sample planes `H` (between horizontal neighbours), `V` (between vertical
66/// neighbours) and `D` (the centre of four).
67pub(crate) struct RefPlanes {
68 /// Padded row length.
69 stride: usize,
70 /// Picture width and height.
71 w: usize,
72 h: usize,
73 /// `[whole, H, V, D]`, each `(h + 2 * PAD) * stride` samples.
74 planes: [Vec<u8>; 4],
75 /// Right shift that brings the reference samples to 8 bits for the search.
76 shift: u32,
77}
78
79impl RefPlanes {
80 /// Empty planes for a `w` x `h` luma picture; [`RefPlanes::fill`] loads a picture.
81 pub(crate) fn new(w: usize, h: usize, bit_depth: u32) -> RefPlanes {
82 let stride = w + 2 * PAD;
83 let size = (h + 2 * PAD) * stride;
84 RefPlanes {
85 stride,
86 w,
87 h,
88 planes: [vec![0; size], vec![0; size], vec![0; size], vec![0; size]],
89 shift: bit_depth - 8,
90 }
91 }
92
93 /// Load the luma picture `luma` (rows `w` apart), using up to `threads` threads.
94 pub(crate) fn fill(&mut self, luma: &[u16], threads: usize) {
95 let (stride, w, h) = (self.stride, self.w, self.h);
96 let shift = self.shift;
97 let rows = h + 2 * PAD;
98 let threads = threads.clamp(1, 8);
99 let band = rows.div_ceil(threads);
100 let [whole, hp, vp, dp] = &mut self.planes;
101 // Phase one: the whole-sample plane, edge samples replicated.
102 std::thread::scope(|scope| {
103 for (i, chunk) in whole.chunks_mut(band * stride).enumerate() {
104 scope.spawn(move || {
105 for (r, dst) in chunk.chunks_exact_mut(stride).enumerate() {
106 let sy = (i * band + r).saturating_sub(PAD).min(h - 1);
107 let src = &luma[sy * w..][..w];
108 for (x, d) in dst[PAD..PAD + w].iter_mut().zip(src) {
109 *x = (*d >> shift) as u8;
110 }
111 let (left, right) = (dst[PAD], dst[PAD + w - 1]);
112 dst[..PAD].fill(left);
113 dst[PAD + w..].fill(right);
114 }
115 });
116 }
117 });
118 // Phase two: the half-sample planes, a band of output rows per thread.
119 let whole: &[u8] = whole;
120 std::thread::scope(|scope| {
121 let bands = hp
122 .chunks_mut(band * stride)
123 .zip(vp.chunks_mut(band * stride))
124 .zip(dp.chunks_mut(band * stride));
125 for (i, ((hc, vc), dc)) in bands.enumerate() {
126 scope.spawn(move || half_band(whole, stride, rows, i * band, hc, vc, dc));
127 }
128 });
129 }
130}
131
132/// The `H`, `V` and `D` rows `r0..` of one band (each chunk holds the band's rows, `stride`
133/// apart), from the padded whole-sample plane. Rows without the full filter support (the
134/// first three and last four) are left as they are; no search vector reads them.
135fn half_band(
136 whole: &[u8],
137 stride: usize,
138 rows: usize,
139 r0: usize,
140 hc: &mut [u8],
141 vc: &mut [u8],
142 dc: &mut [u8],
143) {
144 let n = stride - 7;
145 let nrows = hc.len() / stride;
146 // Horizontal sums of the whole plane, unrounded (they fit 16 bits for 8-bit samples):
147 // the first stage of both `H` and `D`. A ring of eight rows holds the vertical support.
148 let mut ring = vec![0i16; 8 * stride];
149 let hsum = |ring: &mut [i16], row: usize| {
150 let srow = &whole[row * stride..][..stride];
151 let dst = &mut ring[(row % 8) * stride + 3..][..n];
152 dst.fill(0);
153 for (k, &c) in HALF.iter().enumerate() {
154 for (a, &s) in dst.iter_mut().zip(&srow[k..k + n]) {
155 *a += c * i16::from(s);
156 }
157 }
158 };
159 let first = r0.max(3);
160 let last = (r0 + nrows).min(rows - 4);
161 if first >= last {
162 return;
163 }
164 for row in first - 3..first + 5 {
165 hsum(&mut ring, row);
166 }
167 let mut acc = vec![0i16; stride];
168 let mut acc_d = vec![0i32; stride];
169 for r in first..last {
170 if r > first {
171 hsum(&mut ring, r + 4);
172 }
173 let o = (r - r0) * stride;
174 let own = &ring[(r % 8) * stride + 3..][..n];
175 for (d, &a) in hc[o + 3..][..n].iter_mut().zip(own) {
176 *d = ((a + 32) >> 6).clamp(0, 255) as u8;
177 }
178 acc.fill(0);
179 acc_d.fill(0);
180 for (k, &c) in HALF.iter().enumerate() {
181 let wrow = &whole[(r + k - 3) * stride..][..stride];
182 for (a, &s) in acc.iter_mut().zip(wrow) {
183 *a += c * i16::from(s);
184 }
185 let srow = &ring[((r + k - 3) % 8) * stride + 3..][..n];
186 for (a, &s) in acc_d[3..][..n].iter_mut().zip(srow) {
187 *a += i32::from(c) * i32::from(s);
188 }
189 }
190 for (d, &a) in vc[o..][..stride].iter_mut().zip(&acc) {
191 *d = ((a + 32) >> 6).clamp(0, 255) as u8;
192 }
193 for (d, &a) in dc[o + 3..][..n].iter_mut().zip(&acc_d[3..][..n]) {
194 *d = (((a >> 6) + 32) >> 6).clamp(0, 255) as u8;
195 }
196 }
197}
198
199/// Which plane, and at which whole-sample offset, a quarter position reads;
200/// two entries mean the rounded average of the two.
201type Taps = [(usize, usize, usize); 2];
202
203/// The planes a quarter-sample fraction `(fx, fy)` is costed against: index
204/// 0 whole, 1 `H`, 2 `V`, 3 `D`; each entry `(plane, dx, dy)`. A single plane is
205/// listed twice.
206const fn taps(fx: usize, fy: usize) -> Taps {
207 const W: usize = 0;
208 const H: usize = 1;
209 const V: usize = 2;
210 const D: usize = 3;
211 match (fx, fy) {
212 (0, 0) => [(W, 0, 0), (W, 0, 0)],
213 (1, 0) => [(W, 0, 0), (H, 0, 0)],
214 (2, 0) => [(H, 0, 0), (H, 0, 0)],
215 (3, 0) => [(H, 0, 0), (W, 1, 0)],
216 (0, 1) => [(W, 0, 0), (V, 0, 0)],
217 (0, 2) => [(V, 0, 0), (V, 0, 0)],
218 (0, 3) => [(V, 0, 0), (W, 0, 1)],
219 (1, 1) => [(H, 0, 0), (V, 0, 0)],
220 (2, 1) => [(H, 0, 0), (D, 0, 0)],
221 (3, 1) => [(H, 0, 0), (V, 1, 0)],
222 (1, 2) => [(V, 0, 0), (D, 0, 0)],
223 (2, 2) => [(D, 0, 0), (D, 0, 0)],
224 (3, 2) => [(D, 0, 0), (V, 1, 0)],
225 (1, 3) => [(V, 0, 0), (H, 0, 1)],
226 (2, 3) => [(D, 0, 0), (H, 0, 1)],
227 _ => [(V, 1, 0), (H, 0, 1)],
228 }
229}
230
231/// Sum of absolute differences of the `W`-wide, `h`-high block of `src` against `a`
232/// (`b` when given: against the rounded average of the two), rows `*_stride` apart.
233/// It stops after a group of four rows once the sum reaches `limit`; a sum that
234/// reaches `limit` is not exact, one below it is.
235#[inline(always)]
236#[allow(clippy::too_many_arguments)]
237fn sad_block<const W: usize>(
238 src: &[u8],
239 src_stride: usize,
240 a: &[u8],
241 b: Option<&[u8]>,
242 stride: usize,
243 h: usize,
244 limit: u32,
245) -> u32 {
246 #[cfg(target_arch = "x86_64")]
247 {
248 // The slices must cover every row the vector loads touch.
249 let need = |len: usize, st: usize| h == 0 || len >= (h - 1) * st + W;
250 if need(src.len(), src_stride)
251 && need(a.len(), stride)
252 && b.is_none_or(|b| need(b.len(), stride))
253 {
254 // The SSE2 token: SSE2 is part of the x86_64 baseline, so this is always Some.
255 if let Some(t) = X64V1Token::summon() {
256 return sad_block_sse2::<W>(t, src, src_stride, a, b, stride, h, limit);
257 }
258 }
259 }
260 sad_block_scalar::<W>(src, src_stride, a, b, stride, h, limit)
261}
262
263/// SSE2 body of [`sad_block`]. The caller checked that row `r` of each slice holds `W`
264/// bytes for every `r < h`; every load below indexes its slice, so that is enforced again.
265#[cfg(target_arch = "x86_64")]
266#[allow(clippy::too_many_arguments)]
267#[arcane]
268fn sad_block_sse2<const W: usize>(
269 _t: X64V1Token,
270 src: &[u8],
271 src_stride: usize,
272 a: &[u8],
273 b: Option<&[u8]>,
274 stride: usize,
275 h: usize,
276 limit: u32,
277) -> u32 {
278 use std::arch::x86_64::*;
279 // `W` bytes at `at`: an 8-byte load moved into the low lanes for W == 8, else 16 bytes.
280 let load = |s: &[u8], at: usize| -> __m128i {
281 if W == 8 {
282 let lo = u64::from_le_bytes(<[u8; 8]>::try_from(&s[at..at + 8]).unwrap());
283 _mm_cvtsi64_si128(lo as i64)
284 } else {
285 bytemuck::cast(<[u8; 16]>::try_from(&s[at..at + 16]).unwrap())
286 }
287 };
288 let mut acc = _mm_setzero_si128();
289 let mut row = 0;
290 while row < h {
291 let end = (row + 4).min(h);
292 while row < end {
293 let sr = row * src_stride;
294 let ar = row * stride;
295 let mut off = 0;
296 while off < W {
297 let s = load(src, sr + off);
298 let mut x = load(a, ar + off);
299 if let Some(b) = b {
300 // (x + y + 1) >> 1 per byte, as the scalar average.
301 x = _mm_avg_epu8(x, load(b, ar + off));
302 }
303 acc = _mm_add_epi64(acc, _mm_sad_epu8(s, x));
304 off += 16;
305 }
306 row += 1;
307 }
308 let sum = _mm_cvtsi128_si32(acc) as u32 + _mm_cvtsi128_si32(_mm_srli_si128(acc, 8)) as u32;
309 if sum >= limit {
310 return sum;
311 }
312 }
313 _mm_cvtsi128_si32(acc) as u32 + _mm_cvtsi128_si32(_mm_srli_si128(acc, 8)) as u32
314}
315
316#[allow(clippy::too_many_arguments)]
317fn sad_block_scalar<const W: usize>(
318 src: &[u8],
319 src_stride: usize,
320 a: &[u8],
321 b: Option<&[u8]>,
322 stride: usize,
323 h: usize,
324 limit: u32,
325) -> u32 {
326 let mut sum = 0u32;
327 let mut row = 0;
328 while row < h {
329 let s: &[u8; W] = src[row * src_stride..][..W].try_into().unwrap_or(&[0; W]);
330 let x: &[u8; W] = a[row * stride..][..W].try_into().unwrap_or(&[0; W]);
331 if let Some(b) = b {
332 let y: &[u8; W] = b[row * stride..][..W].try_into().unwrap_or(&[0; W]);
333 for i in 0..W {
334 let avg = ((u16::from(x[i]) + u16::from(y[i]) + 1) >> 1) as u8;
335 sum += u32::from(s[i].abs_diff(avg));
336 }
337 } else {
338 for i in 0..W {
339 sum += u32::from(s[i].abs_diff(x[i]));
340 }
341 }
342 if sum >= limit {
343 break;
344 }
345 row += 1;
346 }
347 sum
348}
349
350/// One block's search problem: the source luma plane, the reference planes, and
351/// the cost weight.
352pub(crate) struct Search<'a> {
353 /// Source luma, `src_stride` apart, at the coded picture size.
354 pub src: &'a [u8],
355 /// Distance between source row starts.
356 pub src_stride: usize,
357 /// The reference luma (the previous reconstruction).
358 pub reference: &'a RefPlanes,
359 /// Lagrange multiplier applied to the vector bits.
360 pub lambda: f64,
361 /// Half-width, in whole samples, of the full integer scan around the best seed
362 /// (0 for none: the seeds and the pattern search only).
363 pub full_range: i16,
364 /// Skip the full integer scan when the seeds already cost less than this per
365 /// sample (0 always scans).
366 pub full_gate: f64,
367 /// First (coarsest) step, in quarter samples, of the whole-sample pattern search.
368 pub first_step: i16,
369 /// Spacing, in whole samples, of the full scan's grid.
370 pub full_stride: i16,
371 /// Most passes of the 8-neighbour refinement at each sub-sample step.
372 pub sub_passes: u32,
373 /// Skip the sub-sample refinement when the best cost is below this per sample.
374 pub sub_gate: f64,
375 /// Skip the quarter-sample step.
376 pub no_quarter: bool,
377}
378
379/// The result of a search: the chosen vector in quarter samples and its cost.
380#[derive(Debug, Clone, Copy, PartialEq)]
381pub(crate) struct Best {
382 /// The vector, quarter luma samples.
383 pub mv: [i16; 2],
384 /// `SAD + lambda * bits`.
385 pub cost: f64,
386}
387
388impl Search<'_> {
389 /// Search the `w` x `h` block at `(x, y)` around the predictor `mvp`,
390 /// starting from `seeds` (the predictor and the neighbours' vectors).
391 pub(crate) fn run(
392 &self,
393 (x, y): (usize, usize),
394 (w, h): (usize, usize),
395 mvp: [i16; 2],
396 seeds: &[[i16; 2]],
397 ) -> Best {
398 let mut best = Best {
399 mv: [0, 0],
400 cost: f64::MAX,
401 };
402 for &cand in std::iter::once(&mvp).chain(seeds.iter()) {
403 let cost = self.cost(x, y, w, h, cand, mvp, best.cost);
404 if cost < best.cost {
405 best = Best { mv: cand, cost };
406 }
407 }
408 if best.cost == f64::MAX {
409 // No seed reaches the planes (a vector far off the picture): the zero vector does.
410 best = Best {
411 mv: [0, 0],
412 cost: self.cost(x, y, w, h, [0, 0], mvp, f64::MAX),
413 };
414 }
415 let range_q = RANGE_SAMPLES * 4;
416 let inside = |mv: [i16; 2]| {
417 (i32::from(mv[0]) - i32::from(mvp[0])).abs() <= range_q
418 && (i32::from(mv[1]) - i32::from(mvp[1])).abs() <= range_q
419 };
420 // A full search over whole samples around the best seed. A greedy pattern
421 // search from a seed stalls in the first local minimum of a textured
422 // cost, which a few samples of real motion are enough to hit.
423 let centre = [best.mv[0] & !3, best.mv[1] & !3];
424 let full = if best.cost < self.full_gate * (w * h) as f64 {
425 0
426 } else {
427 self.full_range
428 };
429 let fstride = self.full_stride.max(1) as usize;
430 for dy in (-full..=full).step_by(fstride) {
431 for dx in (-full..=full).step_by(fstride) {
432 let cand = [centre[0] + 4 * dx, centre[1] + 4 * dy];
433 if !inside(cand) {
434 continue;
435 }
436 let cost = self.cost(x, y, w, h, cand, mvp, best.cost);
437 if cost < best.cost {
438 best = Best { mv: cand, cost };
439 }
440 }
441 }
442 // The whole-sample walk below starts from the whole-sample position of the best
443 // vector. The sub-sample refinement recovers the fraction.
444 if best.mv[0] & 3 != 0 || best.mv[1] & 3 != 0 {
445 let mv = [best.mv[0] & !3, best.mv[1] & !3];
446 let cost = self.cost(x, y, w, h, mv, mvp, f64::MAX);
447 if cost < f64::MAX {
448 best = Best { mv, cost };
449 }
450 }
451 // Whole-sample steps, coarse to fine: four samples, two, one.
452 let mut step = self.first_step;
453 while step >= 4 {
454 let mut improved = true;
455 while improved {
456 improved = false;
457 for (dx, dy) in PATTERN {
458 let cand = [best.mv[0] + dx * step, best.mv[1] + dy * step];
459 if !inside(cand) {
460 continue;
461 }
462 let cost = self.cost(x, y, w, h, cand, mvp, best.cost);
463 if cost < best.cost {
464 best = Best { mv: cand, cost };
465 improved = true;
466 }
467 }
468 }
469 step /= 2;
470 }
471 // Sub-sample refinement: half, then quarter steps, to convergence.
472 let steps: &[i16] = if best.cost < self.sub_gate * (w * h) as f64 {
473 &[]
474 } else if self.no_quarter {
475 &[2]
476 } else {
477 &[2, 1]
478 };
479 for &step in steps {
480 let mut improved = true;
481 let mut passes = 0;
482 while improved && passes < self.sub_passes {
483 passes += 1;
484 improved = false;
485 for (dx, dy) in PATTERN {
486 let cand = [best.mv[0] + dx * step, best.mv[1] + dy * step];
487 let cost = self.cost(x, y, w, h, cand, mvp, best.cost);
488 if cost < best.cost {
489 best = Best { mv: cand, cost };
490 improved = true;
491 }
492 }
493 }
494 }
495 best
496 }
497
498 /// `SAD(source, prediction(mv)) + lambda * MV_BITS_WEIGHT * bits(mv - mvp)`, with the
499 /// prediction read from the reference planes ([`taps`]). The sum stops once it reaches
500 /// `cutoff` (the best cost so far): the caller only compares against `cutoff`, so the
501 /// returned value is exact whenever it is below it. A vector whose block (and the
502 /// neighbour a quarter position averages with) leaves the padded planes costs
503 /// `f64::MAX`.
504 #[allow(clippy::too_many_arguments)] // the block is its origin and its two sides
505 #[inline]
506 fn cost(
507 &self,
508 x: usize,
509 y: usize,
510 w: usize,
511 h: usize,
512 mv: [i16; 2],
513 mvp: [i16; 2],
514 cutoff: f64,
515 ) -> f64 {
516 let rp = self.reference;
517 let rx = x as i32 + i32::from(mv[0] >> 2);
518 let ry = y as i32 + i32::from(mv[1] >> 2);
519 let lo = 3 - PAD as i32;
520 if rx < lo
521 || ry < lo
522 || rx + w as i32 + 1 > rp.w as i32 + PAD as i32 - 5
523 || ry + h as i32 + 1 > rp.h as i32 + PAD as i32 - 5
524 {
525 return f64::MAX;
526 }
527 let bits = se_bits(i32::from(mv[0]) - i32::from(mvp[0]))
528 + se_bits(i32::from(mv[1]) - i32::from(mvp[1]));
529 let rate = self.lambda * MV_BITS_WEIGHT * f64::from(bits);
530 let t = taps((mv[0] & 3) as usize, (mv[1] & 3) as usize);
531 // The bounds check above keeps `rx`/`ry` >= 3 - PAD, so these sums are >= 0;
532 // they are formed in i32 so a negative vector never wraps through `as usize`.
533 let at = |tap: (usize, usize, usize)| {
534 let row = (ry + PAD as i32 + tap.2 as i32) as usize;
535 let col = (rx + PAD as i32 + tap.1 as i32) as usize;
536 row * rp.stride + col
537 };
538 let (a0, a1) = (at(t[0]), at(t[1]));
539 let limit = if cutoff == f64::MAX {
540 u32::MAX
541 } else {
542 let v = (cutoff - rate).max(0.0).min(f64::from(u32::MAX));
543 let t = v as u32;
544 if f64::from(t) < v { t + 1 } else { t }
545 };
546 let src = &self.src[y * self.src_stride + x..];
547 let pa = &rp.planes[t[0].0][a0..];
548 let pb = (t[0] != t[1]).then(|| &rp.planes[t[1].0][a1..]);
549 let sad = match w {
550 8 => sad_block::<8>(src, self.src_stride, pa, pb, rp.stride, h, limit),
551 16 => sad_block::<16>(src, self.src_stride, pa, pb, rp.stride, h, limit),
552 _ => sad_block::<32>(src, self.src_stride, pa, pb, rp.stride, h, limit),
553 };
554 f64::from(sad) + rate
555 }
556}
557
558#[cfg(test)]
559mod tests {
560 use super::*;
561
562 #[test]
563 fn sad_vector_path_matches_the_scalar_one() {
564 let mut seed = 7u32;
565 let mut buf = |n: usize| -> Vec<u8> {
566 (0..n)
567 .map(|_| {
568 seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
569 (seed >> 16) as u8
570 })
571 .collect()
572 };
573 let (src, a, b) = (buf(80 * 40), buf(80 * 40), buf(80 * 40));
574 for h in [8usize, 16, 32] {
575 for limit in [u32::MAX, 5000] {
576 for pb in [None, Some(&b[3..])] {
577 macro_rules! chk {
578 ($w:literal) => {
579 let v = sad_block::<$w>(&src, 80, &a[1..], pb, 80, h, limit);
580 let s = sad_block_scalar::<$w>(&src, 80, &a[1..], pb, 80, h, limit);
581 if limit == u32::MAX {
582 assert_eq!(v, s);
583 } else {
584 assert_eq!(v.min(limit), s.min(limit));
585 }
586 };
587 }
588 chk!(8);
589 chk!(16);
590 chk!(32);
591 }
592 }
593 }
594 }
595
596 #[test]
597 fn se_bits_matches_the_exp_golomb_table() {
598 assert_eq!(se_bits(0), 1);
599 assert_eq!(se_bits(1), 3);
600 assert_eq!(se_bits(-1), 3);
601 assert_eq!(se_bits(2), 5);
602 assert_eq!(se_bits(-2), 5);
603 assert_eq!(se_bits(3), 5);
604 }
605
606 #[test]
607 fn search_finds_a_large_vertical_shift() {
608 // A 32x32 block whose source is the reference 14 rows up: the vector is
609 // (0, -14) samples, which is (0, -56) quarters.
610 let (w, h) = (256usize, 256usize);
611 let mut refs = vec![0u16; w * h];
612 for y in 0..h {
613 for x in 0..w {
614 refs[y * w + x] = (((x * 37 + y * 11) % 211) + 20) as u16;
615 }
616 }
617 let mut src = vec![0u8; w * h];
618 for y in 0..h {
619 for x in 0..w {
620 let sy = (y as i32 - 14).clamp(0, h as i32 - 1) as usize;
621 src[y * w + x] = refs[sy * w + x] as u8;
622 }
623 }
624 let mut reference = RefPlanes::new(w, h, 8);
625 reference.fill(&refs, 1);
626 let search = Search {
627 src: &src,
628 src_stride: w,
629 reference: &reference,
630 lambda: 1.0,
631 full_range: FULL_RANGE_LARGE,
632 full_stride: 1,
633 sub_passes: 8,
634 sub_gate: 0.0,
635 no_quarter: false,
636 full_gate: 0.0,
637 first_step: 16,
638 };
639 let best = search.run((96, 96), (32, 32), [0, 0], &[]);
640 assert_eq!(best.mv, [0, -56], "cost {}", best.cost);
641 }
642
643 #[test]
644 fn search_finds_a_shifted_block() {
645 // The source at (x, y) is the reference at (x - 3, y + 2), so the vector
646 // that predicts it exactly is (-3, +2) samples, which is (-12, 8) quarters.
647 let (w, h) = (64usize, 64usize);
648 let mut refs = vec![0u16; w * h];
649 for y in 0..h {
650 for x in 0..w {
651 refs[y * w + x] = (((x * 7 + y * 13) % 200) + 20) as u16;
652 }
653 }
654 let mut src = vec![0u8; w * h];
655 for y in 0..h {
656 for x in 0..w {
657 let sx = (x as i32 - 3).clamp(0, w as i32 - 1) as usize;
658 let sy = (y as i32 + 2).clamp(0, h as i32 - 1) as usize;
659 src[y * w + x] = refs[sy * w + sx] as u8;
660 }
661 }
662 let mut reference = RefPlanes::new(w, h, 8);
663 reference.fill(&refs, 1);
664 let search = Search {
665 src: &src,
666 src_stride: w,
667 reference: &reference,
668 lambda: 1.0,
669 full_range: FULL_RANGE_SMALL,
670 full_stride: 1,
671 sub_passes: 8,
672 sub_gate: 0.0,
673 no_quarter: false,
674 full_gate: 0.0,
675 first_step: 16,
676 };
677 let best = search.run((24, 24), (8, 8), [0, 0], &[]);
678 assert_eq!(best.mv, [-12, 8]);
679 assert_eq!(
680 best.cost,
681 search.lambda * MV_BITS_WEIGHT * f64::from(se_bits(-12) + se_bits(8))
682 );
683 }
684
685 #[test]
686 fn cost_at_the_low_bound_reads_the_padded_plane() {
687 // A vector that points 40 samples up and left of the frame reads the
688 // replicated top-left corner of the padded planes. The cost used to compute
689 // the plane index from `negative as usize`, which overflows in debug builds.
690 let (w, h) = (64usize, 64usize);
691 let mut refs = vec![0u16; w * h];
692 for y in 0..h {
693 for x in 0..w {
694 refs[y * w + x] = (((x * 7 + y * 13) % 200) + 20) as u16;
695 }
696 }
697 // Source block at (0, 0) equals the reference at (-40, -40), which is the
698 // top-left sample (0, 0) replicated.
699 let mut src = vec![0u8; w * h];
700 for y in 0..h {
701 for x in 0..w {
702 src[y * w + x] = refs[0] as u8;
703 }
704 }
705 let mut reference = RefPlanes::new(w, h, 8);
706 reference.fill(&refs, 1);
707 let search = Search {
708 src: &src,
709 src_stride: w,
710 reference: &reference,
711 lambda: 1.0,
712 full_range: FULL_RANGE_SMALL,
713 full_stride: 1,
714 sub_passes: 8,
715 sub_gate: 0.0,
716 no_quarter: false,
717 full_gate: 0.0,
718 first_step: 16,
719 };
720 let mv = [-160i16, -160];
721 // Whole-sample vector: the prediction is exactly the source, so only the
722 // rate term (two zero-difference components) remains.
723 let exact = search.cost(0, 0, 8, 8, mv, mv, f64::MAX);
724 assert_eq!(exact, 1.0 * MV_BITS_WEIGHT * 2.0);
725 // Fractional vectors at the same spot stay in bounds and are finite.
726 for mv in [[-159i16, -160], [-160, -157], [-157, -159]] {
727 let c = search.cost(0, 0, 8, 8, mv, [0, 0], f64::MAX);
728 assert!(c.is_finite() && c < f64::MAX, "mv {mv:?} cost {c}");
729 }
730 }
731}