forge
Explore
Log in

Don't you dare go Hollow

Film grain writes its output once, from the bands

Browse files at this commit

8db0d01ab6d72ca7fac3027f0bb28d463da7ecadAhmet Kaan GümüşParent: cb9db45
  • perf
    • film grain writes its output once, from the bands
Show full message
perf(av1): film grain writes its output once, from the bands

apply_grain cloned the whole clean picture on the frame thread and then
wrote the noise over the copy -- a serial 25 MB memmove per 4K frame
ahead of the parallel block-row walk. The grain bands already own a
partition of the picture's rows, so each band now copies its own rows
out of the clean source one block row AHEAD of the noise it adds to
them: the copy runs on the filter pool, the rows the kernels read back
are still in the core's cache, and the destination is allocated
uninitialised instead of cloned or zeroed.

Byte-exact: 12/12 gate hashes at 1, 4 and 16 threads, plus a real
film-cut decode at (16,4,2) hashing identical to the base binary. seg4k
at (16,4,2), 4 interleaved rounds: task-clock 48.50/47.07/46.62/45.34 s
base -> 46.44/45.12/45.74/44.76 s, -1.3..-4.2% every round; instructions
408.385 -> 408.404 G (flat); page-faults flat. At 1 thread task-clock
36.98 -> 32.41 s.
crates/ec-av1/src/film_grain.rsmodified+143 -5
@@ -1041,6 +1041,48 @@ pub(crate) fn grain_hits() -> usize {
10411041 GRAIN_HITS.with(|c| c.get())
10421042 }
10431043
1044+/// Copies the clean rows `*lcur..l_to` (luma) and `*ccur..c_to` (chroma) of
1045+/// `src` into `out`, advancing the cursors. [`apply_grain`]'s bands fill
1046+/// their own uninitialised destination rows with this before adding noise.
1047+fn copy_clean_rows(
1048+ out: &mut Picture,
1049+ src: &Picture,
1050+ ys: usize,
1051+ cs: usize,
1052+ lcur: &mut usize,
1053+ ccur: &mut usize,
1054+ l_to: usize,
1055+ c_to: usize,
1056+) {
1057+ if l_to > *lcur {
1058+ out.y[*lcur * ys..l_to * ys].copy_from_slice(&src.y[*lcur * ys..l_to * ys]);
1059+ *lcur = l_to;
1060+ }
1061+ if c_to > *ccur {
1062+ out.u[*ccur * cs..c_to * cs].copy_from_slice(&src.u[*ccur * cs..c_to * cs]);
1063+ out.v[*ccur * cs..c_to * cs].copy_from_slice(&src.v[*ccur * cs..c_to * cs]);
1064+ *ccur = c_to;
1065+ }
1066+}
1067+
1068+/// A plane of `n` samples whose contents are written before they are read.
1069+///
1070+/// corner-cut: `set_len` over `Vec::with_capacity` skips the zeroing pass a
1071+/// `vec![0; n]` would cost (25 MB per 4K frame) for a buffer every one of
1072+/// whose samples is written by [`apply_grain`]'s band copy. The proof is the
1073+/// band row partition at that call site, not the type system, exactly as
1074+/// [`crate::par::Shared`]'s disjointness is; the byte-exact 1-vs-4-thread
1075+/// gate is what checks it. Upgrade path: `Box<[MaybeUninit<u16>]>` plumbed
1076+/// through the kernels.
1077+#[allow(unsafe_code)]
1078+fn uninit_plane(n: usize) -> Vec<u16> {
1079+ let mut v: Vec<u16> = Vec::with_capacity(n);
1080+ // SAFETY: `u16` has no invalid bit pattern and no uninitialised sample is
1081+ // read -- see the doc comment.
1082+ unsafe { v.set_len(n) };
1083+ v
1084+}
1085+
10441086 /// `av1_add_film_grain`/`add_film_grain_run` (spec 7.18.3.5): synthesize and
10451087 /// apply film grain to `picture`, returning a new grained picture. `picture`
10461088 /// itself is unchanged -- it stays the clean reference-frame-bank copy.
@@ -1051,14 +1093,13 @@ pub(crate) fn apply_grain(
10511093 mc_identity: bool,
10521094 bit_depth: u32, fctx: &crate::decode::FrameCtx,
10531095 ) -> Picture {
1054- let mut out = picture.clone();
10551096 if !fg.apply_grain {
1056- return out;
1097+ return picture.clone();
10571098 }
10581099 fctx.grain_bit_depth.with(|c| c.set(bit_depth));
10591100 GRAIN_HITS.with(|c| c.set(c.get() + 1));
1060- let width = out.width as i32;
1061- let height = out.height as i32;
1101+ let width = picture.width as i32;
1102+ let height = picture.height as i32;
10621103 let y_stride = width;
10631104 let c_stride = width / 2;
10641105
@@ -1113,13 +1154,47 @@ pub(crate) fn apply_grain(
11131154 // single-threaded walk does.
11141155 let row_step = LUMA_SUBBLOCK >> 1;
11151156 let nrows = ((height / 2).max(0) as usize).div_ceil(row_step as usize);
1116- let so = crate::par::Shared::new(&mut out);
11171157 let gbands = crate::par::bands(nrows, crate::par::filter_threads());
1158+ // lane-grain2: the clean picture used to be cloned here, on the frame
1159+ // thread, and the noise then written over the copy -- a whole-picture
1160+ // `memmove` (3.5% of a 4K frame thread's cycles) ahead of the parallel
1161+ // walk. The bands own a partition of the plane rows, so each band copies
1162+ // its OWN rows out of the clean source and adds noise to them: the copy
1163+ // moves onto the filter pool and the destination never needs zeroing.
1164+ let y_rows = if y_stride > 0 { picture.y.len() / y_stride as usize } else { 0 };
1165+ let c_rows = if c_stride > 0 { picture.u.len() / c_stride as usize } else { 0 };
1166+ let banded = !gbands.is_empty() && y_stride > 0 && c_stride > 0;
1167+ let mut out = if banded {
1168+ Picture {
1169+ width: picture.width,
1170+ height: picture.height,
1171+ y: uninit_plane(picture.y.len()),
1172+ u: uninit_plane(picture.u.len()),
1173+ v: uninit_plane(picture.v.len()),
1174+ }
1175+ } else {
1176+ picture.clone()
1177+ };
1178+ let so = crate::par::Shared::new(&mut out);
11181179 crate::par::run_bands(&gbands, fctx, |b_lo, b_hi, fctx| {
11191180 // SAFETY: this band writes only the picture rows its own block rows
11201181 // cover, disjoint from every other band's.
11211182 #[allow(unsafe_code)]
11221183 let out = unsafe { so.get() };
1184+ // The row ranges below partition every plane across the bands (the
1185+ // last band runs to the plane's end, so an odd tail row or a height
1186+ // that is not a multiple of 32 is covered too), which is what makes
1187+ // every sample of the uninitialised destination written before it is
1188+ // read -- by this copy, or by the noise written over it. The copy
1189+ // runs one block row AHEAD of the noise rather than once per band, so
1190+ // the rows the kernels then read back are still in this core's cache.
1191+ let ys = y_stride as usize;
1192+ let cs = c_stride as usize;
1193+ let c_end = if b_hi == nrows { c_rows } else { (b_hi * row_step as usize).min(c_rows) };
1194+ let l_end =
1195+ if b_hi == nrows { y_rows } else { (2 * b_hi * row_step as usize).min(y_rows) };
1196+ let mut ccur = (b_lo * row_step as usize).min(c_rows);
1197+ let mut lcur = (2 * b_lo * row_step as usize).min(y_rows);
11231198 let y_lo = (b_lo * row_step as usize) as i32;
11241199 let y_hi = ((b_hi * row_step as usize) as i32).min(height / 2);
11251200 let y_first = if b_lo > 0 { y_lo - row_step } else { y_lo };
@@ -1133,6 +1208,16 @@ pub(crate) fn apply_grain(
11331208 let mut y = y_first;
11341209 while y < y_hi {
11351210 let prelude = y < y_lo;
1211+ copy_clean_rows(
1212+ out,
1213+ picture,
1214+ ys,
1215+ cs,
1216+ &mut lcur,
1217+ &mut ccur,
1218+ (2 * (y as usize + row_step as usize)).min(l_end),
1219+ (y as usize + row_step as usize).min(c_end),
1220+ );
11361221 let mut row_rng = Rng::line(y * 2, fg.grain_seed);
11371222 let mut x = 0;
11381223 while x < width / 2 {
@@ -1466,6 +1551,7 @@ pub(crate) fn apply_grain(
14661551 }
14671552 y += row_step;
14681553 }
1554+ copy_clean_rows(out, picture, ys, cs, &mut lcur, &mut ccur, l_end, c_end);
14691555 });
14701556 let _ = so;
14711557
@@ -1605,3 +1691,55 @@ mod perf5_tests {
16051691 assert_eq!(checked, 3 * 2 * 3 * 2 * 7);
16061692 }
16071693 }
1694+
1695+#[cfg(test)]
1696+mod grain2_tests {
1697+ use super::{Picture, apply_grain};
1698+ use ec_av1_syntax::FilmGrainParams;
1699+
1700+ /// lane-grain2: the destination picture is allocated uninitialised and
1701+ /// filled by the bands' own row copy, so a plane the noise kernels never
1702+ /// touch -- and the ragged last block row and column of a size that is
1703+ /// not a multiple of 32 -- must still come back as the clean source,
1704+ /// sample for sample. An uncovered row would read back as garbage here.
1705+ #[test]
1706+ fn untouched_planes_and_ragged_tail_come_back_clean() {
1707+ let (w, h) = (48usize, 100usize);
1708+ let src = Picture {
1709+ width: w,
1710+ height: h,
1711+ y: (0..w * h).map(|i| ((i * 7 + 3) % 256) as u16).collect(),
1712+ u: (0..w * h / 4).map(|i| ((i * 11 + 5) % 256) as u16).collect(),
1713+ v: (0..w * h / 4).map(|i| ((i * 13 + 9) % 256) as u16).collect(),
1714+ };
1715+ let mut fg = FilmGrainParams {
1716+ apply_grain: true,
1717+ grain_seed: 0x2f1c,
1718+ overlap_flag: true,
1719+ ar_coeff_lag: 2,
1720+ ar_coeff_shift_minus_6: 1,
1721+ num_cb_points: 2,
1722+ cb_mult: 128,
1723+ cb_luma_mult: 192,
1724+ cr_mult: 128,
1725+ cr_luma_mult: 192,
1726+ ..Default::default()
1727+ };
1728+ fg.point_cb_value[..2].copy_from_slice(&[0, 255]);
1729+ fg.point_cb_scaling[..2].copy_from_slice(&[40, 60]);
1730+ let fctx = crate::decode::FrameCtx::new();
1731+ let out = apply_grain(&src, &fg, false, 8, &fctx);
1732+ assert_eq!(out.y, src.y, "no luma points: the luma plane is the clean copy");
1733+ assert_eq!(out.v, src.v, "no cr points: the V plane is the clean copy");
1734+ assert_ne!(out.u, src.u, "cb grain landed on the U plane");
1735+
1736+ let mut fg2 = fg;
1737+ fg2.num_y_points = 2;
1738+ fg2.point_y_value[..2].copy_from_slice(&[0, 255]);
1739+ fg2.point_y_scaling[..2].copy_from_slice(&[50, 70]);
1740+ let out2 = apply_grain(&src, &fg2, false, 8, &fctx);
1741+ assert_ne!(out2.y, src.y, "luma grain landed");
1742+ assert_eq!(out2.v, src.v, "no cr points: the V plane is still the clean copy");
1743+ assert_eq!(out2.y.len(), w * h, "the ragged tail row is present");
1744+ }
1745+}