Skip to content

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

Speed up exact Shape Blur convolution (#1566)

optimalbyteef5a86628edf5
diff --git a/crates/algo/examples/bench_shape_blur.rs b/crates/algo/examples/bench_shape_blur.rs
new file mode 100644
index 000000000..0f53b0bf0
--- /dev/null
+++ b/crates/algo/examples/bench_shape_blur.rs
@@ -0,0 +1,71 @@
+//! Reproducible end-to-end Shape Blur timings; no native CPU flags required.
+//! Arguments: width height repetitions radius (or all) depth (8/16/32) shape (or all).
+use std::{hint::black_box, time::Instant};
+
+use photocraft_algo::{BlurShape, FilterParams, apply_in};
+use photocraft_color::{ColorMode, PixelFormat, SampleType};
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ let arg = |i: usize, default: &str| args.get(i).map(String::as_str).unwrap_or(default).to_owned();
+ let w: i32 = arg(0, "6000").parse()?;
+ let h: i32 = arg(1, "4000").parse()?;
+ let repeats: usize = arg(2, "3").parse()?;
+ if !(1..=8000).contains(&w) || !(1..=8000).contains(&h) || !(1..=20).contains(&repeats) {
+ return Err("size or repetition count outside benchmark limits".into());
+ }
+ let radius = arg(3, "all");
+ let radii = if radius == "all" { vec![5.0, 25.0, 100.0] } else { vec![radius.parse::<f32>()?] };
+ if radii.iter().any(|r| !r.is_finite() || !(0.0..=1000.0).contains(r)) {
+ return Err("radius outside 0..=1000".into());
+ }
+ let depth = arg(4, "8");
+ let sample = match depth.as_str() {
+ "8" => SampleType::U8,
+ "16" => SampleType::U16,
+ "32" => SampleType::F32,
+ _ => return Err("depth must be 8, 16 or 32".into()),
+ };
+ let only = arg(5, "all");
+ let bounds = Rect::new(0, 0, w, h);
+ let mut src = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true));
+ // Write in rows: input setup does not need a full-image float buffer.
+ for y in 0..h {
+ let data: Vec<f32> = (0..w)
+ .flat_map(|x| [(x % 256) as f32 / 255.0, ((x * 3 + y) % 256) as f32 / 255.0, ((x ^ y) % 256) as f32 / 255.0, ((x + y) % 5) as f32 / 4.0])
+ .collect();
+ src.write_region(Rect::new(0, y, w, y + 1), &data);
+ }
+ for shape in [
+ BlurShape::Circle,
+ BlurShape::Ring,
+ BlurShape::Square,
+ BlurShape::Diamond,
+ BlurShape::Triangle,
+ BlurShape::Hexagon,
+ BlurShape::Star,
+ BlurShape::Heart,
+ BlurShape::Cross,
+ ] {
+ if only != "all" && only != format!("{shape:?}").to_lowercase() {
+ continue;
+ }
+ for &radius in &radii {
+ let p = FilterParams::ShapeBlur { radius, shape };
+ drop(black_box(apply_in(&src, &p, bounds, bounds, None, bounds)));
+ let mut times = Vec::new();
+ for _ in 0..repeats {
+ let start = Instant::now();
+ let result = apply_in(&src, &p, bounds, bounds, None, bounds);
+ times.push(start.elapsed().as_secs_f64() * 1000.0);
+ drop(black_box(result));
+ }
+ times.sort_by(f64::total_cmp);
+ let median = times.get(times.len() / 2).copied().unwrap_or(0.0);
+ println!("{w},{h},{depth},{shape:?},{radius},{median:.3},{times:?}");
+ }
+ }
+ Ok(())
+}
diff --git a/crates/algo/src/blur2.rs b/crates/algo/src/blur2.rs
index b510fad0f..e91740508 100644
--- a/crates/algo/src/blur2.rs
+++ b/crates/algo/src/blur2.rs
@@ -122,7 +122,7 @@ fn polygon_radius(theta: f32, n: u32, rot: f32) -> f32 {
(PI / n as f32).cos() / a.cos()
}
-fn shape_inside(shape: BlurShape) -> Box<dyn Fn(f32, f32) -> bool + Send + Sync> {
+pub(crate) fn shape_inside(shape: BlurShape) -> Box<dyn Fn(f32, f32) -> bool + Send + Sync> {
match shape {
BlurShape::Circle => Box::new(|u, v| u * u + v * v <= 1.0),
BlurShape::Ring => Box::new(|u, v| {
@@ -154,10 +154,10 @@ fn shape_inside(shape: BlurShape) -> Box<dyn Fn(f32, f32) -> bool + Send + Sync>
/// Shape Blur: mean over a built-in shape of the given radius.
pub(crate) fn shape_blur(src: &Image, out: Rect, ctx: &Ctx, radius: f32, shape: BlurShape) -> Vec<f32> {
- let spans = Spans::new(radius.max(0.0), shape_inside(shape));
- conv_spans(src, out, ctx, &spans)
+ crate::shape_blur::Prepared::new(radius, shape).run(src, out, ctx)
}
+#[cfg(test)]
fn conv_spans(src: &Image, out: Rect, ctx: &Ctx, spans: &Spans) -> Vec<f32> {
let n = src.ch;
let win = src.rect;
@@ -180,6 +180,10 @@ fn conv_spans(src: &Image, out: Rect, ctx: &Ctx, spans: &Spans) -> Vec<f32> {
res
}
+#[cfg(test)]
+#[path = "shape_blur_tests.rs"]
+mod shape_tests;
+
// ---------- smart blur ----------
/// Smart Blur: averages only neighbours within `threshold` levels of the
diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs
index 18d8785e1..f82d60733 100644
--- a/crates/algo/src/lib.rs
+++ b/crates/algo/src/lib.rs
@@ -64,6 +64,7 @@ pub mod seam;
pub mod segment;
pub mod selection;
mod selection_blur;
+mod shape_blur;
mod sharpen;
pub mod stack;
mod stylize;
@@ -671,7 +672,7 @@ fn halo_ext(p: &FilterParams) -> Halo {
FilterParams::ReduceNoise { .. } => r(denoise::reach()),
FilterParams::SmartBlur { radius, .. } => r(*radius),
FilterParams::LensBlur { radius, .. } => r(*radius),
- FilterParams::ShapeBlur { radius, .. } => r(*radius),
+ FilterParams::ShapeBlur { radius, .. } => r(shape_blur::radius(*radius)),
FilterParams::TiltShift { blur, .. } => r(gallery::reach(*blur)),
FilterParams::IrisBlur { pins } => r(gallery::reach(pins.iter().map(|p| p.blur).fold(0.0, f32::max))),
FilterParams::FieldBlur { pins } => r(gallery::reach(pins.iter().map(|p| p.blur).fold(0.0, f32::max))),
@@ -944,12 +945,13 @@ pub fn apply_tiled(
tile: i32,
extent: Option<Rect>,
) -> Surface {
- // Never cancelled, so always `Some`; the fallback (the input unchanged) is unreachable.
+ // Preserve the input if a checked Shape Blur 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.
+/// one tile's work) and progress (after each group of tiles). `None` when cancelled,
+/// or when Shape Blur cannot allocate a tile.
#[allow(clippy::too_many_arguments)]
pub fn apply_tiled_with(
surface: &Surface,
@@ -971,19 +973,32 @@ pub fn apply_tiled_with(
if let Some(result) = blur::motion_apply::apply(surface, params, area, bounds, selection, extent, tile, ctl) {
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 };
let fmt = surface.format();
let ctx = Ctx { bounds, mode: fmt.mode, alpha: fmt.alpha };
let halo = params.halo_for(bounds);
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 {
+ FilterParams::ShapeBlur { radius, shape } => {
+ if ctl.cancelled() {
+ return None;
+ }
+ Some(shape_blur::Prepared::new(*radius, *shape))
+ }
+ _ => None,
+ };
let mut tiles = Vec::new();
let mut y = area.y0;
while y < area.y1 {
let mut x = area.x0;
while x < area.x1 {
- tiles.push(Rect::new(x, y, (x + tile).min(area.x1), (y + tile).min(area.y1)));
- x += tile;
+ tiles.push(Rect::new(x, y, x.saturating_add(tile).min(area.x1), y.saturating_add(tile).min(area.y1)));
+ x = x.saturating_add(tile);
}
- y += tile;
+ y = y.saturating_add(tile);
}
// Tiles finished so far, for progress reported per tile (from any worker thread).
let finished = std::sync::atomic::AtomicUsize::new(0);
@@ -1014,7 +1029,12 @@ pub fn apply_tiled_with(
&owned
}
};
- let mut data = kernel(params, src, *t, &ctx);
+ let Some(mut data) = (match &shape {
+ Some(shape) => shape.checked_run(src, *t, &ctx),
+ None => Some(kernel(params, src, *t, &ctx)),
+ }) else {
+ return (*t, Vec::new());
+ };
if let Some(sel) = selection {
mix_selection(&mut data, *t, sel, src);
}
@@ -1044,6 +1064,11 @@ pub fn apply_tiled_with(
if ctl.cancelled() {
return None;
}
+ // Shape Blur 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()) {
+ return None;
+ }
for (t, data) in results {
out.write_region(t, &data);
}
diff --git a/crates/algo/src/shape_blur.rs b/crates/algo/src/shape_blur.rs
new file mode 100644
index 000000000..26e9ad15b
--- /dev/null
+++ b/crates/algo/src/shape_blur.rs
@@ -0,0 +1,123 @@
+//! Shape Blur's row-wise convolution. Each sample sees the same f64 additions,
+//! in the same span order as the scalar implementation, but contiguous slices
+//! let the compiler vectorize without architecture-specific code or unsafe.
+use photocraft_geom::Rect;
+
+use crate::{
+ BlurShape, Ctx,
+ blur2::{Spans, shape_inside},
+ fxutil::unpremul_px,
+ image::Image,
+};
+
+/// The command supports at most 1000 px. Bound direct API input too, before
+/// halo arithmetic or O(r²) kernel rasterization. Nonfinite input uses zero radius.
+pub(crate) fn radius(r: f32) -> f32 {
+ if r.is_finite() { r.clamp(0.0, 1000.0) } else { 0.0 }
+}
+
+pub(crate) struct Prepared {
+ spans: Spans,
+}
+
+impl Prepared {
+ pub(crate) fn new(r: f32, shape: BlurShape) -> Self {
+ Self { spans: Spans::new(radius(r), shape_inside(shape)) }
+ }
+
+ pub(crate) fn run(&self, src: &Image, out: Rect, ctx: &Ctx) -> Vec<f32> {
+ self.checked_run(src, out, ctx).unwrap_or_default()
+ }
+
+ pub(crate) fn checked_run(&self, src: &Image, out: Rect, ctx: &Ctx) -> Option<Vec<f32>> {
+ let n = src.ch;
+ if n == 0 || n > crate::fxutil::MAXC || out.is_empty() {
+ return Some(Vec::new());
+ }
+ let w = src.rect.width() as usize;
+ let h = src.rect.height() as usize;
+ let input_row = w.checked_mul(n)?;
+ if src.data.len() != input_row.checked_mul(h)? {
+ return None;
+ }
+ let stride = w.checked_add(1)?.checked_mul(n)?;
+ let prefix_len = stride.checked_mul(h)?;
+ let row_len = (out.width() as usize).checked_mul(n)?;
+ let output_len = row_len.checked_mul(out.height() as usize)?;
+ // Bound scratch and output allocations, including hostile public Image/Rect input.
+ // Also accommodate direct full-image kernels (36 MP at all eight
+ // channels), not just the application's halo-expanded tiles.
+ const MAX_SAMPLES: usize = 512 * 1024 * 1024;
+ if prefix_len > MAX_SAMPLES || output_len > MAX_SAMPLES {
+ return None;
+ }
+ let mut prefix = Vec::new();
+ prefix.try_reserve_exact(prefix_len).ok()?;
+ prefix.resize(prefix_len, 0.0f64);
+ if input_row != 0 {
+ for (s, d) in src.data.chunks_exact(input_row).zip(prefix.chunks_exact_mut(stride)) {
+ let mut sum = [0.0f64; crate::fxutil::MAXC];
+ for (px, dst) in s.chunks_exact(n).zip(d.get_mut(n..)?.chunks_exact_mut(n)) {
+ let alpha = if ctx.alpha { *px.last()? } else { 1.0 };
+ for (c, ((v, sum), dst)) in px.iter().zip(sum.iter_mut()).zip(dst).enumerate() {
+ // Multiplication stays f32, exactly as premul_window.
+ let v = if ctx.alpha && c + 1 < n { *v * alpha } else { *v };
+ *sum += f64::from(v);
+ *dst = *sum;
+ }
+ }
+ }
+ }
+ let mut result = Vec::new();
+ result.try_reserve_exact(output_len).ok()?;
+ let mut acc = Vec::new();
+ acc.try_reserve_exact(row_len).ok()?;
+ acc.resize(row_len, 0.0f64);
+ let x = i64::from(out.x0) - i64::from(src.rect.x0);
+ for y in out.y0..out.y1 {
+ acc.fill(0.0);
+ for &(dy, a, b) in &self.spans.rows {
+ let yy = i64::from(y) - i64::from(src.rect.y0) + i64::from(dy);
+ let Ok(yy) = usize::try_from(yy) else {
+ continue;
+ };
+ if yy >= h {
+ continue;
+ }
+ let row = prefix.get(yy.checked_mul(stride)?..yy.checked_add(1)?.checked_mul(stride)?)?;
+ let lo = x + i64::from(a);
+ let hi = x + i64::from(b) + 1;
+ let end = out.width() as i64;
+ if lo >= 0 && hi + end <= w as i64 {
+ let start_lo = usize::try_from(lo).ok()?.checked_mul(n)?;
+ let start_hi = usize::try_from(hi).ok()?.checked_mul(n)?;
+ let low = row.get(start_lo..start_lo.checked_add(row_len)?)?;
+ let high = row.get(start_hi..start_hi.checked_add(row_len)?)?;
+ for ((acc, hi), lo) in acc.iter_mut().zip(high).zip(low) {
+ *acc += hi - lo;
+ }
+ } else {
+ // Direct kernel callers may omit the halo or request pixels outside src.
+ // Retain the scalar kernel's zero extension and fixed normalization.
+ for (i, px) in acc.chunks_exact_mut(n).enumerate() {
+ let low = (lo + i as i64).clamp(0, w as i64) as usize * n;
+ let high = (hi + i as i64).clamp(0, w as i64) as usize * n;
+ for ((acc, hi), lo) in px.iter_mut().zip(row.get(high..high + n)?).zip(row.get(low..low + n)?) {
+ *acc += hi - lo;
+ }
+ }
+ }
+ }
+ for px in acc.chunks_exact(n) {
+ let mut sample = [0.0f32; crate::fxutil::MAXC];
+ let sample = sample.get_mut(..n)?;
+ for (dst, sum) in sample.iter_mut().zip(px) {
+ *dst = (*sum / self.spans.count) as f32;
+ }
+ unpremul_px(sample, ctx.alpha);
+ result.extend_from_slice(sample);
+ }
+ }
+ Some(result)
+ }
+}
diff --git a/crates/algo/src/shape_blur_tests.rs b/crates/algo/src/shape_blur_tests.rs
new file mode 100644
index 000000000..96f8f4c1e
--- /dev/null
+++ b/crates/algo/src/shape_blur_tests.rs
@@ -0,0 +1,234 @@
+//! The pre-optimization prefix implementation remains an exact scalar oracle.
+//! A separate point-by-point convolution also checks normalization and sampling.
+use super::*;
+use crate::{FilterParams, apply_tiled, kernel};
+use photocraft_color::{ColorMode, PixelFormat, SampleType};
+use photocraft_raster::Surface;
+
+const SHAPES: [BlurShape; 9] = [
+ BlurShape::Circle,
+ BlurShape::Ring,
+ BlurShape::Square,
+ BlurShape::Diamond,
+ BlurShape::Triangle,
+ BlurShape::Hexagon,
+ BlurShape::Star,
+ BlurShape::Heart,
+ BlurShape::Cross,
+];
+
+#[test]
+fn binary_kernel_sampling_including_fractional_square_is_preserved() {
+ for (shape, radius, count) in [
+ (BlurShape::Circle, 3.0, 29.0),
+ (BlurShape::Ring, 3.0, 20.0),
+ (BlurShape::Square, 3.0, 49.0),
+ (BlurShape::Square, 2.5, 49.0),
+ (BlurShape::Diamond, 3.0, 25.0),
+ (BlurShape::Triangle, 3.0, 18.0),
+ (BlurShape::Cross, 3.0, 13.0),
+ ] {
+ assert_eq!(Spans::new(radius, shape_inside(shape)).count, count);
+ }
+}
+
+fn image(rect: Rect, n: usize, alpha: bool) -> Image {
+ let data = (0..rect.width() as usize * rect.height() as usize)
+ .flat_map(|i| (0..n).map(move |c| if alpha && c + 1 == n { (i % 7) as f32 / 6.0 } else { ((i * 31 + c * 13) % 97) as f32 / 96.0 }))
+ .collect();
+ Image { rect, ch: n, data }
+}
+
+fn exact(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} != {b}");
+ }
+}
+
+#[test]
+fn scalar_prefix_exact_all_shapes_radii_channels_subrects() {
+ for shape in SHAPES {
+ for radius in [0.0, 0.49, 0.5, 0.75, 1.0, 1.1, 2.5, 5.0, 25.0, 100.0] {
+ let spans = Spans::new(radius, shape_inside(shape));
+ for n in 1..=MAXC {
+ for alpha in [false, true] {
+ let src = image(Rect::new(-5, -3, 9, 7), n, alpha);
+ let ctx = Ctx { bounds: src.rect, mode: ColorMode::Multichannel, alpha };
+ for out in [src.rect, Rect::new(-2, 1, 3, 2), Rect::new(-8, -7, 12, 10), Rect::EMPTY] {
+ exact(&shape_blur(&src, out, &ctx, radius, shape), &conv_spans(&src, out, &ctx, &spans));
+ }
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn point_convolution_independent_of_prefix_and_span_accumulation() {
+ for shape in SHAPES {
+ for radius in [0.0f32, 0.5, 1.0, 1.25, 2.5, 5.0, 7.75] {
+ let src = image(Rect::new(-3, -2, 4, 3), 4, true);
+ let ctx = Ctx { bounds: src.rect, mode: ColorMode::Rgb, alpha: true };
+ let out = Rect::new(-5, -4, 6, 5);
+ let actual = shape_blur(&src, out, &ctx, radius, shape);
+ let inside = shape_inside(shape);
+ let ri = radius.ceil() as i32;
+ let mut points: Vec<(i32, i32)> = (-ri..=ri)
+ .flat_map(|y| (-ri..=ri).map(move |x| (x, y)))
+ .filter(|&(x, y)| radius >= 0.5 && inside(x as f32 / radius, y as f32 / radius))
+ .collect();
+ if points.is_empty() {
+ points.push((0, 0));
+ }
+ let mut reference = Vec::new();
+ for y in out.y0..out.y1 {
+ for x in out.x0..out.x1 {
+ let mut sums = [0.0f64; 4];
+ for &(dx, dy) in &points {
+ let a = src.get(x + dx, y + dy, 3);
+ for (c, sum) in sums.iter_mut().enumerate() {
+ let v = src.get(x + dx, y + dy, c);
+ *sum += f64::from(if c < 3 { v * a } else { v });
+ }
+ }
+ let mut px = sums.map(|s| (s / points.len() as f64) as f32);
+ unpremul_px(&mut px, true);
+ reference.extend(px);
+ }
+ }
+ // Finite f32 inputs are exactly representable in these short f64 sums.
+ exact(&actual, &reference);
+ }
+ }
+}
+
+#[test]
+fn surfaces_exact_depth_models_alpha_selection_and_tile_boundaries() {
+ let bounds = Rect::new(-2, -1, 263, 5);
+ let area = Rect::new(0, 0, 260, 4);
+ let mut selection = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));
+ let coverage: Vec<f32> = (0..area.width() as usize * area.height() as usize).map(|i| (i % 5) as f32 / 4.0).collect();
+ selection.write_region(area, &coverage);
+ for shape in SHAPES {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab, ColorMode::Multichannel] {
+ for alpha in [false, true] {
+ let fmt = PixelFormat::new(mode, depth, alpha);
+ let n = fmt.channels();
+ let mut surface = Surface::new(fmt);
+ surface.write_region(bounds, &image(bounds, n, alpha).data);
+ let ctx = Ctx { bounds, mode, alpha };
+ for radius in [2.5, 5.0, 25.0] {
+ let p = FilterParams::ShapeBlur { radius, shape };
+ let reach = radius.ceil() as i32 + 1;
+ for extent in [None, Some(bounds)] {
+ let src = match extent {
+ None => Image::read(&surface, area.inflate(reach)),
+ Some(e) => Image::read_clamped(&surface, area.inflate(reach), e),
+ };
+ let spans = Spans::new(radius, shape_inside(shape));
+ let mut expected = conv_spans(&src, area, &ctx, &spans);
+ crate::mix_selection(&mut expected, area, &selection, &src);
+ let mut reference = surface.clone();
+ reference.write_region(area, &expected);
+ for tile in [17, 256] {
+ let actual = apply_tiled(&surface, &p, area, bounds, Some(&selection), tile, extent);
+ exact(&actual.read_region(bounds), &reference.read_region(bounds));
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn largest_supported_radius_and_fraction_keep_scalar_kernel() {
+ let src = image(Rect::new(-1, -1, 2, 2), 4, true);
+ let ctx = Ctx { bounds: src.rect, mode: ColorMode::Rgb, alpha: true };
+ for shape in SHAPES {
+ for radius in [999.25, 1000.0] {
+ let spans = Spans::new(radius, shape_inside(shape));
+ exact(&shape_blur(&src, src.rect, &ctx, radius, shape), &conv_spans(&src, src.rect, &ctx, &spans));
+ }
+ }
+}
+
+#[test]
+fn degenerate_hdr_and_nonfinite_samples_keep_scalar_behavior() {
+ for rect in [Rect::EMPTY, Rect::new(0, 0, 1, 1), Rect::new(0, 0, 1, 7), Rect::new(0, 0, 9, 1)] {
+ for alpha in [false, true] {
+ let mut src = image(rect, 4, alpha);
+ for (i, v) in src.data.iter_mut().enumerate() {
+ if !alpha || i % 4 != 3 {
+ *v = [f32::MAX, -f32::MAX, 1e-30, -17.0, f32::INFINITY, f32::NEG_INFINITY, f32::NAN][i % 7];
+ } else {
+ *v = [0.0, 1e-8, 1e-7, 1.1e-7, 1.0][i % 5];
+ }
+ }
+ let ctx = Ctx { bounds: rect, mode: ColorMode::Lab, alpha };
+ for shape in SHAPES {
+ let spans = Spans::new(2.5, shape_inside(shape));
+ exact(&shape_blur(&src, rect, &ctx, 2.5, shape), &conv_spans(&src, rect, &ctx, &spans));
+ }
+ }
+ }
+ for alpha in [f32::NEG_INFINITY, -1.0, f32::NAN, 1e-30, f32::INFINITY, f32::MAX] {
+ let rect = Rect::new(0, 0, 3, 2);
+ let src = Image { rect, ch: 4, data: [1e20, -17.0, 0.0, alpha].repeat(6) };
+ let ctx = Ctx { bounds: rect, mode: ColorMode::Rgb, alpha: true };
+ for shape in SHAPES {
+ let spans = Spans::new(2.5, shape_inside(shape));
+ exact(&shape_blur(&src, rect, &ctx, 2.5, shape), &conv_spans(&src, rect, &ctx, &spans));
+ }
+ }
+}
+
+#[test]
+fn hostile_shape_inputs_are_bounded_and_do_not_panic() {
+ let rect = Rect::new(0, 0, 1, 1);
+ let ctx = Ctx { bounds: rect, mode: ColorMode::Rgb, alpha: true };
+ for src in [
+ Image { rect, ch: 0, data: vec![] },
+ Image { rect, ch: 9, data: vec![0.0; 9] },
+ Image { rect, ch: 4, data: vec![] },
+ Image { rect: Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX), ch: 4, data: vec![] },
+ ] {
+ assert!(kernel(&FilterParams::ShapeBlur { radius: 5.0, shape: BlurShape::Circle }, &src, rect, &ctx).is_empty());
+ }
+ let src = image(rect, 4, true);
+ for radius in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0, f32::MAX] {
+ let p = FilterParams::ShapeBlur { radius, shape: BlurShape::Circle };
+ assert!(matches!(p.halo(), crate::Halo::Radius(1..=1001)));
+ assert_eq!(kernel(&p, &src, rect, &ctx).len(), 4);
+ }
+ assert!(shape_blur(&src, Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX), &ctx, 5.0, BlurShape::Circle).is_empty());
+}
+
+#[test]
+fn shape_tile_overrides_and_cancel_preserve_input() {
+ for r in [Rect::new(0, 0, 4, 4), Rect::new(i32::MAX - 8, i32::MAX - 8, i32::MAX - 4, i32::MAX - 4)] {
+ let mut s = Surface::new(PixelFormat::RGBA8);
+ s.fill_rect(r, &[0.25, 0.5, 0.75, 1.0]);
+ let before = s.read_region(r);
+ let p = FilterParams::ShapeBlur { radius: 0.0, shape: BlurShape::Circle };
+ for tile in [i32::MIN, -1, 0, 256, i32::MAX] {
+ exact(&apply_tiled(&s, &p, r, r, None, tile, Some(r)).read_region(r), &before);
+ }
+ let ctl = photocraft_raster::Interrupt::cancel_only(&|| true);
+ assert!(crate::apply_tiled_with(&s, &p, r, r, None, 256, Some(r), &ctl).is_none());
+ exact(&s.read_region(r), &before);
+ }
+}
+
+#[test]
+#[ignore = "36 MP direct-kernel memory regression (about 1.7 GiB); run explicitly"]
+fn direct_36mp_image_with_small_output_is_not_rejected() {
+ let rect = Rect::new(0, 0, 6000, 6000);
+ let src = Image { rect, ch: 4, data: vec![0.25; 36_000_000 * 4] };
+ let ctx = Ctx { bounds: rect, mode: ColorMode::Rgb, alpha: true };
+ let result = shape_blur(&src, Rect::new(3000, 3000, 3001, 3001), &ctx, 5.0, BlurShape::Circle);
+ assert_eq!(result, vec![0.25; 4]);
+}