Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Smart Blur: 3.5x faster at radius 12 with identical output (#7921)

Khawar Zamman Wanid51202c5a459
diff --git a/crates/algo/examples/bench_filters2.rs b/crates/algo/examples/bench_filters2.rs
index a84bb3ca5..9849c4f84 100644
--- a/crates/algo/examples/bench_filters2.rs
+++ b/crates/algo/examples/bench_filters2.rs
@@ -33,6 +33,8 @@ fn main() {
depth_map: None,
},
FilterParams::SmartBlur { radius: 3.0, threshold: 25.0, quality: BlurQuality::High, mode: SmartBlurMode::Normal },
+ FilterParams::SmartBlur { radius: 12.0, threshold: 25.0, quality: BlurQuality::High, mode: SmartBlurMode::Normal },
+ FilterParams::SmartBlur { radius: 100.0, threshold: 25.0, quality: BlurQuality::High, mode: SmartBlurMode::Normal },
FilterParams::ShapeBlur { radius: 10.0, shape: BlurShape::Star },
FilterParams::TiltShift { blur: 15.0, center_x: 0.5, center_y: 0.5, angle: 0.0, focus: 0.1, transition: 0.15 },
FilterParams::IrisBlur { pins: vec![IrisPin::default()] },
@@ -60,7 +62,12 @@ fn main() {
let area = output_area(&p, s.content_bounds(), r, None).intersect(&r);
let t = std::time::Instant::now();
let out = apply(&s, &p, area, r, None);
- println!("{:<18} {w}x{h} RGBA8: {:.2?}", p.label(), t.elapsed());
+ // Smart Blur's cost peaks near radius 12, where High quality visits every pixel in the circle.
+ let name = match p {
+ FilterParams::SmartBlur { radius, .. } => format!("{} r{radius}", p.label()),
+ _ => p.label().to_string(),
+ };
+ println!("{name:<18} {w}x{h} RGBA8: {:.2?}", t.elapsed());
drop(out);
}
}
diff --git a/crates/algo/src/blur2.rs b/crates/algo/src/blur2.rs
index bb6b47656..dc57f39ad 100644
--- a/crates/algo/src/blur2.rs
+++ b/crates/algo/src/blur2.rs
@@ -189,6 +189,11 @@ mod shape_tests;
/// Smart Blur: averages only neighbours within `threshold` levels of the
/// centre pixel (so edges stay crisp); Edge Only / Overlay Edge draw the
/// edges (where neighbours differ by more than the threshold) in white.
+///
+/// Neighbours outside `src` read as zero, as [`Image::get`] does. Pixels whose whole
+/// kernel lies inside `src` (all of them, with the usual halo) read neighbours at
+/// precomputed offsets into the window instead of by coordinates, and for up to five
+/// channels go through [`smart_rows`] (#7921).
pub(crate) fn smart_blur(src: &Image, out: Rect, ctx: &Ctx, radius: f32, threshold: f32, quality: BlurQuality, mode: SmartBlurMode) -> Vec<f32> {
let n = src.ch;
let cc = ncol(ctx, n);
@@ -201,31 +206,48 @@ pub(crate) fn smart_blur(src: &Image, out: Rect, ctx: &Ctx, radius: f32, thresho
BlurQuality::High => 12,
};
let stride = ((ri + target - 1) / target).max(1);
- let offs: Vec<(i32, i32)> = (-ri..=ri)
+ let win = src.rect;
+ let ww = win.width() as isize;
+ // Each offset with its distance in samples within the window.
+ let offs: Vec<(i32, i32, isize)> = (-ri..=ri)
.step_by(stride as usize)
.flat_map(|dy| (-ri..=ri).step_by(stride as usize).map(move |dx| (dx, dy)))
.filter(|(dx, dy)| ((dx * dx + dy * dy) as f32) <= r * r + 0.5)
+ .map(|(dx, dy)| (dx, dy, (dy as isize * ww + dx as isize) * n as isize))
.collect();
+ let at = |x: i32, y: i32| win.contains(x, y).then(|| ((y - win.y0) as usize * ww as usize + (x - win.x0) as usize) * n);
+ let zeros = [0.0f32; MAXC];
+ let data = &src.data[..];
+ // The pixel at sample `i`, or zeros outside the window.
+ let sample = |i: Option<usize>| i.and_then(|i| data.get(i..i + n)).unwrap_or(&zeros[..n]);
let white = native(ctx, [1.0, 1.0, 1.0, 1.0]);
let black = native(ctx, [0.0, 0.0, 0.0, 1.0]);
let mut res = src.crop(out);
- let mut q = [0.0f32; MAXC];
+ let inner = Rect::new(win.x0.saturating_add(ri), win.y0.saturating_add(ri), win.x1.saturating_sub(ri), win.y1.saturating_sub(ri)).intersect(&out);
+ let lin: Vec<isize> = offs.iter().map(|o| o.2).collect();
+ let rows = match (mode, n, ctx.alpha) {
+ (SmartBlurMode::Normal, 1, false) => smart_rows::<1, false>(src, out, inner, &lin, t, &mut res),
+ (SmartBlurMode::Normal, 1, true) => smart_rows::<1, true>(src, out, inner, &lin, t, &mut res),
+ (SmartBlurMode::Normal, 2, false) => smart_rows::<2, false>(src, out, inner, &lin, t, &mut res),
+ (SmartBlurMode::Normal, 2, true) => smart_rows::<2, true>(src, out, inner, &lin, t, &mut res),
+ (SmartBlurMode::Normal, 3, false) => smart_rows::<3, false>(src, out, inner, &lin, t, &mut res),
+ (SmartBlurMode::Normal, 3, true) => smart_rows::<3, true>(src, out, inner, &lin, t, &mut res),
+ (SmartBlurMode::Normal, 4, false) => smart_rows::<4, false>(src, out, inner, &lin, t, &mut res),
+ (SmartBlurMode::Normal, 4, true) => smart_rows::<4, true>(src, out, inner, &lin, t, &mut res),
+ (SmartBlurMode::Normal, 5, false) => smart_rows::<5, false>(src, out, inner, &lin, t, &mut res),
+ (SmartBlurMode::Normal, 5, true) => smart_rows::<5, true>(src, out, inner, &lin, t, &mut res),
+ _ => Rect::EMPTY,
+ };
let mut acc = [0.0f32; MAXC];
for (i, px) in res.chunks_exact_mut(n).enumerate() {
let (x, y) = xy(out, i);
+ if rows.contains(x, y) {
+ continue;
+ }
let me: [f32; MAXC] = std::array::from_fn(|c| if c < n { px[c] } else { 0.0 });
- let differs = |q: &[f32]| (0..cc).any(|c| (q[c] - me[c]).abs() > t);
+ let differs = |q: &[f32]| q[..cc].iter().zip(&me).any(|(q, m)| (q - m).abs() > t);
if mode != SmartBlurMode::Normal {
- let mut edge = false;
- for (dx, dy) in [(1, 0), (0, 1), (-1, 0), (0, -1)] {
- for (c, v) in q.iter_mut().enumerate().take(n) {
- *v = src.get(x + dx, y + dy, c);
- }
- if differs(&q[..n]) {
- edge = true;
- break;
- }
- }
+ let edge = [(1, 0), (0, 1), (-1, 0), (0, -1)].into_iter().any(|(dx, dy)| differs(sample(at(x + dx, y + dy))));
let a = if ctx.alpha { px[n - 1] } else { 1.0 };
if edge {
px[..cc].copy_from_slice(&white[..cc]);
@@ -237,18 +259,28 @@ pub(crate) fn smart_blur(src: &Image, out: Rect, ctx: &Ctx, radius: f32, thresho
}
continue;
}
+ let interior = x - ri >= win.x0 && x + ri < win.x1 && y - ri >= win.y0 && y + ri < win.y1;
+ let centre = if interior { at(x, y) } else { None };
acc[..n].fill(0.0);
let mut wsum = 0.0f32;
- for &(dx, dy) in &offs {
- for (c, v) in q.iter_mut().enumerate().take(n) {
- *v = src.get(x + dx, y + dy, c);
- }
- if differs(&q[..n]) {
+ for &(dx, dy, d) in &offs {
+ let q = sample(match centre {
+ Some(c) => c.checked_add_signed(d),
+ None => at(x + dx, y + dy),
+ });
+ if differs(q) {
continue;
}
- let a = if ctx.alpha { q[n - 1] } else { 1.0 };
- for c in 0..n {
- acc[c] += if ctx.alpha && c < n - 1 { q[c] * a } else { q[c] };
+ if ctx.alpha {
+ let a = q[n - 1];
+ for (s, v) in acc.iter_mut().zip(&q[..cc]) {
+ *s += v * a;
+ }
+ acc[n - 1] += a;
+ } else {
+ for (s, v) in acc.iter_mut().zip(q) {
+ *s += v;
+ }
}
wsum += 1.0;
}
@@ -262,6 +294,77 @@ pub(crate) fn smart_blur(src: &Image, out: Rect, ctx: &Ctx, radius: f32, thresho
res
}
+/// Smart Blur's normal mode over `inner` (pixels whose whole kernel lies in `src`) for `N`
+/// channels, the last alpha if `A`; `lin` are the neighbours as sample offsets in the window.
+/// Each offset sweeps a whole row, so neighbours load contiguously and a rejected one adds
+/// `-0.0` (an exact identity) instead of branching: every pixel sums its neighbours in the same
+/// order as [`smart_blur`]'s per-pixel loop, giving the same bits. Returns the area written: the
+/// rows finished, empty if the layout doesn't match.
+fn smart_rows<const N: usize, const A: bool>(src: &Image, out: Rect, inner: Rect, lin: &[isize], t: f32, res: &mut [f32]) -> Rect {
+ let win = src.rect;
+ if src.ch != N || inner.is_empty() || !win.contains_rect(&inner) || !out.contains_rect(&inner) {
+ return Rect::EMPTY;
+ }
+ let cc = if A { N - 1 } else { N };
+ let (ww, ow, len) = (win.width() as usize, out.width() as usize, inner.width() as usize);
+ let pixels = len * N;
+ let mut acc = vec![[0.0f32; N]; len];
+ let mut wsum = vec![0.0f32; len];
+ // Rows before `y` are done; a row is written only once all its neighbours were read.
+ let done = |y: i32| Rect::new(inner.x0, inner.y0, inner.x1, y);
+ for y in inner.y0..inner.y1 {
+ let centre = ((y - win.y0) as usize * ww + (inner.x0 - win.x0) as usize) * N;
+ let Some(me) = src.data.get(centre..centre + pixels) else {
+ return done(y);
+ };
+ let me = me.as_chunks::<N>().0;
+ acc.fill([0.0; N]);
+ wsum.fill(0.0);
+ for &d in lin {
+ let Some(q) = centre.checked_add_signed(d).and_then(|i| src.data.get(i..i + pixels)) else {
+ return done(y);
+ };
+ for (((s, w), q), m) in acc.iter_mut().zip(wsum.iter_mut()).zip(q.as_chunks::<N>().0).zip(me) {
+ // As `differs`: a NaN difference is not over the threshold.
+ let mut far = false;
+ for c in 0..cc {
+ far |= (q[c] - m[c]).abs() > t;
+ }
+ let keep = !far;
+ if A {
+ let a = q[N - 1];
+ for c in 0..N - 1 {
+ s[c] += if keep { q[c] * a } else { -0.0 };
+ }
+ s[N - 1] += if keep { a } else { -0.0 };
+ } else {
+ for c in 0..N {
+ s[c] += if keep { q[c] } else { -0.0 };
+ }
+ }
+ *w += if keep { 1.0 } else { 0.0 };
+ }
+ }
+ let o = ((y - out.y0) as usize * ow + (inner.x0 - out.x0) as usize) * N;
+ let Some(dst) = res.get_mut(o..o + pixels) else {
+ return done(y);
+ };
+ for ((px, s), &w) in dst.as_chunks_mut::<N>().0.iter_mut().zip(&acc).zip(&wsum) {
+ if w > 0.0 {
+ for c in 0..N {
+ px[c] = s[c] / w;
+ }
+ unpremul_px(px, A);
+ }
+ }
+ }
+ inner
+}
+
+#[cfg(test)]
+#[path = "smart_blur_tests.rs"]
+mod smart_tests;
+
// ---------- lens blur ----------
pub(crate) struct LensSpec<'a> {
diff --git a/crates/algo/src/smart_blur_tests.rs b/crates/algo/src/smart_blur_tests.rs
new file mode 100644
index 000000000..47290e242
--- /dev/null
+++ b/crates/algo/src/smart_blur_tests.rs
@@ -0,0 +1,173 @@
+//! The pre-#7921 Smart Blur (every neighbour read per channel through `Image::get`) stays as an
+//! exact oracle: the offset fast path must give the same bits for every mode, depth and layout.
+use super::*;
+use photocraft_color::ColorMode;
+
+#[allow(clippy::too_many_arguments)]
+fn smart_blur_oracle(src: &Image, out: Rect, ctx: &Ctx, radius: f32, threshold: f32, quality: BlurQuality, mode: SmartBlurMode) -> Vec<f32> {
+ let n = src.ch;
+ let cc = ncol(ctx, n);
+ let r = radius.clamp(0.1, 100.0);
+ let t = threshold.clamp(0.1, 100.0) / 255.0;
+ let ri = r.ceil() as i32;
+ let target = match quality {
+ BlurQuality::Low => 4,
+ BlurQuality::Medium => 7,
+ BlurQuality::High => 12,
+ };
+ let stride = ((ri + target - 1) / target).max(1);
+ let offs: Vec<(i32, i32)> = (-ri..=ri)
+ .step_by(stride as usize)
+ .flat_map(|dy| (-ri..=ri).step_by(stride as usize).map(move |dx| (dx, dy)))
+ .filter(|(dx, dy)| ((dx * dx + dy * dy) as f32) <= r * r + 0.5)
+ .collect();
+ let white = native(ctx, [1.0, 1.0, 1.0, 1.0]);
+ let black = native(ctx, [0.0, 0.0, 0.0, 1.0]);
+ let mut res = src.crop(out);
+ let mut q = [0.0f32; MAXC];
+ let mut acc = [0.0f32; MAXC];
+ for (i, px) in res.chunks_exact_mut(n).enumerate() {
+ let (x, y) = xy(out, i);
+ let me: [f32; MAXC] = std::array::from_fn(|c| if c < n { px[c] } else { 0.0 });
+ let differs = |q: &[f32]| (0..cc).any(|c| (q[c] - me[c]).abs() > t);
+ if mode != SmartBlurMode::Normal {
+ let mut edge = false;
+ for (dx, dy) in [(1, 0), (0, 1), (-1, 0), (0, -1)] {
+ for (c, v) in q.iter_mut().enumerate().take(n) {
+ *v = src.get(x + dx, y + dy, c);
+ }
+ if differs(&q[..n]) {
+ edge = true;
+ break;
+ }
+ }
+ let a = if ctx.alpha { px[n - 1] } else { 1.0 };
+ if edge {
+ px[..cc].copy_from_slice(&white[..cc]);
+ } else if mode == SmartBlurMode::EdgeOnly {
+ px[..cc].copy_from_slice(&black[..cc]);
+ }
+ if ctx.alpha {
+ px[n - 1] = a;
+ }
+ continue;
+ }
+ acc[..n].fill(0.0);
+ let mut wsum = 0.0f32;
+ for &(dx, dy) in &offs {
+ for (c, v) in q.iter_mut().enumerate().take(n) {
+ *v = src.get(x + dx, y + dy, c);
+ }
+ if differs(&q[..n]) {
+ continue;
+ }
+ let a = if ctx.alpha { q[n - 1] } else { 1.0 };
+ for c in 0..n {
+ acc[c] += if ctx.alpha && c < n - 1 { q[c] * a } else { q[c] };
+ }
+ wsum += 1.0;
+ }
+ if wsum > 0.0 {
+ for c in 0..n {
+ px[c] = acc[c] / wsum;
+ }
+ unpremul_px(px, ctx.alpha);
+ }
+ }
+ res
+}
+
+/// Flat blocks with small noise, so some neighbours fall within the threshold and some don't.
+fn image(rect: Rect, n: usize, alpha: bool) -> Image {
+ let w = rect.width() as usize;
+ let data = (0..w * rect.height() as usize)
+ .flat_map(|i| {
+ let (x, y) = (i % w, i / w);
+ let block = ((x / 5 + y / 7) % 3) as f32 * 0.3;
+ (0..n).map(move |c| {
+ let noise = ((i * 31 + c * 13) % 17) as f32 / 160.0;
+ if alpha && c + 1 == n { [1.0, 0.0, 0.4, 0.75][(x + y) % 4] } else { block + noise }
+ })
+ })
+ .collect();
+ Image { rect, ch: n, data }
+}
+
+fn exact(a: &[f32], b: &[f32], what: &str) {
+ assert_eq!(a.len(), b.len(), "{what}");
+ for (i, (a, b)) in a.iter().zip(b).enumerate() {
+ assert!(a.to_bits() == b.to_bits() || (a.is_nan() && b.is_nan()), "{what}: sample {i}: {a} != {b}");
+ }
+}
+
+#[test]
+fn offset_fast_path_matches_the_per_channel_oracle() {
+ let mut layouts: Vec<(ColorMode, usize, bool)> = vec![
+ (ColorMode::Rgb, 3, false),
+ (ColorMode::Rgb, 4, true),
+ (ColorMode::Grayscale, 1, false),
+ (ColorMode::Grayscale, 2, true),
+ (ColorMode::Cmyk, 4, false),
+ (ColorMode::Cmyk, 5, true),
+ (ColorMode::Lab, 4, true),
+ ];
+ layouts.extend((1..=MAXC).flat_map(|n| [(ColorMode::Multichannel, n, false), (ColorMode::Multichannel, n, true)]));
+ let win = Rect::new(-7, -4, 33, 30);
+ for (mode, n, alpha) in layouts {
+ let src = image(win, n, alpha);
+ let ctx = Ctx { bounds: win, mode, alpha };
+ for radius in [0.1f32, 1.0, 3.0, 12.0, 17.5] {
+ let ri = f32::ceil(radius) as i32;
+ // The usual tile (the window less the halo), the whole window, and one sticking out of it.
+ let inner = Rect::new(win.x0 + ri, win.y0 + ri, win.x1 - ri, win.y1 - ri);
+ for out in [inner, win, Rect::new(-12, -9, 10, 8), Rect::EMPTY] {
+ for quality in [BlurQuality::Low, BlurQuality::Medium, BlurQuality::High] {
+ for sm in [SmartBlurMode::Normal, SmartBlurMode::EdgeOnly, SmartBlurMode::OverlayEdge] {
+ for threshold in [8.0, 60.0] {
+ let what = format!("{mode:?} n={n} alpha={alpha} r={radius} {out:?} {quality:?} {sm:?} t={threshold}");
+ exact(
+ &smart_blur(&src, out, &ctx, radius, threshold, quality, sm),
+ &smart_blur_oracle(&src, out, &ctx, radius, threshold, quality, sm),
+ &what,
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn out_of_window_neighbours_read_as_zero() {
+ // A one-pixel window: every neighbour is outside and reads as transparent black, so a black
+ // centre averages with all of them and a white one keeps itself.
+ let ctx = Ctx { bounds: Rect::new(0, 0, 1, 1), mode: ColorMode::Rgb, alpha: true };
+ for v in [0.0, 1.0] {
+ let src = Image { rect: Rect::new(0, 0, 1, 1), ch: 4, data: vec![v, v, v, 1.0] };
+ let got = smart_blur(&src, src.rect, &ctx, 3.0, 25.0, BlurQuality::High, SmartBlurMode::Normal);
+ exact(&got, &smart_blur_oracle(&src, src.rect, &ctx, 3.0, 25.0, BlurQuality::High, SmartBlurMode::Normal), "1 px");
+ }
+}
+
+#[test]
+fn nan_and_infinite_samples_match_the_oracle() {
+ // A NaN difference is never over the threshold, so it is averaged in; an infinite one is.
+ let win = Rect::new(0, 0, 24, 20);
+ for (n, alpha) in [(3, false), (4, true)] {
+ let mut src = image(win, n, alpha);
+ for (i, v) in [(5, f32::NAN), (97, f32::INFINITY), (230, f32::NEG_INFINITY), (311, -0.0)] {
+ let len = src.data.len();
+ src.data[(i * n) % len] = v;
+ }
+ let ctx = Ctx { bounds: win, mode: ColorMode::Rgb, alpha };
+ let out = Rect::new(4, 4, 20, 16);
+ for threshold in [8.0, 100.0] {
+ exact(
+ &smart_blur(&src, out, &ctx, 4.0, threshold, BlurQuality::High, SmartBlurMode::Normal),
+ &smart_blur_oracle(&src, out, &ctx, 4.0, threshold, BlurQuality::High, SmartBlurMode::Normal),
+ &format!("n={n} t={threshold}"),
+ );
+ }
+ }
+}