Skip to content

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

Check peak RAW development memory and bound AHD scratch (#4597)

optimalbytee876bb8e2815f
diff --git a/crates/raw/README.md b/crates/raw/README.md
index fcb3c1a95..efba4e833 100644
--- a/crates/raw/README.md
+++ b/crates/raw/README.md
@@ -91,6 +91,11 @@ camera colour tables were copied.
16 bits.
5. Orientation.
+Development validates public sensor/crop/CFA metadata before allocation. The working-memory
+limit checks peak live development buffers instead of summing disjoint phases. AHD limits
+simultaneous scratch bands only when required; normal load balancing and pixels are preserved.
+The default 2 GiB limit is unchanged and excludes caller-owned sensor/document storage.
+
Files without colour calibration (CR2, NEF, ARW, RW2, ORF, RAF…) have no camera matrix. Every one of
them carries a JPEG the camera rendered from the same sensor data, so `fit_look` estimates the
camera's rendering per file: both the sensor data (white-balanced as `develop` does) and the
diff --git a/crates/raw/src/demosaic.rs b/crates/raw/src/demosaic.rs
index 2689061b3..8b87f14a6 100644
--- a/crates/raw/src/demosaic.rs
+++ b/crates/raw/src/demosaic.rs
@@ -187,14 +187,14 @@ fn kernels(phase: [u8; 4], method: Demosaic, stride: usize) -> [[Vec<(isize, f32
}
/// Demosaics a padded CFA plane into interleaved RGB (`w × h × 3`).
-pub(crate) fn demosaic(p: &Padded, phase: [u8; 4], method: Demosaic, to_xyz: &Mat3) -> Vec<f32> {
+pub(crate) fn demosaic(p: &Padded, phase: [u8; 4], method: Demosaic, to_xyz: &Mat3, ahd_jobs: usize) -> Vec<f32> {
let (w, h, s) = (p.w, p.h, p.stride);
let mut out = vec![0.0f32; w * h * 3];
if w == 0 || h == 0 || p.data.len() < s * (h + 2 * PAD) {
return out;
}
if method == Demosaic::Ahd {
- ahd(p, phase, to_xyz, &mut out);
+ ahd(p, phase, to_xyz, &mut out, ahd_jobs);
return out;
}
let ks = kernels(phase, method, s);
@@ -460,7 +460,19 @@ const AHD_BAND: usize = 32;
/// Extra band rows above and below the output rows.
const M: usize = 3;
-fn ahd(p: &Padded, phase: [u8; 4], to_xyz: &Mat3, out: &mut [f32]) {
+/// Maximum scratch allocation of one AHD band: two green, RGB and Lab float
+/// planes and two byte homogeneity planes, including their border rows.
+pub(crate) fn ahd_scratch(w: u64, h: u64) -> u64 {
+ w.saturating_add(2 * PAD as u64).saturating_mul(h.min(AHD_BAND as u64).saturating_add(2 * M as u64)).saturating_mul(58)
+}
+
+pub(crate) fn ahd_bands(h: usize) -> usize {
+ h.div_ceil(AHD_BAND)
+}
+
+pub(crate) const AHD_TABLE_BYTES: u64 = (LABF_STEPS as u64 + 2) * 4;
+
+fn ahd(p: &Padded, phase: [u8; 4], to_xyz: &Mat3, out: &mut [f32], jobs: usize) {
let (w, s) = (p.w, p.stride);
let d = &p.data;
// Colour at padded coordinates (PAD is even, so the phase is unchanged).
@@ -468,7 +480,7 @@ fn ahd(p: &Padded, phase: [u8; 4], to_xyz: &Mat3, out: &mut [f32]) {
let white = [0.9642f32, 1.0, 0.8249];
let m: [[f32; 3]; 3] = std::array::from_fn(|i| std::array::from_fn(|j| to_xyz[i][j] as f32 / white[i]));
let labf = LabF::new();
- par::chunks_mut(out, AHD_BAND * w * 3, |band, chunk| {
+ par::chunks_mut_limited(out, AHD_BAND * w * 3, jobs, |band, chunk| {
let rows = chunk.len() / (w * 3);
let n = rows + 2 * M;
// Band row b ↔ padded row py(b); padded columns are used as is.
@@ -577,13 +589,24 @@ mod tests {
use super::*;
use crate::color::IDENTITY;
+ #[test]
+ fn ahd_band_concurrency_does_not_change_pixels() {
+ let (w, h) = (53, 103);
+ let cfa: Vec<f32> = (0..w * h).map(|i| ((i * 97 + i / w * 31) % 1009) as f32 / 1009.0).collect();
+ let p = Padded::from_plane(&cfa, w, h);
+ let one = demosaic(&p, [0, 1, 1, 2], Demosaic::Ahd, &IDENTITY, 1);
+ for jobs in [2, 3, 4, 128] {
+ assert_eq!(one, demosaic(&p, [0, 1, 1, 2], Demosaic::Ahd, &IDENTITY, jobs));
+ }
+ }
+
/// Mosaics an RGB image with the given phase.
fn mosaic(rgb: &[[f32; 3]], w: usize, h: usize, phase: [u8; 4]) -> Vec<f32> {
(0..w * h).map(|i| rgb[i][phase[((i / w) & 1) * 2 + ((i % w) & 1)] as usize]).collect()
}
fn run(cfa: &[f32], w: usize, h: usize, phase: [u8; 4], m: Demosaic) -> Vec<f32> {
- demosaic(&Padded::from_plane(cfa, w, h), phase, m, &IDENTITY)
+ demosaic(&Padded::from_plane(cfa, w, h), phase, m, &IDENTITY, par::workers())
}
fn psnr(a: &[f32], b: &[[f32; 3]], w: usize, h: usize, border: usize) -> f64 {
@@ -671,7 +694,7 @@ mod tests {
let cfa: Vec<f32> = (0..w * h).map(|i| ((i * 7919) % 1000) as f32 / 1000.0).collect();
for phase in [[0, 1, 1, 2], [1, 2, 0, 1]] {
let p = Padded::from_plane(&cfa, w, h);
- let fast = demosaic(&p, phase, Demosaic::Bilinear, &IDENTITY);
+ let fast = demosaic(&p, phase, Demosaic::Bilinear, &IDENTITY, par::workers());
let ks = kernels(phase, Demosaic::Bilinear, p.stride);
for y in 0..h {
for x in 0..w {
diff --git a/crates/raw/src/develop.rs b/crates/raw/src/develop.rs
index ebe8656a3..e3ab70b0c 100644
--- a/crates/raw/src/develop.rs
+++ b/crates/raw/src/develop.rs
@@ -195,16 +195,31 @@ pub(crate) fn resolve_neutral(s: &Sensor, opts: &DevelopOptions, sc: &Scale, war
/// Develops sensor data.
pub fn develop_sensor(s: &Sensor, opts: &DevelopOptions) -> Result<Developed> {
let c = s.crop;
- if c.is_empty() || c.x + c.width > s.width || c.y + c.height > s.height || s.data.len() < s.width * s.height * s.samples {
+ let samples = s.width.checked_mul(s.height).and_then(|n| n.checked_mul(s.samples));
+ if c.is_empty()
+ || c.x.checked_add(c.width).is_none_or(|x| x > s.width)
+ || c.y.checked_add(c.height).is_none_or(|y| y > s.height)
+ || samples.is_none_or(|n| s.data.len() < n)
+ {
return Err(RawError::malformed("crop lies outside the sensor data"));
}
+ // LinearRaw can be monochrome (one sample) or RGB (three); CFA data needs one.
if s.samples != 1 && s.samples != 3 {
return Err(RawError::unsupported(format!("{} samples per pixel", s.samples)));
}
- // Working buffers: one f32 plane plus f32 RGB plus u16 RGB per pixel, and
- // a green plane for non-Bayer patterns.
+ if let Some(cfa) = &s.cfa
+ && (s.samples != 1
+ || cfa.width == 0
+ || cfa.height == 0
+ || cfa.width > 16
+ || cfa.height > 16
+ || cfa.colors.len() != cfa.width * cfa.height
+ || cfa.colors.iter().any(|c| *c > 2))
+ {
+ return Err(RawError::malformed("invalid sensor CFA pattern"));
+ }
let bayer = s.cfa.as_ref().is_none_or(|cfa| cfa.is_bayer());
- opts.limits.check(c.width as u64, c.height as u64, if bayer { 4 + 12 + 6 } else { 4 + 4 + 12 + 6 })?;
+ let ahd_jobs = working_memory(c.width, c.height, s.cfa.is_some(), bayer, opts, par::workers())?;
let mut warnings = s.warnings.clone();
let sc = Scale::new(s);
@@ -304,7 +319,7 @@ pub fn develop_sensor(s: &Sensor, opts: &DevelopOptions) -> Result<Developed> {
if bayer {
let p = cfa.phase(c.x, c.y);
pattern = Some(names(&p));
- rgb = demosaic(&plane, p, opts.demosaic, &to_xyz);
+ rgb = demosaic(&plane, p, opts.demosaic, &to_xyz, ahd_jobs);
} else {
let pat = Pattern::of(cfa, c.x, c.y);
pattern = Some(pat.colors.chunks(pat.w.max(1)).map(names).collect::<Vec<_>>().join("/"));
@@ -400,6 +415,36 @@ pub fn develop_sensor(s: &Sensor, opts: &DevelopOptions) -> Result<Developed> {
})
}
+/// Checks the peak of the two development phases. The CFA and non-Bayer green
+/// planes are freed before the u16 output is allocated; AHD scratch is bounded
+/// by reducing simultaneous bands when needed. Sensor storage belongs to the
+/// caller and is checked separately by the decoder.
+fn working_memory(w: usize, h: usize, cfa: bool, bayer: bool, opts: &DevelopOptions, workers: usize) -> Result<usize> {
+ let limits = &opts.limits;
+ limits.check(w as u64, h as u64, 18)?;
+ let pixels = (w as u64).saturating_mul(h as u64);
+ let output = pixels.saturating_mul(18).saturating_add((GAMMA_STEPS as u64 + 2) * 4);
+ let mut peak = output;
+ let mut jobs = workers.max(1);
+ if cfa {
+ let plane = (w as u64).saturating_add(2 * PAD as u64).saturating_mul((h as u64).saturating_add(2 * PAD as u64)).saturating_mul(4);
+ let mut mosaic = pixels.saturating_mul(if bayer { 12 } else { 16 }).saturating_add(plane);
+ if bayer && opts.demosaic == Demosaic::Ahd {
+ mosaic = mosaic.saturating_add(crate::demosaic::AHD_TABLE_BYTES);
+ let scratch = crate::demosaic::ahd_scratch(w as u64, h as u64);
+ let available = limits.max_alloc.saturating_sub(mosaic) / scratch.max(1);
+ jobs = jobs.min(crate::demosaic::ahd_bands(h)).min(usize::try_from(available).unwrap_or(usize::MAX));
+ // At least one band must fit, even when no parallelism is available.
+ mosaic = mosaic.saturating_add(scratch.saturating_mul(jobs.max(1) as u64));
+ }
+ peak = peak.max(mosaic);
+ }
+ if peak > limits.max_alloc || usize::try_from(peak).is_err() {
+ return Err(RawError::LimitExceeded(format!("{peak} bytes of RAW working memory exceed {}", limits.max_alloc)));
+ }
+ Ok(jobs.max(1))
+}
+
/// Gain-map factors (DNG OpcodeList2 GainMap) for data row `y`, columns
/// `x0..x0 + w`, sample `k`; `None` when no map touches the row.
fn gain_row(s: &Sensor, y: usize, x0: usize, w: usize, k: usize) -> Option<Vec<f32>> {
@@ -544,6 +589,34 @@ pub(crate) fn orient(src: Vec<u16>, w: usize, h: usize, o: u16) -> (Vec<u16>, us
mod tests {
use super::*;
+ #[test]
+ fn hundred_megapixel_bayer_fits_without_raising_default_limits() {
+ let mut opts = DevelopOptions::default();
+ for method in [Demosaic::Bilinear, Demosaic::Mhc, Demosaic::Ahd] {
+ opts.demosaic = method;
+ for workers in [1, 10, 32, 128] {
+ let jobs = working_memory(11648, 8736, true, true, &opts, workers).unwrap();
+ assert!(jobs <= workers);
+ if method == Demosaic::Ahd && workers >= 32 {
+ assert!(jobs < workers);
+ }
+ }
+ }
+ opts.limits.max_alloc = 1 << 30;
+ assert!(working_memory(11648, 8736, true, true, &opts, 1).is_err());
+ }
+
+ #[test]
+ fn working_memory_accounts_for_padding_and_at_least_one_ahd_band() {
+ let mut opts = DevelopOptions { demosaic: Demosaic::Ahd, ..Default::default() };
+ opts.limits.max_alloc = 100 * 100 * 22;
+ assert!(working_memory(100, 100, true, true, &opts, 1).is_err());
+ opts.demosaic = Demosaic::Mhc;
+ assert!(working_memory(100, 100, true, true, &opts, 1).is_ok());
+ opts.limits.max_alloc = 100 * 100 * 18;
+ assert!(working_memory(100, 100, false, true, &opts, 1).is_err());
+ }
+
#[test]
fn gamma_table_matches_powf() {
let lut = GammaLut::new();
diff --git a/crates/raw/src/par.rs b/crates/raw/src/par.rs
index a8e2c9f94..6d23fd70c 100644
--- a/crates/raw/src/par.rs
+++ b/crates/raw/src/par.rs
@@ -12,6 +12,35 @@ pub(crate) fn chunks_mut<T: Send>(buf: &mut [T], chunk: usize, f: impl Fn(usize,
buf.chunks_mut(chunk).enumerate().for_each(|(i, c)| f(i, c));
}
+/// Native worker count (the browser builds run sequentially).
+pub(crate) fn workers() -> usize {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ rayon::current_num_threads()
+ }
+ #[cfg(target_arch = "wasm32")]
+ {
+ 1
+ }
+}
+
+/// Processes normal-sized chunks with at most `jobs` live scratch buffers.
+pub(crate) fn chunks_mut_limited<T: Send>(buf: &mut [T], chunk: usize, jobs: usize, f: impl Fn(usize, &mut [T]) + Sync + Send) {
+ let chunk = chunk.max(1);
+ // Each worker holds one band's scratch at a time. When the normal worker
+ // count fits, preserve Rayon's fine-grained load balancing.
+ if jobs >= workers() {
+ chunks_mut(buf, chunk, f);
+ return;
+ }
+ let per_group = buf.len().div_ceil(chunk).div_ceil(jobs.max(1)).max(1);
+ chunks_mut(buf, chunk.saturating_mul(per_group), |group, part| {
+ for (local, c) in part.chunks_mut(chunk).enumerate() {
+ f(group * per_group + local, c);
+ }
+ });
+}
+
/// Maps `f` over `0..n`, keeping order.
pub(crate) fn map<T: Send>(n: usize, f: impl Fn(usize) -> T + Sync + Send) -> Vec<T> {
#[cfg(not(target_arch = "wasm32"))]
diff --git a/crates/raw/src/sensor.rs b/crates/raw/src/sensor.rs
index e8c65ebf5..585191b79 100644
--- a/crates/raw/src/sensor.rs
+++ b/crates/raw/src/sensor.rs
@@ -63,14 +63,22 @@ impl Cfa {
/// Colour at data coordinates.
#[inline]
pub fn color(&self, x: usize, y: usize) -> u8 {
- let cx = (x + self.width - self.origin_x % self.width) % self.width;
- let cy = (y + self.height - self.origin_y % self.height) % self.height;
- self.colors.get(cy * self.width + cx).copied().unwrap_or(1)
+ fn relative(v: usize, origin: usize, period: usize) -> Option<usize> {
+ if period == 0 {
+ return None;
+ }
+ let (v, origin) = (v % period, origin % period);
+ Some(if v >= origin { v - origin } else { period - (origin - v) })
+ }
+ let Some((cx, cy)) = relative(x, self.origin_x, self.width).zip(relative(y, self.origin_y, self.height)) else {
+ return 1;
+ };
+ cy.checked_mul(self.width).and_then(|i| i.checked_add(cx)).and_then(|i| self.colors.get(i)).copied().unwrap_or(1)
}
/// The 2×2 colours seen from data coordinates (`x0`, `y0`), row-major.
pub fn phase(&self, x0: usize, y0: usize) -> [u8; 4] {
- [self.color(x0, y0), self.color(x0 + 1, y0), self.color(x0, y0 + 1), self.color(x0 + 1, y0 + 1)]
+ [self.color(x0, y0), self.color(x0.saturating_add(1), y0), self.color(x0, y0.saturating_add(1)), self.color(x0.saturating_add(1), y0.saturating_add(1))]
}
/// `true` for a Bayer pattern: a 2×2 period holding one red, one blue and two
@@ -79,10 +87,11 @@ impl Cfa {
if self.width == 0 || self.height == 0 || self.width > 16 || self.height > 16 {
return false;
}
- let p = self.phase(self.origin_x, self.origin_y);
- let periodic = (0..self.height).all(|y| (0..self.width).all(|x| self.color(self.origin_x + x, self.origin_y + y) == p[(y % 2) * 2 + x % 2]));
- let greens_on_diagonal =
- (p[0] == 1 && p[3] == 1 && p[1] != 1 && p[2] != 1 && p[1] + p[2] == 2) || (p[1] == 1 && p[2] == 1 && p[0] != 1 && p[3] != 1 && p[0] + p[3] == 2);
+ let (ox, oy) = (self.origin_x % self.width, self.origin_y % self.height);
+ let p = self.phase(ox, oy);
+ let periodic = (0..self.height).all(|y| (0..self.width).all(|x| self.color(ox + x, oy + y) == p[(y % 2) * 2 + x % 2]));
+ let greens_on_diagonal = (p[0] == 1 && p[3] == 1 && p[1] != 1 && p[2] != 1 && u16::from(p[1]) + u16::from(p[2]) == 2)
+ || (p[1] == 1 && p[2] == 1 && p[0] != 1 && p[3] != 1 && u16::from(p[0]) + u16::from(p[3]) == 2);
periodic && greens_on_diagonal
}
}
@@ -110,7 +119,8 @@ impl BlackLevels {
pub fn at(&self, ax: usize, ay: usize, s: usize, spp: usize) -> f32 {
let r = ay % self.rows.max(1);
let c = ax % self.cols.max(1);
- let base = self.values.get((r * self.cols.max(1) + c) * spp + s).or_else(|| self.values.first()).copied().unwrap_or(0.0);
+ let index = r.checked_mul(self.cols.max(1)).and_then(|i| i.checked_add(c)).and_then(|i| i.checked_mul(spp)).and_then(|i| i.checked_add(s));
+ let base = index.and_then(|i| self.values.get(i)).or_else(|| self.values.first()).copied().unwrap_or(0.0);
base + self.delta_h.get(ax).copied().unwrap_or(0.0) + self.delta_v.get(ay).copied().unwrap_or(0.0)
}
diff --git a/crates/raw/tests/development_limits.rs b/crates/raw/tests/development_limits.rs
new file mode 100644
index 000000000..4e5e1636d
--- /dev/null
+++ b/crates/raw/tests/development_limits.rs
@@ -0,0 +1,91 @@
+//! Development limits and hostile public sensor metadata.
+use photocraft_raw::testgen::DngSpec;
+use photocraft_raw::*;
+
+fn small_sensor() -> Sensor {
+ decode(&DngSpec::cfa(64, 48, vec![1000; 64 * 48]).build(), &Limits::default()).unwrap()
+}
+
+#[test]
+fn checks_peak_live_buffers_instead_of_summing_disjoint_phases() {
+ let sensor = decode(&DngSpec::cfa(128, 96, vec![1000; 128 * 96]).build(), &Limits::default()).unwrap();
+ let mut opts = DevelopOptions { demosaic: Demosaic::Mhc, ..Default::default() };
+ opts.limits.max_alloc = 128 * 96 * 18 + (4096 + 2) * 4;
+ let expected = develop_sensor(&sensor, &DevelopOptions { demosaic: Demosaic::Mhc, ..Default::default() }).unwrap();
+ assert_eq!(develop_sensor(&sensor, &opts).unwrap().rgb, expected.rgb);
+ opts.limits.max_alloc -= 1;
+ assert!(matches!(develop_sensor(&sensor, &opts), Err(RawError::LimitExceeded(_))));
+}
+
+#[test]
+fn monochrome_and_rgb_linear_raw_preserve_output_and_memory_limits() {
+ let (w, h) = (32, 24);
+ for samples in [1, 3] {
+ let data = (0..w * h).flat_map(|i| (0..samples).map(move |c| (i % w * 1000 + c * 5000) as u16)).collect();
+ let spec = DngSpec { samples, monochrome: samples == 1, ..DngSpec::cfa(w, h, data) };
+ let sensor = decode(&spec.build(), &Limits::default()).unwrap();
+ assert!(sensor.cfa.is_none());
+ assert_eq!(sensor.samples, samples);
+ let expected = develop_sensor(&sensor, &DevelopOptions::default()).unwrap();
+ let mut opts = DevelopOptions::default();
+ opts.limits.max_alloc = 32 * 1024;
+ let got = develop_sensor(&sensor, &opts).unwrap();
+ assert_eq!(got.rgb, expected.rgb);
+ assert_eq!((got.width, got.height), (w as u32, h as u32));
+ if samples == 1 {
+ assert!(got.rgb.as_chunks::<3>().0.iter().all(|p| p[0] == p[1] && p[1] == p[2]));
+ }
+ // Even the encoded RGB output alone cannot fit this budget.
+ opts.limits.max_alloc = (expected.rgb.len() * 2 - 1) as u64;
+ assert!(matches!(develop_sensor(&sensor, &opts), Err(RawError::LimitExceeded(_))));
+ }
+}
+
+#[test]
+fn invalid_public_sensor_metadata_returns_errors() {
+ let sensor = small_sensor();
+ let mut cases = Vec::new();
+ let mut s = sensor.clone();
+ s.crop.x = usize::MAX;
+ cases.push(s);
+ let mut s = sensor.clone();
+ s.width = usize::MAX;
+ cases.push(s);
+ let mut s = sensor.clone();
+ s.samples = usize::MAX;
+ cases.push(s);
+ let mut s = sensor.clone();
+ s.cfa.as_mut().unwrap().width = 0;
+ cases.push(s);
+ let mut s = sensor.clone();
+ s.cfa.as_mut().unwrap().colors.clear();
+ cases.push(s);
+ let mut s = sensor.clone();
+ s.cfa.as_mut().unwrap().colors[0] = 255;
+ cases.push(s);
+ let mut s = sensor.clone();
+ s.cfa = None;
+ s.samples = 2;
+ s.data.resize(64 * 48 * 2, 1000);
+ cases.push(s);
+ let mut s = sensor.clone();
+ s.samples = 3;
+ s.data.resize(64 * 48 * 3, 1000);
+ cases.push(s);
+ for s in cases {
+ assert!(develop_sensor(&s, &DevelopOptions::default()).is_err());
+ }
+}
+
+#[test]
+fn extreme_cfa_and_black_origins_do_not_overflow() {
+ let mut sensor = small_sensor();
+ let cfa = sensor.cfa.as_mut().unwrap();
+ cfa.origin_x = usize::MAX;
+ cfa.origin_y = usize::MAX;
+ assert!(cfa.is_bayer());
+ sensor.black.rows = usize::MAX;
+ sensor.black.cols = usize::MAX;
+ assert!(develop_sensor(&sensor, &DevelopOptions::default()).is_ok());
+ assert_eq!(Cfa { width: 0, height: 0, colors: vec![], origin_x: 0, origin_y: 0 }.color(1, 2), 1);
+}