forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

deblock.rs1043 lines, 40.9 KiBHistoryRawDownload
1//! Deblocking filters: the edge filters, the deblock plane drivers, the filter-replay capture and the pooled plane scratch. Moved out of `decode/mod.rs` (av1split D12); the items are unchanged apart from visibility.
2
3use archmage::SimdToken;
4use super::*;
5
6/// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
7fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
8 let sharpness = i32::from(sharpness);
9 let shift = i32::from(sharpness > 0) + i32::from(sharpness > 4);
10 let mut lim = level >> shift;
11 if sharpness > 0 {
12 lim = lim.min(9 - sharpness);
13 }
14 lim = lim.max(1);
15 (2 * (level + 2) + lim, lim, level >> 4)
16}
17
18#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
19pub(super) fn sclamp(v: i32, fctx: &crate::decode::FrameCtx) -> i32 {
20 // libaom's `signed_char_clamp_high`: the clamp range scales with
21 // `128 << (bit_depth - 8)` alongside the centering constant below.
22 let scale = 1i32 << (bit_depth(fctx) - 8);
23 v.clamp(-128 * scale, 128 * scale - 1)
24}
25
26fn round_pow2(v: i32, n: u32) -> i32 {
27 (v + (1 << (n - 1))) >> n
28}
29
30/// `filter4`: the narrow 4-tap kernel, and every wider kernel's non-flat
31/// fallback.
32pub(super) fn filter4(
33 mask: bool,
34 thresh: i32,
35 p1: i32,
36 p0: i32,
37 q0: i32,
38 q1: i32,
39 fctx: &crate::decode::FrameCtx,
40) -> [i32; 4] {
41 if !mask {
42 return [p1, p0, q0, q1];
43 }
44 let hev = (p1 - p0).abs() > thresh || (q1 - q0).abs() > thresh;
45 // lane-perf6: `sclamp` re-read the thread-local bit depth on every one of
46 // this kernel's eight clamps, and this kernel runs per deblocked sample.
47 // Same bound, resolved once.
48 let scale = 1i32 << (bit_depth(fctx) - 8);
49 let sclamp = |v: i32| v.clamp(-128 * scale, 128 * scale - 1);
50 let centre = 128i32 * scale;
51 let (ps1, ps0, qs0, qs1) = (p1 - centre, p0 - centre, q0 - centre, q1 - centre);
52 let outer = if hev { sclamp(ps1 - qs1) } else { 0 };
53 let filter = sclamp(outer + 3 * (qs0 - ps0));
54 let filter1 = sclamp(filter + 4) >> 3;
55 let filter2 = sclamp(filter + 3) >> 3;
56 let oq0 = sclamp(qs0 - filter1) + centre;
57 let op0 = sclamp(ps0 + filter2) + centre;
58 let tap = if hev { 0 } else { round_pow2(filter1, 1) };
59 let oq1 = sclamp(qs1 - tap) + centre;
60 let op1 = sclamp(ps1 + tap) + centre;
61 [op1, op0, oq0, oq1]
62}
63
64/// `filter6`: chroma's flat 5-tap smoothing (spec `[1,2,2,2,1]`) over
65/// `filter4`'s narrow taps.
66#[allow(clippy::too_many_arguments)]
67pub(super) fn filter6(
68 mask: bool,
69 thresh: i32,
70 flat: bool,
71 p2: i32,
72 p1: i32,
73 p0: i32,
74 q0: i32,
75 q1: i32,
76 q2: i32,
77 fctx: &crate::decode::FrameCtx,
78) -> [i32; 4] {
79 if flat && mask {
80 [
81 round_pow2(p2 * 3 + p1 * 2 + p0 * 2 + q0, 3),
82 round_pow2(p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1, 3),
83 round_pow2(p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2, 3),
84 round_pow2(p0 + q0 * 2 + q1 * 2 + q2 * 3, 3),
85 ]
86 } else {
87 filter4(mask, thresh, p1, p0, q0, q1, fctx)
88 }
89}
90
91/// `filter8`: luma's flat 7-tap smoothing (spec `[1,1,1,2,1,1,1]`).
92#[allow(clippy::too_many_arguments)]
93pub(super) fn filter8(
94 mask: bool,
95 thresh: i32,
96 flat: bool,
97 p3: i32,
98 p2: i32,
99 p1: i32,
100 p0: i32,
101 q0: i32,
102 q1: i32,
103 q2: i32,
104 q3: i32,
105 fctx: &crate::decode::FrameCtx,
106) -> [i32; 6] {
107 if flat && mask {
108 [
109 round_pow2(p3 + p3 + p3 + 2 * p2 + p1 + p0 + q0, 3),
110 round_pow2(p3 + p3 + p2 + 2 * p1 + p0 + q0 + q1, 3),
111 round_pow2(p3 + p2 + p1 + 2 * p0 + q0 + q1 + q2, 3),
112 round_pow2(p2 + p1 + p0 + 2 * q0 + q1 + q2 + q3, 3),
113 round_pow2(p1 + p0 + q0 + 2 * q1 + q2 + q3 + q3, 3),
114 round_pow2(p0 + q0 + q1 + 2 * q2 + q3 + q3 + q3, 3),
115 ]
116 } else {
117 let [op1, op0, oq0, oq1] = filter4(mask, thresh, p1, p0, q0, q1, fctx);
118 [p2, op1, op0, oq0, oq1, q2]
119 }
120}
121
122/// `filter14`: the wide 13-tap smoothing used at 16x16-and-larger transform
123/// edges; falls back to [`filter8`] (leaving `op6`/`oq6` untouched either
124/// way -- they are only ever taps here, never written).
125#[allow(clippy::too_many_arguments)]
126pub(super) fn filter14(
127 mask: bool,
128 thresh: i32,
129 flat: bool,
130 flat2: bool,
131 p6: i32,
132 p5: i32,
133 p4: i32,
134 p3: i32,
135 p2: i32,
136 p1: i32,
137 p0: i32,
138 q0: i32,
139 q1: i32,
140 q2: i32,
141 q3: i32,
142 q4: i32,
143 q5: i32,
144 q6: i32,
145 fctx: &crate::decode::FrameCtx,
146) -> [i32; 12] {
147 if flat2 && flat && mask {
148 [
149 round_pow2(p6 * 7 + p5 * 2 + p4 * 2 + p3 + p2 + p1 + p0 + q0, 4),
150 round_pow2(
151 p6 * 5 + p5 * 2 + p4 * 2 + p3 * 2 + p2 + p1 + p0 + q0 + q1,
152 4,
153 ),
154 round_pow2(
155 p6 * 4 + p5 + p4 * 2 + p3 * 2 + p2 * 2 + p1 + p0 + q0 + q1 + q2,
156 4,
157 ),
158 round_pow2(
159 p6 * 3 + p5 + p4 + p3 * 2 + p2 * 2 + p1 * 2 + p0 + q0 + q1 + q2 + q3,
160 4,
161 ),
162 round_pow2(
163 p6 * 2 + p5 + p4 + p3 + p2 * 2 + p1 * 2 + p0 * 2 + q0 + q1 + q2 + q3 + q4,
164 4,
165 ),
166 round_pow2(
167 p6 + p5 + p4 + p3 + p2 + p1 * 2 + p0 * 2 + q0 * 2 + q1 + q2 + q3 + q4 + q5,
168 4,
169 ),
170 round_pow2(
171 p5 + p4 + p3 + p2 + p1 + p0 * 2 + q0 * 2 + q1 * 2 + q2 + q3 + q4 + q5 + q6,
172 4,
173 ),
174 round_pow2(
175 p4 + p3 + p2 + p1 + p0 + q0 * 2 + q1 * 2 + q2 * 2 + q3 + q4 + q5 + q6 * 2,
176 4,
177 ),
178 round_pow2(
179 p3 + p2 + p1 + p0 + q0 + q1 * 2 + q2 * 2 + q3 * 2 + q4 + q5 + q6 * 3,
180 4,
181 ),
182 round_pow2(
183 p2 + p1 + p0 + q0 + q1 + q2 * 2 + q3 * 2 + q4 * 2 + q5 + q6 * 4,
184 4,
185 ),
186 round_pow2(
187 p1 + p0 + q0 + q1 + q2 + q3 * 2 + q4 * 2 + q5 * 2 + q6 * 5,
188 4,
189 ),
190 round_pow2(p0 + q0 + q1 + q2 + q3 + q4 * 2 + q5 * 2 + q6 * 7, 4),
191 ]
192 } else {
193 let [op2, op1, op0, oq0, oq1, oq2] =
194 filter8(mask, thresh, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
195 [p5, p4, p3, op2, op1, op0, oq0, oq1, oq2, q3, q4, q5]
196 }
197}
198
199/// Filters one 4-pixel edge group: `base` is the plane-local byte offset of
200/// the first (`q0`) sample past the edge, `outer_stride` advances to the
201/// next of the 4 perpendicular samples, `tap_stride` steps from one tap to
202/// the next along the edge's own filtering direction.
203#[allow(clippy::too_many_arguments)]
204pub(super) fn filter_edge(
205 data: &mut [u16],
206 base: usize,
207 outer_stride: isize,
208 tap_stride: isize,
209 len: u8,
210 level: i32,
211 sharpness: u8,
212 fctx: &crate::decode::FrameCtx,
213) {
214 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
215 // libaom `highbd_filter_mask*`/`highbd_flat_mask4`/`highbd_hev_mask`:
216 // every 8-bit threshold (including the flat masks' fixed `1`) is
217 // compared against a raw pixel difference on the stream's own bit-depth
218 // scale, so each is shifted left by `bit_depth - 8` before use.
219 let shift = bit_depth(fctx) - 8;
220 let (blimit, limit, hev_thr) = (blimit << shift, limit << shift, hev_thr << shift);
221 let flat_thresh = 1i32 << shift;
222 let smax = sample_max(fctx);
223 for i in 0..4isize {
224 let center = (base as isize + i * outer_stride) as usize;
225 let idx = |k: isize| -> usize { (center as isize + k * tap_stride) as usize };
226 let px = |k: isize| -> i32 { i32::from(data[idx(k)]) };
227 match len {
228 4 => {
229 let (p1, p0, q0, q1) = (px(-2), px(-1), px(0), px(1));
230 let mask = (p1 - p0).abs() <= limit
231 && (q1 - q0).abs() <= limit
232 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
233 let [op1, op0, oq0, oq1] = filter4(mask, hev_thr, p1, p0, q0, q1, fctx);
234 data[idx(-2)] = op1.clamp(0, smax) as u16;
235 data[idx(-1)] = op0.clamp(0, smax) as u16;
236 data[idx(0)] = oq0.clamp(0, smax) as u16;
237 data[idx(1)] = oq1.clamp(0, smax) as u16;
238 }
239 6 => {
240 let (p2, p1, p0, q0, q1, q2) = (px(-3), px(-2), px(-1), px(0), px(1), px(2));
241 let mask = (p2 - p1).abs() <= limit
242 && (p1 - p0).abs() <= limit
243 && (q1 - q0).abs() <= limit
244 && (q2 - q1).abs() <= limit
245 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
246 let flat = (p1 - p0).abs() <= flat_thresh
247 && (q1 - q0).abs() <= flat_thresh
248 && (p2 - p0).abs() <= flat_thresh
249 && (q2 - q0).abs() <= flat_thresh;
250 let [op1, op0, oq0, oq1] =
251 filter6(mask, hev_thr, flat, p2, p1, p0, q0, q1, q2, fctx);
252 data[idx(-2)] = op1.clamp(0, smax) as u16;
253 data[idx(-1)] = op0.clamp(0, smax) as u16;
254 data[idx(0)] = oq0.clamp(0, smax) as u16;
255 data[idx(1)] = oq1.clamp(0, smax) as u16;
256 }
257 8 => {
258 let (p3, p2, p1, p0, q0, q1, q2, q3) =
259 (px(-4), px(-3), px(-2), px(-1), px(0), px(1), px(2), px(3));
260 let mask = (p3 - p2).abs() <= limit
261 && (p2 - p1).abs() <= limit
262 && (p1 - p0).abs() <= limit
263 && (q1 - q0).abs() <= limit
264 && (q2 - q1).abs() <= limit
265 && (q3 - q2).abs() <= limit
266 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
267 let flat = (p1 - p0).abs() <= flat_thresh
268 && (q1 - q0).abs() <= flat_thresh
269 && (p2 - p0).abs() <= flat_thresh
270 && (q2 - q0).abs() <= flat_thresh
271 && (p3 - p0).abs() <= flat_thresh
272 && (q3 - q0).abs() <= flat_thresh;
273 let [op2, op1, op0, oq0, oq1, oq2] =
274 filter8(mask, hev_thr, flat, p3, p2, p1, p0, q0, q1, q2, q3, fctx);
275 data[idx(-3)] = op2.clamp(0, smax) as u16;
276 data[idx(-2)] = op1.clamp(0, smax) as u16;
277 data[idx(-1)] = op0.clamp(0, smax) as u16;
278 data[idx(0)] = oq0.clamp(0, smax) as u16;
279 data[idx(1)] = oq1.clamp(0, smax) as u16;
280 data[idx(2)] = oq2.clamp(0, smax) as u16;
281 }
282 _ => {
283 let (p6, p5, p4, p3, p2, p1, p0) =
284 (px(-7), px(-6), px(-5), px(-4), px(-3), px(-2), px(-1));
285 let (q0, q1, q2, q3, q4, q5, q6) =
286 (px(0), px(1), px(2), px(3), px(4), px(5), px(6));
287 let mask = (p3 - p2).abs() <= limit
288 && (p2 - p1).abs() <= limit
289 && (p1 - p0).abs() <= limit
290 && (q1 - q0).abs() <= limit
291 && (q2 - q1).abs() <= limit
292 && (q3 - q2).abs() <= limit
293 && (p0 - q0).abs() * 2 + (p1 - q1).abs() / 2 <= blimit;
294 let flat = (p1 - p0).abs() <= flat_thresh
295 && (q1 - q0).abs() <= flat_thresh
296 && (p2 - p0).abs() <= flat_thresh
297 && (q2 - q0).abs() <= flat_thresh
298 && (p3 - p0).abs() <= flat_thresh
299 && (q3 - q0).abs() <= flat_thresh;
300 let flat2 = (p4 - p0).abs() <= flat_thresh
301 && (q4 - q0).abs() <= flat_thresh
302 && (p5 - p0).abs() <= flat_thresh
303 && (q5 - q0).abs() <= flat_thresh
304 && (p6 - p0).abs() <= flat_thresh
305 && (q6 - q0).abs() <= flat_thresh;
306 let out = filter14(
307 mask, hev_thr, flat, flat2, p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5,
308 q6, fctx,
309 );
310 for (k, v) in (-6..=5isize).zip(out) {
311 data[idx(k)] = v.clamp(0, smax) as u16;
312 }
313 }
314 }
315 }
316}
317
318/// lane-perf8: [`filter_edge`]'s AVX2 kernel -- the scalar loop was 8.0% of a
319/// 4K decode's self time, spent almost entirely on the per-tap strided
320/// addressing (`perf annotate`'s hot lines are `leaq`/`movzwl` pairs, not the
321/// arithmetic). Nothing here is spec logic: the same masks, the same
322/// `filter4`/`filter6`/`filter8`/`filter14` weighted sums and the same
323/// rounding, done for 16 edge lines at once.
324///
325/// 16-bit lanes are exact for every value these filters see. Samples are in
326/// `[0, 4095]`, so a difference and the `blimit` term (`2 * |p0 - q0| +
327/// |p1 - q1| / 2 <= 10237`) fit `i16`; `filter4` works in the centred domain
328/// where every intermediate is clamped to `+-128 << (bit_depth - 8)`; and the
329/// wide kernels' weights each total 8 or 16, so their sums (at most
330/// `16 * 4095 + 8 = 65528`) fit `u16` -- hence `_mm256_srli_epi16` for their
331/// rounding shift, which is the unsigned shift the scalar's non-negative sum
332/// takes.
333/// [`filter_edge`] for 16 adjacent edge lines that share `edge_params`'
334/// output. Returns `false` when this build or CPU has no kernel, leaving the
335/// caller on the scalar path.
336#[allow(unused_variables)]
337// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
338#[allow(clippy::too_many_arguments)]
339pub(super) fn filter_edge16(
340 data: &mut [u16],
341 base: usize,
342 stride: usize,
343 vertical: bool,
344 len: u8,
345 level: i32,
346 sharpness: u8,
347 fctx: &crate::decode::FrameCtx,
348) -> bool {
349 let Some(t) = archmage::X64V3Token::summon() else {
350 return false;
351 };
352 let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
353 let shift = bit_depth(fctx) - 8;
354 deblock_simd::edge16(
355 t,
356 data,
357 base,
358 stride,
359 vertical,
360 len,
361 blimit << shift,
362 limit << shift,
363 hev_thr << shift,
364 1 << shift,
365 1 << shift,
366 sample_max(fctx),
367 );
368 true
369}
370
371/// One plane's worth of spec 7.14: every vertical edge across the plane,
372/// then every horizontal edge (the order the spec and libaom both use).
373pub(super) fn deblock_plane(
374 plane: &mut PlaneBuf<'static>,
375 plane_idx: usize,
376 lf: &LoopFilterParams,
377 n: &Neighbours,
378 frame_width: usize,
379 frame_height: usize,
380 fctx: &crate::decode::FrameCtx,
381) {
382 // spec 7.14's order: this plane's whole vertical pass, then its whole
383 // horizontal one. `0..usize::MAX` is the whole plane, i.e. exactly this call.
384 deblock_plane_span(
385 plane,
386 plane_idx,
387 lf,
388 n,
389 frame_width,
390 frame_height,
391 0,
392 usize::MAX,
393 false,
394 fctx,
395 );
396 deblock_plane_span(
397 plane,
398 plane_idx,
399 lf,
400 n,
401 frame_width,
402 frame_height,
403 0,
404 usize::MAX,
405 true,
406 fctx,
407 );
408}
409
410/// One pass of [`deblock_plane`] -- vertical edges (`horz == false`) or
411/// horizontal ones -- restricted to the plane rows `span_lo..span_hi`.
412///
413/// A row span is a legal cut of either pass because a band boundary is a
414/// multiple of 16 rows and every edge's kernel stays inside its own
415/// 4-sample group's reach.
416#[allow(clippy::too_many_arguments)]
417pub(super) fn deblock_plane_span(
418 plane: &mut PlaneBuf<'static>,
419 plane_idx: usize,
420 lf: &LoopFilterParams,
421 n: &Neighbours,
422 frame_width: usize,
423 frame_height: usize,
424 span_lo: usize,
425 span_hi: usize,
426 horz: bool,
427 fctx: &crate::decode::FrameCtx,
428) {
429 let chroma = plane_idx != 0;
430 // r7: libaom clips the deblock loop to the CODED frame's own
431 // width/height, not the mi-aligned `true_width`/`true_height` margin
432 // (the padding up to the next 8-pixel/superblock boundary that
433 // reconstruction still fills in but the loop filter never visits).
434 // Confirmed against the superres gate: with the margin included, the
435 // last coded mi column's horizontal edges were filtered when libaom's
436 // real output leaves them untouched (r6's post-deblock diff, 37 px, all
437 // in columns 44-47); clipping here closes it (3/3 frames pixel-exact).
438 // lane-golomb r9: the bound is the MI-ROUNDED frame, not the coded
439 // frame. libaom's `av1_filter_block_plane_vert/horz` walk the superblock
440 // and stop at `cm->mi_params.mi_cols`/`mi_rows`, which
441 // `av1_set_mb_mi` derives from `ALIGN_POWER_OF_TWO(width, 3)` -- the
442 // 8-pixel-aligned frame, i.e. a 68-wide frame is filtered out to column
443 // 72 and the vertical edge AT x=68 is a real edge that rewrites the
444 // in-crop columns 64..67. Clipping at `frame_width` skipped it, which is
445 // the +-1 straddling-band defect (68x192 cq35, frame 1, 141 luma pixels
446 // all in columns 64..67; frame 0 survived because that edge carried no
447 // filter level there). r7's superres measurement is preserved: its frame
448 // was already 8-aligned, so this bound equals `frame_width` there and
449 // still excludes the superblock padding up to `true_width`.
450 // lane-av1-444: the chroma crop follows the sequence subsampling, not a
451 // hardcoded 4:2:0 halving -- at 4:4:4 the halved bound clipped the whole
452 // filter to the top-left quarter of each chroma plane.
453 let (cw, ch) = if chroma {
454 (
455 frame_width.div_ceil(1 << ss_x(fctx)),
456 frame_height.div_ceil(1 << ss_y(fctx)),
457 )
458 } else {
459 (frame_width, frame_height)
460 };
461 let (tw, th, stride) = (
462 plane.true_width.min(cw),
463 plane.true_height.min(ch),
464 plane.width,
465 );
466 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") {
467 eprintln!(
468 "DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}",
469 plane.true_width, plane.true_height
470 );
471 }
472 // lane-perf8: both passes iterate the edge's OWN direction innermost, so
473 // 4 consecutive 4-sample groups (16 lines) can go through one AVX2
474 // kernel. The swap is order-preserving: a filtered group overlaps only
475 // groups along the edge it sits on -- the vertical pass's writes at
476 // `x0` reach columns `x0 - 7 ..= x0 + 5` of its own 4 rows, so the
477 // dependence is on ascending `x0` within a row, which stays the outer
478 // loop's order, and rows remain independent (horizontal pass mirrored).
479 let rows = plane.data.len() / stride.max(1);
480 let seg_lf_active = fctx.seg.with(|s| s.borrow().enabled);
481 // lane-filt1: both passes are split across `EC_AV1_FILTER_THREADS`
482 // bands along the axis whose writes are disjoint. A vertical edge's
483 // 4-sample groups write columns `x0-7 ..= x0+5` of their OWN 4 rows, so
484 // row bands never touch each other; a horizontal edge's groups write rows
485 // `y0-7 ..= y0+6` of their own 4 columns, so column bands never do. Both
486 // read the mode-info grids immutably. The grouping a band starts with is
487 // free: every 4-row (4-column) group's output is a pure function of that
488 // group, whether it goes through `filter_edge16` with three neighbours or
489 // through `filter_edge` alone. Band boundaries are multiples of 16 so no
490 // group ever straddles one.
491 // lane-perf10 merge: the output plane is owned (perf10 made mutable
492 // plane params PlaneBuf<'static>); force the Cow to Owned ONCE here so
493 // the bands below never clone it concurrently.
494 let data: &mut [u16] = plane.data.to_mut();
495 let threads = crate::par::filter_threads();
496 let (sp_lo, sp_hi) = (span_lo.min(th), span_hi.min(th));
497 let mut vbands: Vec<(usize, usize)> = if horz || sp_lo >= sp_hi {
498 Vec::new()
499 } else {
500 crate::par::bands((sp_hi - sp_lo).div_ceil(16), threads)
501 .into_iter()
502 .map(|(a, b)| (sp_lo + a * 16, (sp_lo + b * 16).min(sp_hi)))
503 .collect()
504 };
505 // The last band's slice runs to the end of the plane: an edge group that
506 // starts inside the band can write up to 3 rows past `sp_hi` (the loop
507 // below still stops at `sp_hi`), as it always has.
508 if let Some(last) = vbands.last_mut() {
509 last.1 = rows.max(last.1);
510 }
511 crate::par::run_bands_mut(&vbands, stride, fctx, data, |y_lo, y_hi, mine, fctx| {
512 let y_hi = y_hi.min(sp_hi);
513 // lane-deblock2: this band's own level table and pass constants,
514 // built once per band instead of re-derived per 4-pixel edge.
515 // `mine` holds rows `y_lo..`, so every index below is `y - y_lo` rows in.
516 let vctx = EdgeCtx::new(lf, n, plane_idx, 0, chroma, seg_lf_active, fctx);
517 let mut x0 = 4usize;
518 while x0 < tw {
519 let mut y0 = y_lo;
520 while y0 < y_hi {
521 if y0 + 16 <= y_hi && x0 >= 8 && x0 + 8 <= stride {
522 let ps: [Option<(u8, i32)>; 4] =
523 std::array::from_fn(|k| edge_params(&vctx, x0, y0 + 4 * k));
524 if let Some((len, level)) = ps[0]
525 && ps.iter().all(|p| *p == ps[0])
526 && filter_edge16(
527 mine,
528 (y0 - y_lo) * stride + x0,
529 stride,
530 true,
531 len,
532 level,
533 lf.sharpness,
534 fctx,
535 )
536 {
537 y0 += 16;
538 continue;
539 }
540 for (k, p) in ps.iter().enumerate() {
541 if let Some((len, level)) = *p {
542 filter_edge(
543 mine,
544 (y0 + 4 * k - y_lo) * stride + x0,
545 stride as isize,
546 1,
547 len,
548 level,
549 lf.sharpness,
550 fctx,
551 );
552 }
553 }
554 y0 += 16;
555 continue;
556 }
557 if let Some((len, level)) = edge_params(&vctx, x0, y0) {
558 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 {
559 eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}");
560 }
561 filter_edge(
562 mine,
563 (y0 - y_lo) * stride + x0,
564 stride as isize,
565 1,
566 len,
567 level,
568 lf.sharpness,
569 fctx,
570 );
571 }
572 y0 += 4;
573 }
574 x0 += 4;
575 }
576 });
577 // The horizontal pass runs only after the WHOLE vertical pass of this
578 // plane (spec 7.14 order), which `run_bands_mut` guarantees by joining.
579 let hbands: Vec<(usize, usize)> = if !horz || sp_lo >= sp_hi {
580 Vec::new()
581 } else {
582 crate::par::bands(tw.div_ceil(16), threads)
583 .into_iter()
584 .map(|(a, b)| (a * 16, (b * 16).min(tw)))
585 .collect()
586 };
587 // A column band is not a contiguous run of the row-major plane, so each
588 // band filters a private strip holding its own columns of every row,
589 // copied in from the (still unchanged) plane and written back after the
590 // join. A horizontal edge's taps run down its own column only, so the
591 // strip has everything the band reads and writes.
592 struct HStrip {
593 x_lo: usize,
594 x_hi: usize,
595 w: usize,
596 buf: Vec<u16>,
597 }
598 let nb = hbands.len();
599 let mut strips: Vec<HStrip> = hbands
600 .iter()
601 .enumerate()
602 .map(|(k, &(x_lo, x_hi))| {
603 // The last band's strip also takes the padding columns: a 4-column
604 // group that starts before `tw` may write past it, as it always has.
605 let w_hi = if k + 1 == nb { stride.max(x_hi) } else { x_hi };
606 HStrip {
607 x_lo,
608 x_hi,
609 w: w_hi - x_lo,
610 buf: Vec::new(),
611 }
612 })
613 .collect();
614 // The horizontal pass reads and writes rows `y0 - 8 ..= y0 + 7` for its
615 // own edges `y0 in sp_lo.max(4)..sp_hi`, so a strip holds only those rows:
616 // rows outside the span can belong to other threads' work in the pipeline,
617 // and copying them back would overwrite it.
618 let r_lo = sp_lo.max(4).saturating_sub(8);
619 let r_hi = (sp_hi + 8).min(rows);
620 let src: &[u16] = &*data;
621 crate::par::run_parts_mut(&mut strips, fctx, |strip, fctx| {
622 let (x_lo, x_hi, w) = (strip.x_lo, strip.x_hi, strip.w);
623 let buf = &mut strip.buf;
624 buf.clear();
625 for y in r_lo..r_hi {
626 buf.extend_from_slice(&src[y * stride + x_lo..][..w]);
627 }
628 let px: &mut [u16] = buf.as_mut_slice();
629 let hctx = EdgeCtx::new(lf, n, plane_idx, 1, chroma, seg_lf_active, fctx);
630 let mut y0 = sp_lo.max(4);
631 while y0 < sp_hi {
632 let mut x0 = x_lo;
633 while x0 < x_hi {
634 // Strip-local: row `y0` is `y0 - r_lo` rows in, column `x0` is `x0 - x_lo`.
635 if x0 + 16 <= x_hi && y0 >= 8 && y0 + 7 <= rows {
636 let ps: [Option<(u8, i32)>; 4] =
637 std::array::from_fn(|k| edge_params(&hctx, x0 + 4 * k, y0));
638 if let Some((len, level)) = ps[0]
639 && ps.iter().all(|p| *p == ps[0])
640 && filter_edge16(
641 px,
642 (y0 - r_lo) * w + (x0 - x_lo),
643 w,
644 false,
645 len,
646 level,
647 lf.sharpness,
648 fctx,
649 )
650 {
651 x0 += 16;
652 continue;
653 }
654 for (k, p) in ps.iter().enumerate() {
655 if let Some((len, level)) = *p {
656 filter_edge(
657 px,
658 (y0 - r_lo) * w + (x0 - x_lo) + 4 * k,
659 1,
660 w as isize,
661 len,
662 level,
663 lf.sharpness,
664 fctx,
665 );
666 }
667 }
668 x0 += 16;
669 continue;
670 }
671 if let Some((len, level)) = edge_params(&hctx, x0, y0) {
672 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE")
673 && plane_idx == 0
674 && x0 == 44
675 {
676 eprintln!(
677 "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
678 lf.sharpness
679 );
680 }
681 filter_edge(
682 px,
683 (y0 - r_lo) * w + (x0 - x_lo),
684 1,
685 w as isize,
686 len,
687 level,
688 lf.sharpness,
689 fctx,
690 );
691 }
692 x0 += 4;
693 }
694 y0 += 4;
695 }
696 });
697 for strip in strips.iter().filter(|s| s.w > 0) {
698 for (i, row) in strip.buf.chunks_exact(strip.w).enumerate() {
699 data[(r_lo + i) * stride + strip.x_lo..][..strip.w].copy_from_slice(row);
700 }
701 }
702}
703
704/// lane-perf6: reused whole-plane `u16` buffers. Every frame takes a
705/// pre-CDEF snapshot of all three planes, a post-deblock snapshot when loop
706/// restoration is active, and a fresh LR destination per plane -- freshly
707/// allocated that is ~25 MB of `mmap`/`munmap` per frame at 4K, so every
708/// sample written also takes a first-touch page fault. The buffers are handed
709/// back here instead and refilled in place.
710///
711/// lane-memfix: PROCESS-WIDE, not one stash per thread. These buffers do not
712/// stay on one thread: the frame thread allocates the snapshots and a filter
713/// worker returns them (the picture's pre-LR planes go back into the pool
714/// from whichever worker ran the restoration), so a per-thread pool leaked
715/// whole-plane buffers into every worker it touched -- 19 MB a set, times
716/// every pool thread the decode ever created. One shared pool with a hard
717/// entry cap bounds the retention at [`SCRATCH_CAP`] buffers no matter how
718/// many threads cycle through it; anything over the cap is freed.
719pub(super) static PLANE_SCRATCH: std::sync::Mutex<Vec<Vec<u16>>> = std::sync::Mutex::new(Vec::new());
720
721/// Most buffers the shared pool keeps. ~3 whole-plane sets per in-flight 4K
722/// frame at the shipped `EC_AV1_THREADS` ceiling; the frames actually in
723/// flight cycle through far fewer.
724pub(super) const SCRATCH_CAP: usize = 32;
725
726/// Takes a pooled buffer for a caller that wants `n` samples, best-fit by
727/// CAPACITY so a chroma-sized request does not permanently promote a
728/// luma-sized allocation (every pooled buffer would drift to the largest
729/// size otherwise). `None` when the pool is empty.
730fn scratch_take(n: usize) -> Option<Vec<u16>> {
731 let mut p = PLANE_SCRATCH.lock().unwrap();
732 if p.is_empty() {
733 return None;
734 }
735 let fit = p
736 .iter()
737 .enumerate()
738 .filter(|(_, v)| v.capacity() >= n)
739 .min_by_key(|(_, v)| v.capacity())
740 .map(|(i, _)| i);
741 let i = match fit {
742 Some(i) => i,
743 // Nothing big enough: grow the largest rather than a small one.
744 None => p
745 .iter()
746 .enumerate()
747 .max_by_key(|(_, v)| v.capacity())
748 .map(|(i, _)| i)
749 .expect("the pool is not empty"),
750 };
751 Some(p.swap_remove(i))
752}
753
754/// A pooled buffer holding a copy of `src`.
755pub(super) fn scratch_from(src: &[u16]) -> Vec<u16> {
756 let mut v = scratch_take(src.len()).unwrap_or_default();
757 v.clear();
758 v.extend_from_slice(src);
759 v
760}
761
762/// An empty pooled buffer, for a caller that fills it itself.
763pub(super) fn scratch_empty() -> Vec<u16> {
764 let mut v = scratch_take(0).unwrap_or_default();
765 v.clear();
766 v
767}
768
769/// A pooled buffer of exactly `n` samples whose contents are NOT cleared --
770/// for a caller that writes every element it later reads (lane-copy: the
771/// post-deblock snapshot writes 4 rows in 64 and reads no other).
772pub(super) fn scratch_sized(n: usize) -> Vec<u16> {
773 let mut v = scratch_take(n).unwrap_or_default();
774 if v.len() > n {
775 v.truncate(n);
776 } else if v.len() < n {
777 v.resize(n, 0);
778 }
779 v
780}
781
782pub(super) fn plane_snapshot(p: &PlaneBuf<'_>, ss_y: u32) -> PlaneBuf<'static> {
783 let mut data = scratch_sized(p.data.len());
784 let rows = p.data.len().checked_div(p.width).unwrap_or(0);
785 let stripe_h = 64usize >> ss_y;
786 let offset = 8usize >> ss_y;
787 let mut b = stripe_h - offset;
788 while b < rows {
789 let (lo, hi) = (b - 2, (b + 2).min(rows));
790 data[lo * p.width..hi * p.width].copy_from_slice(&p.data[lo * p.width..hi * p.width]);
791 b += stripe_h;
792 }
793 PlaneBuf {
794 data: std::borrow::Cow::Owned(data),
795 ..*p
796 }
797}
798
799/// The pre-filter reconstruction of one coded frame, plus the per-block state
800/// the loop filters read.
801///
802/// The encoder's filter search ([`crate::filter_search::pick_filters`])
803/// decodes the same coded tile under ~25 candidate deblock/CDEF parameter
804/// sets to score each one, and the entropy decode and reconstruction it
805/// repeats are identical every time -- both filters run after it, on the
806/// finished planes. That re-parse was 24% of the encoder's profile. A caller
807/// arms [`arm_filter_replay`] around ONE decode and then re-runs the filters
808/// alone through [`replay_filters`]; the result is the same picture the full
809/// decode would have returned, because it is the same two calls on a copy of
810/// the same planes.
811pub(crate) struct FilterReplay {
812 pub(super) y: PlaneBuf<'static>,
813 pub(super) u: PlaneBuf<'static>,
814 pub(super) v: PlaneBuf<'static>,
815 pub(super) neighbours: Neighbours,
816 pub(super) frame_width: usize,
817 pub(super) frame_height: usize,
818 pub(super) width: usize,
819 pub(super) height: usize,
820 /// The reconstructed extent (`mi_cols`/`mi_rows` * 4), for the wide-margin
821 /// stash the cropped return path leaves behind.
822 pub(super) true_width: usize,
823 pub(super) true_height: usize,
824 /// lane-av1fpar: plane buffers this replay is done with. Every candidate
825 /// works on its own copy of three ~6 MB planes, and a fresh `Vec` per
826 /// copy is a fresh mmap the kernel faults in page by page -- 12.6% of a
827 /// 1080p frame's wall in allocation, not in filtering. Recycled here
828 /// instead; the pool holds at most the six planes one candidate has live.
829 pub(super) scratch: Vec<Vec<u16>>,
830 /// lane-av1cap2: the final replay's post-CDEF luma plane and the TRUE
831 /// post-deblock rows loop restoration substitutes at its stripe
832 /// borders ([`plane_snapshot`], exactly `restoration::lr_src_row`'s
833 /// rows) -- what [`replay_restoration`] filters, instead of decoding
834 /// the re-coded tile a second time.
835 pub(super) final_luma: Option<(PlaneBuf<'static>, PlaneBuf<'static>)>,
836 /// lane-av1speed3: the previous candidate's DESTINATION planes, still
837 /// holding its post-CDEF samples, and one byte per 8x8 CDEF unit its
838 /// filter wrote (see [`cdef_band`]). The CDEF half of the search moves
839 /// no deblocking level, so every candidate of it used to copy the three
840 /// post-deblock planes (~19 MB at 4K) into fresh destinations. Here the
841 /// destinations are kept and only the units the last candidate touched
842 /// are restored -- the same bytes, since a unit nobody wrote still holds
843 /// the deblocked sample it was copied from.
844 pub(super) work: Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
845 pub(super) wrote: Vec<u8>,
846 /// The strengths [`FilterReplay::work`] was filtered under: a plane whose
847 /// new candidate can only write MORE units than the old one needs no
848 /// restore at all, since every unit CDEF writes it writes from the
849 /// post-deblock source alone.
850 pub(super) work_cdef: Option<CdefParams>,
851 /// The last deblocked planes and the levels that produced them.
852 /// Deblocking depends on nothing else the search moves, and the search
853 /// fixes the levels before it walks the CDEF strengths, so every
854 /// candidate after the first of a level pair replays CDEF alone.
855 pub(super) deblocked: Option<(
856 LoopFilterParams,
857 PlaneBuf<'static>,
858 PlaneBuf<'static>,
859 PlaneBuf<'static>,
860 )>,
861}
862
863thread_local! {
864 /// Set by [`arm_filter_replay`] for the span of one decode.
865 static REPLAY_ARMED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
866 /// What that decode captured, until [`clear_filter_replay`].
867 pub(super) static REPLAY: std::cell::RefCell<Option<FilterReplay>> =
868 const { std::cell::RefCell::new(None) };
869}
870
871/// Capture this thread's next decode's pre-filter frame (see [`FilterReplay`]).
872pub(crate) fn arm_filter_replay() {
873 REPLAY_ARMED.set(true);
874}
875
876/// Test-only: force every filter candidate through a full decode, so a gate
877/// can hold the replay against the decode it stands in for
878/// (`encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode`).
879#[cfg(test)]
880pub(super) static REPLAY_DISABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
881
882#[cfg(test)]
883pub(crate) fn set_filter_replay_disabled(off: bool) {
884 REPLAY_DISABLED.store(off, std::sync::atomic::Ordering::Relaxed);
885}
886
887// Test-only: run the capture decode `replay_final` replaced as well, and
888// hold its picture and its `FilterStages` against the replay's
889// (`encoder::tests::filter_replay_final_matches_the_capture_decode`).
890// Thread-local, not a global: the filter stage runs on the frame thread the
891// test itself drives, and a process-wide flag would put every test encoding
892// in parallel with this one through the extra decode too.
893#[cfg(test)]
894thread_local! {
895 static VERIFY_FINAL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
896}
897
898#[cfg(test)]
899pub(crate) fn set_verify_final_replay(on: bool) {
900 VERIFY_FINAL.set(on);
901}
902
903#[cfg(test)]
904pub(crate) fn verify_final_replay() -> bool {
905 VERIFY_FINAL.get()
906}
907
908/// Drop the armed flag and anything captured: the tile it belongs to is done.
909pub(crate) fn clear_filter_replay() {
910 REPLAY_ARMED.set(false);
911 REPLAY.with_borrow_mut(|r| *r = None);
912}
913
914/// The capture itself, called from the decoder's own pre-filter point. Owns
915/// copies of the planes, since the caller filters them in place.
916// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
917#[allow(clippy::too_many_arguments)]
918pub(super) fn capture_filter_replay(
919 y: &PlaneBuf<'_>,
920 u: &PlaneBuf<'_>,
921 v: &PlaneBuf<'_>,
922 neighbours: &Neighbours,
923 frame_width: usize,
924 frame_height: usize,
925 width: usize,
926 height: usize,
927 true_width: usize,
928 true_height: usize,
929) {
930 if !REPLAY_ARMED.replace(false) {
931 return;
932 }
933 let own = |p: &PlaneBuf<'_>| PlaneBuf {
934 data: std::borrow::Cow::Owned(p.data.to_vec()),
935 ..*p
936 };
937 REPLAY.with_borrow_mut(|slot| {
938 *slot = Some(FilterReplay {
939 y: own(y),
940 u: own(u),
941 v: own(v),
942 neighbours: neighbours.clone(),
943 frame_width,
944 frame_height,
945 width,
946 height,
947 true_width,
948 true_height,
949 scratch: Vec::new(),
950 work: None,
951 wrote: Vec::new(),
952 work_cdef: None,
953 final_luma: None,
954 deblocked: None,
955 });
956 });
957}
958
959/// Restores, from the post-deblock cache, every sample the previous CDEF
960/// candidate may have written: for each unit row, the column span between
961/// its first and last written unit (a superset of the written units, which
962/// is what makes the copy contiguous -- and never more than the whole-plane
963/// copy it replaces). `unit` is this plane's CDEF unit side, 8 for luma and
964/// 4 for 4:2:0 chroma.
965pub(super) fn restore_written(
966 dst: &mut PlaneBuf<'static>,
967 src: &PlaneBuf<'_>,
968 wrote: &[u8],
969 mask: u8,
970 unit_cols: usize,
971 unit: usize,
972) {
973 let w = dst.width;
974 if w == 0 || unit_cols == 0 || wrote.is_empty() {
975 return;
976 }
977 let rows = dst.data.len() / w;
978 let s: &[u16] = &src.data;
979 let d = dst.data.to_mut();
980 let band = |d: &mut [u16], wr: &[u8], ur0: usize| {
981 for (i, row) in wr.chunks(unit_cols).enumerate() {
982 let Some(c0) = row.iter().position(|&b| b & mask != 0) else {
983 continue;
984 };
985 let c1 = row
986 .iter()
987 .rposition(|&b| b & mask != 0)
988 .expect("just found one");
989 let (x0, x1) = ((c0 * unit).min(w), ((c1 + 1) * unit).min(w));
990 let ur = ur0 + i;
991 let (y0, y1) = ((ur * unit).min(rows), ((ur + 1) * unit).min(rows));
992 for r in y0..y1 {
993 let off = (r - ur0 * unit) * w;
994 d[off + x0..off + x1].copy_from_slice(&s[r * w + x0..r * w + x1]);
995 }
996 }
997 };
998 let urows = wrote.len() / unit_cols;
999 let threads = crate::par::filter_threads().min(urows.max(1));
1000 if threads <= 1 {
1001 band(d, wrote, 0);
1002 return;
1003 }
1004 let per = urows.div_ceil(threads);
1005 crate::par::scope("ec-av1-filter", |batch| {
1006 for (i, (dc, wr)) in d
1007 .chunks_mut(per * unit * w)
1008 .zip(wrote.chunks(per * unit_cols))
1009 .enumerate()
1010 {
1011 let band = &band;
1012 batch.submit(move || band(dc, wr, i * per));
1013 }
1014 });
1015}
1016
1017/// One candidate's working copy of a captured plane, off [`FilterReplay`]'s
1018/// own buffer pool: a cleared `Vec` that already has the capacity keeps the
1019/// allocator and the page fault handler out of the filter search.
1020pub(super) fn pooled(p: &PlaneBuf<'_>, scratch: &mut Vec<Vec<u16>>) -> PlaneBuf<'static> {
1021 let mut buf = scratch.pop().unwrap_or_default();
1022 let src: &[u16] = &p.data;
1023 let threads = crate::par::filter_threads();
1024 if buf.len() != src.len() || threads <= 1 {
1025 buf.clear();
1026 buf.extend_from_slice(src);
1027 } else {
1028 // A recycled buffer is already the right length, so the copy is a
1029 // plain `copy_from_slice` -- and one worth banding: ~6 MB per
1030 // candidate is memory bandwidth, not arithmetic, and the halves are
1031 // disjoint `&mut` slices (no `par::Shared` needed).
1032 let per = src.len().div_ceil(threads);
1033 crate::par::scope("ec-av1-filter", |batch| {
1034 for (dst, src) in buf.chunks_mut(per).zip(src.chunks(per)) {
1035 batch.submit(move || dst.copy_from_slice(src));
1036 }
1037 });
1038 }
1039 PlaneBuf {
1040 data: std::borrow::Cow::Owned(buf),
1041 ..*p
1042 }
1043}