From 63e598c51ac03a12d5fda9d37695f1b0d2b2ac13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 5 Sep 2026 01:57:38 +0300 Subject: [PATCH] perf(av1): parallelise the in-frame filter chain (deblock, CDEF, LR, film grain) `EC_AV1_FILTER_THREADS` (default 1, so the shipped behaviour is unchanged) splits every post-decode filter stage across `std::thread::scope` workers, each along an axis whose writes are disjoint: * deblock: 16-row bands for the vertical-edge pass (a vertical edge writes columns x0-7..x0+5 of its OWN 4 rows) and 16-column bands for the horizontal one (rows y0-7..y0+6 of its own 4 columns); the horizontal pass still runs after the whole vertical pass of that plane, spec 7.14 order. * CDEF: mi ROW bands. Every unit reads only the pre-CDEF snapshots and writes its own 8x8 luma / 4x4 chroma square. * loop restoration: restoration-unit row bands. The RU row walk is resolved into a row list first (a short remainder is swallowed by the previous row), and row `r`'s write range starts where row `r-1`'s ended. * film grain: 32-pixel block rows. A row's noise comes from `Rng::line(y * 2, seed)` alone, and the one carry across rows -- the line buffers -- is rebuilt by replaying exactly ONE preceding row with its pixel writes suppressed. `FrameCtx` stays `!Sync`; a worker gets `filter_ctx_copy`'s copy of the fields the filter chain reads (bit depth, segmentation, superres, grain bit depth). The aliasing that the band arithmetic proves and the borrow checker cannot is confined to `par::Shared` (one `#[allow(unsafe_code)]` module). Gated byte-exact: the new `a_real_stream_filters_identically_with_one_and_four_filter_threads` compares every output plane of a 10-bit CDEF+LR stream and of a film-grain stream at 1 vs 4 filter threads, with per-stage firing counters asserted; the four perf6 stream hashes are equal at 1 and at 4 filter threads. seg4k 272 frames: 34.99 s -> 31.33 s (7.77 -> 8.68 fps), seg4k_lr 32.13 s -> 27.31 s at 4 filter threads (interleaved medians of 3, 12-core box under load 6.5). Single-threaded cost: +1.6% instructions (607.34 G -> 617.18 G on seg4k), mostly CDEF losing alias facts through the raw-pointer-derived `&mut`. --- crates/ec-av1/src/decode.rs | 508 +++++++++++++++----------- crates/ec-av1/src/film_grain.rs | 604 ++++++++++++++++--------------- crates/ec-av1/src/lib.rs | 1 + crates/ec-av1/src/par.rs | 135 +++++++ crates/ec-av1/src/restoration.rs | 72 ++-- crates/ec-av1/src/stream.rs | 69 ++++ 6 files changed, 858 insertions(+), 531 deletions(-) create mode 100644 crates/ec-av1/src/par.rs diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 5f33e5db..5f1fc6b8 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -151,6 +151,27 @@ pub(crate) trait WithRef { } impl WithRef for T {} +/// A [`FrameCtx`] copy for one of [`crate::par`]'s filter worker threads. +/// +/// `FrameCtx` is `!Sync` on purpose (a decode's state belongs to one thread), +/// and the post-decode filter chain reads exactly these fields: the bit depth +/// (every kernel's clamp and threshold shift), the segmentation table +/// (`segment_id_at`/`lf_level` in the deblocker), the frame's superres state +/// and the film-grain bit depth. Everything else keeps [`FrameCtx::new`]'s +/// default -- a field that turns out to be read after all shows up as a hash +/// mismatch in +/// `a_real_stream_filters_identically_with_one_and_four_filter_threads`. +pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx { + let out = FrameCtx::new(); + out.bit_depth.set(fctx.bit_depth.get()); + out.grain_bit_depth.set(fctx.grain_bit_depth.get()); + out.superres.set(fctx.superres.get()); + out.seg_mi_dims.set(fctx.seg_mi_dims.get()); + out.seg.replace(fctx.seg.borrow().clone()); + out.seg_ids.replace(fctx.seg_ids.borrow().clone()); + out +} + use crate::cdf; use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables}; use crate::encode::{Picture, Reach}; @@ -17175,126 +17196,158 @@ fn deblock_plane( // loop's order, and rows remain independent (horizontal pass mirrored). let rows = plane.data.len() / stride.max(1); let seg_lf_active = fctx.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, seg_lf_active, fctx)); - if let Some((len, level)) = ps[0] { - if ps.iter().all(|p| *p == ps[0]) - && filter_edge16( - &mut plane.data, - y0 * stride + x0, - stride, - true, - len, - level, - lf.sharpness, fctx, - ) - { - y0 += 16; - continue; + // lane-filt1: both passes are split across `EC_AV1_FILTER_THREADS` + // bands along the axis whose writes are disjoint. A vertical edge's + // 4-sample groups write columns `x0-7 ..= x0+5` of their OWN 4 rows, so + // row bands never touch each other; a horizontal edge's groups write rows + // `y0-7 ..= y0+6` of their own 4 columns, so column bands never do. Both + // read the mode-info grids immutably. The grouping a band starts with is + // free: every 4-row (4-column) group's output is a pure function of that + // group, whether it goes through `filter_edge16` with three neighbours or + // through `filter_edge` alone. Band boundaries are multiples of 16 so no + // group ever straddles one. + let threads = crate::par::filter_threads(); + let sp = crate::par::Shared::new(plane); + let vbands: Vec<(usize, usize)> = crate::par::bands(th.div_ceil(16), threads) + .into_iter() + .map(|(a, b)| (a * 16, (b * 16).min(th))) + .collect(); + crate::par::run_bands(&vbands, fctx, |y_lo, y_hi, fctx| { + // SAFETY: this band writes only rows `y_lo..y_hi` of the plane, which + // no other band touches (see `Shared`'s own corner-cut note). + #[allow(unsafe_code)] + let plane = unsafe { sp.get() }; + let mut x0 = 4usize; + while x0 < tw { + let mut y0 = y_lo; + while y0 < y_hi { + if y0 + 16 <= y_hi && 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, seg_lf_active, fctx)); + if let Some((len, level)) = ps[0] { + if ps.iter().all(|p| *p == ps[0]) + && filter_edge16( + &mut plane.data, + y0 * stride + x0, + stride, + true, + len, + level, + lf.sharpness, fctx, + ) + { + y0 += 16; + continue; + } } - } - for (k, p) in ps.iter().enumerate() { - if let Some((len, level)) = *p { - filter_edge( - &mut plane.data, - (y0 + 4 * k) * stride + x0, - stride as isize, - 1, - len, - level, - lf.sharpness, fctx, - ); + for (k, p) in ps.iter().enumerate() { + if let Some((len, level)) = *p { + filter_edge( + &mut plane.data, + (y0 + 4 * k) * stride + x0, + stride as isize, + 1, + len, + level, + lf.sharpness, fctx, + ); + } } + y0 += 16; + continue; } - y0 += 16; - continue; - } - if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0, seg_lf_active, fctx) { - if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 { - eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}"); + if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0, seg_lf_active, fctx) { + if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 { + eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}"); + } + filter_edge( + &mut plane.data, + y0 * stride + x0, + stride as isize, + 1, + len, + level, + lf.sharpness, fctx, + ); } - filter_edge( - &mut plane.data, - y0 * stride + x0, - stride as isize, - 1, - len, - level, - lf.sharpness, fctx, - ); + y0 += 4; } - y0 += 4; + x0 += 4; } - x0 += 4; - } - let mut y0 = 4usize; - while y0 < th { - let mut x0 = 0usize; - 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, seg_lf_active, fctx)); - if let Some((len, level)) = ps[0] { - if ps.iter().all(|p| *p == ps[0]) - && filter_edge16( - &mut plane.data, - y0 * stride + x0, - stride, - false, - len, - level, - lf.sharpness, fctx, - ) - { - x0 += 16; - continue; + }); + // The horizontal pass runs only after the WHOLE vertical pass of this + // plane (spec 7.14 order), which `run_bands` guarantees by joining. + let hbands: Vec<(usize, usize)> = crate::par::bands(tw.div_ceil(16), threads) + .into_iter() + .map(|(a, b)| (a * 16, (b * 16).min(tw))) + .collect(); + crate::par::run_bands(&hbands, fctx, |x_lo, x_hi, fctx| { + // SAFETY: this band writes only columns `x_lo..x_hi`. + #[allow(unsafe_code)] + let plane = unsafe { sp.get() }; + let mut y0 = 4usize; + while y0 < th { + let mut x0 = x_lo; + while x0 < x_hi { + if x0 + 16 <= x_hi && 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, seg_lf_active, fctx)); + if let Some((len, level)) = ps[0] { + if ps.iter().all(|p| *p == ps[0]) + && filter_edge16( + &mut plane.data, + y0 * stride + x0, + stride, + false, + len, + level, + lf.sharpness, fctx, + ) + { + x0 += 16; + continue; + } } + for (k, p) in ps.iter().enumerate() { + if let Some((len, level)) = *p { + filter_edge( + &mut plane.data, + y0 * stride + x0 + 4 * k, + 1, + stride as isize, + len, + level, + lf.sharpness, fctx, + ); + } + } + x0 += 16; + continue; } - for (k, p) in ps.iter().enumerate() { - if let Some((len, level)) = *p { - filter_edge( - &mut plane.data, - y0 * stride + x0 + 4 * k, - 1, - stride as isize, - len, - level, - lf.sharpness, fctx, + if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0, seg_lf_active, fctx) { + if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE") + && plane_idx == 0 + && x0 == 44 + { + eprintln!( + "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}", + lf.sharpness ); } - } - x0 += 16; - continue; - } - if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0, seg_lf_active, fctx) { - if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE") - && plane_idx == 0 - && x0 == 44 - { - eprintln!( - "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}", - lf.sharpness + filter_edge( + &mut plane.data, + y0 * stride + x0, + 1, + stride as isize, + len, + level, + lf.sharpness, fctx, ); } - filter_edge( - &mut plane.data, - y0 * stride + x0, - 1, - stride as isize, - len, - level, - lf.sharpness, fctx, - ); + x0 += 4; } - x0 += 4; - } - y0 += 4; - } + y0 += 4; + } }); } thread_local! { @@ -17425,124 +17478,145 @@ fn apply_cdef( let coeff_shift = i32::from(bit_depth(fctx)) - 8; let damping = i32::from(cdef.damping) + coeff_shift; let damping_uv = (damping - 1).max(0); - // One scratch window per plane kind, reused by every unit (8x8 luma and - // 4x4 chroma, each grown by the [`CDEF_BORDER`] tap ring). - let mut win_y = [0i32; (8 + 2 * CDEF_BORDER) * (8 + 2 * CDEF_BORDER)]; - let mut win_uv = [0i32; (4 + 2 * CDEF_BORDER) * (4 + 2 * CDEF_BORDER)]; - let mut mi_r = 0usize; - while mi_r < skip_grid.mi_rows { - let mut mi_c = 0usize; - while mi_c < skip_grid.mi_cols { - if skip_grid.is_skip_txfm(mi_r, mi_c) { - CDEF_SKIPPED_UNITS.with(|c| c.set(c.get() + 1)); - } - if !skip_grid.is_skip_txfm(mi_r, mi_c) { - let sidx = strength_idx(mi_r, mi_c); - let (ox, oy) = (mi_c * 4, mi_r * 4); - // Nothing to do for this unit at all: the direction search is - // only ever consumed through a strength, so a unit whose four - // strengths are zero never needs its 8x8 window gathered. - if cdef.y_pri_strength[sidx] == 0 - && cdef.y_sec_strength[sidx] == 0 - && cdef.uv_pri_strength[sidx] == 0 - && cdef.uv_sec_strength[sidx] == 0 - { - mi_c += 2; - continue; - } - let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height); - cdef_gather(&src_y, y_stride, y_true_w, y_true_h, ox, oy, 8, 8, &mut win_y); - let sample_y = |r: i32, c: i32| -> i32 { - win_y[(r + CDEF_BORDER as i32) as usize * (8 + 2 * CDEF_BORDER) - + (c + CDEF_BORDER as i32) as usize] - }; - // lane-cdef r1: the direction search reads the SAME padded - // block the taps do -- libaom runs `cdef_find_dir` on the - // prepared filter block (`cdef_block.c:296-320` over - // `cdef_prepare_fb`'s buffer, `cdef.c:249-256`), whose columns - // and rows past the mi-rounded frame extent are CDEF_VERY_LARGE. - // Clamping to the last real sample instead made every straddling - // edge 8x8 (odd `mi_cols`/`mi_rows`) pick a different var, hence - // a different `adjust_strength`, hence a +-1 band at the crop edge. - let (dir, var) = cdef_find_dir(coeff_shift, |r, c| sample_y(r as i32, c as i32)); - - // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0` - // -- each plane zeroes the shared direction when *its own* - // frame-level primary strength is 0, independent of the - // per-block adjusted `t` and of the other plane's strength. - let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift; - let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift; - let y_dir = if y_pri_strength != 0 { dir } else { 0 }; - let t = cdef_adjust_strength(y_pri_strength, var); - // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit. - if crate::envflags::env_flag!("EC_AV1_CDEF_DBG") { - eprintln!( - "EC_CDEF mi_r={mi_r} mi_c={mi_c} x={ox} y={oy} sidx={sidx} dir={dir} var={var} t={t} pri={y_pri_strength} sec={y_sec_strength} damp={damping}" - ); - } - let enable_primary = t != 0; - let enable_secondary = y_sec_strength != 0; - if (ox + 8 > frame_w || oy + 8 > frame_h) - && (enable_primary - || enable_secondary - || cdef.uv_pri_strength[sidx] != 0 - || cdef.uv_sec_strength[sidx] != 0) - { - CDEF_STRADDLE_UNITS.with(|c| c.set(c.get() + 1)); - } - if enable_primary || enable_secondary { - cdef_filter_block( - &win_y, - y, - ox, - oy, - 8, - 8, - t, - y_sec_strength, - y_dir, - damping, - damping, - enable_primary, - enable_secondary, - coeff_shift, fctx, - ); + // lane-filt1: every CDEF unit reads ONLY the pre-CDEF snapshots + // (`src_y`/`src_u`/`src_v`, immutable here) and writes its own 8x8 luma / + // 4x4 chroma square, so units are independent. Bands are mi ROW bands (2 + // mi = 8 luma rows, 4 chroma rows), which makes each band's writes a + // disjoint row range of all three planes. + let (sy, su, sv) = ( + crate::par::Shared::new(y), + crate::par::Shared::new(u), + crate::par::Shared::new(v), + ); + let mi_rows = skip_grid.mi_rows; + let cbands: Vec<(usize, usize)> = crate::par::bands(mi_rows.div_ceil(2), crate::par::filter_threads()) + .into_iter() + .map(|(a, b)| (a * 2, (b * 2).min(mi_rows))) + .collect(); + crate::par::run_bands(&cbands, fctx, |r_lo, r_hi, fctx| { + // SAFETY: this band writes only the plane rows its own mi rows cover, + // disjoint from every other band's (see `Shared`). + #[allow(unsafe_code)] + let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) }; + // One scratch window per plane kind, reused by every unit (8x8 luma and + // 4x4 chroma, each grown by the [`CDEF_BORDER`] tap ring). + let mut win_y = [0i32; (8 + 2 * CDEF_BORDER) * (8 + 2 * CDEF_BORDER)]; + let mut win_uv = [0i32; (4 + 2 * CDEF_BORDER) * (4 + 2 * CDEF_BORDER)]; + let mut mi_r = r_lo; + while mi_r < r_hi { + let mut mi_c = 0usize; + while mi_c < skip_grid.mi_cols { + if skip_grid.is_skip_txfm(mi_r, mi_c) { + CDEF_SKIPPED_UNITS.with(|c| c.set(c.get() + 1)); } - - let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift; - let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift; - let uv_dir = if t_uv != 0 { dir } else { 0 }; - let enable_primary_uv = t_uv != 0; - let enable_secondary_uv = uv_sec_strength != 0; - if enable_primary_uv || enable_secondary_uv { - let (cox, coy) = (ox / 2, oy / 2); - for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] { - let (tw, th) = (plane.true_width, plane.true_height); - let stride = plane.width; - cdef_gather(src_p, stride, tw, th, cox, coy, 4, 4, &mut win_uv); + if !skip_grid.is_skip_txfm(mi_r, mi_c) { + let sidx = strength_idx(mi_r, mi_c); + let (ox, oy) = (mi_c * 4, mi_r * 4); + // Nothing to do for this unit at all: the direction search is + // only ever consumed through a strength, so a unit whose four + // strengths are zero never needs its 8x8 window gathered. + if cdef.y_pri_strength[sidx] == 0 + && cdef.y_sec_strength[sidx] == 0 + && cdef.uv_pri_strength[sidx] == 0 + && cdef.uv_sec_strength[sidx] == 0 + { + mi_c += 2; + continue; + } + let (y_stride, y_true_w, y_true_h) = (y.width, y.true_width, y.true_height); + cdef_gather(&src_y, y_stride, y_true_w, y_true_h, ox, oy, 8, 8, &mut win_y); + let sample_y = |r: i32, c: i32| -> i32 { + win_y[(r + CDEF_BORDER as i32) as usize * (8 + 2 * CDEF_BORDER) + + (c + CDEF_BORDER as i32) as usize] + }; + // lane-cdef r1: the direction search reads the SAME padded + // block the taps do -- libaom runs `cdef_find_dir` on the + // prepared filter block (`cdef_block.c:296-320` over + // `cdef_prepare_fb`'s buffer, `cdef.c:249-256`), whose columns + // and rows past the mi-rounded frame extent are CDEF_VERY_LARGE. + // Clamping to the last real sample instead made every straddling + // edge 8x8 (odd `mi_cols`/`mi_rows`) pick a different var, hence + // a different `adjust_strength`, hence a +-1 band at the crop edge. + let (dir, var) = cdef_find_dir(coeff_shift, |r, c| sample_y(r as i32, c as i32)); + + // libaom `av1_cdef_filter_fb` passes `pri_strength ? dir : 0` + // -- each plane zeroes the shared direction when *its own* + // frame-level primary strength is 0, independent of the + // per-block adjusted `t` and of the other plane's strength. + let y_pri_strength = i32::from(cdef.y_pri_strength[sidx]) << coeff_shift; + let y_sec_strength = i32::from(cdef.y_sec_strength[sidx]) << coeff_shift; + let y_dir = if y_pri_strength != 0 { dir } else { 0 }; + let t = cdef_adjust_strength(y_pri_strength, var); + // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit. + if crate::envflags::env_flag!("EC_AV1_CDEF_DBG") { + eprintln!( + "EC_CDEF mi_r={mi_r} mi_c={mi_c} x={ox} y={oy} sidx={sidx} dir={dir} var={var} t={t} pri={y_pri_strength} sec={y_sec_strength} damp={damping}" + ); + } + let enable_primary = t != 0; + let enable_secondary = y_sec_strength != 0; + if (ox + 8 > frame_w || oy + 8 > frame_h) + && (enable_primary + || enable_secondary + || cdef.uv_pri_strength[sidx] != 0 + || cdef.uv_sec_strength[sidx] != 0) + { + CDEF_STRADDLE_UNITS.with(|c| c.set(c.get() + 1)); + } + if enable_primary || enable_secondary { cdef_filter_block( - &win_uv, - plane, - cox, - coy, - 4, - 4, - t_uv, - uv_sec_strength, - uv_dir, - damping_uv, - damping_uv, - enable_primary_uv, - enable_secondary_uv, + &win_y, + y, + ox, + oy, + 8, + 8, + t, + y_sec_strength, + y_dir, + damping, + damping, + enable_primary, + enable_secondary, coeff_shift, fctx, ); } + + let t_uv = i32::from(cdef.uv_pri_strength[sidx]) << coeff_shift; + let uv_sec_strength = i32::from(cdef.uv_sec_strength[sidx]) << coeff_shift; + let uv_dir = if t_uv != 0 { dir } else { 0 }; + let enable_primary_uv = t_uv != 0; + let enable_secondary_uv = uv_sec_strength != 0; + if enable_primary_uv || enable_secondary_uv { + let (cox, coy) = (ox / 2, oy / 2); + for (plane, src_p) in [(&mut *u, &src_u), (&mut *v, &src_v)] { + let (tw, th) = (plane.true_width, plane.true_height); + let stride = plane.width; + cdef_gather(src_p, stride, tw, th, cox, coy, 4, 4, &mut win_uv); + cdef_filter_block( + &win_uv, + plane, + cox, + coy, + 4, + 4, + t_uv, + uv_sec_strength, + uv_dir, + damping_uv, + damping_uv, + enable_primary_uv, + enable_secondary_uv, + coeff_shift, fctx, + ); + } + } } + mi_c += 2; } - mi_c += 2; - } mi_r += 2; - } + } + }); scratch_return(src_y); scratch_return(src_u); scratch_return(src_v); diff --git a/crates/ec-av1/src/film_grain.rs b/crates/ec-av1/src/film_grain.rs index 8bfba7b2..629e93fb 100644 --- a/crates/ec-av1/src/film_grain.rs +++ b/crates/ec-av1/src/film_grain.rs @@ -879,342 +879,374 @@ pub(crate) fn apply_grain( let overlap = fg.overlap_flag; - let mut y_line_buf = vec![0i32; (y_stride * 2).max(1) as usize]; - let mut cb_line_buf = vec![0i32; c_stride.max(1) as usize]; - let mut cr_line_buf = vec![0i32; c_stride.max(1) as usize]; - let mut y_col_buf = vec![0i32; ((LUMA_SUBBLOCK + 2) * 2) as usize]; - let mut cb_col_buf = vec![0i32; (CHROMA_SUBBLOCK + 1) as usize]; - let mut cr_col_buf = vec![0i32; (CHROMA_SUBBLOCK + 1) as usize]; + // lane-filt1: 32-pixel block ROWS are the parallel axis. A row's noise + // offsets come from `Rng::line(y * 2, grain_seed)` -- a function of the + // row and the frame seed alone -- and a row writes only luma rows + // `y*2 .. y*2+31` (chroma `y .. y+15`), so rows are write-disjoint. The + // one carry ACROSS rows is `*_line_buf` (the row above's bottom lines, + // blended into this row's top lines when `overlap_flag`), and its final + // content is written by that row's own blocks out of the grain templates + // and `*_col_buf` -- never out of the row above it. So a band replays + // exactly ONE preceding row with its pixel writes suppressed (`prelude`) + // to rebuild the line buffers, then codes its own rows exactly as the + // single-threaded walk does. + let row_step = LUMA_SUBBLOCK >> 1; + let nrows = ((height / 2).max(0) as usize).div_ceil(row_step as usize); + let so = crate::par::Shared::new(&mut out); + let gbands = crate::par::bands(nrows, crate::par::filter_threads()); + crate::par::run_bands(&gbands, fctx, |b_lo, b_hi, fctx| { + // SAFETY: this band writes only the picture rows its own block rows + // cover, disjoint from every other band's. + #[allow(unsafe_code)] + let out = unsafe { so.get() }; + let y_lo = (b_lo * row_step as usize) as i32; + let y_hi = ((b_hi * row_step as usize) as i32).min(height / 2); + let y_first = if b_lo > 0 { y_lo - row_step } else { y_lo }; + let mut y_line_buf = vec![0i32; (y_stride * 2).max(1) as usize]; + let mut cb_line_buf = vec![0i32; c_stride.max(1) as usize]; + let mut cr_line_buf = vec![0i32; c_stride.max(1) as usize]; + let mut y_col_buf = vec![0i32; ((LUMA_SUBBLOCK + 2) * 2) as usize]; + let mut cb_col_buf = vec![0i32; (CHROMA_SUBBLOCK + 1) as usize]; + let mut cr_col_buf = vec![0i32; (CHROMA_SUBBLOCK + 1) as usize]; - let mut y = 0; - while y < height / 2 { - let mut row_rng = Rng::line(y * 2, fg.grain_seed); - let mut x = 0; - while x < width / 2 { - let raw = row_rng.get(8); - let offset_x = (raw >> 4) & 15; - let offset_y = raw & 15; + let mut y = y_first; + while y < y_hi { + let prelude = y < y_lo; + let mut row_rng = Rng::line(y * 2, fg.grain_seed); + let mut x = 0; + while x < width / 2 { + let raw = row_rng.get(8); + let offset_x = (raw >> 4) & 15; + let offset_y = raw & 15; - let luma_off_y = LEFT_PAD + 2 * AR_PADDING + (offset_y << 1); - let luma_off_x = TOP_PAD + 2 * AR_PADDING + (offset_x << 1); - let chroma_off_y = TOP_PAD + AR_PADDING + offset_y; - let chroma_off_x = LEFT_PAD + AR_PADDING + offset_x; + let luma_off_y = LEFT_PAD + 2 * AR_PADDING + (offset_y << 1); + let luma_off_x = TOP_PAD + 2 * AR_PADDING + (offset_x << 1); + let chroma_off_y = TOP_PAD + AR_PADDING + offset_y; + let chroma_off_x = LEFT_PAD + AR_PADDING + offset_x; - if overlap && x != 0 { - let h_count = (LUMA_SUBBLOCK + 2).min(height - (y << 1)); - ver_overlap_inplace( - &mut y_col_buf, - 2, - 0, - 0, - &luma_template, - LUMA_BLOCK_W, - luma_off_y, - luma_off_x, - 2, - h_count, fctx, - ); - let hc_count = (CHROMA_SUBBLOCK + 1).min((height - (y << 1)) >> 1); - ver_overlap_inplace( - &mut cb_col_buf, - 1, - 0, - 0, - &cb_template, - CHROMA_BLOCK_W, - chroma_off_y, - chroma_off_x, - 1, - hc_count, fctx, - ); - ver_overlap_inplace( - &mut cr_col_buf, - 1, - 0, - 0, - &cr_template, - CHROMA_BLOCK_W, - chroma_off_y, - chroma_off_x, - 1, - hc_count, fctx, - ); + if overlap && x != 0 { + let h_count = (LUMA_SUBBLOCK + 2).min(height - (y << 1)); + ver_overlap_inplace( + &mut y_col_buf, + 2, + 0, + 0, + &luma_template, + LUMA_BLOCK_W, + luma_off_y, + luma_off_x, + 2, + h_count, fctx, + ); + let hc_count = (CHROMA_SUBBLOCK + 1).min((height - (y << 1)) >> 1); + ver_overlap_inplace( + &mut cb_col_buf, + 1, + 0, + 0, + &cb_template, + CHROMA_BLOCK_W, + chroma_off_y, + chroma_off_x, + 1, + hc_count, fctx, + ); + ver_overlap_inplace( + &mut cr_col_buf, + 1, + 0, + 0, + &cr_template, + CHROMA_BLOCK_W, + chroma_off_y, + chroma_off_x, + 1, + hc_count, fctx, + ); - let i = if y != 0 { 1 } else { 0 }; - add_noise_to_block( - fg, - mc_identity, - &scaling_y, - &scaling_cb, - &scaling_cr, - &mut out, - (y + i) << 1, - x << 1, - &y_col_buf, - 2, - i * 2, - 0, - &cb_col_buf, - &cr_col_buf, - 1, - i, - 0, - (LUMA_SUBBLOCK >> 1).min(height / 2 - y) - i, - 1, fctx, - ); - } + let i = if y != 0 { 1 } else { 0 }; + if !prelude { + add_noise_to_block( + fg, + mc_identity, + &scaling_y, + &scaling_cb, + &scaling_cr, + &mut *out, + (y + i) << 1, + x << 1, + &y_col_buf, + 2, + i * 2, + 0, + &cb_col_buf, + &cr_col_buf, + 1, + i, + 0, + (LUMA_SUBBLOCK >> 1).min(height / 2 - y) - i, + 1, fctx, + ); + } + } - if overlap && y != 0 { - if x != 0 { + if overlap && y != 0 { + if x != 0 { + hor_overlap_inplace( + &mut y_line_buf, + y_stride, + 0, + x << 1, + &y_col_buf, + 2, + 0, + 0, + 2, + 2, fctx, + ); + hor_overlap_inplace( + &mut cb_line_buf, + c_stride, + 0, + x, + &cb_col_buf, + 1, + 0, + 0, + 1, + 1, fctx, + ); + hor_overlap_inplace( + &mut cr_line_buf, + c_stride, + 0, + x, + &cr_col_buf, + 1, + 0, + 0, + 1, + 1, fctx, + ); + } + let lcol0 = if x != 0 { (x + 1) << 1 } else { 0 }; + let ccol0 = if x != 0 { x + 1 } else { 0 }; + let lw = (LUMA_SUBBLOCK - (if x != 0 { 2 } else { 0 })).min(width - lcol0); hor_overlap_inplace( &mut y_line_buf, y_stride, 0, - x << 1, - &y_col_buf, - 2, - 0, - 0, - 2, + lcol0, + &luma_template, + LUMA_BLOCK_W, + luma_off_y, + luma_off_x + if x != 0 { 2 } else { 0 }, + lw, 2, fctx, ); + let cw = (CHROMA_SUBBLOCK - (if x != 0 { 1 } else { 0 })).min((width - lcol0) >> 1); hor_overlap_inplace( &mut cb_line_buf, c_stride, 0, - x, - &cb_col_buf, - 1, - 0, - 0, - 1, + ccol0, + &cb_template, + CHROMA_BLOCK_W, + chroma_off_y, + chroma_off_x + if x != 0 { 1 } else { 0 }, + cw, 1, fctx, ); hor_overlap_inplace( &mut cr_line_buf, c_stride, 0, - x, - &cr_col_buf, - 1, - 0, - 0, - 1, + ccol0, + &cr_template, + CHROMA_BLOCK_W, + chroma_off_y, + chroma_off_x + if x != 0 { 1 } else { 0 }, + cw, 1, fctx, ); - } - let lcol0 = if x != 0 { (x + 1) << 1 } else { 0 }; - let ccol0 = if x != 0 { x + 1 } else { 0 }; - let lw = (LUMA_SUBBLOCK - (if x != 0 { 2 } else { 0 })).min(width - lcol0); - hor_overlap_inplace( - &mut y_line_buf, - y_stride, - 0, - lcol0, - &luma_template, - LUMA_BLOCK_W, - luma_off_y, - luma_off_x + if x != 0 { 2 } else { 0 }, - lw, - 2, fctx, - ); - let cw = (CHROMA_SUBBLOCK - (if x != 0 { 1 } else { 0 })).min((width - lcol0) >> 1); - hor_overlap_inplace( - &mut cb_line_buf, - c_stride, - 0, - ccol0, - &cb_template, - CHROMA_BLOCK_W, - chroma_off_y, - chroma_off_x + if x != 0 { 1 } else { 0 }, - cw, - 1, fctx, - ); - hor_overlap_inplace( - &mut cr_line_buf, - c_stride, - 0, - ccol0, - &cr_template, - CHROMA_BLOCK_W, - chroma_off_y, - chroma_off_x + if x != 0 { 1 } else { 0 }, - cw, - 1, fctx, - ); - add_noise_to_block( - fg, - mc_identity, - &scaling_y, - &scaling_cb, - &scaling_cr, - &mut out, - y << 1, - x << 1, - &y_line_buf, - y_stride, - 0, - x << 1, - &cb_line_buf, - &cr_line_buf, - c_stride, - 0, - x, - 1, - (LUMA_SUBBLOCK >> 1).min(width / 2 - x), fctx, - ); - } + if !prelude { + add_noise_to_block( + fg, + mc_identity, + &scaling_y, + &scaling_cb, + &scaling_cr, + &mut *out, + y << 1, + x << 1, + &y_line_buf, + y_stride, + 0, + x << 1, + &cb_line_buf, + &cr_line_buf, + c_stride, + 0, + x, + 1, + (LUMA_SUBBLOCK >> 1).min(width / 2 - x), fctx, + ); + } + } - let i = if overlap && y != 0 { 1 } else { 0 }; - let j = if overlap && x != 0 { 1 } else { 0 }; - add_noise_to_block( - fg, - mc_identity, - &scaling_y, - &scaling_cb, - &scaling_cr, - &mut out, - (y + i) << 1, - (x + j) << 1, - &luma_template, - LUMA_BLOCK_W, - luma_off_y + (i << 1), - luma_off_x + (j << 1), - &cb_template, - &cr_template, - CHROMA_BLOCK_W, - chroma_off_y + i, - chroma_off_x + j, - (LUMA_SUBBLOCK >> 1).min(height / 2 - y) - i, - (LUMA_SUBBLOCK >> 1).min(width / 2 - x) - j, fctx, - ); + let i = if overlap && y != 0 { 1 } else { 0 }; + let j = if overlap && x != 0 { 1 } else { 0 }; + if !prelude { + add_noise_to_block( + fg, + mc_identity, + &scaling_y, + &scaling_cb, + &scaling_cr, + &mut *out, + (y + i) << 1, + (x + j) << 1, + &luma_template, + LUMA_BLOCK_W, + luma_off_y + (i << 1), + luma_off_x + (j << 1), + &cb_template, + &cr_template, + CHROMA_BLOCK_W, + chroma_off_y + i, + chroma_off_x + j, + (LUMA_SUBBLOCK >> 1).min(height / 2 - y) - i, + (LUMA_SUBBLOCK >> 1).min(width / 2 - x) - j, fctx, + ); + } - if overlap { - if x != 0 { + if overlap { + if x != 0 { + copy_area( + &mut y_line_buf, + y_stride, + 0, + x << 1, + &y_col_buf, + 2, + LUMA_SUBBLOCK, + 0, + 2, + 2, fctx, + ); + copy_area( + &mut cb_line_buf, + c_stride, + 0, + x, + &cb_col_buf, + 1, + CHROMA_SUBBLOCK, + 0, + 1, + 1, fctx, + ); + copy_area( + &mut cr_line_buf, + c_stride, + 0, + x, + &cr_col_buf, + 1, + CHROMA_SUBBLOCK, + 0, + 1, + 1, fctx, + ); + } + let lcol0 = if x != 0 { (x + 1) << 1 } else { 0 }; + let ccol0 = if x != 0 { x + 1 } else { 0 }; + let lcut = if x != 0 { 2 } else { 0 }; + let ccut = if x != 0 { 1 } else { 0 }; copy_area( &mut y_line_buf, y_stride, 0, - x << 1, - &y_col_buf, - 2, - LUMA_SUBBLOCK, - 0, - 2, + lcol0, + &luma_template, + LUMA_BLOCK_W, + luma_off_y + LUMA_SUBBLOCK, + luma_off_x + lcut, + LUMA_SUBBLOCK.min(width - (x << 1)) - lcut, 2, fctx, ); copy_area( &mut cb_line_buf, c_stride, 0, - x, - &cb_col_buf, - 1, - CHROMA_SUBBLOCK, - 0, - 1, + ccol0, + &cb_template, + CHROMA_BLOCK_W, + chroma_off_y + CHROMA_SUBBLOCK, + chroma_off_x + ccut, + CHROMA_SUBBLOCK.min((width - (x << 1)) >> 1) - ccut, 1, fctx, ); copy_area( &mut cr_line_buf, c_stride, 0, - x, - &cr_col_buf, + ccol0, + &cr_template, + CHROMA_BLOCK_W, + chroma_off_y + CHROMA_SUBBLOCK, + chroma_off_x + ccut, + CHROMA_SUBBLOCK.min((width - (x << 1)) >> 1) - ccut, + 1, fctx, + ); + + let h_count = (LUMA_SUBBLOCK + 2).min(height - (y << 1)); + copy_area( + &mut y_col_buf, + 2, + 0, + 0, + &luma_template, + LUMA_BLOCK_W, + luma_off_y, + luma_off_x + LUMA_SUBBLOCK, + 2, + h_count, fctx, + ); + let hc_count = (CHROMA_SUBBLOCK + 1).min((height - (y << 1)) >> 1); + copy_area( + &mut cb_col_buf, 1, - CHROMA_SUBBLOCK, 0, + 0, + &cb_template, + CHROMA_BLOCK_W, + chroma_off_y, + chroma_off_x + CHROMA_SUBBLOCK, 1, - 1, fctx, + hc_count, fctx, + ); + copy_area( + &mut cr_col_buf, + 1, + 0, + 0, + &cr_template, + CHROMA_BLOCK_W, + chroma_off_y, + chroma_off_x + CHROMA_SUBBLOCK, + 1, + hc_count, fctx, ); } - let lcol0 = if x != 0 { (x + 1) << 1 } else { 0 }; - let ccol0 = if x != 0 { x + 1 } else { 0 }; - let lcut = if x != 0 { 2 } else { 0 }; - let ccut = if x != 0 { 1 } else { 0 }; - copy_area( - &mut y_line_buf, - y_stride, - 0, - lcol0, - &luma_template, - LUMA_BLOCK_W, - luma_off_y + LUMA_SUBBLOCK, - luma_off_x + lcut, - LUMA_SUBBLOCK.min(width - (x << 1)) - lcut, - 2, fctx, - ); - copy_area( - &mut cb_line_buf, - c_stride, - 0, - ccol0, - &cb_template, - CHROMA_BLOCK_W, - chroma_off_y + CHROMA_SUBBLOCK, - chroma_off_x + ccut, - CHROMA_SUBBLOCK.min((width - (x << 1)) >> 1) - ccut, - 1, fctx, - ); - copy_area( - &mut cr_line_buf, - c_stride, - 0, - ccol0, - &cr_template, - CHROMA_BLOCK_W, - chroma_off_y + CHROMA_SUBBLOCK, - chroma_off_x + ccut, - CHROMA_SUBBLOCK.min((width - (x << 1)) >> 1) - ccut, - 1, fctx, - ); - let h_count = (LUMA_SUBBLOCK + 2).min(height - (y << 1)); - copy_area( - &mut y_col_buf, - 2, - 0, - 0, - &luma_template, - LUMA_BLOCK_W, - luma_off_y, - luma_off_x + LUMA_SUBBLOCK, - 2, - h_count, fctx, - ); - let hc_count = (CHROMA_SUBBLOCK + 1).min((height - (y << 1)) >> 1); - copy_area( - &mut cb_col_buf, - 1, - 0, - 0, - &cb_template, - CHROMA_BLOCK_W, - chroma_off_y, - chroma_off_x + CHROMA_SUBBLOCK, - 1, - hc_count, fctx, - ); - copy_area( - &mut cr_col_buf, - 1, - 0, - 0, - &cr_template, - CHROMA_BLOCK_W, - chroma_off_y, - chroma_off_x + CHROMA_SUBBLOCK, - 1, - hc_count, fctx, - ); + x += LUMA_SUBBLOCK >> 1; } - - x += LUMA_SUBBLOCK >> 1; + y += row_step; } - y += LUMA_SUBBLOCK >> 1; - } + }); + drop(so); out } diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index 270c8fb7..e7d61ba3 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -41,6 +41,7 @@ mod motion_field; pub mod msac; pub mod mvstack; pub mod obu; +mod par; pub mod quant; mod refusal_inventory; mod restoration; diff --git a/crates/ec-av1/src/par.rs b/crates/ec-av1/src/par.rs new file mode 100644 index 00000000..76419670 --- /dev/null +++ b/crates/ec-av1/src/par.rs @@ -0,0 +1,135 @@ +//! lane-filt1: in-frame parallelism for the post-decode filter chain +//! (deblock, CDEF, loop restoration, film grain). +//! +//! Every stage here is split along an axis whose per-band writes are +//! *disjoint* and whose reads come either from an immutable snapshot or from +//! the band's own pixels, so N bands reproduce the single-threaded output +//! byte for byte -- gated by +//! `a_real_stream_filters_identically_with_one_and_four_filter_threads`. +//! +//! Threading is opt-in: [`filter_threads`] is 1 unless `EC_AV1_FILTER_THREADS` +//! says otherwise, and at 1 band nothing is spawned at all (the work runs on +//! the calling thread, so every `thread_local!` gate counter in `decode.rs` +//! still sees it). Above 1, a worker's counter increments are lost -- which is +//! why the default stays 1 and every existing gate is unaffected. The knob +//! composes multiplicatively with `EC_AV1_THREADS` (frame workers), so the +//! product of the two is what must stay inside the core count. +//! +//! Measured on a 12-core box, `seg4k` (272 shown frames, interleaved medians +//! of 3, other lanes decoding alongside): 34.41 s at 1 filter thread, 30.04 s +//! at 2, 28.41 s at 4, 28.36 s at 6, 27.70 s at 8 -- i.e. the filter chain is +//! ~19% of frame time and 4 threads take most of what is there. Recommended: +//! `EC_AV1_FILTER_THREADS=4` with frame threading off, and the product with +//! `EC_AV1_THREADS` kept at or below the core count once it lands (e.g. 2 +//! frame workers x 4 filter threads on 12 cores). +#![allow(unsafe_code)] + +/// `EC_AV1_FILTER_THREADS`, the number of worker threads each in-frame filter +/// stage splits itself across (default 1 = single-threaded, the shipped +/// behaviour). Read once per process. +/// 0 = "not read yet"; the env read happens once and the value is a plain +/// atomic afterwards, so a test can flip it ([`set_filter_threads`]) without +/// touching the process environment. +static FILTER_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +pub(crate) fn filter_threads() -> usize { + match FILTER_THREADS.load(std::sync::atomic::Ordering::Relaxed) { + 0 => { + let n = crate::envflags::var("EC_AV1_FILTER_THREADS") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(1) + .clamp(1, 64); + FILTER_THREADS.store(n, std::sync::atomic::Ordering::Relaxed); + n + } + n => n, + } +} + +/// Test-only override of [`filter_threads`]. Process-global, so a gate using +/// it must hold `stream.rs`'s gate-counter lock (which also keeps the +/// counter-delta gates from decoding while the workers are on). +#[cfg(test)] +pub(crate) fn set_filter_threads(n: usize) { + FILTER_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed); +} + +/// Splits `units` work units into at most `threads` contiguous, non-empty +/// bands. The caller picks the unit so that a band boundary is always a legal +/// cut of its stage (16-pixel rows for the deblocker, 2 mi for CDEF, one +/// restoration-unit row for LR, one 32-pixel block row for film grain). +pub(crate) fn bands(units: usize, threads: usize) -> Vec<(usize, usize)> { + if units == 0 { + return Vec::new(); + } + let t = threads.clamp(1, units); + let per = units.div_ceil(t); + (0..t) + .map(|i| (i * per, ((i + 1) * per).min(units))) + .filter(|(a, b)| a < b) + .collect() +} + +/// A `&mut T` handed to several scoped workers that write provably disjoint +/// parts of it. +/// +/// corner-cut: the disjointness is proved by the caller's band arithmetic and +/// checked end-to-end by the 1-vs-4-thread byte-exact gate, not by the borrow +/// checker -- so Miri/stacked-borrows would flag the overlapping `&mut`s. The +/// upgrade path is per-stage `chunks_mut`/`split_at_mut` plumbing (an origin +/// offset through `filter_edge`, `cdef_filter_block`, +/// `filter_restoration_unit` and `add_noise_to_block`), which is a far larger +/// diff for the same output. +pub(crate) struct Shared<'a, T: ?Sized>(*mut T, std::marker::PhantomData<&'a mut T>); + +// SAFETY: `Shared` only ever hands out the pointer it was built from; sending +// it to a scoped thread is sending the `&mut T` the constructor consumed, and +// the bands each worker touches are disjoint. +unsafe impl Send for Shared<'_, T> {} +unsafe impl Sync for Shared<'_, T> {} + +impl Clone for Shared<'_, T> { + fn clone(&self) -> Self { + *self + } +} +impl Copy for Shared<'_, T> {} + +impl<'a, T: ?Sized> Shared<'a, T> { + pub(crate) fn new(v: &'a mut T) -> Self { + Self(v, std::marker::PhantomData) + } + + /// # Safety + /// The caller must touch only its own band, disjoint from every other + /// worker's, for as long as the returned reference lives. + pub(crate) unsafe fn get(&self) -> &mut T { + unsafe { &mut *self.0 } + } +} + +/// Runs `f(band_start, band_end, ctx)` once per band: band 0 on this thread +/// with the caller's own [`crate::decode::FrameCtx`], the rest on scoped +/// worker threads, each with its own filter-scope copy of it (`FrameCtx` is +/// `!Sync` by design). Nothing outlives the call. +#[inline] +pub(crate) fn run_bands(bands: &[(usize, usize)], fctx: &crate::decode::FrameCtx, f: F) +where + F: Fn(usize, usize, &crate::decode::FrameCtx) + Sync, +{ + match bands { + [] => {} + [(a, b)] => f(*a, *b, fctx), + [(a0, b0), rest @ ..] => { + std::thread::scope(|s| { + for &(a, b) in rest { + let ctx = crate::decode::filter_ctx_copy(fctx); + let f = &f; + s.spawn(move || f(a, b, &ctx)); + } + f(*a0, *b0, fctx); + }); + } + } +} diff --git a/crates/ec-av1/src/restoration.rs b/crates/ec-av1/src/restoration.rs index 1d4fb6da..50cde500 100644 --- a/crates/ec-av1/src/restoration.rs +++ b/crates/ec-av1/src/restoration.rs @@ -1074,8 +1074,13 @@ pub(crate) fn apply_loop_restoration_plane( } let voffset = 8u32 >> ss_y; let ext_size = (unit_size * 3) / 2; + // lane-filt1: the RU row walk is data-dependent (a short remainder is + // swallowed by the previous unit row), so resolve it into a row list + // first. Each row writes exactly `v_start..v_end` of `out` and the next + // row's `v_start` is this one's `v_end`, so row bands are disjoint; the + // reads are all from `cdef`/`deblocked`, immutable snapshots. + let mut rows: Vec<(u32, u32)> = Vec::new(); let mut y0 = 0u32; - let mut rrow = 0usize; while y0 < plane_h as u32 { let remaining_h = plane_h as u32 - y0; let uh = if remaining_h < ext_size { remaining_h } else { unit_size }; @@ -1084,35 +1089,46 @@ pub(crate) fn apply_loop_restoration_plane( if v_end < plane_h as u32 { v_end -= voffset; } - - let mut x0 = 0u32; - let mut rcol = 0usize; - while x0 < plane_w as u32 { - let remaining_w = plane_w as u32 - x0; - let uw = if remaining_w < ext_size { remaining_w } else { unit_size }; - let filter = grid.get(plane, rrow, rcol); - if filter != UnitFilter::None { - filter_restoration_unit( - out, - cdef, - deblocked, - stride, - plane_w, - plane_h, - x0 as usize, - (x0 + uw) as usize, - v_start as usize, - v_end as usize, - ss_y, - filter, fctx, - ); - } - x0 += uw; - rcol += 1; - } + rows.push((v_start, v_end)); y0 += uh; - rrow += 1; } + let rrow_count = rows.len(); + let so = crate::par::Shared::new(out); + let rbands = crate::par::bands(rrow_count, crate::par::filter_threads()); + crate::par::run_bands(&rbands, fctx, |r_lo, r_hi, fctx| { + // SAFETY: this band writes only the `out` rows its own RU rows cover. + #[allow(unsafe_code)] + let out = unsafe { so.get() }; + for rrow in r_lo..r_hi { + let (v_start, v_end) = rows[rrow]; + let mut x0 = 0u32; + let mut rcol = 0usize; + while x0 < plane_w as u32 { + let remaining_w = plane_w as u32 - x0; + let uw = if remaining_w < ext_size { remaining_w } else { unit_size }; + let filter = grid.get(plane, rrow, rcol); + if filter != UnitFilter::None { + filter_restoration_unit( + out, + cdef, + deblocked, + stride, + plane_w, + plane_h, + x0 as usize, + (x0 + uw) as usize, + v_start as usize, + v_end as usize, + ss_y, + filter, fctx, + ); + } + x0 += uw; + rcol += 1; + } + } + }); + let rrow = rrow_count; debug_assert_eq!(rrow, grid.vert_units[plane], "RU row walk must match RestorationGrid::new's count_units"); } diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 2ade4c0e..b751b4ac 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -5816,6 +5816,75 @@ mod tests { assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg"); } + /// lane-filt1: `EC_AV1_FILTER_THREADS` splits every in-frame filter stage + /// -- deblock (row bands for the vertical-edge pass, column bands for the + /// horizontal one), CDEF (mi row bands), loop restoration (RU row bands) + /// and film grain (32-pixel block rows) -- across scoped worker threads. + /// A split is only legal if it is BYTE-EXACT, so this gate decodes two + /// real aomenc streams at 1 and at 4 filter threads and compares every + /// output frame's three planes. + /// + /// Between them the fixtures fire all four stages, and the firing + /// counters are asserted rather than assumed (class `gate-blind-to-feature`): + /// `superres_alltools_sb128_320x180.obu` is the 10-bit CDEF + loop + /// restoration stream, `grain_cdef_lr_128x128.obu` a 128x128 + /// `--denoise-noise-level=25` stream whose frames carry film grain + /// parameters (small enough that 4 bands is one block row each, which is + /// what exercises the grain band's one-row `prelude` replay). + #[test] + fn a_real_stream_filters_identically_with_one_and_four_filter_threads() { + const NAME: &str = "a_real_stream_filters_identically_with_one_and_four_filter_threads"; + let _gate_lock = lock_gate_counters(); + for (fixture, wants_lr, wants_grain) in [ + ("superres_alltools_sb128_320x180.obu", true, false), + ("grain_cdef_lr_128x128.obu", false, true), + ] { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join(fixture); + let stream = std::fs::read(&path) + .unwrap_or_else(|e| panic!("{NAME}: reading {}: {e}", path.display())); + let before = ( + crate::decode::deblock_hits(), + crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(), + crate::film_grain::grain_hits(), + ); + crate::par::set_filter_threads(1); + let one = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => panic!("{NAME}: {fixture} refused at 1 filter thread: {e}"), + }; + let after = ( + crate::decode::deblock_hits(), + crate::restoration::wiener_hits() + crate::restoration::sgrproj_hits(), + crate::film_grain::grain_hits(), + ); + crate::par::set_filter_threads(4); + let four = match decode_stream(&stream) { + Ok(frames) => frames, + Err(e) => { + crate::par::set_filter_threads(1); + panic!("{NAME}: {fixture} refused at 4 filter threads: {e}") + } + }; + crate::par::set_filter_threads(1); + assert!(after.0 > before.0, "{NAME}: {fixture} deblocked no edge at all"); + if wants_lr { + assert!(after.1 > before.1, "{NAME}: {fixture} ran no restoration unit"); + } + if wants_grain { + assert!(after.2 > before.2, "{NAME}: {fixture} applied no film grain"); + } + assert_eq!(one.len(), four.len(), "{NAME}: {fixture} frame count"); + assert!(!one.is_empty(), "{NAME}: {fixture} decoded nothing"); + for (i, (a, b)) in one.iter().zip(four.iter()).enumerate() { + assert_eq!(a.y, b.y, "{NAME}: {fixture} frame {i} luma differs at 4 filter threads"); + assert_eq!(a.u, b.u, "{NAME}: {fixture} frame {i} U differs at 4 filter threads"); + assert_eq!(a.v, b.v, "{NAME}: {fixture} frame {i} V differs at 4 filter threads"); + } + } + } + /// lane-t900 r30b: `fixtures/superres_alltools_sb128_320x180.obu` is 10 /// frames of `--cpu-used=4 --sb-size=128 --superres-mode=1 /// --superres-denominator=12 --cq-level=32` with every tool aomenc turns