diff --git a/crates/algo/examples/bench_seam.rs b/crates/algo/examples/bench_seam.rs new file mode 100644 index 00000000000..50225c4b501 --- /dev/null +++ b/crates/algo/examples/bench_seam.rs @@ -0,0 +1,32 @@ +//! Timing and output hash for Content-Aware Scale's seam carving core (P28). +//! +//! `cargo run --release -p photocraft-algo --example bench_seam [width height new_width channels]` +//! +//! Prints the carve time and an FNV-1a hash of the output's raw f32 bits, so two builds can be +//! compared with `cmp`-level strictness without writing tens of megabytes of pixels to disk. +use std::time::Instant; + +fn main() { + let a: Vec = std::env::args().skip(1).collect(); + let num = |i: usize, d: usize| a.get(i).and_then(|s| s.parse().ok()).unwrap_or(d); + let (w, h, new_w, ch) = (num(0, 6000), num(1, 4000), num(2, 5400), num(3, 4)); + if !(1..=4).contains(&ch) { + eprintln!("channels must be 1..=4"); + std::process::exit(2); + } + // Deterministic photo-ish content: gradients with fine detail, so the energy map carries + // structure instead of one flat value per row. + let img: Vec = (0..w * h) + .flat_map(|i| { + let (x, y) = ((i % w) as f32, (i / w) as f32); + let d = ((x * 0.13).sin() * (y * 0.07).cos()).abs() * 0.3; + [(x / w as f32) * 0.6 + d, (y / h as f32) * 0.9 - d, d, 1.0].into_iter().take(ch) + }) + .collect(); + let t = Instant::now(); + let out = photocraft_algo::seam::carve_width(w, h, ch, &img, None, new_w); + let ms = t.elapsed().as_secs_f64() * 1e3; + let hash = + out.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, v| v.to_bits().to_le_bytes().iter().fold(h, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3))); + println!("{w}x{h}x{ch} -> {new_w}: {ms:.1} ms, {} samples, fnv {hash:016x}", out.len()); +} diff --git a/crates/algo/src/seam.rs b/crates/algo/src/seam.rs index 97619c7406c..0cbd9a66a2b 100644 --- a/crates/algo/src/seam.rs +++ b/crates/algo/src/seam.rs @@ -359,19 +359,18 @@ fn carve_width_proxy_height(w: usize, h: usize, ch: usize, img: &[f32], protect: }); let seam_count = w - new_w; - let mut carver = Carver::new(w, proxy_h, ch, proxy, proxy_protect, true); - let mut removed = Vec::with_capacity(seam_count); + // Removing a seam shifts the panel left, so a panel column is not an original one. Tracking + // the original column per pixel costs a third buffer that every seam has to shift (24 MB a + // seam at 24 MP); counting the columns already taken from that row is exact and costs a + // binary search per removed column. + let mut carver = Carver::new(w, proxy_h, ch, proxy, proxy_protect, false); + let mut removed_by_row: Vec> = vec![Vec::new(); proxy_h]; + let mut taken = 0usize; while carver.cw > new_w { ctl.check()?; - removed.push(carver.remove_seam()); - ctl.progress(removed.len() as f32 / seam_count as f32); - } - - let mut removed_by_row = Vec::with_capacity(proxy_h); - for proxy_y in 0..proxy_h { - let mut columns: Vec = removed.iter().map(|path| path[proxy_y]).collect(); - columns.sort_unstable(); - removed_by_row.push(columns); + record_removed(&mut removed_by_row, &carver.remove_seam()); + taken += 1; + ctl.progress(taken as f32 / seam_count as f32); } let mut out = Vec::with_capacity(new_w * h * ch); let mut columns = vec![0; seam_count]; @@ -403,6 +402,32 @@ fn carve_width_proxy_height(w: usize, h: usize, ch: usize, img: &[f32], protect: Ok(out) } +/// Add one seam, given in panel columns, to each row's sorted list of removed original columns. +/// For the `i`-th column already taken from a row, `o - i` is the panel column it occupied, and +/// that never decreases along the list, so the taken columns at or left of panel column `x` are a +/// prefix found by binary search. `x` plus that prefix's length is the original column, and every +/// removal the search passed is left of it, so it inserts where the search stopped. The rows are +/// independent, so they update in parallel like the pixel shift. +fn record_removed(removed_by_row: &mut [Vec], seam: &[usize]) { + // The entries are the original columns still taken from one row, sorted, so entry `i` is at + // least `i` and `o - i` cannot underflow. + let add = |(row, &x): (&mut Vec, &usize)| { + let (mut lo, mut hi) = (0, row.len()); + while lo < hi { + let mid = lo + (hi - lo) / 2; + if row[mid] - mid <= x { lo = mid + 1 } else { hi = mid } + } + row.insert(lo, x + lo); + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + removed_by_row.par_iter_mut().zip(seam.par_iter()).for_each(add); + } + #[cfg(target_arch = "wasm32")] + removed_by_row.iter_mut().zip(seam.iter()).for_each(add); +} + /// Content-aware resize of `img` to `new_w × new_h` (width first, then height by transposing). pub fn carve(w: usize, h: usize, ch: usize, img: &[f32], protect: Option<&[f32]>, new_w: usize, new_h: usize) -> Vec { // Never cancelled; the fallback is unreachable. @@ -761,6 +786,33 @@ mod tests { assert_eq!(carve_width_with(w, h, ch, &img, None, 64, &Interrupt::cancel_only(&cancelled)), Err(Cancelled)); } + /// The proxy path counts each removed original column instead of shifting an index map, so a + /// tracking and a counting carver must agree: run both side by side down to one column and + /// check every row's list after every seam (tie-heavy noise gives rows different histories; + /// 1-4 channels, with and without protection). + #[test] + fn counted_removed_columns_match_the_tracked_map() { + let cases: [(usize, usize, usize, u32, bool); 5] = + [(37, 9, 1, 2, false), (40, 12, 2, 3, true), (53, 7, 3, 255, false), (29, 16, 4, 1000, true), (64, 5, 3, 2, true)]; + for (i, &(w, h, ch, levels, prot)) in cases.iter().enumerate() { + let img = noise(w * h * ch, levels, 31 + i as u32); + let protect = prot.then(|| noise(w * h, 3, 77 + i as u32)); + let mut tracked = Carver::new(w, h, ch, img.clone(), protect.clone(), true); + let mut counted = Carver::new(w, h, ch, img, protect, false); + let mut expected: Vec> = vec![Vec::new(); h]; + let mut got: Vec> = vec![Vec::new(); h]; + while tracked.cw > 1 { + let seam = tracked.remove_seam(); + for (row, &x) in expected.iter_mut().zip(seam.iter()) { + let at = row.partition_point(|&o| o < x); + row.insert(at, x); + } + record_removed(&mut got, &counted.remove_seam()); + assert_eq!(got, expected, "case {i} after {} seams", w - tracked.cw); + } + } + } + #[test] fn enlarging_duplicates_flat_areas() { let (w, h) = (30, 8); diff --git a/docs/seam-carving-performance.md b/docs/seam-carving-performance.md new file mode 100644 index 00000000000..77fc736264e --- /dev/null +++ b/docs/seam-carving-performance.md @@ -0,0 +1,100 @@ +# Content-Aware Scale performance + +2026-10-22. Two things are recorded here: what this change saves, and a correction to the P28 row's +recorded number, which predates the seam-search proxies and reads as hundreds of times worse than +the code does today. + +## The change + +Content-Aware Scale shrinks an image by removing one seam at a time. On large images the seams are +searched on a vertically averaged copy (`carve_width_proxy_height`), and a panel column found there +is not an original column: each seam already removed has shifted the panel left. That was tracked +with an `idx` map — one `usize` per proxy pixel, built up front and shifted by every seam. + +The original column is recoverable without the map: for the `i`-th column already taken from a row, +`o - i` is the panel column it occupied, so the taken columns at or left of panel column `x` are +those with `o - i <= x`, and the original column is `x` plus that count. `o - i` never decreases +along the row's list, so that count is a binary search and the original column inserts where the +search stopped; the rows are independent and update in parallel, like the pixel shift. + +Counting it by scanning the row's list instead is a comparison per already-removed column, so its +cost grows with the square of the seam count and a deep shrink pays it on every row and every seam. +The binary search removes that term; what is left per removed column is one insert into a list of at +most `seam_count` entries, i.e. an element move rather than a comparison. + +Output is unchanged: the same original columns reach the assembly pass, in the same order, so every +pixel written is the pixel the map produced. The 4-channel cases below hash identically (FNV-1a over +the output's raw `f32` bits); the 3-channel case is unchanged within timer noise. + +## Timings + +Windows 11, Intel i5-10300H (4 cores / 8 threads), rustc 1.98.1, `--release`, default rayon pool. +The timer covers `seam::carve_width` only: document read, tile writeback, history and the undo that +follows the command are outside it. Each cell is the same binary run before and after the change, in +the same session, nothing else running. + +| Case | Before (ms) | After (ms) | Change | Output | +|---|---:|---:|---:|---| +| 4000 × 3000 → 3600, 4 ch | 1424.7 | 1132.9 | −20.5 % | identical | +| 6000 × 4000 → 5400, 4 ch | 3009.3 | 2559.4 | −15.0 % | identical | +| 7200 × 5000 → 6480, 4 ch | 4352.8 | 3766.9 | −13.5 % | identical | + +Deep shrinks, where the counting scan was quadratic, on the same machine and the same binary with +only the recording swapped (three alternating runs per side, `min`/`median`): + +| Case | Scan (ms) | Binary search (ms) | Change | Output | +|---|---:|---:|---:|---| +| 6000 × 4000 → 600, 4 ch (5 400 seams) | 16 640 / 16 757 | 13 915 / 14 066 | −16 % | identical, fnv `0f7eaa6af3cf1557` | +| 6000 × 4000 → 3000, 4 ch (3 000 seams) | 10 617 / 10 814 | 9 936 / 10 012 | −6 % | identical, fnv `1780ee9bc9077ee9` | + +The element move that remains is still linear in the row's list length, so a shrink this deep is not +down to the index map's cost yet on four cores; a rank bitvector over the row would remove it, and is +not in this change. + +The map was 24 MB next to a 36 MB pixel buffer at 24 MP, so the saving tracks how many bytes of row +the seams have to shift. A three-channel case was measured too and moved inside the timer noise, so +it is not reported as a win here. Further seam-search savings have to come from the dynamic program +itself, not from bookkeeping. + +## P28's recorded number is stale + +`perf/baseline.json` records P28 (Content-Aware Scale on 24 MP to 90 % width) as 954 192 ms from the +2026-10-05 baseline, which is why `perf/budgets.toml` carries `enforce = false` for that row. The +seam-search proxies and the per-seam energy update landed after that capture: + +| Tree | 6000 × 4000 → 5400, 4 ch | +|---|---:| +| `f5d2bcb` (the 2026-10-05 baseline commit) | 266 039 ms | +| `1104b6f` (main, plus this change) | 2 559 ms | + +`f5d2bcb` has no `PROXY_SHRINK_MIN_HEIGHT`: it carves at full height with a full energy recompute per +seam. The 954 s in the baseline was that code on a machine whose recorded load average was 226–290 +on 14 cores. The two example runs above are 104× apart (266 039 ms against 2 559 ms); that is the +seam-search core alone, and it is not the same measurement as the row's 954 s, which also includes a +document read and writeback the timer above excludes. + +The row itself is not flipped to `enforce = true` here: the budget is set for the macOS/aarch64 +machine class and only a run on that class can vouch for it. The carving core above is 2.56 s at +24 MP on a 4-core laptop CPU; the budgeted machine is faster, but the row also includes the document +read and writeback this measurement excludes. Flip it in the PR whose nightly run shows the row +under 3 s, and delete this paragraph with it. + +## Reproduce + +```sh +cargo build --release -p photocraft-algo --example bench_seam +./target/release/examples/bench_seam 6000 4000 5400 4 # width height new_width channels (1..=4) +``` + +Build the base and the changed tree with separate `CARGO_TARGET_DIR`s and run the same line in both; +the printed FNV hash of the output must match, and the millisecond figure is the row above. The +example builds deterministic gradient-plus-detail content, so two runs of the same binary agree. + +## Correctness and repository checks + +`cargo test --release -p photocraft-algo seam` passes, including `carver_matches_reference`, +`output_bits_are_pinned`, `tall_proxy_shrink_preserves_full_resolution_salient_and_protected_pixels` +and the cancellation test. `cargo fmt --all --check` and +`cargo clippy -p photocraft-algo --all-targets -- -D warnings` are clean. No command, UI or format +contract changed; `Carver`'s `track` mode is still used by the enlargement path, which needs the +original columns it was written for. diff --git a/perf/budgets.toml b/perf/budgets.toml index 83983e42065..6b264a936dc 100644 --- a/perf/budgets.toml +++ b/perf/budgets.toml @@ -359,7 +359,9 @@ 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 # 954 s in the 2026-10-05 baseline, which predates the seam-search proxies: the +# carving core is 2.6 s at 24 MP RGBA (docs/seam-carving-performance.md). Flip once a +# budgeted-class run shows the whole row under 3 s. [[scenario]] id = "P29"