#[cfg(target_arch = "x86")]
use std::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use std::arch::x86_64::*;
#[inline]
#[target_feature(enable = "sse4.1")]
fn hsum(v: __m128) -> f32 {
let shuf = _mm_movehdup_ps(v); let sums = _mm_add_ps(v, shuf);
let shuf2 = _mm_movehl_ps(shuf, sums);
let sums = _mm_add_ss(sums, shuf2);
_mm_cvtss_f32(sums)
}
#[allow(clippy::too_many_arguments)]
#[target_feature(enable = "sse4.1")]
pub(crate) fn sse_and_rate_sse(
coeff: &[f32],
inv_matrix: &[f32],
q_scaled: f32,
width: usize,
height: usize,
half: usize,
cx: usize,
cy: usize,
thr: &[f32; 4],
) -> (f32, usize, f32) {
let n = width * height;
assert!(coeff.len() >= n && inv_matrix.len() >= n);
debug_assert!(width.is_multiple_of(4) && half.is_multiple_of(4));
let qs = _mm_set1_ps(q_scaled);
let mut sse_acc = _mm_setzero_ps();
let mut nzeros = 0usize;
let mut mag_bits = 0.0f32;
const RND: i32 = _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC;
let mut qbuf = [0.0f32; 4];
for y in 0..height {
let yfix = if y >= height / 2 { 2 } else { 0 };
let thr_lo = thr[yfix];
let thr_hi = thr[yfix + 1];
let row = y * width;
let mut x = 0;
while x < width {
let threshold = if x >= half { thr_hi } else { thr_lo };
let thrv = _mm_set1_ps(threshold);
let idx = row + x;
let cv = unsafe { _mm_loadu_ps(coeff[idx..idx + 4].as_ptr()) };
let mv = unsafe { _mm_loadu_ps(inv_matrix[idx..idx + 4].as_ptr()) };
let a = _mm_mul_ps(_mm_mul_ps(mv, qs), cv);
let absa = _mm_andnot_ps(_mm_set1_ps(-0.0), a);
let keep = _mm_cmpge_ps(absa, thrv);
let rounded = _mm_round_ps::<RND>(a);
let q = _mm_and_ps(rounded, keep); let d = _mm_sub_ps(a, q);
let mut d2 = _mm_mul_ps(d, d);
if y < cy && x == 0 {
let mut lanemask = [1.0f32; 4];
for lane in 0..cx.min(4) {
lanemask[lane] = 0.0;
}
let lm = unsafe { _mm_loadu_ps(lanemask.as_ptr()) };
d2 = _mm_mul_ps(d2, lm); }
sse_acc = _mm_add_ps(sse_acc, d2);
unsafe {
_mm_storeu_ps(qbuf.as_mut_ptr(), q);
}
for lane in 0..4 {
if y < cy && x == 0 && lane < cx {
continue; }
let qv = qbuf[lane];
if qv != 0.0 {
nzeros += 1;
mag_bits += crate::enc_ac_strategy::rate_log2(qv.abs());
}
}
x += 4;
}
}
(hsum(sse_acc), nzeros, mag_bits)
}