Skip to content

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

Speed up large-radius Unsharp Mask with guarded FFT convolution (#2987)

optimalbytee50c4f72af71f
diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs
index 39f48034b..78dae7b06 100644
--- a/crates/algo/src/lib.rs
+++ b/crates/algo/src/lib.rs
@@ -553,7 +553,8 @@ impl FilterParams {
let g = |sigma: f32| Halo::Radius((sigma.max(0.0) * 3.0).ceil() as i32 + 1);
match self {
FilterParams::GaussianBlur { radius } | FilterParams::HighPass { radius } => g(*radius),
- FilterParams::UnsharpMask { radius, .. } | FilterParams::SmartSharpen { radius, .. } => g(*radius),
+ FilterParams::UnsharpMask { radius, .. } => Halo::Radius(sharpen::exact::halo(*radius)),
+ FilterParams::SmartSharpen { radius, .. } => g(*radius),
FilterParams::BoxBlur { radius }
| FilterParams::SurfaceBlur { radius, .. }
| FilterParams::Median { radius }
@@ -938,7 +939,8 @@ pub fn apply_in(surface: &Surface, params: &FilterParams, area: Rect, bounds: Re
}
/// [`apply_in`] that can be cancelled (checked before each tile) and reports progress per tile
-/// group. `None` when `ctl` was cancelled; the input surface is never modified.
+/// group. `None` when cancelled, or when a checked filter rejects geometry/allocation;
+/// the input surface is never modified.
pub fn apply_in_with(
surface: &Surface,
params: &FilterParams,
@@ -970,13 +972,13 @@ pub fn apply_tiled(
tile: i32,
extent: Option<Rect>,
) -> Surface {
- // Preserve the input if a checked Shape Blur allocation cannot be completed.
+ // Preserve the input if a checked filter allocation cannot be completed.
apply_tiled_with(surface, params, area, bounds, selection, tile, extent, &photocraft_raster::Interrupt::NONE).unwrap_or_else(|| surface.clone())
}
/// [`apply_tiled`] with cancellation (checked before each tile, so a cancel takes effect within
/// one tile's work) and progress (after each group of tiles). `None` when cancelled,
-/// or when Shape Blur cannot allocate a tile.
+/// or when a checked filter rejects geometry or cannot allocate a tile.
#[allow(clippy::too_many_arguments)]
pub fn apply_tiled_with(
surface: &Surface,
@@ -1001,15 +1003,27 @@ fn apply_tiled_with_impl(
tile: i32,
extent: Option<Rect>,
ctl: &photocraft_raster::Interrupt,
- prepare_radial: bool,
+ prepare_fast_paths: bool,
) -> Option<Surface> {
if ctl.cancelled() {
return None;
}
+ if let FilterParams::UnsharpMask { amount, radius, threshold } = *params
+ && (!sharpen::exact::valid_params(amount, radius, threshold)
+ || !sharpen::exact::valid_area(area)
+ || !sharpen::exact::valid_area(bounds)
+ || extent.is_some_and(|e| !sharpen::exact::valid_area(e)))
+ {
+ return None;
+ }
let mut out = surface.clone();
if area.is_empty() {
return Some(out);
}
+ #[cfg(not(target_arch = "wasm32"))]
+ if prepare_fast_paths && let Some(result) = sharpen::fft::apply(surface, params, area, selection, extent, ctl) {
+ return result;
+ }
if let Some(boxes) = blur::box_widths(params) {
return apply_box_blur(out, surface, area, extent, selection, &boxes, ctl);
}
@@ -1017,15 +1031,15 @@ fn apply_tiled_with_impl(
return result;
}
// The public tile override must not create a zero-step loop or an
- // unbounded Shape Blur scratch buffer. Standard automatic tiles are unchanged.
- let tile = if matches!(params, FilterParams::ShapeBlur { .. }) { tile.clamp(1, 2048) } else { tile };
+ // unbounded scratch buffer for these checked filters. Automatic tiles are unchanged.
+ let tile = if matches!(params, FilterParams::ShapeBlur { .. } | FilterParams::UnsharpMask { .. }) { tile.clamp(1, 2048) } else { tile };
let fmt = surface.format();
let ctx = Ctx { bounds, mode: fmt.mode, alpha: fmt.alpha };
// Prepare the immutable sample transforms once for all output tiles. If the
// optional table allocation fails, use the existing sampler; only a real
// cancellation returns None. Source reads keep their upstream semantics.
let radial = match params {
- FilterParams::RadialBlur { amount, method, quality, center_x, center_y } if prepare_radial => {
+ FilterParams::RadialBlur { amount, method, quality, center_x, center_y } if prepare_fast_paths => {
blur::radial::Plan::for_area(bounds, *amount, *method, *quality, (*center_x, *center_y), area, ctl)
}
_ => None,
@@ -1034,6 +1048,17 @@ fn apply_tiled_with_impl(
return None;
}
let halo = params.halo_for(bounds);
+ if matches!(params, FilterParams::UnsharpMask { .. }) {
+ let Halo::Radius(reach) = halo else { return None };
+ let (w, h) = (area.width().min(tile as u32) as usize, area.height().min(tile as u32) as usize);
+ let read_samples = w.checked_add(2 * reach as usize)?.checked_mul(h.checked_add(2 * reach as usize)?)?.checked_mul(fmt.channels())?;
+ let tile_count = u64::from(area.width()).div_ceil(tile as u64).checked_mul(u64::from(area.height()).div_ceil(tile as u64))?;
+ // Reject hostile source-window sizes before Image::read allocates them.
+ // Ordinary filter parameters and automatic tiles fit these bounds.
+ if read_samples > 512 * 1024 * 1024 || read_samples.checked_mul(std::mem::size_of::<f32>())? > isize::MAX as usize || tile_count > 1_048_576 {
+ return None;
+ }
+ }
let shared = (halo == Halo::Bounds).then(|| Image::read(surface, bounds.union(&area)));
// Shape rasterization depends only on params, not on a tile's pixels.
let shape = match params {
@@ -1091,7 +1116,10 @@ fn apply_tiled_with_impl(
None if ctl.cancelled() => None,
None => Some(kernel(params, src, *t, &ctx)),
},
- (None, None) => Some(kernel(params, src, *t, &ctx)),
+ (None, None) => match *params {
+ FilterParams::UnsharpMask { amount, radius, threshold } => sharpen::exact::run(src, *t, &ctx, amount, radius, threshold, ctl),
+ _ => Some(kernel(params, src, *t, &ctx)),
+ },
}) else {
return (*t, Vec::new());
};
@@ -1124,9 +1152,11 @@ fn apply_tiled_with_impl(
if ctl.cancelled() {
return None;
}
- // Shape Blur can reject malformed geometry or an allocation failure.
+ // Checked filters can reject malformed geometry or an allocation failure.
// Do not hand an incomplete tile to Surface::write_region.
- if shape.is_some() && results.iter().any(|(t, data)| data.len() != t.width() as usize * t.height() as usize * fmt.channels()) {
+ if (shape.is_some() || matches!(params, FilterParams::UnsharpMask { .. }))
+ && results.iter().any(|(t, data)| data.len() != t.width() as usize * t.height() as usize * fmt.channels())
+ {
return None;
}
for (t, data) in results {
diff --git a/crates/algo/src/sharpen.rs b/crates/algo/src/sharpen.rs
index 175de2b37..9e87c6b84 100644
--- a/crates/algo/src/sharpen.rs
+++ b/crates/algo/src/sharpen.rs
@@ -6,6 +6,17 @@ use crate::Ctx;
use crate::blur::{conv_sep, gaussian_kernel};
use crate::image::Image;
+pub(crate) mod exact;
+
+#[cfg(not(target_arch = "wasm32"))]
+pub(crate) mod fft;
+
+#[cfg(test)]
+mod tests;
+
+#[cfg(all(test, not(target_arch = "wasm32")))]
+mod fft_bench;
+
fn with_blur(src: &Image, out: Rect, ctx: &Ctx, radius: f32, mut f: impl FnMut(f32, f32) -> f32) -> Vec<f32> {
let k = gaussian_kernel(radius);
let blurred = conv_sep(src, out, &k, &k, ctx.alpha);
@@ -24,12 +35,7 @@ fn with_blur(src: &Image, out: Rect, ctx: &Ctx, radius: f32, mut f: impl FnMut(f
}
pub(crate) fn unsharp(src: &Image, out: Rect, ctx: &Ctx, amount: f32, radius: f32, threshold: f32) -> Vec<f32> {
- let k = amount / 100.0;
- let t = threshold / 255.0;
- with_blur(src, out, ctx, radius, |o, b| {
- let d = o - b;
- if d.abs() + 1e-6 >= t { o + k * d } else { o }
- })
+ exact::run(src, out, ctx, amount, radius, threshold, &photocraft_raster::Interrupt::NONE).unwrap_or_default()
}
pub(crate) fn smart(src: &Image, out: Rect, ctx: &Ctx, amount: f32, radius: f32, reduce_noise: f32) -> Vec<f32> {
diff --git a/crates/algo/src/sharpen/exact.rs b/crates/algo/src/sharpen/exact.rs
new file mode 100644
index 000000000..7d74bc538
--- /dev/null
+++ b/crates/algo/src/sharpen/exact.rs
@@ -0,0 +1,134 @@
+//! Exact separable convolution for Unsharp Mask: stream one source row and reuse
+//! the blurred output for the final arithmetic. Each sample retains its tap order.
+use crate::image::premultiply;
+use crate::{Ctx, Image};
+use photocraft_geom::Rect;
+use photocraft_raster::Interrupt;
+
+const MAX_SAMPLES: usize = 128 * 1024 * 1024;
+// The filter dialog caps radius at 1000. Preserve Details resampling can ask
+// for more; permit that while the unchanged kernel's i32 square is safe.
+const MAX_RADIUS: f32 = 15_446.0;
+
+pub(crate) fn valid_params(amount: f32, radius: f32, threshold: f32) -> bool {
+ amount.is_finite() && threshold.is_finite() && radius.is_finite() && (0.0..=MAX_RADIUS).contains(&radius)
+}
+
+pub(crate) fn halo(radius: f32) -> i32 {
+ if radius.is_finite() && (0.0..=MAX_RADIUS).contains(&radius) { (radius * 3.0).ceil() as i32 + 1 } else { 0 }
+}
+
+pub(crate) fn valid_area(r: Rect) -> bool {
+ r.x0 <= r.x1
+ && r.y0 <= r.y1
+ && r.width() <= 300_000
+ && r.height() <= 300_000
+ && [r.x0, r.x1, r.y0, r.y1].iter().all(|v| (-1_000_000..=1_000_000).contains(v))
+}
+
+fn zeros(len: usize) -> Option<Vec<f32>> {
+ if len > MAX_SAMPLES {
+ return None;
+ }
+ let mut data = Vec::new();
+ data.try_reserve_exact(len).ok()?;
+ data.resize(len, 0.0);
+ Some(data)
+}
+
+/// Checked contiguous row copy, with the same zero extension as Image::get.
+fn read_row(src: &Image, x0: i32, x1: i32, y: i32, dst: &mut [f32]) -> Option<()> {
+ dst.fill(0.0);
+ if y < src.rect.y0 || y >= src.rect.y1 {
+ return Some(());
+ }
+ let (lo, hi) = (x0.max(src.rect.x0), x1.min(src.rect.x1));
+ if lo >= hi {
+ return Some(());
+ }
+ let n = src.ch;
+ let count = usize::try_from(i64::from(hi) - i64::from(lo)).ok()?.checked_mul(n)?;
+ let offset = usize::try_from(i64::from(lo) - i64::from(x0)).ok()?.checked_mul(n)?;
+ let row = usize::try_from(i64::from(y) - i64::from(src.rect.y0)).ok()?;
+ let col = usize::try_from(i64::from(lo) - i64::from(src.rect.x0)).ok()?;
+ let start = row.checked_mul(src.rect.width() as usize)?.checked_add(col)?.checked_mul(n)?;
+ dst.get_mut(offset..offset.checked_add(count)?)?.copy_from_slice(src.data.get(start..start.checked_add(count)?)?);
+ Some(())
+}
+
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn run(src: &Image, out: Rect, ctx: &Ctx, amount: f32, radius: f32, threshold: f32, ctl: &Interrupt) -> Option<Vec<f32>> {
+ if ctl.cancelled() || !valid_params(amount, radius, threshold) || !valid_area(out) || !valid_area(src.rect) {
+ return None;
+ }
+ let n = src.ch;
+ if n == 0 || n > crate::fxutil::MAXC {
+ return None;
+ }
+ if src.data.len() != (src.rect.width() as usize).checked_mul(src.rect.height() as usize)?.checked_mul(n)? {
+ return None;
+ }
+ if out.is_empty() {
+ return Some(Vec::new());
+ }
+ let kernel = super::gaussian_kernel(radius);
+ let r = kernel.len() / 2;
+ let (ow, oh) = (out.width() as usize, out.height() as usize);
+ let row_len = ow.checked_mul(n)?;
+ let th = oh.checked_add(2 * r)?;
+ let ww = ow.checked_add(2 * r)?;
+ let (x0, x1, y0) = (out.x0.checked_sub(r as i32)?, out.x1.checked_add(r as i32)?, out.y0.checked_sub(r as i32)?);
+ let mut row = zeros(ww.checked_mul(n)?)?;
+ let mut tmp = zeros(row_len.checked_mul(th)?)?;
+ let mut result = zeros(row_len.checked_mul(oh)?)?;
+ for (y, dst) in tmp.chunks_exact_mut(row_len).enumerate() {
+ if ctl.cancelled() {
+ return None;
+ }
+ read_row(src, x0, x1, y0.checked_add(y as i32)?, &mut row)?;
+ premultiply(&mut row, n, ctx.alpha);
+ // Tap-major traversal exposes contiguous independent samples to LLVM. No
+ // reduction, tap merging, symmetry or fused multiply-add changes the sums.
+ for (i, weight) in kernel.iter().enumerate() {
+ let start = i.checked_mul(n)?;
+ let samples = row.get(start..start.checked_add(row_len)?)?;
+ for (d, s) in dst.iter_mut().zip(samples) {
+ *d += s * weight;
+ }
+ }
+ }
+ let (amount, threshold) = (amount / 100.0, threshold / 255.0);
+ let cc = n - usize::from(ctx.alpha);
+ for (y, dst) in result.chunks_exact_mut(row_len).enumerate() {
+ if ctl.cancelled() {
+ return None;
+ }
+ for (i, weight) in kernel.iter().enumerate() {
+ let start = y.checked_add(i)?.checked_mul(row_len)?;
+ let samples = tmp.get(start..start.checked_add(row_len)?)?;
+ for (d, s) in dst.iter_mut().zip(samples) {
+ *d += s * weight;
+ }
+ }
+ let originals = row.get_mut(..row_len)?;
+ read_row(src, out.x0, out.x1, out.y0.checked_add(y as i32)?, originals)?;
+ for (blurred, original) in dst.chunks_exact_mut(n).zip(originals.chunks_exact(n)) {
+ if ctx.alpha && *original.last()? <= 0.0 {
+ blurred.copy_from_slice(original);
+ continue;
+ }
+ let a = if ctx.alpha { *blurred.last()? } else { 1.0 };
+ for (b, o) in blurred.iter_mut().zip(original).take(cc) {
+ // Keep the original unpremultiply cut-off and division, followed by
+ // the threshold epsilon and inclusive comparison, at every depth.
+ let b_value = if ctx.alpha { if a > 1e-7 { *b / a } else { 0.0 } } else { *b };
+ let d = o - b_value;
+ *b = if d.abs() + 1e-6 >= threshold { o + amount * d } else { *o };
+ }
+ if ctx.alpha {
+ *blurred.last_mut()? = *original.last()?;
+ }
+ }
+ }
+ Some(result)
+}
diff --git a/crates/algo/src/sharpen/fft.rs b/crates/algo/src/sharpen/fft.rs
new file mode 100644
index 000000000..6fdf18c8b
--- /dev/null
+++ b/crates/algo/src/sharpen/fft.rs
@@ -0,0 +1,325 @@
+//! Wide exact-kernel Gaussian convolution using FFTs. Summation order changes:
+//! positive thresholds and unstable samples retain the sequential f32 fallback.
+use crate::{FilterParams, Image};
+use photocraft_geom::Rect;
+use photocraft_raster::{Interrupt, Surface};
+use rayon::prelude::*;
+use rustfft::{Fft, FftPlanner, num_complex::Complex};
+use std::sync::{
+ Arc,
+ atomic::{AtomicUsize, Ordering},
+};
+
+const MAX_BYTES: usize = 1 << 30;
+const MAX_SIDE: usize = 32_768;
+const STRIPE: usize = 32;
+type Number = Complex<f64>;
+
+fn buffer<T: Clone>(len: usize, value: T) -> Option<Vec<T>> {
+ if len.checked_mul(std::mem::size_of::<T>())? > MAX_BYTES {
+ return None;
+ }
+ let mut data = Vec::new();
+ data.try_reserve_exact(len).ok()?;
+ data.resize(len, value);
+ Some(data)
+}
+
+struct Plan {
+ size: usize,
+ forward: Arc<dyn Fft<f64>>,
+ inverse: Arc<dyn Fft<f64>>,
+ spectrum: Vec<Number>,
+ scratch: usize,
+}
+impl Plan {
+ fn new(needed: usize, kernel: &[f32], planner: &mut FftPlanner<f64>) -> Option<Self> {
+ let size = needed.checked_next_power_of_two()?;
+ if size > MAX_SIDE || kernel.len() > size {
+ return None;
+ }
+ let forward = planner.plan_fft_forward(size);
+ let inverse = planner.plan_fft_inverse(size);
+ let scratch = forward.get_inplace_scratch_len().max(inverse.get_inplace_scratch_len());
+ let mut spectrum = buffer(size, Number::default())?;
+ for (dst, &weight) in spectrum.iter_mut().zip(kernel) {
+ dst.re = f64::from(weight) / size as f64;
+ }
+ forward.process_with_scratch(&mut spectrum, &mut buffer(scratch, Number::default())?);
+ Some(Self { size, forward, inverse, spectrum, scratch })
+ }
+ fn work(&self) -> Option<(Vec<Number>, Vec<Number>)> {
+ Some((buffer(self.size, Number::default())?, buffer(self.scratch, Number::default())?))
+ }
+ fn convolve(&self, data: &mut [Number], scratch: &mut [Number]) -> Option<()> {
+ if data.len() != self.size || scratch.len() < self.scratch {
+ return None;
+ }
+ self.forward.process_with_scratch(data, scratch);
+ for (d, k) in data.iter_mut().zip(&self.spectrum) {
+ *d *= k;
+ }
+ self.inverse.process_with_scratch(data, scratch);
+ Some(())
+ }
+}
+
+// Bound the complete temporary working set, including all concurrently live
+// column gathers, originals, FFT scratch and result stripes. Document tiles are
+// excluded, just as in the existing tile scheduler's scratch budget.
+fn group_size(resident: usize, worker: usize, count: usize, workers: usize) -> Option<usize> {
+ let group = MAX_BYTES.checked_sub(resident)?.checked_div(worker.max(1))?.min(workers).min(count);
+ (group > 0).then_some(group)
+}
+
+/// `None` declines the optimization, `Some(None)` propagates cancellation.
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn apply(
+ surface: &Surface,
+ params: &FilterParams,
+ area: Rect,
+ selection: Option<&Surface>,
+ extent: Option<Rect>,
+ ctl: &Interrupt,
+) -> Option<Option<Surface>> {
+ let FilterParams::UnsharpMask { amount, radius, threshold } = *params else { return None };
+ // At a positive threshold, even a tiny sum-order difference can switch the
+ // entire sharpen contribution. Zero/negative thresholds always keep it.
+ if !(64.0..=1000.0).contains(&radius)
+ || threshold > 0.0
+ || amount == 0.0
+ || !super::exact::valid_params(amount, radius, threshold)
+ || !super::exact::valid_area(area)
+ || area.is_empty()
+ || u64::from(area.width()) * u64::from(area.height()) < 65_536
+ || !(1..=crate::fxutil::MAXC).contains(&surface.channels())
+ || selection.is_some_and(|s| s.channels() == 0)
+ || extent.is_some_and(|e| !super::exact::valid_area(e) || area.intersect(&e) != area)
+ {
+ return None;
+ }
+ if ctl.cancelled() {
+ return Some(None);
+ }
+ match run(surface, area, amount, radius, selection, extent, ctl) {
+ Some(out) => Some(Some(out)),
+ None if ctl.cancelled() => Some(None),
+ None => None,
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+fn run(surface: &Surface, area: Rect, amount: f32, radius: f32, selection: Option<&Surface>, extent: Option<Rect>, ctl: &Interrupt) -> Option<Surface> {
+ let (w, h, n) = (area.width() as usize, area.height() as usize, surface.channels());
+ let alpha = surface.format().alpha;
+ let kernel = super::gaussian_kernel(radius);
+ let r = kernel.len() / 2;
+ let reach = i32::try_from(r).ok()?;
+ let (x0, x1) = (area.x0.checked_sub(reach)?, area.x1.checked_add(reach)?);
+ let (y0, y1) = (area.y0.checked_sub(reach)?, area.y1.checked_add(reach)?);
+ let (read_x0, read_x1, read_y0, read_y1) = match extent {
+ Some(e) => (x0.max(e.x0), x1.min(e.x1), y0.max(e.y0), y1.min(e.y1)),
+ None => (x0, x1, y0, y1),
+ };
+ let rows = usize::try_from(i64::from(read_y1) - i64::from(read_y0)).ok()?;
+ let read_width = usize::try_from(i64::from(read_x1) - i64::from(read_x0)).ok()?;
+ let row_len = w.checked_mul(n)?;
+ let samples = row_len.checked_mul(rows)?;
+ let resident = samples.checked_mul(4)?;
+ let mut planner = FftPlanner::<f64>::new();
+ let horizontal = Plan::new(w.checked_add(2 * r)?, &kernel, &mut planner)?;
+ let vertical = Plan::new(h.checked_add(2 * r)?, &kernel, &mut planner)?;
+ // A conservative allowance includes FFT plans/twiddles in addition to spectra.
+ let plans = horizontal.size.checked_add(vertical.size)?.checked_mul(256)?;
+ let resident = resident.checked_add(plans)?;
+ let workers = rayon::current_num_threads().max(1);
+ let horizontal_worker = read_width.checked_mul(n)?.checked_mul(4)?.checked_add(horizontal.size.checked_add(horizontal.scratch)?.checked_mul(16)?)?;
+ let vertical_worker = STRIPE
+ .checked_mul(rows)?
+ .checked_mul(n)?
+ .checked_mul(4)?
+ .checked_add(STRIPE.checked_mul(h)?.checked_mul(n)?.checked_mul(12)?)?
+ .checked_add(vertical.size.checked_add(vertical.scratch)?.checked_mul(16)?)?;
+ let group = group_size(resident, horizontal_worker.max(vertical_worker), w.div_ceil(STRIPE), workers)?;
+ let mut tmp = buffer(samples, 0.0f32)?;
+ let finished = AtomicUsize::new(0);
+ // Read each needed real row once. Outside a repeated extent, horizontal
+ // results are repeated lazily by the vertical gather, not transformed again.
+ for band in tmp.chunks_mut(row_len.checked_mul(group)?) {
+ let first = finished.load(Ordering::Relaxed);
+ let ok: Option<Vec<()>> = band
+ .par_chunks_exact_mut(row_len)
+ .enumerate()
+ .map(|(offset, dst)| {
+ if ctl.cancelled() {
+ return None;
+ }
+ let y = read_y0.checked_add(i32::try_from(first.checked_add(offset)?).ok()?)?;
+ let mut row = buffer(read_width.checked_mul(n)?, 0.0f32)?;
+ // Reservation above covers resize, so the reusable raster read cannot allocate.
+ surface.read_region_into(Rect::new(read_x0, y, read_x1, y.checked_add(1)?), &mut row);
+ let mut scales = [0.0f64; crate::fxutil::MAXC];
+ for px in row.chunks_exact_mut(n) {
+ if px.iter().any(|v| !v.is_finite() || v.abs() > 1e6) || (alpha && !px.last().is_some_and(|a| (0.0..=1.0).contains(a))) {
+ return None;
+ }
+ let a = if alpha { *px.last()? } else { 1.0 };
+ for (c, v) in px.iter_mut().enumerate() {
+ if alpha && c + 1 < n {
+ *v *= a;
+ }
+ let scale = scales.get_mut(c)?;
+ *scale = scale.max(f64::from(v.abs()));
+ }
+ }
+ let (mut data, mut scratch) = horizontal.work()?;
+ for channel in (0..n).step_by(2) {
+ if ctl.cancelled() {
+ return None;
+ }
+ data.fill(Number::default());
+ for (i, d) in data.iter_mut().take(w + 2 * r).enumerate() {
+ let sx = x0.checked_add(i32::try_from(i).ok()?)?.clamp(read_x0, read_x1.checked_sub(1)?);
+ let start = usize::try_from(sx - read_x0).ok()?.checked_mul(n)?;
+ let px = row.get(start..start.checked_add(n)?)?;
+ let sample = |c: usize| -> f64 {
+ match (px.get(c), scales.get(c)) {
+ (Some(v), Some(s)) if *s > 0.0 => f64::from(*v) / s,
+ _ => 0.0,
+ }
+ };
+ *d = Number::new(sample(channel), sample(channel + 1));
+ }
+ horizontal.convolve(&mut data, &mut scratch)?;
+ for (px, d) in dst.chunks_exact_mut(n).zip(data.get(2 * r..2 * r + w)?) {
+ *px.get_mut(channel)? = (d.re * scales.get(channel)?) as f32;
+ if let Some(v) = px.get_mut(channel + 1) {
+ *v = (d.im * scales.get(channel + 1)?) as f32;
+ }
+ }
+ }
+ finished.fetch_add(1, Ordering::Relaxed);
+ Some(())
+ })
+ .collect();
+ ok?;
+ ctl.progress(0.5 * finished.load(Ordering::Relaxed) as f32 / rows as f32);
+ if ctl.cancelled() {
+ return None;
+ }
+ }
+ let mut out = surface.clone();
+ let count = w.div_ceil(STRIPE);
+ for first in (0..count).step_by(group) {
+ let end = first.checked_add(group)?.min(count);
+ let results: Option<Vec<_>> = (first..end)
+ .into_par_iter()
+ .map(|index| {
+ if ctl.cancelled() {
+ return None;
+ }
+ let x = index.checked_mul(STRIPE)?;
+ let width = STRIPE.min(w.checked_sub(x)?);
+ let mut columns = buffer(width.checked_mul(rows)?.checked_mul(n)?, 0.0f32)?;
+ for (y, row) in tmp.chunks_exact(row_len).enumerate() {
+ if y % 64 == 0 && ctl.cancelled() {
+ return None;
+ }
+ for (c, px) in row.get(x * n..(x + width) * n)?.chunks_exact(n).enumerate() {
+ let start = (c * rows + y) * n;
+ columns.get_mut(start..start + n)?.copy_from_slice(px);
+ }
+ }
+ let rect = Rect::new(area.x0.checked_add(x as i32)?, area.y0, area.x0.checked_add((x + width) as i32)?, area.y1);
+ let len = width.checked_mul(h)?.checked_mul(n)?;
+ let mut result = buffer(len, 0.0f32)?;
+ let mut original = buffer(len, 0.0f32)?;
+ surface.read_region_into(rect, &mut original);
+ let (mut data, mut scratch) = vertical.work()?;
+ for (c, samples) in columns.chunks_exact(rows * n).enumerate() {
+ if ctl.cancelled() {
+ return None;
+ }
+ let mut scales = [0.0f64; crate::fxutil::MAXC];
+ for px in samples.chunks_exact(n) {
+ for (s, v) in scales.iter_mut().zip(px) {
+ *s = s.max(f64::from(v.abs()));
+ }
+ }
+ for channel in (0..n).step_by(2) {
+ if ctl.cancelled() {
+ return None;
+ }
+ data.fill(Number::default());
+ for (i, d) in data.iter_mut().take(h + 2 * r).enumerate() {
+ let sy = y0.checked_add(i as i32)?.clamp(read_y0, read_y1.checked_sub(1)?);
+ let start = usize::try_from(sy - read_y0).ok()?.checked_mul(n)?;
+ let px = samples.get(start..start + n)?;
+ let sample = |c: usize| -> f64 {
+ match (px.get(c), scales.get(c)) {
+ (Some(v), Some(s)) if *s > 0.0 => f64::from(*v) / s,
+ _ => 0.0,
+ }
+ };
+ *d = Number::new(sample(channel), sample(channel + 1));
+ }
+ vertical.convolve(&mut data, &mut scratch)?;
+ for (y, d) in data.get(2 * r..2 * r + h)?.iter().enumerate() {
+ let start = (y * width + c) * n;
+ *result.get_mut(start + channel)? = (d.re * scales.get(channel)?) as f32;
+ if let Some(v) = result.get_mut(start + channel + 1).filter(|_| channel + 1 < n) {
+ *v = (d.im * scales.get(channel + 1)?) as f32;
+ }
+ }
+ }
+ }
+ for (px, o) in result.chunks_exact_mut(n).zip(original.chunks_exact(n)) {
+ if alpha && *o.last()? <= 0.0 {
+ px.copy_from_slice(o);
+ continue;
+ }
+ let a = if alpha { *px.last()? } else { 1.0 };
+ // Near the original unpremultiply cutoff, cancellation/FFT noise
+ // or f32 sum order can expose colour. Decline the whole fast path.
+ let uncertainty = 4.0 * kernel.len() as f32 * f32::EPSILON;
+ if alpha && a <= 1e-7 + uncertainty {
+ return None;
+ }
+ for (v, o) in px.iter_mut().zip(o).take(n - usize::from(alpha)) {
+ let b = if alpha { *v / a } else { *v };
+ *v = o + amount / 100.0 * (o - b);
+ if !v.is_finite() {
+ return None;
+ }
+ }
+ if alpha {
+ *px.last_mut()? = *o.last()?;
+ }
+ }
+ if let Some(sel) = selection {
+ crate::mix_selection(&mut result, rect, sel, &Image { rect, ch: n, data: original }, alpha);
+ }
+ Some((rect, result))
+ })
+ .collect();
+ for (rect, data) in results? {
+ if ctl.cancelled() {
+ return None;
+ }
+ out.try_write_region(rect, &data).ok()?;
+ }
+ ctl.progress(0.5 + 0.48 * end as f32 / count as f32);
+ }
+ if ctl.cancelled() {
+ return None;
+ }
+ out.prune();
+ if ctl.cancelled() {
+ return None;
+ }
+ ctl.progress(1.0);
+ Some(out)
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/algo/src/sharpen/fft/tests.rs b/crates/algo/src/sharpen/fft/tests.rs
new file mode 100644
index 000000000..e1f7a26ed
--- /dev/null
+++ b/crates/algo/src/sharpen/fft/tests.rs
@@ -0,0 +1,146 @@
+use super::*;
+use crate::sharpen::tests::{reference, source};
+use crate::{Ctx, image::Image};
+use photocraft_color::{ColorMode, PixelFormat, SampleType};
+
+fn compare(old: &Surface, new: &Surface, area: Rect) {
+ let tolerance = match old.format().sample {
+ SampleType::U8 => 1.0 / 255.0 + 1e-7,
+ SampleType::U16 => 2.0 / 65535.0 + 1e-7,
+ SampleType::F32 => 3e-5,
+ };
+ for (a, b) in old.read_region(area).iter().zip(new.read_region(area)) {
+ let limit = if old.format().sample == SampleType::F32 { tolerance * (1.0 + a.abs()) } else { tolerance };
+ assert!((a - b).abs() <= limit, "{a} != {b}, tolerance {limit}");
+ }
+}
+
+#[test]
+fn fft_preserves_gaussian_quality_at_every_depth_and_model() {
+ let area = Rect::new(-3, 2, 10, 13);
+ for mode in [
+ ColorMode::Bitmap,
+ ColorMode::Grayscale,
+ ColorMode::Duotone,
+ ColorMode::Indexed,
+ ColorMode::Rgb,
+ ColorMode::Cmyk,
+ ColorMode::Lab,
+ ColorMode::Multichannel,
+ ] {
+ for depth in SampleType::ALL {
+ for alpha in [false, true] {
+ let s = source(area, PixelFormat::new(mode, depth, alpha));
+ let ctx = Ctx { bounds: area, mode, alpha };
+ for radius in [3.25, 64.0] {
+ let src = Image::read_clamped(&s, area.inflate((radius * 3.0_f32).ceil() as i32 + 1), area);
+ let pixels = reference::unsharp(&src, area, &ctx, 500.0, radius, 0.0);
+ let mut expected = s.clone();
+ expected.write_region(area, &pixels);
+ let actual = run(&s, area, 500.0, radius, None, Some(area), &Interrupt::NONE).unwrap();
+ compare(&expected, &actual, area);
+ if alpha {
+ for (a, b) in s.read_region(area).chunks_exact(s.channels()).zip(actual.read_region(area).chunks_exact(s.channels())) {
+ assert_eq!(a.last(), b.last());
+ if a.last() == Some(&0.0) {
+ assert_eq!(a, b);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn fft_keeps_partial_regions_selections_and_edge_policies() {
+ let extent = Rect::new(-7, -9, 35, 39);
+ let area = Rect::new(-3, 2, 19, 23);
+ let mut sel = Surface::new(PixelFormat::GRAY8);
+ sel.fill_rect(area, &[0.4]);
+ for depth in SampleType::ALL {
+ let s = source(extent, PixelFormat::new(ColorMode::Rgb, depth, true));
+ let p = FilterParams::UnsharpMask { amount: 150.0, radius: 64.0, threshold: 0.0 };
+ for edge in [None, Some(extent)] {
+ let expected = crate::sharpen::tests::apply_reference(&s, &p, area, extent, Some(&sel), edge, 256);
+ let actual = run(&s, area, 150.0, 64.0, Some(&sel), edge, &Interrupt::NONE).unwrap();
+ compare(&expected, &actual, extent);
+ }
+ }
+}
+
+#[test]
+fn fft_falls_back_for_thresholds_and_unstable_samples() {
+ let area = Rect::new(0, 0, 256, 256);
+ let mut s = source(area, PixelFormat::RGBA32F);
+ let p = FilterParams::UnsharpMask { amount: 150.0, radius: 64.0, threshold: 8.0 };
+ assert!(apply(&s, &p, area, None, Some(area), &Interrupt::NONE).is_none());
+ let p = FilterParams::UnsharpMask { amount: 150.0, radius: 64.0, threshold: 0.0 };
+ s.fill_rect(Rect::new(0, 0, 1, 1), &[f32::NAN, 0.5, 0.5, 1.0]);
+ assert!(apply(&s, &p, area, None, Some(area), &Interrupt::NONE).is_none());
+ s.fill_rect(area, &[0.5, 0.5, 0.5, 1e-8]);
+ assert!(apply(&s, &p, area, None, Some(area), &Interrupt::NONE).is_none());
+ s.fill_rect(area, &[0.5, 0.5, 0.5, -0.1]);
+ assert!(apply(&s, &p, area, None, Some(area), &Interrupt::NONE).is_none());
+}
+
+#[test]
+fn fft_cancellation_discards_partial_work_and_bounds_scratch() {
+ let area = Rect::new(0, 0, 256, 256);
+ let s = source(area, PixelFormat::RGBA8);
+ let original = s.to_interleaved(area);
+ let p = FilterParams::UnsharpMask { amount: 150.0, radius: 300.0, threshold: 0.0 };
+ let flag = std::sync::atomic::AtomicBool::new(false);
+ let cancel = || flag.load(Ordering::Relaxed);
+ let progress = |_| flag.store(true, Ordering::Relaxed);
+ assert!(apply(&s, &p, area, None, Some(area), &Interrupt::new(&cancel, &progress)).unwrap().is_none());
+ assert_eq!(s.to_interleaved(area), original);
+ flag.store(false, Ordering::Relaxed);
+ let after_writes = |value| {
+ if value > 0.55 {
+ flag.store(true, Ordering::Relaxed);
+ }
+ };
+ assert!(apply(&s, &p, area, None, Some(area), &Interrupt::new(&cancel, &after_writes)).unwrap().is_none());
+ assert_eq!(s.to_interleaved(area), original);
+ assert_eq!(group_size(MAX_BYTES, 1, 1, 1), None);
+ assert_eq!(group_size(0, usize::MAX, 1, 1), None);
+ assert!(Plan::new(usize::MAX, &[1.0], &mut FftPlanner::new()).is_none());
+ assert!(buffer::<f32>(usize::MAX, 0.0).is_none());
+}
+
+#[test]
+fn positive_threshold_dispatch_retains_exact_pixel_decisions() {
+ let area = Rect::new(-3, 2, 253, 258);
+ for depth in SampleType::ALL {
+ let s = source(area, PixelFormat::new(ColorMode::Rgb, depth, true));
+ let p = FilterParams::UnsharpMask { amount: 500.0, radius: 64.0, threshold: 8.0 };
+ let expected = crate::sharpen::tests::apply_reference(&s, &p, area, area, None, Some(area), 256);
+ let actual = crate::apply_in(&s, &p, area, area, None, area);
+ assert_eq!(expected.to_interleaved(area), actual.to_interleaved(area));
+ }
+}
+
+#[test]
+fn fft_handles_maximum_radius_and_hdr_alpha_channel_pairs() {
+ let area = Rect::new(0, 0, 1, 1);
+ let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));
+ s.fill_rect(area, &[0.5]);
+ let ctx = Ctx { bounds: area, mode: ColorMode::Grayscale, alpha: false };
+ let src = Image::read_clamped(&s, area.inflate(3001), area);
+ let pixels = reference::unsharp(&src, area, &ctx, 500.0, 1000.0, 0.0);
+ let mut expected = s.clone();
+ expected.write_region(area, &pixels);
+ compare(&expected, &run(&s, area, 500.0, 1000.0, None, Some(area), &Interrupt::NONE).unwrap(), area);
+
+ let area = Rect::new(-2, 3, 11, 14);
+ let mut s = Surface::new(PixelFormat::RGBA32F);
+ s.fill_rect(area, &[1e6, -1e5, 1e-4, 0.02]);
+ let ctx = Ctx { bounds: area, mode: ColorMode::Rgb, alpha: true };
+ let src = Image::read_clamped(&s, area.inflate(193), area);
+ let pixels = reference::unsharp(&src, area, &ctx, 500.0, 64.0, 0.0);
+ let mut expected = s.clone();
+ expected.write_region(area, &pixels);
+ compare(&expected, &run(&s, area, 500.0, 64.0, None, Some(area), &Interrupt::NONE).unwrap(), area);
+}
diff --git a/crates/algo/src/sharpen/fft_bench.rs b/crates/algo/src/sharpen/fft_bench.rs
new file mode 100644
index 000000000..3081ff7cd
--- /dev/null
+++ b/crates/algo/src/sharpen/fft_bench.rs
@@ -0,0 +1,112 @@
+//! Opt-in benchmark of the adaptive production path against the frozen original.
+use super::tests::{apply_reference, source};
+use crate::FilterParams;
+use photocraft_color::{ColorMode, PixelFormat, SampleType};
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+use std::time::Instant;
+#[test]
+#[ignore = "adaptive large-radius full-operation quality and performance; run alone"]
+fn unsharp_fft_performance() {
+ let number = |name: &str, default| std::env::var(name).ok().and_then(|v| v.parse::<i32>().ok()).unwrap_or(default);
+ let (w, h) = (number("PHOTOCRAFT_UNSHARP_WIDTH", 1920), number("PHOTOCRAFT_UNSHARP_HEIGHT", 1080));
+ let reps = number("PHOTOCRAFT_UNSHARP_REPS", 3);
+ assert!((1..=8192).contains(&w) && (1..=8192).contains(&h) && (1..=5).contains(&reps));
+ let depth = match number("PHOTOCRAFT_UNSHARP_DEPTH", 8) {
+ 8 => SampleType::U8,
+ 16 => SampleType::U16,
+ 32 => SampleType::F32,
+ _ => panic!("depth"),
+ };
+ let area = Rect::new(0, 0, w, h);
+ let surface = source(area, PixelFormat::new(ColorMode::Rgb, depth, true));
+ let cases = std::env::var("PHOTOCRAFT_UNSHARP_CASES").unwrap_or_else(|_| "100:150:0,300:150:0,500:150:8".into());
+ for case in cases.split(',') {
+ let v: Vec<f32> = case.split(':').map(|v| v.parse().unwrap()).collect();
+ let (radius, amount, threshold) = (v[0], v[1], v[2]);
+ let params = FilterParams::UnsharpMask { amount, radius, threshold };
+ let baseline = || apply_reference(&surface, &params, area, area, None, Some(area), crate::auto_tile(&params, area));
+ let candidate = || crate::apply_in(&surface, &params, area, area, None, area);
+ for _ in 0..2 {
+ std::hint::black_box(baseline());
+ std::hint::black_box(candidate());
+ }
+ let mut before = Vec::new();
+ let mut after = Vec::new();
+ let mut max_error = 0.0f32;
+ let mut changed = 0usize;
+ let mut sum_error = 0.0f64;
+ for rep in 0..reps {
+ let timed = |f: &dyn Fn() -> Surface| {
+ let t = Instant::now();
+ let output = f();
+ (output, t.elapsed().as_secs_f64() * 1000.0)
+ };
+ let ((old, a), (new, b)) = if rep % 2 == 0 {
+ (timed(&baseline), timed(&candidate))
+ } else {
+ let b = timed(&candidate);
+ (timed(&baseline), b)
+ };
+ before.push(a);
+ after.push(b);
+ for (a, b) in old.read_region(area).iter().zip(new.read_region(area)) {
+ let e = (a - b).abs();
+ let limit = match depth {
+ SampleType::U8 => 1.0 / 255.0 + 1e-7,
+ SampleType::U16 => 3.0 / 65535.0 + 1e-7,
+ SampleType::F32 => 3e-5 * (1.0 + a.abs()),
+ };
+ assert!(e <= limit, "quality regression: {a} != {b} at radius {radius}, threshold {threshold}");
+ max_error = max_error.max(e);
+ if rep == 0 {
+ sum_error += f64::from(e);
+ changed += usize::from(a.to_bits() != b.to_bits());
+ }
+ }
+ }
+ let median = |v: &[f64]| {
+ let mut v = v.to_vec();
+ v.sort_by(f64::total_cmp);
+ v[v.len() / 2]
+ };
+ println!(
+ "{}",
+ serde_json::json!({"experiment":"adaptive FFT same Gaussian, changed summation","width":w,"height":h,"depth":number("PHOTOCRAFT_UNSHARP_DEPTH",8),"radius":radius,"amount":amount,"threshold":threshold,"before_ms":before,"after_ms":after,"before_median_ms":median(&before),"after_median_ms":median(&after),"speedup":median(&before)/median(&after),"max_error":max_error,"mean_error":sum_error/(w as f64*h as f64*4.0),"changed_samples":changed})
+ );
+ }
+}
+
+#[test]
+#[ignore = "4K wide-radius cancellation latency; run alone in release"]
+fn unsharp_fft_cancel_latency() {
+ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+ let area = Rect::new(0, 0, 3840, 2160);
+ let surface = source(area, PixelFormat::RGBA8);
+ let input = surface.to_interleaved(area);
+ let p = FilterParams::UnsharpMask { amount: 150.0, radius: 1000.0, threshold: 0.0 };
+ let mut latencies = Vec::new();
+ for _ in 0..5 {
+ let flag = AtomicBool::new(false);
+ let cancel_at = AtomicU64::new(0);
+ let started = Instant::now();
+ std::thread::scope(|scope| {
+ let timer = scope.spawn(|| {
+ std::thread::sleep(std::time::Duration::from_millis(10));
+ cancel_at.store(started.elapsed().as_micros() as u64, Ordering::Relaxed);
+ flag.store(true, Ordering::Release);
+ });
+ let cancel = || flag.load(Ordering::Acquire);
+ let result = crate::apply_in_with(&surface, &p, area, area, None, area, &photocraft_raster::Interrupt::cancel_only(&cancel));
+ let elapsed = started.elapsed().as_micros() as u64;
+ timer.join().unwrap();
+ assert!(result.is_none());
+ latencies.push(elapsed.saturating_sub(cancel_at.load(Ordering::Relaxed)) as f64 / 1000.0);
+ });
+ assert_eq!(surface.to_interleaved(area), input);
+ }
+ println!(
+ "{}",
+ serde_json::json!({"width":3840,"height":2160,"radius":1000,"cancel_after_ms":10,"cancel_return_latencies_ms":latencies,"scope":"native full-resolution algo dispatch, excludes GUI scheduling/proxy creation"})
+ );
+}
diff --git a/crates/algo/src/sharpen/reference.rs b/crates/algo/src/sharpen/reference.rs
new file mode 100644
index 000000000..a99665c18
--- /dev/null
+++ b/crates/algo/src/sharpen/reference.rs
@@ -0,0 +1,113 @@
+//! Frozen exact Unsharp Mask from a28d7866, independent of production helpers.
+use crate::Ctx;
+use crate::image::{Image, premultiply, unpremultiply};
+use photocraft_geom::Rect;
+pub(crate) fn gaussian_kernel(sigma: f32) -> Vec<f32> {
+ if sigma < 0.05 {
+ return vec![1.0];
+ }
+ let r = (sigma * 3.0).ceil() as i32;
+ let k: Vec<f32> = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect();
+ let s: f32 = k.iter().sum();
+ k.into_iter().map(|v| v / s).collect()
+}
+
+/// Separable convolution of `src` (premultiplied internally) for `out`.
+/// `src` must cover `out` grown by the kernel radii.
+pub(crate) fn conv_sep(src: &Image, out: Rect, kx: &[f32], ky: &[f32], alpha: bool) -> Vec<f32> {
+ let n = src.ch;
+ let (rx, ry) = ((kx.len() / 2) as i32, (ky.len() / 2) as i32);
+ let (ow, oh) = (out.width() as usize, out.height() as usize);
+ let th = oh + 2 * ry as usize;
+ // Premultiplied copy of the needed source window.
+ let win = Rect::new(out.x0 - rx, out.y0 - ry, out.x1 + rx, out.y1 + ry);
+ let ww = win.width() as usize;
+ let mut p = vec![0.0f32; ww * win.height() as usize * n];
+ for y in win.y0..win.y1 {
+ for x in win.x0..win.x1 {
+ let o = ((y - win.y0) as usize * ww + (x - win.x0) as usize) * n;
+ for c in 0..n {
+ p[o + c] = src.get(x, y, c);
+ }
+ }
+ }
+ premultiply(&mut p, n, alpha);
+ // Horizontal pass: (ow × th).
+ let mut tmp = vec![0.0f32; ow * th * n];
+ for ty in 0..th {
+ let row = &p[ty * ww * n..(ty + 1) * ww * n];
+ let dst = &mut tmp[ty * ow * n..(ty + 1) * ow * n];
+ match n {
+ 1 => conv_row::<1>(row, dst, kx),
+ 2 => conv_row::<2>(row, dst, kx),
+ 3 => conv_row::<3>(row, dst, kx),
+ 4 => conv_row::<4>(row, dst, kx),
+ 5 => conv_row::<5>(row, dst, kx),
+ _ => {
+ for ox in 0..ow {
+ let d = &mut dst[ox * n..(ox + 1) * n];
+ for (i, kv) in kx.iter().enumerate() {
+ let s = &row[(ox + i) * n..(ox + i + 1) * n];
+ for c in 0..n {
+ d[c] += s[c] * kv;
+ }
+ }
+ }
+ }
+ }
+ }
+ // Vertical pass.
+ let mut res = vec![0.0f32; ow * oh * n];
+ for oy in 0..oh {
+ let d = &mut res[oy * ow * n..(oy + 1) * ow * n];
+ for (i, kv) in ky.iter().enumerate() {
+ let s = &tmp[(oy + i) * ow * n..(oy + i + 1) * ow * n];
+ for (dv, sv) in d.iter_mut().zip(s) {
+ *dv += sv * kv;
+ }
+ }
+ }
+ unpremultiply(&mut res, n, alpha);
+ res
+}
+
+// Fixed channel counts let LLVM keep one pixel's accumulators in registers and vectorize
+// channels. The tap order is unchanged; unusual multichannel images keep the generic path.
+fn conv_row<const N: usize>(src: &[f32], dst: &mut [f32], kernel: &[f32]) {
+ let pixels = src.as_chunks::<N>().0;
+ for (x, out) in dst.as_chunks_mut::<N>().0.iter_mut().enumerate() {
+ let mut acc = [0.0f32; N];
+ for (pixel, weight) in pixels.get(x..).unwrap_or(&[]).iter().zip(kernel) {
+ for c in 0..N {
+ acc[c] += pixel[c] * weight;
+ }
+ }
+ *out = acc;
+ }
+}
+
+fn with_blur(src: &Image, out: Rect, ctx: &Ctx, radius: f32, mut f: impl FnMut(f32, f32) -> f32) -> Vec<f32> {
+ let k = gaussian_kernel(radius);
+ let blurred = conv_sep(src, out, &k, &k, ctx.alpha);
+ let mut res = src.crop(out);
+ let n = src.ch;
+ let cc = if ctx.alpha { n - 1 } else { n };
+ for (px, bl) in res.chunks_exact_mut(n).zip(blurred.chunks_exact(n)) {
+ if ctx.alpha && px[n - 1] <= 0.0 {
+ continue;
+ }
+ for c in 0..cc {
+ px[c] = f(px[c], bl[c]);
+ }
+ }
+ res
+}
+
+pub(crate) fn unsharp(src: &Image, out: Rect, ctx: &Ctx, amount: f32, radius: f32, threshold: f32) -> Vec<f32> {
+ let k = amount / 100.0;
+ let t = threshold / 255.0;
+ with_blur(src, out, ctx, radius, |o, b| {
+ let d = o - b;
+ if d.abs() + 1e-6 >= t { o + k * d } else { o }
+ })
+}
diff --git a/crates/algo/src/sharpen/tests.rs b/crates/algo/src/sharpen/tests.rs
new file mode 100644
index 000000000..4699bb3a1
--- /dev/null
+++ b/crates/algo/src/sharpen/tests.rs
@@ -0,0 +1,434 @@
+use super::*;
+use photocraft_color::{ColorMode, PixelFormat, SampleType};
+use photocraft_raster::{Interrupt, Surface};
+use std::time::Instant;
+
+#[path = "reference.rs"]
+pub(super) mod reference;
+
+pub(super) fn source(rect: Rect, fmt: PixelFormat) -> Surface {
+ let mut s = Surface::new(fmt);
+ for y in rect.y0..rect.y1 {
+ let data: Vec<f32> = (rect.x0..rect.x1)
+ .flat_map(|x| {
+ (0..fmt.channels()).map(move |c| {
+ if fmt.alpha && c + 1 == fmt.channels() {
+ if (x + y).rem_euclid(17) == 0 { 0.0 } else { ((x ^ y).rem_euclid(255) + 1) as f32 / 255.0 }
+ } else {
+ let value = ((x * (7 + c as i32) + y * 13).rem_euclid(257)) as f32 / 256.0;
+ if fmt.sample == SampleType::F32 { 3.0 * value - 0.5 } else { value }
+ }
+ })
+ })
+ .collect();
+ s.write_region(Rect::new(rect.x0, y, rect.x1, y + 1), &data);
+ }
+ s
+}
+
+// Preserve the surrounding tiled workload as well as the old convolution: halo reads,
+// automatic tiles, grouping, selection mixing, writes and pruning are timed in both paths.
+#[allow(clippy::too_many_arguments)]
+pub(super) fn apply_reference(
+ s: &Surface,
+ p: &crate::FilterParams,
+ area: Rect,
+ bounds: Rect,
+ sel: Option<&Surface>,
+ extent: Option<Rect>,
+ tile: i32,
+) -> Surface {
+ let crate::FilterParams::UnsharpMask { amount, radius, threshold } = *p else { panic!("unsharp params") };
+ let crate::Halo::Radius(halo) = p.halo_for(bounds) else { panic!("radius halo") };
+ let fmt = s.format();
+ let ctx = Ctx { bounds, mode: fmt.mode, alpha: fmt.alpha };
+ let tiles: Vec<_> = (area.y0..area.y1)
+ .step_by(tile as usize)
+ .flat_map(|y| (area.x0..area.x1).step_by(tile as usize).map(move |x| Rect::new(x, y, (x + tile).min(area.x1), (y + tile).min(area.y1))))
+ .collect();
+ let group = (crate::RESULT_BUDGET / ((tile as usize).pow(2) * fmt.channels() * 4)).max(workers()).max(1);
+ let finished = std::sync::atomic::AtomicUsize::new(0);
+ let ctl = Interrupt::NONE;
+ let run = |t: &Rect| {
+ let src = match extent {
+ Some(e) => Image::read_clamped(s, t.inflate(halo), e),
+ None => Image::read(s, t.inflate(halo)),
+ };
+ let mut data = reference::unsharp(&src, *t, &ctx, amount, radius, threshold);
+ if let Some(sel) = sel {
+ crate::mix_selection(&mut data, *t, sel, &src, fmt.alpha);
+ }
+ let done = finished.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
+ ctl.progress(0.98 * done as f32 / tiles.len().max(1) as f32);
+ (*t, data)
+ };
+ let mut out = s.clone();
+ for chunk in tiles.chunks(group) {
+ #[cfg(not(target_arch = "wasm32"))]
+ let results: Vec<_> = {
+ use rayon::prelude::*;
+ chunk.par_iter().map(run).collect()
+ };
+ #[cfg(target_arch = "wasm32")]
+ let results: Vec<_> = chunk.iter().map(run).collect();
+ for (t, data) in results {
+ out.write_region(t, &data);
+ }
+ }
+ out.prune();
+ out
+}
+
+fn workers() -> usize {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ rayon::current_num_threads()
+ }
+ #[cfg(target_arch = "wasm32")]
+ {
+ 1
+ }
+}
+
+#[test]
+fn frozen_reference_matches_current_kernel() {
+ let out = Rect::new(-3, 2, 16, 15);
+ let src = Image { rect: out.inflate(13), ch: 4, data: (0..(out.width() + 26) * (out.height() + 26) * 4).map(|i| (i % 127) as f32 / 126.0).collect() };
+ let ctx = Ctx { bounds: out, mode: ColorMode::Rgb, alpha: true };
+ for radius in [0.1, 0.6, 1.5, 4.0] {
+ assert_eq!(unsharp(&src, out, &ctx, 150.0, radius, 8.0), reference::unsharp(&src, out, &ctx, 150.0, radius, 8.0));
+ }
+}
+
+fn same_bits(a: &[f32], b: &[f32]) {
+ assert_eq!(a.len(), b.len());
+ for (i, (&a, &b)) in a.iter().zip(b).enumerate() {
+ assert!(a.to_bits() == b.to_bits() || a.is_nan() && b.is_nan(), "sample {i}: {a:?} ({:x}) != {b:?} ({:x})", a.to_bits(), b.to_bits());
+ }
+}
+
+#[test]
+fn exact_kernel_across_models_depths_edges_and_thresholds() {
+ let modes = [
+ ColorMode::Bitmap,
+ ColorMode::Grayscale,
+ ColorMode::Duotone,
+ ColorMode::Indexed,
+ ColorMode::Rgb,
+ ColorMode::Cmyk,
+ ColorMode::Lab,
+ ColorMode::Multichannel,
+ ];
+ for mode in modes {
+ for depth in SampleType::ALL {
+ for alpha in [false, true] {
+ let fmt = PixelFormat::new(mode, depth, alpha);
+ let area = Rect::new(-3, 2, 8, 7);
+ let mut surface = source(area, fmt);
+ if depth == SampleType::F32 {
+ // HDR, negative, signed zero, subnormal and nonfinite samples; colour is
+ // never clamped by this filter. Transparent hidden colour must survive.
+ let px: Vec<f32> = (0..fmt.channels()).map(|c| if alpha && c + 1 == fmt.channels() { 0.0 } else { -4.0 }).collect();
+ surface.fill_rect(Rect::new(0, 3, 1, 4), &px);
+ for (x, value) in [3.5, -0.0, f32::MIN_POSITIVE, f32::INFINITY, f32::NAN].into_iter().enumerate() {
+ let mut px = vec![value; fmt.channels()];
+ if alpha {
+ *px.last_mut().unwrap() = if x == 2 { 1e-8 } else { 1.0 };
+ }
+ surface.fill_rect(Rect::new(x as i32, 5, x as i32 + 1, 6), &px);
+ }
+ }
+ let ctx = Ctx { bounds: area, mode, alpha };
+ for radius in [0.0, 0.049, 0.1, 0.6, 1.5, 4.0, 17.25] {
+ let src = Image::read_clamped(&surface, area.inflate((radius * 3.0_f32).ceil() as i32 + 1), area);
+ for (amount, threshold) in [(0.0, 0.0), (50.0, 0.0), (500.0, 8.0), (300.0, 255.0)] {
+ same_bits(&unsharp(&src, area, &ctx, amount, radius, threshold), &reference::unsharp(&src, area, &ctx, amount, radius, threshold));
+ }
+ // An incomplete halo has zero extension, even with alpha.
+ let src = Image::read(&surface, area);
+ let out = Rect::new(-5, 1, 10, 8);
+ same_bits(&unsharp(&src, out, &ctx, 150.0, radius, 8.0), &reference::unsharp(&src, out, &ctx, 150.0, radius, 8.0));
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn exact_threshold_boundary_and_degenerate_images() {
+ for (w, h, n) in [(1, 1, 1), (1, 7, 2), (9, 1, 3), (7, 5, 4), (2, 3, 5), (5, 2, 7)] {
+ let out = Rect::new(-2, 3, w - 2, h + 3);
+ let ctx = Ctx { bounds: out, mode: ColorMode::Rgb, alpha: n % 2 == 0 };
+ let src = Image { rect: out, ch: n, data: (0..w * h * n as i32).map(|i| if i % 7 == 0 { -0.0 } else { (i % 17) as f32 / 16.0 }).collect() };
+ for radius in [0.0, 0.1, 0.75, 8.5, 64.0] {
+ let k = reference::gaussian_kernel(radius);
+ let blurred = reference::conv_sep(&src, out, &k, &k, ctx.alpha);
+ for (&o, &b) in src.data.iter().zip(&blurred).take(8) {
+ let boundary = ((o - b).abs() + 1e-6) * 255.0;
+ for threshold in [boundary, f32::from_bits(boundary.to_bits().saturating_sub(1)), f32::from_bits(boundary.to_bits() + 1)] {
+ same_bits(&unsharp(&src, out, &ctx, 500.0, radius, threshold), &reference::unsharp(&src, out, &ctx, 500.0, radius, threshold));
+ }
+ }
+ }
+ }
+ let empty = Image { rect: Rect::EMPTY, ch: 4, data: Vec::new() };
+ let ctx = Ctx { bounds: Rect::EMPTY, mode: ColorMode::Rgb, alpha: true };
+ assert!(unsharp(&empty, Rect::EMPTY, &ctx, 100.0, 1.0, 0.0).is_empty());
+}
+
+#[test]
+fn exact_tiled_selected_outputs_and_cancellation() {
+ let bounds = Rect::new(-13, -7, 281, 271);
+ let area = Rect::new(-3, 5, 273, 265);
+ let mut sel = Surface::new(PixelFormat::GRAY8);
+ sel.fill_rect(area, &[0.4]);
+ sel.fill_rect(Rect::new(250, 250, 270, 265), &[1.0]);
+ for depth in SampleType::ALL {
+ let surface = source(bounds, PixelFormat::new(ColorMode::Rgb, depth, true));
+ for radius in [0.6, 3.0, 10.0] {
+ let p = crate::FilterParams::UnsharpMask { amount: 150.0, radius, threshold: 8.0 };
+ for extent in [None, Some(bounds)] {
+ let expected = apply_reference(&surface, &p, area, bounds, Some(&sel), extent, 256);
+ for tile in [63, 256, 512] {
+ let actual = crate::apply_tiled(&surface, &p, area, bounds, Some(&sel), tile, extent);
+ assert_eq!(expected.to_interleaved(bounds), actual.to_interleaved(bounds));
+ }
+ }
+ let cancelled = std::sync::atomic::AtomicBool::new(false);
+ let cancel = || cancelled.load(std::sync::atomic::Ordering::Relaxed);
+ let progress = |_| cancelled.store(true, std::sync::atomic::Ordering::Relaxed);
+ let ctl = Interrupt::new(&cancel, &progress);
+ let input = surface.to_interleaved(bounds);
+ assert!(crate::apply_in_with(&surface, &p, area, bounds, Some(&sel), bounds, &ctl).is_none());
+ assert_eq!(surface.to_interleaved(bounds), input);
+ }
+ }
+}
+
+#[test]
+fn preserve_details_resampling_keeps_the_same_sharpening() {
+ use crate::resample::{Resample, resize_surface};
+ let src = Rect::new(-3, 2, 19, 17);
+ let (sx, sy) = (2.0, 1.5);
+ let dst = crate::resample::scaled_rect(src, sx, sy);
+ for depth in SampleType::ALL {
+ for mode in [ColorMode::Grayscale, ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab] {
+ let s = source(src, PixelFormat::new(mode, depth, true));
+ let resized = resize_surface(&s, sx, sy, Resample::Lanczos);
+ let p = crate::FilterParams::UnsharpMask { amount: 30.0, radius: 0.6 * sx.max(sy) as f32, threshold: 0.0 };
+ let area = crate::output_area(&p, resized.content_bounds(), dst, None);
+ let expected = apply_reference(&resized, &p, area, dst, None, None, crate::auto_tile(&p, dst));
+ let actual = resize_surface(&s, sx, sy, Resample::PreserveDetails);
+ assert_eq!(actual.to_interleaved(area), expected.to_interleaved(area));
+ }
+ }
+}
+
+#[test]
+fn flat_fields_and_sharp_edges_keep_exact_halos() {
+ let out = Rect::new(0, 0, 17, 9);
+ for alpha in [false, true] {
+ let ctx = Ctx { bounds: out, mode: ColorMode::Rgb, alpha };
+ for radius in [0.1, 0.6, 3.25, 64.0] {
+ let rect = out.inflate((radius * 3.0_f32).ceil() as i32 + 1);
+ for edge in [false, true] {
+ let n = 3 + usize::from(alpha);
+ let data = (rect.y0..rect.y1)
+ .flat_map(|_| {
+ (rect.x0..rect.x1).flat_map(|x| {
+ (0..n).map(move |c| {
+ if alpha && c + 1 == n {
+ 0.7
+ } else if edge && x >= 8 {
+ 0.75
+ } else {
+ 0.25
+ }
+ })
+ })
+ })
+ .collect();
+ let src = Image { rect, ch: n, data };
+ same_bits(&unsharp(&src, out, &ctx, 300.0, radius, 0.0), &reference::unsharp(&src, out, &ctx, 300.0, radius, 0.0));
+ }
+ }
+ }
+}
+
+#[test]
+fn malformed_inputs_and_allocations_stop_gracefully() {
+ let rect = Rect::new(0, 0, 2, 2);
+ let src = Image { rect, ch: 1, data: vec![0.5; 4] };
+ let ctx = Ctx { bounds: rect, mode: ColorMode::Grayscale, alpha: false };
+ for (amount, radius, threshold) in [(f32::NAN, 1.0, 0.0), (100.0, f32::INFINITY, 0.0), (100.0, -1.0, 0.0), (100.0, f32::MAX, 0.0), (100.0, 1.0, f32::NAN)] {
+ assert!(exact::run(&src, rect, &ctx, amount, radius, threshold, &Interrupt::NONE).is_none());
+ let s = source(rect, PixelFormat::GRAY8);
+ let p = crate::FilterParams::UnsharpMask { amount, radius, threshold };
+ assert!(crate::apply_in_with(&s, &p, rect, rect, None, rect, &Interrupt::NONE).is_none());
+ assert_eq!(crate::apply_in(&s, &p, rect, rect, None, rect), s);
+ }
+ for bad in [Image { ch: 0, ..src.clone() }, Image { data: vec![0.0], ..src.clone() }, Image { rect: Rect::new(5, 0, 0, 2), ..src.clone() }] {
+ assert!(exact::run(&bad, rect, &ctx, 100.0, 1.0, 0.0, &Interrupt::NONE).is_none());
+ }
+ for rect in [Rect::new(i32::MIN, 0, i32::MAX, 2), Rect::new(0, 0, 300_000, 300_000), Rect::new(2, 0, 0, 2)] {
+ assert!(exact::run(&src, rect, &ctx, 100.0, 1.0, 0.0, &Interrupt::NONE).is_none());
+ }
+ let s = source(Rect::new(0, 0, 2, 2), PixelFormat::GRAY8);
+ let p = crate::FilterParams::UnsharpMask { amount: 100.0, radius: 1.0, threshold: 0.0 };
+ for tile in [i32::MIN, 0, i32::MAX] {
+ let r = s.content_bounds();
+ assert_eq!(crate::apply_tiled(&s, &p, r, r, None, tile, Some(r)), crate::apply_in(&s, &p, r, r, None, r));
+ }
+ // Allocation/geometry guard prevents a huge halo read before allocating it.
+ let p = crate::FilterParams::UnsharpMask { amount: 100.0, radius: 15_446.0, threshold: 0.0 };
+ assert!(crate::apply_in_with(&s, &p, s.content_bounds(), s.content_bounds(), None, s.content_bounds(), &Interrupt::NONE).is_none());
+}
+
+#[test]
+fn maximum_supported_radius_matches_the_frozen_kernel() {
+ let out = Rect::new(0, 0, 1, 1);
+ let src = Image { rect: out, ch: 1, data: vec![0.75] };
+ let ctx = Ctx { bounds: out, mode: ColorMode::Grayscale, alpha: false };
+ same_bits(&unsharp(&src, out, &ctx, 500.0, 1000.0, 8.0), &reference::unsharp(&src, out, &ctx, 500.0, 1000.0, 8.0));
+}
+
+#[test]
+fn cancellation_stops_inside_a_tile_before_publishing() {
+ let rect = Rect::new(0, 0, 16, 16);
+ let s = source(rect, PixelFormat::RGBA8);
+ let src = Image::read(&s, rect);
+ let ctx = Ctx { bounds: rect, mode: ColorMode::Rgb, alpha: true };
+ let checks = std::sync::atomic::AtomicUsize::new(0);
+ let cancel = || checks.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 10;
+ assert!(exact::run(&src, rect, &ctx, 150.0, 30.0, 8.0, &Interrupt::cancel_only(&cancel)).is_none());
+ assert_eq!(src, Image::read(&s, rect));
+}
+
+#[test]
+#[ignore = "release full-operation baseline/candidate comparison; run alone"]
+fn unsharp_performance() {
+ let number = |name: &str, default: i32| std::env::var(name).ok().and_then(|s| s.parse::<i32>().ok()).unwrap_or(default);
+ let (w, h, reps) = (number("PHOTOCRAFT_UNSHARP_WIDTH", 1500), number("PHOTOCRAFT_UNSHARP_HEIGHT", 1000), number("PHOTOCRAFT_UNSHARP_REPS", 5));
+ assert!((1..=8192).contains(&w) && (1..=8192).contains(&h) && (1..=15).contains(&reps));
+ let depth = match number("PHOTOCRAFT_UNSHARP_DEPTH", 8) {
+ 8 => SampleType::U8,
+ 16 => SampleType::U16,
+ 32 => SampleType::F32,
+ _ => panic!("depth"),
+ };
+ let area = Rect::new(0, 0, w, h);
+ let channels = number("PHOTOCRAFT_UNSHARP_CHANNELS", 4);
+ let (mode, alpha) = match channels {
+ 1 => (ColorMode::Grayscale, false),
+ 2 => (ColorMode::Grayscale, true),
+ 3 => (ColorMode::Rgb, false),
+ 4 => (ColorMode::Rgb, true),
+ 5 => (ColorMode::Cmyk, true),
+ _ => panic!("channels 1..5"),
+ };
+ let surface = source(area, PixelFormat::new(mode, depth, alpha));
+ let measure = std::env::var("PHOTOCRAFT_UNSHARP_MODE").unwrap_or_else(|_| "paired".into());
+ assert!(matches!(measure.as_str(), "paired" | "reference" | "candidate"));
+ let cases = std::env::var("PHOTOCRAFT_UNSHARP_CASES").unwrap_or_else(|_| "0.6:150:0,3:150:8,10:300:16,30:150:0".into());
+ for case in cases.split(',') {
+ let values: Vec<f32> = case.split(':').map(|v| v.parse().unwrap()).collect();
+ let (radius, amount, threshold) = (values[0], values[1], values[2]);
+ let p = crate::FilterParams::UnsharpMask { amount, radius, threshold };
+ let tile = crate::auto_tile(&p, area);
+ let before = || apply_reference(&surface, &p, area, area, None, Some(area), tile);
+ // Isolate the streamed exact path from the new adaptive FFT dispatcher.
+ let after = || crate::apply_tiled_with_impl(&surface, &p, area, area, None, tile, Some(area), &Interrupt::NONE, false).unwrap();
+ if measure != "paired" {
+ let f = if measure == "reference" { &before as &dyn Fn() -> Surface } else { &after as &dyn Fn() -> Surface };
+ let mut times = Vec::new();
+ for rep in 0..reps + 2 {
+ let start = Instant::now();
+ let output = f();
+ let ms = start.elapsed().as_secs_f64() * 1000.0;
+ std::hint::black_box(output);
+ if rep >= 2 {
+ times.push(ms);
+ }
+ }
+ println!(
+ "{}",
+ serde_json::json!({"mode":measure,"width":w,"height":h,"channels":channels,"depth":number("PHOTOCRAFT_UNSHARP_DEPTH",8),"radius":radius,"amount":amount,"threshold":threshold,"workers":workers(),"runs_ms":times})
+ );
+ continue;
+ }
+ for _ in 0..2 {
+ std::hint::black_box(before());
+ std::hint::black_box(after());
+ }
+ let (mut a, mut b) = (Vec::new(), Vec::new());
+ for rep in 0..reps {
+ let timed = |f: &dyn Fn() -> Surface| {
+ let start = Instant::now();
+ let s = f();
+ (s, start.elapsed().as_secs_f64() * 1000.0)
+ };
+ let ((old, old_ms), (new, new_ms)) = if rep % 2 == 0 {
+ (timed(&before), timed(&after))
+ } else {
+ let b = timed(&after);
+ (timed(&before), b)
+ };
+ assert_eq!(old.to_interleaved(area), new.to_interleaved(area));
+ a.push(old_ms);
+ b.push(new_ms);
+ }
+ let median = |v: &[f64]| {
+ let mut v = v.to_vec();
+ v.sort_by(f64::total_cmp);
+ v[v.len() / 2]
+ };
+ println!(
+ "{}",
+ serde_json::json!({"width":w,"height":h,"channels":channels,"depth":number("PHOTOCRAFT_UNSHARP_DEPTH",8),"radius":radius,"amount":amount,"threshold":threshold,"workers":workers(),"before_ms":a,"after_ms":b,"before_median_ms":median(&a),"after_median_ms":median(&b),"speedup":median(&a)/median(&b),"max_error":0})
+ );
+ }
+}
+
+#[test]
+#[ignore = "unchanged-filter stage profile; run alone in release"]
+fn unsharp_baseline_profile() {
+ let out = Rect::new(0, 0, 256, 256);
+ for radius in [0.6, 3.0, 10.0, 30.0] {
+ let reach = (radius * 3.0_f32).ceil() as i32 + 1;
+ let s = source(out.inflate(reach), PixelFormat::new(ColorMode::Rgb, SampleType::U8, true));
+ let src = Image::read(&s, out.inflate(reach));
+ let ctx = Ctx { bounds: out, mode: ColorMode::Rgb, alpha: true };
+ let k = reference::gaussian_kernel(radius);
+ let mut times = [0.0; 4];
+ for _ in 0..20 {
+ let start = Instant::now();
+ std::hint::black_box(reference::gaussian_kernel(radius));
+ times[0] += start.elapsed().as_secs_f64();
+ let start = Instant::now();
+ let bl = reference::conv_sep(&src, out, &k, &k, true);
+ times[1] += start.elapsed().as_secs_f64();
+ let start = Instant::now();
+ let mut res = src.crop(out);
+ for (px, b) in res.as_chunks_mut::<4>().0.iter_mut().zip(bl.as_chunks::<4>().0) {
+ if px[3] <= 0.0 {
+ continue;
+ }
+ for c in 0..3 {
+ let d = px[c] - b[c];
+ if d.abs() + 1e-6 >= 8.0 / 255.0 {
+ px[c] += 1.5 * d;
+ }
+ }
+ }
+ std::hint::black_box(res);
+ times[2] += start.elapsed().as_secs_f64();
+ let start = Instant::now();
+ std::hint::black_box(reference::unsharp(&src, out, &ctx, 150.0, radius, 8.0));
+ times[3] += start.elapsed().as_secs_f64();
+ }
+ println!(
+ "{}",
+ serde_json::json!({"baseline_tile_radius":radius,"kernel_ms":times[0]*50.0,"convolution_ms":times[1]*50.0,"crop_blend_ms":times[2]*50.0,"total_kernel_ms":times[3]*50.0})
+ );
+ }
+}
diff --git a/crates/ui-egui/examples/unsharp_preview_bench.rs b/crates/ui-egui/examples/unsharp_preview_bench.rs
new file mode 100644
index 000000000..0f4518187
--- /dev/null
+++ b/crates/ui-egui/examples/unsharp_preview_bench.rs
@@ -0,0 +1,67 @@
+//! Synthetic existing preview workload, including proxy creation, command/history and CPU
+//! flattening. Excludes scheduling, egui frames, display conversion, GPU upload/presentation.
+use photocraft_color::{Color, ColorMode, SampleType};
+use photocraft_doc::{Document, LayerContent};
+use photocraft_geom::{Rect, Size};
+use photocraft_ui_egui::{filter_dialog, proxy};
+use serde_json::json;
+use std::time::Instant;
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let n = |key: &str, default| std::env::var(key).ok().and_then(|s| s.parse::<u32>().ok()).unwrap_or(default);
+ let (w, h, reps) = (n("PHOTOCRAFT_UNSHARP_WIDTH", 6000), n("PHOTOCRAFT_UNSHARP_HEIGHT", 4000), n("PHOTOCRAFT_UNSHARP_REPS", 5));
+ if w == 0 || h == 0 || w > 8192 || h > 8192 || !(1..=15).contains(&reps) {
+ return Err("invalid benchmark dimensions/reps".into());
+ }
+ let depth = match n("PHOTOCRAFT_UNSHARP_DEPTH", 8) {
+ 8 => SampleType::U8,
+ 16 => SampleType::U16,
+ 32 => SampleType::F32,
+ _ => return Err("invalid depth".into()),
+ };
+ let mut doc = Document::with_background("Synthetic Unsharp Mask", Size::new(w, h), ColorMode::Rgb, depth, Color::WHITE);
+ let layer = doc.layers.first_mut().ok_or("missing layer")?;
+ let id = layer.id;
+ let LayerContent::Raster(s) = &mut layer.content else { return Err("raster required".into()) };
+ for y in 0..h as i32 {
+ let data: Vec<_> = (0..w as i32)
+ .flat_map(|x| [((x * 7 + y * 13) % 257) as f32 / 256.0, ((x ^ y) % 251) as f32 / 250.0, ((x + y * 11) % 127) as f32 / 126.0, 1.0])
+ .collect();
+ s.write_region(Rect::new(0, y, w as i32, y + 1), &data);
+ }
+ let cmd = "filter.sharpen.unsharpMask";
+ let cases = std::env::var("PHOTOCRAFT_UNSHARP_CASES").unwrap_or_else(|_| "0.6:150:0,3:150:8,10:300:16,30:150:0".into());
+ for case in cases.split(',') {
+ let v: Vec<f64> = case.split(':').map(str::parse).collect::<Result<_, _>>()?;
+ let (&radius, &amount, &threshold) = (v.first().ok_or("radius")?, v.get(1).ok_or("amount")?, v.get(2).ok_or("threshold")?);
+ for reduced in [true, false] {
+ let k = filter_dialog::preview_factor(cmd, &json!({"radius":radius}), proxy::preview_factor(&doc, reduced));
+ let mut times = Vec::new();
+ let mut checksum = 0u64;
+ for rep in 0..reps + 2 {
+ let start = Instant::now();
+ let result = filter_dialog::preview_document(&doc, Some(id), cmd, &json!({"radius":radius,"amount":amount,"threshold":threshold}), k)
+ .ok_or("preview failed")?;
+ let pixels = photocraft_compose::flatten(&result);
+ let ms = start.elapsed().as_secs_f64() * 1000.0;
+ // Outside timing: stable hash over the full flattened result, no image file needed.
+ let hash = pixels.px.iter().flatten().fold(0u64, |h, v| h.wrapping_mul(1099511628211).wrapping_add(u64::from(v.to_bits())));
+ if rep == 0 {
+ checksum = hash;
+ } else if checksum != hash {
+ return Err("unstable preview output".into());
+ }
+ if rep >= 2 {
+ times.push(ms);
+ }
+ }
+ let mut sorted = times.clone();
+ sorted.sort_by(f64::total_cmp);
+ println!(
+ "{}",
+ json!({"width":w,"height":h,"depth":n("PHOTOCRAFT_UNSHARP_DEPTH",8),"radius":radius,"amount":amount,"threshold":threshold,"proxy_factor":k,"runs_ms":times,"median_ms":sorted.get(sorted.len()/2),"checksum":checksum,"workers":rayon::current_num_threads(),"scope":"existing preview_document + CPU flatten; excludes GUI and GPU"})
+ );
+ }
+ }
+ Ok(())
+}
diff --git a/docs/roadmap.md b/docs/roadmap.md
index e14a05113..bca91616c 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -1,6 +1,6 @@
# Roadmap
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** minor (Photomerge implementation status corrected; real-world quality validation remains open) · **Target:** Adobe Photoshop 2026
+> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-11 · **Change:** minor (adaptive Unsharp Mask performance evidence linked; Photomerge status correction retained; alpha gate, focus and estimates unchanged) · **Target:** Adobe Photoshop 2026
- UI.5: Panels can detach, join other tab groups, split, resize and redock through shared docking transactions. Custom layouts persist with workspaces, respect workspace locking, and retain collapse flags for intact native groups.
@@ -72,6 +72,9 @@ Ranked; each item links to its gap entry. Pick from the top unless an issue is a
Photoshop re-open check (FILE-216-4); Photoshop-oracle floor 133/256 → 200+. 150–250 h.
2. **Performance budgets** ([G2](gaps.md#g2-interactive-performance)): the 22 over-budget
scenarios, the P12 GPU crash at 150 layers, brush and cursor lag (#2619, #2566). 200–350 h.
+ Local adaptive [Unsharp Mask optimisation](unsharp-mask-performance.md) improves native
+ threshold-zero 24 MP RGBA CPU application by 37–102x at radii 300–1000, with measured
+ rounding differences and an exact fallback; no published budget is closed by that measurement.
3. **User bug backlog** ([G3](gaps.md#g3-user-reported-bug-backlog)): 579 open issues, most from
0.5/0.6 users; triage weekly, fix regressions first. 250–400 h.
4. **Brush and transform feel** ([G4](gaps.md#g4-brush-feel), [G5](gaps.md#g5-transform-handles-and-modifiers)):
@@ -113,6 +116,7 @@ Each milestone has a **definition of done (DoD)** and must leave `main` green on
| Date | Change | Summary |
|---|---|---|
+| 2026-10-11 | minor | Linked adaptive Unsharp Mask performance and quality evidence; milestones, alpha gate and estimates unchanged |
| 2026-10-10 | minor | Photomerge is implemented; real-world quality validation remains open |
| 2026-10-10 | minor | Alpha gate table (core-workflow gate from the progress-docs standard): passes, stage stays alpha |
| 2026-10-10 | major | Progress-docs standard: honest assessment and dated measurements moved to `target-app-parity.md`, Affinity notes to `file-format-parity.md`; new Current focus and estimates; `parity.md` renamed `parity-checklist.md` |
diff --git a/docs/unsharp-mask-performance.md b/docs/unsharp-mask-performance.md
new file mode 100644
index 000000000..d530cf2f9
--- /dev/null
+++ b/docs/unsharp-mask-performance.md
@@ -0,0 +1,23 @@
+# Unsharp Mask performance
+
+Large-radius native Unsharp Mask uses separable FFT convolution with the original
+discrete Gaussian coefficients and the existing `rustfft` dependency. A streamed
+separable path preserves the original tap order for exact processing.
+
+FFT is eligible for radii 64–1000 with at least 65,536 output pixels, a nonzero
+amount and a zero or negative threshold. Positive thresholds, unstable samples,
+unsupported geometry and insufficient scratch use the exact path. WebAssembly
+retains exact processing. Alpha, selections, edges and cancellation are preserved.
+Smart Sharpen, High Pass and shared blur math are unchanged.
+
+FFT changes summation order and permits small rounding differences. The measured
+maximum was one 8-bit storage level, approximately one 16-bit level, and 8.762e-6
+for the HDR fixture. Exact-path comparisons were byte-identical. Transform axes
+are capped at 32,768; FFT scratch grouping has a 1 GiB budget, excluding document
+tiles. This is not a whole-process memory limit.
+
+Before/after numbers, benchmark methodology, numerical tolerances and preview
+measurement limits are recorded in [PR #2987](https://github.com/storytold/photocraft/pull/2987).
+The comparisons use synthetic images and measure CPU computation, not slider
+event-to-screen latency. No published performance budget or rendering-parity
+floor is raised by these measurements.