PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Speed up wide Motion Blur with adaptive FFT convolution (#1471)
optimalbyteec7dbb37b3c61
diff --git a/Cargo.lock b/Cargo.lockindex c6bbbeb6a..2dc5e7437 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3540,6 +3540,7 @@ dependencies = ["photocraft-geom","photocraft-raster","rayon",+ "rustfft","serde","serde_json",]@@ -4069,6 +4070,15 @@ version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa"+[[package]]+name = "primal-check"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08"+dependencies = [+ "num-integer",+]+[[package]]name = "proc-macro-crate"version = "3.5.0"@@ -4574,6 +4584,20 @@ dependencies = ["semver",]+[[package]]+name = "rustfft"+version = "6.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89"+dependencies = [+ "num-complex",+ "num-integer",+ "num-traits",+ "primal-check",+ "strength_reduce",+ "transpose",+]+[[package]]name = "rustix"version = "0.38.44"@@ -4993,6 +5017,12 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"+[[package]]+name = "strength_reduce"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82"+[[package]]name = "strict-num"version = "0.1.1"@@ -5333,6 +5363,16 @@ dependencies = ["once_cell",]+[[package]]+name = "transpose"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e"+dependencies = [+ "num-integer",+ "strength_reduce",+]+[[package]]name = "tree_magic_mini"version = "3.2.2"diff --git a/crates/algo/Cargo.toml b/crates/algo/Cargo.tomlindex 533ec0bad..c4f34b4b1 100644--- a/crates/algo/Cargo.toml+++ b/crates/algo/Cargo.toml@@ -14,6 +14,7 @@ photocraft-geom = { workspace = true }photocraft-color = { workspace = true }photocraft-raster = { workspace = true }serde = { workspace = true }+rustfft = "6.4.1"# Parallel tiles on native; wasm builds stay single-threaded.[target.'cfg(not(target_arch = "wasm32"))'.dependencies]diff --git a/crates/algo/src/blur.rs b/crates/algo/src/blur.rsindex d978b5f0c..97e9fa1a7 100644--- a/crates/algo/src/blur.rs+++ b/crates/algo/src/blur.rs@@ -7,6 +7,18 @@ use crate::image::{Edge, Image, premultiply, unpremultiply};use crate::photo_util::{par_map, par_rows};use crate::{Ctx, FilterParams, RadialMethod, RadialQuality};+#[cfg(test)]+use self::motion as motion_rows;++pub(crate) mod motion_apply;+#[cfg(all(test, not(target_arch = "wasm32")))]+mod motion_bench;+mod motion_fft;+#[cfg(test)]+mod motion_fft_tests;+#[cfg(test)]+mod motion_tests;+/// Normalized Gaussian kernel with standard deviation `sigma` (radius 3σ).pub(crate) fn gaussian_kernel(sigma: f32) -> Vec<f32> {if sigma < 0.05 {diff --git a/crates/algo/src/blur/motion_apply.rs b/crates/algo/src/blur/motion_apply.rsnew file mode 100644index 000000000..cc2f3e84e--- /dev/null+++ b/crates/algo/src/blur/motion_apply.rs@@ -0,0 +1,292 @@+//! Bounded tile scheduling for wide Motion Blur convolution.++use photocraft_geom::Rect;+use photocraft_raster::{Interrupt, Surface};++use super::motion_fft::{COORDINATE_LIMIT, Plan, ordinary_coordinates, worthwhile};+use crate::{FilterParams, Image};++const MAX_RESIDENT_BYTES: usize = 512 << 20;+const MIN_TILE: i32 = 64;+const MAX_TILE: i32 = 512;++fn valid_rect(rect: Rect) -> bool {+ !rect.is_empty() && rect.width() <= COORDINATE_LIMIT as u32 && rect.height() <= COORDINATE_LIMIT as u32 && ordinary_coordinates(rect)+}++fn bytes(rect: Rect, channels: usize) -> Option<usize> {+ usize::try_from(rect.width()).ok()?.checked_mul(usize::try_from(rect.height()).ok()?)?.checked_mul(channels)?.checked_mul(std::mem::size_of::<f32>())+}++fn group_size(resident: usize, metadata: usize, worker: usize, output: usize, tiles: usize, workers: usize) -> Option<usize> {+ if tiles == 0 || workers == 0 {+ return None;+ }+ let available = MAX_RESIDENT_BYTES.checked_sub(resident)?.checked_sub(metadata)?;+ let per_tile = worker.checked_add(output)?;+ let memory_workers = available.checked_div(per_tile.max(1))?;+ (memory_workers > 0).then_some(memory_workers.min(workers).min(tiles))+}++/// `None` declines the specialization; `Some(None)` propagates cancellation. Input pixels are+/// never edited, including when cancellation discards a partially written output clone.+#[allow(clippy::too_many_arguments)]+pub(crate) fn apply(+ surface: &Surface,+ params: &FilterParams,+ area: Rect,+ bounds: Rect,+ selection: Option<&Surface>,+ extent: Option<Rect>,+ tile: i32,+ ctl: &Interrupt,+) -> Option<Option<Surface>> {+ apply_inner(surface, params, area, bounds, selection, extent, tile, ctl, false)+}++#[allow(clippy::too_many_arguments)]+#[cfg(test)]+pub(super) fn apply_for_bench(+ surface: &Surface,+ params: &FilterParams,+ area: Rect,+ bounds: Rect,+ selection: Option<&Surface>,+ extent: Option<Rect>,+ tile: i32,+ ctl: &Interrupt,+) -> Option<Option<Surface>> {+ apply_inner(surface, params, area, bounds, selection, extent, tile, ctl, true)+}++#[allow(clippy::too_many_arguments)]+fn apply_inner(+ surface: &Surface,+ params: &FilterParams,+ area: Rect,+ bounds: Rect,+ selection: Option<&Surface>,+ extent: Option<Rect>,+ tile: i32,+ ctl: &Interrupt,+ force: bool,+) -> Option<Option<Surface>> {+ let FilterParams::MotionBlur { angle, distance } = *params else { return None };+ if ctl.cancelled() {+ return Some(None);+ }+ if area.is_empty() {+ return Some(Some(surface.clone()));+ }+ let fmt = surface.format();+ let channels = fmt.channels();+ if !(1..=5).contains(&channels)+ || !valid_rect(area)+ || !valid_rect(bounds)+ || extent.is_some_and(|rect| !valid_rect(rect))+ // read_clamped falls back to raw reads when its window misses the+ // extent. A directional and square halo can differ in that case;+ // preserve the old boundary policy for out-of-canvas output areas.+ || extent.is_some_and(|rect| area.intersect(&rect) != area)+ || selection.is_some_and(|selection| selection.channels() == 0)+ {+ return None;+ }+ let pixels = u64::from(area.width()).checked_mul(u64::from(area.height()))?;+ if pixels < 4096 {+ return None;+ }+ let row_tile = usize::try_from(tile).ok()?;+ #[cfg(not(target_arch = "wasm32"))]+ let workers = rayon::current_num_threads();+ #[cfg(target_arch = "wasm32")]+ let workers = 1;+ let mut tile = tile.clamp(MIN_TILE, MAX_TILE);+ while tile > MIN_TILE && (area.width() < tile as u32 || area.height() < tile as u32) {+ tile = (tile / 2).max(MIN_TILE);+ }+ let tile_usize = usize::try_from(tile).ok()?;+ if !force && !worthwhile(angle, distance, tile_usize, area, row_tile, channels, workers)? {+ return None;+ }+ let plan = match Plan::new_with(angle, distance, tile_usize, ctl) {+ Some(plan) => plan,+ None if ctl.cancelled() => return Some(None),+ None => return None,+ };+ if ctl.cancelled() {+ return Some(None);+ }+ let columns = usize::try_from(area.width()).ok()?.div_ceil(tile_usize);+ let rows = usize::try_from(area.height()).ok()?.div_ceil(tile_usize);+ let count = columns.checked_mul(rows)?;+ let metadata_bytes = count.checked_mul(std::mem::size_of::<(Rect, Rect)>())?;+ let mut tiles = Vec::new();+ tiles.try_reserve_exact(count).ok()?;+ let mut largest_source_bytes = 0;+ let mut y = area.y0;+ while y < area.y1 {+ let y1 = y.checked_add(tile)?.min(area.y1);+ let mut x = area.x0;+ while x < area.x1 {+ let x1 = x.checked_add(tile)?.min(area.x1);+ let output = Rect::new(x, y, x1, y1);+ let source = plan.read_rect(output)?;+ if !valid_rect(source) {+ return None;+ }+ largest_source_bytes = largest_source_bytes.max(bytes(source, channels)?);+ tiles.push((output, source));+ x = x1;+ }+ y = y1;+ }+ // read_clamped temporarily holds both its inner read and expanded image. The convolution+ // estimate includes its input and scratch, but that decoding peak needs a separate check.+ let decode_bytes = largest_source_bytes.checked_mul(if extent.is_some() { 2 } else { 1 })?;+ let worker_bytes = plan.worker_bytes(channels, tile_usize)?.max(decode_bytes);+ let output_bytes = tile_usize.checked_mul(tile_usize)?.checked_mul(channels)?.checked_mul(std::mem::size_of::<f32>())?;+ // A group's results remain live until its last worker finishes. Bounding the complete+ // group by each tile's scratch plus output is conservative and avoids forcing one per core.+ let group = group_size(plan.resident_bytes(), metadata_bytes, worker_bytes, output_bytes, tiles.len(), workers)?;+ let finished = std::sync::atomic::AtomicUsize::new(0);+ let run = |&(output, source): &(Rect, Rect)| -> Option<(Rect, Vec<f32>)> {+ if ctl.cancelled() {+ return None;+ }+ let src = match extent {+ Some(extent) => Image::read_clamped(surface, source, extent),+ None => Image::read(surface, source),+ };+ if ctl.cancelled() {+ return None;+ }+ // Unsupported source values decline the entire specialization. The caller then+ // retries its unchanged row pipeline, discarding this clone and any partial writes.+ // Do not allocate a row kernel's square window inside the FFT working-set budget.+ let mut data = plan.filter(&src, output, fmt.alpha, ctl)?;+ if ctl.cancelled() || data.len().checked_mul(std::mem::size_of::<f32>())? != bytes(output, channels)? {+ return None;+ }+ if let Some(selection) = selection {+ crate::mix_selection(&mut data, output, selection, &src);+ }+ if ctl.cancelled() {+ return None;+ }+ let done = finished.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;+ ctl.progress(0.98 * done as f32 / count as f32);+ Some((output, data))+ };+ let mut out = surface.clone();+ for chunk in tiles.chunks(group) {+ if ctl.cancelled() {+ return Some(None);+ }+ #[cfg(not(target_arch = "wasm32"))]+ let results: Option<Vec<_>> = {+ use rayon::prelude::*;+ chunk.par_iter().map(run).collect()+ };+ #[cfg(target_arch = "wasm32")]+ let results: Option<Vec<_>> = chunk.iter().map(run).collect();+ let Some(results) = results else { return if ctl.cancelled() { Some(None) } else { None } };+ for (output, data) in results {+ if ctl.cancelled() {+ return Some(None);+ }+ out.write_region(output, &data);+ }+ }+ if ctl.cancelled() {+ return Some(None);+ }+ out.prune();+ if ctl.cancelled() {+ return Some(None);+ }+ ctl.progress(1.0);+ Some(Some(out))+}++#[cfg(test)]+mod tests {+ use std::sync::atomic::{AtomicBool, Ordering};++ use photocraft_color::PixelFormat;++ use super::*;++ #[test]+ fn scheduler_bounds_complete_groups_including_sources_and_outputs() {+ let mib = 1 << 20;+ let group = group_size(100 * mib, mib, 150 * mib, 5 * mib, 100, 12).unwrap();+ assert_eq!(group, 2, "memory limits must take precedence over one tile per worker");+ assert!(100 * mib + mib + group * (150 * mib + 5 * mib) <= MAX_RESIDENT_BYTES);+ assert_eq!(group_size(100 * mib, 0, 450 * mib, 5 * mib, 100, 12), None);+ assert_eq!(group_size(MAX_RESIDENT_BYTES, 1, 1, 1, 1, 1), None);+ assert_eq!(group_size(0, 0, usize::MAX, 1, 1, 1), None);+ assert_eq!(group_size(0, 0, 1, 1, 0, 1), None);+ }++ #[test]+ fn scheduler_preflight_declines_unsupported_geometry_and_small_distances() {+ let surface = Surface::new(PixelFormat::GRAY8);+ let bounds = Rect::new(0, 0, 128, 128);+ let small = FilterParams::MotionBlur { angle: 30.0, distance: 10.0 };+ assert!(apply(&surface, &small, bounds, bounds, None, Some(bounds), 64, &Interrupt::NONE).is_none());+ let wide = FilterParams::MotionBlur { angle: 30.0, distance: 64.0 };+ let oversized = Rect::new(0, 0, i32::MAX, 128);+ assert!(apply(&surface, &wide, oversized, bounds, None, Some(bounds), 64, &Interrupt::NONE).is_none());+ assert!(apply(&surface, &wide, bounds, bounds, None, Some(Rect::EMPTY), 64, &Interrupt::NONE).is_none());+ assert!(apply(&surface, &wide, Rect::new(0, 0, 1, 1), bounds, None, Some(bounds), 512, &Interrupt::NONE).is_none());+ let huge = FilterParams::MotionBlur { angle: 30.0, distance: 2000.0 };+ assert!(apply(&surface, &huge, bounds, bounds, None, Some(bounds), 512, &Interrupt::NONE).is_none());+ assert!(!valid_rect(Rect::new(-COORDINATE_LIMIT, 0, COORDINATE_LIMIT, 1)));+ assert!(apply(&surface, &wide, Rect::EMPTY, bounds, None, Some(bounds), 64, &Interrupt::NONE).unwrap().unwrap().tiles().next().is_none());+ }++ #[test]+ fn crossover_keeps_rows_for_measured_losses_and_memory_limited_large_streaks() {+ let proxy = Rect::new(0, 0, 1500, 1000);+ let full = Rect::new(0, 0, 6000, 4000);+ for workers in [1, 2, 4, 12] {+ for channels in 1..=5 {+ for angle in [0.0, 30.0, 45.0, 90.0] {+ for distance in [10.0, 64.0, 128.0, 256.0] {+ assert_eq!(worthwhile(angle, distance, 512, proxy, 576, channels, workers), Some(false));+ }+ }+ }+ }+ for workers in [4, 12] {+ assert_eq!(worthwhile(30.0, 1000.0, 512, proxy, 1024, 4, workers), Some(true));+ assert_eq!(worthwhile(45.0, 2000.0, 512, proxy, 2048, 4, workers), Some(true));+ assert_eq!(worthwhile(30.0, 2000.0, 512, full, 2048, 4, workers), Some(false));+ }+ assert_eq!(worthwhile(30.0, 1000.0, 512, full, 1024, 4, 12), Some(true));+ assert_eq!(worthwhile(30.0, 1000.0, 512, proxy, 1024, 4, 1), Some(false));+ assert_eq!(worthwhile(30.0, 1000.0, 64, Rect::new(0, 0, 64, 64), 1024, 4, 12), Some(false));+ }++ #[test]+ fn scheduler_cancellation_discards_all_partial_output() {+ let bounds = Rect::new(0, 0, 128, 128);+ let mut surface = Surface::new(PixelFormat::GRAY8);+ surface.fill_rect(bounds, &[0.4]);+ let before = surface.to_interleaved(bounds);+ let params = FilterParams::MotionBlur { angle: 0.0, distance: 64.0 };+ let cancelled = AtomicBool::new(true);+ let cancel = || cancelled.load(Ordering::Relaxed);+ assert!(matches!(apply(&surface, ¶ms, bounds, bounds, None, Some(bounds), 64, &Interrupt::cancel_only(&cancel)), Some(None)));+ cancelled.store(false, Ordering::Relaxed);+ let progress = |fraction: f32| {+ if fraction > 0.0 {+ cancelled.store(true, Ordering::Relaxed);+ }+ };+ let ctl = Interrupt::new(&cancel, &progress);+ assert!(matches!(apply_for_bench(&surface, ¶ms, bounds, bounds, None, Some(bounds), 64, &ctl), Some(None)));+ assert_eq!(surface.to_interleaved(bounds), before);+ }+}diff --git a/crates/algo/src/blur/motion_bench.rs b/crates/algo/src/blur/motion_bench.rsnew file mode 100644index 000000000..849dbda74--- /dev/null+++ b/crates/algo/src/blur/motion_bench.rs@@ -0,0 +1,224 @@+//! Opt-in release comparisons against the Motion Blur row kernel merged in upstream PR #902.+#![cfg(not(target_arch = "wasm32"))]++use super::*;+use photocraft_color::{ColorMode, PixelFormat, SampleType};+use photocraft_raster::Surface;+use rayon::prelude::*;+use serde_json::json;+use std::time::Instant;++/// Copy of upstream's tiled apply_in pipeline, with its merged row kernel called directly so+/// the experimental FFT dispatch cannot change the baseline. Source reads, automatic tile+/// sizing, Rayon groups, writes, progress and pruning follow the current upstream implementation.+#[allow(clippy::panic)] // Fixed benchmark parameters, never a production entry point.+fn apply_reference(surface: &Surface, params: &FilterParams, area: Rect) -> Surface {+ let FilterParams::MotionBlur { angle, distance } = params else { panic!("Motion Blur benchmark parameters required") };+ let crate::Halo::Radius(halo) = params.halo_for(area) else { panic!("Motion Blur must declare a radius halo") };+ let tile = crate::auto_tile(params, area);+ let fmt = surface.format();+ let ctx = Ctx { bounds: area, mode: fmt.mode, alpha: fmt.alpha };+ let mut out = surface.clone();+ 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;+ }+ y += tile;+ }+ let finished = std::sync::atomic::AtomicUsize::new(0);+ let total = tiles.len().max(1);+ let ctl = Interrupt::NONE;+ let run = |t: &Rect| {+ if ctl.cancelled() {+ return (*t, Vec::new());+ }+ let src = Image::read_clamped(surface, t.inflate(halo), area);+ let data = motion_rows(&src, *t, &ctx, *angle, *distance);+ let n = finished.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;+ ctl.progress(0.98 * n as f32 / total as f32);+ (*t, data)+ };+ let per_tile = (tile.max(1) as usize).pow(2) * fmt.channels() * std::mem::size_of::<f32>();+ let group = (crate::RESULT_BUDGET / per_tile.max(1)).max(rayon::current_num_threads()).max(1);+ for chunk in tiles.chunks(group) {+ let results: Vec<_> = chunk.par_iter().map(run).collect();+ for (t, data) in results {+ out.write_region(t, &data);+ }+ }+ out.prune();+ ctl.progress(1.0);+ out+}++fn source(area: Rect, variable_alpha: bool, channels: usize) -> Surface {+ 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),+ _ => (ColorMode::Rgb, true),+ };+ let mut surface = Surface::new(PixelFormat::new(mode, SampleType::U8, alpha));+ let bytes: Vec<u8> = (area.y0..area.y1)+ .flat_map(|y| {+ (area.x0..area.x1).flat_map(move |x| {+ let (r, g, b) = ((x % 256) as u8, ((x * 3 + y) / 11 % 256) as u8, ((x ^ y) % 256) as u8);+ let alpha = if variable_alpha { (x ^ (y * 7)) as u8 } else { 255 };+ let pixel = match channels {+ 1 => [r, 0, 0, 0, 0],+ 2 => [r, alpha, 0, 0, 0],+ 3 => [r, g, b, 0, 0],+ 4 => [r, g, b, alpha, 0],+ 5 => [r, g, b, ((x * 5 + y * 7) % 256) as u8, alpha],+ _ => [0; 5],+ };+ pixel.into_iter().take(channels)+ })+ })+ .collect();+ surface.write_interleaved(area, &bytes);+ surface+}++fn median(values: &[f64]) -> f64 {+ let mut sorted = values.to_vec();+ sorted.sort_by(f64::total_cmp);+ match sorted.get(sorted.len() / 2) {+ Some(&value) if !sorted.len().is_multiple_of(2) => value,+ Some(&value) => (value + sorted.get(sorted.len() / 2 - 1).copied().unwrap_or(value)) * 0.5,+ None => 0.0,+ }+}++#[allow(clippy::panic)] // Invalid benchmark configuration should fail visibly.+fn env_number(name: &str, default: u32) -> u32 {+ match std::env::var(name) {+ Ok(value) => match value.parse() {+ Ok(value) => value,+ Err(_) => panic!("invalid benchmark number {name}={value}"),+ },+ Err(_) => default,+ }+}++#[allow(clippy::panic)] // Invalid benchmark configuration should fail visibly.+fn cases() -> Vec<(f32, f32)> {+ let spec = std::env::var("PHOTOCRAFT_MOTION_CASES")+ .unwrap_or_else(|_| "30:10,30:50,30:64,30:128,30:256,30:500,30:1000,30:2000,0:256,0:1000,0:2000,90:256,90:1000,90:2000,45:256,45:1000,45:2000".into());+ spec.split(',')+ .map(|case| {+ let Some((angle, distance)) = case.trim().split_once(':') else { panic!("expected angle:distance in PHOTOCRAFT_MOTION_CASES") };+ let (Ok(angle), Ok(distance)) = (angle.parse::<f32>(), distance.parse::<f32>()) else { panic!("invalid Motion Blur benchmark case {case}") };+ assert!(angle.is_finite() && (0.5..=2000.0).contains(&distance), "out-of-range benchmark case {case}");+ (angle, distance)+ })+ .collect()+}++#[allow(clippy::panic)] // A cancellation with Interrupt::NONE is a benchmark failure.+fn candidate(surface: &Surface, params: &FilterParams, area: Rect, forced: bool) -> (Surface, bool) {+ if forced {+ match super::motion_apply::apply_for_bench(surface, params, area, area, None, Some(area), crate::auto_tile(params, area), &Interrupt::NONE) {+ Some(Some(result)) => return (result, true),+ Some(None) => panic!("uncancellable forced FFT benchmark was cancelled"),+ None => {}+ }+ }+ (crate::apply_in(surface, params, area, area, None, area), false)+}++fn compare(surface: &Surface, area: Rect, angle: f32, distance: f32, runs: usize, forced: bool, variable_alpha: bool) {+ let params = FilterParams::MotionBlur { angle, distance };+ let channels = surface.channels();+ let mut upstream_ms = Vec::with_capacity(runs);+ let mut candidate_ms = Vec::with_capacity(runs);+ let mut largest_error = 0u8;+ let mut changed_samples = 0usize;+ let mut squared_error = 0u64;+ let mut compared_samples = 0usize;+ let mut fft_applied = false;+ for run in 0..runs {+ let upstream = || {+ let start = Instant::now();+ let result = apply_reference(surface, ¶ms, area);+ (result, start.elapsed().as_secs_f64() * 1000.0)+ };+ let after = || {+ let start = Instant::now();+ let (result, used_fft) = candidate(surface, ¶ms, area, forced);+ (result, start.elapsed().as_secs_f64() * 1000.0, used_fft)+ };+ let ((before, before_ms), (after, after_ms, used_fft)) = if run % 2 == 0 {+ (upstream(), after())+ } else {+ let after = after();+ (upstream(), after)+ };+ upstream_ms.push(before_ms);+ candidate_ms.push(after_ms);+ fft_applied |= used_fft;+ let before = before.to_interleaved(area);+ let after = after.to_interleaved(area);+ assert_eq!(before.len(), after.len());+ let mut maximum = 0u8;+ let mut changed = 0usize;+ let mut squared = 0u64;+ for (&before, &after) in before.iter().zip(&after) {+ let error = before.abs_diff(after);+ maximum = maximum.max(error);+ changed += usize::from(error != 0);+ squared += u64::from(error).pow(2);+ }+ assert!(maximum <= 1, "upstream comparison exceeded one U8 level: angle={angle}, distance={distance}, error={maximum}");+ largest_error = largest_error.max(maximum);+ changed_samples += changed;+ squared_error += squared;+ compared_samples += before.len();+ println!(+ "{}",+ json!({"event":"motion_upstream_run", "width":area.width(), "height":area.height(), "channels":channels, "angle":angle, "distance":distance, "run":run, "mode":if forced {"forced_fft"} else {"public"}, "fft_applied":if forced {Some(used_fft)} else {None}, "variable_alpha":variable_alpha, "upstream_ms":before_ms, "candidate_ms":after_ms, "max_u8_error":maximum, "changed_samples":changed, "rms_u8_error":(squared as f64 / before.len() as f64).sqrt()})+ );+ }+ println!(+ "{}",+ json!({"event":"motion_upstream_median", "width":area.width(), "height":area.height(), "channels":channels, "angle":angle, "distance":distance, "runs":runs, "mode":if forced {"forced_fft"} else {"public"}, "fft_applied":if forced {Some(fft_applied)} else {None}, "variable_alpha":variable_alpha, "upstream_median_ms":median(&upstream_ms), "candidate_median_ms":median(&candidate_ms), "speedup":median(&upstream_ms)/median(&candidate_ms), "upstream_runs_ms":upstream_ms, "candidate_runs_ms":candidate_ms, "max_u8_error":largest_error, "changed_samples":changed_samples, "rms_u8_error":(squared_error as f64 / compared_samples as f64).sqrt()})+ );+}++/// Reproduce in release with --ignored --nocapture. PHOTOCRAFT_MOTION_WIDTH/HEIGHT default to+/// 1500/1000; PHOTOCRAFT_MOTION_RUNS defaults to 3; PHOTOCRAFT_MOTION_CASES is comma-separated+/// angle:distance pairs. PHOTOCRAFT_MOTION_MODE=public measures final dispatch, otherwise forced+/// FFT is attempted (normal eligibility/memory guards remain). PHOTOCRAFT_MOTION_CHANNELS=1..5+/// selects Gray, Gray-alpha, RGB, RGBA (default), or CMYK-alpha. PHOTOCRAFT_MOTION_VARIABLE_ALPHA=1+/// enables varying alpha in formats that have alpha. Timings include reads, writes and pruning, excluding+/// source construction, output comparison, proxy construction, compositing and GPU upload.+#[test]+#[ignore = "upstream row kernel versus FFT/full-dispatch release calibration"]+fn motion_upstream_performance() {+ let width = env_number("PHOTOCRAFT_MOTION_WIDTH", 1500);+ let height = env_number("PHOTOCRAFT_MOTION_HEIGHT", 1000);+ let runs = env_number("PHOTOCRAFT_MOTION_RUNS", 3) as usize;+ let channels = env_number("PHOTOCRAFT_MOTION_CHANNELS", 4) as usize;+ assert!((1..=16384).contains(&width) && (1..=16384).contains(&height));+ assert!((1..=31).contains(&runs));+ assert!((1..=5).contains(&channels));+ let area = Rect::new(0, 0, width as i32, height as i32);+ let mode = std::env::var("PHOTOCRAFT_MOTION_MODE").unwrap_or_else(|_| "forced_fft".into());+ assert!(matches!(mode.as_str(), "public" | "forced_fft"), "PHOTOCRAFT_MOTION_MODE must be public or forced_fft");+ let forced = mode == "forced_fft";+ let variable_alpha = matches!(channels, 2 | 4 | 5) && std::env::var("PHOTOCRAFT_MOTION_VARIABLE_ALPHA").is_ok_and(|value| value != "0" && value != "false");+ println!(+ "{}",+ json!({"event":"motion_upstream_config", "width":width, "height":height, "channels":channels, "runs":runs, "mode":if forced {"forced_fft"} else {"public"}, "variable_alpha":variable_alpha, "rayon_workers":rayon::current_num_threads(), "os":std::env::consts::OS, "arch":std::env::consts::ARCH, "baseline":"merged upstream PR902 motion_rows plus current upstream tiled pipeline", "timing_scope":"source decode/halo reads, filtering, writes, pruning; excludes construction/comparison/UI"})+ );+ let surface = source(area, variable_alpha, channels);+ for (angle, distance) in cases() {+ compare(&surface, area, angle, distance, runs, forced, variable_alpha);+ }+}diff --git a/crates/algo/src/blur/motion_fft.rs b/crates/algo/src/blur/motion_fft.rsnew file mode 100644index 000000000..9da1b1a1b--- /dev/null+++ b/crates/algo/src/blur/motion_fft.rs@@ -0,0 +1,515 @@+//! Overlap-save convolution of the discrete Motion Blur kernel.+//!+//! The spectrum uses the upstream row kernel's merged f32 coefficients, with+//! no intermediate image resampling. Transforms use doubles and keep alpha+//! premultiplied until the final output. The summation order differs from the+//! row kernel, which remains the fallback.++use std::sync::Arc;++use photocraft_geom::Rect;+use photocraft_raster::Interrupt;+use rustfft::{Fft, FftPlanner, num_complex::Complex};++use crate::Image;++const MAX_POINTS: usize = 4 << 20;+const MAX_SIDE: usize = 8192;+const MAX_BYTES: usize = 128 << 20;+const MAX_SAMPLE: f32 = 1e10;+pub(super) const COORDINATE_LIMIT: i32 = 16_384;++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 result = Vec::new();+ result.try_reserve_exact(len).ok()?;+ result.resize(len, value);+ Some(result)+}++fn dimensions(rect: Rect) -> Option<(usize, usize)> {+ Some((usize::try_from(i64::from(rect.x1) - i64::from(rect.x0)).ok()?, usize::try_from(i64::from(rect.y1) - i64::from(rect.y0)).ok()?))+}++pub(super) fn ordinary_coordinates(rect: Rect) -> bool {+ [rect.x0, rect.y0, rect.x1, rect.y1].iter().all(|v| (-COORDINATE_LIMIT..=COORDINATE_LIMIT).contains(v))+}++// Smooth lengths avoid the almost fourfold padding of a 512px tile plus a+// short halo to a 1024x1024 power-of-two transform. RustFFT supports these+// mixed-radix lengths efficiently.+fn fft_size(needed: usize) -> Option<usize> {+ if needed == 0 || needed > MAX_SIDE {+ return None;+ }+ let mut best = MAX_SIDE;+ let mut a = 1usize;+ while a <= MAX_SIDE {+ let mut b = a;+ while b <= MAX_SIDE {+ let mut c = b;+ while c <= MAX_SIDE {+ if c >= needed {+ best = best.min(c);+ }+ c = c.checked_mul(5)?;+ }+ b = b.checked_mul(3)?;+ }+ a = a.checked_mul(2)?;+ }+ Some(best)+}++#[derive(Clone, Copy)]+struct Tap {+ x: i32,+ y: i32,+ weight: f64,+}++fn taps(angle: f32, distance: f32, clip: Option<(Rect, Rect)>) -> Option<Vec<Tap>> {+ let distance = distance.abs();+ if !angle.is_finite() || !(64.0..=2000.0).contains(&distance) {+ return None;+ }+ let steps = distance.ceil() as i32;+ let (sin, cos) = angle.to_radians().sin_cos();+ let norm = 1.0 / (steps + 1) as f32;+ let capacity = usize::try_from(steps + 1).ok()?.checked_mul(4)?;+ let mut merged: Vec<(i32, i32, f32)> = Vec::new();+ merged.try_reserve_exact(capacity).ok()?;+ let mut slots = std::collections::HashMap::new();+ slots.try_reserve(capacity).ok()?;+ for i in 0..=steps {+ // Match PR #902's f32 geometry, normalized weights and first-seen merge order.+ let t = i as f32 / steps as f32 - 0.5;+ let (x, y) = (cos * distance * t, -sin * distance * t);+ let (ix, iy) = (x.floor() as i32, y.floor() as i32);+ let (fx, fy) = (x - ix as f32, y - iy as f32);+ for (x, y, weight) in [(ix, iy, (1.0 - fx) * (1.0 - fy)), (ix + 1, iy, fx * (1.0 - fy)), (ix, iy + 1, (1.0 - fx) * fy), (ix + 1, iy + 1, fx * fy)] {+ if weight <= 0.0 {+ continue;+ }+ let slot = *slots.entry((x, y)).or_insert_with(|| {+ merged.push((x, y, 0.0));+ merged.len() - 1+ });+ merged.get_mut(slot)?.2 += weight * norm;+ }+ }+ let mut result = Vec::new();+ result.try_reserve_exact(merged.len()).ok()?;+ for (x, y, weight) in merged {+ if let Some((source, out)) = clip {+ // Omitted reads are transparent; retain the complete kernel's coefficients.+ if i64::from(out.x0) + i64::from(x) >= i64::from(source.x1)+ || i64::from(out.x1) - 1 + i64::from(x) < i64::from(source.x0)+ || i64::from(out.y0) + i64::from(y) >= i64::from(source.y1)+ || i64::from(out.y1) - 1 + i64::from(y) < i64::from(source.y0)+ {+ continue;+ }+ }+ result.push(Tap { x, y, weight: f64::from(weight) });+ }+ Some(result)+}++/// One pixel of the upstream row kernel, without allocating its premultiplied+/// square window. Coefficients and accumulation retain their original f32 order.+fn sample_row_point(src: &Image, x: i32, y: i32, alpha: bool, taps: &[Tap], ctl: &Interrupt) -> Option<[f32; 5]> {+ let (width, height) = dimensions(src.rect)?;+ if !(1..=5).contains(&src.ch) || width.checked_mul(height)?.checked_mul(src.ch)? != src.data.len() || !ordinary_coordinates(src.rect) {+ return None;+ }+ let mut result = [0.0f32; 5];+ for (i, tap) in taps.iter().enumerate() {+ if i % 64 == 0 && ctl.cancelled() {+ return None;+ }+ let (sx, sy) = (x.checked_add(tap.x)?, y.checked_add(tap.y)?);+ let a = if alpha { src.get(sx, sy, src.ch - 1) } else { 1.0 };+ // Each stored coefficient came directly from f32 and converts back+ // exactly. Match the row kernel's weight * premultiplied sample order.+ let weight = tap.weight as f32;+ for (c, value) in result.iter_mut().take(src.ch).enumerate() {+ let sample = src.get(sx, sy, c);+ let premultiplied = if alpha && c + 1 < src.ch { sample * a } else { sample };+ *value += weight * premultiplied;+ }+ }+ if alpha {+ let a = *result.get(src.ch - 1)?;+ for value in result.iter_mut().take(src.ch - 1) {+ *value = if a > 1e-7 { *value / a } else { 0.0 };+ }+ }+ Some(result)+}++/// Conservative native crossover against the merged row kernel. Wide rows can+/// be faster than transforms unless FFT tiles retain enough parallelism. The+/// release matrix in motion_bench covers both winners and declined cases.+#[allow(clippy::too_many_arguments)]+pub(super) fn worthwhile(angle: f32, distance: f32, tile: usize, area: Rect, row_tile: usize, channels: usize, workers: usize) -> Option<bool> {+ if workers < 4 || !(1..=5).contains(&channels) || row_tile == 0 {+ return Some(false);+ }+ let pairs = channels.div_ceil(2);+ // Transforming a channel pair costs almost the same as one channel. Stay+ // on rows for short streaks, with a higher crossover for odd channel counts.+ if !distance.is_finite() || distance.abs() * (channels as f32) < 1500.0 * pairs as f32 {+ return Some(false);+ }+ let taps = taps(angle, distance, None)?;+ let (mut min_x, mut max_x, mut min_y, mut max_y) = (0, 0, 0, 0);+ for tap in &taps {+ min_x = min_x.min(tap.x);+ max_x = max_x.max(tap.x);+ min_y = min_y.min(tap.y);+ max_y = max_y.max(tap.y);+ }+ let sx = usize::try_from(max_x - min_x).ok()?;+ let sy = usize::try_from(max_y - min_y).ok()?;+ let width = fft_size(tile.checked_add(sx)?)?;+ let height = fft_size(tile.checked_add(sy)?)?;+ let points = width.checked_mul(height)?;+ if points > MAX_POINTS {+ return Some(false);+ }+ let (ow, oh) = dimensions(area)?;+ let tiles = ow.div_ceil(tile).checked_mul(oh.div_ceil(tile))?;+ let row_tiles = ow.div_ceil(row_tile).checked_mul(oh.div_ceil(row_tile))?;+ let row_workers = workers.min(row_tiles);+ // Before creating any FFT plans, conservatively estimate the same complete+ // working-set budget as the scheduler. Mixed-radix scratch is bounded here+ // by four times the longest side; the real plan supplies its exact size.+ let source = tile.checked_add(sx)?.checked_mul(tile.checked_add(sy)?)?.checked_mul(channels)?.checked_mul(4)?;+ let result = tile.checked_mul(tile)?.checked_mul(channels)?;+ let scratch = width.max(height).checked_mul(4)?;+ let worker =+ points.checked_mul(2)?.checked_add(scratch)?.checked_mul(16)?.checked_add(source)?.checked_add(result.checked_mul(8)?)?.max(source.checked_mul(2)?);+ let resident = points+ .checked_mul(16)?+ .checked_add(width.checked_add(height)?.checked_mul(256)?)?+ .checked_add(taps.capacity().checked_mul(std::mem::size_of::<Tap>())?)?;+ let metadata = tiles.checked_mul(std::mem::size_of::<(Rect, Rect)>())?;+ let available = (512usize << 20).checked_sub(resident)?.checked_sub(metadata)?;+ let memory_workers = available.checked_div(worker.checked_add(result.checked_mul(4)?)?)?;+ let fft_workers = workers.min(memory_workers).min(tiles);+ // A few large diagonal transforms can lose to well-parallelized rows.+ // Admit them only when their task count gives a clear parallelism advantage.+ let parallel = fft_workers >= row_workers.checked_mul(2)? || (fft_workers >= 4 && fft_workers.checked_mul(2)? >= row_workers);+ let transform_work = points.checked_mul((width.ilog2() + height.ilog2()) as usize)?.checked_mul(tiles)?;+ let row_work = ow.checked_mul(oh)?.checked_mul(taps.len())?;+ Some(parallel && transform_work < row_work)+}++/// Immutable FFT plans and kernel spectrum, shared by every tile of one apply.+pub(super) struct Plan {+ distance: f32,+ width: usize,+ height: usize,+ tile_width: usize,+ tile_height: usize,+ min_x: i32,+ max_x: i32,+ min_y: i32,+ max_y: i32,+ kernel: Vec<Number>,+ taps: Vec<Tap>,+ row_forward: Arc<dyn Fft<f64>>,+ col_forward: Arc<dyn Fft<f64>>,+ row_inverse: Arc<dyn Fft<f64>>,+ col_inverse: Arc<dyn Fft<f64>>,+ scratch_len: usize,+}++impl Plan {+ pub(super) fn new_with(angle: f32, distance: f32, tile: usize, ctl: &Interrupt) -> Option<Self> {+ Self::build(angle, distance, tile, tile, None, ctl)+ }++ fn build(angle: f32, distance: f32, tile_width: usize, tile_height: usize, clip: Option<(Rect, Rect)>, ctl: &Interrupt) -> Option<Self> {+ if ctl.cancelled() {+ return None;+ }+ if tile_width == 0 || tile_height == 0 || tile_width > 512 || tile_height > 512 {+ return None;+ }+ let taps = taps(angle, distance, clip)?;+ let (mut min_x, mut max_x, mut min_y, mut max_y) = (0, 0, 0, 0);+ for tap in &taps {+ min_x = min_x.min(tap.x);+ max_x = max_x.max(tap.x);+ min_y = min_y.min(tap.y);+ max_y = max_y.max(tap.y);+ }+ let width = fft_size(tile_width.checked_add(usize::try_from(max_x - min_x).ok()?)?)?;+ let height = fft_size(tile_height.checked_add(usize::try_from(max_y - min_y).ok()?)?)?;+ let count = width.checked_mul(height)?;+ if count > MAX_POINTS {+ return None;+ }+ let mut kernel = buffer(count, Number::default())?;+ for tap in &taps {+ // Convolution reverses the displacement of a correlation tap.+ let x = usize::try_from((-tap.x).rem_euclid(i32::try_from(width).ok()?)).ok()?;+ let y = usize::try_from((-tap.y).rem_euclid(i32::try_from(height).ok()?)).ok()?;+ kernel.get_mut(y.checked_mul(width)?.checked_add(x)?)?.re += tap.weight;+ }+ let mut planner = FftPlanner::<f64>::new();+ let row_forward = planner.plan_fft_forward(width);+ let col_forward = planner.plan_fft_forward(height);+ let row_inverse = planner.plan_fft_inverse(width);+ let col_inverse = planner.plan_fft_inverse(height);+ let scratch_len = [+ row_forward.get_inplace_scratch_len(),+ col_forward.get_inplace_scratch_len(),+ row_inverse.get_inplace_scratch_len(),+ col_inverse.get_inplace_scratch_len(),+ ]+ .into_iter()+ .max()+ .unwrap_or(0);+ let mut result = Self {+ distance,+ width,+ height,+ tile_width,+ tile_height,+ min_x,+ max_x,+ min_y,+ max_y,+ kernel: Vec::new(),+ taps,+ row_forward,+ col_forward,+ row_inverse,+ col_inverse,+ scratch_len,+ };+ let mut transposed = buffer(count, Number::default())?;+ let mut scratch = buffer(scratch_len, Number::default())?;+ result.transform(&mut kernel, &mut transposed, &mut scratch, false, ctl)?;+ result.kernel = kernel;+ Some(result)+ }++ pub(super) fn resident_bytes(&self) -> usize {+ // Include a conservative allowance for the FFT plans' twiddle tables.+ self.kernel.len() * std::mem::size_of::<Number>() + self.taps.capacity() * std::mem::size_of::<Tap>() + (self.width + self.height) * 256+ }++ pub(super) fn worker_bytes(&self, channels: usize, tile: usize) -> Option<usize> {+ let source = tile+ .checked_add(usize::try_from(self.max_x - self.min_x).ok()?)?+ .checked_mul(tile.checked_add(usize::try_from(self.max_y - self.min_y).ok()?)?)?+ .checked_mul(channels)?+ .checked_mul(4)?;+ self.kernel+ .len()+ .checked_mul(2)?+ .checked_add(self.scratch_len)?+ .checked_mul(std::mem::size_of::<Number>())?+ .checked_add(source)?+ .checked_add(tile.checked_mul(tile)?.checked_mul(channels)?.checked_mul(8)?)+ }++ pub(super) fn read_rect(&self, out: Rect) -> Option<Rect> {+ Some(Rect::new(out.x0.checked_add(self.min_x)?, out.y0.checked_add(self.min_y)?, out.x1.checked_add(self.max_x)?, out.y1.checked_add(self.max_y)?))+ }++ fn transform(&self, data: &mut [Number], transposed: &mut [Number], scratch: &mut [Number], inverse: bool, ctl: &Interrupt) -> Option<()> {+ let (rows, cols) = if inverse { (&self.row_inverse, &self.col_inverse) } else { (&self.row_forward, &self.col_forward) };+ // Every row has the planned length, and scratch_len covers all four+ // plans. Those invariants satisfy RustFFT's checked process API.+ for (i, row) in data.chunks_exact_mut(self.width).enumerate() {+ if i % 8 == 0 && ctl.cancelled() {+ return None;+ }+ rows.process_with_scratch(row, scratch);+ }+ transpose(data, transposed, self.width, self.height, ctl)?;+ for (i, row) in transposed.chunks_exact_mut(self.height).enumerate() {+ if i % 8 == 0 && ctl.cancelled() {+ return None;+ }+ cols.process_with_scratch(row, scratch);+ }+ transpose(transposed, data, self.height, self.width, ctl)+ }++ pub(super) fn filter(&self, src: &Image, out: Rect, alpha: bool, ctl: &Interrupt) -> Option<Vec<f32>> {+ let (ow, oh) = dimensions(out)?;+ if out.is_empty() {+ return Some(Vec::new());+ }+ let (sw, sh) = dimensions(src.rect)?;+ if !(1..=5).contains(&src.ch)+ || sw.checked_mul(sh)?.checked_mul(src.ch)? != src.data.len()+ || ow > self.tile_width+ || oh > self.tile_height+ || !ordinary_coordinates(src.rect)+ || !ordinary_coordinates(out)+ {+ return None;+ }+ let mut scales = [0.0f64; 5];+ for (i, pixel) in src.data.chunks_exact(src.ch).enumerate() {+ if i % 4096 == 0 && ctl.cancelled() {+ return None;+ }+ if pixel.iter().any(|value| !value.is_finite() || value.abs() > MAX_SAMPLE)+ || (alpha && !pixel.last().is_some_and(|value| (0.0..=1.0).contains(value)))+ {+ return None;+ }+ let a = if alpha { *pixel.last()? } else { 1.0 };+ for (c, &value) in pixel.iter().enumerate() {+ let value = if alpha && c + 1 < src.ch { value * a } else { value };+ let scale = scales.get_mut(c)?;+ *scale = scale.max(f64::from(value.abs()));+ }+ }+ let mut result = buffer(ow.checked_mul(oh)?.checked_mul(src.ch)?, 0.0f64)?;+ let read = self.read_rect(out)?;+ let used = read.intersect(&src.rect);+ if used.is_empty() || scales.iter().take(src.ch).all(|&scale| scale == 0.0) {+ return buffer(result.len(), 0.0f32);+ }+ let count = self.kernel.len();+ let mut data = buffer(count, Number::default())?;+ let mut transposed = buffer(count, Number::default())?;+ let mut scratch = buffer(self.scratch_len, Number::default())?;+ let norm = 1.0 / count as f64;+ for channel in (0..src.ch).step_by(2) {+ if ctl.cancelled() {+ return None;+ }+ data.fill(Number::default());+ for y in used.y0..used.y1 {+ if (y - used.y0) % 8 == 0 && ctl.cancelled() {+ return None;+ }+ let source_start =+ usize::try_from(y - src.rect.y0).ok()?.checked_mul(sw)?.checked_add(usize::try_from(used.x0 - src.rect.x0).ok()?)?.checked_mul(src.ch)?;+ let source_len = usize::try_from(used.x1 - used.x0).ok()?.checked_mul(src.ch)?;+ let row = src.data.get(source_start..source_start.checked_add(source_len)?)?;+ let start = usize::try_from(y - read.y0).ok()?.checked_mul(self.width)?.checked_add(usize::try_from(used.x0 - read.x0).ok()?)?;+ let dst = data.get_mut(start..start.checked_add(source_len / src.ch)?)?;+ for (pixel, dst) in row.chunks_exact(src.ch).zip(dst) {+ let a = if alpha { *pixel.last()? } else { 1.0 };+ // Normalize each channel separately before packing a pair.+ // Otherwise a bright HDR colour's FFT residual could swamp+ // a small alpha channel sharing the imaginary component.+ let sample = |c: usize| -> f64 {+ match (pixel.get(c), scales.get(c)) {+ (Some(&value), Some(&scale)) if scale > 0.0 => f64::from(if alpha && c + 1 < src.ch { value * a } else { value }) / scale,+ _ => 0.0,+ }+ };+ *dst = Number::new(sample(channel), sample(channel + 1));+ }+ }+ self.transform(&mut data, &mut transposed, &mut scratch, false, ctl)?;+ for (value, kernel) in data.iter_mut().zip(&self.kernel) {+ *value *= kernel;+ }+ self.transform(&mut data, &mut transposed, &mut scratch, true, ctl)?;+ let x0 = usize::try_from(-self.min_x).ok()?;+ let y0 = usize::try_from(-self.min_y).ok()?;+ for (y, dst) in result.chunks_exact_mut(ow * src.ch).enumerate() {+ let start = y.checked_add(y0)?.checked_mul(self.width)?.checked_add(x0)?;+ let values = data.get(start..start.checked_add(ow)?)?;+ for (pixel, value) in dst.chunks_exact_mut(src.ch).zip(values) {+ *pixel.get_mut(channel)? = value.re * norm * scales.get(channel)?;+ if let Some(next) = pixel.get_mut(channel + 1) {+ *next = value.im * norm * scales.get(channel + 1)?;+ }+ }+ }+ }+ if alpha {+ // The row kernel accumulates in f32. Recompute very small alpha+ // near its cutoff so a different summation order cannot expose colour.+ let uncertainty = f64::from(self.distance.abs().ceil()) * f64::from(f32::EPSILON) * scales.get(src.ch - 1)?;+ for (i, pixel) in result.chunks_exact_mut(src.ch).enumerate() {+ if i % 16 == 0 && ctl.cancelled() {+ return None;+ }+ let a = pixel.last_mut()?;+ // Valid alpha is nonnegative. Remove transform roundoff at+ // zero to keep fully transparent regions empty.+ if a.abs() < 1e-14 * scales.get(src.ch - 1)? {+ *a = 0.0;+ }+ *a = a.clamp(0.0, 1.0);+ let a = *a;+ // The row kernel's f32 sum can straddle the cutoff at long distances.+ // Keep its branch and straight colour exactly for that narrow+ // range, rather than amplifying a tiny alpha difference.+ if a > 0.0 && (a <= 1.01e-7 + uncertainty || (0.99e-7..=1.01e-7).contains(&(a as f32))) {+ let x = out.x0.checked_add(i32::try_from(i % ow).ok()?)?;+ let y = out.y0.checked_add(i32::try_from(i / ow).ok()?)?;+ let original = sample_row_point(src, x, y, alpha, &self.taps, ctl)?;+ for (dst, value) in pixel.iter_mut().zip(original) {+ *dst = f64::from(value);+ }+ continue;+ }+ for value in pixel.iter_mut().take(src.ch - 1) {+ *value = if a as f32 > 1e-7 { *value / a } else { 0.0 };+ }+ }+ }+ let mut output = buffer(result.len(), 0.0f32)?;+ for (dst, value) in output.iter_mut().zip(result) {+ *dst = value as f32;+ }+ Some(output)+ }+}++#[cfg(test)]+pub(super) fn row_point_for_test(src: &Image, x: i32, y: i32, alpha: bool, angle: f32, distance: f32) -> Option<Vec<f32>> {+ let taps = taps(angle, distance, None)?;+ let result = sample_row_point(src, x, y, alpha, &taps, &Interrupt::NONE)?;+ Some(result.into_iter().take(src.ch).collect())+}++fn transpose(src: &[Number], dst: &mut [Number], width: usize, height: usize, ctl: &Interrupt) -> Option<()> {+ // Blocking keeps both row-major matrices in cache while transposing.+ for by in (0..height).step_by(32) {+ if ctl.cancelled() {+ return None;+ }+ for bx in (0..width).step_by(32) {+ for y in by..(by + 32).min(height) {+ let start = y.checked_mul(width)?.checked_add(bx)?;+ let row = src.get(start..start.checked_add((width - bx).min(32))?)?;+ for (x, value) in row.iter().enumerate() {+ *dst.get_mut((bx + x).checked_mul(height)?.checked_add(y)?)? = *value;+ }+ }+ }+ }+ Some(())+}++/// Small-window oracle tests omit taps whose reads must be transparent. The+/// production plan covers the whole kernel and is reused across output tiles.+#[cfg(test)]+pub(super) fn filter(src: &Image, out: Rect, alpha: bool, angle: f32, distance: f32) -> Option<Vec<f32>> {+ if out.is_empty() {+ return Some(Vec::new());+ }+ let (width, height) = dimensions(out)?;+ Plan::build(angle, distance, width, height, Some((src.rect, out)), &Interrupt::NONE)?.filter(src, out, alpha, &Interrupt::NONE)+}diff --git a/crates/algo/src/blur/motion_fft_tests.rs b/crates/algo/src/blur/motion_fft_tests.rsnew file mode 100644index 000000000..12271d7bc--- /dev/null+++ b/crates/algo/src/blur/motion_fft_tests.rs@@ -0,0 +1,538 @@+//! Numerical and geometric oracles for convolution of the finite motion kernel.+//! The reference independently builds the current upstream merged f32 taps and+//! source premultiplication, then performs convolution and accumulation in f64.++use super::*;+use photocraft_color::{ColorMode, PixelFormat, SampleType};+use photocraft_raster::Surface;+use std::collections::BTreeMap;++fn offsets(angle: f32, distance: f32) -> Vec<(f64, f64)> {+ let distance = distance.abs();+ let steps = distance.ceil() as i32;+ let (sin, cos) = angle.to_radians().sin_cos();+ (0..=steps)+ .map(|i| {+ let t = i as f32 / steps as f32 - 0.5;+ (f64::from(cos * distance * t), -f64::from(sin * distance * t))+ })+ .collect()+}++fn merged_taps(angle: f32, distance: f32) -> BTreeMap<(i32, i32), f32> {+ let offsets = offsets(angle, distance);+ let norm = 1.0 / offsets.len() as f32;+ let mut taps = BTreeMap::new();+ for (x, y) in offsets {+ let (x, y) = (x as f32, y as f32);+ let (x0, y0) = (x.floor(), y.floor());+ let (ax, ay) = (x - x0, y - y0);+ let (x0, y0) = (x0 as i32, y0 as i32);+ for (dx, dy, weight) in [(0, 0, (1.0 - ax) * (1.0 - ay)), (1, 0, ax * (1.0 - ay)), (0, 1, (1.0 - ax) * ay), (1, 1, ax * ay)] {+ if weight > 0.0 {+ *taps.entry((x0 + dx, y0 + dy)).or_insert(0.0) += weight * norm;+ }+ }+ }+ taps+}++fn ideal(src: &Image, out: Rect, alpha: bool, angle: f32, distance: f32) -> Vec<f64> {+ let taps = merged_taps(angle, distance);+ let mut result = Vec::new();+ for y in out.y0..out.y1 {+ for x in out.x0..out.x1 {+ let mut acc = vec![0.0; src.ch];+ for (&(dx, dy), &weight) in &taps {+ let (sx, sy) = (x + dx, y + dy);+ let a = if alpha { src.get(sx, sy, src.ch - 1) } else { 1.0 };+ for (c, value) in acc.iter_mut().enumerate() {+ let sample = src.get(sx, sy, c);+ let premultiplied = if alpha && c + 1 < src.ch { sample * a } else { sample };+ *value += f64::from(premultiplied) * f64::from(weight);+ }+ }+ if alpha {+ let a = acc[src.ch - 1];+ for value in acc.iter_mut().take(src.ch - 1) {+ *value = if a as f32 > 1e-7 { *value / a } else { 0.0 };+ }+ }+ result.extend(acc);+ }+ }+ result+}++fn fft(src: &Image, out: Rect, alpha: bool, angle: f32, distance: f32) -> Vec<f32> {+ super::motion_fft::filter(src, out, alpha, angle, distance).expect("supported finite motion convolution")+}++fn assert_ideal(actual: &[f32], expected: &[f64], case: &str) {+ assert_eq!(actual.len(), expected.len(), "{case}");+ for (i, (&actual, &expected)) in actual.iter().zip(expected).enumerate() {+ let rounded = expected as f32;+ // The public result is f32; allow two rounding units and a small absolute+ // FFT residual at exact zero, rather than claiming sub-ULP precision.+ let tolerance = 1e-9 + 2.0 * f64::from(f32::EPSILON) * f64::from(rounded.abs());+ assert!((f64::from(actual) - f64::from(rounded)).abs() <= tolerance, "{case}, sample {i}: actual={actual}, ideal={expected}, tolerance={tolerance}");+ }+}++fn pattern(rect: Rect, ch: usize, alpha: bool) -> Image {+ let mut data = Vec::new();+ for y in 0..rect.height() as usize {+ for x in 0..rect.width() as usize {+ for c in 0..ch {+ let value = if alpha && c + 1 == ch { [0.0, 0.25, 0.5, 1.0][(x + y * 3) % 4] } else { ((x * 31 + y * 17 + c * 43) % 251) as f32 / 250.0 };+ data.push(value);+ }+ }+ }+ Image { rect, ch, data }+}++#[test]+fn motion_fft_matches_independent_ideal_for_channels_angles_and_distances() {+ let rect = Rect::new(-4, -4, 5, 5);+ let out = Rect::new(-1, -1, 2, 2);+ for ch in 1..=5 {+ for alpha in [false, true] {+ let src = pattern(rect, ch, alpha);+ for (angle, distance) in [(0.0, 64.0), (90.0, 65.5), (30.0, 127.0), (-45.0, -256.0), (89.75, 2000.0), (37.0, 2000.0)] {+ let actual = fft(&src, out, alpha, angle, distance);+ assert_ideal(&actual, &ideal(&src, out, alpha, angle, distance), &format!("ch={ch}, alpha={alpha}, angle={angle}, distance={distance}"));+ }+ }+ }+}++fn impulse_kernel(angle: f32, distance: f32) -> BTreeMap<(i32, i32), f64> {+ merged_taps(angle, distance).into_iter().map(|((x, y), weight)| ((-x, -y), f64::from(weight))).collect()+}++fn moments(samples: impl Iterator<Item = ((i32, i32), f64)>, angle: f32) -> [f64; 5] {+ let angle = f64::from(angle).to_radians();+ let (sin, cos) = angle.sin_cos();+ let mut result = [0.0; 5];+ for ((x, y), weight) in samples {+ let (x, y) = (f64::from(x), f64::from(y));+ result[0] += weight;+ result[1] += x * weight;+ result[2] += y * weight;+ result[3] += (x * sin + y * cos).powi(2) * weight;+ result[4] += (x * cos - y * sin).powi(2) * weight;+ }+ result+}++#[test]+fn motion_fft_impulse_preserves_mass_centroid_and_directional_width() {+ let src = Image { rect: Rect::new(0, 0, 1, 1), ch: 1, data: vec![1.0] };+ for distance in [64.0_f32, 127.0] {+ let reach = (distance / 2.0).ceil() as i32 + 2;+ let out = Rect::new(-reach, -reach, reach + 1, reach + 1);+ for angle in [0.0, 30.0, 45.0, 89.75] {+ let expected = impulse_kernel(angle, distance);+ let actual = fft(&src, out, false, angle, distance);+ let width = out.width() as usize;+ let samples = actual.iter().enumerate().map(|(i, &v)| ((out.x0 + (i % width) as i32, out.y0 + (i / width) as i32), f64::from(v)));+ let actual_moments = moments(samples, angle);+ let expected_moments = moments(expected.iter().map(|(&p, &v)| (p, v)), angle);+ assert!((actual_moments[0] - 1.0).abs() <= 3e-6, "angle={angle}, distance={distance}, mass={}", actual_moments[0]);+ for i in 1..=3 {+ assert!(+ (actual_moments[i] - expected_moments[i]).abs() <= 2e-5,+ "angle={angle}, distance={distance}, moment={i}, actual={}, expected={}",+ actual_moments[i],+ expected_moments[i]+ );+ }+ assert!((actual_moments[4] - expected_moments[4]).abs() <= 5e-4, "along-motion variance changed: angle={angle}, distance={distance}");+ let expected_pixels: Vec<f64> =+ (out.y0..out.y1).flat_map(|y| (out.x0..out.x1).map(move |x| (x, y))).map(|p| expected.get(&p).copied().unwrap_or(0.0)).collect();+ assert_ideal(&actual, &expected_pixels, &format!("impulse angle={angle}, distance={distance}"));+ }+ }+}++#[test]+fn motion_fft_sharp_stripes_match_uniform_streak_without_cross_direction_softening() {+ let rect = Rect::new(-80, -80, 81, 81);+ let out = Rect::new(-2, -2, 3, 3);+ for angle in [0.0_f32, 30.0, 45.0] {+ let (sin, cos) = f64::from(angle).to_radians().sin_cos();+ for perpendicular in [false, true] {+ for frequency in [0.125, 0.375] {+ let mut src = Image::new(rect, 1);+ for (i, value) in src.data.iter_mut().enumerate() {+ let (x, y) = (rect.x0 + (i % rect.width() as usize) as i32, rect.y0 + (i / rect.width() as usize) as i32);+ let coordinate = if perpendicular { f64::from(x) * sin + f64::from(y) * cos } else { f64::from(x) * cos - f64::from(y) * sin };+ *value = (0.5 + 0.5 * (std::f64::consts::TAU * frequency * coordinate).cos()) as f32;+ }+ let distance = if perpendicular { 127.0 } else { 64.0 };+ assert_ideal(+ &fft(&src, out, false, angle, distance),+ &ideal(&src, out, false, angle, distance),+ &format!("stripe angle={angle}, perpendicular={perpendicular}, frequency={frequency}"),+ );+ }+ }+ }+}++#[test]+fn motion_fft_premultiplied_alpha_hidden_colour_hdr_and_cutoff_are_preserved() {+ let rect = Rect::new(-5, -5, 6, 6);+ let out = Rect::new(-1, -1, 2, 2);+ let mut src = pattern(rect, 4, true);+ let mut hidden = src.clone();+ for (pixel, changed) in src.data.as_chunks_mut::<4>().0.iter_mut().zip(hidden.data.as_chunks_mut::<4>().0.iter_mut()) {+ for value in pixel.iter_mut().take(3) {+ *value = *value * 32.0 - 8.0;+ }+ changed.copy_from_slice(pixel);+ if pixel[3] == 0.0 {+ changed[..3].copy_from_slice(&[1e6, 7e5, 9e5]);+ }+ }+ let actual = fft(&src, out, true, 38.0, 67.75);+ assert_ideal(&actual, &ideal(&src, out, true, 38.0, 67.75), "HDR premultiplied image");+ assert_ideal(&fft(&hidden, out, true, 38.0, 67.75), &actual.iter().map(|&v| f64::from(v)).collect::<Vec<_>>(), "hidden transparent colours do not bleed");++ let rect = Rect::new(-40, -40, 41, 41);+ for alpha in [0.0_f32, 1e-8, 1e-7, f32::from_bits(1e-7_f32.to_bits() + 1), 0.25, 1.0] {+ let src = Image { rect, ch: 4, data: [0.25, 0.5, 0.75, alpha].repeat((rect.width() * rect.height()) as usize) };+ if (0.99e-7..=1.01e-7).contains(&alpha) {+ // The upstream row f32 sum can move alpha across its discontinuous+ // colour cutoff. Near that boundary, retain the upstream row kernel.+ let actual = fft(&src, out, true, 30.0, 64.0);+ let ctx = Ctx { bounds: rect, mode: ColorMode::Rgb, alpha: true };+ let expected = motion_rows(&src, out, &ctx, 30.0, 64.0);+ assert_eq!(actual, expected, "near-cutoff alpha={alpha}");+ continue;+ }+ let actual = fft(&src, out, true, 30.0, 64.0);+ assert_ideal(&actual, &ideal(&src, out, true, 30.0, 64.0), &format!("constant alpha={alpha}"));+ if alpha <= 1e-7 {+ assert!(actual.as_chunks::<4>().0.iter().all(|p| p[..3].iter().all(|&v| v == 0.0)), "alpha cutoff={alpha}");+ }+ }+}++#[test]+fn motion_fft_upstream_summation_error_is_bounded_in_supported_coordinates() {+ for origin in [-16_384, 0, 16_375] {+ let rect = Rect::new(origin, origin, origin + 9, origin + 9);+ let out = Rect::new(origin + 2, origin + 2, origin + 5, origin + 5);+ for alpha in [false, true] {+ let src = pattern(rect, 4, alpha);+ let ctx = Ctx { bounds: rect, mode: ColorMode::Rgb, alpha };+ for (angle, distance) in [(30.0, 64.0), (89.75, 127.0)] {+ let actual = fft(&src, out, alpha, angle, distance);+ let expected = motion_rows(&src, out, &ctx, angle, distance);+ for (&a, &b) in actual.iter().zip(&expected) {+ assert!((a - b).abs() <= 1e-3, "origin={origin}, alpha={alpha}, angle={angle}, distance={distance}, actual={a}, original={b}");+ }+ }+ }+ }+}++#[test]+fn motion_fft_large_hdr_colours_do_not_change_small_alpha_or_its_cutoff() {+ let rect = Rect::new(-40, -40, 41, 41);+ let out = Rect::new(-1, -1, 2, 2);+ for alpha in [1e-7_f32, f32::from_bits(1e-7_f32.to_bits() + 1), 0.25] {+ let src = Image { rect, ch: 4, data: [1e10, -5e9, 9e9, alpha].repeat((rect.width() * rect.height()) as usize) };+ if (0.99e-7..=1.01e-7).contains(&alpha) {+ let actual = fft(&src, out, true, 33.0, 64.0);+ let ctx = Ctx { bounds: rect, mode: ColorMode::Rgb, alpha: true };+ assert_eq!(actual, motion_rows(&src, out, &ctx, 33.0, 64.0), "near-cutoff HDR alpha={alpha}");+ continue;+ }+ let actual = fft(&src, out, true, 33.0, 64.0);+ assert_ideal(&actual, &ideal(&src, out, true, 33.0, 64.0), &format!("large HDR, alpha={alpha}"));+ if alpha <= 1e-7 {+ assert!(actual.as_chunks::<4>().0.iter().all(|p| p[..3].iter().all(|&v| v == 0.0)), "HDR changed alpha cutoff");+ }+ }+}++#[test]+fn motion_fft_pipeline_supports_depths_models_edges_selections_and_tile_seams() {+ let rect = Rect::new(-6, 3, 7, 16);+ let mut selection = Surface::new(PixelFormat::GRAY8);+ let coverage: Vec<f32> = (0..rect.width() * rect.height()).map(|i| [0.0, 0.25, 0.5, 1.0][i as usize % 4]).collect();+ selection.write_region(rect, &coverage);+ for mode in [ColorMode::Grayscale, ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab] {+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {+ for alpha in [false, true] {+ let mut source = Surface::new(PixelFormat::new(mode, depth, alpha));+ let image = pattern(rect, source.channels(), alpha);+ source.write_region(rect, &image.data);+ let params = FilterParams::MotionBlur { angle: 31.0, distance: 73.25 };+ let crate::Halo::Radius(reach) = params.halo() else { panic!("local motion halo") };+ for extent in [None, Some(rect)] {+ let src =+ if extent.is_some() { Image::read_clamped(&source, rect.inflate(reach), rect) } else { Image::read(&source, rect.inflate(reach)) };+ let filtered = fft(&src, rect, alpha, 31.0, 73.25);+ for mask in [None, Some(&selection)] {+ let mut expected_data = filtered.clone();+ if let Some(mask) = mask {+ crate::mix_selection(&mut expected_data, rect, mask, &src);+ }+ let mut expected = source.clone();+ expected.write_region(rect, &expected_data);+ let expected = expected.read_region(rect.inflate(2));+ let tolerance = match depth {+ SampleType::U8 => 1.0 / 255.0 + 1e-7,+ SampleType::U16 => 1.0 / 65_535.0 + 1e-7,+ SampleType::F32 => 1e-6,+ };+ for tile in [5, 17, 256] {+ let actual = crate::apply_tiled(&source, ¶ms, rect, rect, mask, tile, extent).read_region(rect.inflate(2));+ assert_eq!(actual.len(), expected.len());+ for (i, (&a, &b)) in actual.iter().zip(&expected).enumerate() {+ assert!(+ (a - b).abs() <= tolerance,+ "mode={mode:?}, depth={depth:?}, alpha={alpha}, extent={extent:?}, selection={}, tile={tile}, sample={i}, actual={a}, expected={b}",+ mask.is_some()+ );+ }+ }+ }+ }+ }+ }+ }+}++#[test]+fn motion_fft_rejects_unsupported_values_and_extreme_geometry() {+ let rect = Rect::new(-2, -2, 3, 3);+ let src = pattern(rect, 4, true);+ for (angle, distance) in [(f32::NAN, 64.0), (f32::INFINITY, 64.0), (30.0, f32::NAN), (30.0, f32::INFINITY), (30.0, 2001.0)] {+ assert!(super::motion_fft::filter(&src, rect, true, angle, distance).is_none());+ }+ for alpha in [-0.25, 1.25, f32::NAN, f32::INFINITY] {+ let mut image = src.clone();+ image.data[3] = alpha;+ assert!(super::motion_fft::filter(&image, rect, true, 30.0, 64.0).is_none(), "alpha={alpha}");+ }+ for sample in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 2e10] {+ let mut image = src.clone();+ image.data[0] = sample;+ assert!(super::motion_fft::filter(&image, rect, true, 30.0, 64.0).is_none(), "sample={sample}");+ }+ let malformed = Image { rect, ch: 4, data: vec![0.0] };+ assert!(super::motion_fft::filter(&malformed, rect, true, 30.0, 64.0).is_none());+ for origin in [16_385, i32::MIN] {+ let rect = Rect::new(origin, 0, origin + 5, 5);+ let image = Image { rect, ch: 1, data: vec![0.0; 25] };+ assert!(super::motion_fft::filter(&image, rect, false, 30.0, 64.0).is_none());+ }+}++#[test]+fn motion_fft_production_crosses_real_tile_seams_and_leaves_other_pixels_untouched() {+ let extent = Rect::new(-180, -145, 173, 144);+ let area = Rect::new(-170, -135, 163, 134);+ let check = extent.inflate(8);+ let params = FilterParams::MotionBlur { angle: 31.0, distance: 73.25 };+ let crate::Halo::Radius(reach) = params.halo() else { panic!("local motion halo") };+ let mut selection = Surface::new(PixelFormat::GRAY8);+ let mut coverage = Vec::new();+ for y in extent.y0..extent.y1 {+ for x in extent.x0..extent.x1 {+ let inside = Rect::new(-51, -31, 53, 34).contains(x, y);+ coverage.push(if inside { [0.0, 0.25, 0.5, 0.75, 1.0][(x + y).rem_euclid(5) as usize] } else { 0.0 });+ }+ }+ selection.write_region(extent, &coverage);+ for depth in [SampleType::U16, SampleType::F32] {+ let mut source = Surface::new(PixelFormat::new(ColorMode::Rgb, depth, true));+ source.write_region(extent, &pattern(extent, 4, true).data);+ source.fill_rect(Rect::new(-86, -61, -82, -57), &[0.125, 0.25, 0.5, 1.0]);+ let original = Image::read(&source, check);+ for clamp in [false, true] {+ let src = if clamp { Image::read_clamped(&source, area.inflate(reach), extent) } else { Image::read(&source, area.inflate(reach)) };+ let filtered = fft(&src, area, true, 31.0, 73.25);+ for mask in [None, Some(&selection)] {+ let mut expected = source.clone();+ let mut data = filtered.clone();+ if let Some(mask) = mask {+ crate::mix_selection(&mut data, area, mask, &src);+ }+ expected.write_region(area, &data);+ let expected = Image::read(&expected, check);+ let tolerance = if depth == SampleType::U16 { 1.0 / 65_535.0 + 1e-7 } else { 1e-6 };+ for tile in [64, 128, 256] {+ let result = super::motion_apply::apply_for_bench(&source, ¶ms, area, extent, mask, clamp.then_some(extent), tile, &Interrupt::NONE)+ .expect("the FFT specialization must actually cross these seams")+ .expect("not cancelled");+ let result = Image::read(&result, check);+ for y in check.y0..check.y1 {+ for x in check.x0..check.x1 {+ for c in 0..4 {+ let actual = result.get(x, y, c);+ if !area.contains(x, y) {+ assert_eq!(+ actual.to_bits(),+ original.get(x, y, c).to_bits(),+ "write outside area: depth={depth:?}, tile={tile}, pixel=({x},{y}), channel={c}"+ );+ } else {+ let target = expected.get(x, y, c);+ assert!(+ (actual - target).abs() <= tolerance,+ "seam: depth={depth:?}, clamp={clamp}, selection={}, tile={tile}, pixel=({x},{y}), channel={c}, actual={actual}, expected={target}",+ mask.is_some()+ );+ }+ }+ }+ }+ }+ }+ }+ }+}++#[test]+fn motion_fft_production_unsupported_inputs_keep_upstream_row_fallback() {+ let params = FilterParams::MotionBlur { angle: 31.0, distance: 64.0 };+ let crate::Halo::Radius(reach) = params.halo() else { panic!("local motion halo") };+ for case in 0..5 {+ let origin = if case == 4 { 20_000 } else { -64 };+ let rect = Rect::new(origin, -32, origin + 128, 32);+ let mut image = pattern(rect, 4, true);+ let middle = (32 * rect.width() as usize + 64) * 4;+ match case {+ 0 => image.data[middle + 3] = -0.25,+ 1 => image.data[middle + 3] = 1.25,+ 2 => image.data[middle] = f32::NAN,+ 3 => image.data[middle] = f32::INFINITY,+ _ => {}+ }+ let mut source = Surface::new(PixelFormat::RGBA32F);+ source.write_region(rect, &image.data);+ let src = Image::read(&source, rect.inflate(reach));+ let ctx = Ctx { bounds: rect, mode: ColorMode::Rgb, alpha: true };+ let mut expected = source.clone();+ expected.write_region(rect, &motion_rows(&src, rect, &ctx, 31.0, 64.0));+ let expected = expected.read_region(rect);+ assert!(+ super::motion_apply::apply_for_bench(&source, ¶ms, rect, rect, None, None, 64, &Interrupt::NONE).is_none(),+ "unsupported FFT input case={case}"+ );+ let actual = crate::apply_tiled(&source, ¶ms, rect, rect, None, 64, None).read_region(rect);+ assert_eq!(actual.len(), expected.len());+ for (i, (&actual, &expected)) in actual.iter().zip(&expected).enumerate() {+ assert!(+ actual.to_bits() == expected.to_bits() || (actual.is_nan() && expected.is_nan()),+ "fallback case={case}, sample={i}, actual={actual}, expected={expected}"+ );+ }+ }+}++#[test]+fn motion_fft_production_near_alpha_cutoff_retains_upstream_row_summation() {+ let extent = Rect::new(-64, -64, 65, 65);+ let area = Rect::new(-32, -32, 32, 32);+ for alpha in [1e-7_f32, 0.999e-7, 1.001e-7] {+ let mut source = Surface::new(PixelFormat::RGBA32F);+ source.fill_rect(extent, &[0.25, 0.5, 0.75, alpha]);+ for distance in [200.0_f32, 500.0] {+ let params = FilterParams::MotionBlur { angle: 0.0, distance };+ let crate::Halo::Radius(reach) = params.halo() else { panic!("local motion halo") };+ let src = Image::read_clamped(&source, area.inflate(reach), extent);+ let ctx = Ctx { bounds: extent, mode: ColorMode::Rgb, alpha: true };+ let mut expected = source.clone();+ expected.write_region(area, &motion_rows(&src, area, &ctx, 0.0, distance));+ let expected = expected.to_interleaved(area);+ // FFT uses a more accurate sum, but accuracy alone cannot preserve+ // this branch: the upstream rounded alpha chooses whether colour+ // survives. Only pixels near 1e-7 use the upstream row kernel.+ let actual = super::motion_apply::apply_for_bench(&source, ¶ms, area, extent, None, Some(extent), 64, &Interrupt::NONE)+ .expect("the FFT path must exercise its low-alpha fallback")+ .expect("not cancelled");+ assert_eq!(actual.to_interleaved(area), expected, "near-cutoff alpha={alpha}, distance={distance}");+ }+ }+}++#[test]+fn motion_fft_low_alpha_at_large_coordinates_retains_upstream_row_cutoff() {+ let rect = Rect::new(15_950, 15_998, 16_080, 16_002);+ let out = Rect::new(16_000, 16_000, 16_003, 16_001);+ let mut src = Image::new(rect, 4);+ for (i, pixel) in src.data.as_chunks_mut::<4>().0.iter_mut().enumerate() {+ let y = rect.y0 + (i / rect.width() as usize) as i32;+ if y == 15_999 {+ pixel.copy_from_slice(&[0.25, 0.5, 0.75, 1.0]);+ }+ }+ let ctx = Ctx { bounds: rect, mode: ColorMode::Rgb, alpha: true };+ let expected = motion_rows(&src, out, &ctx, 0.0005, 64.0);+ let actual = fft(&src, out, true, 0.0005, 64.0);+ // The relative upstream kernel does not inherit absolute-coordinate phase+ // rounding. Away from its true alpha cutoff, compare numerical accuracy.+ assert_ideal(&actual, &expected.into_iter().map(f64::from).collect::<Vec<_>>(), "positive low alpha at translated coordinates");+}++#[test]+fn motion_fft_scalar_row_point_matches_upstream_for_layouts_hdr_and_cutoff() {+ let rect = Rect::new(-5, -4, 6, 5);+ let out = Rect::new(-1, 0, 2, 1);+ for ch in 1..=5 {+ for alpha in [false, true] {+ let mut src = pattern(rect, ch, alpha);+ for pixel in src.data.chunks_exact_mut(ch) {+ for value in pixel.iter_mut().take(ch - usize::from(alpha)) {+ *value = *value * 32.0 - 8.0;+ }+ }+ let ctx = Ctx { bounds: rect, mode: ColorMode::Multichannel, alpha };+ for (angle, distance) in [(30.0, 64.0), (0.0, 256.0), (43.0, 1000.0)] {+ // Read the reference's square window once for all three points.+ // The scalar path itself never allocates that window.+ let expected = motion_rows(&src, out, &ctx, angle, distance);+ for (i, x) in (out.x0..out.x1).enumerate() {+ let actual = super::motion_fft::row_point_for_test(&src, x, out.y0, alpha, angle, distance).expect("valid scalar row point");+ assert_eq!(actual, expected[i * ch..(i + 1) * ch], "ch={ch}, alpha={alpha}, angle={angle}, distance={distance}, x={x}");+ }+ }+ }+ }++ let rect = Rect::new(-34, -34, 35, 35);+ for ch in 1..=5 {+ for alpha in [1e-7_f32, f32::from_bits(1e-7_f32.to_bits() + 1), 0.999e-7, 1.001e-7] {+ let mut pixel = vec![1e6; ch];+ pixel[ch - 1] = alpha;+ let src = Image { rect, ch, data: pixel.repeat((rect.width() * rect.height()) as usize) };+ let ctx = Ctx { bounds: rect, mode: ColorMode::Multichannel, alpha: true };+ let expected = motion_rows(&src, Rect::new(0, 0, 1, 1), &ctx, 31.0, 64.0);+ let actual = super::motion_fft::row_point_for_test(&src, 0, 0, true, 31.0, 64.0).expect("valid cutoff scalar point");+ assert_eq!(actual, expected, "cutoff ch={ch}, alpha={alpha}");+ }+ }+}++#[test]+fn motion_fft_output_outside_extent_retains_upstream_boundary_reads() {+ let extent = Rect::new(0, 0, 128, 128);+ let area = Rect::new(0, 200, 64, 264);+ let mut source = Surface::new(PixelFormat::RGBA32F);+ source.fill_rect(extent, &[0.25, 0.5, 0.75, 1.0]);+ let params = FilterParams::MotionBlur { angle: 0.0, distance: 256.0 };+ assert!(super::motion_apply::apply(&source, ¶ms, area, extent, None, Some(extent), 64, &Interrupt::NONE).is_none());+ let crate::Halo::Radius(reach) = params.halo() else { panic!("local motion halo") };+ let src = Image::read_clamped(&source, area.inflate(reach), extent);+ let ctx = Ctx { bounds: extent, mode: ColorMode::Rgb, alpha: true };+ let expected = motion_rows(&src, area, &ctx, 0.0, 256.0);+ let actual = crate::apply_tiled(&source, ¶ms, area, extent, None, 64, Some(extent));+ assert_eq!(actual.read_region(area), expected);+}diff --git a/crates/algo/src/blur/motion_tests.rs b/crates/algo/src/blur/motion_tests.rsnew file mode 100644index 000000000..822cbb755--- /dev/null+++ b/crates/algo/src/blur/motion_tests.rs@@ -0,0 +1,128 @@+use super::*;+use photocraft_color::{ColorMode, PixelFormat, SampleType};+use photocraft_raster::Surface;++fn assert_samples_equal(actual: &[f32], expected: &[f32], case: &str) {+ assert_eq!(actual.len(), expected.len(), "{case}");+ for (i, (&a, &b)) in actual.iter().zip(expected).enumerate() {+ assert!(a.to_bits() == b.to_bits() || (a.is_nan() && b.is_nan()), "{case}, sample {i}: {a:?} != {b:?}");+ }+}++fn patterned_image(rect: Rect, ch: usize, alpha: bool) -> Image {+ let mut data = Vec::new();+ for y in 0..rect.height() as usize {+ for x in 0..rect.width() as usize {+ for c in 0..ch {+ let k = x * 37 + y * 13 + c * 29;+ let value = if alpha && c + 1 == ch { [0.0, 1.0, 0.125, 0.875][k % 4] } else { (k % 256) as f32 / 255.0 };+ data.push(value);+ }+ }+ }+ Image { rect, ch, data }+}++#[test]+fn motion_identity_preserves_signed_zero_and_transparent_colours() {+ let rect = Rect::new(-1, -1, 2, 2);+ let src = Image { rect, ch: 4, data: [-0.0, 8.0, -2.0, 0.0].repeat(9) };+ let ctx = Ctx { bounds: rect, mode: ColorMode::Rgb, alpha: true };+ for distance in [-0.49, -0.0, 0.0, 0.49] {+ assert_samples_equal(&motion(&src, rect, &ctx, 17.0, distance), &src.data, &format!("distance={distance}"));+ }+ let blurred = motion(&src, rect, &ctx, 31.0, 2.0);+ assert!(blurred.iter().all(|value| *value == 0.0));+}++#[test]+fn motion_default_kernel_retains_current_upstream_rows() {+ // PR 902 deliberately merges bilinear taps and changes summation order.+ // The default kernel follows that implementation at every distance.+ for (x0, y0) in [(0, 0), (-17, 31), (16_000, -16_000), (1 << 20, -(1 << 20))] {+ let rect = Rect::new(x0, y0, x0 + 11, y0 + 9);+ for ch in [1, 2, 3, 4, 5, 6] {+ for alpha in [false, true] {+ let src = patterned_image(rect, ch, alpha);+ let ctx = Ctx { bounds: rect, mode: ColorMode::Multichannel, alpha };+ let out = Rect::new(x0 + 2, y0 + 1, x0 + 7, y0 + 6);+ for (angle, distance) in [(0.0, 1.0), (90.0, 2.5), (30.0, 10.0), (-45.0, -63.5), (89.75, 64.0), (37.0, 127.0)] {+ assert_samples_equal(+ &motion(&src, out, &ctx, angle, distance),+ &motion_rows(&src, out, &ctx, angle, distance),+ &format!("upstream rows: origin=({x0},{y0}), ch={ch}, alpha={alpha}, angle={angle}, distance={distance}"),+ );+ }+ }+ }+ }+}++fn row_surface(surface: &Surface, params: &FilterParams, area: Rect, bounds: Rect, selection: Option<&Surface>, extent: Option<Rect>) -> Surface {+ let FilterParams::MotionBlur { angle, distance } = params else { panic!("motion-only oracle") };+ let crate::Halo::Radius(reach) = params.halo() else { panic!("motion uses a local halo") };+ let src = match extent {+ Some(e) => Image::read_clamped(surface, area.inflate(reach), e),+ None => Image::read(surface, area.inflate(reach)),+ };+ let format = surface.format();+ let ctx = Ctx { bounds, mode: format.mode, alpha: format.alpha };+ let mut data = motion_rows(&src, area, &ctx, *angle, *distance);+ if let Some(selection) = selection {+ crate::mix_selection(&mut data, area, selection, &src);+ }+ let mut result = surface.clone();+ result.write_region(area, &data);+ result.prune();+ result+}++#[test]+fn motion_pipeline_matches_upstream_rows_across_formats_edges_selections_and_tiles() {+ let rect = Rect::new(-13, 9, 16, 30);+ let mut selection = Surface::new(PixelFormat::GRAY8);+ let mut coverage = Vec::new();+ for y in 0..rect.height() as usize {+ for x in 0..rect.width() as usize {+ coverage.push([0.0, 0.25, 0.5, 0.75, 1.0][(x + y * 3) % 5]);+ }+ }+ selection.write_region(rect, &coverage);+ for mode in [ColorMode::Grayscale, ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab] {+ for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {+ for alpha in [false, true] {+ let format = PixelFormat::new(mode, sample, alpha);+ let mut source = Surface::new(format);+ let mut image = patterned_image(rect, source.channels(), alpha);+ if sample == SampleType::F32 {+ for pixel in image.data.chunks_exact_mut(image.ch) {+ for value in pixel.iter_mut().take(image.ch - usize::from(alpha)) {+ *value = *value * 4.0 - 1.0;+ }+ }+ }+ source.write_region(rect, &image.data);+ for params in [+ FilterParams::MotionBlur { angle: 0.0, distance: 2.5 },+ FilterParams::MotionBlur { angle: 32.0, distance: 11.0 },+ FilterParams::MotionBlur { angle: -90.0, distance: -7.25 },+ ] {+ for extent in [None, Some(rect)] {+ for mask in [None, Some(&selection)] {+ let expected = row_surface(&source, ¶ms, rect, rect, mask, extent);+ for tile in [5, 17, 256] {+ let actual = crate::apply_tiled(&source, ¶ms, rect, rect, mask, tile, extent);+ assert_eq!(+ actual.to_interleaved(rect.inflate(2)),+ expected.to_interleaved(rect.inflate(2)),+ "mode={mode:?}, sample={sample:?}, alpha={alpha}, params={params:?}, extent={extent:?}, selection={}, tile={tile}",+ mask.is_some()+ );+ }+ }+ }+ }+ }+ }+ }+}diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rsindex 7ef299213..18d8785e1 100644--- a/crates/algo/src/lib.rs+++ b/crates/algo/src/lib.rs@@ -968,6 +968,9 @@ pub fn apply_tiled_with(if let Some(boxes) = blur::box_widths(params) {return apply_box_blur(out, surface, area, extent, selection, &boxes, ctl);}+ if let Some(result) = blur::motion_apply::apply(surface, params, area, bounds, selection, extent, tile, ctl) {+ return result;+ }let fmt = surface.format();let ctx = Ctx { bounds, mode: fmt.mode, alpha: fmt.alpha };let halo = params.halo_for(bounds);diff --git a/docs/roadmap.md b/docs/roadmap.mdindex 8611cf22e..7fb0555ed 100644--- a/docs/roadmap.md+++ b/docs/roadmap.md@@ -82,6 +82,19 @@ Confidence: moderate — the next users of 0.2.x will move these numbers either| Platforms | macOS (notarized), Windows, Linux (AppImage/deb/rpm/Flatpak bundle), web | medium-high | Flathub later (#173); Windows signing material pending. || Localisation | 2026-10-07: 10 UI languages; menu, `tl!`, blend mode, preference and brush-section coverage enforced by tests; live switching and scoped Preferences previews | medium | Engine errors/status messages still partly English; CJK web fonts, browser-locale detection, and RTL remain open. |+2026-10-08: Motion Blur adds adaptive FFT convolution for wide streaks while retaining the+row kernel merged in [#902](https://github.com/storytold/photocraft/pull/902) for shorter+streaks and unsupported cases. Native release medians of three paired runs on an Intel+i7-9750H with 12 Rayon workers, synthetic RGBA8 at 30° / distance 1000: 24 MP+22.594 → 9.785 s (2.31×), and 1.5 MP+2.455 → 0.592 s (4.15×).+Full-image comparisons differ by at most one U8 code level; distance 64/256 retain the+byte-identical row output. These measure decode/halo/filter/write/prune, excluding UI proxy+creation, compositing and upload; the UI remains synchronous. FFT work is scheduled within+a conservative 512 MiB working-set estimate, excluding stored Surface tiles and row fallback+memory. The crossover is a heuristic; images dominated by near-cutoff alpha can need extra+scalar work. These measurements do not establish Photoshop filter parity.+2026-10-08: the tools update above is checked against the current toolbar groups in[`panels.rs`](../crates/ui-egui/src/panels.rs), the Pencil and tool-cycle tests in[`pencil_tests.rs`](../crates/ui-egui/src/pencil_tests.rs), Patch's live-preview test in