diff --git a/crates/algo/examples/bench_multiband.rs b/crates/algo/examples/bench_multiband.rs index 2e18f9457e..9c2f0b55bf 100644 --- a/crates/algo/examples/bench_multiband.rs +++ b/crates/algo/examples/bench_multiband.rs @@ -77,7 +77,7 @@ fn run() -> Result<(), String> { let mut samples_ms = Vec::with_capacity(o.reps); for _ in 0..o.reps { let t0 = Instant::now(); - let output = panorama::multiband(cw, ch, &rois, &wts, levels); + let output = panorama::multiband(cw, ch, &rois, &wts, levels).map_err(|e| format!("multiband: {e}"))?; samples_ms.push(t0.elapsed().as_secs_f64() * 1000.0); std::hint::black_box(&output); } diff --git a/crates/algo/src/panorama.rs b/crates/algo/src/panorama.rs index dc44f06c1f..86e3faea08 100644 --- a/crates/algo/src/panorama.rs +++ b/crates/algo/src/panorama.rs @@ -40,9 +40,9 @@ use crate::transform::Homography; mod blend; -pub use blend::{Geometry, Photometric, RoiImage, blend_levels, multiband, photometric, seam_labels}; +pub use blend::{BAND_BUDGET, Geometry, Photometric, RoiImage, band_bytes_bound, blend_levels, multiband, photometric, seam_labels, try_multiband_batched}; #[cfg(test)] -use blend::{expand, multiband_batched, push_pull, reduce}; +use blend::{band_cost, expand, push_pull, reduce}; /// Photomerge layouts. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -929,7 +929,7 @@ mod tests { .collect() }) .collect(); - let (out, cov) = multiband(w, h, &imgs, &wts, 4); + let (out, cov) = multiband(w, h, &imgs, &wts, 4).unwrap(); let row: Vec = (0..w).map(|x| out[20 * w + x]).collect(); assert!((row[2] - 0.3).abs() < 0.02 && (row[w - 3] - 0.7).abs() < 0.02, "{row:?}"); let max_jump = row.windows(2).map(|p| (p[1] - p[0]).abs()).fold(0.0f32, f32::max); diff --git a/crates/algo/src/panorama/blend.rs b/crates/algo/src/panorama/blend.rs index 034e5ed96d..9b4be0262c 100644 --- a/crates/algo/src/panorama/blend.rs +++ b/crates/algo/src/panorama/blend.rs @@ -1,4 +1,17 @@ use super::{Normal, Placement, par_map, par_rows}; +use photocraft_raster::AllocationError; + +fn alloc_plane(len: usize) -> Result, AllocationError> { + let bytes = len.checked_mul(std::mem::size_of::()).ok_or(AllocationError::SizeOverflow)?; + let mut v = Vec::new(); + v.try_reserve_exact(len).map_err(|_| AllocationError::NotEnoughMemory { bytes })?; + v.resize(len, 0.0); + Ok(v) +} + +fn plane_len(w: usize, h: usize, ch: usize) -> Result { + w.checked_mul(h).and_then(|n| n.checked_mul(ch)).ok_or(AllocationError::SizeOverflow) +} // ---------- photometric ---------- @@ -311,29 +324,22 @@ pub fn blend_levels(w: usize, h: usize) -> usize { n } -/// `a[i] ⊕ b[i]` for every `i` (the shorter length wins, like `zip`), in parallel on native -/// targets. Purely elementwise, so the result is the serial result bit for bit. -fn par_zip(a: &[f32], b: &[f32], f: impl Fn(f32, f32) -> f32 + Sync + Send) -> Vec { +/// `a[i] = f(a[i], b[i])` for every `i` (the shorter length wins), in place and in parallel on +/// native targets. Purely elementwise, so the result is the serial result bit for bit. +fn par_zip_assign(a: &mut [f32], b: &[f32], f: impl Fn(f32, f32) -> f32 + Sync + Send) { const CHUNK: usize = 1 << 14; - let mut out = vec![0.0f32; a.len().min(b.len())]; - let fill = |o: &mut [f32], a: &[f32], b: &[f32]| { - for ((o, &a), &b) in o.iter_mut().zip(a).zip(b) { - *o = f(a, b); + let fill = |a: &mut [f32], b: &[f32]| { + for (a, &b) in a.iter_mut().zip(b) { + *a = f(*a, b); } }; #[cfg(not(target_arch = "wasm32"))] { use rayon::prelude::*; - out.par_chunks_mut(CHUNK).zip(a.par_chunks(CHUNK)).zip(b.par_chunks(CHUNK)).for_each(|((o, a), b)| fill(o, a, b)); + a.par_chunks_mut(CHUNK).zip(b.par_chunks(CHUNK)).for_each(|(a, b)| fill(a, b)); } #[cfg(target_arch = "wasm32")] - out.chunks_mut(CHUNK).zip(a.chunks(CHUNK)).zip(b.chunks(CHUNK)).for_each(|((o, a), b)| fill(o, a, b)); - out -} - -/// `f(a[i])` for every `i`, in parallel on native targets (elementwise, so bit for bit serial). -fn par_map1(a: &[f32], f: impl Fn(f32) -> f32 + Sync + Send) -> Vec { - par_zip(a, a, |x, _| f(x)) + a.chunks_mut(CHUNK).zip(b.chunks(CHUNK)).for_each(|(a, b)| fill(a, b)); } // `reduce`, `expand` and `push_pull` run one pyramid level for one image at a time, and the @@ -342,11 +348,11 @@ fn par_map1(a: &[f32], f: impl Fn(f32) -> f32 + Sync + Send) -> Vec { // the one-thread loops they replace (rows never read each other's output), so the result is // bit for bit unchanged. -pub(super) fn reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> (usize, usize, Vec) { +pub(super) fn reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> Result<(usize, usize, Vec), AllocationError> { let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); let k = [1.0f32, 4.0, 6.0, 4.0, 1.0]; // Separable 5-tap binomial, then decimate. - let mut tmp = vec![0.0f32; nw * h * ch]; + let mut tmp = alloc_plane(plane_len(nw, h, ch)?)?; par_rows(&mut tmp, nw, ch, |y, row| { let line = &src[y * w * ch..(y + 1) * w * ch]; for x in 0..nw { @@ -361,7 +367,7 @@ pub(super) fn reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> (usize, usiz } } }); - let mut out = vec![0.0f32; nw * nh * ch]; + let mut out = alloc_plane(plane_len(nw, nh, ch)?)?; par_rows(&mut out, nw, ch, |y, row| { // Each output row is five source rows added in tap order: the same sum per element as // before (`0 + k0·a + k1·b + …`), but over whole rows so it vectorises. @@ -375,21 +381,21 @@ pub(super) fn reduce(w: usize, h: usize, ch: usize, src: &[f32]) -> (usize, usiz *o /= 16.0; } }); - (nw, nh, out) + Ok((nw, nh, out)) } -pub(super) fn expand(sw: usize, sh: usize, ch: usize, src: &[f32], w: usize, h: usize) -> Vec { +pub(super) fn expand(sw: usize, sh: usize, ch: usize, src: &[f32], w: usize, h: usize) -> Result, AllocationError> { // Bilinear upsampling at half-pixel-aligned positions. - let mut out = vec![0.0f32; w * h * ch]; + let mut out = alloc_plane(plane_len(w, h, ch)?)?; // Source columns and weights depend on x only: worked out once instead of for every row. // The clamped position is never negative, so truncating is `floor` (and spares the libm call). - let cols: Vec<(usize, usize, f32)> = (0..w) - .map(|x| { - let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sw - 1) as f32); - let x0 = fx as usize; - (x0 * ch, (x0 + 1).min(sw - 1) * ch, fx - x0 as f32) - }) - .collect(); + let mut cols = Vec::new(); + cols.try_reserve_exact(w).map_err(|_| AllocationError::NotEnoughMemory { bytes: w.saturating_mul(std::mem::size_of::<(usize, usize, f32)>()) })?; + cols.extend((0..w).map(|x| { + let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sw - 1) as f32); + let x0 = fx as usize; + (x0 * ch, (x0 + 1).min(sw - 1) * ch, fx - x0 as f32) + })); par_rows(&mut out, w, ch, |y, row| { let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (sh - 1) as f32); let y0 = fy as usize; @@ -404,20 +410,20 @@ pub(super) fn expand(sw: usize, sh: usize, ch: usize, src: &[f32], w: usize, h: } } }); - out + Ok(out) } /// Fills pixels with zero `wt` from their surroundings (push-pull), so pyramid levels don't /// pull in black from outside an image. -pub(super) fn push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32]) { +pub(super) fn push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32]) -> Result<(), AllocationError> { if w <= 1 && h <= 1 { - return; + return Ok(()); } let (nw, nh) = (w.div_ceil(2), h.div_ceil(2)); // Coarse sums. A coarse row is fed by two fine rows; walking them in raster order adds each // coarse cell's (up to) four fine pixels in the order the serial scatter-add did, from zero. - let mut cpx = vec![0.0f32; nw * nh * ch]; - let mut cw = vec![0.0f32; nw * nh]; + let mut cpx = alloc_plane(plane_len(nw, nh, ch)?)?; + let mut cw = alloc_plane(plane_len(nw, nh, 1)?)?; par_rows(&mut cw, nw, 1, |cy, row| { for y in 2 * cy..(2 * cy + 2).min(h) { for (x, &a) in wt[y * w..(y + 1) * w].iter().enumerate() { @@ -454,7 +460,7 @@ pub(super) fn push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32 } } if cw.contains(&0.0) && cw.iter().any(|v| *v > 0.0) { - push_pull(nw, nh, ch, &mut cpx, &cw); + push_pull(nw, nh, ch, &mut cpx, &cw)?; } par_rows(px, w, ch, |y, row| { for x in 0..w { @@ -468,6 +474,7 @@ pub(super) fn push_pull(w: usize, h: usize, ch: usize, px: &mut [f32], wt: &[f32 } } }); + Ok(()) } /// One image's pyramid in [`multiband`]: the grid origin `(gx0, gy0)` at level 0, the Laplacian @@ -491,50 +498,89 @@ fn band_row(band: &PyramidBand, l: usize, ch: usize, py: usize) -> Option<(usize /// uses a many-core machine better than one band's row-parallel work, and one at a time made the /// usual 2–4 image Photomerge 12–36% slower on a 32-thread desktop. #[cfg(not(target_arch = "wasm32"))] -const BAND_BUDGET: usize = 5 << 30; +pub const BAND_BUDGET: usize = 5 << 30; /// Without threads the bands of a batch are built one after another anyway, so each is added as /// soon as it is built (the browser's address space is 4 GB). #[cfg(target_arch = "wasm32")] -const BAND_BUDGET: usize = 0; +pub const BAND_BUDGET: usize = 0; /// Multi-band blend of `imgs` into a `w × h` panorama (origin 0,0) with one weight map per image /// over the same grid as its ROI (`weights[i]` has `w_i × h_i` entries). Returns the colour -/// channels (`ch` per pixel) and the total coverage. -pub fn multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize) -> (Vec, Vec) { - multiband_batched(w, h, imgs, weights, levels, BAND_BUDGET) +/// channels (`ch` per pixel) and the total coverage, or an error when a buffer can't be allocated. +pub fn multiband(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize) -> Result<(Vec, Vec), AllocationError> { + try_multiband_batched(w, h, imgs, weights, levels, BAND_BUDGET, None) +} + +/// The grid an image's band is built on: its ROI grown by a margin and aligned down to the +/// coarsest level's grid, clipped to the `w × h` canvas. Returns `(x0, y0, width, height)`. +fn band_grid(im: &RoiImage, w: usize, h: usize, levels: usize) -> (i32, i32, usize, usize) { + let align = 1i32 << (levels.max(1) - 1); + let margin = align * 4; + let gx0 = ((im.x0 - margin).max(0) / align) * align; + let gy0 = ((im.y0 - margin).max(0) / align) * align; + let gx1 = (im.x0 + im.w as i32 + margin).min(w as i32); + let gy1 = (im.y0 + im.h as i32 + margin).min(h as i32); + (gx0, gy0, (gx1 - gx0).max(1) as usize, (gy1 - gy0).max(1) as usize) +} + +/// Estimated bytes of building one band: its grid's colour and weight planes about three times +/// over (the pyramids are 4/3 of a plane, and the grid copy and `expand`/`reduce` scratch come +/// on top). A safe upper bound: the build itself peaks lower. +pub(super) fn band_cost(im: &RoiImage, w: usize, h: usize, ch: usize, levels: usize) -> usize { + let (_, _, gw, gh) = band_grid(im, w, h, levels); + gw.saturating_mul(gh).saturating_mul(ch + 1).saturating_mul(4 * 3) +} + +/// An upper bound on `band_cost` (the estimate batching uses) for any ROI of `w × h` pixels on a `canvas_w × canvas_h` +/// canvas: the grid grows the ROI by the margin on both sides and aligns its start down by up to +/// `align - 1`, and never exceeds the canvas. +pub fn band_bytes_bound(w: usize, h: usize, ch: usize, levels: usize, canvas_w: usize, canvas_h: usize) -> usize { + let align = 1usize << (levels.max(1) - 1).min(30); + let margin = align.saturating_mul(4); + let extent = |n: usize, canvas: usize| n.saturating_add(margin.saturating_mul(2)).saturating_add(align).min(canvas).max(1); + extent(w, canvas_w).saturating_mul(extent(h, canvas_h)).saturating_mul(ch.saturating_add(1)).saturating_mul(4 * 3) } /// [`multiband`], building at most `budget` estimated bytes of bands at a time (at least one /// image). Each pixel still adds the bands in image order, so the result doesn't depend on it. -pub(super) fn multiband_batched(w: usize, h: usize, imgs: &[RoiImage], weights: &[Vec], levels: usize, budget: usize) -> (Vec, Vec) { +/// With `max_band_budget`, a single band estimated above it is an error instead. +pub fn try_multiband_batched( + w: usize, + h: usize, + imgs: &[RoiImage], + weights: &[Vec], + levels: usize, + budget: usize, + max_band_budget: Option, +) -> Result<(Vec, Vec), AllocationError> { let ch = imgs.first().map_or(1, |i| i.ch); let levels = levels.max(1); - let align = 1i32 << (levels - 1); + let cost = |im: &RoiImage| band_cost(im, w, h, ch, levels); + if let Some(limit) = max_band_budget { + for im in imgs { + let bytes = cost(im); + if bytes > limit { + return Err(AllocationError::NotEnoughMemory { bytes }); + } + } + } // Level sizes of the panorama. let mut sizes = vec![(w, h)]; for _ in 1..levels { let Some(&(pw, ph)) = sizes.last() else { break }; sizes.push((pw.div_ceil(2), ph.div_ceil(2))); } - let mut acc: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh * ch]).collect(); - let mut wsum: Vec> = sizes.iter().map(|&(lw, lh)| vec![0.0; lw * lh]).collect(); - let margin = align * 4; - // Each image on its ROI grown by a margin and aligned to the coarsest level's grid. - let grid = |im: &RoiImage| { - let gx0 = ((im.x0 - margin).max(0) / align) * align; - let gy0 = ((im.y0 - margin).max(0) / align) * align; - let gx1 = (im.x0 + im.w as i32 + margin).min(w as i32); - let gy1 = (im.y0 + im.h as i32 + margin).min(h as i32); - (gx0, gy0, (gx1 - gx0).max(1) as usize, (gy1 - gy0).max(1) as usize) - }; - // Building one band holds its grid's colour and weight planes about three times over: the - // pyramids are 4/3 of a plane, and the grid copy, coverage and `expand` scratch come on top. - let cost = |im: &RoiImage| { - let (_, _, gw, gh) = grid(im); - gw.saturating_mul(gh).saturating_mul(ch + 1).saturating_mul(4 * 3) - }; - let band = |k: usize| -> PyramidBand { + let mut acc: Vec> = Vec::with_capacity(sizes.len()); + let mut wsum: Vec> = Vec::with_capacity(sizes.len()); + for &(lw, lh) in &sizes { + let acc_len = lw.checked_mul(lh).and_then(|n| n.checked_mul(ch)).ok_or(AllocationError::SizeOverflow)?; + acc.push(alloc_plane(acc_len)?); + let wsum_len = lw.checked_mul(lh).ok_or(AllocationError::SizeOverflow)?; + wsum.push(alloc_plane(wsum_len)?); + } + let grid = |im: &RoiImage| band_grid(im, w, h, levels); + let band = |k: usize| -> Result { let im = &imgs[k]; let (gx0, gy0, gw, gh) = grid(im); // Each grid pixel takes the image pixel that lands on it (every image pixel lands on at @@ -543,7 +589,7 @@ pub(super) fn multiband_batched(w: usize, h: usize, imgs: &[RoiImage], weights: let (x, y) = (gx as i64 + gx0 as i64 - im.x0 as i64, gy as i64 + gy0 as i64 - im.y0 as i64); (x >= 0 && y >= 0 && (x as usize) < im.w && (y as usize) < im.h).then(|| y as usize * im.w + x as usize) }; - let mut px = vec![0.0f32; gw * gh * ch]; + let mut px = alloc_plane(plane_len(gw, gh, ch)?)?; par_rows(&mut px, gw, ch, |gy, row| { for gx in 0..gw { if let Some(i) = src_of(gx, gy) { @@ -551,15 +597,7 @@ pub(super) fn multiband_batched(w: usize, h: usize, imgs: &[RoiImage], weights: } } }); - let mut cov = vec![0.0f32; gw * gh]; - par_rows(&mut cov, gw, 1, |gy, row| { - for (gx, o) in row.iter_mut().enumerate() { - if let Some(i) = src_of(gx, gy) { - *o = im.alpha[i]; - } - } - }); - let mut wt = vec![0.0f32; gw * gh]; + let mut wt = alloc_plane(plane_len(gw, gh, 1)?)?; par_rows(&mut wt, gw, 1, |gy, row| { for (gx, o) in row.iter_mut().enumerate() { if let Some(i) = src_of(gx, gy) { @@ -567,9 +605,16 @@ pub(super) fn multiband_batched(w: usize, h: usize, imgs: &[RoiImage], weights: } } }); - let bin: Vec = par_map1(&cov, |a| if a > 0.5 { 1.0 } else { 0.0 }); - drop(cov); - push_pull(gw, gh, ch, &mut px, &bin); + // Binary coverage straight from the alpha (0 outside the image), without a coverage plane. + let mut bin = alloc_plane(plane_len(gw, gh, 1)?)?; + par_rows(&mut bin, gw, 1, |gy, row| { + for (gx, o) in row.iter_mut().enumerate() { + if let Some(i) = src_of(gx, gy) { + *o = if im.alpha[i] > 0.5 { 1.0 } else { 0.0 }; + } + } + }); + push_pull(gw, gh, ch, &mut px, &bin)?; drop(bin); // Laplacian of the colours, Gaussian of the weights. Planes move into the pyramids rather // than being copied: with one image built at a time, a copy is a serial pass over it. @@ -582,17 +627,20 @@ pub(super) fn multiband_batched(w: usize, h: usize, imgs: &[RoiImage], weights: gau.push(cwt); break; } - let (nw, nh, down) = reduce(cw, chh, ch, &cur); - let up = expand(nw, nh, ch, &down, cw, chh); - lap.push((cw, chh, par_zip(&cur, &up, |a, b| a - b))); - let (_, _, wdown) = reduce(cw, chh, 1, &cwt); + let (nw, nh, down) = reduce(cw, chh, ch, &cur)?; + let up = expand(nw, nh, ch, &down, cw, chh)?; + // The Laplacian replaces the level's colours in place (`cur - up`, elementwise). + par_zip_assign(&mut cur, &up, |a, b| a - b); + drop(up); + lap.push((cw, chh, cur)); + let (_, _, wdown) = reduce(cw, chh, 1, &cwt)?; gau.push(cwt); cw = nw; chh = nh; cur = down; cwt = wdown; } - (gx0, gy0, lap, gau) + Ok((gx0, gy0, lap, gau)) }; // Build the bands a batch at a time and add each batch before building the next. Each pixel // adds the bands in the same order as the serial loop (per level, bands one after another; @@ -601,14 +649,15 @@ pub(super) fn multiband_batched(w: usize, h: usize, imgs: &[RoiImage], weights: let mut start = 0; while start < imgs.len() { let mut end = start + 1; - let mut bytes = cost(&imgs[start]); + let c = cost(&imgs[start]); + let mut bytes = c; while let Some(im) = imgs.get(end) && bytes.saturating_add(cost(im)) <= budget { bytes = bytes.saturating_add(cost(im)); end += 1; } - let bands = par_map(end - start, |j| band(start + j)); + let bands = par_map(end - start, |j| band(start + j)).into_iter().collect::, _>>()?; for l in 0..levels { let pw = sizes[l].0; par_rows(&mut wsum[l], pw, 1, |py, row| { @@ -660,18 +709,28 @@ pub(super) fn multiband_batched(w: usize, h: usize, imgs: &[RoiImage], weights: } }); } + drop(wsum); // Collapse. // `levels ≥ 1`, so there is always a coarsest level. - let Some(mut cur) = acc.pop() else { return (vec![0.0; w * h * ch], vec![0.0; w * h]) }; + let Some(mut cur) = acc.pop() else { + let total = w.checked_mul(h).and_then(|n| n.checked_mul(ch)).ok_or(AllocationError::SizeOverflow)?; + let cov_total = w.checked_mul(h).ok_or(AllocationError::SizeOverflow)?; + return Ok((alloc_plane(total)?, alloc_plane(cov_total)?)); + }; for l in (0..levels - 1).rev() { let (pw, ph) = sizes[l]; let (sw, sh) = sizes[l + 1]; - let up = expand(sw, sh, ch, &cur, pw, ph); - cur = par_zip(&acc[l], &up, |a, b| a + b); + let up = expand(sw, sh, ch, &cur, pw, ph)?; + // Add the upsampled coarser levels into this level's accumulator (`acc + up`, in place). + let mut level = std::mem::take(&mut acc[l]); + par_zip_assign(&mut level, &up, |a, b| a + b); + drop(up); + cur = level; } // Coverage: union of the images. Rows are independent; each walks the images in order, so a // pixel sees the same sequence of `max` calls as in the serial loop. - let mut cov = vec![0.0f32; w * h]; + let cov_len = w.checked_mul(h).ok_or(AllocationError::SizeOverflow)?; + let mut cov = alloc_plane(cov_len)?; par_rows(&mut cov, w, 1, |py, row| { for im in imgs { let y = py as i64 - im.y0 as i64; @@ -688,5 +747,5 @@ pub(super) fn multiband_batched(w: usize, h: usize, imgs: &[RoiImage], weights: } } }); - (cur, cov) + Ok((cur, cov)) } diff --git a/crates/algo/src/panorama/parallel_tests.rs b/crates/algo/src/panorama/parallel_tests.rs index 77c25b0f98..a8972f32cb 100644 --- a/crates/algo/src/panorama/parallel_tests.rs +++ b/crates/algo/src/panorama/parallel_tests.rs @@ -284,13 +284,13 @@ fn reduce_and_expand_match_the_serial_code() { for (n, &(w, h)) in SIZES.iter().enumerate() { for ch in [1usize, 3, 4] { let src = noise(w * h * ch, n as u64 * 7 + ch as u64); - let (nw, nh, got) = reduce(w, h, ch, &src); + let (nw, nh, got) = reduce(w, h, ch, &src).unwrap(); let (rw, rh, want) = ref_reduce(w, h, ch, &src); assert_eq!((nw, nh), (rw, rh)); assert_eq!(bits(&got), bits(&want), "reduce {w}x{h}x{ch}"); // Expand back to the original size and to sizes that are not twice the source's. for (ew, eh) in [(w, h), (2 * nw, 2 * nh), (2 * nw - 1, 2 * nh + 1), (w + 3, h + 5)] { - let got = expand(nw, nh, ch, &want, ew, eh); + let got = expand(nw, nh, ch, &want, ew, eh).unwrap(); let want_up = ref_expand(nw, nh, ch, &want, ew, eh); assert_eq!(bits(&got), bits(&want_up), "expand {nw}x{nh}x{ch} to {ew}x{eh}"); } @@ -311,7 +311,7 @@ fn push_pull_matches_the_serial_code() { }; let px = noise(w * h * ch, 100 + n as u64); let (mut got, mut want) = (px.clone(), px); - push_pull(w, h, ch, &mut got, &wt); + push_pull(w, h, ch, &mut got, &wt).unwrap(); ref_push_pull(w, h, ch, &mut want, &wt); assert_eq!(bits(&got), bits(&want), "push_pull {w}x{h}x{ch} variant {variant}"); } @@ -350,7 +350,7 @@ fn multiband_matches_the_serial_code() { for ch in [1usize, 3] { let (imgs, wts) = rois(w, h, ch, n as u64 * 31 + ch as u64); for levels in [1usize, 2, 3, 5, 7] { - let got = multiband(w, h, &imgs, &wts, levels); + let got = multiband(w, h, &imgs, &wts, levels).unwrap(); let want = ref_multiband(w, h, &imgs, &wts, levels); assert_eq!(bits(&got.0), bits(&want.0), "colours {w}x{h}x{ch} levels {levels}"); assert_eq!(bits(&got.1), bits(&want.1), "coverage {w}x{h}x{ch} levels {levels}"); @@ -358,7 +358,7 @@ fn multiband_matches_the_serial_code() { } } // No images at all, and zero levels. - assert_eq!(multiband(9, 7, &[], &[], 3).0.len(), ref_multiband(9, 7, &[], &[], 3).0.len()); + assert_eq!(multiband(9, 7, &[], &[], 3).unwrap().0.len(), ref_multiband(9, 7, &[], &[], 3).0.len()); } /// Batching the bands (#7758) changes when they are built, not the result. Budgets from none @@ -374,7 +374,7 @@ fn multiband_batches_match_the_serial_code() { for levels in [1usize, 3, 5] { let want = ref_multiband(w, h, &imgs, &wts, levels); for &budget in &budgets { - let got = multiband_batched(w, h, &imgs, &wts, levels, budget); + let got = try_multiband_batched(w, h, &imgs, &wts, levels, budget, None).unwrap(); assert_eq!(bits(&got.0), bits(&want.0), "colours {w}x{h}x{ch} levels {levels} budget {budget}"); assert_eq!(bits(&got.1), bits(&want.1), "coverage {w}x{h}x{ch} levels {levels} budget {budget}"); } @@ -388,15 +388,60 @@ fn multiband_batches_match_the_serial_code() { #[test] fn multiband_hashes_recorded_from_the_serial_code() { let (imgs, wts) = rois(97, 61, 3, 5); - let (px, cov) = multiband(97, 61, &imgs, &wts, 5); + let (px, cov) = multiband(97, 61, &imgs, &wts, 5).unwrap(); assert_eq!(fnv(&[&px, &cov]), 0xf89a5726082ebb6c, "97x61 rgb, 5 levels"); let (imgs, wts) = rois(130, 70, 1, 9); - let (px, cov) = multiband(130, 70, &imgs, &wts, 7); + let (px, cov) = multiband(130, 70, &imgs, &wts, 7).unwrap(); assert_eq!(fnv(&[&px, &cov]), 0xb7d7ddc59d201730, "130x70 grey, 7 levels"); let wt = weights(65, 41, 3); let mut px = noise(65 * 41 * 3, 4); - push_pull(65, 41, 3, &mut px, &wt); + push_pull(65, 41, 3, &mut px, &wt).unwrap(); assert_eq!(fnv(&[&px]), 0x50ea36a84ca9a68f, "push_pull 65x41 rgb"); - let (nw, nh, r) = reduce(65, 41, 3, &px); - assert_eq!(fnv(&[&r, &expand(nw, nh, 3, &r, 65, 41)]), 0x51823acfb4206dd8, "reduce + expand 65x41 rgb"); + let (nw, nh, r) = reduce(65, 41, 3, &px).unwrap(); + assert_eq!(fnv(&[&r, &expand(nw, nh, 3, &r, 65, 41).unwrap()]), 0x51823acfb4206dd8, "reduce + expand 65x41 rgb"); +} + +#[test] +fn multiband_rejects_single_band_larger_than_budget() { + let (w, h, ch) = (97, 61, 3); + let (imgs, wts) = rois(w, h, ch, 42); + let err = try_multiband_batched(w, h, &imgs, &wts, 3, 100, Some(100)).unwrap_err(); + assert!(matches!(err, photocraft_raster::AllocationError::NotEnoughMemory { bytes } if bytes > 100)); +} + +/// [`band_bytes_bound`] covers the cost the batching estimates for any ROI, offsets and levels. +#[test] +fn band_bytes_bound_covers_the_band_cost() { + for (n, &(w, h)) in [(1usize, 1usize), (5, 3), (40, 30), (97, 61), (130, 70), (201, 129)].iter().enumerate() { + for ch in [1usize, 3, 4] { + let (imgs, _) = rois(w, h, ch, n as u64 + 3); + for levels in [0usize, 1, 2, 3, 5, 7] { + for im in &imgs { + let cost = band_cost(im, w, h, ch, levels); + let bound = band_bytes_bound(im.w, im.h, ch, levels, w, h); + assert!(bound >= cost, "{w}x{h}x{ch} levels {levels} roi {}x{} at ({}, {}): bound {bound} < cost {cost}", im.w, im.h, im.x0, im.y0); + } + } + } + } +} + +#[test] +fn multiband_checks_later_images_and_zero_limit() { + let small = RoiImage { x0: 0, y0: 0, w: 1, h: 1, ch: 1, px: vec![1.0], alpha: vec![1.0] }; + let large = RoiImage { x0: 0, y0: 0, w: 20, h: 20, ch: 1, px: vec![1.0; 400], alpha: vec![1.0; 400] }; + let limit = band_cost(&small, 40, 40, 1, 1); + let expected = band_cost(&large, 40, 40, 1, 1); + assert!(expected > limit); + let err = try_multiband_batched(40, 40, &[small.clone(), large], &[vec![1.0], vec![1.0; 400]], 1, usize::MAX, Some(limit)).unwrap_err(); + assert!(matches!(err, photocraft_raster::AllocationError::NotEnoughMemory { bytes } if bytes == expected)); + let err = try_multiband_batched(40, 40, &[small], &[vec![1.0]], 1, usize::MAX, Some(0)).unwrap_err(); + assert!(matches!(err, photocraft_raster::AllocationError::NotEnoughMemory { .. })); +} + +#[test] +fn pyramid_planes_reject_size_overflow() { + assert!(matches!(reduce(usize::MAX, 3, 3, &[]), Err(photocraft_raster::AllocationError::SizeOverflow))); + assert!(matches!(expand(1, 1, 3, &[0.0; 3], usize::MAX, 2), Err(photocraft_raster::AllocationError::SizeOverflow))); + assert!(matches!(push_pull(usize::MAX, 3, 3, &mut [], &[]), Err(photocraft_raster::AllocationError::SizeOverflow))); } diff --git a/crates/engine/src/cmd/align_cmds.rs b/crates/engine/src/cmd/align_cmds.rs index 1cddbb51cd..485c2085f6 100644 --- a/crates/engine/src/cmd/align_cmds.rs +++ b/crates/engine/src/cmd/align_cmds.rs @@ -31,7 +31,7 @@ use photocraft_raster::{Surface, to_rgba}; use serde_json::{Value, json}; use crate::commands::CommandSpec; -use crate::photo_cmds::{NO_DETAIL, plane_matrix, register, register_direct, seam_blend, seam_order, warp_placed}; +use crate::photo_cmds::{BlendOptions, NO_DETAIL, plane_matrix, register, register_direct, seam_blend, seam_order, warp_placed}; use crate::{EngineError, Result, Session}; fn bad(cmd: &str, msg: impl Into) -> EngineError { @@ -264,7 +264,8 @@ fn auto_blend(s: &mut Session, p: &Value) -> Result { let order = seam_order(&surfs, 0); // Seamless Tones and Colors also evens out exposure and colour between the layers (gain // compensation over their overlaps), as in Photomerge. - let b = seam_blend(&surfs, area, &order, seamless, seamless, None); + let opt = BlendOptions { seamless, gains: seamless, geometry: None, budget: None }; + let b = seam_blend(surfs, area, &order, opt, None)?; let weights: Vec> = b.layers.iter().map(|(_, m)| m.read_region(area)).collect(); let blended = seamless.then(|| b.composite.read_region(area)); (weights, blended) diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 4f555c2a61..1d70e3a731 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -54,7 +54,7 @@ pub use paths::{ extension, holds, holds_at, is_template, layered_extension, list_images, losses_at, portable_device_name, same_destination, same_file, saves_in_place, template_name, untitled_name, }; -pub(crate) use paths::{file_name, forward_slashes, is_windows_device_name, join, read_file, sanitize, stem, write_file}; +pub(crate) use paths::{file_name, forward_slashes, is_windows_device_name, join, read_file, read_file_limited, sanitize, stem, write_file}; use processing::{conditional_mode_change, fit_image, flatten_all_effects, flatten_all_masks, image_processor, load_files_into_stack}; use save::save_a_copy; pub(crate) use save::{SaveOpts, encode, save_doc}; diff --git a/crates/engine/src/cmd/file_cmds/paths.rs b/crates/engine/src/cmd/file_cmds/paths.rs index 928325e92f..77a2bd7dc7 100644 --- a/crates/engine/src/cmd/file_cmds/paths.rs +++ b/crates/engine/src/cmd/file_cmds/paths.rs @@ -24,6 +24,20 @@ pub(crate) fn read_file(path: &str) -> Result> { Err(EngineError::Other(format!("cannot read {path}: no file system on the web"))) } +#[cfg(not(target_arch = "wasm32"))] +/// [`read_file`] with the caller's own byte limit: a larger file is refused without being read, +/// for a caller that has to fit it into what is left of a memory budget. The `io::Error` is +/// returned as is, so the caller can tell a file over its limit (`FileTooLarge`, `OutOfMemory`) +/// from one it could not open or read. +pub(crate) fn read_file_limited(path: &str, max: u64) -> std::io::Result> { + photocraft_format::read_file_limited(std::path::Path::new(path), max) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn read_file_limited(path: &str, _max: u64) -> std::io::Result> { + Err(std::io::Error::new(std::io::ErrorKind::Unsupported, format!("cannot read {path}: no file system on the web"))) +} + #[cfg(not(target_arch = "wasm32"))] /// Every file the engine writes goes through here: crash-safe (temp file + fsync + rename, see /// [`photocraft_format::atomic`]), so a failed save never destroys the previous file. diff --git a/crates/engine/src/cmd/photo_cmds.rs b/crates/engine/src/cmd/photo_cmds.rs index 9dd7da094b..e9a98c6184 100644 --- a/crates/engine/src/cmd/photo_cmds.rs +++ b/crates/engine/src/cmd/photo_cmds.rs @@ -16,12 +16,12 @@ use photocraft_algo::transform::{Homography, Interp, warp_surface}; use photocraft_algo::warp::warp_mesh_surface; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_doc::{Document, Layer, LayerContent, LayerMask, Size}; -use photocraft_geom::Rect; +use photocraft_geom::{Rect, TILE_SIZE}; use photocraft_raster::{Surface, to_rgba}; use serde_json::{Value, json}; use crate::commands::CommandSpec; -use crate::file_cmds::{file_name, flattened, import, list_images, read_file}; +use crate::file_cmds::{file_name, flattened, flattened_checked, import, import_with_options, list_images, read_file, read_file_limited}; use crate::{EngineError, Result, Session}; /// Wall-clock timer for the `ms` fields of results (always 0 on the web, where @@ -64,11 +64,248 @@ pub(crate) struct Source { /// Loaded sources, the common pixel format and the first source's ICC profile. type Loaded = (Vec, PixelFormat, Option>>); -fn load_sources(s: &Session, p: &Value, cmd: &str) -> Result { - let mut docs: Vec<(String, Document)> = Vec::new(); +/// Pixel bytes every surface `doc` holds, counting a tile shared between surfaces once. +fn document_pixels(doc: &Document) -> usize { + let mut seen = std::collections::HashSet::new(); + let mut total = 0usize; + doc.for_each_surface(|surface| { + for (_, tile) in surface.tiles() { + if seen.insert(std::sync::Arc::as_ptr(tile) as usize) { + total = total.saturating_add(tile.len()); + } + } + }); + total +} + +/// Bytes a `w` × `h` surface allocates in `bpp`: whole 256 px tiles, as [`Surface`] stores them. +fn surface_bytes(w: usize, h: usize, bpp: usize) -> usize { + if w == 0 || h == 0 { + return 0; + } + let side = TILE_SIZE as usize; + w.div_ceil(side).saturating_mul(h.div_ceil(side)).saturating_mul(side.saturating_mul(side)).saturating_mul(bpp) +} + +/// `bytes` for people ("12 MiB", "900 KiB", "17 B"). +fn bytes_text(bytes: usize) -> String { + if bytes >= 1 << 20 { + format!("{} MiB", bytes >> 20) + } else if bytes >= 1 << 10 { + format!("{} KiB", bytes >> 10) + } else { + format!("{bytes} B") + } +} + +/// Keeps a Photomerge's sources inside the command's memory budget while they are loaded. +/// +/// `None` (Merge to HDR Pro) has no budget and loads as before. With a budget, a file is read +/// only up to what is left, its import is lowered to that remainder through the importer's own +/// preflight, and the decoded document plus the surfaces flattening allocates are charged +/// before the source is flattened. +struct SourceLoad { + budget: Option, + /// Pixels of the flattened sources kept so far. + retained: usize, + /// Sources admitted so far (for the error message). + count: usize, +} + +impl SourceLoad { + fn new(budget: Option) -> Self { + Self { budget, retained: 0, count: 0 } + } + + /// What one more source needs while it is flattened: the document's own pixels, the source + /// surface, the flatten's working and output surfaces, and a file's encoded bytes. + fn needed(&self, doc: &Document, bpp: usize, encoded: usize) -> usize { + let b = doc.bounds(); + let output = surface_bytes(b.width() as usize, b.height() as usize, bpp); + self.retained.saturating_add(encoded).saturating_add(document_pixels(doc)).saturating_add(output.saturating_mul(2)) + } + + fn exceeds(&self, cmd: &str, doc: &Document, bpp: usize, encoded: usize, budget: usize) -> EngineError { + let b = doc.bounds(); + crate::allocation::error( + cmd, + &format!( + "loading {} source image(s) plus another {}×{} one needs about {}, which exceeds the {} budget; use fewer or smaller images, or raise \"memoryBudget\"", + self.count, + b.width(), + b.height(), + bytes_text(self.needed(doc, bpp, encoded)), + bytes_text(budget) + ), + ) + } + + /// Admits and charges one `doc` flattened in `bpp`, or fails before the flatten allocates. + fn admit(&mut self, cmd: &str, doc: &Document, bpp: usize, encoded: usize) -> Result<()> { + let Some(budget) = self.budget else { + self.count += 1; + return Ok(()); + }; + if self.needed(doc, bpp, encoded) > budget { + return Err(self.exceeds(cmd, doc, bpp, encoded, budget)); + } + let b = doc.bounds(); + self.retained = self.retained.saturating_add(surface_bytes(b.width() as usize, b.height() as usize, bpp)); + self.count += 1; + Ok(()) + } + + /// What is left of the budget for the next source. + fn remaining(&self, cmd: &str) -> Result { + let Some(budget) = self.budget else { return Ok(usize::MAX) }; + budget + .checked_sub(self.retained) + .filter(|left| *left > 0) + .ok_or_else(|| crate::allocation::error(cmd, &format!("the sources loaded so far use the whole {} budget", bytes_text(budget)))) + } + + /// Reads and imports one file, bounding the encoded read and the decode by what is left. + /// `None` (Merge to HDR Pro) reads and imports as before. + fn load_file(&mut self, s: &Session, path: &str, cmd: &str) -> Result<(String, Document, usize)> { + let name = file_name(path); + if self.budget.is_none() { + let bytes = read_file(path)?; + return Ok((name.clone(), import(&name, &bytes)?, bytes.len())); + } + let left = self.remaining(cmd)?; + let bytes = read_file_limited(path, u64::try_from(left).unwrap_or(u64::MAX)).map_err(|e| match e.kind() { + // Only a file over what is left, or one memory cannot hold, is a memory error; a + // missing or unreadable file is a file error, as without a budget. + std::io::ErrorKind::FileTooLarge | std::io::ErrorKind::OutOfMemory => { + crate::allocation::error(cmd, &format!("{e} (only {} is left of the budget for a source file's bytes)", bytes_text(left))) + } + _ => EngineError::Other(format!("{path}: {e}")), + })?; + let available = left.saturating_sub(bytes.len()); + let opts = self.import_options(s, &name, &bytes, available, cmd)?; + let doc = import_with_options(&name, &bytes, &opts).map_err(|e| match e { + // The caller limit is this command's remainder, not the machine's hard limit. + EngineError::PsdHardBudget { required, limit, .. } if limit == u64::try_from(available).unwrap_or(u64::MAX) => crate::allocation::error( + cmd, + &format!( + "decoding {name} needs about {}, which exceeds the {} left; use fewer or smaller images, or raise \"memoryBudget\"", + bytes_text(usize::try_from(required).unwrap_or(usize::MAX)), + bytes_text(available) + ), + ), + e => e, + })?; + Ok((name, doc, bytes.len())) + } + + /// The importer options that lower this import to what is left after the retained sources + /// and the encoded buffer: the importer's own PSD/TIFF preflight, or a flat decode limit. + /// The decoded document and the flatten are still charged by [`Self::admit`]. + fn import_options(&self, s: &Session, name: &str, bytes: &[u8], available: usize, cmd: &str) -> Result { + use photocraft_io::ImportPreflight; + let mut opts = crate::jobs::import_options(s.prefs()); + if available == 0 { + return Err(crate::allocation::error( + cmd, + &format!("the sources already loaded and {name}'s {} encoded bytes use the whole budget", bytes_text(bytes.len())), + )); + } + let limit = u64::try_from(available).unwrap_or(u64::MAX); + match photocraft_io::import_preflight(name, bytes) { + ImportPreflight::Psd => opts.psd_max_pixel_bytes = limit, + ImportPreflight::Tiff => { + self.admit_tiff_header(name, bytes, available, cmd)?; + opts.psd_max_pixel_bytes = limit; + } + ImportPreflight::Flat => { + // The decoded buffer, the document built from it and the flatten's output are + // alive together, so keep a third of the remainder for each. + let decode = available / 3; + if decode == 0 { + return Err(crate::allocation::error( + cmd, + &format!("no room is left to decode {name} after the {} of sources already loaded", bytes_text(self.retained)), + )); + } + opts.flat_max_pixel_bytes = u64::try_from(decode).unwrap_or(u64::MAX); + } + ImportPreflight::Unbounded => { + return Err(bad( + cmd, + format!( + "{name}: this format has no memory estimate before decoding, so Photomerge cannot fit it into its budget; use a PSD, TIFF or flat raster file, or open it first and add the open document" + ), + )); + } + } + Ok(opts) + } + + /// Refuses a TIFF whose default page alone would not fit in `available`; a layered TIFF is + /// also bounded by the importer's own PSD-style preflight. + fn admit_tiff_header(&self, name: &str, bytes: &[u8], available: usize, cmd: &str) -> Result<()> { + let info = photocraft_codecs::tiff_info(bytes).map_err(|e| bad(cmd, format!("{name}: {e}")))?; + let page = info.default_page().and_then(|i| info.pages.get(i)).ok_or_else(|| bad(cmd, format!("{name}: the TIFF has no readable page")))?; + let bpp = u64::from(page.samples_per_pixel).saturating_mul(u64::from(page.bits_per_sample).div_ceil(8)); + let needed = u64::from(page.width).saturating_mul(u64::from(page.height)).saturating_mul(bpp); + let available = u64::try_from(available).unwrap_or(u64::MAX); + if needed > available { + let needed = usize::try_from(needed).unwrap_or(usize::MAX); + let available = usize::try_from(available).unwrap_or(usize::MAX); + return Err(crate::allocation::error( + cmd, + &format!( + "{name} needs about {} for its {}×{} page, which exceeds the {} left", + bytes_text(needed), + page.width, + page.height, + bytes_text(available) + ), + )); + } + Ok(()) + } +} + +/// Sources collected so far, with the common format and the first source's ICC profile. +#[derive(Default)] +struct Sources { + out: Vec, + fmt: Option, + icc: Option>>, +} + +impl Sources { + /// Flattens `d` into the common format, admitted by `load` first. + fn add(&mut self, load: &mut SourceLoad, name: String, d: &Document, encoded: usize, cmd: &str) -> Result<()> { + let source_fmt = d.pixel_format(); + // Registration and blending work in RGB, so the result is RGB. + let output_fmt = *self.fmt.get_or_insert_with(|| { + if matches!(source_fmt.mode, ColorMode::Cmyk | ColorMode::Lab | ColorMode::Multichannel) { + PixelFormat::new(ColorMode::Rgb, source_fmt.sample, true) + } else { + source_fmt + } + }); + if self.out.is_empty() && source_fmt.mode == output_fmt.mode { + self.icc = d.icc_profile.clone(); + } + let info = d.metadata.exif.as_ref().map(|e| exif::read(e)).unwrap_or_default(); + load.admit(cmd, d, output_fmt.bytes_per_pixel(), encoded)?; + self.out.push(Source { name, surf: flattened_checked(d, output_fmt, cmd)?, w: d.size.width as usize, h: d.size.height as usize, exif: info }); + Ok(()) + } +} + +/// Flattens the open documents and files named by `p` into common-format sources. With a +/// `budget`, each source is read, imported and admitted by [`SourceLoad`]; `None` (Merge to HDR +/// Pro) only flattens, as before. `cmd` names the command in errors. +fn load_sources(s: &Session, p: &Value, cmd: &str, budget: Option) -> Result { + let mut src = Sources::default(); + let mut load = SourceLoad::new(budget); if p.get("useOpenDocuments").and_then(Value::as_bool).unwrap_or(false) { for d in s.documents() { - docs.push((d.doc.name.clone(), (*d.doc).clone())); + src.add(&mut load, d.doc.name.clone(), &d.doc, 0, cmd)?; } } let paths: Vec = match p.get("paths").or_else(|| p.get("input")) { @@ -77,27 +314,14 @@ fn load_sources(s: &Session, p: &Value, cmd: &str) -> Result { _ => Vec::new(), }; for path in &paths { - let bytes = read_file(path)?; - docs.push((file_name(path), import(&file_name(path), &bytes)?)); + let (name, doc, encoded) = load.load_file(s, path, cmd)?; + src.add(&mut load, name, &doc, encoded, cmd)?; } - if docs.is_empty() { + if src.out.is_empty() { return Err(bad(cmd, "pass \"paths\" (files or a folder) or \"useOpenDocuments\": true")); } - let first = &docs[0].1; - let mut fmt = first.pixel_format(); - if matches!(fmt.mode, ColorMode::Cmyk | ColorMode::Lab | ColorMode::Multichannel) { - // Registration and blending work in RGB; like Photoshop, the result is RGB. - fmt = PixelFormat::new(ColorMode::Rgb, fmt.sample, true); - } - let icc = (first.pixel_format().mode == fmt.mode).then(|| first.icc_profile.clone()).flatten(); - let out = docs - .into_iter() - .map(|(name, d)| { - let info = d.metadata.exif.as_ref().map(|e| exif::read(e)).unwrap_or_default(); - Source { name, surf: flattened(&d, fmt), w: d.size.width as usize, h: d.size.height as usize, exif: info } - }) - .collect(); - Ok((out, fmt, icc)) + let Some(fmt) = src.fmt else { return Err(bad(cmd, "no readable image sources")) }; + Ok((src.out, fmt, src.icc)) } /// Luminance and coverage of `surf` over `area`, box-downsampled by `k`. @@ -259,20 +483,103 @@ pub(crate) fn plane_matrix(pl: &Placement, origin: (f64, f64)) -> Option usize { + let env_mb = std::env::var("PHOTOCRAFT_PHOTOMERGE_BUDGET_MB").ok(); + budget_from(p.get("memoryBudget").and_then(Value::as_u64), env_mb.as_deref(), crate::memory::physical_memory()) +} + +/// The budget: `param` (bytes) wins, then `env_mb` (a budget in MiB), then half of `ram` bytes +/// (4 GiB assumed when unknown) but at least 1 GiB. +fn budget_from(param: Option, env_mb: Option<&str>, ram: Option) -> usize { + if let Some(b) = param { + return usize::try_from(b).unwrap_or(usize::MAX); + } + if let Some(mb) = env_mb.and_then(|v| v.trim().parse::().ok()) { + return usize::try_from(mb.saturating_mul(1 << 20)).unwrap_or(usize::MAX); + } + let ram = ram.unwrap_or(4 << 30); + usize::try_from((ram / 2).max(1 << 30)).unwrap_or(usize::MAX) +} + +/// Estimated peak working memory of a Photomerge and the part of it that stays allocated while +/// bands are built (the ROIs, weights and accumulators; what is left of the budget goes to the +/// bands, see [`panorama::band_bytes_bound`]). `source_sizes` and `placed_sizes` are the source +/// and warped sizes of the placed images, `cw` × `ch` the canvas, `cc` its colour channels and +/// `bpp` its bytes per pixel. +/// +/// The peak is the largest of the phases, since each frees what the next no longer needs: warping +/// (sources and warped images), ROI conversion (ROIs, weights, warped images), the bands (ROIs, +/// accumulators and the largest band), the collapse (ROIs, accumulators and the running result), +/// the output (ROIs, blended colour, composite and output layers) and the fill (layers, composite +/// and the fill's own planes). +#[allow(clippy::too_many_arguments)] +fn estimate_photomerge_memory( + source_sizes: &[(usize, usize)], + placed_sizes: &[(usize, usize)], + cw: usize, + ch: usize, + cc: usize, + bpp: usize, + blend: bool, + fill: bool, +) -> (usize, usize) { + let px_sum = |sizes: &[(usize, usize)]| sizes.iter().map(|&(w, h)| w.saturating_mul(h)).fold(0usize, usize::saturating_add); + let sources = px_sum(source_sizes).saturating_mul(bpp); + let roi_px = px_sum(placed_sizes); + let warped = roi_px.saturating_mul(bpp); + if !blend { + return (sources.saturating_add(warped).max(warped), 0); + } + // ROI colours, alpha and the seam weights (f32 each). + let rois_weights = roi_px.saturating_mul((cc + 2) * 4); + let canvas_px = cw.saturating_mul(ch); + // The accumulator and weight-sum pyramids (4/3 of a plane each). + let accumulators = canvas_px.saturating_mul((cc + 1) * 4 * 4 / 3); + let blend_out = canvas_px.saturating_mul((cc + 1) * 4); + let output_layers = roi_px.saturating_mul(bpp + 1); + let composite = canvas_px.saturating_mul(bpp); + let fill_bytes = if fill { composite.saturating_add(24 << 20) } else { 0 }; + + // The levels `seam_blend` blends with. + let levels = panorama::blend_levels(cw, ch).min(7); + let max_band_cost = placed_sizes.iter().map(|&(w, h)| panorama::band_bytes_bound(w, h, cc, levels, cw, ch)).max().unwrap_or(0); + + let fixed_during_bands = rois_weights.saturating_add(accumulators); + let phases = [ + sources.saturating_add(warped), + rois_weights.saturating_add(warped), + fixed_during_bands.saturating_add(max_band_cost), + fixed_during_bands.saturating_add(canvas_px.saturating_mul(cc * 4)), + rois_weights.saturating_add(blend_out).saturating_add(composite).saturating_add(output_layers), + output_layers.saturating_add(composite).saturating_add(fill_bytes), + ]; + (phases.into_iter().max().unwrap_or(0), fixed_during_bands) +} + /// Splits a surface region into colour channels and coverage. -fn roi_of(surf: &Surface, area: Rect) -> RoiImage { +fn roi_of(surf: &Surface, area: Rect) -> Result { let fmt = surf.format(); let n = fmt.channels(); let cc = fmt.mode.color_channels(); - let raw = surf.read_region(area); let (w, h) = (area.width() as usize, area.height() as usize); - let mut px = Vec::with_capacity(w * h * cc); - let mut alpha = Vec::with_capacity(w * h); - for q in raw.chunks_exact(n) { - px.extend_from_slice(&q[..cc]); - alpha.push(if fmt.alpha { q[n - 1] } else { 1.0 }); + let total_px = w.checked_mul(h).and_then(|v| v.checked_mul(cc)).ok_or_else(|| crate::allocation::error("Photomerge", "ROI size overflowed"))?; + let total_alpha = w.checked_mul(h).ok_or_else(|| crate::allocation::error("Photomerge", "ROI size overflowed"))?; + let mut px = crate::allocation::capacity(total_px, "Photomerge ROI")?; + let mut alpha = crate::allocation::capacity(total_alpha, "Photomerge alpha")?; + if w > 0 && h > 0 { + let mut row = vec![0.0f32; w * n]; + for y in 0..h { + let row_rect = Rect::new(area.x0, area.y0 + y as i32, area.x1, area.y0 + y as i32 + 1); + surf.read_region_into(row_rect, &mut row); + for q in row.chunks_exact(n) { + px.extend_from_slice(&q[..cc]); + alpha.push(if fmt.alpha { q[n - 1] } else { 1.0 }); + } + } } - RoiImage { x0: area.x0, y0: area.y0, w, h, ch: cc, px, alpha } + Ok(RoiImage { x0: area.x0, y0: area.y0, w, h, ch: cc, px, alpha }) } /// Placements, source sizes and the panorama offset (for vignette removal). @@ -287,25 +594,26 @@ pub(crate) struct Blended { pub vignette: [f64; 2], } -/// Gain compensation (+ optional vignetting), seams in `order`, multi-band blending. Inputs are -/// surfaces already in panorama coordinates with alpha. `geometry` enables vignette removal. -pub(crate) fn seam_blend(warped: &[Surface], canvas: Rect, order: &[usize], seamless: bool, gains: bool, geometry: Option) -> Blended { - let n = warped.len(); - let fmt = warped.first().map_or(PixelFormat::RGBA8, Surface::format); - let mut rois: Vec = warped - .iter() - .map(|s| { - let b = s.content_bounds().intersect(&canvas); - if b.is_empty() { RoiImage { x0: 0, y0: 0, w: 0, h: 0, ch: fmt.mode.color_channels(), px: Vec::new(), alpha: Vec::new() } } else { roi_of(s, b) } - }) - .collect(); +/// How [`seam_blend`] blends: `seamless` blends the bands (else hard seams), `gains` compensates +/// exposure and colour, `geometry` enables vignette removal. `budget` is the bytes of bands built +/// at a time and the cap on any single band (an error beyond it); `None` is 5 GiB batches with +/// no cap. +pub(crate) struct BlendOptions<'a> { + pub seamless: bool, + pub gains: bool, + pub geometry: Option>, + pub budget: Option, +} + +/// Applies the photometric model (gains, vignetting) to `rois`; returns the gains and the vignette. +fn apply_photometric(rois: &mut [RoiImage], fmt: PixelFormat, geometry: Option>, seamless: bool, gains: bool) -> (Vec>, [f64; 2]) { // Photometric model in panorama coordinates relative to the canvas origin used by placements. let shifted: Option> = geometry.map(|(pl, _, off)| pl.iter().map(|p| p.translated(off.0, off.1)).collect()); let geo = match (&shifted, geometry) { (Some(pl), Some((_, sizes, _))) => Some((pl.as_slice(), sizes)), _ => None, }; - let photo = panorama::photometric(&rois, geo, seamless && gains, geo.is_some()); + let photo = panorama::photometric(rois, geo, seamless && gains, geo.is_some()); let vig = photo.vignette != [0.0, 0.0]; for (i, roi) in rois.iter_mut().enumerate() { let ch = roi.ch; @@ -335,6 +643,12 @@ pub(crate) fn seam_blend(warped: &[Surface], canvas: Rect, order: &[usize], seam } } } + (photo.gains, photo.vignette) +} + +/// Per-image seam weights (1 inside an image's seam region, else 0) over each ROI. +fn compute_seam_weights(rois: &[RoiImage], canvas: Rect, order: &[usize]) -> Vec> { + let n = rois.len(); // Seams on a ≤ 1000 px grid. let (cw, chh) = (canvas.width().max(1) as usize, canvas.height().max(1) as usize); let s = cw.max(chh).div_ceil(1000).max(1); @@ -377,8 +691,7 @@ pub(crate) fn seam_blend(warped: &[Surface], canvas: Rect, order: &[usize], seam let (lx, ly) = (x - r.x0, y - r.y0); if lx < 0 || ly < 0 || lx as usize >= r.w || ly as usize >= r.h { 0.0 } else { r.alpha[ly as usize * r.w + lx as usize] } }; - let weights: Vec> = rois - .iter() + rois.iter() .enumerate() .map(|(i, roi)| { (0..roi.w * roi.h) @@ -401,65 +714,131 @@ pub(crate) fn seam_blend(warped: &[Surface], canvas: Rect, order: &[usize], seam }) .collect() }) - .collect(); + .collect() +} + +/// The blended composite over `canvas`, its alpha the coverage. +fn build_composite(canvas: Rect, fmt: PixelFormat, blend: &[f32], cov: &[f32]) -> Surface { + let (cw, chh) = (canvas.width().max(1) as usize, canvas.height().max(1) as usize); + let cc = fmt.mode.color_channels(); + let nch = fmt.channels(); + let mut composite = Surface::new(fmt); + if cw > 0 && chh > 0 { + let mut row_comp = vec![0.0f32; cw * nch]; + for y in 0..chh { + for x in 0..cw { + let i = y * cw + x; + for c in 0..cc { + let v = blend[i * cc + c]; + row_comp[x * nch + c] = if fmt.sample == SampleType::F32 { v } else { v.clamp(0.0, 1.0) }; + } + row_comp[x * nch + nch - 1] = cov[i]; + } + let row_area = Rect::new(canvas.x0, canvas.y0 + y as i32, canvas.x1, canvas.y0 + y as i32 + 1); + composite.write_region(row_area, &row_comp); + } + composite.prune(); + } + composite +} + +/// Per input, its pixels (blended inside its seam region when `seamless`) and its seam mask. +fn build_layers( + rois: &[RoiImage], + weights: &[Vec], + canvas: Rect, + fmt: PixelFormat, + blend: &[f32], + seamless: bool, + check_cancel: Option<&dyn Fn() -> Result<()>>, +) -> Result> { + let cw = canvas.width().max(1) as usize; + let cc = fmt.mode.color_channels(); + let nch = fmt.channels(); + let mut layers = Vec::with_capacity(rois.len()); + for (roi, wt) in rois.iter().zip(weights) { + if let Some(check) = check_cancel { + check()?; + } + let area = Rect::new(roi.x0, roi.y0, roi.x0 + roi.w as i32, roi.y0 + roi.h as i32); + let mut ls = Surface::new(fmt); + let mut ms = Surface::with_default(PixelFormat::GRAY8, &[0.0]); + if !area.is_empty() && roi.w > 0 && roi.h > 0 { + let mut row_px = vec![0.0f32; roi.w * nch]; + let mut row_mask = vec![0.0f32; roi.w]; + for y in 0..roi.h { + let v = (roi.y0 - canvas.y0) as usize + y; + for x in 0..roi.w { + let u = (roi.x0 - canvas.x0) as usize + x; + let k = y * roi.w + x; + let g = v * cw + u; + let inside = wt[k] > 0.5; + for c in 0..cc { + row_px[x * nch + c] = if inside && seamless { data_clamp(blend[g * cc + c], fmt) } else { roi.px[k * cc + c] }; + } + row_px[x * nch + nch - 1] = roi.alpha[k]; + row_mask[x] = wt[k]; + } + let row_area = Rect::new(roi.x0, roi.y0 + y as i32, roi.x0 + roi.w as i32, roi.y0 + y as i32 + 1); + ls.write_region(row_area, &row_px); + ms.write_region(row_area, &row_mask); + } + } + ls.prune(); + ms.prune(); + layers.push((ls, ms)); + } + Ok(layers) +} + +/// Gain compensation (+ optional vignetting), seams in `order`, multi-band blending. Inputs are +/// surfaces already in panorama coordinates with alpha. `geometry` enables vignette removal. +pub(crate) fn seam_blend( + warped: Vec, + canvas: Rect, + order: &[usize], + opt: BlendOptions<'_>, + check_cancel: Option<&dyn Fn() -> Result<()>>, +) -> Result { + let n = warped.len(); + let fmt = warped.first().map_or(PixelFormat::RGBA8, Surface::format); + let mut rois: Vec = Vec::with_capacity(n); + for s in warped { + if let Some(check) = check_cancel { + check()?; + } + let b = s.content_bounds().intersect(&canvas); + if b.is_empty() { + rois.push(RoiImage { x0: 0, y0: 0, w: 0, h: 0, ch: fmt.mode.color_channels(), px: Vec::new(), alpha: Vec::new() }); + } else { + rois.push(roi_of(&s, b)?); + } + } + let (gains, vignette) = apply_photometric(&mut rois, fmt, opt.geometry, opt.seamless, opt.gains); + let weights = compute_seam_weights(&rois, canvas, order); // Shift ROIs to canvas-relative coordinates for the blend, and back after: a shifted copy // would hold every source's pixels twice (#7758). for r in &mut rois { r.x0 -= canvas.x0; r.y0 -= canvas.y0; } - let levels = if seamless { panorama::blend_levels(cw, chh).min(7) } else { 1 }; - let (blend, cov) = panorama::multiband(cw, chh, &rois, &weights, levels); + if let Some(check) = check_cancel { + check()?; + } + let (cw, chh) = (canvas.width().max(1) as usize, canvas.height().max(1) as usize); + let levels = if opt.seamless { panorama::blend_levels(cw, chh).min(7) } else { 1 }; + let band_budget = opt.budget.unwrap_or(panorama::BAND_BUDGET); + let (blend, cov) = panorama::try_multiband_batched(cw, chh, &rois, &weights, levels, band_budget, opt.budget)?; for r in &mut rois { r.x0 += canvas.x0; r.y0 += canvas.y0; } - let cc = fmt.mode.color_channels(); - let nch = fmt.channels(); - let mut composite = Surface::new(fmt); - { - let mut data = vec![0.0f32; cw * chh * nch]; - for i in 0..cw * chh { - for c in 0..cc { - let v = blend[i * cc + c]; - data[i * nch + c] = if fmt.sample == SampleType::F32 { v } else { v.clamp(0.0, 1.0) }; - } - data[i * nch + nch - 1] = cov[i]; - } - composite.write_region(canvas, &data); - composite.prune(); + if let Some(check) = check_cancel { + check()?; } - let layers = rois - .iter() - .zip(&weights) - .map(|(roi, wt)| { - let area = Rect::new(roi.x0, roi.y0, roi.x0 + roi.w as i32, roi.y0 + roi.h as i32); - let mut px = vec![0.0f32; roi.w * roi.h * nch]; - let mut mask = vec![0.0f32; roi.w * roi.h]; - for k in 0..roi.w * roi.h { - let (u, v) = ((roi.x0 - canvas.x0) as usize + k % roi.w, (roi.y0 - canvas.y0) as usize + k / roi.w); - let g = v * cw + u; - let inside = wt[k] > 0.5; - for c in 0..cc { - px[k * nch + c] = if inside && seamless { data_clamp(blend[g * cc + c], fmt) } else { roi.px[k * cc + c] }; - } - px[k * nch + nch - 1] = roi.alpha[k]; - mask[k] = wt[k]; - } - let mut ls = Surface::new(fmt); - if !area.is_empty() { - ls.write_region(area, &px); - } - ls.prune(); - let mut ms = Surface::with_default(PixelFormat::GRAY8, &[0.0]); - if !area.is_empty() { - ms.write_region(area, &mask); - } - ms.prune(); - (ls, ms) - }) - .collect(); - Blended { layers, composite, gains: photo.gains, vignette: photo.vignette } + let composite = build_composite(canvas, fmt, &blend, &cov); + let layers = build_layers(&rois, &weights, canvas, fmt, &blend, opt.seamless, check_cancel)?; + Ok(Blended { layers, composite, gains, vignette }) } fn data_clamp(v: f32, fmt: PixelFormat) -> f32 { @@ -494,7 +873,10 @@ fn photomerge(s: &mut Session, p: &Value) -> Result { let vignette = p.get("vignetteRemoval").and_then(Value::as_bool).unwrap_or(false); let geometric = p.get("geometricCorrection").and_then(Value::as_bool).unwrap_or(false); let fill = p.get("contentAwareFill").and_then(Value::as_bool).unwrap_or(false); - let (srcs, fmt, icc) = load_sources(s, p, cmd)?; + // Resolved before loading: the sources are flattened and retained one at a time, so the + // budget has to bound them before the first surface is allocated, not after they all exist. + let budget = photomerge_memory_budget(p); + let (mut srcs, fmt, icc) = load_sources(s, p, cmd, Some(budget))?; if srcs.len() < 2 { return Err(bad(cmd, "Photomerge needs two or more images")); } @@ -515,37 +897,57 @@ fn photomerge(s: &mut Session, p: &Value) -> Result { let t_reg = t0.ms() / 1000.0; ctx.check()?; ctx.progress(0.35, "Photomerge: warping images"); - let placed: Vec = (0..srcs.len()).filter(|&i| al.placements[i].is_some()).collect(); + let placed: Vec = (0..srcs.len()).filter(|&i| al.placements.get(i).is_some_and(Option::is_some)).collect(); // Parallel to `placed`. - let placements: Vec<&Placement> = placed.iter().filter_map(|&i| al.placements[i].as_ref()).collect(); - let failed: Vec = (0..srcs.len()).filter(|&i| al.placements[i].is_none()).map(|i| srcs[i].name.clone()).collect(); + let placements: Vec<&Placement> = placed.iter().filter_map(|&i| al.placements.get(i).and_then(Option::as_ref)).collect(); + let failed: Vec = (0..srcs.len()).filter(|&i| al.placements.get(i).is_none_or(Option::is_none)).map(|i| srcs[i].name.clone()).collect(); // Canvas: union of the placed images. let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + // Each placed image's warped extent (the bounds of its placement). + let mut extents: Vec<(f64, f64)> = Vec::with_capacity(placed.len()); for (&i, pl) in placed.iter().zip(&placements) { let b = pl.bounds(srcs[i].w as f64, srcs[i].h as f64); + extents.push((b[2] - b[0], b[3] - b[1])); x0 = x0.min(b[0]); y0 = y0.min(b[1]); x1 = x1.max(b[2]); y1 = y1.max(b[3]); } let (cw, ch) = ((x1 - x0).ceil(), (y1 - y0).ceil()); - if !(cw.is_finite() && ch.is_finite()) || cw > 30_000.0 || ch > 30_000.0 || cw * ch > 6.0e8 { + if !(cw.is_finite() && ch.is_finite()) || cw <= 0.0 || ch <= 0.0 || cw > 30_000.0 || ch > 30_000.0 || cw * ch > 6.0e8 { return Err(EngineError::Other(format!("the panorama would be {cw}×{ch} px; try another layout"))); } let canvas = Rect::new(0, 0, cw as i32, ch as i32); let offset = (-x0.floor(), -y0.floor()); - let warped: Vec = { - placed - .iter() - .zip(&placements) - .enumerate() - .map(|(k, (&i, pl))| { - ctx.check()?; - ctx.progress(0.35 + 0.25 * k as f32 / placed.len().max(1) as f32, ""); - warp_placed(&srcs[i].surf, Rect::new(0, 0, srcs[i].w as i32, srcs[i].h as i32), (0.0, 0.0), pl, offset, Interp::Bicubic) - }) - .collect::>>()? - }; + let sizes: Vec<(usize, usize)> = placed.iter().map(|&i| (srcs[i].w, srcs[i].h)).collect(); + let cc = fmt.mode.color_channels(); + let bpp = fmt.bytes_per_pixel(); + // The estimate follows the warped images (one pixel of slack for sub-pixel bounds), clipped to the canvas. + let warped_sizes: Vec<(usize, usize)> = + extents.iter().map(|&(w, h)| ((w.ceil() + 1.0).max(0.0).min(cw) as usize, (h.ceil() + 1.0).max(0.0).min(ch) as usize)).collect(); + let (est_needed, fixed_during_bands) = estimate_photomerge_memory(&sizes, &warped_sizes, cw as usize, ch as usize, cc, bpp, blend, fill); + if est_needed > budget { + let mb_est = est_needed / (1 << 20); + let mb_budget = budget / (1 << 20); + return Err(crate::allocation::error( + "Photomerge", + &format!("estimated memory of {mb_est} MiB exceeds budget of {mb_budget} MiB; use fewer or smaller images, or raise \"memoryBudget\""), + )); + } + for (i, s) in srcs.iter_mut().enumerate() { + if al.placements.get(i).is_none_or(Option::is_none) { + s.surf = Surface::new(fmt); + } + } + let mut warped: Vec = Vec::with_capacity(placed.len()); + for (k, (&i, pl)) in placed.iter().zip(&placements).enumerate() { + ctx.check()?; + ctx.progress(0.35 + 0.25 * k as f32 / placed.len().max(1) as f32, ""); + let src_rect = Rect::new(0, 0, srcs[i].w as i32, srcs[i].h as i32); + let w = warp_placed(&srcs[i].surf, src_rect, (0.0, 0.0), pl, offset, Interp::Bicubic)?; + srcs[i].surf = Surface::new(fmt); + warped.push(w); + } let t_warp = t0.ms() / 1000.0; ctx.check()?; ctx.progress(0.6, "Photomerge: blending images"); @@ -555,10 +957,12 @@ fn photomerge(s: &mut Session, p: &Value) -> Result { let ref_pos = placed.iter().position(|&i| i == al.reference).unwrap_or(0); if blend { let pls: Vec = placements.iter().map(|p| (*p).clone()).collect(); - let sizes: Vec<(usize, usize)> = placed.iter().map(|&i| (srcs[i].w, srcs[i].h)).collect(); let order = seam_order(&warped, ref_pos); let geo = vignette.then_some((pls.as_slice(), sizes.as_slice(), offset)); - let b = seam_blend(&warped, canvas, &order, true, true, geo); + let remaining_band_budget = budget.saturating_sub(fixed_during_bands); + let check_cancel = || ctx.check(); + let opt = BlendOptions { seamless: true, gains: true, geometry: geo, budget: Some(remaining_band_budget) }; + let b = seam_blend(warped, canvas, &order, opt, Some(&check_cancel))?; for (k, (px, mask)) in b.layers.into_iter().enumerate() { let mut l = Layer::new(srcs[placed[k]].name.clone(), LayerContent::Raster(px)); let mut m = LayerMask::hide_all(); @@ -617,16 +1021,16 @@ fn content_aware_fill(comp: &Surface, canvas: Rect) -> Surface { let (w, h) = (canvas.width() as usize, canvas.height() as usize); let k = ((w * h) as f64 / 1.5e6).sqrt().ceil().max(1.0) as usize; let (sw, sh) = (w.div_ceil(k), h.div_ceil(k)); - let full = comp.read_region(canvas); let cc = n - 1; let mut small = vec![0.0f32; sw * sh * cc]; let mut hole = vec![false; sw * sh]; let mut acc_a = vec![0.0f32; sw * sh]; let mut cnt = vec![0.0f32; sw * sh]; for y in 0..h { + let row = comp.read_region(Rect::new(canvas.x0, canvas.y0 + y as i32, canvas.x1, canvas.y0 + y as i32 + 1)); for x in 0..w { let i = (y / k) * sw + x / k; - let px = &full[(y * w + x) * n..(y * w + x + 1) * n]; + let px = &row[x * n..(x + 1) * n]; let a = px[cc]; for c in 0..cc { small[i * cc + c] += px[c] * a; @@ -644,10 +1048,13 @@ fn content_aware_fill(comp: &Surface, canvas: Rect) -> Surface { } let source: Vec = hole.iter().map(|h| !h).collect(); let filled = fill(sw, sh, cc, &small, &hole, &source, &FillOptions::default()); - let mut out = vec![0.0f32; w * h * n]; + let mut s = Surface::new(fmt); for y in 0..h { + let area = Rect::new(canvas.x0, canvas.y0 + y as i32, canvas.x1, canvas.y0 + y as i32 + 1); + let full = comp.read_region(area); + let mut out = vec![0.0f32; w * n]; for x in 0..w { - let o = (y * w + x) * n; + let o = x * n; let a = full[o + cc]; let i = (y / k) * sw + x / k; for c in 0..cc { @@ -664,9 +1071,8 @@ fn content_aware_fill(comp: &Surface, canvas: Rect) -> Surface { } out[o + cc] = 1.0; } + s.write_region(area, &out); } - let mut s = Surface::new(fmt); - s.write_region(canvas, &out); s.prune(); s } @@ -685,7 +1091,7 @@ fn shift_rgba(px: &[[f32; 4]], w: usize, h: usize, dx: i32, dy: i32) -> Vec<[f32 fn merge_to_hdr(s: &mut Session, p: &Value) -> Result { let cmd = "file.automate.mergeToHdrPro"; let t0 = Stopwatch::start(); - let (srcs, _fmt, icc) = load_sources(s, p, cmd)?; + let (srcs, _fmt, icc) = load_sources(s, p, cmd, None)?; if srcs.len() < 2 { return Err(bad(cmd, "Merge to HDR Pro needs two or more exposures")); } @@ -969,7 +1375,7 @@ pub fn specs() -> Vec { label: "Photomerge…", menu: &["File", "Automate"], shortcut: None, - params: r##"{"paths":[str]|folder,"useOpenDocuments":bool=false,"layout":"auto|perspective|cylindrical|spherical|collage|reposition","blend":bool=true,"vignetteRemoval":bool=false,"geometricCorrection":bool=false,"contentAwareFill":bool=false,"focalLength":mm=0 (35 mm equivalent; 0 = EXIF or estimated)} → new document, one masked layer per image"##, + params: r##"{"paths":[str]|folder,"useOpenDocuments":bool=false,"layout":"auto|perspective|cylindrical|spherical|collage|reposition","blend":bool=true,"vignetteRemoval":bool=false,"geometricCorrection":bool=false,"contentAwareFill":bool=false,"focalLength":mm=0 (35 mm equivalent; 0 = EXIF or estimated),"memoryBudget":bytes?=half of RAM} → new document, one masked layer per image"##, enabled: always, run: photomerge, journal: true, diff --git a/crates/engine/src/cmd/photo_cmds/tests.rs b/crates/engine/src/cmd/photo_cmds/tests.rs index 8d0152a986..a161099d46 100644 --- a/crates/engine/src/cmd/photo_cmds/tests.rs +++ b/crates/engine/src/cmd/photo_cmds/tests.rs @@ -50,6 +50,15 @@ fn crop(px: &[[f32; 4]], sw: usize, x0: usize, y0: usize, w: usize, h: usize, ga .collect() } +/// A fresh temporary folder for a test's files. +#[cfg(not(target_arch = "wasm32"))] +fn temp_dir(name: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("photocraft-photomerge-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + #[test] fn photomerge_open_documents_reposition_and_perspective() { for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { @@ -350,3 +359,272 @@ fn crop_and_straighten_makes_documents() { let (c, e) = (l.rgba(d.size.width as i32 / 2, 6)[0], l.rgba(d.size.width as i32 / 2, d.size.height as i32 - 6)[0]); assert!((c - e).abs() < 0.05); } + +#[test] +fn photomerge_rejects_insufficient_memory_budget() { + let (sw, sh) = (520, 220); + let sc = scene(sw, sh, 5); + let mut s = Session::new(); + for (k, x0) in [0usize, 180].into_iter().enumerate() { + s.add_document(doc_from(&format!("img{k}"), &crop(&sc, sw, x0, 10, 260, 200, 1.0), 260, 200, SampleType::U8), None); + } + assert_eq!(s.documents().len(), 2); + // Budget of 1024 bytes is insufficient for the panorama. + let err = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "reposition", "memoryBudget": 1024})).unwrap_err(); + assert!(err.to_string().contains("not enough memory for file.automate.photomerge"), "{err}"); + assert!(err.to_string().contains("exceeds the"), "{err}"); + // Session state and documents must remain intact. + assert_eq!(s.documents().len(), 2); + assert_eq!(s.active().unwrap().doc.name, "img1"); +} + +#[test] +fn photomerge_estimate_is_the_largest_phase_not_the_sum() { + // Two 100×100 RGB8 images (4 bytes per pixel in the canvas) on a 150×100 canvas. + let sizes = [(100, 100), (100, 100)]; + let (cw, ch, cc, bpp) = (150, 100, 3, 4); + let band = panorama::band_bytes_bound(100, 100, cc, panorama::blend_levels(cw, ch).min(7), cw, ch); + assert_eq!(band, 150 * 100 * 4 * 12); + let (rois, accumulators) = (20_000 * 20, 15_000 * 21); + let (peak, fixed) = estimate_photomerge_memory(&sizes, &sizes, cw, ch, cc, bpp, true, false); + assert_eq!(fixed, rois + accumulators); + // The bands phase (ROIs, accumulators and one band) is the largest here. + let bands = rois + accumulators + band; + let collapse = rois + accumulators + 15_000 * 12; + let output = rois + 15_000 * 16 + 15_000 * 4 + 20_000 * 5; + assert!(bands > collapse && bands > output); + assert_eq!(peak, bands); + // A sum of every buffer would be far more. + assert!(peak < rois + accumulators + 15_000 * 16 + 20_000 * 5 + band); + // Filling adds its own phase, which does not exceed the bands here. + let (with_fill, _) = estimate_photomerge_memory(&sizes, &sizes, cw, ch, cc, bpp, true, true); + assert_eq!(with_fill, (20_000 * 5 + 15_000 * 4 + 15_000 * 4 + (24 << 20)).max(peak)); + // Without blending only the sources and warped layers are held. + assert_eq!(estimate_photomerge_memory(&sizes, &sizes, cw, ch, cc, bpp, false, false), (80_000 + 80_000, 0)); +} + +#[test] +fn photomerge_estimate_fits_six_large_photos_in_eight_gib() { + let photos = [(6000, 4000); 6]; + let (peak, fixed) = estimate_photomerge_memory(&photos, &photos, 27_000, 4_112, 3, 4, true, false); + assert!(peak < 8 << 30, "{} MiB", peak >> 20); + assert!(fixed < peak); +} + +/// A flat opaque RGBA8 surface covering `area`. +fn flat_surface(area: Rect, v: f32) -> Surface { + let fmt = PixelFormat::RGBA8; + let n = (area.width() * area.height()) as usize; + let data: Vec = (0..n).flat_map(|_| [v, v, v, 1.0]).collect(); + let mut s = Surface::new(fmt); + s.write_region(area, &data); + s +} + +#[test] +fn seam_blend_rejects_a_band_larger_than_its_budget() { + let (a, b) = (Rect::new(0, 0, 64, 64), Rect::new(32, 0, 96, 64)); + let warped = vec![flat_surface(a, 0.3), flat_surface(b, 0.6)]; + let opt = BlendOptions { seamless: true, gains: true, geometry: None, budget: Some(1000) }; + let err = seam_blend(warped, Rect::new(0, 0, 96, 64), &[0, 1], opt, None).err().expect("a 1000 byte budget can't hold a band"); + assert!(err.to_string().contains("not enough memory to allocate"), "{err}"); + // Without a budget the same blend succeeds. + let warped = vec![flat_surface(a, 0.3), flat_surface(b, 0.6)]; + let opt = BlendOptions { seamless: true, gains: true, geometry: None, budget: None }; + assert!(seam_blend(warped, Rect::new(0, 0, 96, 64), &[0, 1], opt, None).is_ok()); +} + +#[test] +fn photomerge_succeeds_with_a_large_enough_memory_budget() { + let (sw, sh) = (520, 220); + let sc = scene(sw, sh, 5); + let mut s = Session::new(); + for (k, x0) in [0usize, 180].into_iter().enumerate() { + s.add_document(doc_from(&format!("img{k}"), &crop(&sc, sw, x0, 10, 260, 200, 1.0), 260, 200, SampleType::U8), None); + } + let r = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "reposition", "memoryBudget": 1u64 << 30})).unwrap(); + assert_eq!(r["layers"], 2, "{r}"); + assert_eq!(s.documents().len(), 3); +} + +#[test] +fn photomerge_memory_budget_precedence_and_defaults() { + // The param wins over the environment and the machine. + assert_eq!(budget_from(Some(123), Some("64"), Some(64 << 30)), 123); + // Then the environment variable (MiB). + assert_eq!(budget_from(None, Some(" 64 "), Some(64 << 30)), 64 << 20); + // An unparsable variable falls through to the machine. + assert_eq!(budget_from(None, Some("lots"), Some(8 << 30)), 4 << 30); + // Half of RAM with no upper ceiling. + assert_eq!(budget_from(None, None, Some(64 << 30)), 32 << 30); + // At least 1 GiB, and 4 GiB of RAM assumed when unknown. + assert_eq!(budget_from(None, None, Some(1 << 30)), 1 << 30); + assert_eq!(budget_from(None, None, None), 2 << 30); + // Huge values saturate instead of panicking or truncating. + assert_eq!(budget_from(Some(u64::MAX), None, None), usize::try_from(u64::MAX).unwrap_or(usize::MAX)); + let _ = budget_from(None, Some("18446744073709551615"), None); + let _ = budget_from(None, None, Some(u64::MAX)); +} + +#[test] +fn photomerge_rejects_oversized_sparse_source_before_flattening() { + let mut s = Session::new(); + s.add_document(Document::new("sparse", Size::new(100_000, 100_000), ColorMode::Rgb, SampleType::U8), None); + let err = load_sources(&s, &json!({"useOpenDocuments": true}), "file.automate.photomerge", None).err().expect("oversized canvas must be refused"); + assert!(err.to_string().contains("too large to flatten"), "{err}"); + assert_eq!(s.documents().len(), 1); + assert_eq!(s.active().unwrap().doc.name, "sparse"); +} + +#[test] +fn photomerge_source_load_charges_the_document_and_both_flatten_surfaces() { + let cmd = "file.automate.photomerge"; + let px = scene(260, 200, 3); + let one = doc_from("a", &px, 260, 200, SampleType::U8); + let bpp = one.pixel_format().bytes_per_pixel(); + let output = surface_bytes(260, 200, bpp); + let cost = SourceLoad::new(None).needed(&one, bpp, 0); + assert_eq!(document_pixels(&one), output, "a covered 260×200 surface is two 256 px tiles"); + assert_eq!(cost, 3 * output, "the document, the kept surface and the flatten's working surface"); + + let mut load = SourceLoad::new(Some(cost)); + assert!(load.admit(cmd, &one, bpp, 0).is_ok(), "the first source fits exactly"); + assert_eq!(load.retained, output); + let err = load.admit(cmd, &one, bpp, 0).expect_err("the second source exceeds the budget"); + assert!(err.to_string().contains("not enough memory for file.automate.photomerge"), "{err}"); + assert!(err.to_string().contains("260×200"), "{err}"); + assert!(err.to_string().contains("exceeds the"), "{err}"); + assert_eq!(load.retained, output, "a refused source is not counted as retained"); + + // An encoded file's bytes are held during the import as well. + assert!(SourceLoad::new(Some(cost + 99)).admit(cmd, &one, bpp, 100).is_err()); + assert!(SourceLoad::new(Some(cost + 100)).admit(cmd, &one, bpp, 100).is_ok()); + + // Every layer of the decoded document is charged, not just the two output surfaces. + let mut layered = one.clone(); + layered.layers.extend(doc_from("b", &px, 260, 200, SampleType::U8).layers); + assert_eq!(document_pixels(&layered), 2 * output); + assert!(SourceLoad::new(Some(cost + output - 1)).admit(cmd, &layered, bpp, 0).is_err()); + assert!(SourceLoad::new(Some(cost + output)).admit(cmd, &layered, bpp, 0).is_ok()); + + // Hostile sizes saturate and fail a finite budget instead of wrapping under it. + assert!(SourceLoad::new(Some(1 << 40)).admit(cmd, &one, usize::MAX, usize::MAX).is_err()); + // Without a budget (Merge to HDR Pro) nothing is assessed. + assert!(SourceLoad::new(None).admit(cmd, &one, usize::MAX, usize::MAX).is_ok()); +} + +#[test] +fn photomerge_rejects_over_budget_sources_before_flattening() { + let (sw, sh) = (520, 220); + let sc = scene(sw, sh, 9); + let mut s = Session::new(); + for (k, x0) in [0usize, 180].into_iter().enumerate() { + s.add_document(doc_from(&format!("img{k}"), &crop(&sc, sw, x0, 10, 260, 200, 1.0), 260, 200, SampleType::U8), None); + } + // Enough for the first source, but not for a second one after its own surface is kept. + let one = &s.documents()[0].doc; + let bpp = one.pixel_format().bytes_per_pixel(); + let cost = SourceLoad::new(None).needed(one, bpp, 0); + let budget = cost + surface_bytes(260, 200, bpp) / 2; + let err = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "reposition", "memoryBudget": budget as u64})).unwrap_err(); + assert!(err.to_string().contains("not enough memory for file.automate.photomerge"), "{err}"); + assert!(err.to_string().contains("exceeds the"), "{err}"); + // Refused during loading, before alignment, warping or a new document. + assert_eq!(s.documents().len(), 2); + assert_eq!(s.active().unwrap().doc.name, "img1"); +} + +#[test] +fn photomerge_rejects_a_panorama_over_budget_after_loading() { + let (sw, sh) = (520, 220); + let sc = scene(sw, sh, 5); + let mut s = Session::new(); + for (k, x0) in [0usize, 180].into_iter().enumerate() { + s.add_document(doc_from(&format!("img{k}"), &crop(&sc, sw, x0, 10, 260, 200, 1.0), 260, 200, SampleType::U8), None); + } + // Enough to load both sources, but below the warp/blend estimate, so the post-alignment + // check refuses the job rather than the loader. + let one = &s.documents()[0].doc; + let bpp = one.pixel_format().bytes_per_pixel(); + let budget = SourceLoad::new(None).needed(one, bpp, 0) + surface_bytes(260, 200, bpp); + let err = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "reposition", "memoryBudget": budget as u64})).unwrap_err(); + assert!(err.to_string().contains("estimated memory"), "{err}"); + assert!(err.to_string().contains("exceeds budget"), "{err}"); + assert_eq!(s.documents().len(), 2); + assert_eq!(s.active().unwrap().doc.name, "img1"); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn photomerge_refuses_an_oversized_file_before_reading_or_decoding_it() { + let cmd = "file.automate.photomerge"; + let dir = temp_dir("oversized-file"); + let path = dir.join("big.png"); + // Not a valid image: reaching the decoder would report a format error instead. + std::fs::write(&path, vec![0xAB; 4096]).unwrap(); + let err = load_sources(&Session::new(), &json!({"paths": [path.to_string_lossy()]}), cmd, Some(1024)) + .err() + .expect("a file larger than the budget must be refused"); + assert!(err.to_string().contains("was not read"), "{err}"); + assert!(err.to_string().contains("only 1 KiB is left"), "{err}"); + assert!(!err.to_string().contains("unrecognized"), "{err}"); + assert!(!err.to_string().contains("image format"), "{err}"); +} + +/// A source that cannot be opened is a file error under a budget too, not a memory error. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn photomerge_reports_a_missing_file_as_a_file_error_under_a_budget() { + let cmd = "file.automate.photomerge"; + let missing = temp_dir("missing-file").join("does-not-exist.png"); + let err = load_sources(&Session::new(), &json!({"paths": [missing.to_string_lossy()]}), cmd, Some(1 << 30)).err().expect("a missing file must fail"); + let message = err.to_string(); + assert!(!message.contains("not enough memory"), "{message}"); + assert!(message.contains("does-not-exist.png"), "{message}"); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn photomerge_file_source_is_charged_beside_the_sources_already_loaded() { + let cmd = "file.automate.photomerge"; + let px = scene(260, 200, 4); + let open = doc_from("open", &px, 260, 200, SampleType::U8); + let bpp = open.pixel_format().bytes_per_pixel(); + let cost = SourceLoad::new(None).needed(&open, bpp, 0); + let png = photocraft_io::export(&open, "source.png", &Default::default()).unwrap().bytes; + let dir = temp_dir("file-budget"); + let path = dir.join("source.png"); + std::fs::write(&path, &png).unwrap(); + // Exactly enough for the file's encoded bytes, its document and its flatten surfaces, plus + // two bytes: alone it loads, but not beside an open source that keeps its surface. + let budget = cost + png.len() + 2; + + let alone = Session::new(); + let (loaded, _, _) = load_sources(&alone, &json!({"paths": [path.to_string_lossy()]}), cmd, Some(budget)).expect("the file alone fits"); + assert_eq!(loaded.len(), 1); + + let mut s = Session::new(); + s.add_document(open, None); + let err = load_sources(&s, &json!({"useOpenDocuments": true, "paths": [path.to_string_lossy()]}), cmd, Some(budget)) + .err() + .expect("the retained open source leaves no room for the file's own pixels"); + let message = err.to_string(); + assert!(message.contains("exceeds the") || message.contains("limit exceeded"), "{message}"); + assert_eq!(s.documents().len(), 1); +} + +#[test] +fn merge_to_hdr_pro_accepts_sources_without_the_photomerge_budget() { + let (sw, sh) = (120, 90); + let sc = scene(sw, sh, 11); + let mut s = Session::new(); + for k in 0..2 { + s.add_document(doc_from(&format!("exp{k}"), &crop(&sc, sw, 0, 0, sw, sh, 1.0 + k as f32), sw, sh, SampleType::U8), None); + } + // A 1-byte Photomerge budget refuses the sources; Merge to HDR Pro passes no budget and + // still loads them, so its behaviour is unchanged. + assert!(load_sources(&s, &json!({"useOpenDocuments": true}), "file.automate.photomerge", Some(1)).is_err()); + let (srcs, fmt, _) = load_sources(&s, &json!({"useOpenDocuments": true}), "file.automate.mergeToHdrPro", None).unwrap(); + assert_eq!(srcs.len(), 2); + assert_eq!(fmt, PixelFormat::RGBA8); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 321480e479..9cae6dcaa9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -31,6 +31,7 @@ pub mod layer_place; pub mod layer_style; pub mod link_watch; pub mod malloc_tuning; +pub mod memory; pub mod new_layer; mod param_check; mod pixels; diff --git a/crates/engine/src/memory.rs b/crates/engine/src/memory.rs new file mode 100644 index 0000000000..7b61e1b063 --- /dev/null +++ b/crates/engine/src/memory.rs @@ -0,0 +1,43 @@ +//! Physical memory of the machine, shared by the engine's memory budgets (Photomerge) and the +//! shell's GPU budgets. + +/// Physical memory of this machine in bytes, if known. `PHOTOCRAFT_RAM_MB` overrides it (to +/// simulate a smaller machine). +pub fn physical_memory() -> Option { + static RAM: std::sync::OnceLock> = std::sync::OnceLock::new(); + *RAM.get_or_init(|| { + if let Some(mb) = std::env::var("PHOTOCRAFT_RAM_MB").ok().and_then(|v| v.trim().parse::().ok()) { + return mb.checked_mul(1 << 20); + } + detect_physical_memory() + }) +} + +/// Physical memory as the operating system reports it, ignoring `PHOTOCRAFT_RAM_MB` and not +/// cached. `None` where nothing reports it (the web build, other platforms). +pub fn detect_physical_memory() -> Option { + #[cfg(target_os = "macos")] + { + let out = std::process::Command::new("/usr/sbin/sysctl").args(["-n", "hw.memsize"]).output().ok()?; + String::from_utf8(out.stdout).ok()?.trim().parse().ok() + } + #[cfg(target_os = "linux")] + { + let info = std::fs::read_to_string("/proc/meminfo").ok()?; + let kb: u64 = info.lines().find_map(|l| l.strip_prefix("MemTotal:"))?.trim().trim_end_matches("kB").trim().parse().ok()?; + kb.checked_mul(1024) + } + #[cfg(target_os = "freebsd")] + { + let out = std::process::Command::new("/sbin/sysctl").args(["-n", "hw.physmem"]).output().ok()?; + String::from_utf8(out.stdout).ok()?.trim().parse().ok() + } + #[cfg(windows)] + { + winsafe::GlobalMemoryStatusEx().map(|m| m.ullTotalPhys).ok().filter(|b| *b > 0) + } + #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "freebsd", windows)))] + { + None + } +} diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index e759e99ae9..06b35f8208 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -47,7 +47,7 @@ pub use autosave::RecoveryStore; pub use autosave::{Autosaver, RecoveryEntry, discard_recovery, list_recovery, recover}; pub use convert::MAX_GROUP_DEPTH; pub use manifest::{FORMAT_VERSION, Manifest}; -pub use read::read_file; +pub use read::{read_file, read_file_limited}; pub use store::{ByteSource, DEFAULT_REVERIFY_BUDGET, PcraftWriter, SaveStats, read_entry}; /// File extension of the native format. diff --git a/crates/format/src/read.rs b/crates/format/src/read.rs index b71e3c8030..5d8856b58d 100644 --- a/crates/format/src/read.rs +++ b/crates/format/src/read.rs @@ -35,6 +35,13 @@ pub fn read_file_with(path: &Path, chunk: usize) -> io::Result> { read_path(path, chunk, MAX_OPEN_BYTES) } +/// [`read_file`] with the caller's own total limit, in bytes: a file larger than `max` is a +/// `FileTooLarge` error and is not read, so a caller holding part of a budget can refuse it +/// before reserving anything. +pub fn read_file_limited(path: &Path, max: u64) -> io::Result> { + read_path(path, READ_CHUNK, max.min(MAX_OPEN_BYTES)) +} + /// [`read_file_with`] with a chosen total limit (tests use small ones). fn read_path(path: &Path, chunk: usize, max: u64) -> io::Result> { #[cfg(unix)] @@ -95,7 +102,12 @@ fn read_all_with(reader: &mut impl Read, size_hint: u64, chunk: usize, max: u64) break; } let needed = buf.len() as u64 + n as u64; - buf.try_reserve(n.max(chunk)).map_err(|_| out_of_memory(needed))?; + // Refuse before reserving, so a caller with a small limit never allocates past it. + if needed > max { + return Err(too_large(max)); + } + let room = usize::try_from(max - buf.len() as u64).unwrap_or(usize::MAX); + buf.try_reserve(n.max(chunk).min(room)).map_err(|_| out_of_memory(needed))?; buf.extend_from_slice(&probe[..n]); } let room = u64::try_from((buf.capacity() - buf.len()).min(chunk)).unwrap_or(u64::MAX); @@ -201,6 +213,28 @@ mod tests { assert_eq!(buf.capacity(), data.len()); } + /// Growing the buffer past the hint never reserves more than the caller's limit, so a small + /// limit is never outgrown by the read chunk. + #[test] + fn growing_past_the_hint_stays_within_the_limit() { + let data = vec![3u8; 4_000]; + let buf = read_all_with(&mut std::io::Cursor::new(&data), 0, 1 << 20, 5_000).unwrap(); + assert_eq!(buf, data); + assert!(buf.capacity() <= 5_000, "reserved {}", buf.capacity()); + let e = read_all_with(&mut std::io::Cursor::new(vec![3u8; 9_000]), 0, 1 << 20, 5_000).unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::FileTooLarge); + } + + #[test] + fn a_caller_limit_refuses_a_larger_file_before_reading_it() { + let data = vec![7u8; 10_000]; + let p = temp("limited", &data); + assert_eq!(read_file_limited(&p, data.len() as u64).unwrap(), data, "exactly at the limit"); + let e = read_file_limited(&p, data.len() as u64 - 1).unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::FileTooLarge); + assert!(e.to_string().contains("was not read"), "{e}"); + } + #[test] fn empty_and_missing_files() { assert!(read_file(&temp("empty", b"")).unwrap().is_empty()); diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 8e21b81ef5..3d3f95b30b 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -47,6 +47,16 @@ fn before_composite_decode() { #[cfg(not(test))] fn before_composite_decode() {} +/// The codec limits a flat import uses: the caller's decoded-pixel allowance lowers the codec's +/// default cap; 0 keeps the defaults. +fn decode_limits(opts: &crate::ImportOptions) -> codecs::Limits { + let mut limits = codecs::Limits::default(); + if opts.flat_max_pixel_bytes > 0 { + limits.max_alloc = limits.max_alloc.min(opts.flat_max_pixel_bytes); + } + limits +} + /// Decodes a flat image into a single-layer document; a TIFF with Photoshop layer data opens /// layered (see [`crate::tiff_layers`]). pub fn import_flat(name: &str, bytes: &[u8]) -> Result { @@ -71,7 +81,8 @@ pub(crate) fn import_flat_with_options( if format == Some(Format::Tiff) { return import_tiff_page_with_options(name, bytes, None, opts, ctl); } - let img = codecs::decode_as(format.ok_or(codecs::CodecError::UnknownFormat)?, bytes)?; + let limits = decode_limits(opts); + let img = codecs::decode_as_with(format.ok_or(codecs::CodecError::UnknownFormat)?, bytes, &codecs::DecodeOptions { limits, ..Default::default() })?; // A palette BMP, PNG or GIF opens in Indexed Color mode with its colour table, as in // Photoshop (#3802, #4804, #7886). A GIF is always palette-based: the first frame's table. let palette = match format { @@ -311,7 +322,7 @@ pub fn import_tiff_page_with_options( // Extra samples (alpha and spot channels) are only available from a whole-image decode. if bands.extra_samples() > 0 { drop(bands); - return import_tiff_with_extras(name, bytes, page, ctl); + return import_tiff_with_extras(name, bytes, page, opts, ctl); } tiff_to_document(name, bands.upright(), crate::memory::available, BAND_BYTES, ctl) } @@ -396,9 +407,15 @@ fn tiff_admission( /// A flat TIFF page with extra samples, decoded whole: the composite becomes the layer, the /// extra samples its channels. -fn import_tiff_with_extras(name: &str, bytes: &[u8], page: Option, ctl: &photocraft_raster::Interrupt) -> Result { +fn import_tiff_with_extras( + name: &str, + bytes: &[u8], + page: Option, + opts: &crate::ImportOptions, + ctl: &photocraft_raster::Interrupt, +) -> Result { ctl.check().map_err(|_| IoError::Cancelled)?; - let keep = codecs::DecodeOptions { keep_orientation: true, ..Default::default() }; + let keep = codecs::DecodeOptions { keep_orientation: true, limits: decode_limits(opts) }; let (img, orientation) = match page { None => (codecs::decode_with(bytes, &keep)?, codecs::tiff_orientation(bytes)), Some(p) => (codecs::decode_tiff_page(bytes, p, &keep)?, codecs::tiff_page_orientation(bytes, p)), diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 7457b5647e..41e5bf0a0c 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -484,6 +484,65 @@ fn is_psd_input(name: &str, bytes: &[u8]) -> bool { is_psd(bytes) || (PSD_EXTS.iter().any(|e| has_extension(name, e)) && photocraft_codecs::detect(bytes).is_none()) } +/// How an import bounds its pixel memory before decoding pixels, for a caller that must fit +/// several imports into one memory budget. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ImportPreflight { + /// PSD/PSB: the import's own layer/mask/merged preflight, lowered by + /// [`ImportOptions::psd_max_pixel_bytes`]. + Psd, + /// TIFF: a layered page uses [`ImportOptions::psd_max_pixel_bytes`]; a flat page is decoded + /// in bands, so the caller bounds its whole canvas from the page's header + /// ([`photocraft_codecs::tiff_info`]). + Tiff, + /// A flat raster decoded into one image, bounded by + /// [`ImportOptions::flat_max_pixel_bytes`]. + Flat, + /// Affinity, OpenRaster, Krita, XCF, PDN, SVG, camera raw and `.pcraft` files: this build has + /// no header-only estimate of their pixel memory before decoding. + Unbounded, +} + +/// Which [`ImportPreflight`] applies to importing `name` and `bytes`. +/// +/// The order matches [`import_stages`]; keep the two in step. +pub fn import_preflight(name: &str, bytes: &[u8]) -> ImportPreflight { + if has_extension(name, photocraft_format::EXTENSION) || photocraft_format::is_pcraft(bytes) { + return ImportPreflight::Unbounded; + } + if is_psd(bytes) { + return ImportPreflight::Psd; + } + if affinity::is_affinity(bytes) || affinity::has_extension(name) { + return ImportPreflight::Unbounded; + } + if ora::is_ora(bytes) || has_extension(name, "ora") { + return ImportPreflight::Unbounded; + } + if kra::is_kra(bytes) || (kra::EXTENSIONS.iter().any(|e| has_extension(name, e)) && photocraft_codecs::detect(bytes).is_none()) { + return ImportPreflight::Unbounded; + } + if xcf::is_xcf(bytes) || (has_extension(name, "xcf") && photocraft_codecs::detect(bytes).is_none()) { + return ImportPreflight::Unbounded; + } + if xcf::is_gzipped_xcf(name, bytes) { + return ImportPreflight::Unbounded; + } + if has_extension(name, "pdn") || bytes.starts_with(b"PDN3") { + return ImportPreflight::Unbounded; + } + if raw::is_raw(bytes) { + return ImportPreflight::Unbounded; + } + if is_svg_input(name, bytes) { + return ImportPreflight::Unbounded; + } + if is_psd_input(name, bytes) { + return ImportPreflight::Psd; + } + if photocraft_codecs::detect(bytes) == Some(photocraft_codecs::Format::Tiff) { ImportPreflight::Tiff } else { ImportPreflight::Flat } +} + /// Imports a file. PSD/PSB, Affinity containers and camera raws are detected by magic; everything /// else is decoded with `photocraft-codecs`. pub fn import(name: &str, bytes: &[u8]) -> Result { @@ -524,6 +583,9 @@ pub struct ImportOptions { /// lower the default cap; 0 uses the adaptive budget. Does not cover metadata or /// smart-filter caches. pub psd_max_pixel_bytes: u64, + /// Decoded-pixel allowance for a flat raster (the buffer a codec decodes into). May lower + /// the codec's default cap; 0 uses it. PSD/PSB and layered TIFF use `psd_max_pixel_bytes`. + pub flat_max_pixel_bytes: u64, /// Explicit one-shot authorization for imports that exceed the soft budget but fit within the hard budget. pub psd_high_memory_approved: bool, /// Optional estimate limit for high-memory approval. When set, approval only applies if @@ -537,6 +599,7 @@ impl Default for ImportOptions { max_group_depth: photocraft_doc::MAX_GROUP_DEPTH, demosaic: raw::Demosaic::default(), psd_max_pixel_bytes: 0, + flat_max_pixel_bytes: 0, psd_high_memory_approved: false, psd_approved_estimate: None, } @@ -1249,9 +1312,25 @@ pub fn merged_composite(file: &PsdFile) -> Result, IoError> { #[cfg(test)] mod tests { - use super::{ImportOptions, import, import_for_open, is_psd_input, is_svg_input}; + use super::{ImportOptions, ImportPreflight, import, import_for_open, import_preflight, is_psd_input, is_svg_input}; use photocraft_psd::{Compression, Version, testgen}; + /// The callers that fit several imports into one budget choose their option from this + /// classification, so it has to follow the same dispatch as [`super::import`]. + #[test] + fn import_preflight_classifies_each_dispatched_format() { + let png = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR"; + assert_eq!(import_preflight("x.png", png), ImportPreflight::Flat); + assert_eq!(import_preflight("x.psd", b"8BPS\0\0"), ImportPreflight::Psd); + assert_eq!(import_preflight("x.tif", b"II*\0"), ImportPreflight::Tiff); + assert_eq!(import_preflight("x.ora", b"PK\x03\x04"), ImportPreflight::Unbounded); + assert_eq!(import_preflight("x.svg", b""), ImportPreflight::Unbounded); + assert_eq!(import_preflight("x.pcraft", b"PCF1"), ImportPreflight::Unbounded); + assert_eq!(import_preflight("x.afphoto", b"Affinity"), ImportPreflight::Unbounded); + // A Photoshop extension whose bytes are a readable flat image follows the image. + assert_eq!(import_preflight("misnamed.psd", png), ImportPreflight::Flat); + } + /// Verifies a valid PSD remains editable after import. #[test] fn valid_psd_can_still_be_edited() { diff --git a/crates/ui-egui/src/canvas/gpu_canvas.rs b/crates/ui-egui/src/canvas/gpu_canvas.rs index ef9435f346..af3d574980 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas.rs @@ -48,6 +48,8 @@ mod setup; mod shaders; mod texels; +#[cfg(all(test, windows))] +use budget::detect_video_memory; #[cfg(all(test, target_os = "linux"))] use budget::nvidia_video_memory; pub use budget::{ @@ -56,8 +58,6 @@ pub use budget::{ }; #[cfg(test)] use budget::{NVIDIA_VENDOR, bounded_output, drm_video_memory, parse_nvidia_smi}; -#[cfg(all(test, windows))] -use budget::{detect_physical_memory, detect_video_memory}; use callback::CanvasCallback; #[cfg(test)] use callback::{filter_mode, map_doc_px, tile_screen_aabb}; @@ -65,6 +65,8 @@ use doc_textures::init_buffer; #[cfg(test)] use doc_textures::{mip_count, mip_damage}; pub use perf::{GpuInfo, Perf, backend_name, now_ms}; +#[cfg(all(test, windows))] +use photocraft_engine::memory::detect_physical_memory; pub use resources::CanvasStyle; use resources::{DocTextures, Resources, identity_lut_bytes, lut_bind_group}; #[cfg(test)] diff --git a/crates/ui-egui/src/canvas/gpu_canvas/budget.rs b/crates/ui-egui/src/canvas/gpu_canvas/budget.rs index 9f5df3ebd6..242eebaaa9 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas/budget.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas/budget.rs @@ -78,46 +78,9 @@ pub fn canvas_texture_bytes(size: [u32; 2], tile: u32, bpp: u64) -> u64 { total } -/// Physical memory of this machine in bytes, if known. `PHOTOCRAFT_RAM_MB` overrides it (to -/// simulate a smaller machine). -pub fn physical_memory() -> Option { - static RAM: std::sync::OnceLock> = std::sync::OnceLock::new(); - *RAM.get_or_init(|| { - if let Some(mb) = std::env::var("PHOTOCRAFT_RAM_MB").ok().and_then(|v| v.trim().parse::().ok()) { - return mb.checked_mul(1 << 20); - } - detect_physical_memory() - }) -} - -#[cfg(target_os = "macos")] -fn detect_physical_memory() -> Option { - let out = std::process::Command::new("/usr/sbin/sysctl").args(["-n", "hw.memsize"]).output().ok()?; - String::from_utf8(out.stdout).ok()?.trim().parse().ok() -} - -#[cfg(target_os = "linux")] -fn detect_physical_memory() -> Option { - let info = std::fs::read_to_string("/proc/meminfo").ok()?; - let kb: u64 = info.lines().find_map(|l| l.strip_prefix("MemTotal:"))?.trim().trim_end_matches("kB").trim().parse().ok()?; - kb.checked_mul(1024) -} - -#[cfg(target_os = "freebsd")] -fn detect_physical_memory() -> Option { - let out = std::process::Command::new("/sbin/sysctl").args(["-n", "hw.physmem"]).output().ok()?; - String::from_utf8(out.stdout).ok()?.trim().parse().ok() -} - -#[cfg(windows)] -pub(super) fn detect_physical_memory() -> Option { - winsafe::GlobalMemoryStatusEx().map(|m| m.ullTotalPhys).ok().filter(|b| *b > 0) -} - -#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "freebsd", windows)))] -fn detect_physical_memory() -> Option { - None -} +/// Physical memory of this machine in bytes, if known (the engine's, shared with its own +/// budgets). `PHOTOCRAFT_RAM_MB` overrides it (to simulate a smaller machine). +pub use photocraft_engine::memory::physical_memory; /// The memory of `adapter` itself, in bytes, when it is a discrete GPU and the platform reports /// it: DXGI's dedicated video memory on Windows, amdgpu's VRAM size or `nvidia-smi`'s report on