use crate::motion_comp::{
fetch_luma_mb_halo, fetch_luma_mb_whole_pixel, filter_set_for_version, sixtap_mb_luma,
stored_luma_mv,
};
use crate::motion_vector::Mv;
pub const MV_MIN: i16 = -1023;
pub const MV_MAX: i16 = 1023;
pub const WHOLE_PIXEL_STEP: i16 = 4;
pub const HALF_PIXEL_STEP: i16 = 2;
pub const QUARTER_PIXEL_STEP: i16 = 1;
#[inline]
pub fn block_sad_16x16(src: &[u8; 256], pred: &[u8; 256]) -> u32 {
block_sad_16x16_scalar(src, pred)
}
#[inline]
fn block_sad_16x16_scalar(src: &[u8; 256], pred: &[u8; 256]) -> u32 {
let mut acc: u32 = 0;
for i in 0..256 {
let s = src[i] as i32;
let p = pred[i] as i32;
acc += (s - p).unsigned_abs();
}
acc
}
#[cfg(feature = "simd")]
#[allow(dead_code)]
#[inline]
fn block_sad_16x16_simd(src: &[u8; 256], pred: &[u8; 256]) -> u32 {
use core::simd::Simd;
use core::simd::cmp::SimdOrd;
use core::simd::num::SimdUint;
let mut acc: Simd<u16, 16> = Simd::splat(0);
for row in 0..16 {
let off = row * 16;
let s: Simd<u8, 16> = Simd::from_slice(&src[off..off + 16]);
let p: Simd<u8, 16> = Simd::from_slice(&pred[off..off + 16]);
let absdiff = s.simd_max(p) - s.simd_min(p);
acc += absdiff.cast::<u16>();
}
acc.cast::<u32>().reduce_sum()
}
#[derive(Debug, Clone, Copy)]
pub struct LumaRef<'a> {
pub plane: &'a [u8],
pub stride: usize,
pub width: usize,
pub height: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SearchResult {
pub mv: Mv,
pub sad: u32,
}
pub fn mb_luma_sad_at_whole_mv(
reference: LumaRef<'_>,
mb_col: usize,
mb_row: usize,
src_y: &[u8; 256],
mv: Mv,
) -> u32 {
debug_assert_eq!(mv.row % WHOLE_PIXEL_STEP, 0, "MV row must be whole-pixel");
debug_assert_eq!(mv.col % WHOLE_PIXEL_STEP, 0, "MV col must be whole-pixel");
debug_assert!((MV_MIN..=MV_MAX).contains(&mv.row));
debug_assert!((MV_MIN..=MV_MAX).contains(&mv.col));
let blk_x0 = mb_col * 16;
let blk_y0 = mb_row * 16;
let mv_eighth = stored_luma_mv(mv);
let src_x0 = blk_x0 as isize + (mv_eighth.col >> 3) as isize;
let src_y0 = blk_y0 as isize + (mv_eighth.row >> 3) as isize;
let w_i = reference.width as isize;
let h_i = reference.height as isize;
if src_x0 >= 0 && src_y0 >= 0 && src_x0 + 16 <= w_i && src_y0 + 16 <= h_i {
let x0 = src_x0 as usize;
let y0 = src_y0 as usize;
let mut acc: u32 = 0;
for r in 0..16 {
let row_start = (y0 + r) * reference.stride + x0;
let pred_row = &reference.plane[row_start..row_start + 16];
let src_row = &src_y[r * 16..r * 16 + 16];
for c in 0..16 {
acc += (src_row[c] as i32 - pred_row[c] as i32).unsigned_abs();
}
}
return acc;
}
let pred = fetch_luma_mb_whole_pixel(
reference.plane,
reference.stride,
reference.width,
reference.height,
blk_x0,
blk_y0,
mv_eighth,
);
block_sad_16x16(src_y, &pred)
}
#[inline]
fn clamp_component(v: i32) -> i16 {
v.clamp(MV_MIN as i32, MV_MAX as i32) as i16
}
#[inline]
fn snap_to_whole_pixel(v: i16) -> i16 {
(v / WHOLE_PIXEL_STEP) * WHOLE_PIXEL_STEP
}
pub fn small_diamond_search_luma(
reference: LumaRef<'_>,
mb_col: usize,
mb_row: usize,
src_y: &[u8; 256],
center: Mv,
max_iters: u32,
) -> SearchResult {
let mut best_mv = Mv {
row: snap_to_whole_pixel(clamp_component(center.row as i32)),
col: snap_to_whole_pixel(clamp_component(center.col as i32)),
};
let mut best_sad = mb_luma_sad_at_whole_mv(reference, mb_col, mb_row, src_y, best_mv);
let neighbours: [(i32, i32); 4] = [
(-(WHOLE_PIXEL_STEP as i32), 0),
(WHOLE_PIXEL_STEP as i32, 0),
(0, -(WHOLE_PIXEL_STEP as i32)),
(0, WHOLE_PIXEL_STEP as i32),
];
for _ in 0..max_iters {
let mut improved = false;
for (drow, dcol) in neighbours {
let cand_row = snap_to_whole_pixel(clamp_component(best_mv.row as i32 + drow));
let cand_col = snap_to_whole_pixel(clamp_component(best_mv.col as i32 + dcol));
if cand_row == best_mv.row && cand_col == best_mv.col {
continue;
}
let cand_mv = Mv {
row: cand_row,
col: cand_col,
};
let cand_sad = mb_luma_sad_at_whole_mv(reference, mb_col, mb_row, src_y, cand_mv);
if cand_sad < best_sad {
best_sad = cand_sad;
best_mv = cand_mv;
improved = true;
}
}
if !improved {
break;
}
}
SearchResult {
mv: best_mv,
sad: best_sad,
}
}
pub fn mb_luma_sad_at_mv(
reference: LumaRef<'_>,
mb_col: usize,
mb_row: usize,
src_y: &[u8; 256],
mv: Mv,
) -> u32 {
debug_assert!((MV_MIN..=MV_MAX).contains(&mv.row));
debug_assert!((MV_MIN..=MV_MAX).contains(&mv.col));
let blk_x0 = mb_col * 16;
let blk_y0 = mb_row * 16;
let mv_eighth = stored_luma_mv(mv);
let filters = filter_set_for_version(0).taps();
let mx = (mv_eighth.col & 7) as usize;
let my = (mv_eighth.row & 7) as usize;
let pred = if mx == 0 && my == 0 {
fetch_luma_mb_whole_pixel(
reference.plane,
reference.stride,
reference.width,
reference.height,
blk_x0,
blk_y0,
mv_eighth,
)
} else {
let halo = fetch_luma_mb_halo(
reference.plane,
reference.stride,
reference.width,
reference.height,
blk_x0,
blk_y0,
mv_eighth,
);
sixtap_mb_luma(&halo, mx, my, filters)
};
block_sad_16x16(src_y, &pred)
}
pub fn half_pixel_refine_luma(
reference: LumaRef<'_>,
mb_col: usize,
mb_row: usize,
src_y: &[u8; 256],
whole_pixel_center: Mv,
) -> SearchResult {
debug_assert_eq!(
whole_pixel_center.row % WHOLE_PIXEL_STEP,
0,
"whole_pixel_center.row must be on the whole-pixel grid"
);
debug_assert_eq!(
whole_pixel_center.col % WHOLE_PIXEL_STEP,
0,
"whole_pixel_center.col must be on the whole-pixel grid"
);
debug_assert!((MV_MIN..=MV_MAX).contains(&whole_pixel_center.row));
debug_assert!((MV_MIN..=MV_MAX).contains(&whole_pixel_center.col));
let mut best_mv = whole_pixel_center;
let mut best_sad = mb_luma_sad_at_mv(reference, mb_col, mb_row, src_y, best_mv);
let step = HALF_PIXEL_STEP as i32;
let offsets: [(i32, i32); 8] = [
(-step, -step),
(-step, 0),
(-step, step),
(0, -step),
(0, step),
(step, -step),
(step, 0),
(step, step),
];
for (drow, dcol) in offsets {
let cand_row = clamp_component(whole_pixel_center.row as i32 + drow);
let cand_col = clamp_component(whole_pixel_center.col as i32 + dcol);
if cand_row == best_mv.row && cand_col == best_mv.col {
continue;
}
let cand_mv = Mv {
row: cand_row,
col: cand_col,
};
let cand_sad = mb_luma_sad_at_mv(reference, mb_col, mb_row, src_y, cand_mv);
if cand_sad < best_sad {
best_sad = cand_sad;
best_mv = cand_mv;
}
}
SearchResult {
mv: best_mv,
sad: best_sad,
}
}
pub fn quarter_pixel_refine_luma(
reference: LumaRef<'_>,
mb_col: usize,
mb_row: usize,
src_y: &[u8; 256],
half_pixel_center: Mv,
) -> SearchResult {
debug_assert_eq!(
half_pixel_center.row % HALF_PIXEL_STEP,
0,
"half_pixel_center.row must be on the half-pixel grid"
);
debug_assert_eq!(
half_pixel_center.col % HALF_PIXEL_STEP,
0,
"half_pixel_center.col must be on the half-pixel grid"
);
debug_assert!((MV_MIN..=MV_MAX).contains(&half_pixel_center.row));
debug_assert!((MV_MIN..=MV_MAX).contains(&half_pixel_center.col));
let mut best_mv = half_pixel_center;
let mut best_sad = mb_luma_sad_at_mv(reference, mb_col, mb_row, src_y, best_mv);
let step = QUARTER_PIXEL_STEP as i32;
let offsets: [(i32, i32); 8] = [
(-step, -step),
(-step, 0),
(-step, step),
(0, -step),
(0, step),
(step, -step),
(step, 0),
(step, step),
];
for (drow, dcol) in offsets {
let cand_row = clamp_component(half_pixel_center.row as i32 + drow);
let cand_col = clamp_component(half_pixel_center.col as i32 + dcol);
if cand_row == best_mv.row && cand_col == best_mv.col {
continue;
}
let cand_mv = Mv {
row: cand_row,
col: cand_col,
};
let cand_sad = mb_luma_sad_at_mv(reference, mb_col, mb_row, src_y, cand_mv);
if cand_sad < best_sad {
best_sad = cand_sad;
best_mv = cand_mv;
}
}
SearchResult {
mv: best_mv,
sad: best_sad,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::motion_comp::filter_block_4x4;
fn ramp_plane(width: usize, height: usize) -> Vec<u8> {
let mut p = vec![0u8; width * height];
for y in 0..height {
for x in 0..width {
p[y * width + x] = ((x + y * 3) % 251) as u8;
}
}
p
}
fn feature_plane(
width: usize,
height: usize,
bg: u8,
fg: u8,
fx: usize,
fy: usize,
feat: usize,
) -> Vec<u8> {
let mut p = vec![bg; width * height];
for r in 0..feat {
for c in 0..feat {
let y = fy + r;
let x = fx + c;
if x < width && y < height {
p[y * width + x] = fg;
}
}
}
p
}
fn extract_mb_block(plane: &[u8], stride: usize, mb_col: usize, mb_row: usize) -> [u8; 256] {
let mut blk = [0u8; 256];
let x0 = mb_col * 16;
let y0 = mb_row * 16;
for r in 0..16 {
let src = (y0 + r) * stride + x0;
blk[r * 16..r * 16 + 16].copy_from_slice(&plane[src..src + 16]);
}
blk
}
fn whole_mv_sad_per_subblock_reference(
reference: LumaRef<'_>,
mb_col: usize,
mb_row: usize,
src_y: &[u8; 256],
mv: Mv,
) -> u32 {
let blk_x0 = mb_col * 16;
let blk_y0 = mb_row * 16;
let mv_eighth = crate::motion_comp::stored_luma_mv(mv);
let mut pred = [0u8; 256];
for sub_r in 0..4 {
for sub_c in 0..4 {
let patch = crate::motion_comp::fetch_block_whole_pixel(
reference.plane,
reference.stride,
reference.width,
reference.height,
blk_x0 + sub_c * 4,
blk_y0 + sub_r * 4,
mv_eighth,
);
for r in 0..4 {
let dst = (sub_r * 4 + r) * 16 + sub_c * 4;
pred[dst..dst + 4].copy_from_slice(&patch[r * 4..r * 4 + 4]);
}
}
}
block_sad_16x16(src_y, &pred)
}
#[test]
fn whole_mv_sad_matches_per_subblock_fetch_assembly() {
let width = 48;
let height = 40;
let reference = ramp_plane(width, height);
let src_plane = feature_plane(width, height, 100, 240, 5, 7, 6);
let candidates: [Mv; 13] = [
Mv { row: 0, col: 0 },
Mv { row: 4, col: 0 },
Mv { row: 0, col: 4 },
Mv { row: -4, col: -4 },
Mv { row: 8, col: -12 },
Mv { row: -16, col: 20 },
Mv { row: 64, col: 64 },
Mv { row: -64, col: -64 },
Mv { row: -1020, col: 0 },
Mv { row: 0, col: -1020 },
Mv { row: 1020, col: 0 },
Mv { row: 0, col: 1020 },
Mv {
row: 1020,
col: -1020,
},
];
for mb_row in 0..(height / 16) {
for mb_col in 0..(width / 16) {
let src_blk = extract_mb_block(&src_plane, width, mb_col, mb_row);
for mv in candidates {
let luma = packed_luma_ref(&reference, width, height);
let expected =
whole_mv_sad_per_subblock_reference(luma, mb_col, mb_row, &src_blk, mv);
let got = mb_luma_sad_at_whole_mv(luma, mb_col, mb_row, &src_blk, mv);
assert_eq!(
got, expected,
"fused whole-pixel SAD diverged at MB({mb_col},{mb_row}) mv={mv:?}"
);
}
}
}
}
#[test]
fn whole_mv_sad_matches_assembly_with_padded_stride() {
let width = 32;
let height = 32;
let stride = 41; let mut plane = vec![0u8; stride * height];
for y in 0..height {
for x in 0..width {
plane[y * stride + x] = ((x * 7 + y * 13) % 253) as u8;
}
}
let luma = LumaRef {
plane: &plane,
stride,
width,
height,
};
let mut src_blk = [0u8; 256];
for (i, slot) in src_blk.iter_mut().enumerate() {
*slot = ((i * 5) % 247) as u8;
}
for mv in [
Mv { row: 0, col: 0 },
Mv { row: 4, col: 8 },
Mv { row: -4, col: 4 },
Mv { row: 40, col: 40 },
Mv { row: -40, col: -40 },
] {
let expected = whole_mv_sad_per_subblock_reference(luma, 0, 0, &src_blk, mv);
let got = mb_luma_sad_at_whole_mv(luma, 0, 0, &src_blk, mv);
assert_eq!(got, expected, "padded-stride divergence at mv={mv:?}");
}
}
#[test]
fn block_sad_identical_inputs_is_zero() {
let mut a = [0u8; 256];
for (i, slot) in a.iter_mut().enumerate() {
*slot = (i % 251) as u8;
}
assert_eq!(block_sad_16x16(&a, &a), 0);
}
#[test]
fn block_sad_one_pixel_delta_is_one() {
let a = [10u8; 256];
let mut b = a;
b[42] = 11;
assert_eq!(block_sad_16x16(&a, &b), 1);
}
#[test]
fn block_sad_saturated_difference() {
let a = [0u8; 256];
let b = [255u8; 256];
assert_eq!(block_sad_16x16(&a, &b), 256 * 255);
}
#[test]
fn block_sad_known_manual_sum() {
let mut a = [0u8; 256];
let mut b = [0u8; 256];
a[0] = 10;
b[0] = 3;
a[1] = 20;
b[1] = 5;
a[2] = 30;
b[2] = 2;
assert_eq!(block_sad_16x16(&a, &b), 50);
}
fn packed_luma_ref<'a>(plane: &'a [u8], width: usize, height: usize) -> LumaRef<'a> {
LumaRef {
plane,
stride: width,
width,
height,
}
}
#[test]
fn sad_at_zero_mv_equals_direct_block_sad() {
let width = 32;
let height = 32;
let reference = ramp_plane(width, height);
let mut src_plane = reference.clone();
for y in 0..16 {
for x in (0..16).step_by(4) {
src_plane[y * width + x] = src_plane[y * width + x].wrapping_add(5);
}
}
let src_blk = extract_mb_block(&src_plane, width, 0, 0);
let ref_blk = extract_mb_block(&reference, width, 0, 0);
let expected = block_sad_16x16(&src_blk, &ref_blk);
let got = mb_luma_sad_at_whole_mv(
packed_luma_ref(&reference, width, height),
0,
0,
&src_blk,
Mv { row: 0, col: 0 },
);
assert_eq!(got, expected);
}
#[test]
fn diamond_search_finds_exact_translation_horizontal() {
let width = 64;
let height = 32;
let reference = feature_plane(width, height, 128, 240, 6, 4, 4);
let source_plane = feature_plane(width, height, 128, 240, 4, 4, 4);
let src_blk = extract_mb_block(&source_plane, width, 0, 0);
let result = small_diamond_search_luma(
packed_luma_ref(&reference, width, height),
0,
0,
&src_blk,
Mv { row: 0, col: 0 },
32,
);
assert_eq!(
result.mv,
Mv {
row: 0,
col: 2 * WHOLE_PIXEL_STEP,
},
"search must find the 2-whole-pixel horizontal offset"
);
assert_eq!(result.sad, 0, "exact translation ⇒ zero SAD");
}
#[test]
fn diamond_search_finds_exact_translation_diagonal() {
let width = 64;
let height = 64;
let reference = feature_plane(width, height, 100, 220, 8, 8, 5);
let source_plane = feature_plane(width, height, 100, 220, 5, 6, 5);
let src_blk = extract_mb_block(&source_plane, width, 0, 0);
let result = small_diamond_search_luma(
packed_luma_ref(&reference, width, height),
0,
0,
&src_blk,
Mv { row: 0, col: 0 },
64,
);
assert_eq!(
result.mv,
Mv {
row: 2 * WHOLE_PIXEL_STEP,
col: 3 * WHOLE_PIXEL_STEP,
}
);
assert_eq!(result.sad, 0);
}
#[test]
fn diamond_search_zero_iters_returns_center_sad() {
let width = 32;
let height = 32;
let reference = ramp_plane(width, height);
let src_blk = extract_mb_block(&reference, width, 0, 0);
let result = small_diamond_search_luma(
packed_luma_ref(&reference, width, height),
0,
0,
&src_blk,
Mv { row: 0, col: 0 },
0,
);
assert_eq!(result.mv, Mv { row: 0, col: 0 });
assert_eq!(result.sad, 0);
}
#[test]
fn diamond_search_identical_source_returns_zero_mv() {
let width = 32;
let height = 32;
let reference = ramp_plane(width, height);
let src_blk = extract_mb_block(&reference, width, 0, 0);
let result = small_diamond_search_luma(
packed_luma_ref(&reference, width, height),
0,
0,
&src_blk,
Mv { row: 0, col: 0 },
8,
);
assert_eq!(result.mv, Mv { row: 0, col: 0 });
assert_eq!(result.sad, 0);
}
#[test]
fn diamond_search_snaps_center_to_whole_pixel() {
let width = 32;
let height = 32;
let reference = vec![200u8; width * height];
let src_blk = [200u8; 256];
let result = small_diamond_search_luma(
packed_luma_ref(&reference, width, height),
0,
0,
&src_blk,
Mv { row: 1, col: 5 },
0,
);
assert_eq!(result.mv.row % WHOLE_PIXEL_STEP, 0);
assert_eq!(result.mv.col % WHOLE_PIXEL_STEP, 0);
assert_eq!(result.mv, Mv { row: 0, col: 4 });
assert_eq!(result.sad, 0);
}
#[test]
fn diamond_search_clamps_extreme_center_to_section_17_1_range() {
let width = 32;
let height = 32;
let reference = vec![128u8; width * height];
let src_blk = [128u8; 256];
let result = small_diamond_search_luma(
packed_luma_ref(&reference, width, height),
0,
0,
&src_blk,
Mv {
row: i16::MAX,
col: i16::MIN,
},
4,
);
assert!((MV_MIN..=MV_MAX).contains(&result.mv.row));
assert!((MV_MIN..=MV_MAX).contains(&result.mv.col));
assert_eq!(result.mv.row % WHOLE_PIXEL_STEP, 0);
assert_eq!(result.mv.col % WHOLE_PIXEL_STEP, 0);
assert_eq!(result.sad, 0);
}
#[test]
fn diamond_search_off_picture_edge_replicate_does_not_panic() {
let width = 32;
let height = 32;
let reference = ramp_plane(width, height);
let src_blk = extract_mb_block(&reference, width, 0, 0);
let result = small_diamond_search_luma(
packed_luma_ref(&reference, width, height),
0,
0,
&src_blk,
Mv { row: -64, col: -64 },
8,
);
assert_eq!(result.mv.row % WHOLE_PIXEL_STEP, 0);
assert_eq!(result.mv.col % WHOLE_PIXEL_STEP, 0);
assert!((MV_MIN..=MV_MAX).contains(&result.mv.row));
assert!((MV_MIN..=MV_MAX).contains(&result.mv.col));
}
#[test]
fn diamond_search_never_increases_sad_from_center() {
let width = 48;
let height = 48;
let reference = feature_plane(width, height, 90, 230, 6, 6, 5);
let source_plane = feature_plane(width, height, 90, 230, 4, 6, 5);
let src_blk = extract_mb_block(&source_plane, width, 0, 0);
let ref_luma = packed_luma_ref(&reference, width, height);
let sad_at_center =
mb_luma_sad_at_whole_mv(ref_luma, 0, 0, &src_blk, Mv { row: 0, col: 0 });
let result = small_diamond_search_luma(ref_luma, 0, 0, &src_blk, Mv { row: 0, col: 0 }, 8);
assert!(
result.sad <= sad_at_center,
"descent must not increase SAD (center={sad_at_center}, result={})",
result.sad
);
assert_eq!(result.mv, Mv { row: 0, col: 8 });
assert_eq!(result.sad, 0);
}
#[test]
fn half_pixel_refine_keeps_center_on_flat_source() {
let width = 32;
let height = 32;
let reference = vec![200u8; width * height];
let src_blk = [200u8; 256];
let result = half_pixel_refine_luma(
packed_luma_ref(&reference, width, height),
0,
0,
&src_blk,
Mv { row: 0, col: 0 },
);
assert_eq!(result.mv, Mv { row: 0, col: 0 });
assert_eq!(result.sad, 0);
}
fn two_d_ramp_plane(width: usize, height: usize) -> Vec<u8> {
let mut p = vec![0u8; width * height];
for y in 0..height {
for x in 0..width {
let v = ((x as i32) + 3 * (y as i32)).clamp(0, 240);
p[y * width + x] = v as u8;
}
}
p
}
#[test]
fn half_pixel_refine_finds_half_pixel_horizontal_shift() {
let width = 64;
let height = 64;
let reference = two_d_ramp_plane(width, height);
let ref_luma = packed_luma_ref(&reference, width, height);
let truth_mv = Mv {
row: 0,
col: HALF_PIXEL_STEP,
};
let mut src_blk = [0u8; 256];
let mv_eighth = stored_luma_mv(truth_mv);
let filters = filter_set_for_version(0).taps();
let blk_x0 = 16;
let blk_y0 = 16;
for sub_r in 0..4 {
for sub_c in 0..4 {
let blk_x = blk_x0 + sub_c * 4;
let blk_y = blk_y0 + sub_r * 4;
let patch = filter_block_4x4(
&reference, width, width, height, blk_x, blk_y, mv_eighth, filters,
);
for r in 0..4 {
let dst_row = sub_r * 4 + r;
let dst_col = sub_c * 4;
src_blk[dst_row * 16 + dst_col..dst_row * 16 + dst_col + 4]
.copy_from_slice(&patch[r * 4..r * 4 + 4]);
}
}
}
let result = half_pixel_refine_luma(ref_luma, 1, 1, &src_blk, Mv { row: 0, col: 0 });
assert_eq!(
result.mv, truth_mv,
"half-pixel +0.5 px horizontal shift expected, got {:?}",
result.mv
);
assert_eq!(result.sad, 0);
}
#[test]
fn half_pixel_refine_never_worsens_sad() {
let width = 48;
let height = 48;
let reference = ramp_plane(width, height);
let mut src_plane = reference.clone();
for y in 0..height {
for x in 1..(width - 1) {
let a = reference[y * width + x - 1] as u32;
let b = reference[y * width + x] as u32;
src_plane[y * width + x] = ((a + b) / 2) as u8;
}
}
let src_blk = extract_mb_block(&src_plane, width, 1, 1);
let ref_luma = packed_luma_ref(&reference, width, height);
let sad_at_center = mb_luma_sad_at_mv(ref_luma, 1, 1, &src_blk, Mv { row: 0, col: 0 });
let result = half_pixel_refine_luma(ref_luma, 1, 1, &src_blk, Mv { row: 0, col: 0 });
assert!(
result.sad <= sad_at_center,
"half-pixel refinement must not worsen SAD (center={sad_at_center}, result={})",
result.sad
);
assert!(result.mv.row.unsigned_abs() <= HALF_PIXEL_STEP as u16);
assert!(result.mv.col.unsigned_abs() <= HALF_PIXEL_STEP as u16);
assert_eq!(result.mv.row % HALF_PIXEL_STEP, 0);
assert_eq!(result.mv.col % HALF_PIXEL_STEP, 0);
}
#[test]
fn half_pixel_refine_clamps_at_section_17_1_boundary() {
let width = 32;
let height = 32;
let reference = vec![100u8; width * height];
let src_blk = [100u8; 256];
let result = half_pixel_refine_luma(
packed_luma_ref(&reference, width, height),
0,
0,
&src_blk,
Mv {
row: 1020,
col: 1020,
},
);
assert!((MV_MIN..=MV_MAX).contains(&result.mv.row));
assert!((MV_MIN..=MV_MAX).contains(&result.mv.col));
assert_eq!(
result.mv,
Mv {
row: 1020,
col: 1020
}
);
assert_eq!(result.sad, 0);
}
#[test]
fn mb_luma_sad_at_mv_whole_pixel_matches_whole_pixel_helper() {
let width = 32;
let height = 32;
let reference = ramp_plane(width, height);
let mut src_plane = reference.clone();
for y in 0..height {
src_plane[y * width + (y % width)] = src_plane[y * width + (y % width)].wrapping_add(7);
}
let src_blk = extract_mb_block(&src_plane, width, 0, 0);
let ref_luma = packed_luma_ref(&reference, width, height);
let mv = Mv { row: 0, col: 0 };
let sad_general = mb_luma_sad_at_mv(ref_luma, 0, 0, &src_blk, mv);
let sad_whole = mb_luma_sad_at_whole_mv(ref_luma, 0, 0, &src_blk, mv);
assert_eq!(sad_general, sad_whole);
}
#[test]
fn quarter_pixel_refine_keeps_center_on_flat_source() {
let width = 32;
let height = 32;
let reference = vec![200u8; width * height];
let src_blk = [200u8; 256];
let result = quarter_pixel_refine_luma(
packed_luma_ref(&reference, width, height),
0,
0,
&src_blk,
Mv {
row: 0,
col: HALF_PIXEL_STEP,
},
);
assert_eq!(
result.mv,
Mv {
row: 0,
col: HALF_PIXEL_STEP,
}
);
assert_eq!(result.sad, 0);
}
fn stepped_plane(width: usize, height: usize) -> Vec<u8> {
let mut p = vec![0u8; width * height];
for y in 0..height {
for x in 0..width {
let base = ((x as i32) + 2 * (y as i32)).clamp(0, 180);
let step = if x % 3 == 0 { 40 } else { 0 };
let stripe = if y % 5 == 0 { -20 } else { 0 };
let v = (base + step + stripe).clamp(0, 240);
p[y * width + x] = v as u8;
}
}
p
}
#[test]
fn quarter_pixel_refine_finds_quarter_pixel_horizontal_shift() {
let width = 64;
let height = 64;
let reference = stepped_plane(width, height);
let ref_luma = packed_luma_ref(&reference, width, height);
let truth_mv = Mv {
row: 0,
col: QUARTER_PIXEL_STEP,
};
let mut src_blk = [0u8; 256];
let mv_eighth = stored_luma_mv(truth_mv);
let filters = filter_set_for_version(0).taps();
let blk_x0 = 16;
let blk_y0 = 16;
for sub_r in 0..4 {
for sub_c in 0..4 {
let blk_x = blk_x0 + sub_c * 4;
let blk_y = blk_y0 + sub_r * 4;
let patch = filter_block_4x4(
&reference, width, width, height, blk_x, blk_y, mv_eighth, filters,
);
for r in 0..4 {
let dst_row = sub_r * 4 + r;
let dst_col = sub_c * 4;
src_blk[dst_row * 16 + dst_col..dst_row * 16 + dst_col + 4]
.copy_from_slice(&patch[r * 4..r * 4 + 4]);
}
}
}
let half = half_pixel_refine_luma(ref_luma, 1, 1, &src_blk, Mv { row: 0, col: 0 });
let result = quarter_pixel_refine_luma(ref_luma, 1, 1, &src_blk, half.mv);
assert_eq!(
result.mv, truth_mv,
"quarter-pixel +1/4 px horizontal shift expected, got {:?}",
result.mv
);
assert_eq!(result.sad, 0);
}
#[test]
fn quarter_pixel_refine_never_worsens_sad() {
let width = 48;
let height = 48;
let reference = ramp_plane(width, height);
let mut src_plane = reference.clone();
for y in 0..height {
for x in 1..(width - 1) {
let a = reference[y * width + x - 1] as u32;
let b = reference[y * width + x] as u32;
let c = reference[y * width + x + 1] as u32;
src_plane[y * width + x] = ((a + 2 * b + c) / 4) as u8;
}
}
let src_blk = extract_mb_block(&src_plane, width, 1, 1);
let ref_luma = packed_luma_ref(&reference, width, height);
let half_center = Mv {
row: 0,
col: HALF_PIXEL_STEP,
};
let sad_at_center = mb_luma_sad_at_mv(ref_luma, 1, 1, &src_blk, half_center);
let result = quarter_pixel_refine_luma(ref_luma, 1, 1, &src_blk, half_center);
assert!(
result.sad <= sad_at_center,
"quarter-pixel refinement must not worsen SAD (center={sad_at_center}, result={})",
result.sad
);
let drow = result.mv.row - half_center.row;
let dcol = result.mv.col - half_center.col;
assert!(drow.abs() <= QUARTER_PIXEL_STEP);
assert!(dcol.abs() <= QUARTER_PIXEL_STEP);
}
#[test]
fn quarter_pixel_refine_clamps_at_section_17_1_boundary() {
let width = 32;
let height = 32;
let reference = vec![100u8; width * height];
let src_blk = [100u8; 256];
let result = quarter_pixel_refine_luma(
packed_luma_ref(&reference, width, height),
0,
0,
&src_blk,
Mv {
row: 1022,
col: 1022,
},
);
assert!((MV_MIN..=MV_MAX).contains(&result.mv.row));
assert!((MV_MIN..=MV_MAX).contains(&result.mv.col));
assert_eq!(
result.mv,
Mv {
row: 1022,
col: 1022,
}
);
assert_eq!(result.sad, 0);
}
#[test]
fn quarter_pixel_refine_at_whole_pixel_center_equals_half_pixel_refine() {
let width = 48;
let height = 48;
let reference = ramp_plane(width, height);
let src_blk = extract_mb_block(&reference, width, 1, 1);
let ref_luma = packed_luma_ref(&reference, width, height);
let whole_center = Mv { row: 0, col: 0 };
let sad_at_center = mb_luma_sad_at_mv(ref_luma, 1, 1, &src_blk, whole_center);
let result = quarter_pixel_refine_luma(ref_luma, 1, 1, &src_blk, whole_center);
assert!(result.sad <= sad_at_center);
assert_eq!(result.mv, whole_center);
assert_eq!(result.sad, 0);
}
#[test]
fn search_result_is_copy_eq() {
let a = SearchResult {
mv: Mv { row: 4, col: -8 },
sad: 1234,
};
let b = a;
assert_eq!(a, b);
assert_eq!(format!("{a:?}"), format!("{b:?}"));
}
#[allow(clippy::vec_init_then_push)]
fn sad_stress_pairs() -> Vec<([u8; 256], [u8; 256])> {
let mut pairs: Vec<([u8; 256], [u8; 256])> = Vec::new();
pairs.push(([0u8; 256], [0u8; 256]));
pairs.push(([255u8; 256], [255u8; 256]));
pairs.push(([0u8; 256], [255u8; 256]));
pairs.push(([255u8; 256], [0u8; 256]));
let mut s5 = [10u8; 256];
let mut p5 = [10u8; 256];
s5[133] = 11;
p5[133] = 10;
pairs.push((s5, p5));
let mut s6 = [0u8; 256];
let mut p6 = [0u8; 256];
for r in 0..16 {
for c in 0..16 {
if c % 2 == 0 {
s6[r * 16 + c] = 200;
p6[r * 16 + c] = 50;
} else {
s6[r * 16 + c] = 70;
p6[r * 16 + c] = 130;
}
}
}
pairs.push((s6, p6));
let mut s7 = [0u8; 256];
let mut p7 = [0u8; 256];
for r in 0..16 {
let (sv, pv) = if r % 2 == 0 { (240, 16) } else { (32, 192) };
for c in 0..16 {
s7[r * 16 + c] = sv;
p7[r * 16 + c] = pv;
}
}
pairs.push((s7, p7));
let mut s8 = [0u8; 256];
for (i, slot) in s8.iter_mut().enumerate() {
*slot = (i & 0xff) as u8;
}
pairs.push((s8, [128u8; 256]));
pairs.push(([128u8; 256], s8));
let mut s10 = [0u8; 256];
let mut p10 = [0u8; 256];
for r in 0..16 {
for c in 0..16 {
let mix = (r as u32 * 7).wrapping_add(c as u32 * 11).wrapping_add(13)
^ (r as u32 * c as u32);
s10[r * 16 + c] = mix as u8;
p10[r * 16 + c] = ((r as u32 * 16 + c as u32) & 0xff) as u8;
}
}
pairs.push((s10, p10));
let mut s11 = [42u8; 256];
let p11 = [42u8; 256];
for (c, slot) in s11.iter_mut().take(16).enumerate() {
*slot = (c * 17) as u8;
}
pairs.push((s11, p11));
let mut s12 = [42u8; 256];
let p12 = [42u8; 256];
for r in 0..16 {
s12[r * 16 + 7] = (r * 17) as u8;
}
pairs.push((s12, p12));
let mut s13 = [0u8; 256];
let mut p13 = [0u8; 256];
for r in 0..16 {
for c in 0..16 {
if (r + c) & 1 == 0 {
s13[r * 16 + c] = 240;
p13[r * 16 + c] = 16;
} else {
s13[r * 16 + c] = 16;
p13[r * 16 + c] = 240;
}
}
}
pairs.push((s13, p13));
let mut s14 = [0u8; 256];
let mut p14 = [0u8; 256];
for i in 0..256 {
s14[i] = ((i.wrapping_mul(101)) ^ 0x5a) as u8;
p14[i] = ((i.wrapping_mul(53)) ^ 0xa5) as u8;
}
pairs.push((s14, p14));
let mut s15 = [0u8; 256];
let mut p15 = [0u8; 256];
for i in 0..256 {
s15[i] = ((i.wrapping_mul(7) ^ (i >> 3)) & 0xff) as u8;
p15[i] = ((i.wrapping_mul(11) ^ (i >> 2)) & 0xff) as u8;
}
pairs.push((s15, p15));
let mut s16a = [0u8; 256];
let mut p16a = [255u8; 256];
for r in 0..16 {
for c in 0..16 {
if (r + c) & 1 == 0 {
s16a[r * 16 + c] = 0;
p16a[r * 16 + c] = 255;
} else {
s16a[r * 16 + c] = 255;
p16a[r * 16 + c] = 0;
}
}
}
pairs.push((s16a, p16a));
let mut s17 = [0u8; 256];
let mut p17 = [0u8; 256];
for r in 8..16 {
for c in 0..16 {
s17[r * 16 + c] = 200;
p17[r * 16 + c] = 40;
}
}
pairs.push((s17, p17));
let mut s18 = [0u8; 256];
let mut p18 = [0u8; 256];
for r in 0..16 {
for c in 0..16 {
if c < 8 {
s18[r * 16 + c] = 220;
p18[r * 16 + c] = 20;
} else {
s18[r * 16 + c] = 20;
p18[r * 16 + c] = 220;
}
}
}
pairs.push((s18, p18));
let mut s19 = [0u8; 256];
let mut p19 = [0u8; 256];
for i in 0..256 {
s19[i] = 100;
p19[i] = 100 + ((i % 4) as u8);
}
pairs.push((s19, p19));
let mut s20 = [0u8; 256];
let mut p20 = [0u8; 256];
for r in 0..16 {
for c in 0..16 {
let v = (r * 16 + c) as i32;
let centred = 128 + ((v % 41) - 20);
let other = 128 - ((v % 41) - 20);
s20[r * 16 + c] = centred.clamp(0, 255) as u8;
p20[r * 16 + c] = other.clamp(0, 255) as u8;
}
}
pairs.push((s20, p20));
let mut s21 = [0u8; 256];
let mut p21 = [0u8; 256];
for i in 0..256 {
s21[i] = (i & 0x7f) as u8;
p21[i] = ((i & 0x7f) + 17).min(255) as u8;
}
pairs.push((s21, p21));
pairs
}
#[test]
fn block_sad_public_dispatch_matches_scalar_on_stress_inputs() {
for (idx, (src, pred)) in sad_stress_pairs().iter().enumerate() {
let via_public = block_sad_16x16(src, pred);
let via_scalar = block_sad_16x16_scalar(src, pred);
assert_eq!(
via_public, via_scalar,
"pair #{idx}: public dispatch ≠ scalar listing"
);
}
}
#[cfg(feature = "simd")]
#[test]
fn block_sad_simd_matches_scalar_on_stress_inputs() {
for (idx, (src, pred)) in sad_stress_pairs().iter().enumerate() {
let via_simd = block_sad_16x16_simd(src, pred);
let via_scalar = block_sad_16x16_scalar(src, pred);
assert_eq!(via_simd, via_scalar, "pair #{idx}: SIMD ≠ scalar listing");
}
}
}