use core::arch::wasm32::*;
#[allow(clippy::too_many_arguments)]
#[target_feature(enable = "simd128")]
pub(crate) fn sse_and_rate_wasm(
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 = f32x4_splat(q_scaled);
let mut sse_acc = f32x4_splat(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 = f32x4_splat(threshold);
let idx = row + x;
let cv =
unsafe { v128_load(coeff[idx..idx + 4].as_ptr() as *const f32 as *const v128) };
let mv = unsafe {
v128_load(inv_matrix[idx..idx + 4].as_ptr() as *const f32 as *const v128)
};
let a = f32x4_mul(f32x4_mul(mv, qs), cv);
let absa = f32x4_abs(a);
let keep = f32x4_ge(absa, thrv);
let rounded = f32x4_nearest(a);
let q = v128_and(rounded, keep);
let d = f32x4_sub(a, q);
let mut d2 = f32x4_mul(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 { v128_load(lanemask.as_ptr() as *const f32 as *const v128) };
d2 = f32x4_mul(d2, lm); }
sse_acc = f32x4_add(sse_acc, d2);
unsafe {
v128_store(qbuf.as_mut_ptr() as *mut f32 as *mut v128, 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;
}
}
(
{
let __h = sse_acc;
f32x4_extract_lane::<0>(__h)
+ f32x4_extract_lane::<1>(__h)
+ f32x4_extract_lane::<2>(__h)
+ f32x4_extract_lane::<3>(__h)
},
nzeros,
mag_bits,
)
}