Skip to content

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

Performance: a cancelled Gaussian Blur job stops within budget (#6205)

David Manna1837706ee8b
diff --git a/crates/algo/src/blur.rs b/crates/algo/src/blur.rs
index ae8b12f40..fb6268122 100644
--- a/crates/algo/src/blur.rs
+++ b/crates/algo/src/blur.rs
@@ -212,12 +212,17 @@ fn box_pass_px<const N: usize>(src: &[f32], dst: &mut [f32], r: usize) {
}
/// Box passes of the given radii in turn along the line in `s.line` (`w`-float elements, as many
-/// as `dst` holds plus twice the radii's sum; consumed), ending in `dst`.
-fn line_passes(dst: &mut [f32], w: usize, radii: &[usize], s: &mut Scratch) {
+/// as `dst` holds plus twice the radii's sum; consumed), ending in `dst`. Stops early (leaving
+/// `dst` unfinished) when `ctl` is cancelled before a pass: a column strip's passes take tens of
+/// milliseconds on a tall image, too long to finish once cancelled (#6205).
+fn line_passes(dst: &mut [f32], w: usize, radii: &[usize], s: &mut Scratch, ctl: &Interrupt) {
let Scratch { line, next, acc } = s;
let Some(len) = dst.len().checked_div(w) else { return };
let mut tail: usize = radii.iter().sum();
for (k, &r) in radii.iter().enumerate() {
+ if ctl.cancelled() {
+ return;
+ }
tail -= r;
if k + 1 == radii.len() {
box_pass(line, dst, w, r, acc);
@@ -281,7 +286,7 @@ pub(crate) fn box_blur(
(0..left).for_each(|_| s.line.extend_from_slice(first));
s.line.extend_from_slice(&row);
(0..right).for_each(|_| s.line.extend_from_slice(last));
- line_passes(dst, n, &radii, &mut s);
+ line_passes(dst, n, &radii, &mut s, ctl);
}
});
// Vertical passes, strip by strip, the same way down the columns.
@@ -300,7 +305,10 @@ pub(crate) fn box_blur(
(0..rows).for_each(|y| s.line.extend_from_slice(row(y)));
(0..bottom).for_each(|_| s.line.extend_from_slice(row(rows - 1)));
let mut res = vec![0.0f32; oh * w];
- line_passes(&mut res, w, &radii, &mut s);
+ line_passes(&mut res, w, &radii, &mut s, ctl);
+ if ctl.cancelled() {
+ return (t, Vec::new());
+ }
unpremultiply(&mut res, n, alpha);
(t, res)
});
@@ -1180,4 +1188,61 @@ mod tests {
}
}
}
+
+ /// A column strip's passes stop between passes once cancelled, not only before the strip
+ /// (#6205); uncancelled, every pass runs.
+ #[test]
+ fn line_passes_stop_between_passes_when_cancelled() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ let (radii, w, len) = ([2usize, 3, 2], 4usize, 50usize);
+ let reach: usize = radii.iter().sum();
+ let line: Vec<f32> = (0..(len + 2 * reach) * w).map(|i| (i % 7) as f32 + 1.0).collect();
+ let run = |ctl: &Interrupt| {
+ let mut s = Scratch { line: line.clone(), ..Scratch::default() };
+ let mut dst = vec![0.0f32; len * w];
+ line_passes(&mut dst, w, &radii, &mut s, ctl);
+ dst
+ };
+ assert!(run(&Interrupt::NONE).iter().all(|v| *v > 0.0));
+ let calls = AtomicUsize::new(0);
+ let cancel = || calls.fetch_add(1, Ordering::SeqCst) >= 1;
+ // Cancelled after the first pass: the last pass (the one writing `dst`) never runs.
+ assert!(run(&Interrupt::cancel_only(&cancel)).iter().all(|v| *v == 0.0));
+ assert_eq!(calls.load(Ordering::SeqCst), 2);
+ }
+
+ /// A box blur cancelled at any of its checks returns `None` (never a half-blurred result);
+ /// one that is asked but never cancelled is bit-identical to the uninterruptible run.
+ #[test]
+ fn box_blur_honours_a_cancel_at_every_check() {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ let (n, src) = (4usize, Rect::new(0, 0, 150, 90));
+ let px: Vec<f32> = (0..src.width() as usize * src.height() as usize * n).map(|i| (i as f32 * 0.13).sin() * 0.5 + 0.5).collect();
+ let read = |r: Rect, buf: &mut Vec<f32>| {
+ buf.clear();
+ let (x0, x1) = ((r.x0 * n as i32) as usize, (r.x1 * n as i32) as usize);
+ let row = r.y0 as usize * src.width() as usize * n;
+ buf.extend_from_slice(&px[row + x0..row + x1]);
+ };
+ let Some(boxes) = box_widths(&FilterParams::GaussianBlur { radius: 12.0 }) else { panic!("box passes") };
+ let out = Rect::new(-5, 3, 155, 80);
+ let want = box_blur(src, &read, out, n, true, &boxes, &Interrupt::NONE).unwrap();
+ let checks = AtomicUsize::new(0);
+ let count = || {
+ checks.fetch_add(1, Ordering::SeqCst);
+ false
+ };
+ let got = box_blur(src, &read, out, n, true, &boxes, &Interrupt::cancel_only(&count)).unwrap();
+ assert_eq!(got.len(), want.len());
+ for ((ta, a), (tb, b)) in got.iter().zip(&want) {
+ assert_eq!(ta, tb);
+ assert!(a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits()), "strip {ta:?} differs");
+ }
+ let total = checks.load(Ordering::SeqCst);
+ for k in (0..total).step_by((total / 40).max(1)) {
+ let seen = AtomicUsize::new(0);
+ let cancel = || seen.fetch_add(1, Ordering::SeqCst) >= k;
+ assert!(box_blur(src, &read, out, n, true, &boxes, &Interrupt::cancel_only(&cancel)).is_none(), "cancelled at check {k}");
+ }
+ }
}
diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs
index 9cd6ff460..4575beb2e 100644
--- a/crates/engine/src/filters.rs
+++ b/crates/engine/src/filters.rs
@@ -298,7 +298,7 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result<Value>
let area = algo::output_area(&fp, content, bounds, sel_bounds);
*surf = filter(surf, &fp, area, bounds, selection.as_ref(), doc_bounds.union(&content))?;
if let Some(before) = &before {
- keep_alpha(before, surf);
+ keep_alpha(before, surf, &|| ctx.cancelled())?;
}
Ok(fp)
},
@@ -307,25 +307,56 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result<Value>
}
/// Lock transparency: put the layer's alpha back after a filter, in the tiles it changed.
-fn keep_alpha(old: &photocraft_raster::Surface, new: &mut photocraft_raster::Surface) {
+///
+/// The tiles are independent, so they are fixed in parallel, each in a scratch surface of its
+/// own, and `cancelled` is asked before each one: on a 24 MP layer (a Background, whose
+/// transparency is locked) a serial pass took about 400 ms that a cancelled job had to sit out
+/// (#6205). `Err(Cancelled)` leaves `new` holding all its tiles, some of them not yet fixed.
+fn keep_alpha(old: &photocraft_raster::Surface, new: &mut photocraft_raster::Surface, cancelled: &(dyn Fn() -> bool + Sync)) -> Result<()> {
+ use photocraft_raster::Surface;
+ use rayon::prelude::*;
if old.format() != new.format() || !new.format().alpha {
- return;
+ return Ok(());
}
let mut coords: Vec<_> = new.tiles().filter(|(c, t)| old.tile(**c).is_none_or(|o| !std::sync::Arc::ptr_eq(o, t))).map(|(c, _)| *c).collect();
coords.extend(old.tiles().filter(|(c, _)| new.tile(**c).is_none()).map(|(c, _)| *c));
- let n = new.channels();
- for c in coords {
- let r = c.rect();
- let o = old.read_region(r);
- let mut v = new.read_region(r);
- for (pn, po) in v.chunks_exact_mut(n).zip(o.chunks_exact(n)) {
- if let (Some(a), Some(b)) = (pn.last_mut(), po.last()) {
- *a = *b;
+ let (fmt, n) = (new.format(), new.channels());
+ let default = new.default_pixel();
+ // Each changed tile alone in a surface (a tile `new` lacks is taken as its default pixel, as
+ // `write_region` would create it).
+ let mut tiles: Vec<(photocraft_geom::Rect, Surface)> = coords
+ .iter()
+ .map(|c| {
+ let mut s = Surface::with_default(fmt, &default);
+ s.put_tiles(new.take_tiles(c.rect()));
+ (c.rect(), s)
+ })
+ .collect();
+ let fixed = tiles
+ .par_iter_mut()
+ .map(|(r, s)| {
+ if cancelled() {
+ return false;
}
- }
- new.write_region(r, &v);
+ let o = old.read_region(*r);
+ let mut v = s.read_region(*r);
+ for (pn, po) in v.chunks_exact_mut(n).zip(o.chunks_exact(n)) {
+ if let (Some(a), Some(b)) = (pn.last_mut(), po.last()) {
+ *a = *b;
+ }
+ }
+ s.write_region(*r, &v);
+ true
+ })
+ .reduce(|| true, |a, b| a && b);
+ for (_, s) in tiles {
+ new.put_tiles(s.tiles().map(|(c, t)| (*c, t.clone())));
+ }
+ if !fixed {
+ return Err(EngineError::Cancelled);
}
new.prune();
+ Ok(())
}
macro_rules! filter_cmd {
@@ -822,4 +853,74 @@ mod tests {
assert_eq!(sm.smart_filters[0].params["radius"], json!(2));
assert!(sm.cache.as_ref().unwrap().pixel(10, 5)[3] > 0.0, "cache was blurred");
}
+
+ /// The serial `keep_alpha` before #6205, kept as the oracle for the parallel one.
+ fn keep_alpha_serial(old: &photocraft_raster::Surface, new: &mut photocraft_raster::Surface) {
+ if old.format() != new.format() || !new.format().alpha {
+ return;
+ }
+ let mut coords: Vec<_> = new.tiles().filter(|(c, t)| old.tile(**c).is_none_or(|o| !std::sync::Arc::ptr_eq(o, t))).map(|(c, _)| *c).collect();
+ coords.extend(old.tiles().filter(|(c, _)| new.tile(**c).is_none()).map(|(c, _)| *c));
+ let n = new.channels();
+ for c in coords {
+ let r = c.rect();
+ let o = old.read_region(r);
+ let mut v = new.read_region(r);
+ for (pn, po) in v.chunks_exact_mut(n).zip(o.chunks_exact(n)) {
+ if let (Some(a), Some(b)) = (pn.last_mut(), po.last()) {
+ *a = *b;
+ }
+ }
+ new.write_region(r, &v);
+ }
+ new.prune();
+ }
+
+ /// A layer before and after a filter: tiles the filter changed, one it left shared, one it
+ /// emptied (only in `old`) and one it added (only in `new`).
+ fn alpha_pair(sample: photocraft_color::SampleType) -> (photocraft_raster::Surface, photocraft_raster::Surface) {
+ use photocraft_geom::Rect;
+ use photocraft_raster::Surface;
+ let fmt = photocraft_color::PixelFormat { mode: photocraft_color::ColorMode::Rgb, sample, alpha: true };
+ let pattern = |r: Rect, k: f32| -> Vec<f32> {
+ (0..r.width() as usize * r.height() as usize * 4).map(|i| ((i as f32 * 0.37 + k).sin() * 0.5 + 0.5).clamp(0.0, 1.0)).collect()
+ };
+ let mut old = Surface::new(fmt);
+ let r = Rect::new(-40, -20, 700, 300);
+ old.write_region(r, &pattern(r, 0.0));
+ let mut new = old.clone();
+ let changed = Rect::new(-40, -20, 400, 300);
+ new.write_region(changed, &pattern(changed, 1.3));
+ let emptied = photocraft_geom::TileCoord::containing(600, 100).rect();
+ drop(new.take_tiles(emptied));
+ let added = Rect::new(800, 0, 900, 50);
+ new.write_region(added, &pattern(added, 2.1));
+ (old, new)
+ }
+
+ #[test]
+ fn keep_alpha_matches_the_serial_pass_at_every_depth() {
+ use photocraft_color::SampleType;
+ for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let (old, new) = alpha_pair(sample);
+ let mut want = new.clone();
+ keep_alpha_serial(&old, &mut want);
+ let mut got = new.clone();
+ keep_alpha(&old, &mut got, &|| false).unwrap();
+ assert!(got == want, "{sample:?}: parallel keep_alpha differs from the serial pass");
+ assert_ne!(got, new, "{sample:?}: alpha was put back");
+ }
+ }
+
+ #[test]
+ fn keep_alpha_stops_when_cancelled_and_keeps_the_tiles() {
+ let (old, new) = alpha_pair(photocraft_color::SampleType::U8);
+ let mut got = new.clone();
+ let calls = std::sync::atomic::AtomicUsize::new(0);
+ let cancel = || calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) >= 2;
+ assert!(matches!(keep_alpha(&old, &mut got, &cancel), Err(EngineError::Cancelled)));
+ // The cancel was seen inside the pass (after some tiles), and no tile went missing.
+ assert!(calls.load(std::sync::atomic::Ordering::SeqCst) > 2);
+ assert!(new.tiles().all(|(c, _)| got.tile(*c).is_some()));
+ }
}
diff --git a/docs/gaps.md b/docs/gaps.md
index faf0884c8..3907ab945 100644
--- a/docs/gaps.md
+++ b/docs/gaps.md
@@ -1,6 +1,6 @@
# Where PhotoCraft falls short of Photoshop
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026
+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** minor (G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget, #6205; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026
Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact
on the way to beta. This is the work list agents pick from: take the highest-ranked entry that
@@ -212,6 +212,11 @@ what an agent can't finish alone.
default small blur and the 36 MP saturated-field gain are inconclusive.
[Method and full ranges](tilt-shift-performance.md). Native GUI latency remains
unmeasured; no scorecard budget or parity percentage is changed by this work.
+- **Measured progress (2026-10-15):** P25, cancelling a Gaussian Blur r 50 job on 24 MP, stops
+ within 13–44 ms max over five runs (was 337–399 ms; budget 200 ms): the transparency-lock
+ pass that puts a Background's alpha back now runs per tile in parallel and checks for
+ cancellation, and column-strip box passes check between passes. The uncancelled job is
+ ~40% faster (p50 about 690 → 400 ms). #6205.
- **Missing:** 22 of 25 budgeted scenarios are over budget (baseline 2026-10-05, a heavily
loaded machine): layer move with styles 321 ms p50 against 25 ms, opacity change 276 ms
against 20 ms, paste 12 MP 1.2 s against 100 ms, layer move on 15000×10000 16-bit 2.7 s,
@@ -270,6 +275,7 @@ what an agent can't finish alone.
| Date | Change | Summary |
|---|---|---|
+| 2026-10-15 | minor | G2: a cancelled 24 MP Gaussian Blur job stops within 44 ms max (P25, budget 200 ms; was about 400 ms), the uncancelled job about 40% faster; #6205 |
| 2026-10-14 | minor | G1: a PSD smart object's filter mask shows when the file opens (Photoshop stores the filtered pixels unmasked); export stores them that way too; Photoshop-oracle floor 185 → 188 of 258 |
| 2026-10-13 | minor | G14: D90 image area measured (4288 × 2848 at (10, 10)); gap remains open |
| 2026-10-14 | minor | Corpus floors raised to the measured results of the CMYK, Lab, 32-bit, Levels, Threshold, Posterize, feather and pass-through fixes landed together: Photoshop-authored 165 → 185 of 258, io 146 → 148 of 170, psd-tools 242 → 249 of 309 |