use std::arch::aarch64::*;
#[allow(clippy::too_many_arguments)]
#[target_feature(enable = "neon")]
pub(crate) fn sse_and_rate_neon(
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 = vdupq_n_f32(q_scaled);
let mut sse_acc = vdupq_n_f32(0.0);
let mut nzeros = 0usize;
let mut mag_bits = 0.0f32;
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 = vdupq_n_f32(threshold);
let idx = row + x;
let cv = unsafe { vld1q_f32(coeff[idx..idx + 4].as_ptr()) };
let mv = unsafe { vld1q_f32(inv_matrix[idx..idx + 4].as_ptr()) };
let a = vmulq_f32(vmulq_f32(mv, qs), cv);
let absa = vabsq_f32(a);
let keep = vcgeq_f32(absa, thrv);
let rounded = vrndnq_f32(a);
let q = vreinterpretq_f32_u32(vandq_u32(vreinterpretq_u32_f32(rounded), keep));
let d = vsubq_f32(a, q);
let mut d2 = vmulq_f32(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 { vld1q_f32(lanemask.as_ptr()) };
d2 = vmulq_f32(d2, lm); }
sse_acc = vaddq_f32(sse_acc, d2);
unsafe {
vst1q_f32(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;
}
}
(vaddvq_f32(sse_acc), nzeros, mag_bits)
}