forge
Explore
Log in

Don't you dare go Hollow

AVX2 luma film-grain row

Browse files at this commit

a620a4d399ce6478c35fc73494be60ce5e7dea5eAhmet Kaan GümüşParent: 66498f4
  • perf
    • AVX2 luma film-grain row
Show full message
perf(av1): AVX2 luma film-grain row

`add_noise_to_block` was 7% of a 1080p decode's self time, and its luma arm
is the larger half: one scaling-LUT read, one multiply, a `Round2` and a
clip per sample. AVX2 does eight at a time -- the LUT read is a
`vpgatherdd`, the rest is the same i32 arithmetic -- and every other CPU
runs the scalar loop, which stays the reference. The gather index is
clamped to the LUT's last entry so the load cannot leave the table; the
scalar form indexes unclamped (it would panic), and the LUT spans the whole
sample range the grain bit depth allows, so the two agree wherever the
scalar one does not panic.

Pinned against the scalar row over 8/10/12-bit sample and LUT ranges, every
`grain_scaling_minus_8` shift, restricted and full clip ranges, and row
lengths covering the 8-lane body plus every tail. Interleaved medians,
1080p: 10.51 s -> 10.40 s (11.01 s at the lane's base). Byte-exact on all
three probe inputs.
crates/ec-av1/src/film_grain.rsmodified+169 -2
@@ -444,12 +444,120 @@ fn add_noise_to_block(
444 let grow = ((lg_row0 + i) * lg_stride + lg_col0) as usize;444 let grow = ((lg_row0 + i) * lg_stride + lg_col0) as usize;
445 let pixels = &mut picture.y[prow..prow + width];445 let pixels = &mut picture.y[prow..prow + width];
446 let grain = &luma_grain[grow..grow + width];446 let grain = &luma_grain[grow..grow + width];
447+ luma_noise_row(
448+ pixels, grain, scaling_y, rounding_offset, scaling_shift, min_luma, max_luma,
449+ );
450+ }
451+ }
452+}
453+
454+/// lane-perf5: the luma noise row (spec 7.18.3.5's `add_noise_to_block` luma
455+/// arm), 7% of a 1080p decode with film grain. AVX2 does 8 samples at a time
456+/// -- the scaling-LUT read is a `vpgatherdd`, the rest is the same i32
457+/// multiply, `Round2` and clip; every other CPU runs the scalar loop, which
458+/// stays the reference (`simd_matches_scalar_luma_noise_row` pins the pair).
459+#[allow(unsafe_code)]
460+fn luma_noise_row(
461+ pixels: &mut [u16],
462+ grain: &[i32],
463+ scaling: &[i32],
464+ rounding_offset: i32,
465+ scaling_shift: i32,
466+ min_luma: i32,
467+ max_luma: i32,
468+) {
469+ #[cfg(target_arch = "x86_64")]
470+ if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
471+ // SAFETY: reached only when the CPU reports avx2; the kernel reads
472+ // `grain[..pixels.len()]` and gathers only in-range LUT entries.
473+ unsafe {
474+ simd::luma_noise_row_avx2(
475+ pixels, grain, scaling, rounding_offset, scaling_shift, min_luma, max_luma,
476+ )
477+ };
478+ return;
479+ }
480+ luma_noise_row_scalar(
481+ pixels, grain, scaling, rounding_offset, scaling_shift, min_luma, max_luma,
482+ );
483+}
484+
485+/// The scalar reference for [`luma_noise_row`].
486+fn luma_noise_row_scalar(
487+ pixels: &mut [u16],
488+ grain: &[i32],
489+ scaling: &[i32],
490+ rounding_offset: i32,
491+ scaling_shift: i32,
492+ min_luma: i32,
493+ max_luma: i32,
494+) {
447 for (p, &g) in pixels.iter_mut().zip(grain) {495 for (p, &g) in pixels.iter_mut().zip(grain) {
448- let delta =496+ let delta = (scaling[*p as usize] * g + rounding_offset) >> scaling_shift;
449- (scaling_y[*p as usize] * g + rounding_offset) >> scaling_shift;
450 *p = ((*p as i32 + delta).clamp(min_luma, max_luma)) as u16;497 *p = ((*p as i32 + delta).clamp(min_luma, max_luma)) as u16;
451 }498 }
452 }499 }
500+
501+#[cfg(target_arch = "x86_64")]
502+#[allow(unsafe_code)]
503+#[allow(unsafe_op_in_unsafe_fn)] // each kernel's whole body is its contract
504+mod simd {
505+ use std::arch::x86_64::*;
506+
507+ /// [`super::luma_noise_row`]'s AVX2 kernel, 8 samples per iteration.
508+ ///
509+ /// The gather index is clamped to the LUT's last entry. The scalar form
510+ /// indexes unclamped -- it would panic rather than read out of bounds --
511+ /// so the clamp is only a bound on the load: the LUT covers the whole
512+ /// sample range the grain bit depth allows, so a real decode never
513+ /// reaches it, and the two forms agree wherever the scalar one does not
514+ /// panic.
515+ ///
516+ /// # Safety
517+ /// Requires AVX2; `grain` must be at least `pixels.len()` long and
518+ /// `scaling` non-empty.
519+ #[target_feature(enable = "avx2")]
520+ #[allow(clippy::too_many_arguments)]
521+ pub unsafe fn luma_noise_row_avx2(
522+ pixels: &mut [u16],
523+ grain: &[i32],
524+ scaling: &[i32],
525+ rounding_offset: i32,
526+ scaling_shift: i32,
527+ min_luma: i32,
528+ max_luma: i32,
529+ ) {
530+ let n = pixels.len().min(grain.len());
531+ let last = _mm256_set1_epi32(scaling.len() as i32 - 1);
532+ let rnd = _mm256_set1_epi32(rounding_offset);
533+ let sh = _mm_cvtsi32_si128(scaling_shift);
534+ let lo = _mm256_set1_epi32(min_luma);
535+ let hi = _mm256_set1_epi32(max_luma);
536+ let pp = pixels.as_mut_ptr();
537+ let gp = grain.as_ptr();
538+ let mut c = 0usize;
539+ while c + 8 <= n {
540+ let p16 = _mm_loadu_si128(pp.add(c).cast());
541+ let p32 = _mm256_cvtepu16_epi32(p16);
542+ let idx = _mm256_min_epi32(p32, last);
543+ let s = _mm256_i32gather_epi32(scaling.as_ptr(), idx, 4);
544+ let g = _mm256_loadu_si256(gp.add(c).cast());
545+ let delta = _mm256_sra_epi32(_mm256_add_epi32(_mm256_mullo_epi32(s, g), rnd), sh);
546+ let v = _mm256_max_epi32(
547+ _mm256_min_epi32(_mm256_add_epi32(p32, delta), hi),
548+ lo,
549+ );
550+ // Every lane is already inside `[min_luma, max_luma]`, so the
551+ // unsigned saturation of `packus` is exact; `permute4x64` undoes
552+ // the pack's per-128-bit-lane interleave.
553+ let packed = _mm256_permute4x64_epi64(_mm256_packus_epi32(v, v), 0b0000_1000);
554+ _mm_storeu_si128(pp.add(c).cast(), _mm256_castsi256_si128(packed));
555+ c += 8;
556+ }
557+ super::luma_noise_row_scalar(
558+ &mut pixels[c..], &grain[c..], scaling, rounding_offset, scaling_shift, min_luma,
559+ max_luma,
560+ );
453 }561 }
454 }562 }
455 563
@@ -987,3 +1095,62 @@ pub(crate) fn apply_grain(
987 1095
988 out1096 out
989 }1097 }
1098+
1099+#[cfg(test)]
1100+mod perf5_tests {
1101+ /// lane-perf5: the AVX2 luma-noise kernel against the scalar reference it
1102+ /// replaces, over the domain a decode hands it -- 8/10/12-bit sample and
1103+ /// LUT ranges, both grain signs, every `grain_scaling_minus_8` shift, the
1104+ /// restricted and full clip ranges, and row lengths that exercise the
1105+ /// 8-lane body and every tail length.
1106+ #[test]
1107+ fn simd_matches_scalar_luma_noise_row() {
1108+ let mut state = 0x1234_5678_9abc_def0u64;
1109+ let mut rng = move || {
1110+ state ^= state << 13;
1111+ state ^= state >> 7;
1112+ state ^= state << 17;
1113+ state
1114+ };
1115+ let mut checked = 0usize;
1116+ for bd_shift in 0..3u32 {
1117+ let lut_len = 256usize << bd_shift;
1118+ let sample_max = (lut_len - 1) as u16;
1119+ let scaling: Vec<i32> = (0..lut_len).map(|_| (rng() % 256) as i32).collect();
1120+ for scaling_shift in 8..12i32 {
1121+ let rounding_offset = 1i32 << (scaling_shift - 1);
1122+ for &(lo, hi) in &[(0i32, sample_max as i32), (16 << bd_shift, 235 << bd_shift)] {
1123+ for len in [1usize, 4, 7, 8, 9, 16, 31, 32, 64, 128] {
1124+ let pixels: Vec<u16> =
1125+ (0..len).map(|_| (rng() % (u64::from(sample_max) + 1)) as u16).collect();
1126+ let grain: Vec<i32> =
1127+ (0..len).map(|_| (rng() % 513) as i32 - 256).collect();
1128+ let mut want = pixels.clone();
1129+ super::luma_noise_row_scalar(
1130+ &mut want, &grain, &scaling, rounding_offset, scaling_shift, lo, hi,
1131+ );
1132+ let mut got = pixels.clone();
1133+ super::luma_noise_row(
1134+ &mut got, &grain, &scaling, rounding_offset, scaling_shift, lo, hi,
1135+ );
1136+ assert_eq!(got, want, "dispatch len={len} shift={scaling_shift}");
1137+ #[cfg(target_arch = "x86_64")]
1138+ if std::arch::is_x86_feature_detected!("avx2") {
1139+ let mut avx = pixels.clone();
1140+ #[allow(unsafe_code)]
1141+ unsafe {
1142+ super::simd::luma_noise_row_avx2(
1143+ &mut avx, &grain, &scaling, rounding_offset, scaling_shift,
1144+ lo, hi,
1145+ )
1146+ };
1147+ assert_eq!(avx, want, "avx2 len={len} shift={scaling_shift}");
1148+ }
1149+ checked += 1;
1150+ }
1151+ }
1152+ }
1153+ }
1154+ assert_eq!(checked, 3 * 4 * 2 * 10);
1155+ }
1156+}
crates/ec-av1/src/mc.rsmodified+4 -2
@@ -248,7 +248,8 @@ fn sample(
248 /// checked against them by `simd_matches_scalar_*` -- and every non-x86_64248 /// checked against them by `simd_matches_scalar_*` -- and every non-x86_64
249 /// build, plus any x86_64 CPU without AVX2 or SSE4.1, decodes through them.249 /// build, plus any x86_64 CPU without AVX2 or SSE4.1, decodes through them.
250 #[derive(Clone, Copy, PartialEq, Eq, Debug)]250 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
251-enum SimdLevel {251+#[allow(dead_code)] // every variant is constructed only on x86_64
252+pub(crate) enum SimdLevel {
252 Scalar,253 Scalar,
253 /// `_mm_madd_epi16` (SSE2) horizontal pass, `_mm_mullo_epi32` (SSE4.1)254 /// `_mm_madd_epi16` (SSE2) horizontal pass, `_mm_mullo_epi32` (SSE4.1)
254 /// vertical pass -- the pair is gated on SSE4.1, the later of the two.255 /// vertical pass -- the pair is gated on SSE4.1, the later of the two.
@@ -257,7 +258,7 @@ enum SimdLevel {
257 }258 }
258 259
259 /// The level, detected once per process (spec-irrelevant: pure dispatch).260 /// The level, detected once per process (spec-irrelevant: pure dispatch).
260-fn simd_level() -> SimdLevel {261+pub(crate) fn simd_level() -> SimdLevel {
261 static LEVEL: std::sync::OnceLock<SimdLevel> = std::sync::OnceLock::new();262 static LEVEL: std::sync::OnceLock<SimdLevel> = std::sync::OnceLock::new();
262 *LEVEL.get_or_init(|| {263 *LEVEL.get_or_init(|| {
263 #[cfg(target_arch = "x86_64")]264 #[cfg(target_arch = "x86_64")]
@@ -322,6 +323,7 @@ fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i32]) {
322 /// scalar function's arithmetic, lane-parallel, with identical rounding.323 /// scalar function's arithmetic, lane-parallel, with identical rounding.
323 #[allow(unsafe_code)]324 #[allow(unsafe_code)]
324 #[cfg(target_arch = "x86_64")]325 #[cfg(target_arch = "x86_64")]
326+#[allow(unsafe_op_in_unsafe_fn)] // each kernel's whole body is its contract
325 mod simd {327 mod simd {
326 use super::{round2, INTER_ROUND_0};328 use super::{round2, INTER_ROUND_0};
327 use std::arch::x86_64::*;329 use std::arch::x86_64::*;