forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

cdef.rs390 lines, 15.3 KiBHistoryRawDownload
1//! CDEF constants and filter kernels. //! av1split: moved out of `decode/mod.rs`; the items are unchanged apart from visibility. (D14)
2
3use archmage::SimdToken;
4use super::*;
5
6/// Spec 7.15.3's `Cdef_Directions`: `(row, col)` offsets for the two primary
7/// taps of each of the eight directions; the secondary taps at `dir+2`/`dir-2`
8/// (mod 8) reuse the same table.
9pub(super) const CDEF_DIRECTIONS: [[(i32, i32); 2]; 8] = [
10 [(-1, 1), (-2, 2)],
11 [(0, 1), (-1, 2)],
12 [(0, 1), (0, 2)],
13 [(0, 1), (1, 2)],
14 [(1, 1), (2, 2)],
15 [(1, 0), (2, 1)],
16 [(1, 0), (2, 0)],
17 [(1, 0), (2, -1)],
18];
19/// A neighbour tap outside the frame's true extent -- `constrain` reads this
20/// as "so far away it never contributes" (spec/libaom `CDEF_VERY_LARGE`).
21pub(super) const CDEF_VERY_LARGE: i32 = 0x4000;
22pub(super) const CDEF_PRI_TAPS: [[i32; 2]; 2] = [[4, 2], [3, 3]];
23pub(super) const CDEF_SEC_TAPS: [i32; 2] = [2, 1];
24/// lane-av1422filter: libaom `av1_cdef_filter_fb` (cdef_block.c) remaps the
25/// luma direction before filtering CHROMA whenever `xdec != ydec` — the
26/// direction grid lives on the subsampled chroma grid, so a direction found
27/// on the 8x8 luma block means a different line there. `conv422` applies
28/// under 4:2:2 (`xdec` set), `conv440` under its mirror (not expressible in
29/// the profiles this decoder accepts, kept for fidelity). 4:2:0 and 4:4:4
30/// (`xdec == ydec`) take no remap, exactly as before this lane.
31pub(super) const CDEF_DIR_CONV422: [usize; 8] = [7, 0, 2, 4, 5, 6, 6, 6];
32pub(super) const CDEF_DIR_CONV440: [usize; 8] = [1, 2, 2, 2, 3, 4, 6, 0];
33
34fn cdef_msb(x: i32) -> i32 {
35 31 - x.leading_zeros() as i32
36}
37
38/// Spec 7.15.3's `constrain`: how much of a neighbour's difference from the
39/// centre sample a filter tap is allowed to contribute.
40#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
41pub(super) fn cdef_constrain(diff: i32, threshold: i32, damping: i32) -> i32 {
42 if threshold == 0 {
43 return 0;
44 }
45 cdef_constrain_shifted(diff, threshold, cdef_constrain_shift(threshold, damping))
46}
47
48/// `constrain`'s damping shift: a function of the block's threshold and
49/// damping alone, so the filter loop computes it once per block instead of
50/// the `leading_zeros` + branch it used to do twice per tap read.
51pub(super) fn cdef_constrain_shift(threshold: i32, damping: i32) -> i32 {
52 (damping - cdef_msb(threshold)).max(0)
53}
54
55/// [`cdef_constrain`]'s body with the shift already resolved; `threshold` is
56/// non-zero on every call (the caller only filters when its strength is).
57pub(super) fn cdef_constrain_shifted(diff: i32, threshold: i32, shift: i32) -> i32 {
58 let a = diff.abs();
59 diff.signum() * (threshold - (a >> shift)).clamp(0, a)
60}
61
62/// The widest `CDEF_DIRECTIONS` offset in either axis: every tap a block reads
63/// lies inside its own samples grown by this much.
64pub(super) const CDEF_BORDER: usize = 2;
65
66/// Copies one block's whole CDEF footprint -- its `bh` x `bw` samples plus the
67/// [`CDEF_BORDER`] tap ring -- out of the *unfiltered* plane into `buf` (row
68/// stride `bw + 2 * CDEF_BORDER`), so the direction search and the tap loops
69/// index a small contiguous window instead of re-deriving the frame-bounds
70/// test on every one of a pixel's ~17 tap reads. Out-of-frame positions get
71/// `CDEF_VERY_LARGE`, exactly as the per-sample closure did.
72// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
73#[allow(clippy::too_many_arguments)]
74pub(super) fn cdef_gather(
75 src: &[u16],
76 stride: usize,
77 true_w: usize,
78 true_h: usize,
79 ox: usize,
80 oy: usize,
81 bw: usize,
82 bh: usize,
83 buf: &mut [i16],
84) {
85 let bstride = bw + 2 * CDEF_BORDER;
86 let rows = bh + 2 * CDEF_BORDER;
87 if oy >= CDEF_BORDER
88 && ox >= CDEF_BORDER
89 && oy + bh + CDEF_BORDER <= true_h
90 && ox + bw + CDEF_BORDER <= true_w
91 {
92 // Interior block: every tap is inside the frame, so the whole window
93 // is `rows` contiguous runs.
94 for r in 0..rows {
95 let s0 = (oy - CDEF_BORDER + r) * stride + (ox - CDEF_BORDER);
96 let src_row = &src[s0..s0 + bstride];
97 let dst_row = &mut buf[r * bstride..r * bstride + bstride];
98 for (d, &v) in dst_row.iter_mut().zip(src_row) {
99 *d = v as i16;
100 }
101 }
102 return;
103 }
104 for r in 0..rows {
105 let ny = oy as isize + r as isize - CDEF_BORDER as isize;
106 for c in 0..bstride {
107 let nx = ox as isize + c as isize - CDEF_BORDER as isize;
108 buf[r * bstride + c] =
109 if ny < 0 || nx < 0 || ny as usize >= true_h || nx as usize >= true_w {
110 CDEF_VERY_LARGE as i16
111 } else {
112 src[ny as usize * stride + nx as usize] as i16
113 };
114 }
115 }
116}
117
118/// libaom `cdef_find_dir_c`'s eight partial-sum arrays, row at a time: each
119/// array takes the row, its reverse, its pairwise sums or its total added
120/// into consecutive slots, so the 512 scalar read-modify-writes on i64 the
121/// per-sample form did become a handful of lane-wide adds per row. i32 is
122/// exact here: every partial is a sum of at most eight values in -128..127,
123/// and slot 15 exists only so an eight-lane store at offset 7 fits.
124pub(super) fn cdef_find_dir_partials(win: &[i16], bstride: usize, coeff_shift: i32) -> [[i32; 16]; 8] {
125 fn add_at<const N: usize>(dst: &mut [i32; 16], off: usize, src: &[i32; N]) {
126 for (d, &x) in dst[off..off + N].iter_mut().zip(src.iter()) {
127 *d += x;
128 }
129 }
130 let mut partial = [[0i32; 16]; 8];
131 for i in 0..8usize {
132 let base = (i + CDEF_BORDER) * bstride + CDEF_BORDER;
133 // libaom `cdef_find_dir_c`: normalise to an 8-bit sample before
134 // accumulating, same as `constrain`'s threshold shift.
135 let row: [i32; 8] =
136 core::array::from_fn(|j| (i32::from(win[base + j]) >> coeff_shift) - 128);
137 let rev: [i32; 8] = core::array::from_fn(|j| row[7 - j]);
138 let pair: [i32; 4] = core::array::from_fn(|k| row[2 * k] + row[2 * k + 1]);
139 let rpair: [i32; 4] = core::array::from_fn(|k| pair[3 - k]);
140 let (p, rest) = partial.split_at_mut(1);
141 add_at(&mut p[0], i, &row); // partial[0][i + j]
142 add_at(&mut rest[0], i, &pair); // partial[1][i + j / 2]
143 rest[1][i] = row.iter().sum(); // partial[2][i]
144 add_at(&mut rest[2], i, &rpair); // partial[3][3 + i - j / 2]
145 add_at(&mut rest[3], i, &rev); // partial[4][7 + i - j]
146 add_at(&mut rest[4], 3 - i / 2, &row); // partial[5][3 - i / 2 + j]
147 add_at(&mut rest[5], 0, &row); // partial[6][j]
148 add_at(&mut rest[6], i / 2, &row); // partial[7][i / 2 + j]
149 }
150 partial
151}
152
153/// Spec 7.15.3's direction search (libaom `cdef_find_dir_c`): the dominant
154/// direction of an 8x8 luma window and the variance gap between it and its
155/// orthogonal, reading [`cdef_gather`]'s window (row stride `bstride`, the
156/// block's own samples starting at `CDEF_BORDER, CDEF_BORDER`).
157/// Runtime dispatch of the direction search's partial sums: the AVX2 clone
158/// runs [`cdef_simd::find_dir_partials_avx2`], the baseline clone the scalar
159/// form. Both read the same eight rows of eight samples.
160pub(super) fn cdef_find_dir_partials_dispatch(win: &[i16], bstride: usize, coeff_shift: i32) -> [[i32; 16]; 8] {
161 if let Some(t) = archmage::X64V3Token::summon() {
162 return cdef_simd::find_dir_partials_avx2(t, win, bstride, coeff_shift);
163 }
164 cdef_find_dir_partials(win, bstride, coeff_shift)
165}
166
167pub(super) fn cdef_find_dir(win: &[i16], bstride: usize, coeff_shift: i32) -> (usize, i32) {
168 const DIV_TABLE: [i64; 9] = [0, 840, 420, 280, 210, 168, 140, 120, 105];
169 let partial = cdef_find_dir_partials_dispatch(win, bstride, coeff_shift);
170 let sq = |a: i32| -> i64 { i64::from(a) * i64::from(a) };
171 let mut cost = [0i64; 8];
172 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
173 #[allow(clippy::needless_range_loop)]
174 for i in 0..8usize {
175 cost[2] += sq(partial[2][i]);
176 cost[6] += sq(partial[6][i]);
177 }
178 cost[2] *= DIV_TABLE[8];
179 cost[6] *= DIV_TABLE[8];
180 for i in 0..7usize {
181 cost[0] += (sq(partial[0][i]) + sq(partial[0][14 - i])) * DIV_TABLE[i + 1];
182 cost[4] += (sq(partial[4][i]) + sq(partial[4][14 - i])) * DIV_TABLE[i + 1];
183 }
184 cost[0] += sq(partial[0][7]) * DIV_TABLE[8];
185 cost[4] += sq(partial[4][7]) * DIV_TABLE[8];
186 for i in (1..8).step_by(2) {
187 for j in 0..5usize {
188 cost[i] += sq(partial[i][3 + j]);
189 }
190 cost[i] *= DIV_TABLE[8];
191 for j in 0..3usize {
192 cost[i] += (sq(partial[i][j]) + sq(partial[i][10 - j])) * DIV_TABLE[2 * j + 2];
193 }
194 }
195 let mut best_cost = 0i64;
196 let mut best_dir = 0usize;
197 for (i, &c) in cost.iter().enumerate() {
198 if c > best_cost {
199 best_cost = c;
200 best_dir = i;
201 }
202 }
203 let var = (best_cost - cost[(best_dir + 4) & 7]) >> 10;
204 (best_dir, var as i32)
205}
206
207/// Spec 7.15.2's per-8x8 strength adjustment: a strongly directional 8x8
208/// (high variance gap) gets more deringing than a flat or non-directional
209/// one, only ever applied to the luma primary strength.
210pub(super) fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
211 if var == 0 {
212 return 0;
213 }
214 let i = if var >> 6 != 0 {
215 cdef_msb(var >> 6).min(12)
216 } else {
217 0
218 };
219 (strength * (4 + i) + 8) >> 4
220}
221
222/// Spec 7.15.3's `cdef_filter_block`: filters one block (8x8 luma, 4x4 4:2:0
223/// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
224/// previously-filtered neighbour must never feed this block's own sum).
225#[allow(clippy::too_many_arguments)]
226pub(super) fn cdef_filter_block(
227 src: &[i16],
228 dst: &mut [u16],
229 stride: usize,
230 ox: usize,
231 oy: usize,
232 bw: usize,
233 bh: usize,
234 pri_strength: i32,
235 sec_strength: i32,
236 dir: usize,
237 pri_damping: i32,
238 sec_damping: i32,
239 enable_primary: bool,
240 enable_secondary: bool,
241 coeff_shift: i32,
242 fctx: &crate::decode::FrameCtx,
243) {
244 let smax = sample_max(fctx);
245 if let Some(t) = archmage::X64V3Token::summon() {
246 if (bw == 4 || bw == 8) && bh.is_multiple_of(2) {
247 // The kernel reads `src`'s whole (bw + 4) x (bh + 4) window
248 // and writes exactly the `bh` runs of `bw` samples the
249 // scalar form writes.
250 cdef_simd::filter_block_avx2(
251 t,
252 src,
253 dst,
254 stride,
255 ox,
256 oy,
257 bw,
258 bh,
259 pri_strength,
260 sec_strength,
261 dir,
262 pri_damping,
263 sec_damping,
264 enable_primary,
265 enable_secondary,
266 coeff_shift,
267 smax,
268 );
269 return;
270 }
271 }
272 cdef_filter_block_scalar(
273 src,
274 dst,
275 stride,
276 ox,
277 oy,
278 bw,
279 bh,
280 pri_strength,
281 sec_strength,
282 dir,
283 pri_damping,
284 sec_damping,
285 enable_primary,
286 enable_secondary,
287 coeff_shift,
288 smax,
289 );
290}
291
292/// [`cdef_filter_block`]'s scalar reference: spec 7.15.3 sample by sample,
293/// the form every non-AVX2 build decodes through and the one
294/// `cdef_simd_kernel_matches_the_scalar_filter` checks the kernel against.
295#[allow(clippy::too_many_arguments)]
296pub(super) fn cdef_filter_block_scalar(
297 src: &[i16],
298 dst: &mut [u16],
299 stride: usize,
300 ox: usize,
301 oy: usize,
302 bw: usize,
303 bh: usize,
304 pri_strength: i32,
305 sec_strength: i32,
306 dir: usize,
307 pri_damping: i32,
308 sec_damping: i32,
309 enable_primary: bool,
310 enable_secondary: bool,
311 coeff_shift: i32,
312 smax: i32,
313) {
314 let clipping_required = enable_primary && enable_secondary;
315 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
316 // coeff_shift) & 1]` -- `pri_strength` (and its `adjust_strength`
317 // derivative) carries the bit-depth shift, so the tap-set parity bit
318 // must be read back above that shift, not off the raw low bit.
319 let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
320 // Both damping shifts depend only on this block's strengths (spec 7.15.3's
321 // `constrain`), so they are resolved here rather than per tap read.
322 let pri_shift = cdef_constrain_shift(pri_strength.max(1), pri_damping);
323 let sec_shift = cdef_constrain_shift(sec_strength.max(1), sec_damping);
324 let bstride = bw + 2 * CDEF_BORDER;
325 // `src` is [`cdef_gather`]'s window: (i, j) in block coordinates, taps
326 // reaching +-CDEF_BORDER, so every index below is in range by construction.
327 let at = |i: i32, j: i32| -> i32 {
328 i32::from(
329 src[(i + CDEF_BORDER as i32) as usize * bstride + (j + CDEF_BORDER as i32) as usize],
330 )
331 };
332 let (pri_dir, sec_dir0, sec_dir1) = (
333 CDEF_DIRECTIONS[dir],
334 CDEF_DIRECTIONS[(dir + 2) & 7],
335 CDEF_DIRECTIONS[(dir + 6) & 7],
336 );
337 for i in 0..bh {
338 for j in 0..bw {
339 let (i32i, i32j) = (i as i32, j as i32);
340 let x = at(i32i, i32j);
341 let mut sum = 0i32;
342 let mut max = x;
343 let mut min = x;
344 for k in 0..2usize {
345 if enable_primary {
346 let (tr, tc) = pri_dir[k];
347 let p0 = at(i32i + tr, i32j + tc);
348 let p1 = at(i32i - tr, i32j - tc);
349 sum += pri_taps[k] * cdef_constrain_shifted(p0 - x, pri_strength, pri_shift);
350 sum += pri_taps[k] * cdef_constrain_shifted(p1 - x, pri_strength, pri_shift);
351 if clipping_required {
352 if p0 != CDEF_VERY_LARGE {
353 max = max.max(p0);
354 }
355 if p1 != CDEF_VERY_LARGE {
356 max = max.max(p1);
357 }
358 min = min.min(p0).min(p1);
359 }
360 }
361 if enable_secondary {
362 let (tr0, tc0) = sec_dir0[k];
363 let (tr1, tc1) = sec_dir1[k];
364 let s0 = at(i32i + tr0, i32j + tc0);
365 let s1 = at(i32i - tr0, i32j - tc0);
366 let s2 = at(i32i + tr1, i32j + tc1);
367 let s3 = at(i32i - tr1, i32j - tc1);
368 if clipping_required {
369 for s in [s0, s1, s2, s3] {
370 if s != CDEF_VERY_LARGE {
371 max = max.max(s);
372 }
373 }
374 min = min.min(s0).min(s1).min(s2).min(s3);
375 }
376 sum += CDEF_SEC_TAPS[k]
377 * (cdef_constrain_shifted(s0 - x, sec_strength, sec_shift)
378 + cdef_constrain_shifted(s1 - x, sec_strength, sec_shift)
379 + cdef_constrain_shifted(s2 - x, sec_strength, sec_shift)
380 + cdef_constrain_shifted(s3 - x, sec_strength, sec_shift));
381 }
382 }
383 let mut y = x + ((8 + sum - i32::from(sum < 0)) >> 4);
384 if clipping_required {
385 y = y.clamp(min, max);
386 }
387 dst[(oy + i) * stride + (ox + j)] = y.clamp(0, smax) as u16;
388 }
389 }
390}