diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 3fd53460..c96801fc 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -19663,6 +19663,7 @@ fn pipe_run( sn: crate::par::Shared<'_, Neighbours>, cfg: PipeCfg<'_>, snap: &mut Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>, + lr_sync: Option<&PipeSync>, fctx: &crate::decode::FrameCtx, ) { // SAFETY: the frame thread parses (and reconstructs) bands the pipeline @@ -19678,6 +19679,9 @@ fn pipe_run( let nb = cfg.nbands; for k in 0..nb + 3 { if !sync.wait_for((k + 2).min(nb)) { + if let Some(ls) = lr_sync { + ls.close(nb, true); + } return; } if k < nb { @@ -19703,9 +19707,148 @@ fn pipe_run( ); } } + // lane-pipefilt2: CDEF bands `0..=k-3` are now complete -- release + // them to the loop restoration worker. + if let Some(ls) = lr_sync { + ls.note(k.saturating_sub(2)); + } + } + if let Some(ls) = lr_sync { + ls.close(nb, false); + } +} + +/// The pipeline's loop restoration worker, a second task alongside +/// [`pipe_run`]: restoration-unit row `r` writes `out` rows +/// `v_start..v_end`, reads post-CDEF rows only inside that span and the +/// post-deblock snapshot at most two rows past `v_end` (see +/// `restoration::lr_src_row`), so it is ready as soon as CDEF band +/// `(v_end - 1) / 64` is done -- `pipe_run` runs that band at its own +/// iteration `band + 3` and the snapshot band one iteration earlier, so the +/// snapshot condition `(v_end + 1) / 64 <= band + 1` is implied, the two row +/// indices being at most one band apart. Running it as its own worker (not +/// as a fourth step inside `pipe_run`'s loop) keeps it OFF the deblock/CDEF +/// critical path: serialised into that loop it measured ~1% slower than the +/// whole-frame form, which at least ran its RU rows across the filter pool. +#[allow(unsafe_code)] +fn pipe_run_lr( + sync: &PipeSync, + sy: crate::par::Shared<'_, PlaneBuf<'static>>, + su: crate::par::Shared<'_, PlaneBuf<'static>>, + sv: crate::par::Shared<'_, PlaneBuf<'static>>, + snap: crate::par::Shared<'_, Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>>, + cfg: LrCfg<'_>, + fctx: &crate::decode::FrameCtx, +) { + // SAFETY: this worker only reads bands `pipe_run` has finished filtering + // and writes its own `out` buffers; the final swap happens after the + // last CDEF band, which is `pipe_run`'s last plane write. + let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) }; + let snap = unsafe { snap.get() }; + let grid = unsafe { &*cfg.lr_grid }; + let (fw, fh) = (cfg.frame_w, cfg.frame_h); + let dims = [ + (fw, fh, 0u32, y.width, y.data.len()), + (fw.div_ceil(2), fh.div_ceil(2), 1, u.width, u.data.len()), + (fw.div_ceil(2), fh.div_ceil(2), 1, v.width, v.data.len()), + ]; + let mut planes: Vec = Vec::new(); + for (p, &(pw, ph, ss, stride, len)) in dims.iter().enumerate() { + let rows = crate::restoration::lr_unit_rows( + ph, + cfg.lr.loop_restoration_size[p], + ss, + cfg.lr.frame_restoration_type[p], + ); + if rows.is_empty() { + continue; + } + planes.push(LrPlane { p, out: scratch_sized(len), rows, next: 0, pw, ph, ss, stride }); + } + for band in 0..cfg.nbands { + if !sync.wait_for(band + 1) { + return; + } + let Some((sy2, su2, sv2)) = snap.as_ref() else { return }; + for lp in &mut planes { + let stripe = 64usize >> lp.ss; + let r_lo = lp.next; + while lp.next < lp.rows.len() && (lp.rows[lp.next].1 as usize - 1) / stripe <= band { + lp.next += 1; + } + if lp.next == r_lo { + continue; + } + let (src, deb) = match lp.p { + 0 => (&y.data, &sy2.data), + 1 => (&u.data, &su2.data), + _ => (&v.data, &sv2.data), + }; + crate::restoration::apply_loop_restoration_plane( + src, + deb, + lp.stride, + lp.pw, + lp.ph, + lp.ss, + cfg.lr.frame_restoration_type[lp.p], + cfg.lr.loop_restoration_size[lp.p], + grid, + lp.p, + &mut lp.out, + Some((r_lo, lp.next)), + fctx, + ); + } + } + // The RU rows partition `0..plane_h`; the mi-rounded rows below it are + // untouched by restoration and copied here, then the restored plane + // takes the picture's place (the whole-frame path's own final swap). + for mut lp in planes { + let buf: &mut PlaneBuf<'static> = match lp.p { + 0 => &mut *y, + 1 => &mut *u, + _ => &mut *v, + }; + let tail = lp.ph * lp.stride; + if tail < buf.data.len() { + lp.out[tail..].copy_from_slice(&buf.data[tail..]); + } + scratch_return( + std::mem::replace(&mut buf.data, std::borrow::Cow::Owned(lp.out)).into_owned(), + ); } } +/// Everything [`pipe_run_lr`] needs beyond the planes. +struct LrCfg<'a> { + lr: &'a LoopRestorationParams, + /// Sized once per frame by `RestorationGrid::new`; the parse thread is + /// many bands ahead of every unit this worker reads. + lr_grid: *const crate::restoration::RestorationGrid, + frame_w: usize, + frame_h: usize, + nbands: usize, +} + +// SAFETY: as `PipeCfg`'s -- a read-only view of a per-frame allocation. +#[allow(unsafe_code)] +unsafe impl Send for LrCfg<'_> {} + +/// One plane's pipelined loop restoration state (see [`pipe_run`]). +struct LrPlane { + p: usize, + /// The restored plane, built band by band and swapped in at the end. + out: Vec, + rows: Vec<(u32, u32)>, + /// The first RU row not yet restored. + next: usize, + pw: usize, + ph: usize, + ss: u32, + stride: usize, +} + /// The pipeline's handle on the frame thread: [`PipeGuard::note`] releases /// bands as reconstruction completes, [`PipeGuard::finish`] drains it, and /// `Drop` aborts it on any `?` out of the tile decoder (the worker holds raw @@ -19714,6 +19857,8 @@ struct PipeGuard<'a> { sync: std::sync::Arc, batch: Option>, nbands: usize, + /// The loop restoration worker's own gate, aborted with the first one. + lr_sync: Option>, } impl PipeGuard<'_> { @@ -19730,6 +19875,9 @@ impl PipeGuard<'_> { impl Drop for PipeGuard<'_> { fn drop(&mut self) { self.sync.close(self.nbands, true); + if let Some(ls) = &self.lr_sync { + ls.close(self.nbands, true); + } } } @@ -20002,7 +20150,7 @@ fn apply_loop_restoration( lr.loop_restoration_size[0], grid, 0, - &mut out, fctx, + &mut out, None, fctx, ); scratch_return(std::mem::replace(&mut y.data, std::borrow::Cow::Owned(out)).into_owned()); let mut out = scratch_empty(); @@ -20017,7 +20165,7 @@ fn apply_loop_restoration( lr.loop_restoration_size[1], grid, 1, - &mut out, fctx, + &mut out, None, fctx, ); scratch_return(std::mem::replace(&mut u.data, std::borrow::Cow::Owned(out)).into_owned()); let mut out = scratch_empty(); @@ -20032,7 +20180,7 @@ fn apply_loop_restoration( lr.loop_restoration_size[2], grid, 2, - &mut out, fctx, + &mut out, None, fctx, ); scratch_return(std::mem::replace(&mut v.data, std::borrow::Cow::Owned(out)).into_owned()); } @@ -32096,9 +32244,28 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( }; let ctx = crate::decode::filter_ctx_copy(fctx); let sync2 = std::sync::Arc::clone(&sync); + // lane-pipefilt2: loop restoration is a SECOND worker, chained one + // CDEF band behind the first (see `pipe_run_lr`). + let lr_sync = lr_active.then(|| std::sync::Arc::new(PipeSync::new())); + let lr_sync2 = lr_sync.clone(); + #[allow(unsafe_code)] + let ssnap = unsafe { crate::par::Shared::from_ptr(std::ptr::from_mut(&mut pipe_snap)) }; let snap = &mut pipe_snap; - batch.submit(move || pipe_run(&sync2, sy, su, sv, sn, cfg, snap, &ctx)); - PipeGuard { sync, batch: Some(batch), nbands } + batch.submit(move || { + pipe_run(&sync2, sy, su, sv, sn, cfg, snap, lr_sync2.as_deref(), &ctx) + }); + if let Some(ls) = lr_sync.clone() { + let lcfg = LrCfg { + lr, + lr_grid: std::ptr::from_mut(&mut lr_grid), + frame_w: frame_width as usize, + frame_h: frame_height as usize, + nbands, + }; + let ctx2 = crate::decode::filter_ctx_copy(fctx); + batch.submit(move || pipe_run_lr(&ls, sy, su, sv, ssnap, lcfg, &ctx2)); + } + PipeGuard { sync, batch: Some(batch), nbands, lr_sync } }); if !pipe_on && wave_stats() { PIPE_WHOLE.fetch_add(1, Relaxed); @@ -34716,10 +34883,15 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( crate::superres::note_upscaled_picture(); } if let Some((deblocked_y, deblocked_u, deblocked_v)) = &deblocked { - apply_loop_restoration( - &mut y, &mut u, &mut v, deblocked_y, deblocked_u, deblocked_v, lr, &lr_grid, - (lr_w, frame_height as usize), fctx, - ); + // lane-pipefilt2: the pipeline already restored every RU row on its + // way past it (its LR step runs in the same iteration as the CDEF + // band that completes the row's last line). + if !pipelined { + apply_loop_restoration( + &mut y, &mut u, &mut v, deblocked_y, deblocked_u, deblocked_v, lr, &lr_grid, + (lr_w, frame_height as usize), fctx, + ); + } } if let Some((db_y, db_u, db_v)) = deblocked { // LIFO pool: return in reverse so the next frame's `y`/`u`/`v` diff --git a/crates/ec-av1/src/restoration.rs b/crates/ec-av1/src/restoration.rs index 29e119d3..19488b21 100644 --- a/crates/ec-av1/src/restoration.rs +++ b/crates/ec-av1/src/restoration.rs @@ -1237,21 +1237,67 @@ pub(crate) fn apply_loop_restoration_plane( // lane-perf6: the destination buffer, refilled from `cdef` here. It used // to be a fresh `cdef.to_vec()` per plane per frame -- a multi-megabyte // allocation whose every page then faulted in on first touch. - out: &mut Vec, fctx: &crate::decode::FrameCtx, + out: &mut Vec, + // lane-pipefilt2: `Some((r_lo, r_hi))` restricts the call to those RU + // ROWS, for the pipeline, which runs loop restoration band by band + // behind CDEF. `out` is then the caller's, already sized, and only this + // range's rows are refilled from `cdef` (the rows below `plane_h` are + // the caller's own tail copy). `None` is the whole-plane form. + rrows: Option<(usize, usize)>, + fctx: &crate::decode::FrameCtx, ) { - out.clear(); - out.extend_from_slice(cdef); - if ftype == RestorationType::None || unit_size == 0 { + let rows = lr_unit_rows(plane_h, unit_size, ss_y, ftype); + let Some((r_lo, r_hi)) = rrows else { + out.clear(); + out.extend_from_slice(cdef); + if rows.is_empty() { + return; + } + let so = crate::par::Shared::new(out); + let rbands = crate::par::bands(rows.len(), 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 { + lr_unit_row( + out, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, + plane, rrow, &rows, fctx, + ); + } + }); + debug_assert_eq!(rows.len(), grid.vert_units[plane], "RU row walk must match RestorationGrid::new's count_units"); return; + }; + for rrow in r_lo..r_hi.min(rows.len()) { + let (v_start, v_end) = rows[rrow]; + let (a, b) = (v_start as usize * stride, v_end as usize * stride); + out[a..b].copy_from_slice(&cdef[a..b]); + lr_unit_row( + out, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, plane, rrow, + &rows, fctx, + ); + } +} + +/// One plane's restoration-unit ROW walk, resolved to each row's `out` write +/// span `v_start..v_end`. The walk is data-dependent (a short remainder is +/// swallowed by the previous unit row), so both callers resolve it into this +/// list first: the next row's `v_start` is this one's `v_end`, so the spans +/// partition `0..plane_h` and row bands are disjoint. Empty when the plane +/// restores nothing. +pub(crate) fn lr_unit_rows( + plane_h: usize, + unit_size: u32, + ss_y: u32, + ftype: RestorationType, +) -> Vec<(u32, u32)> { + let mut rows: Vec<(u32, u32)> = Vec::new(); + if ftype == RestorationType::None || unit_size == 0 { + return rows; } 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; while y0 < plane_h as u32 { let remaining_h = plane_h as u32 - y0; @@ -1264,44 +1310,54 @@ pub(crate) fn apply_loop_restoration_plane( rows.push((v_start, v_end)); y0 += uh; } - 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; - } + rows +} + +/// The restoration units of one RU row, filtered into `out`. Reads only +/// `cdef`/`deblocked`, writes only this row's `v_start..v_end` span. +#[allow(clippy::too_many_arguments)] +fn lr_unit_row( + out: &mut [u16], + cdef: &[u16], + deblocked: &[u16], + stride: usize, + plane_w: usize, + plane_h: usize, + ss_y: u32, + unit_size: u32, + grid: &RestorationGrid, + plane: usize, + rrow: usize, + rows: &[(u32, u32)], + fctx: &crate::decode::FrameCtx, +) { + let ext_size = (unit_size * 3) / 2; + 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, + ); } - }); - let rrow = rrow_count; - debug_assert_eq!(rrow, grid.vert_units[plane], "RU row walk must match RestorationGrid::new's count_units"); + x0 += uw; + rcol += 1; + } } #[cfg(test)]