diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 05a768ba..1f8ac229 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -16140,6 +16140,9 @@ fn lf_level( // Feature index: `SEG_LVL_ALT_LF_Y_V + dir` for luma, `_U`/`_V` (3/4) // for chroma. let feature = if plane_idx == 0 { SEG_LVL_ALT_LF_Y_V + dir } else { plane_idx + 2 }; + // lane-perf9: `segment_id` is `0` and this lookup is skipped entirely + // when the frame codes no segmentation (`seg_lf_active`), which is what + // spares the deblock loop two thread-local reads per 4x4 edge. let base = match seg_feature(usize::from(segment_id), feature) { Some(data) => (base + data).clamp(0, 63), None => base, @@ -16173,6 +16176,11 @@ fn edge_params( chroma: bool, x0: usize, y0: usize, + // lane-perf9: `segmentation_enabled`, read once per plane pass instead of + // four thread-local reads (`SEG_MI_DIMS`, `SEG_IDS`, twice each) plus two + // `SEG` borrows per 4x4 edge. With it clear, every segment id is 0 and no + // `SEG_LVL_ALT_LF_*` feature can be active, so the levels are unchanged. + seg_lf_active: bool, ) -> Option<(u8, i32)> { let (mi_r, mi_c) = (plane_to_mi(chroma, y0), plane_to_mi(chroma, x0)); let cur_tx = if dir == 0 { @@ -16220,15 +16228,13 @@ fn edge_params( { return None; } - let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf, segment_id_at(mi_r, mi_c)); - let pv_level = lf_level( - lf, - plane_idx, - dir, - pv_ref, - pv_delta_lf, - segment_id_at(pv_mi_r, pv_mi_c), - ); + let (cur_seg, pv_seg) = if seg_lf_active { + (segment_id_at(mi_r, mi_c), segment_id_at(pv_mi_r, pv_mi_c)) + } else { + (0, 0) + }; + let cur_level = lf_level(lf, plane_idx, dir, cur_ref, cur_delta_lf, cur_seg); + let pv_level = lf_level(lf, plane_idx, dir, pv_ref, pv_delta_lf, pv_seg); if cur_level == 0 && pv_level == 0 { return None; } @@ -16976,13 +16982,14 @@ fn deblock_plane( // dependence is on ascending `x0` within a row, which stays the outer // loop's order, and rows remain independent (horizontal pass mirrored). let rows = plane.data.len() / stride.max(1); + let seg_lf_active = SEG.with(|s| s.borrow().enabled); let mut x0 = 4usize; while x0 < tw { let mut y0 = 0usize; while y0 < th { if y0 + 16 <= th && x0 >= 8 && x0 + 8 <= stride { let ps: [Option<(u8, i32)>; 4] = - std::array::from_fn(|k| edge_params(lf, n, plane_idx, 0, chroma, x0, y0 + 4 * k)); + std::array::from_fn(|k| edge_params(lf, n, plane_idx, 0, chroma, x0, y0 + 4 * k, seg_lf_active)); if let Some((len, level)) = ps[0] { if ps.iter().all(|p| *p == ps[0]) && filter_edge16( @@ -17015,7 +17022,7 @@ fn deblock_plane( y0 += 16; continue; } - if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) { + if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0, seg_lf_active) { if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 { eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}"); } @@ -17039,7 +17046,7 @@ fn deblock_plane( while x0 < tw { if x0 + 16 <= tw && y0 >= 8 && y0 + 7 <= rows { let ps: [Option<(u8, i32)>; 4] = - std::array::from_fn(|k| edge_params(lf, n, plane_idx, 1, chroma, x0 + 4 * k, y0)); + std::array::from_fn(|k| edge_params(lf, n, plane_idx, 1, chroma, x0 + 4 * k, y0, seg_lf_active)); if let Some((len, level)) = ps[0] { if ps.iter().all(|p| *p == ps[0]) && filter_edge16( @@ -17072,7 +17079,7 @@ fn deblock_plane( x0 += 16; continue; } - if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) { + if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0, seg_lf_active) { if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE") && plane_idx == 0 && x0 == 44 diff --git a/crates/ec-av1/src/film_grain.rs b/crates/ec-av1/src/film_grain.rs index 5a5470cb..72c89802 100644 --- a/crates/ec-av1/src/film_grain.rs +++ b/crates/ec-av1/src/film_grain.rs @@ -408,30 +408,25 @@ fn add_noise_to_block( let gcr = &cr_grain[grow..grow + cw]; let urow = &mut u_plane[crow..crow + cw]; let vrow = &mut v_plane[crow..crow + cw]; - for ((((lpair, u), v), &gb), &gr) in luma - .chunks_exact(2) - .zip(urow.iter_mut()) - .zip(vrow.iter_mut()) - .zip(gcb.iter()) - .zip(gcr.iter()) - { - let average_luma = (lpair[0] as i32 + lpair[1] as i32 + 1) >> 1; - if apply_cb { - let scaled = (((average_luma * cb_luma_mult + cb_mult * *u as i32) >> 6) - + cb_offset) - .clamp(0, index_max); - let delta = - (scaling_cb[scaled as usize] * gb + rounding_offset) >> scaling_shift; - *u = ((*u as i32 + delta).clamp(min_chroma, max_chroma)) as u16; - } - if apply_cr { - let scaled = (((average_luma * cr_luma_mult + cr_mult * *v as i32) >> 6) - + cr_offset) - .clamp(0, index_max); - let delta = - (scaling_cr[scaled as usize] * gr + rounding_offset) >> scaling_shift; - *v = ((*v as i32 + delta).clamp(min_chroma, max_chroma)) as u16; - } + // lane-perf9: one plane at a time, so the row is a straight + // vectorisable kernel (the per-sample `apply_cb`/`apply_cr` tests + // were loop-invariant anyway). + let params = ChromaNoise { + index_max, + rounding_offset, + scaling_shift, + min_chroma, + max_chroma, + }; + if apply_cb { + chroma_noise_row( + urow, luma, gcb, scaling_cb, cb_luma_mult, cb_mult, cb_offset, params, + ); + } + if apply_cr { + chroma_noise_row( + vrow, luma, gcr, scaling_cr, cr_luma_mult, cr_mult, cr_offset, params, + ); } } } @@ -482,6 +477,70 @@ fn luma_noise_row( ); } +/// The loop-invariant half of [`chroma_noise_row`]'s spec 7.18.3.5 arithmetic +/// (the same values for both chroma planes and every row of a block). +#[derive(Clone, Copy)] +struct ChromaNoise { + index_max: i32, + rounding_offset: i32, + scaling_shift: i32, + min_chroma: i32, + max_chroma: i32, +} + +/// One chroma row of spec 7.18.3.5's `add_noise_to_block`: `luma` is the +/// block's own luma row pair-averaged 4:2:0 (`luma.len() == 2 * +/// chroma.len()`), `grain` and `scaling` are the plane's own. +/// +/// lane-perf9: AVX2 does 8 chroma samples at a time, the luma pair sum being +/// one `vpmaddwd` against ones; every other CPU runs the scalar loop, which +/// stays the reference (`simd_matches_scalar_chroma_noise_row` pins the pair). +#[allow(unsafe_code)] +#[allow(clippy::too_many_arguments)] +fn chroma_noise_row( + chroma: &mut [u16], + luma: &[u16], + grain: &[i32], + scaling: &[i32], + luma_mult: i32, + mult: i32, + offset: i32, + p: ChromaNoise, +) { + #[cfg(target_arch = "x86_64")] + if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 { + // SAFETY: reached only when the CPU reports avx2; the kernel reads + // `luma[..2 * n]`/`grain[..n]` for `n` samples it writes, and gathers + // only in-range LUT entries. + unsafe { + simd::chroma_noise_row_avx2(chroma, luma, grain, scaling, luma_mult, mult, offset, p) + }; + return; + } + chroma_noise_row_scalar(chroma, luma, grain, scaling, luma_mult, mult, offset, p); +} + +/// The scalar reference for [`chroma_noise_row`]. +#[allow(clippy::too_many_arguments)] +fn chroma_noise_row_scalar( + chroma: &mut [u16], + luma: &[u16], + grain: &[i32], + scaling: &[i32], + luma_mult: i32, + mult: i32, + offset: i32, + p: ChromaNoise, +) { + for ((c, lpair), &g) in chroma.iter_mut().zip(luma.chunks_exact(2)).zip(grain) { + let average_luma = (lpair[0] as i32 + lpair[1] as i32 + 1) >> 1; + let scaled = + (((average_luma * luma_mult + mult * *c as i32) >> 6) + offset).clamp(0, p.index_max); + let delta = (scaling[scaled as usize] * g + p.rounding_offset) >> p.scaling_shift; + *c = ((*c as i32 + delta).clamp(p.min_chroma, p.max_chroma)) as u16; + } +} + /// The scalar reference for [`luma_noise_row`]. fn luma_noise_row_scalar( pixels: &mut [u16], @@ -559,6 +618,72 @@ mod simd { max_luma, ); } + + /// [`super::chroma_noise_row`]'s AVX2 kernel, 8 chroma samples per + /// iteration. `vpmaddwd` against a vector of ones is the 4:2:0 luma pair + /// sum (the 16 luma samples of the pairs are non-negative and below + /// `1 << 15` at every supported bit depth, so the signed multiply is + /// exact), and the LUT index is clamped exactly as the scalar form + /// clamps it. + /// + /// # Safety + /// Requires AVX2; `luma` must be at least `2 * chroma.len()` long, + /// `grain` at least `chroma.len()`, and `scaling` non-empty. + #[target_feature(enable = "avx2")] + #[allow(clippy::too_many_arguments)] + pub unsafe fn chroma_noise_row_avx2( + chroma: &mut [u16], + luma: &[u16], + grain: &[i32], + scaling: &[i32], + luma_mult: i32, + mult: i32, + offset: i32, + p: super::ChromaNoise, + ) { + let n = chroma.len().min(grain.len()).min(luma.len() / 2); + let ones = _mm256_set1_epi16(1); + let vluma_mult = _mm256_set1_epi32(luma_mult); + let vmult = _mm256_set1_epi32(mult); + let voffset = _mm256_set1_epi32(offset); + let vindex_max = _mm256_set1_epi32(p.index_max); + let last = _mm256_set1_epi32(scaling.len() as i32 - 1); + let zero = _mm256_setzero_si256(); + let rnd = _mm256_set1_epi32(p.rounding_offset); + let sh = _mm_cvtsi32_si128(p.scaling_shift); + let lo = _mm256_set1_epi32(p.min_chroma); + let hi = _mm256_set1_epi32(p.max_chroma); + let cp = chroma.as_mut_ptr(); + let lp = luma.as_ptr(); + let gp = grain.as_ptr(); + let mut c = 0usize; + while c + 8 <= n { + let l = _mm256_loadu_si256(lp.add(c * 2).cast()); + let pair_sum = _mm256_madd_epi16(l, ones); + let avg = _mm256_srai_epi32(_mm256_add_epi32(pair_sum, _mm256_set1_epi32(1)), 1); + let c16 = _mm_loadu_si128(cp.add(c).cast()); + let c32 = _mm256_cvtepu16_epi32(c16); + let mixed = _mm256_add_epi32( + _mm256_mullo_epi32(avg, vluma_mult), + _mm256_mullo_epi32(c32, vmult), + ); + let scaled = _mm256_add_epi32(_mm256_srai_epi32(mixed, 6), voffset); + let clamped = _mm256_max_epi32(_mm256_min_epi32(scaled, vindex_max), zero); + let idx = _mm256_min_epi32(clamped, last); + let s = _mm256_i32gather_epi32(scaling.as_ptr(), idx, 4); + let g = _mm256_loadu_si256(gp.add(c).cast()); + let delta = _mm256_sra_epi32(_mm256_add_epi32(_mm256_mullo_epi32(s, g), rnd), sh); + let v = _mm256_max_epi32(_mm256_min_epi32(_mm256_add_epi32(c32, delta), hi), lo); + // Same packing argument as the luma kernel: every lane already + // sits inside `[min_chroma, max_chroma]`. + let packed = _mm256_permute4x64_epi64(_mm256_packus_epi32(v, v), 0b0000_1000); + _mm_storeu_si128(cp.add(c).cast(), _mm256_castsi256_si128(packed)); + c += 8; + } + super::chroma_noise_row_scalar( + &mut chroma[c..], &luma[c * 2..], &grain[c..], scaling, luma_mult, mult, offset, p, + ); + } } /// `ver_boundary_overlap` (spec 7.18.3.5), in place on `dst` (== the C's @@ -1153,4 +1278,79 @@ mod perf5_tests { } assert_eq!(checked, 3 * 4 * 2 * 10); } + + /// [`super::chroma_noise_row`]'s AVX2 kernel against its scalar + /// reference, over the parameter ranges a real stream reaches: every + /// grain bit depth, both clip ranges, the `chroma_scaling_from_luma` + /// multipliers (0/64/0) and coded ones, and lengths either side of the + /// 8-sample vector step. + #[test] + fn simd_matches_scalar_chroma_noise_row() { + let mut state = 0x0f1e_2d3c_4b5a_6978u64; + let mut rng = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + let mut checked = 0usize; + for bd_shift in 0..3u32 { + let lut_len = 256usize << bd_shift; + let sample_max = (lut_len - 1) as u16; + let index_max = (lut_len - 1) as i32; + let scaling: Vec = (0..lut_len).map(|_| (rng() % 256) as i32).collect(); + for scaling_shift in [8i32, 11] { + for &(luma_mult, mult, offset) in &[ + (64i32, 0i32, 0i32), + (-128, 127, -(1 << (8 + bd_shift))), + (17, -64, 42), + ] { + for &(lo, hi) in + &[(0i32, index_max), (16 << bd_shift, 240 << bd_shift)] + { + for len in [1usize, 5, 8, 9, 16, 17, 32] { + let p = super::ChromaNoise { + index_max, + rounding_offset: 1i32 << (scaling_shift - 1), + scaling_shift, + min_chroma: lo, + max_chroma: hi, + }; + let chroma: Vec = (0..len) + .map(|_| (rng() % (u64::from(sample_max) + 1)) as u16) + .collect(); + let luma: Vec = (0..len * 2) + .map(|_| (rng() % (u64::from(sample_max) + 1)) as u16) + .collect(); + let grain: Vec = + (0..len).map(|_| (rng() % 513) as i32 - 256).collect(); + let mut want = chroma.clone(); + super::chroma_noise_row_scalar( + &mut want, &luma, &grain, &scaling, luma_mult, mult, offset, p, + ); + let mut got = chroma.clone(); + super::chroma_noise_row( + &mut got, &luma, &grain, &scaling, luma_mult, mult, offset, p, + ); + assert_eq!(got, want, "dispatch len={len} mult={mult}"); + #[cfg(target_arch = "x86_64")] + if std::arch::is_x86_feature_detected!("avx2") { + let mut avx = chroma.clone(); + #[allow(unsafe_code)] + unsafe { + super::simd::chroma_noise_row_avx2( + &mut avx, &luma, &grain, &scaling, luma_mult, mult, + offset, p, + ) + }; + assert_eq!(avx, want, "avx2 len={len} mult={mult}"); + } + checked += 1; + } + } + } + } + } + assert_eq!(checked, 3 * 2 * 3 * 2 * 7); + } } diff --git a/crates/ec-av1/src/restoration.rs b/crates/ec-av1/src/restoration.rs index bc357cfe..e7dd7dc6 100644 --- a/crates/ec-av1/src/restoration.rs +++ b/crates/ec-av1/src/restoration.rs @@ -751,30 +751,52 @@ fn compute_ab( let mut col_b = vec![0i64; ncols]; // Hoisted out of the per-point body: one thread-local read per call. let bd_shift = u32::from(crate::decode::bit_depth()).saturating_sub(8); + let base_col = h_start as i64 - 1 - r as i64; + // lane-perf9: the column sums slide down the grid too. Grid row `gi+1`'s + // window is row `gi`'s minus its top source row plus one new bottom row, + // so each source sample is read once per grid row instead of (2r+1) + // times -- the same exactness argument as the separable split above + // (i64 addition is associative, and subtracting a row that was added is + // exact), and `lr_sample`'s stripe-boundary test, which is what makes a + // sample read expensive, is a pure function of `(row, col)`. for gi in 0..gh { let i = gi as i64 - 1; - let base_col = h_start as i64 - 1 - r as i64; - for k in 0..ncols { - let col = base_col + k as i64; - let (mut ca, mut cb) = (0i64, 0i64); - for dr in -r..=r { - let row = v_start as i64 + i + dr as i64; - let px = lr_sample( - cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, col, - ) as i64; - ca += px * px; - cb += px; + { + let mut accumulate = |row: i64, sign: i64| { + for k in 0..ncols { + let px = lr_sample( + cdef, + deblocked, + stride, + plane_w, + plane_h, + v_start, + v_end, + row, + base_col + k as i64, + ) as i64; + col_a[k] += sign * px * px; + col_b[k] += sign * px; + } + }; + if gi == 0 { + for dr in -r..=r { + accumulate(v_start as i64 + i + dr as i64, 1); + } + } else { + accumulate(v_start as i64 + i - 1 - r as i64, -1); + accumulate(v_start as i64 + i + r as i64, 1); } - col_a[k] = ca; - col_b[k] = cb; } + // The horizontal sum slides the same way (one add and one subtract + // per grid point instead of 2r+1 adds). + let mut a = col_a[..2 * ru + 1].iter().sum::(); + let mut b = col_b[..2 * ru + 1].iter().sum::(); for gj in 0..gw { let j = gj as i64 - 1; - let mut a = 0i64; - let mut b = 0i64; - for k in gj..gj + 2 * ru + 1 { - a += col_a[k]; - b += col_b[k]; + if gj > 0 { + a += col_a[gj + 2 * ru] - col_a[gj - 1]; + b += col_b[gj + 2 * ru] - col_b[gj - 1]; } // libaom `restoration.c:660` -- the box sums are brought back // to the 8-bit scale before `p` is formed (`a` is a sum of