forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-pipefilt2' (69fbe27b): loop restoration pipelined as a second filter-pool worker one CDEF band behind (RU row ready when CDEF band (v_end-1)/64 is done); byte-exact on 16 gate hashes + 6 film cuts; -3% wall at one frame thread, flat at sixteen

Browse files at this commit

c604fcdcd083c48212bb3e8f56c48edf7b5f502aAhmet Kaan GümüşParent: 551e13eeca8ad9
crates/ec-av1/src/decode.rsmodified+181 -9
@@ -19663,6 +19663,7 @@ fn pipe_run(
19663 sn: crate::par::Shared<'_, Neighbours>,19663 sn: crate::par::Shared<'_, Neighbours>,
19664 cfg: PipeCfg<'_>,19664 cfg: PipeCfg<'_>,
19665 snap: &mut Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,19665 snap: &mut Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
19666+ lr_sync: Option<&PipeSync>,
19666 fctx: &crate::decode::FrameCtx,19667 fctx: &crate::decode::FrameCtx,
19667 ) {19668 ) {
19668 // SAFETY: the frame thread parses (and reconstructs) bands the pipeline19669 // SAFETY: the frame thread parses (and reconstructs) bands the pipeline
@@ -19678,6 +19679,9 @@ fn pipe_run(
19678 let nb = cfg.nbands;19679 let nb = cfg.nbands;
19679 for k in 0..nb + 3 {19680 for k in 0..nb + 3 {
19680 if !sync.wait_for((k + 2).min(nb)) {19681 if !sync.wait_for((k + 2).min(nb)) {
19682+ if let Some(ls) = lr_sync {
19683+ ls.close(nb, true);
19684+ }
19681 return;19685 return;
19682 }19686 }
19683 if k < nb {19687 if k < nb {
@@ -19703,9 +19707,148 @@ fn pipe_run(
19703 );19707 );
19704 }19708 }
19705 }19709 }
19710+ // lane-pipefilt2: CDEF bands `0..=k-3` are now complete -- release
19711+ // them to the loop restoration worker.
19712+ if let Some(ls) = lr_sync {
19713+ ls.note(k.saturating_sub(2));
19714+ }
19715+ }
19716+ if let Some(ls) = lr_sync {
19717+ ls.close(nb, false);
19718+ }
19719+}
19720+
19721+/// The pipeline's loop restoration worker, a second task alongside
19722+/// [`pipe_run`]: restoration-unit row `r` writes `out` rows
19723+/// `v_start..v_end`, reads post-CDEF rows only inside that span and the
19724+/// post-deblock snapshot at most two rows past `v_end` (see
19725+/// `restoration::lr_src_row`), so it is ready as soon as CDEF band
19726+/// `(v_end - 1) / 64` is done -- `pipe_run` runs that band at its own
19727+/// iteration `band + 3` and the snapshot band one iteration earlier, so the
19728+/// snapshot condition `(v_end + 1) / 64 <= band + 1` is implied, the two row
19729+/// indices being at most one band apart. Running it as its own worker (not
19730+/// as a fourth step inside `pipe_run`'s loop) keeps it OFF the deblock/CDEF
19731+/// critical path: serialised into that loop it measured ~1% slower than the
19732+/// whole-frame form, which at least ran its RU rows across the filter pool.
19733+#[allow(unsafe_code)]
19734+fn pipe_run_lr(
19735+ sync: &PipeSync,
19736+ sy: crate::par::Shared<'_, PlaneBuf<'static>>,
19737+ su: crate::par::Shared<'_, PlaneBuf<'static>>,
19738+ sv: crate::par::Shared<'_, PlaneBuf<'static>>,
19739+ snap: crate::par::Shared<'_, Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>>,
19740+ cfg: LrCfg<'_>,
19741+ fctx: &crate::decode::FrameCtx,
19742+) {
19743+ // SAFETY: this worker only reads bands `pipe_run` has finished filtering
19744+ // and writes its own `out` buffers; the final swap happens after the
19745+ // last CDEF band, which is `pipe_run`'s last plane write.
19746+ let (y, u, v) = unsafe { (sy.get(), su.get(), sv.get()) };
19747+ let snap = unsafe { snap.get() };
19748+ let grid = unsafe { &*cfg.lr_grid };
19749+ let (fw, fh) = (cfg.frame_w, cfg.frame_h);
19750+ let dims = [
19751+ (fw, fh, 0u32, y.width, y.data.len()),
19752+ (fw.div_ceil(2), fh.div_ceil(2), 1, u.width, u.data.len()),
19753+ (fw.div_ceil(2), fh.div_ceil(2), 1, v.width, v.data.len()),
19754+ ];
19755+ let mut planes: Vec<LrPlane> = Vec::new();
19756+ for (p, &(pw, ph, ss, stride, len)) in dims.iter().enumerate() {
19757+ let rows = crate::restoration::lr_unit_rows(
19758+ ph,
19759+ cfg.lr.loop_restoration_size[p],
19760+ ss,
19761+ cfg.lr.frame_restoration_type[p],
19762+ );
19763+ if rows.is_empty() {
19764+ continue;
19765+ }
19766+ planes.push(LrPlane { p, out: scratch_sized(len), rows, next: 0, pw, ph, ss, stride });
19767+ }
19768+ for band in 0..cfg.nbands {
19769+ if !sync.wait_for(band + 1) {
19770+ return;
19771+ }
19772+ let Some((sy2, su2, sv2)) = snap.as_ref() else { return };
19773+ for lp in &mut planes {
19774+ let stripe = 64usize >> lp.ss;
19775+ let r_lo = lp.next;
19776+ while lp.next < lp.rows.len() && (lp.rows[lp.next].1 as usize - 1) / stripe <= band {
19777+ lp.next += 1;
19778+ }
19779+ if lp.next == r_lo {
19780+ continue;
19781+ }
19782+ let (src, deb) = match lp.p {
19783+ 0 => (&y.data, &sy2.data),
19784+ 1 => (&u.data, &su2.data),
19785+ _ => (&v.data, &sv2.data),
19786+ };
19787+ crate::restoration::apply_loop_restoration_plane(
19788+ src,
19789+ deb,
19790+ lp.stride,
19791+ lp.pw,
19792+ lp.ph,
19793+ lp.ss,
19794+ cfg.lr.frame_restoration_type[lp.p],
19795+ cfg.lr.loop_restoration_size[lp.p],
19796+ grid,
19797+ lp.p,
19798+ &mut lp.out,
19799+ Some((r_lo, lp.next)),
19800+ fctx,
19801+ );
19802+ }
19803+ }
19804+ // The RU rows partition `0..plane_h`; the mi-rounded rows below it are
19805+ // untouched by restoration and copied here, then the restored plane
19806+ // takes the picture's place (the whole-frame path's own final swap).
19807+ for mut lp in planes {
19808+ let buf: &mut PlaneBuf<'static> = match lp.p {
19809+ 0 => &mut *y,
19810+ 1 => &mut *u,
19811+ _ => &mut *v,
19812+ };
19813+ let tail = lp.ph * lp.stride;
19814+ if tail < buf.data.len() {
19815+ lp.out[tail..].copy_from_slice(&buf.data[tail..]);
19816+ }
19817+ scratch_return(
19818+ std::mem::replace(&mut buf.data, std::borrow::Cow::Owned(lp.out)).into_owned(),
19819+ );
19706 }19820 }
19707 }19821 }
19708 19822
19823+/// Everything [`pipe_run_lr`] needs beyond the planes.
19824+struct LrCfg<'a> {
19825+ lr: &'a LoopRestorationParams,
19826+ /// Sized once per frame by `RestorationGrid::new`; the parse thread is
19827+ /// many bands ahead of every unit this worker reads.
19828+ lr_grid: *const crate::restoration::RestorationGrid,
19829+ frame_w: usize,
19830+ frame_h: usize,
19831+ nbands: usize,
19832+}
19833+
19834+// SAFETY: as `PipeCfg`'s -- a read-only view of a per-frame allocation.
19835+#[allow(unsafe_code)]
19836+unsafe impl Send for LrCfg<'_> {}
19837+
19838+/// One plane's pipelined loop restoration state (see [`pipe_run`]).
19839+struct LrPlane {
19840+ p: usize,
19841+ /// The restored plane, built band by band and swapped in at the end.
19842+ out: Vec<u16>,
19843+ rows: Vec<(u32, u32)>,
19844+ /// The first RU row not yet restored.
19845+ next: usize,
19846+ pw: usize,
19847+ ph: usize,
19848+ ss: u32,
19849+ stride: usize,
19850+}
19851+
19709 /// The pipeline's handle on the frame thread: [`PipeGuard::note`] releases19852 /// The pipeline's handle on the frame thread: [`PipeGuard::note`] releases
19710 /// bands as reconstruction completes, [`PipeGuard::finish`] drains it, and19853 /// bands as reconstruction completes, [`PipeGuard::finish`] drains it, and
19711 /// `Drop` aborts it on any `?` out of the tile decoder (the worker holds raw19854 /// `Drop` aborts it on any `?` out of the tile decoder (the worker holds raw
@@ -19714,6 +19857,8 @@ struct PipeGuard<'a> {
19714 sync: std::sync::Arc<PipeSync>,19857 sync: std::sync::Arc<PipeSync>,
19715 batch: Option<crate::par::Batch<'a>>,19858 batch: Option<crate::par::Batch<'a>>,
19716 nbands: usize,19859 nbands: usize,
19860+ /// The loop restoration worker's own gate, aborted with the first one.
19861+ lr_sync: Option<std::sync::Arc<PipeSync>>,
19717 }19862 }
19718 19863
19719 impl PipeGuard<'_> {19864 impl PipeGuard<'_> {
@@ -19730,6 +19875,9 @@ impl PipeGuard<'_> {
19730 impl Drop for PipeGuard<'_> {19875 impl Drop for PipeGuard<'_> {
19731 fn drop(&mut self) {19876 fn drop(&mut self) {
19732 self.sync.close(self.nbands, true);19877 self.sync.close(self.nbands, true);
19878+ if let Some(ls) = &self.lr_sync {
19879+ ls.close(self.nbands, true);
19880+ }
19733 }19881 }
19734 }19882 }
19735 19883
@@ -20002,7 +20150,7 @@ fn apply_loop_restoration(
20002 lr.loop_restoration_size[0],20150 lr.loop_restoration_size[0],
20003 grid,20151 grid,
20004 0,20152 0,
20005- &mut out, fctx,20153+ &mut out, None, fctx,
20006 );20154 );
20007 scratch_return(std::mem::replace(&mut y.data, std::borrow::Cow::Owned(out)).into_owned());20155 scratch_return(std::mem::replace(&mut y.data, std::borrow::Cow::Owned(out)).into_owned());
20008 let mut out = scratch_empty();20156 let mut out = scratch_empty();
@@ -20017,7 +20165,7 @@ fn apply_loop_restoration(
20017 lr.loop_restoration_size[1],20165 lr.loop_restoration_size[1],
20018 grid,20166 grid,
20019 1,20167 1,
20020- &mut out, fctx,20168+ &mut out, None, fctx,
20021 );20169 );
20022 scratch_return(std::mem::replace(&mut u.data, std::borrow::Cow::Owned(out)).into_owned());20170 scratch_return(std::mem::replace(&mut u.data, std::borrow::Cow::Owned(out)).into_owned());
20023 let mut out = scratch_empty();20171 let mut out = scratch_empty();
@@ -20032,7 +20180,7 @@ fn apply_loop_restoration(
20032 lr.loop_restoration_size[2],20180 lr.loop_restoration_size[2],
20033 grid,20181 grid,
20034 2,20182 2,
20035- &mut out, fctx,20183+ &mut out, None, fctx,
20036 );20184 );
20037 scratch_return(std::mem::replace(&mut v.data, std::borrow::Cow::Owned(out)).into_owned());20185 scratch_return(std::mem::replace(&mut v.data, std::borrow::Cow::Owned(out)).into_owned());
20038 }20186 }
@@ -32096,9 +32244,28 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
32096 };32244 };
32097 let ctx = crate::decode::filter_ctx_copy(fctx);32245 let ctx = crate::decode::filter_ctx_copy(fctx);
32098 let sync2 = std::sync::Arc::clone(&sync);32246 let sync2 = std::sync::Arc::clone(&sync);
32247+ // lane-pipefilt2: loop restoration is a SECOND worker, chained one
32248+ // CDEF band behind the first (see `pipe_run_lr`).
32249+ let lr_sync = lr_active.then(|| std::sync::Arc::new(PipeSync::new()));
32250+ let lr_sync2 = lr_sync.clone();
32251+ #[allow(unsafe_code)]
32252+ let ssnap = unsafe { crate::par::Shared::from_ptr(std::ptr::from_mut(&mut pipe_snap)) };
32099 let snap = &mut pipe_snap;32253 let snap = &mut pipe_snap;
32100- batch.submit(move || pipe_run(&sync2, sy, su, sv, sn, cfg, snap, &ctx));32254+ batch.submit(move || {
32101- PipeGuard { sync, batch: Some(batch), nbands }32255+ pipe_run(&sync2, sy, su, sv, sn, cfg, snap, lr_sync2.as_deref(), &ctx)
32256+ });
32257+ if let Some(ls) = lr_sync.clone() {
32258+ let lcfg = LrCfg {
32259+ lr,
32260+ lr_grid: std::ptr::from_mut(&mut lr_grid),
32261+ frame_w: frame_width as usize,
32262+ frame_h: frame_height as usize,
32263+ nbands,
32264+ };
32265+ let ctx2 = crate::decode::filter_ctx_copy(fctx);
32266+ batch.submit(move || pipe_run_lr(&ls, sy, su, sv, ssnap, lcfg, &ctx2));
32267+ }
32268+ PipeGuard { sync, batch: Some(batch), nbands, lr_sync }
32102 });32269 });
32103 if !pipe_on && wave_stats() {32270 if !pipe_on && wave_stats() {
32104 PIPE_WHOLE.fetch_add(1, Relaxed);32271 PIPE_WHOLE.fetch_add(1, Relaxed);
@@ -34716,10 +34883,15 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34716 crate::superres::note_upscaled_picture();34883 crate::superres::note_upscaled_picture();
34717 }34884 }
34718 if let Some((deblocked_y, deblocked_u, deblocked_v)) = &deblocked {34885 if let Some((deblocked_y, deblocked_u, deblocked_v)) = &deblocked {
34719- apply_loop_restoration(34886+ // lane-pipefilt2: the pipeline already restored every RU row on its
34720- &mut y, &mut u, &mut v, deblocked_y, deblocked_u, deblocked_v, lr, &lr_grid,34887+ // way past it (its LR step runs in the same iteration as the CDEF
34721- (lr_w, frame_height as usize), fctx,34888+ // band that completes the row's last line).
34722- );34889+ if !pipelined {
34890+ apply_loop_restoration(
34891+ &mut y, &mut u, &mut v, deblocked_y, deblocked_u, deblocked_v, lr, &lr_grid,
34892+ (lr_w, frame_height as usize), fctx,
34893+ );
34894+ }
34723 }34895 }
34724 if let Some((db_y, db_u, db_v)) = deblocked {34896 if let Some((db_y, db_u, db_v)) = deblocked {
34725 // LIFO pool: return in reverse so the next frame's `y`/`u`/`v`34897 // LIFO pool: return in reverse so the next frame's `y`/`u`/`v`
crates/ec-av1/src/restoration.rsmodified+103 -47
@@ -1237,21 +1237,67 @@ pub(crate) fn apply_loop_restoration_plane(
1237 // lane-perf6: the destination buffer, refilled from `cdef` here. It used1237 // lane-perf6: the destination buffer, refilled from `cdef` here. It used
1238 // to be a fresh `cdef.to_vec()` per plane per frame -- a multi-megabyte1238 // to be a fresh `cdef.to_vec()` per plane per frame -- a multi-megabyte
1239 // allocation whose every page then faulted in on first touch.1239 // allocation whose every page then faulted in on first touch.
1240- out: &mut Vec<u16>, fctx: &crate::decode::FrameCtx,1240+ out: &mut Vec<u16>,
1241+ // lane-pipefilt2: `Some((r_lo, r_hi))` restricts the call to those RU
1242+ // ROWS, for the pipeline, which runs loop restoration band by band
1243+ // behind CDEF. `out` is then the caller's, already sized, and only this
1244+ // range's rows are refilled from `cdef` (the rows below `plane_h` are
1245+ // the caller's own tail copy). `None` is the whole-plane form.
1246+ rrows: Option<(usize, usize)>,
1247+ fctx: &crate::decode::FrameCtx,
1241 ) {1248 ) {
1242- out.clear();1249+ let rows = lr_unit_rows(plane_h, unit_size, ss_y, ftype);
1243- out.extend_from_slice(cdef);1250+ let Some((r_lo, r_hi)) = rrows else {
1244- if ftype == RestorationType::None || unit_size == 0 {1251+ out.clear();
1252+ out.extend_from_slice(cdef);
1253+ if rows.is_empty() {
1254+ return;
1255+ }
1256+ let so = crate::par::Shared::new(out);
1257+ let rbands = crate::par::bands(rows.len(), crate::par::filter_threads());
1258+ crate::par::run_bands(&rbands, fctx, |r_lo, r_hi, fctx| {
1259+ // SAFETY: this band writes only the `out` rows its own RU rows cover.
1260+ #[allow(unsafe_code)]
1261+ let out = unsafe { so.get() };
1262+ for rrow in r_lo..r_hi {
1263+ lr_unit_row(
1264+ out, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid,
1265+ plane, rrow, &rows, fctx,
1266+ );
1267+ }
1268+ });
1269+ debug_assert_eq!(rows.len(), grid.vert_units[plane], "RU row walk must match RestorationGrid::new's count_units");
1245 return;1270 return;
1271+ };
1272+ for rrow in r_lo..r_hi.min(rows.len()) {
1273+ let (v_start, v_end) = rows[rrow];
1274+ let (a, b) = (v_start as usize * stride, v_end as usize * stride);
1275+ out[a..b].copy_from_slice(&cdef[a..b]);
1276+ lr_unit_row(
1277+ out, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, plane, rrow,
1278+ &rows, fctx,
1279+ );
1280+ }
1281+}
1282+
1283+/// One plane's restoration-unit ROW walk, resolved to each row's `out` write
1284+/// span `v_start..v_end`. The walk is data-dependent (a short remainder is
1285+/// swallowed by the previous unit row), so both callers resolve it into this
1286+/// list first: the next row's `v_start` is this one's `v_end`, so the spans
1287+/// partition `0..plane_h` and row bands are disjoint. Empty when the plane
1288+/// restores nothing.
1289+pub(crate) fn lr_unit_rows(
1290+ plane_h: usize,
1291+ unit_size: u32,
1292+ ss_y: u32,
1293+ ftype: RestorationType,
1294+) -> Vec<(u32, u32)> {
1295+ let mut rows: Vec<(u32, u32)> = Vec::new();
1296+ if ftype == RestorationType::None || unit_size == 0 {
1297+ return rows;
1246 }1298 }
1247 let voffset = 8u32 >> ss_y;1299 let voffset = 8u32 >> ss_y;
1248 let ext_size = (unit_size * 3) / 2;1300 let ext_size = (unit_size * 3) / 2;
1249- // lane-filt1: the RU row walk is data-dependent (a short remainder is
1250- // swallowed by the previous unit row), so resolve it into a row list
1251- // first. Each row writes exactly `v_start..v_end` of `out` and the next
1252- // row's `v_start` is this one's `v_end`, so row bands are disjoint; the
1253- // reads are all from `cdef`/`deblocked`, immutable snapshots.
1254- let mut rows: Vec<(u32, u32)> = Vec::new();
1255 let mut y0 = 0u32;1301 let mut y0 = 0u32;
1256 while y0 < plane_h as u32 {1302 while y0 < plane_h as u32 {
1257 let remaining_h = plane_h as u32 - y0;1303 let remaining_h = plane_h as u32 - y0;
@@ -1264,44 +1310,54 @@ pub(crate) fn apply_loop_restoration_plane(
1264 rows.push((v_start, v_end));1310 rows.push((v_start, v_end));
1265 y0 += uh;1311 y0 += uh;
1266 }1312 }
1267- let rrow_count = rows.len();1313+ rows
1268- let so = crate::par::Shared::new(out);1314+}
1269- let rbands = crate::par::bands(rrow_count, crate::par::filter_threads());1315+
1270- crate::par::run_bands(&rbands, fctx, |r_lo, r_hi, fctx| {1316+/// The restoration units of one RU row, filtered into `out`. Reads only
1271- // SAFETY: this band writes only the `out` rows its own RU rows cover.1317+/// `cdef`/`deblocked`, writes only this row's `v_start..v_end` span.
1272- #[allow(unsafe_code)]1318+#[allow(clippy::too_many_arguments)]
1273- let out = unsafe { so.get() };1319+fn lr_unit_row(
1274- for rrow in r_lo..r_hi {1320+ out: &mut [u16],
1275- let (v_start, v_end) = rows[rrow];1321+ cdef: &[u16],
1276- let mut x0 = 0u32;1322+ deblocked: &[u16],
1277- let mut rcol = 0usize;1323+ stride: usize,
1278- while x0 < plane_w as u32 {1324+ plane_w: usize,
1279- let remaining_w = plane_w as u32 - x0;1325+ plane_h: usize,
1280- let uw = if remaining_w < ext_size { remaining_w } else { unit_size };1326+ ss_y: u32,
1281- let filter = grid.get(plane, rrow, rcol);1327+ unit_size: u32,
1282- if filter != UnitFilter::None {1328+ grid: &RestorationGrid,
1283- filter_restoration_unit(1329+ plane: usize,
1284- out,1330+ rrow: usize,
1285- cdef,1331+ rows: &[(u32, u32)],
1286- deblocked,1332+ fctx: &crate::decode::FrameCtx,
1287- stride,1333+) {
1288- plane_w,1334+ let ext_size = (unit_size * 3) / 2;
1289- plane_h,1335+ let (v_start, v_end) = rows[rrow];
1290- x0 as usize,1336+ let mut x0 = 0u32;
1291- (x0 + uw) as usize,1337+ let mut rcol = 0usize;
1292- v_start as usize,1338+ while x0 < plane_w as u32 {
1293- v_end as usize,1339+ let remaining_w = plane_w as u32 - x0;
1294- ss_y,1340+ let uw = if remaining_w < ext_size { remaining_w } else { unit_size };
1295- filter, fctx,1341+ let filter = grid.get(plane, rrow, rcol);
1296- );1342+ if filter != UnitFilter::None {
1297- }1343+ filter_restoration_unit(
1298- x0 += uw;1344+ out,
1299- rcol += 1;1345+ cdef,
1300- }1346+ deblocked,
1347+ stride,
1348+ plane_w,
1349+ plane_h,
1350+ x0 as usize,
1351+ (x0 + uw) as usize,
1352+ v_start as usize,
1353+ v_end as usize,
1354+ ss_y,
1355+ filter, fctx,
1356+ );
1301 }1357 }
1302- });1358+ x0 += uw;
1303- let rrow = rrow_count;1359+ rcol += 1;
1304- debug_assert_eq!(rrow, grid.vert_units[plane], "RU row walk must match RestorationGrid::new's count_units");1360+ }
1305 }1361 }
1306 1362
1307 #[cfg(test)]1363 #[cfg(test)]