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(
1966319663 sn: crate::par::Shared<'_, Neighbours>,
1966419664 cfg: PipeCfg<'_>,
1966519665 snap: &mut Option<(PlaneBuf<'static>, PlaneBuf<'static>, PlaneBuf<'static>)>,
19666+ lr_sync: Option<&PipeSync>,
1966619667 fctx: &crate::decode::FrameCtx,
1966719668 ) {
1966819669 // SAFETY: the frame thread parses (and reconstructs) bands the pipeline
@@ -19678,6 +19679,9 @@ fn pipe_run(
1967819679 let nb = cfg.nbands;
1967919680 for k in 0..nb + 3 {
1968019681 if !sync.wait_for((k + 2).min(nb)) {
19682+ if let Some(ls) = lr_sync {
19683+ ls.close(nb, true);
19684+ }
1968119685 return;
1968219686 }
1968319687 if k < nb {
@@ -19703,9 +19707,148 @@ fn pipe_run(
1970319707 );
1970419708 }
1970519709 }
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+ );
1970619820 }
1970719821 }
1970819822
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+
1970919852 /// The pipeline's handle on the frame thread: [`PipeGuard::note`] releases
1971019853 /// bands as reconstruction completes, [`PipeGuard::finish`] drains it, and
1971119854 /// `Drop` aborts it on any `?` out of the tile decoder (the worker holds raw
@@ -19714,6 +19857,8 @@ struct PipeGuard<'a> {
1971419857 sync: std::sync::Arc<PipeSync>,
1971519858 batch: Option<crate::par::Batch<'a>>,
1971619859 nbands: usize,
19860+ /// The loop restoration worker's own gate, aborted with the first one.
19861+ lr_sync: Option<std::sync::Arc<PipeSync>>,
1971719862 }
1971819863
1971919864 impl PipeGuard<'_> {
@@ -19730,6 +19875,9 @@ impl PipeGuard<'_> {
1973019875 impl Drop for PipeGuard<'_> {
1973119876 fn drop(&mut self) {
1973219877 self.sync.close(self.nbands, true);
19878+ if let Some(ls) = &self.lr_sync {
19879+ ls.close(self.nbands, true);
19880+ }
1973319881 }
1973419882 }
1973519883
@@ -20002,7 +20150,7 @@ fn apply_loop_restoration(
2000220150 lr.loop_restoration_size[0],
2000320151 grid,
2000420152 0,
20005- &mut out, fctx,
20153+ &mut out, None, fctx,
2000620154 );
2000720155 scratch_return(std::mem::replace(&mut y.data, std::borrow::Cow::Owned(out)).into_owned());
2000820156 let mut out = scratch_empty();
@@ -20017,7 +20165,7 @@ fn apply_loop_restoration(
2001720165 lr.loop_restoration_size[1],
2001820166 grid,
2001920167 1,
20020- &mut out, fctx,
20168+ &mut out, None, fctx,
2002120169 );
2002220170 scratch_return(std::mem::replace(&mut u.data, std::borrow::Cow::Owned(out)).into_owned());
2002320171 let mut out = scratch_empty();
@@ -20032,7 +20180,7 @@ fn apply_loop_restoration(
2003220180 lr.loop_restoration_size[2],
2003320181 grid,
2003420182 2,
20035- &mut out, fctx,
20183+ &mut out, None, fctx,
2003620184 );
2003720185 scratch_return(std::mem::replace(&mut v.data, std::borrow::Cow::Owned(out)).into_owned());
2003820186 }
@@ -32096,9 +32244,28 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3209632244 };
3209732245 let ctx = crate::decode::filter_ctx_copy(fctx);
3209832246 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)) };
3209932253 let snap = &mut pipe_snap;
32100- batch.submit(move || pipe_run(&sync2, sy, su, sv, sn, cfg, snap, &ctx));
32101- PipeGuard { sync, batch: Some(batch), nbands }
32254+ batch.submit(move || {
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 }
3210232269 });
3210332270 if !pipe_on && wave_stats() {
3210432271 PIPE_WHOLE.fetch_add(1, Relaxed);
@@ -34716,10 +34883,15 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3471634883 crate::superres::note_upscaled_picture();
3471734884 }
3471834885 if let Some((deblocked_y, deblocked_u, deblocked_v)) = &deblocked {
34719- apply_loop_restoration(
34720- &mut y, &mut u, &mut v, deblocked_y, deblocked_u, deblocked_v, lr, &lr_grid,
34721- (lr_w, frame_height as usize), fctx,
34722- );
34886+ // lane-pipefilt2: the pipeline already restored every RU row on its
34887+ // way past it (its LR step runs in the same iteration as the CDEF
34888+ // band that completes the row's last line).
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+ }
3472334895 }
3472434896 if let Some((db_y, db_u, db_v)) = deblocked {
3472534897 // 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(
12371237 // lane-perf6: the destination buffer, refilled from `cdef` here. It used
12381238 // to be a fresh `cdef.to_vec()` per plane per frame -- a multi-megabyte
12391239 // 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,
12411248 ) {
1242- out.clear();
1243- out.extend_from_slice(cdef);
1244- if ftype == RestorationType::None || unit_size == 0 {
1249+ let rows = lr_unit_rows(plane_h, unit_size, ss_y, ftype);
1250+ let Some((r_lo, r_hi)) = rrows else {
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");
12451270 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;
12461298 }
12471299 let voffset = 8u32 >> ss_y;
12481300 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();
12551301 let mut y0 = 0u32;
12561302 while y0 < plane_h as u32 {
12571303 let remaining_h = plane_h as u32 - y0;
@@ -1264,44 +1310,54 @@ pub(crate) fn apply_loop_restoration_plane(
12641310 rows.push((v_start, v_end));
12651311 y0 += uh;
12661312 }
1267- let rrow_count = rows.len();
1268- let so = crate::par::Shared::new(out);
1269- let rbands = crate::par::bands(rrow_count, crate::par::filter_threads());
1270- crate::par::run_bands(&rbands, fctx, |r_lo, r_hi, fctx| {
1271- // SAFETY: this band writes only the `out` rows its own RU rows cover.
1272- #[allow(unsafe_code)]
1273- let out = unsafe { so.get() };
1274- for rrow in r_lo..r_hi {
1275- let (v_start, v_end) = rows[rrow];
1276- let mut x0 = 0u32;
1277- let mut rcol = 0usize;
1278- while x0 < plane_w as u32 {
1279- let remaining_w = plane_w as u32 - x0;
1280- let uw = if remaining_w < ext_size { remaining_w } else { unit_size };
1281- let filter = grid.get(plane, rrow, rcol);
1282- if filter != UnitFilter::None {
1283- filter_restoration_unit(
1284- out,
1285- cdef,
1286- deblocked,
1287- stride,
1288- plane_w,
1289- plane_h,
1290- x0 as usize,
1291- (x0 + uw) as usize,
1292- v_start as usize,
1293- v_end as usize,
1294- ss_y,
1295- filter, fctx,
1296- );
1297- }
1298- x0 += uw;
1299- rcol += 1;
1300- }
1313+ rows
1314+}
1315+
1316+/// The restoration units of one RU row, filtered into `out`. Reads only
1317+/// `cdef`/`deblocked`, writes only this row's `v_start..v_end` span.
1318+#[allow(clippy::too_many_arguments)]
1319+fn lr_unit_row(
1320+ out: &mut [u16],
1321+ cdef: &[u16],
1322+ deblocked: &[u16],
1323+ stride: usize,
1324+ plane_w: usize,
1325+ plane_h: usize,
1326+ ss_y: u32,
1327+ unit_size: u32,
1328+ grid: &RestorationGrid,
1329+ plane: usize,
1330+ rrow: usize,
1331+ rows: &[(u32, u32)],
1332+ fctx: &crate::decode::FrameCtx,
1333+) {
1334+ let ext_size = (unit_size * 3) / 2;
1335+ let (v_start, v_end) = rows[rrow];
1336+ let mut x0 = 0u32;
1337+ let mut rcol = 0usize;
1338+ while x0 < plane_w as u32 {
1339+ let remaining_w = plane_w as u32 - x0;
1340+ let uw = if remaining_w < ext_size { remaining_w } else { unit_size };
1341+ let filter = grid.get(plane, rrow, rcol);
1342+ if filter != UnitFilter::None {
1343+ filter_restoration_unit(
1344+ out,
1345+ cdef,
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+ );
13011357 }
1302- });
1303- let rrow = rrow_count;
1304- debug_assert_eq!(rrow, grid.vert_units[plane], "RU row walk must match RestorationGrid::new's count_units");
1358+ x0 += uw;
1359+ rcol += 1;
1360+ }
13051361 }
13061362
13071363 #[cfg(test)]