use super::xyb::rgb_to_xyb_f32x8_avx2;
use crate::image::Image3F;
use crate::xyb::XybMatrix;
use std::arch::x86_64::*;
#[target_feature(enable = "avx2,fma")]
pub(crate) fn sampled_b_gradient_ratio_avx2(linear: &Image3F, stride: usize) -> f32 {
let (w, h) = (linear.xsize(), linear.ysize());
let [rp, gp, bp] = std::array::from_fn(|c| linear.plane_data(c));
let (mut sum_y, mut sum_b) = (0.0, 0.0);
for y in (0..h).step_by(stride) {
let has_below = y + 1 < h;
for x in (0..w).step_by(2 * stride) {
let i = y * w + x;
let right = if x + 1 < w { i + 1 } else { i };
let below = if has_below { i + w } else { i };
let next_x = x + stride;
let paired = next_x < w;
let j = if paired { i + stride } else { i };
let next_right = if paired && next_x + 1 < w { j + 1 } else { j };
let next_below = if paired && has_below { j + w } else { j };
let gather = |p: &[f32]| {
_mm256_setr_ps(
p[i],
p[right],
p[below],
0.0,
p[j],
p[next_right],
p[next_below],
0.0,
)
};
let (_, yv, bv) =
rgb_to_xyb_f32x8_avx2::<true>(&XybMatrix::SPEC, gather(rp), gather(gp), gather(bp));
let bv = _mm256_sub_ps(bv, yv);
let mut ys = [0.0; 8];
let mut bs = [0.0; 8];
unsafe {
_mm256_storeu_ps(ys.as_mut_ptr(), yv);
_mm256_storeu_ps(bs.as_mut_ptr(), bv);
}
for (lane, sx) in [(0, x), (4, next_x)] {
if sx >= w {
break;
}
if sx + 1 < w {
sum_y += (ys[lane + 1] - ys[lane]).abs();
sum_b += (bs[lane + 1] - bs[lane]).abs();
}
if has_below {
sum_y += (ys[lane + 2] - ys[lane]).abs();
sum_b += (bs[lane + 2] - bs[lane]).abs();
}
}
}
}
if sum_y > f32::EPSILON {
sum_b / sum_y
} else {
0.0
}
}