From ce94ac430df12d301308d4068b5fda4d7f948bd9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 13 Oct 2026 14:24:55 +0000 Subject: [PATCH 1/6] test(algo): pin seam carving's tall-image output; bench_seam timing example The reduced-height seam search for tall images (P28's path) had no bit-exact test: output_bits_are_pinned and carver_matches_reference only cover images under 2048 rows. Pin five proxy-path carves (widths and, through the transposed pass, heights; with and without protection) from the current code, so the speed work that follows can't change which seams are chosen. bench_seam times the carver alone on a synthetic 24 MP photo (P28's width change, its height change) and two exact-path sizes, and prints a hash of each output. Before (4 cores, release): 2279 ms, 4872 ms, 1542 ms and 658 ms p50. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LELc5BQzgV5dA7dxdMejkK --- crates/algo/examples/bench_seam.rs | 78 ++++++++++++++++++++++++++++++ crates/algo/src/seam.rs | 29 +++++++++++ 2 files changed, 107 insertions(+) create mode 100644 crates/algo/examples/bench_seam.rs diff --git a/crates/algo/examples/bench_seam.rs b/crates/algo/examples/bench_seam.rs new file mode 100644 index 00000000000..e427a6b270c --- /dev/null +++ b/crates/algo/examples/bench_seam.rs @@ -0,0 +1,78 @@ +//! Timing of Content-Aware Scale's seam carving alone (no document plumbing), on a synthetic +//! photo-like RGBA image: perf scenario P28's 24 MP width change (#211), the same image's height +//! (the transposed pass) and two images short enough for the exact full-resolution seam search. +//! Prints an FNV-1a hash of each output's bits, so a speed-up can be checked to choose exactly the +//! same seams. +//! `cargo run --release -p photocraft-algo --example bench_seam [reps] [case filter]` +use std::time::Instant; + +use photocraft_algo::seam::carve; + +/// Smooth gradients, a few hard-edged shapes and fine noise: enough structure that seams are +/// steered by content, as in a photo. +fn photo(w: usize, h: usize) -> Vec { + let mut seed = 0x9e37_79b9u32; + let mut noise = move || { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + (seed % 1000) as f32 / 1000.0 - 0.5 + }; + let mut img = Vec::with_capacity(w * h * 4); + for y in 0..h { + for x in 0..w { + let (u, v) = (x as f32 / w as f32, y as f32 / h as f32); + let sky = 0.35 + 0.4 * v; + let disc = ((u - 0.3).powi(2) + (v - 0.55).powi(2)) < 0.02; + let bar = (0.62..0.66).contains(&u) && v > 0.3; + let hill = v > 0.7 + 0.08 * (u * 11.0).sin(); + let (r, g, b) = if disc { + (0.85, 0.3, 0.2) + } else if bar { + (0.1, 0.1, 0.12) + } else if hill { + (0.2, 0.45 + 0.1 * (u * 40.0).sin(), 0.15) + } else { + (sky * 0.6, sky * 0.8, sky) + }; + let n = noise() * 0.02; + img.extend_from_slice(&[r + n, g + n, b + n, 1.0]); + } + } + img +} + +fn fnv(v: &[f32]) -> u64 { + v.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, f| (h ^ u64::from(f.to_bits())).wrapping_mul(0x0100_0000_01b3)) +} + +fn main() { + let args: Vec = std::env::args().collect(); + let reps = args.get(1).and_then(|s| s.parse::().ok()).unwrap_or(1).clamp(1, 20); + let only = args.get(2).cloned(); + // (name, w, h, new w, new h) + let cases = [ + ("24 MP to 90 % width (P28, proxy rows)", 6000, 4000, 5400, 4000), + ("24 MP to 90 % height (transposed, proxy rows)", 6000, 4000, 6000, 3600), + ("5.4 MP to 90 % width (exact)", 3000, 1800, 2700, 1800), + ("1.5 MP to 70 % width (exact)", 1500, 1000, 1050, 1000), + ]; + for (name, w, h, nw, nh) in cases { + if only.as_ref().is_some_and(|o| !name.contains(o.as_str())) { + continue; + } + let img = photo(w, h); + let mut times = Vec::with_capacity(reps); + let mut hash = 0; + for _ in 0..reps { + let t = Instant::now(); + let out = carve(w, h, 4, &img, None, nw, nh); + times.push(t.elapsed().as_secs_f64() * 1000.0); + hash = fnv(&out); + } + times.sort_by(f64::total_cmp); + let p50 = times[times.len() / 2]; + let max = times[times.len() - 1]; + println!("{name:<48} p50 {p50:>9.1} ms max {max:>9.1} ms output {hash:016x}"); + } +} diff --git a/crates/algo/src/seam.rs b/crates/algo/src/seam.rs index 97619c7406c..498e84a414f 100644 --- a/crates/algo/src/seam.rs +++ b/crates/algo/src/seam.rs @@ -852,6 +852,35 @@ mod tests { 0x2157_9f86_27d6_b835, ]; + /// [`output_bits_are_pinned`] for the reduced-height seam search of tall images (rows at + /// least [`PROXY_SHRINK_MIN_HEIGHT`], at least [`PROXY_SHRINK_MIN_SEAMS`] seams): widths and, + /// through the transposed pass, heights, with and without protection, on tie-heavy and + /// fine-grained noise. + #[test] + fn tall_proxy_output_bits_are_pinned() { + let cases: [(usize, usize, usize, u32, bool, usize, usize); 5] = [ + (96, PROXY_SHRINK_MIN_HEIGHT, 3, 2, false, 30, PROXY_SHRINK_MIN_HEIGHT), + (130, 2_100, 4, 255, true, 64, 2_100), + (80, 2_600, 1, 65_536, false, 16, 2_600), + (PROXY_SHRINK_MIN_HEIGHT, 90, 3, 5, false, PROXY_SHRINK_MIN_HEIGHT, 20), + (2_050, 100, 4, 1000, true, 2_050, 36), + ]; + let got: Vec = cases + .iter() + .enumerate() + .map(|(i, &(w, h, ch, levels, prot, nw, nh))| { + let img = noise(w * h * ch, levels, 31 + i as u32); + let protect = prot.then(|| noise(w * h, 3, 131 + i as u32)); + let out = carve(w, h, ch, &img, protect.as_deref(), nw, nh); + assert_eq!(out.len(), nw * nh * ch); + fnv(&out) + }) + .collect(); + assert_eq!(got, TALL_PINNED); + } + + const TALL_PINNED: [u64; 5] = [0x5657_83ac_cb26_56a5, 0x81a6_b5f7_e299_fdfb, 0xcdf2_9df9_9b83_def5, 0xa713_544a_4dcc_d8d8, 0x3557_de9f_ffb0_881e]; + #[test] fn one_pixel_lines_enlarge_by_repeating() { // Width 1 has no seam to spare: its one column is repeated. Height 1 likewise (through From 67d32bcab592c27282cb60020553fefe8d905516 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 13 Oct 2026 15:09:45 +0000 Subject: [PATCH 2/6] perf(algo): Content-Aware Scale keeps its seam search and moves no pixels (#211) Seam carving recomputed the whole dynamic programme for every seam (about 1.8 G serial cell updates for P28's 600 seams) and shifted every buffer, the image included, over each removed pixel. - The seam search keeps its path-cost map across seams. After a removal only the pixels near the seam and those whose parents' costs actually changed are recomputed, row by row; nothing else can change, so the map is bit-identical to a full pass (incremental_dp_matches_ full_dp checks it after every removal). The direction buffer is gone: the seam is traced back from the costs with the same tie rules. - The carver no longer copies or moves pixels: it keeps each remaining pixel's source column (u32) and reads energy neighbours and the output through it. A removal shifts the shorter side of each row in three 4-byte buffers instead of the longer tail in up to four, 16-byte pixels included. - The tall-image proxy build, its full-resolution rebuild (runs copied between removed columns), the height pass's transposes (blocked) and the plain resample run in parallel over rows. Output is unchanged: the pinned hashes (small and tall images), the 400-case reference comparison and bench_seam's hashes of 24 MP results all match. bench_seam, interleaved A/B over 5 rounds on 4 cores: 24 MP to 90 % width (P28) 2292 -> 612 ms, 24 MP to 90 % height 2795 -> 1076 ms, 5.4 MP exact path 1912 -> 797 ms, 1.5 MP 782 -> 428 ms. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LELc5BQzgV5dA7dxdMejkK --- crates/algo/src/seam.rs | 580 +++++++++++++++++++++++++++++----------- 1 file changed, 424 insertions(+), 156 deletions(-) diff --git a/crates/algo/src/seam.rs b/crates/algo/src/seam.rs index 498e84a414f..8b5befda80d 100644 --- a/crates/algo/src/seam.rs +++ b/crates/algo/src/seam.rs @@ -33,7 +33,7 @@ pub fn energy(w: usize, h: usize, ch: usize, img: &[f32]) -> Vec { } let row = |(y, out): (usize, &mut [f32])| { for (x, v) in out.iter_mut().enumerate() { - *v = energy_at(img, w, w, h, ch, x, y); + *v = energy_at(img, w, w, h, ch, x, y, |xx, _| xx); } }; #[cfg(not(target_arch = "wasm32"))] @@ -46,18 +46,21 @@ pub fn energy(w: usize, h: usize, ch: usize, img: &[f32]) -> Vec { e } -/// [`energy`] of one pixel of a `cw`-wide image whose rows are `stride` pixels apart. Shared by -/// the full map and the per-seam updates so both give bit-identical values. +/// [`energy`] of pixel `x` of row `y` of a `cw`-wide, `h`-tall image whose pixel `xx` of row `yy` +/// is column `col(xx, yy)` of `img` (`w` pixels per row). Shared by the full map and the carver's +/// per-seam updates, so both give bit-identical values. +#[allow(clippy::too_many_arguments)] #[inline] -fn energy_at(img: &[f32], stride: usize, cw: usize, h: usize, ch: usize, x: usize, y: usize) -> f32 { +fn energy_at(img: &[f32], w: usize, cw: usize, h: usize, ch: usize, x: usize, y: usize, col: impl Fn(usize, usize) -> usize) -> f32 { let (xl, xr) = (x.saturating_sub(1), (x + 1).min(cw - 1)); let (yu, yd) = (y.saturating_sub(1), (y + 1).min(h - 1)); - let at = |xx: usize, yy: usize, c: usize| img[(yy * stride + xx) * ch + c]; + let at = |xx: usize, yy: usize| (yy * w + col(xx, yy)) * ch; + let (centre, right, left, down, up) = (at(x, y), at(xr, y), at(xl, y), at(x, yd), at(x, yu)); let mut s = 0.0; for c in 0..ch { - let v = at(x, y, c); - s += (at(xr, y, c) - v).abs() + (v - at(xl, y, c)).abs(); - s += (at(x, yd, c) - v).abs() + (v - at(x, yu, c)).abs(); + let v = img[centre + c]; + s += (img[right + c] - v).abs() + (v - img[left + c]).abs(); + s += (img[down + c] - v).abs() + (v - img[up + c]).abs(); } s * 0.5 } @@ -67,57 +70,177 @@ pub fn find_seam(w: usize, h: usize, energy: &[f32]) -> Vec { if w == 0 || h == 0 || energy.len() < w * h { return vec![0; h]; } - Dp::default().seam(w, w, h, energy) + let off = vec![0; h]; + let rows = Rows { stride: w, cw: w, off: &off }; + let mut dp = Dp::default(); + dp.full(rows, energy); + dp.seam(rows) } -/// Scratch buffers for the seam search, reused across seams. +/// Where the `cw` pixels in use of each of a carver's rows are, in buffers whose rows are +/// `stride` apart: row y's are `off[y]..off[y] + cw` of its `stride` slots. +#[derive(Clone, Copy)] +struct Rows<'o> { + stride: usize, + cw: usize, + off: &'o [usize], +} + +impl Rows<'_> { + fn h(&self) -> usize { + self.off.len() + } + + /// Row y's pixels in use, as a range of its buffers. + #[inline] + fn of(&self, y: usize) -> std::ops::Range { + let start = y * self.stride + self.off[y]; + start..start + self.cw + } +} + +/// The seam search's dynamic programme over an energy map laid out as [`Rows`] (the carver's own +/// layout, so a removal shifts it like the other buffers): for every pixel, the cost of the +/// cheapest 8-connected path down to it from the top row. [`Carver`] keeps it across seams and +/// recomputes only what each removal changed ([`Dp::update`]). #[derive(Default)] struct Dp { + /// Cost of the cheapest path from the top row to each pixel. cost: Vec, - next: Vec, - /// Per pixel, where the cheapest path came from: 0 = up-left, 1 = up, 2 = up-right. - from: Vec, +} + +/// Pixel `x` of a `cw`-wide row with energy `e`, given the path costs of the row above (`up`): +/// its path cost and where that path came from (0 = up-left, 1 = up, 2 = up-right). Ties go to +/// the pixel straight up, then up-left, then up-right. The cost doesn't depend on the tie-break +/// and the direction doesn't depend on `e`, so the seam can be traced back from the costs alone. +/// The full pass's edges, [`Dp::update`] and [`Dp::seam`] use it, and the full pass's interior +/// repeats it exactly, so every way of filling the map gives the same bits. +#[inline] +fn cell(up: &[f32], cw: usize, x: usize, e: f32) -> (f32, u8) { + let (b, d) = if x == 0 { + if cw > 1 && up[1] < up[0] { (up[1], 2) } else { (up[0], 1) } + } else if x + 1 == cw { + if up[x - 1] < up[x] { (up[x - 1], 0) } else { (up[x], 1) } + } else { + let (b, d) = if up[x - 1] < up[x] { (up[x - 1], 0) } else { (up[x], 1) }; + if up[x + 1] < b { (up[x + 1], 2) } else { (b, d) } + }; + (b + e, d) +} + +/// Path costs of pixels `lo..lo + out.len()` of a `cw`-wide row with energies `e` (the whole +/// row's), from the path costs of the row above (`up`), into `out`. [`cell`] at the ends of the +/// row; in between, the same selection without edge tests or directions, so it vectorises. +#[inline] +fn row_costs(up: &[f32], e: &[f32], cw: usize, lo: usize, out: &mut [f32]) { + let Some(last) = (lo + out.len()).checked_sub(1) else { return }; + let (mut a, mut b) = (lo, last); + if a == 0 { + out[0] = cell(up, cw, 0, e[0]).0; + a = 1; + } + if b + 1 == cw && b >= a { + out[b - lo] = cell(up, cw, b, e[b]).0; + b -= 1; + } + if a > b { + return; + } + // Every pixel in a..=b has all three parents: up-left, up and up-right. + let parents = up[a - 1..b].iter().zip(&up[a..=b]).zip(&up[a + 1..=b + 1]); + for ((n, &ev), ((&l, &u), &r)) in out[a - lo..=b - lo].iter_mut().zip(&e[a..=b]).zip(parents) { + let m = if l < u { l } else { u }; + let m = if r < m { r } else { m }; + *n = m + ev; + } } impl Dp { - /// The lowest-energy seam of a `cw`-wide, `h`-tall energy map with rows `stride` apart. - /// Ties go to the pixel straight up, then up-left, then up-right; at the bottom, to the - /// leftmost end. - fn seam(&mut self, stride: usize, cw: usize, h: usize, energy: &[f32]) -> Vec { - self.cost.clear(); - self.cost.extend_from_slice(&energy[..cw]); - self.next.resize(cw, 0.0); - self.from.resize(cw * h, 0); - for y in 1..h { - let (cost, next) = (&self.cost[..cw], &mut self.next[..cw]); - let e = &energy[y * stride..y * stride + cw]; - let from = &mut self.from[y * cw..(y + 1) * cw]; - if cw == 1 { - (next[0], from[0]) = (cost[0] + e[0], 1); - } else { - let (b, d) = if cost[1] < cost[0] { (cost[1], 2) } else { (cost[0], 1) }; - (next[0], from[0]) = (b + e[0], d); - // The interior has all three parents: no edge tests in the hot loop. - let inner = next[1..cw - 1].iter_mut().zip(&mut from[1..cw - 1]).zip(&e[1..cw - 1]).zip(cost.windows(3)); - for (((n, f), &ev), c) in inner { - let (b, d) = if c[0] < c[1] { (c[0], 0) } else { (c[1], 1) }; - let (b, d) = if c[2] < b { (c[2], 2) } else { (b, d) }; - (*n, *f) = (b + ev, d); - } - let (b, d) = if cost[cw - 2] < cost[cw - 1] { (cost[cw - 2], 0) } else { (cost[cw - 1], 1) }; - (next[cw - 1], from[cw - 1]) = (b + e[cw - 1], d); - } - std::mem::swap(&mut self.cost, &mut self.next); + /// Fill the map for the pixels in use of every row of `energy`. + fn full(&mut self, rows: Rows, energy: &[f32]) { + let (cw, h) = (rows.cw, rows.h()); + self.cost.resize(rows.stride * h, 0.0); + if cw == 0 || h == 0 { + return; } - let cost = &self.cost[..cw]; - let mut x = (0..cw).min_by(|a, b| cost[*a].total_cmp(&cost[*b])).unwrap_or(0); + let first = rows.of(0); + self.cost[first.clone()].copy_from_slice(&energy[first]); + for y in 1..h { + let (above, rest) = self.cost.split_at_mut(y * rows.stride); + let (r, base) = (rows.of(y), y * rows.stride); + row_costs(&above[rows.of(y - 1)], &energy[r.clone()], cw, 0, &mut rest[r.start - base..r.end - base]); + } + } + + /// Bring the map up to date after `seam` (one x per row, counted before the removal) was + /// removed from every row of the map and of `energy`, leaving `rows.cw` pixels per row. + /// + /// A pixel's path cost depends only on its energy and on the costs of its parents in the row + /// above. Where a pixel and all its parents are on the same side of the seam in their rows, + /// the removal moved them together; that leaves, in row y, only the pixels from one left of + /// min(seam[y-1], seam[y]) to max(seam[y-1], seam[y]) with new parents. The energy changed + /// only where [`Carver::update_energy`] recomputed it: from one left of the leftmost of + /// `seam[y-1..=y+1]` to the rightmost, which covers those pixels too. Every other pixel needs + /// recomputing only if a parent's cost changed, so the work follows the changed costs down + /// the map and narrows wherever they settle, instead of covering the whole map. Recomputed + /// pixels go through [`cell`], so the map matches a [`Dp::full`] pass over the same energy + /// bit for bit. + fn update(&mut self, rows: Rows, energy: &[f32], seam: &[usize]) { + let (cw, h) = (rows.cw, rows.h()); + if cw == 0 || h == 0 || seam.len() < h { + return; + } + // Pixels of the row above whose cost changed: `lo..=hi`, or none when `lo > hi`. + let (mut changed_lo, mut changed_hi) = (usize::MAX, 0); + let mut fresh = Vec::new(); + for y in 0..h { + let near = &seam[y.saturating_sub(1)..(y + 2).min(h)]; + let mut lo = near.iter().min().map_or(0, |&s| s.saturating_sub(1)); + let mut hi = near.iter().max().map_or(0, |&s| s.min(cw - 1)); + if changed_lo <= changed_hi { + lo = lo.min(changed_lo.saturating_sub(1)); + hi = hi.max((changed_hi + 1).min(cw - 1)); + } + let (above, rest) = self.cost.split_at_mut(y * rows.stride); + let (r, base) = (rows.of(y), y * rows.stride); + let e = &energy[r.clone()]; + if fresh.len() < hi + 1 - lo { + fresh.resize(hi + 1 - lo, 0.0); + } + let fresh = &mut fresh[..hi + 1 - lo]; + match y.checked_sub(1) { + Some(u) => row_costs(&above[rows.of(u)], e, cw, lo, fresh), + None => fresh.copy_from_slice(&e[lo..=hi]), + } + // Store only what changed, and remember where that was for the row below. + let row = &mut rest[r.start - base + lo..r.start - base + hi + 1]; + let differs = |(a, b): (&f32, &f32)| a.to_bits() != b.to_bits(); + (changed_lo, changed_hi) = (usize::MAX, 0); + if let Some(first) = fresh.iter().zip(row.iter()).position(differs) { + let last = fresh.iter().zip(row.iter()).rposition(differs).unwrap_or(first); + row[first..=last].copy_from_slice(&fresh[first..=last]); + (changed_lo, changed_hi) = (lo + first, lo + last); + } + } + } + + /// The lowest-energy seam of the map: one x per row. At the bottom, ties go to the leftmost + /// end; going up, [`cell`] tells where each pixel's path came from. + fn seam(&self, rows: Rows) -> Vec { + let (cw, h) = (rows.cw, rows.h()); let mut seam = vec![0usize; h]; + if cw == 0 || h == 0 { + return seam; + } + let last = &self.cost[rows.of(h - 1)]; + let mut x = (0..cw).min_by(|a, b| last[*a].total_cmp(&last[*b])).unwrap_or(0); for y in (0..h).rev() { seam[y] = x; if y > 0 { - x = match self.from[y * cw + x] { - 0 => x - 1, - 2 => x + 1, + // `cell` never points past either end of the row; saturate rather than trust it. + x = match cell(&self.cost[rows.of(y - 1)], cw, x, 0.0).1 { + 0 => x.saturating_sub(1), + 2 => (x + 1).min(cw - 1), _ => x, }; } @@ -126,118 +249,212 @@ impl Dp { } } -/// Shrinks an image one seam at a time in place. Rows keep their original stride, so removing a -/// seam shifts only the rest of each row (in parallel), and the energy map is updated only next -/// to the removed seam instead of being recomputed: the gradient of a pixel changes only when a -/// neighbour does, which happens within a pixel of the seam in its own row and the rows around it. -struct Carver { - stride: usize, - cw: usize, +/// Shrinks an image one seam at a time without moving its pixels: the carver keeps which source +/// column each remaining pixel is (`idx`) and reads pixels through it. A removal shifts, in each +/// row, whichever side of the seam is shorter in the three per-pixel buffers (in parallel over +/// rows), and nothing is recomputed in full: the gradient of a pixel changes only when a +/// neighbour does, which happens within a pixel of the seam in its own row and the rows around +/// it, and the seam search's path costs are updated from there down ([`Dp::update`]). +struct Carver<'a> { + /// The image, `w × h × ch`, and the protection, one value per pixel: as given, never moved. + src: &'a [f32], + prot: Option<&'a [f32]>, + w: usize, h: usize, ch: usize, - img: Vec, - prot: Option>, + /// Pixels left per row. + cw: usize, + /// Where each row's first remaining pixel is in the per-pixel buffers (see [`Rows`]). + off: Vec, + /// Source column of each remaining pixel (rows `w` apart; layer areas are at most i32::MAX + /// wide, so `u32` holds any column). + idx: Vec, /// Energy plus protection, as the seam search sees it. e: Vec, - /// Original column of each pixel, when the caller needs to know which ones were removed. - idx: Option>, + /// The seam search over `e`, kept up to date. dp: Dp, } -impl Carver { - fn new(w: usize, h: usize, ch: usize, img: Vec, prot: Option>, track: bool) -> Self { - let mut e = energy(w, h, ch, &img); - if let Some(p) = &prot { +impl<'a> Carver<'a> { + fn new(w: usize, h: usize, ch: usize, src: &'a [f32], prot: Option<&'a [f32]>) -> Self { + let mut e = energy(w, h, ch, src); + if let Some(p) = prot { for (e, p) in e.iter_mut().zip(p) { *e += p.clamp(0.0, 1.0) * PROTECT_ENERGY; } } - let idx = track.then(|| (0..h).flat_map(|_| 0..w).collect()); - Carver { stride: w, cw: w, h, ch, img, prot, e, idx, dp: Dp::default() } + let idx = (0..h).flat_map(|_| (0..w).map(|x| u32::try_from(x).unwrap_or(u32::MAX))).collect(); + let off = vec![0; h]; + let mut dp = Dp::default(); + dp.full(Rows { stride: w, cw: w, off: &off }, &e); + Carver { src, prot, w, h, ch, cw: w, off, idx, e, dp } } - /// Remove the lowest-energy seam. Returns, per row, the removed column (the original column - /// when tracking). + /// Remove the lowest-energy seam. Returns, per row, the source column removed. fn remove_seam(&mut self) -> Vec { - let (stride, cw, h, ch) = (self.stride, self.cw, self.h, self.ch); - let seam = self.dp.seam(stride, cw, h, &self.e); - let removed = match &self.idx { - Some(idx) => seam.iter().enumerate().map(|(y, &x)| idx[y * stride + x]).collect(), - None => seam.clone(), - }; - shift_rows(&mut self.img, stride * ch, &seam, ch, cw); - shift_rows(&mut self.e, stride, &seam, 1, cw); - if let Some(p) = &mut self.prot { - shift_rows(p, stride, &seam, 1, cw); - } - if let Some(idx) = &mut self.idx { - shift_rows(idx, stride, &seam, 1, cw); + if self.cw == 0 { + return Vec::new(); } + let rows = Rows { stride: self.w, cw: self.cw, off: &self.off }; + let seam = self.dp.seam(rows); + let removed = seam.iter().enumerate().map(|(y, &x)| self.idx[rows.of(y).start + x] as usize).collect(); + self.shift(&seam); self.cw -= 1; self.update_energy(&seam); + self.dp.update(Rows { stride: self.w, cw: self.cw, off: &self.off }, &self.e, &seam); removed } + /// Remove `seam[y]` from each row of the per-pixel buffers. + fn shift(&mut self, seam: &[usize]) { + let (w, cw) = (self.w, self.cw); + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + self.e + .par_chunks_mut(w) + .zip(self.idx.par_chunks_mut(w)) + .zip(self.dp.cost.par_chunks_mut(w)) + .zip(self.off.par_iter_mut()) + .zip(seam.par_iter()) + .for_each(|((((e, idx), cost), off), &x)| shift_row(e, idx, cost, off, x, cw)); + } + #[cfg(target_arch = "wasm32")] + self.e + .chunks_mut(w) + .zip(self.idx.chunks_mut(w)) + .zip(self.dp.cost.chunks_mut(w)) + .zip(self.off.iter_mut()) + .zip(seam) + .for_each(|((((e, idx), cost), off), &x)| shift_row(e, idx, cost, off, x, cw)); + } + /// Recompute the energy of the pixels whose neighbours changed when `seam` was removed: in /// row y, from one left of the leftmost of the seam's x in rows y-1..=y+1 to the rightmost. fn update_energy(&mut self, seam: &[usize]) { - let (stride, cw, h, ch) = (self.stride, self.cw, self.h, self.ch); + let (w, cw, h, ch) = (self.w, self.cw, self.h, self.ch); if cw == 0 { return; } - let (img, prot) = (&self.img, self.prot.as_deref()); + let (src, prot, off, idx) = (self.src, self.prot, &self.off, &self.idx); + let col = |xx: usize, yy: usize| idx[yy * w + off[yy] + xx] as usize; let row = |(y, e): (usize, &mut [f32])| { let near = &seam[y.saturating_sub(1)..(y + 2).min(h)]; let lo = near.iter().min().map_or(0, |&s| s.saturating_sub(1)); let hi = near.iter().max().map_or(0, |&s| s.min(cw - 1)); for x in lo..=hi { - let mut v = energy_at(img, stride, cw, h, ch, x, y); + let mut v = energy_at(src, w, cw, h, ch, x, y, col); if let Some(p) = prot { - v += p[y * stride + x].clamp(0.0, 1.0) * PROTECT_ENERGY; + v += p[y * w + col(x, y)].clamp(0.0, 1.0) * PROTECT_ENERGY; } - e[x] = v; + e[off[y] + x] = v; + } + }; + // A few pixels per row (seams move at most one column per row), but each waits on reads + // from three rows of the source: rows in parallel overlap the waits. + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + self.e.par_chunks_mut(w).enumerate().for_each(row); + } + #[cfg(target_arch = "wasm32")] + self.e.chunks_mut(w).enumerate().for_each(row); + } + + /// The carved pixels, `cw × h × ch`, rows packed. + fn into_pixels(self) -> Vec { + let (w, cw, ch) = (self.w, self.cw, self.ch); + let mut out = vec![0.0f32; cw * self.h * ch]; + if cw == 0 { + return out; + } + let (src, off, idx) = (self.src, &self.off, &self.idx); + let row = |(y, out): (usize, &mut [f32])| { + let cols = &idx[y * w + off[y]..y * w + off[y] + cw]; + for (px, &x) in out.chunks_exact_mut(ch).zip(cols) { + let s = (y * w + x as usize) * ch; + px.copy_from_slice(&src[s..s + ch]); } }; #[cfg(not(target_arch = "wasm32"))] { use rayon::prelude::*; - self.e.par_chunks_mut(stride).enumerate().for_each(row); + out.par_chunks_mut(cw * ch).enumerate().for_each(row); } #[cfg(target_arch = "wasm32")] - self.e.chunks_mut(stride).enumerate().for_each(row); - } - - /// The carved pixels, `cw × h × ch`, rows packed. - fn into_pixels(self) -> Vec { - let (row, used) = (self.stride * self.ch, self.cw * self.ch); - if row == used { - return self.img; - } - self.img.chunks(row).flat_map(|r| &r[..used]).copied().collect() + out.chunks_mut(cw * ch).enumerate().for_each(row); + out } } -/// Remove pixel `seam[y]` (of `n` values) from each `row_len`-long row whose first `cw` pixels -/// are in use, by shifting the rest of the row left. -fn shift_rows(buf: &mut [T], row_len: usize, seam: &[usize], n: usize, cw: usize) { - let shift = |(r, &x): (&mut [T], &usize)| r.copy_within((x + 1) * n..cw * n, x * n); - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - buf.par_chunks_mut(row_len).zip(seam.par_iter()).for_each(shift); +/// Remove pixel `x` of the `cw` in use, from `off` on, of one row of a carver's per-pixel +/// buffers, moving whichever side of it holds fewer pixels (the row then starts one later when +/// that is the left side). +fn shift_row(e: &mut [f32], idx: &mut [u32], cost: &mut [f32], off: &mut usize, x: usize, cw: usize) { + let o = *off; + if x < cw - 1 - x { + e.copy_within(o..o + x, o + 1); + idx.copy_within(o..o + x, o + 1); + cost.copy_within(o..o + x, o + 1); + *off = o + 1; + } else { + e.copy_within(o + x + 1..o + cw, o + x); + idx.copy_within(o + x + 1..o + cw, o + x); + cost.copy_within(o + x + 1..o + cw, o + x); } - #[cfg(target_arch = "wasm32")] - buf.chunks_mut(row_len).zip(seam).for_each(shift); } fn transpose(w: usize, h: usize, ch: usize, img: &[f32]) -> Vec { let mut out = vec![0.0f32; img.len()]; - for y in 0..h { - for x in 0..w { - let (s, d) = ((y * w + x) * ch, (x * h + y) * ch); - out[d..d + ch].copy_from_slice(&img[s..s + ch]); - } + if w == 0 || h == 0 || ch == 0 { + return out; } + // Output rows (source columns) in blocks, so each source cache line serves several of them. + const BLOCK: usize = 16; + let block = |(b, out): (usize, &mut [f32])| { + let x0 = b * BLOCK; + let n = out.len() / (h * ch); + for y in 0..h { + for i in 0..n { + let (s, d) = ((y * w + x0 + i) * ch, (i * h + y) * ch); + out[d..d + ch].copy_from_slice(&img[s..s + ch]); + } + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + out.par_chunks_mut(BLOCK * h * ch).enumerate().for_each(block); + } + #[cfg(target_arch = "wasm32")] + out.chunks_mut(BLOCK * h * ch).enumerate().for_each(block); + out +} + +/// Each `step` rows of `src` (`h` rows of `row_len` values) averaged into one, the last group +/// possibly shorter: `h.div_ceil(step)` rows. +fn average_rows(src: &[f32], row_len: usize, h: usize, step: usize) -> Vec { + let mut out = vec![0.0; h.div_ceil(step) * row_len]; + if row_len == 0 { + return out; + } + let group = |(py, out_row): (usize, &mut [f32])| { + let y0 = py * step; + let y1 = (y0 + step).min(h); + let divisor = (y1 - y0) as f32; + for y in y0..y1 { + for (out, &sample) in out_row.iter_mut().zip(&src[y * row_len..(y + 1) * row_len]) { + *out += sample / divisor; + } + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + out.par_chunks_exact_mut(row_len).enumerate().for_each(group); + } + #[cfg(target_arch = "wasm32")] + out.chunks_exact_mut(row_len).enumerate().for_each(group); out } @@ -250,7 +467,8 @@ pub fn carve_width(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<& /// [`carve_width`] that checks `ctl` before every seam and reports progress per seam. pub fn carve_width_with(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<&[f32]>, new_w: usize, ctl: &Interrupt) -> Result, Cancelled> { let new_w = new_w.max(1); - if new_w == w || w == 0 || h == 0 { + // No channels: nothing to carve (and no pixels to size the work by). + if new_w == w || w == 0 || h == 0 || ch == 0 { return Ok(img.to_vec()); } let seams = new_w.abs_diff(w).max(1) as f32; @@ -258,7 +476,7 @@ pub fn carve_width_with(w: usize, h: usize, ch: usize, img: &[f32], protect: Opt if h >= PROXY_SHRINK_MIN_HEIGHT && w - new_w >= PROXY_SHRINK_MIN_SEAMS { return carve_width_proxy_height(w, h, ch, img, protect, new_w, ctl); } - let mut carver = Carver::new(w, h, ch, img.to_vec(), protect.map(<[f32]>::to_vec), false); + let mut carver = Carver::new(w, h, ch, img, protect); while carver.cw > new_w { ctl.check()?; ctl.progress((w - carver.cw) as f32 / seams); @@ -272,7 +490,7 @@ pub fn carve_width_with(w: usize, h: usize, ch: usize, img: &[f32], protect: Opt while cw < new_w { let k = (new_w - cw).min((cw / 2).max(1)); // Find k seams on a shrinking copy, mapping each back to original columns. - let mut carver = Carver::new(cw, h, ch, cur.clone(), prot.clone(), true); + let mut carver = Carver::new(cw, h, ch, &cur, prot.as_deref()); let mut dup: Vec> = vec![Vec::with_capacity(k); h]; for _ in 0..k { // A 1 px wide image's only seam is its one column: take it, so it is duplicated. @@ -329,37 +547,11 @@ fn carve_width_proxy_height(w: usize, h: usize, ch: usize, img: &[f32], protect: let step = h.div_ceil(SEAM_SEARCH_MAX_HEIGHT); let proxy_h = h.div_ceil(step); let row_len = w * ch; - let proxy_row_len = proxy_h * row_len; - let mut proxy = vec![0.0; proxy_row_len]; - for (py, out_row) in proxy.chunks_exact_mut(row_len).enumerate() { - let y0 = py * step; - let y1 = (y0 + step).min(h); - let divisor = (y1 - y0) as f32; - for y in y0..y1 { - let in_row = &img[y * row_len..(y + 1) * row_len]; - for (out, &sample) in out_row.iter_mut().zip(in_row) { - *out += sample / divisor; - } - } - } - let proxy_protect = protect.map(|mask| { - let mut reduced = vec![0.0; proxy_h * w]; - for (py, out_row) in reduced.chunks_exact_mut(w).enumerate() { - let y0 = py * step; - let y1 = (y0 + step).min(h); - let divisor = (y1 - y0) as f32; - for y in y0..y1 { - let in_row = &mask[y * w..(y + 1) * w]; - for (out, &sample) in out_row.iter_mut().zip(in_row) { - *out += sample / divisor; - } - } - } - reduced - }); + let proxy = average_rows(img, row_len, h, step); + let proxy_protect = protect.map(|mask| average_rows(mask, w, h, step)); let seam_count = w - new_w; - let mut carver = Carver::new(w, proxy_h, ch, proxy, proxy_protect, true); + let mut carver = Carver::new(w, proxy_h, ch, &proxy, proxy_protect.as_deref()); let mut removed = Vec::with_capacity(seam_count); while carver.cw > new_w { ctl.check()?; @@ -373,31 +565,44 @@ fn carve_width_proxy_height(w: usize, h: usize, ch: usize, img: &[f32], protect: columns.sort_unstable(); removed_by_row.push(columns); } - let mut out = Vec::with_capacity(new_w * h * ch); - let mut columns = vec![0; seam_count]; - for y in 0..h { + // Each full-resolution row removes the columns interpolated between its two proxy rows'. + let rebuild = |columns: &mut Vec, (y, out): (usize, &mut [f32])| -> Result<(), Cancelled> { ctl.check()?; let proxy_y = (y / step).min(proxy_h - 1); let next_proxy_y = (proxy_y + 1).min(proxy_h - 1); let blend = (y % step) as f32 / step as f32; let lower = &removed_by_row[proxy_y]; let upper = &removed_by_row[next_proxy_y]; + columns.clear(); let mut min_x = 0; - for (i, x) in columns.iter_mut().enumerate() { + for i in 0..seam_count { let interpolated = lower[i] as f32 + (upper[i] as f32 - lower[i] as f32) * blend; let max_x = w - (seam_count - i); - *x = (interpolated.round() as usize).clamp(min_x, max_x); + let x = (interpolated.round() as usize).clamp(min_x, max_x); + columns.push(x); min_x = x.saturating_add(1); } - let mut next = 0; + // The columns rise strictly within the row: copy the runs between them. let row = &img[y * row_len..(y + 1) * row_len]; - for (x, pixel) in row.chunks_exact(ch).enumerate() { - if columns.get(next) == Some(&x) { - next += 1; - } else { - out.extend_from_slice(pixel); - } + let (mut from, mut at) = (0, 0); + for &x in columns.iter() { + let run = (x - from) * ch; + out[at..at + run].copy_from_slice(&row[from * ch..x * ch]); + (from, at) = (x + 1, at + run); } + out[at..].copy_from_slice(&row[from * ch..]); + Ok(()) + }; + let mut out = vec![0.0f32; new_w * h * ch]; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + out.par_chunks_exact_mut(new_w * ch).enumerate().try_for_each_init(|| Vec::with_capacity(seam_count), rebuild)?; + } + #[cfg(target_arch = "wasm32")] + { + let mut columns = Vec::with_capacity(seam_count); + out.chunks_exact_mut(new_w * ch).enumerate().try_for_each(|r| rebuild(&mut columns, r))?; } ctl.progress(1.0); Ok(out) @@ -443,10 +648,10 @@ pub fn carve_with( /// Plain bilinear resize (the non-content-aware part of the Amount blend). pub fn resize_bilinear(w: usize, h: usize, ch: usize, img: &[f32], nw: usize, nh: usize) -> Vec { let mut out = vec![0.0f32; nw * nh * ch]; - if w == 0 || h == 0 { + if w == 0 || h == 0 || nw == 0 || nh == 0 { return out; } - for y in 0..nh { + let row = |(y, out): (usize, &mut [f32])| { let fy = ((y as f32 + 0.5) * h as f32 / nh as f32 - 0.5).clamp(0.0, (h - 1) as f32); let (y0, ty) = (fy.floor() as usize, fy.fract()); let y1 = (y0 + 1).min(h - 1); @@ -458,10 +663,17 @@ pub fn resize_bilinear(w: usize, h: usize, ch: usize, img: &[f32], nw: usize, nh let p = |xx: usize, yy: usize| img[(yy * w + xx) * ch + c]; let top = p(x0, y0) + (p(x1, y0) - p(x0, y0)) * tx; let bot = p(x0, y1) + (p(x1, y1) - p(x0, y1)) * tx; - out[(y * nw + x) * ch + c] = top + (bot - top) * ty; + out[x * ch + c] = top + (bot - top) * ty; } } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + out.par_chunks_mut(nw * ch).enumerate().for_each(row); } + #[cfg(target_arch = "wasm32")] + out.chunks_mut(nw * ch).enumerate().for_each(row); out } @@ -683,6 +895,62 @@ mod tests { } } + /// After every removal, the carver's incrementally updated seam search matches a full pass + /// over its current energy bit for bit (path costs and the seam traced from them), on images + /// where seams run through the edges, through flat areas full of ties and through protection. + /// Its energy matches a fresh map of the pixels left, and so do the pixels. + #[test] + fn incremental_dp_matches_full_dp() { + let mut ramp = vec![0.0f32; 120 * 90]; + for (i, v) in ramp.iter_mut().enumerate() { + let (x, y) = ((i % 120) as f32, (i / 120) as f32); + *v = ((x * 0.07).sin() * (y * 0.05).cos() * 0.5 + 0.5).clamp(0.0, 1.0); + } + // (w, h, channels, image, protection, seams to remove) + type Case = (usize, usize, usize, Vec, Option>, usize); + let cases: Vec = vec![ + (120, 90, 1, ramp, None, 40), + (97, 64, 3, noise(97 * 64 * 3, 2, 5), None, 90), + (80, 70, 4, noise(80 * 70 * 4, 1000, 6), Some(noise(80 * 70, 3, 7)), 60), + (64, 50, 3, bar(64, 50), None, 63), + (33, 1, 1, noise(33, 5, 8), None, 32), + (2, 40, 3, noise(2 * 40 * 3, 9, 9), None, 2), + (50, 40, 1, vec![0.5; 50 * 40], Some(noise(50 * 40, 2, 10)), 49), + ]; + let bits = |v: &[f32]| v.iter().map(|f| f.to_bits()).collect::>(); + for (case, (w, h, ch, img, prot, seams)) in cases.into_iter().enumerate() { + let mut c = Carver::new(w, h, ch, &img, prot.as_deref()); + for step in 0..=seams { + let rows = Rows { stride: c.w, cw: c.cw, off: &c.off }; + let mut fresh = Dp::default(); + fresh.full(rows, &c.e); + for y in 0..h { + assert_eq!(bits(&c.dp.cost[rows.of(y)]), bits(&fresh.cost[rows.of(y)]), "case {case} step {step} row {y}: costs"); + } + assert_eq!(c.dp.seam(rows), fresh.seam(rows), "case {case} step {step}: seam"); + // The pixels left, packed, and their energy (plus protection) from scratch. + let left: Vec = (0..h) + .flat_map(|y| c.idx[rows.of(y)].iter().flat_map(move |&x| (0..ch).map(move |k| (y * w + x as usize) * ch + k))) + .map(|i| img[i]) + .collect(); + let mut want = energy(c.cw, h, ch, &left); + if let Some(p) = &prot { + let kept = (0..h).flat_map(|y| c.idx[rows.of(y)].iter().map(move |&x| y * w + x as usize)); + for (e, i) in want.iter_mut().zip(kept) { + *e += p[i].clamp(0.0, 1.0) * PROTECT_ENERGY; + } + } + let have: Vec = (0..h).flat_map(|y| c.e[rows.of(y)].to_vec()).collect(); + assert_eq!(bits(&have), bits(&want), "case {case} step {step}: energy"); + if step == seams { + assert_eq!(bits(&c.into_pixels()), bits(&left), "case {case}: pixels"); + break; + } + c.remove_seam(); + } + } + } + #[test] fn cancelled_carve_stops() { let (w, h) = (40, 20); From b8b8483bf9b5af858bb44ead80dafebc31f42d7a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 13 Oct 2026 18:08:45 +0000 Subject: [PATCH 3/6] fix(algo): seam carving never panics on degenerate input; NaN never steers seams From an adversarial review of the Content-Aware Scale speed-up: - resize_bilinear with zero channels panicked (chunk size 0) since the previous commit; it, carve_with and carve_width_with now return early when there are no pixels or channels, or fewer values than the size says (sizes checked with checked_mul). carve with an empty width and a height change, and a protection map shorter than the image (now ignored), panicked before this series too. - With NaN in the energy map, which seam was chosen depended on the NaN payload, and that differed between builds. NaN samples now give the highest energy and NaN protection protects nothing, so costs are never NaN; outputs without NaN are unchanged (all pins match). Tests: degenerate_inputs_do_not_panic and nan_payloads_do_not_steer_seams (both failed before), proxy_rebuild_observes_cancellation (a cancel during the tall-image rebuild), and NaN/inf cases in incremental_dp_matches_full_dp. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LELc5BQzgV5dA7dxdMejkK --- crates/algo/src/seam.rs | 121 ++++++++++++++++++++++++++++++++++------ 1 file changed, 105 insertions(+), 16 deletions(-) diff --git a/crates/algo/src/seam.rs b/crates/algo/src/seam.rs index 8b5befda80d..59e235bc059 100644 --- a/crates/algo/src/seam.rs +++ b/crates/algo/src/seam.rs @@ -9,13 +9,21 @@ //! //! A protect map (`0..=1`, e.g. an alpha channel or detected skin tones) adds a large energy so //! seams avoid protected pixels. Buffers are interleaved `w × h × ch` normalised floats of any -//! colour model and depth (alpha is carried like any other channel). Deterministic. +//! colour model and depth (alpha is carried like any other channel). Deterministic: a NaN sample +//! gives its pixels the highest energy and NaN protection protects nothing, so no NaN (whose +//! payload arithmetic does not keep consistently across builds) ever reaches the seam search. use photocraft_raster::{Cancelled, Interrupt}; /// Energy added per unit of protection: far above any gradient magnitude. const PROTECT_ENERGY: f32 = 1.0e4; +/// The energy protection `p` (`0..=1`) adds. NaN protects nothing. +#[inline] +fn protection(p: f32) -> f32 { + if p.is_nan() { 0.0 } else { p.clamp(0.0, 1.0) * PROTECT_ENERGY } +} + /// Keep full horizontal detail while reducing the height used to find vertical seams. At a /// 24 MP working size this cuts the dynamic-programming work by about four times without /// quantising the output pixels or changing the requested output dimensions. @@ -48,7 +56,7 @@ pub fn energy(w: usize, h: usize, ch: usize, img: &[f32]) -> Vec { /// [`energy`] of pixel `x` of row `y` of a `cw`-wide, `h`-tall image whose pixel `xx` of row `yy` /// is column `col(xx, yy)` of `img` (`w` pixels per row). Shared by the full map and the carver's -/// per-seam updates, so both give bit-identical values. +/// per-seam updates, so both give bit-identical values. NaN samples give the highest energy. #[allow(clippy::too_many_arguments)] #[inline] fn energy_at(img: &[f32], w: usize, cw: usize, h: usize, ch: usize, x: usize, y: usize, col: impl Fn(usize, usize) -> usize) -> f32 { @@ -62,7 +70,8 @@ fn energy_at(img: &[f32], w: usize, cw: usize, h: usize, ch: usize, x: usize, y: s += (img[right + c] - v).abs() + (v - img[left + c]).abs(); s += (img[down + c] - v).abs() + (v - img[up + c]).abs(); } - s * 0.5 + let e = s * 0.5; + if e.is_nan() { f32::INFINITY } else { e } } /// The lowest-energy vertical seam: one x per row. @@ -114,7 +123,8 @@ struct Dp { /// the pixel straight up, then up-left, then up-right. The cost doesn't depend on the tie-break /// and the direction doesn't depend on `e`, so the seam can be traced back from the costs alone. /// The full pass's edges, [`Dp::update`] and [`Dp::seam`] use it, and the full pass's interior -/// repeats it exactly, so every way of filling the map gives the same bits. +/// repeats it exactly, so every way of filling the map gives the same bits (costs are never NaN: +/// see [`energy_at`] and [`protection`]). #[inline] fn cell(up: &[f32], cw: usize, x: usize, e: f32) -> (f32, u8) { let (b, d) = if x == 0 { @@ -279,8 +289,8 @@ impl<'a> Carver<'a> { fn new(w: usize, h: usize, ch: usize, src: &'a [f32], prot: Option<&'a [f32]>) -> Self { let mut e = energy(w, h, ch, src); if let Some(p) = prot { - for (e, p) in e.iter_mut().zip(p) { - *e += p.clamp(0.0, 1.0) * PROTECT_ENERGY; + for (e, &p) in e.iter_mut().zip(p) { + *e += protection(p); } } let idx = (0..h).flat_map(|_| (0..w).map(|x| u32::try_from(x).unwrap_or(u32::MAX))).collect(); @@ -345,7 +355,7 @@ impl<'a> Carver<'a> { for x in lo..=hi { let mut v = energy_at(src, w, cw, h, ch, x, y, col); if let Some(p) = prot { - v += p[y * w + col(x, y)].clamp(0.0, 1.0) * PROTECT_ENERGY; + v += protection(p[y * w + col(x, y)]); } e[off[y] + x] = v; } @@ -458,6 +468,11 @@ fn average_rows(src: &[f32], row_len: usize, h: usize, step: usize) -> Vec out } +/// No pixels or channels to work with, or `img` holds fewer than `w × h × ch` values. +fn unusable(w: usize, h: usize, ch: usize, img: &[f32]) -> bool { + w == 0 || h == 0 || ch == 0 || w.checked_mul(h).and_then(|n| n.checked_mul(ch)).is_none_or(|n| img.len() < n) +} + /// Change the width of `img` to `new_w` by removing or duplicating vertical seams. pub fn carve_width(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<&[f32]>, new_w: usize) -> Vec { // Never cancelled; the fallback is unreachable. @@ -467,10 +482,12 @@ pub fn carve_width(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<& /// [`carve_width`] that checks `ctl` before every seam and reports progress per seam. pub fn carve_width_with(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<&[f32]>, new_w: usize, ctl: &Interrupt) -> Result, Cancelled> { let new_w = new_w.max(1); - // No channels: nothing to carve (and no pixels to size the work by). - if new_w == w || w == 0 || h == 0 || ch == 0 { + // Nothing to carve: no pixels or channels, or fewer values than the size says. + if new_w == w || unusable(w, h, ch, img) { return Ok(img.to_vec()); } + // A protection map that doesn't cover the image protects nothing. + let protect = protect.filter(|p| p.len() >= w * h); let seams = new_w.abs_diff(w).max(1) as f32; if new_w < w { if h >= PROXY_SHRINK_MIN_HEIGHT && w - new_w >= PROXY_SHRINK_MIN_SEAMS { @@ -628,6 +645,10 @@ pub fn carve_with( ctl: &Interrupt, ) -> Result, Cancelled> { let (new_w, new_h) = (new_w.max(1), new_h.max(1)); + if unusable(w, h, ch, img) { + return Ok(img.to_vec()); + } + let protect = protect.filter(|p| p.len() >= w * h); // Split progress between the passes by their seam counts. let (sw, sh) = (new_w.abs_diff(w) as f32, new_h.abs_diff(h) as f32); let split = if sw + sh > 0.0 { sw / (sw + sh) } else { 1.0 }; @@ -647,8 +668,11 @@ pub fn carve_with( /// Plain bilinear resize (the non-content-aware part of the Amount blend). pub fn resize_bilinear(w: usize, h: usize, ch: usize, img: &[f32], nw: usize, nh: usize) -> Vec { - let mut out = vec![0.0f32; nw * nh * ch]; - if w == 0 || h == 0 || nw == 0 || nh == 0 { + let Some(len) = nw.checked_mul(nh).and_then(|n| n.checked_mul(ch)) else { + return Vec::new(); + }; + let mut out = vec![0.0f32; len]; + if len == 0 || unusable(w, h, ch, img) { return out; } let row = |(y, out): (usize, &mut [f32])| { @@ -702,7 +726,7 @@ mod tests { /// The straightforward implementation the per-seam carver replaced (full energy map, fresh /// seam search and a new buffer per seam), kept as the oracle for `carver_matches_reference`. mod reference { - use super::super::{PROTECT_ENERGY, resize_bilinear, transpose}; + use super::super::{protection, resize_bilinear, transpose}; pub(super) fn energy(w: usize, h: usize, ch: usize, img: &[f32]) -> Vec { let mut e = vec![0.0f32; w * h]; @@ -717,7 +741,8 @@ mod tests { s += (at(xr, y, c) - v).abs() + (v - at(xl, y, c)).abs(); s += (at(x, yd, c) - v).abs() + (v - at(x, yu, c)).abs(); } - e[y * w + x] = s * 0.5; + let v = s * 0.5; + e[y * w + x] = if v.is_nan() { f32::INFINITY } else { v }; } } e @@ -770,8 +795,8 @@ mod tests { } let protect_e = |e: &mut [f32], p: Option<&Vec>| { if let Some(p) = p { - for (e, p) in e.iter_mut().zip(p) { - *e += p.clamp(0.0, 1.0) * PROTECT_ENERGY; + for (e, &p) in e.iter_mut().zip(p) { + *e += protection(p); } } }; @@ -906,6 +931,12 @@ mod tests { let (x, y) = ((i % 120) as f32, (i / 120) as f32); *v = ((x * 0.07).sin() * (y * 0.05).cos() * 0.5 + 0.5).clamp(0.0, 1.0); } + // NaN and infinite samples and NaN protection: infinite energies, never NaN costs. + let mut odd = noise(40 * 30 * 3, 255, 11); + odd.iter_mut().step_by(13).for_each(|v| *v = f32::NAN); + odd.iter_mut().skip(5).step_by(17).for_each(|v| *v = f32::INFINITY); + let mut odd_prot = noise(40 * 30, 3, 12); + odd_prot.iter_mut().step_by(7).for_each(|v| *v = -f32::NAN); // (w, h, channels, image, protection, seams to remove) type Case = (usize, usize, usize, Vec, Option>, usize); let cases: Vec = vec![ @@ -916,6 +947,7 @@ mod tests { (33, 1, 1, noise(33, 5, 8), None, 32), (2, 40, 3, noise(2 * 40 * 3, 9, 9), None, 2), (50, 40, 1, vec![0.5; 50 * 40], Some(noise(50 * 40, 2, 10)), 49), + (40, 30, 3, odd, Some(odd_prot), 25), ]; let bits = |v: &[f32]| v.iter().map(|f| f.to_bits()).collect::>(); for (case, (w, h, ch, img, prot, seams)) in cases.into_iter().enumerate() { @@ -937,7 +969,7 @@ mod tests { if let Some(p) = &prot { let kept = (0..h).flat_map(|y| c.idx[rows.of(y)].iter().map(move |&x| y * w + x as usize)); for (e, i) in want.iter_mut().zip(kept) { - *e += p[i].clamp(0.0, 1.0) * PROTECT_ENERGY; + *e += protection(p[i]); } } let have: Vec = (0..h).flat_map(|y| c.e[rows.of(y)].to_vec()).collect(); @@ -951,6 +983,63 @@ mod tests { } } + /// Hostile but well-formed shapes return early instead of panicking: no channels, empty + /// sizes (also through the height pass), and images or protection maps shorter than their + /// size says (a short map protects nothing). + #[test] + fn degenerate_inputs_do_not_panic() { + assert!(carve(3, 3, 0, &[], None, 2, 2).is_empty()); + assert!(carve(3, 3, 0, &[], None, 5, 5).is_empty()); + assert!(transpose(3, 3, 0, &[]).is_empty()); + assert!(resize_bilinear(3, 3, 0, &[], 2, 2).is_empty()); + assert!(resize_bilinear(3, 3, 1, &[0.5; 9], 0, 2).is_empty()); + assert!(resize_bilinear(3, 3, 1, &[0.5; 9], 2, 0).is_empty()); + assert_eq!(resize_bilinear(3, 3, 1, &[0.5; 4], 2, 2), vec![0.0; 4]); + assert!(carve(0, 5, 3, &[], None, 3, 7).is_empty()); + assert!(carve(0, 5, 3, &[], None, 3, 2).is_empty()); + let img = noise(10 * 5, 7, 3); + assert_eq!(carve(10, 5, 1, &img, Some(&[0.0; 3]), 4, 5), carve(10, 5, 1, &img, None, 4, 5)); + assert_eq!(carve(10, 5, 1, &img, Some(&[0.0; 3]), 4, 3), carve(10, 5, 1, &img, None, 4, 3)); + assert_eq!(carve(10, 5, 3, &[0.5; 20], None, 4, 5), vec![0.5; 20]); + assert_eq!(carve_width(usize::MAX, 2, 4, &[0.5; 8], None, 1), vec![0.5; 8]); + } + + /// A cancel that arrives after the seam search, during the tall-image rebuild, still stops + /// the carve. + #[test] + fn proxy_rebuild_observes_cancellation() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let (w, h, ch, new_w) = (128, PROXY_SHRINK_MIN_HEIGHT, 3, 64); + let img = noise(w * h * ch, 7, 5); + let calls = AtomicUsize::new(0); + // One check per seam passes; the first one after the search cancels. + let cancel = || calls.fetch_add(1, Ordering::Relaxed) >= w - new_w; + assert_eq!(carve_width_with(w, h, ch, &img, None, new_w, &Interrupt::cancel_only(&cancel)), Err(Cancelled)); + assert!(calls.load(Ordering::Relaxed) > w - new_w, "the rebuild checked for cancellation"); + } + + /// NaN samples and NaN protection steer seams the same whatever their sign and payload + /// (which arithmetic does not preserve consistently across builds): the same pixels are kept. + #[test] + fn nan_payloads_do_not_steer_seams() { + let (w, h, ch) = (24, 18, 3); + let (base, prot_base) = (noise(w * h * ch, 255, 21), noise(w * h, 3, 22)); + let carve_with_nans = |pixel: f32, prot: f32| { + let (mut img, mut p) = (base.clone(), prot_base.clone()); + img.iter_mut().step_by(37).for_each(|v| *v = pixel); + p.iter_mut().step_by(29).for_each(|v| *v = prot); + carve(w, h, ch, &img, Some(&p), 15, 11) + }; + let canonical = |v: Vec| v.into_iter().map(|f| if f.is_nan() { u32::MAX } else { f.to_bits() }).collect::>(); + let nans = [f32::NAN, -f32::NAN, f32::from_bits(0x7fc0_1234), f32::from_bits(0xffc0_0001)]; + let want = canonical(carve_with_nans(nans[0], nans[0])); + for &a in &nans { + for &b in &nans { + assert_eq!(canonical(carve_with_nans(a, b)), want, "pixel NaN {:#x}, protection NaN {:#x}", a.to_bits(), b.to_bits()); + } + } + } + #[test] fn cancelled_carve_stops() { let (w, h) = (40, 20); From d1a1569a6cda9e6984ad2a6ebab2d980c43df047 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 13 Oct 2026 18:20:06 +0000 Subject: [PATCH 4/6] bench(engine): bench_content_aware_scale times P28's command without the UI perf_scenarios needs the whole UI crate in release (about 25 min to build on 4 cores) to time edit.contentAwareScale. This example times the same command on the same synthetic 24 MP JPEG photo from the engine alone (about 6 min), undoing between runs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LELc5BQzgV5dA7dxdMejkK --- .../examples/bench_content_aware_scale.rs | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 crates/engine/examples/bench_content_aware_scale.rs diff --git a/crates/engine/examples/bench_content_aware_scale.rs b/crates/engine/examples/bench_content_aware_scale.rs new file mode 100644 index 00000000000..dd137fefd5b --- /dev/null +++ b/crates/engine/examples/bench_content_aware_scale.rs @@ -0,0 +1,50 @@ +//! End-to-end timing of `edit.contentAwareScale` (perf scenario P28, #211) without the UI: a +//! synthetic 24 MP RGB photo opened from JPEG like `perf_scenarios`' (gradients, soft blobs, fine +//! noise and a high-contrast disc), scaled to 90 % width, undone between runs. +//! `cargo run --release -p photocraft-engine --example bench_content_aware_scale [reps] [width height]` +use std::time::Instant; + +use photocraft_engine::Session; +use serde_json::json; + +fn photo_jpeg(w: u32, h: u32) -> Result, String> { + let mut px = vec![0u8; w as usize * h as usize * 3]; + let (cx, cy, r) = (w as f32 * 0.55, h as f32 * 0.5, w.min(h) as f32 / 3.0); + for (y, row) in px.chunks_mut(w as usize * 3).enumerate() { + for x in 0..w as usize { + let (fx, fy) = (x as f32 / w as f32, y as f32 / h as f32); + let n = ((x.wrapping_mul(73_856_093) ^ y.wrapping_mul(19_349_663)) % 997) as f32 / 997.0 - 0.5; + let blob = (-(((fx - 0.4) * 3.0).powi(2) + ((fy - 0.55) * 4.0).powi(2))).exp(); + let inside = ((x as f32 - cx).powi(2) + (y as f32 - cy).powi(2)).sqrt() < r; + let (r0, g0, b0) = if inside { (0.85, 0.3 + 0.2 * (fx * 40.0).sin(), 0.15) } else { (0.35, 0.45, 0.55) }; + let rgb = [r0 + 0.1 * blob + n * 0.08, g0 + 0.1 * blob + n * 0.08, b0 + 0.2 * fy + n * 0.08]; + for (c, v) in rgb.into_iter().enumerate() { + row[x * 3 + c] = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + } + } + } + let img = + photocraft_codecs::Image::from_raw(w, h, photocraft_codecs::ChannelLayout::Rgb, photocraft_codecs::SampleType::U8, px).map_err(|e| e.to_string())?; + photocraft_codecs::encode(&img, photocraft_codecs::Format::Jpeg, &Default::default()).map_err(|e| e.to_string()) +} + +fn main() -> Result<(), String> { + let args: Vec = std::env::args().collect(); + let num = |i: usize, d: u32| args.get(i).and_then(|v| v.parse::().ok()).unwrap_or(d); + let (reps, w, h) = (num(1, 3).clamp(1, 20) as usize, num(2, 6000).clamp(16, 20_000), num(3, 4000).clamp(16, 20_000)); + let jpeg = photo_jpeg(w, h)?; + let doc = photocraft_io::import("photo.jpg", &jpeg).map_err(|e| e.to_string())?.document; + let mut s = Session::new(); + s.open_document(doc, Some("photo.jpg".into())); + let mut times = Vec::with_capacity(reps); + for _ in 0..reps { + let t = Instant::now(); + s.execute("edit.contentAwareScale", json!({"scaleX": 90, "scaleY": 100})).map_err(|e| e.to_string())?; + times.push(t.elapsed().as_secs_f64() * 1000.0); + s.execute("edit.undo", json!({})).map_err(|e| e.to_string())?; + } + times.sort_by(f64::total_cmp); + let (p50, max) = (times[times.len() / 2], times[times.len() - 1]); + println!("edit.contentAwareScale {w}x{h} to 90 % width: p50 {p50:.1} ms, max {max:.1} ms ({reps} runs)"); + Ok(()) +} From 615f9d66589cae9dc1e28469aaf9b69623414eb2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 13 Oct 2026 18:48:45 +0000 Subject: [PATCH 5/6] fix(algo): seam carving review follow-ups; infinite protection protects in the height pass From the second half of the adversarial review: - Correction to the previous commit: mapping energies that aren't numbers to +inf also changes output where the original computed NaN energies from NaN-free input (infinite samples at the border or next to each other, overflowing differences). The original's choice there went through NaN costs; keeping it would bring NaN back into the seam search, whose sign and payload aren't consistent across builds and wasm. So the contract is: bit-identical for every input whose energy stays a number (all finite images without overflow), deterministic everywhere else. infinite_samples_carve_deterministically pins it. - The height pass resampled the raw protection map, so an infinite value (or neighbours whose difference overflows) became NaN, which protects nothing: a row protected with +inf was carved away while 1.0 kept it. Where the plain resample gives NaN, the map clamped to 0..=1 is resampled instead (resample_protection); every other value is unchanged. infinite_protection_protects_in_both_passes failed before. - Values past w x h x ch are ignored through both passes. - Docs: row_costs is what recomputes pixels; the reduced-height search cuts the work 8-12 times at 24 MP, not about four; bench_seam's hash is FNV-style over 32-bit words. Carver::new reserves its index. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LELc5BQzgV5dA7dxdMejkK --- crates/algo/examples/bench_seam.rs | 4 +- crates/algo/src/seam.rs | 99 ++++++++++++++++++++++++------ 2 files changed, 83 insertions(+), 20 deletions(-) diff --git a/crates/algo/examples/bench_seam.rs b/crates/algo/examples/bench_seam.rs index e427a6b270c..d25df5d8de1 100644 --- a/crates/algo/examples/bench_seam.rs +++ b/crates/algo/examples/bench_seam.rs @@ -1,8 +1,8 @@ //! Timing of Content-Aware Scale's seam carving alone (no document plumbing), on a synthetic //! photo-like RGBA image: perf scenario P28's 24 MP width change (#211), the same image's height //! (the transposed pass) and two images short enough for the exact full-resolution seam search. -//! Prints an FNV-1a hash of each output's bits, so a speed-up can be checked to choose exactly the -//! same seams. +//! Prints an FNV-style hash of each output's bits (over 32-bit words), so a speed-up can be checked +//! to choose exactly the same seams. //! `cargo run --release -p photocraft-algo --example bench_seam [reps] [case filter]` use std::time::Instant; diff --git a/crates/algo/src/seam.rs b/crates/algo/src/seam.rs index 59e235bc059..b85fba5babe 100644 --- a/crates/algo/src/seam.rs +++ b/crates/algo/src/seam.rs @@ -9,9 +9,10 @@ //! //! A protect map (`0..=1`, e.g. an alpha channel or detected skin tones) adds a large energy so //! seams avoid protected pixels. Buffers are interleaved `w × h × ch` normalised floats of any -//! colour model and depth (alpha is carried like any other channel). Deterministic: a NaN sample -//! gives its pixels the highest energy and NaN protection protects nothing, so no NaN (whose -//! payload arithmetic does not keep consistently across builds) ever reaches the seam search. +//! colour model and depth (alpha is carried like any other channel). Deterministic on every +//! platform: an energy that isn't a number (from NaN samples, or infinite ones next to each other +//! or at the border) is the highest energy, and NaN protection protects nothing, so no NaN (whose +//! sign and payload arithmetic does not keep consistently across builds) reaches the seam search. use photocraft_raster::{Cancelled, Interrupt}; @@ -24,9 +25,10 @@ fn protection(p: f32) -> f32 { if p.is_nan() { 0.0 } else { p.clamp(0.0, 1.0) * PROTECT_ENERGY } } -/// Keep full horizontal detail while reducing the height used to find vertical seams. At a -/// 24 MP working size this cuts the dynamic-programming work by about four times without -/// quantising the output pixels or changing the requested output dimensions. +/// Keep full horizontal detail while reducing the height used to find vertical seams. On a +/// 6000×4000 image this cuts the dynamic-programming work eight times for a width change (4000 +/// rows to 500) and twelve times for a height change, without quantising the output pixels or +/// changing the requested output dimensions. const SEAM_SEARCH_MAX_HEIGHT: usize = 512; const PROXY_SHRINK_MIN_HEIGHT: usize = 2_048; const PROXY_SHRINK_MIN_SEAMS: usize = 64; @@ -56,7 +58,8 @@ pub fn energy(w: usize, h: usize, ch: usize, img: &[f32]) -> Vec { /// [`energy`] of pixel `x` of row `y` of a `cw`-wide, `h`-tall image whose pixel `xx` of row `yy` /// is column `col(xx, yy)` of `img` (`w` pixels per row). Shared by the full map and the carver's -/// per-seam updates, so both give bit-identical values. NaN samples give the highest energy. +/// per-seam updates, so both give bit-identical values. An energy that isn't a number is the +/// highest energy (`+inf`). #[allow(clippy::too_many_arguments)] #[inline] fn energy_at(img: &[f32], w: usize, cw: usize, h: usize, ch: usize, x: usize, y: usize, col: impl Fn(usize, usize) -> usize) -> f32 { @@ -122,9 +125,9 @@ struct Dp { /// its path cost and where that path came from (0 = up-left, 1 = up, 2 = up-right). Ties go to /// the pixel straight up, then up-left, then up-right. The cost doesn't depend on the tie-break /// and the direction doesn't depend on `e`, so the seam can be traced back from the costs alone. -/// The full pass's edges, [`Dp::update`] and [`Dp::seam`] use it, and the full pass's interior -/// repeats it exactly, so every way of filling the map gives the same bits (costs are never NaN: -/// see [`energy_at`] and [`protection`]). +/// [`row_costs`] uses it at the ends of a row and repeats its selection in between, and +/// [`Dp::seam`] traces seams with it, so every way of filling the map gives the same bits (costs +/// are never NaN: see [`energy_at`] and [`protection`]). #[inline] fn cell(up: &[f32], cw: usize, x: usize, e: f32) -> (f32, u8) { let (b, d) = if x == 0 { @@ -193,8 +196,8 @@ impl Dp { /// `seam[y-1..=y+1]` to the rightmost, which covers those pixels too. Every other pixel needs /// recomputing only if a parent's cost changed, so the work follows the changed costs down /// the map and narrows wherever they settle, instead of covering the whole map. Recomputed - /// pixels go through [`cell`], so the map matches a [`Dp::full`] pass over the same energy - /// bit for bit. + /// pixels go through [`row_costs`], like a [`Dp::full`] pass's, so the map matches one over + /// the same energy bit for bit. fn update(&mut self, rows: Rows, energy: &[f32], seam: &[usize]) { let (cw, h) = (rows.cw, rows.h()); if cw == 0 || h == 0 || seam.len() < h { @@ -293,7 +296,10 @@ impl<'a> Carver<'a> { *e += protection(p); } } - let idx = (0..h).flat_map(|_| (0..w).map(|x| u32::try_from(x).unwrap_or(u32::MAX))).collect(); + let mut idx = Vec::with_capacity(w * h); + for _ in 0..h { + idx.extend((0..w).map(|x| u32::try_from(x).unwrap_or(u32::MAX))); + } let off = vec![0; h]; let mut dp = Dp::default(); dp.full(Rows { stride: w, cw: w, off: &off }, &e); @@ -483,7 +489,12 @@ pub fn carve_width(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<& pub fn carve_width_with(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<&[f32]>, new_w: usize, ctl: &Interrupt) -> Result, Cancelled> { let new_w = new_w.max(1); // Nothing to carve: no pixels or channels, or fewer values than the size says. - if new_w == w || unusable(w, h, ch, img) { + if unusable(w, h, ch, img) { + return Ok(img.to_vec()); + } + // Values past the size are not part of the image. + let img = img.get(..w * h * ch).unwrap_or(img); + if new_w == w { return Ok(img.to_vec()); } // A protection map that doesn't cover the image protects nothing. @@ -648,6 +659,7 @@ pub fn carve_with( if unusable(w, h, ch, img) { return Ok(img.to_vec()); } + let img = img.get(..w * h * ch).unwrap_or(img); let protect = protect.filter(|p| p.len() >= w * h); // Split progress between the passes by their seam counts. let (sw, sh) = (new_w.abs_diff(w) as f32, new_h.abs_diff(h) as f32); @@ -658,14 +670,30 @@ pub fn carve_with( if new_h == h { return Ok(wide); } - // Protection follows the width change by plain resampling (it only steers seams). - let prot_t = protect.map(|p| transpose(new_w, h, 1, &resize_bilinear(w, h, 1, p, new_w, h))); + let prot_t = protect.map(|p| transpose(new_w, h, 1, &resample_protection(w, h, p, new_w))); let t = transpose(new_w, h, ch, &wide); let second = |f: f32| ctl.progress(split + f * (1.0 - split)); let tall = carve_width_with(h, new_w, ch, &t, prot_t.as_deref(), new_h, &Interrupt::new(&cancel, &second))?; Ok(transpose(new_h, new_w, ch, &tall)) } +/// The protection map `p` (`w × h`) for the height pass, after the width changed to `new_w`: +/// plainly resampled (it only steers seams). Where values out of `0..=1` resample to NaN +/// (infinities, or neighbours whose difference overflows), the map clamped to `0..=1` (NaN to 0) +/// resampled instead, so an infinite protection still protects. +fn resample_protection(w: usize, h: usize, p: &[f32], new_w: usize) -> Vec { + let mut out = resize_bilinear(w, h, 1, p, new_w, h); + if out.iter().any(|v| v.is_nan()) { + let clamped: Vec = p.iter().map(|&v| if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) }).collect(); + for (v, c) in out.iter_mut().zip(resize_bilinear(w, h, 1, &clamped, new_w, h)) { + if v.is_nan() { + *v = c; + } + } + } + out +} + /// Plain bilinear resize (the non-content-aware part of the Amount blend). pub fn resize_bilinear(w: usize, h: usize, ch: usize, img: &[f32], nw: usize, nh: usize) -> Vec { let Some(len) = nw.checked_mul(nh).and_then(|n| n.checked_mul(ch)) else { @@ -726,7 +754,7 @@ mod tests { /// The straightforward implementation the per-seam carver replaced (full energy map, fresh /// seam search and a new buffer per seam), kept as the oracle for `carver_matches_reference`. mod reference { - use super::super::{protection, resize_bilinear, transpose}; + use super::super::{protection, resample_protection, transpose}; pub(super) fn energy(w: usize, h: usize, ch: usize, img: &[f32]) -> Vec { let mut e = vec![0.0f32; w * h]; @@ -879,7 +907,7 @@ mod tests { if new_h == h { return wide; } - let prot_t = protect.map(|p| transpose(new_w, h, 1, &resize_bilinear(w, h, 1, p, new_w, h))); + let prot_t = protect.map(|p| transpose(new_w, h, 1, &resample_protection(w, h, p, new_w))); let t = transpose(new_w, h, ch, &wide); let tall = carve_width(h, new_w, ch, &t, prot_t.as_deref(), new_h); transpose(new_h, new_w, ch, &tall) @@ -1002,6 +1030,41 @@ mod tests { assert_eq!(carve(10, 5, 1, &img, Some(&[0.0; 3]), 4, 3), carve(10, 5, 1, &img, None, 4, 3)); assert_eq!(carve(10, 5, 3, &[0.5; 20], None, 4, 5), vec![0.5; 20]); assert_eq!(carve_width(usize::MAX, 2, 4, &[0.5; 8], None, 1), vec![0.5; 8]); + // Values past the size are ignored, through both passes. + let long = noise(20, 7, 4); + assert_eq!(carve(5, 3, 1, &long, None, 3, 3), carve(5, 3, 1, &long[..15], None, 3, 3)); + assert_eq!(carve(5, 3, 1, &long, None, 5, 2), carve(5, 3, 1, &long[..15], None, 5, 2)); + } + + /// Infinite samples, and finite ones whose differences overflow, give energies that aren't + /// numbers; those are the highest energy (pinned deliberately: the code before NaN-free costs + /// fed NaN to the seam search and chose differently). + #[test] + fn infinite_samples_carve_deterministically() { + let inf = f32::INFINITY; + assert_eq!(carve(2, 1, 1, &[inf, 0.5], None, 1, 1), [0.5]); + assert_eq!(carve(2, 1, 1, &[f32::MAX, f32::MAX], None, 6, 1), [f32::MAX, inf, inf, inf, inf, f32::MAX]); + let mut img = noise(30 * 20 * 3, 255, 41); + img.iter_mut().step_by(11).for_each(|v| *v = inf); + img.iter_mut().skip(4).step_by(23).for_each(|v| *v = -inf); + let out = carve(30, 20, 3, &img, None, 21, 14); + assert_eq!(out.len(), 21 * 14 * 3); + assert_eq!(out, carve(30, 20, 3, &img, None, 21, 14)); + } + + /// Infinite protection protects like full protection in the height pass too, where the map + /// is resampled (and an infinity alone would resample to NaN). + #[test] + fn infinite_protection_protects_in_both_passes() { + let (w, h) = (6, 6); + let img: Vec = (0..w * h).map(|i| (i * 7 % 5) as f32 / 4.0).collect(); + let row = |v: f32| (0..w * h).map(|i| if i / w == 2 { v } else { 0.0 }).collect::>(); + let (full, inf) = (row(1.0), row(f32::INFINITY)); + for (nw, nh) in [(6, 3), (4, 3), (3, 6)] { + assert_eq!(carve(w, h, 1, &img, Some(&inf), nw, nh), carve(w, h, 1, &img, Some(&full), nw, nh), "{nw}x{nh}"); + } + let kept = carve(w, h, 1, &img, Some(&inf), 6, 3); + assert!(kept.chunks(6).any(|r| r == &img[12..18]), "the protected row survives"); } /// A cancel that arrives after the seam search, during the tall-image rebuild, still stops From e4dd35ce23550bd62b7103bea7e6d65c5d1b1bb1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 13 Oct 2026 19:00:14 +0000 Subject: [PATCH 6/6] docs: Content-Aware Scale (P28) measured within its budget docs/content-aware-scale-performance.md records what changed, the exactness contract (bit-identical wherever the energy stays a number; NaN and infinities now deterministic), and interleaved before/after timings on a 4-core VM: the carve of P28's 24 MP photo 2013 -> 556 ms, the P28 row 3281 -> 1639 ms against its 3 s budget, smaller images 1.65-2.3x faster, peak memory unchanged or lower. gaps.md G2 and target-app-parity.md get the dated measurement; budgets.toml's P28 comment says the target is met. Its enforce flag and the committed baseline stay as they are until the reference machine reruns cargo xtask perf --update-baseline. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LELc5BQzgV5dA7dxdMejkK --- docs/content-aware-scale-performance.md | 138 ++++++++++++++++++++++++ docs/gaps.md | 14 ++- docs/target-app-parity.md | 12 ++- perf/budgets.toml | 2 +- 4 files changed, 162 insertions(+), 4 deletions(-) create mode 100644 docs/content-aware-scale-performance.md diff --git a/docs/content-aware-scale-performance.md b/docs/content-aware-scale-performance.md new file mode 100644 index 00000000000..5d15702a51d --- /dev/null +++ b/docs/content-aware-scale-performance.md @@ -0,0 +1,138 @@ +# Content-Aware Scale seam carving (2026-10-13) + +Perf scenario P28 ([#211](https://github.com/storytold/photocraft/issues/211)) scales a 24 MP +photo to 90 % width with Edit › Content-Aware Scale. Its budget is 3 s. + +- The committed baseline (2026-10-05) records 954 s. That predates the per-seam energy updates + and the reduced-height seam search already in `crates/algo/src/seam.rs`. +- Before this change, the row measured 3.3 s on the machine below. +- After it, the row measures 1.6 s and the carve itself is 3.6 times faster. The output is the + same. + +## What changed + +All changes are in `crates/algo/src/seam.rs`. The command, its parameters and its output are +unchanged. + +- **The seam search keeps its path-cost map across seams.** + - The search is the dynamic programme of Avidan and Shamir (2007). Before, it refilled the whole + map for every seam: for P28, 600 serial passes over about 3 M cells. + - After a removal, `Dp::update` recomputes row by row only two kinds of pixel: those next to the + seam, whose energies or parents changed, and those with a parent whose cost actually changed + (compared bit for bit). Nothing else can change, so the map stays identical to a full pass. + - On the bench images this recomputes 1.3 % of the map per seam on the reduced-height search, + and 6–10 % on the full-resolution one. 98–99 % of the recomputed pixels do change, so the work + is the removed seam's basin, not slack in the bounds. + - Directions are no longer stored. The seam is traced back from the costs with the same tie + rules (`cell`). Rows are computed by one shared, vectorised kernel (`row_costs`). +- **The carver moves no pixels.** + - It borrows the image, keeps each remaining pixel's source column (`u32`), and reads energy + neighbours and the result through it. + - A removal shifts whichever side of the seam is shorter, in three 4-byte per-pixel buffers + (index, energy, cost). Before, it shifted everything right of the seam in up to four buffers, + including the 16-byte RGBA pixels and, on the tracked paths, an 8-byte index. + - The image is no longer copied. +- **The full-resolution stages run in parallel over rows.** These are the tall-image proxy build, + its full-resolution rebuild (runs copied between removed columns), the height pass's transposes + (blocked) and the plain resample used by Amount. + +## Exactness + +**Inputs whose energy stays a number** (every finite image without overflow) produce output that +is bit-identical to the previous code. These tests pin it: + +- `output_bits_are_pinned`, for images under 2048 rows. +- `tall_proxy_output_bits_are_pinned`, for the reduced-height search. It was pinned from the + previous code before any change. +- `carver_matches_reference`, which runs 400 random cases against the original straightforward + implementation. +- `incremental_dp_matches_full_dp`, which after every removal checks the kept map, the seam, the + energy and the pixels against a recomputation from scratch. +- The hashes of the four `bench_seam` outputs. + +**An adversarial review** compared the previous and new code side by side over more than 37 000 +generated cases. Inputs included huge values, denormals, -0.0, out-of-range protection, enlarging +past 2× and proxy-size images. No difference appeared on any input whose energy stays a number. + +**NaN and infinities** are now deterministic on every platform: + +- An energy that isn't a number is the highest energy (`+inf`). Such energies come from NaN + samples, from infinite samples at the border or next to each other, and from overflowing + differences. +- NaN protection protects nothing. + +Before, these inputs fed NaN to the seam search. The chosen seam then depended on NaN payloads, +which arithmetic does not keep consistently across builds or on wasm. `nan_payloads_do_not_steer_seams` +and `infinite_samples_carve_deterministically` pin the new behaviour. + +**The height pass now keeps infinite protection.** It resamples the protection map; where that +gives NaN, the map clamped to 0..=1 is resampled instead. Before, a row protected with `+inf` +was carved away while one protected with `1.0` was kept. + +**Degenerate inputs now return early instead of panicking.** These are no channels, an empty +width with a height change, and images or protection maps shorter than their size. + +## Measurements + +**Machine and method:** + +- 4-vCPU cloud VM (Intel Xeon 2.1 GHz, Linux, no GPU), release builds. +- The VM's speed drifts by about 20 % over time, so before and after binaries ran interleaved in + the same window. Reported values are p50 with the [min–max] range. + +**The carver alone:** + +- Command: `cargo run --release -p photocraft-algo --example bench_seam`. +- Input: a synthetic photo-like RGBA image. +- Five interleaved rounds; the output hashes were identical in every run. + +| Case | Before | After | Speed-up | +|---|---|---|---| +| 24 MP to 90 % width (P28's carve, reduced-height search) | 2013 ms [1958–2149] | 556 ms [542–623] | 3.6× | +| 24 MP to 90 % height (transposed) | 2639 ms [2617–2809] | 993 ms [967–1017] | 2.7× | +| 5.4 MP to 90 % width (full-resolution search) | 1548 ms [1514–1648] | 677 ms [664–719] | 2.3× | +| 1.5 MP to 70 % width (full-resolution search) | 671 ms [658–766] | 406 ms [376–421] | 1.65× | + +**The P28 row:** + +- Command: `perf_scenarios --cpu --only "Content-Aware Scale"`. +- It also times reading the layer, the job and writing the result back. +- Five interleaved rounds, n = 1 per run: + +| P28 row | Before | After | +|---|---|---| +| Time | 3281 ms [3178–3364] | 1639 ms [1503–1728] | +| Peak RSS | 1368–1386 MB | 1305–1367 MB | + +`cargo run --release -p photocraft-engine --example bench_content_aware_scale` times the same +command without building the UI crate. After the change, one run split as follows: + +| Stage | Time | +|---|---| +| Reading the layer region | about 0.3 s | +| The carve | about 0.5 s | +| Writing the result back, with the undo step | about 0.2 s | + +**Memory inside the carver** is now 12 bytes per pixel. Before, it was the image copy (4 bytes per +channel), the energy and the stored directions, plus protection and an 8-byte index where used. + +- The only case that uses more is a one-channel shrink without protection: 9 → 12 bytes per pixel. + The review measured its peak 1.17× higher. +- Every other case uses less. + +## Limits and what is still open + +- **The scorecard and enforcement.** The scorecard keeps showing the 2026-10-05 baseline until + `cargo xtask perf --update-baseline` runs on the reference machine. `enforce` stays false for + P28 until then. +- **The rest of the P28 row** is now mostly plumbing outside the carver. `Surface::read_region` + converts the 24 MP layer pixel by pixel on one thread, and `write_region` also runs on one + thread. +- **Full-resolution searches.** Enlarging still runs them, since only shrinking tall images uses + the reduced-height search. The review measured a 24 MP 1 % enlarge going from 7.0 s to 1.8 s on a + loaded machine. What remains per seam is the removed seam's basin in the cost map (serial, row by + row) and the row shifts. +- **A worst case.** When every seam hugs the right edge of a one-sided smooth ramp, the old code + shifted nothing, but the new code's cost changes cover almost the whole map. The review measured + that case 1.3–1.5× slower than before. No other input it tried was slower. +- **wasm** builds run the same code on one thread. diff --git a/docs/gaps.md b/docs/gaps.md index 23b37512355..580a094f41f 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -200,10 +200,19 @@ what an agent can't finish alone. default small blur and the 36 MP saturated-field gain are inconclusive. [Method and full ranges](tilt-shift-performance.md). Native GUI latency remains unmeasured; no scorecard budget or parity percentage is changed by this work. +- **Measured progress (2026-10-13):** Content-Aware Scale (P28) keeps its seam search across + seams and moves no pixels. On a 4-core cloud VM (CPU, interleaved runs), the carve of P28's + 24 MP photo to 90 % width takes 556 ms instead of 2013 ms (3.6×), and the whole P28 row takes + 1.64 s instead of 3.28 s, within its 3 s budget. Smaller images on the full-resolution search + are 1.65–2.3× faster. Output is bit-identical wherever the energy stays a number (pinned + hashes); NaN and infinities are now deterministic. The scorecard keeps the 2026-10-05 + baseline's 954 s, which predates the per-seam energy updates and the reduced-height search, + until the reference machine reruns it. Most of the row is now `read_region`/`write_region` + plumbing. [Method and ranges](content-aware-scale-performance.md). - **Missing:** 22 of 25 budgeted scenarios are over budget (baseline 2026-10-05, a heavily loaded machine): layer move with styles 321 ms p50 against 25 ms, opacity change 276 ms against 20 ms, paste 12 MP 1.2 s against 100 ms, layer move on 15000×10000 16-bit 2.7 s, - Content-Aware Scale 24 MP 954 s against 3 s, Select Subject 559 ms against 100 ms; the + Content-Aware Scale 24 MP 954 s against 3 s (older code; now met, see above), Select Subject 559 ms against 100 ms; the 150-layer nudge crashes the GPU compositor (P12); menus slow with thousands of layers (#2460); old machines lag (#2687). - **Estimate:** 200–350 h. Serial in places (compositor architecture). @@ -255,6 +264,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | G2: Content-Aware Scale (P28) measured: carve 2013 → 556 ms, row 3.28 → 1.64 s on a 4-core VM, output unchanged; baseline, budgets and estimate unchanged | | 2026-10-13 | minor | G4: minimum inputs in Shape Dynamics and Transfer follow their Control (#3825, partial); no readiness percentage or estimate changed | | 2026-10-12 | minor | G5: Free Transform options bar H/V skew fields done | | 2026-10-12 | minor | G11: `.atn` import maps 112 events (Select and Mask, Spatter, Ripple, Crystallize, Pattern Fill, mask targeting, Step Backward, points, Bitmap) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f6209c58db3..e9a27beac99 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # PhotoCraft vs Adobe Photoshop: target-app parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (`.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-13 · **Change:** minor (Content-Aware Scale measurements added; 2026-10-12: `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment) · **Target:** Adobe Photoshop 2026 The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". The one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md); @@ -367,6 +367,15 @@ The transform also corrects f32 envelope errors past coordinate 4096, including distances at selected pixels. The parallel path needs an additional four bytes per pixel; see [measurements, correctness and limits](selection-distance-performance.md). +2026-10-13: Content-Aware Scale keeps its seam search's path costs across seams (recomputing +only the removed seam's basin) and no longer moves pixels. On a 4-core cloud VM (CPU, release, +interleaved runs) the carve of P28's 24 MP photo to 90 % width takes 2013 → 556 ms (3.6×), the +same image's height 2639 → 993 ms, and full-resolution searches 1.65–2.3× less time. The P28 +row with its document plumbing takes 3.28 → 1.64 s, within its 3 s budget. Output bits are +unchanged wherever the energy stays a number (pinned hashes, reference comparison, a 37 000-case +differential review); NaN and infinities are now deterministic. The committed baseline (954 s, +older code) is unchanged until the reference machine reruns it; see [method and limits](content-aware-scale-performance.md). + **Bottom line.** Two days after 0.2.0 we had merged ~96 PRs and closed ~48 issues, but **real Photoshop parity is still well below 50%**. The biggest gaps are AI, missing tools, professional workflow depth and the plug-in ecosystem. Most fixes since 0.2.0 have passed our tests but have @@ -563,6 +572,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | Date | Change | Summary | |---|---|---| +| 2026-10-13 | minor | Added measured Content-Aware Scale gains (P28 under its budget on a 4-core VM, not yet in the baseline); percentages and budgets unchanged | | 2026-10-12 | minor | Free Transform options bar H/V skew fields; percentages unchanged | | 2026-10-12 | minor | `.atn` import: 112 events mapped (TrueGrit Texture Supply sets play end to end); percentages unchanged | | 2026-10-12 | minor | Photoshop Actions `.atn` load and save (90 events mapped both ways); percentages unchanged | diff --git a/perf/budgets.toml b/perf/budgets.toml index a95c1c83dc8..348be1d65f7 100644 --- a/perf/budgets.toml +++ b/perf/budgets.toml @@ -342,7 +342,7 @@ issue = 211 bench = "perf_scenarios" row = "Content-Aware Scale 24 MP to 90 % width" budget_ms = 3000 -enforce = false # over budget in the 2026-10-05 baseline +enforce = false # 2026-10-13: met on a 4-core VM (CPU), row 3.3 s -> 1.6 s (docs/content-aware-scale-performance.md); enforce once the baseline is refreshed [[scenario]] id = "P29"