diff --git a/Cargo.lock b/Cargo.lock index a9cf2d2ef3..c5c4f529a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3464,6 +3464,7 @@ dependencies = [ name = "craft-tga" version = "0.1.0" dependencies = [ + "image", "thiserror 2.0.21", ] @@ -3471,9 +3472,11 @@ dependencies = [ name = "craft-tiff" version = "0.1.0" dependencies = [ + "image", "proptest", "serde", "thiserror 2.0.21", + "tiff", ] [[package]] diff --git a/crates/aaf/src/aaf.rs b/crates/aaf/src/aaf.rs index efa618fb39..8e6e600af2 100644 --- a/crates/aaf/src/aaf.rs +++ b/crates/aaf/src/aaf.rs @@ -37,6 +37,7 @@ //! name), `FilmCraft Frame Size` and `FilmCraft Audio Sample Rate` (on the composition). mod ids; +pub mod properties; mod read; pub(crate) mod store; mod write; diff --git a/crates/aaf/src/aaf/properties.rs b/crates/aaf/src/aaf/properties.rs new file mode 100644 index 0000000000..5db9619aca --- /dev/null +++ b/crates/aaf/src/aaf/properties.rs @@ -0,0 +1,86 @@ +//! Borrowed little-endian AAF property-stream records, independent of CFB and object policy. + +/// One indexed AAF property. The payload borrows the original stream. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Property<'a> { + pub id: u16, + pub form: u16, + pub payload: &'a [u8], +} + +/// Malformed property-stream framing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PropertyError { + ShortHeader, + UnsupportedByteOrder, + TruncatedIndex, + TruncatedValue, +} + +/// Property-stream record iterator. It does not deduplicate IDs, interpret forms, +/// copy payloads or impose object budgets; those decisions belong to the caller. +#[derive(Clone, Debug)] +pub struct Properties<'a> { + headers: std::slice::Iter<'a, [u8; 6]>, + payload: &'a [u8], +} + +impl<'a> Properties<'a> { + /// Validate the header and complete index. Payload extents are checked during + /// iteration; callers can validate all extents before copying by iterating a clone. + pub fn new(stream: &'a [u8]) -> Result { + let [order, _, lo, hi, tail @ ..] = stream else { return Err(PropertyError::ShortHeader) }; + if *order != 0x4c { + return Err(PropertyError::UnsupportedByteOrder); + } + let count = usize::from(u16::from_le_bytes([*lo, *hi])); + let (headers, payload) = tail.split_at_checked(count * 6).ok_or(PropertyError::TruncatedIndex)?; + Ok(Self { headers: headers.as_chunks::<6>().0.iter(), payload }) + } + pub(super) fn remaining_count(&self) -> usize { + self.headers.len() + } + + // The store checks duplicate IDs before validating the corresponding payload, + // so a record that is both duplicate and truncated retains its old diagnostic. + pub(super) fn next_id(&self) -> Option { + let [lo, hi, ..] = self.headers.as_slice().first()?; + Some(u16::from_le_bytes([*lo, *hi])) + } +} + +impl<'a> Iterator for Properties<'a> { + type Item = Result, PropertyError>; + + fn next(&mut self) -> Option { + let [id0, id1, form0, form1, len0, len1] = self.headers.next()?; + let len = usize::from(u16::from_le_bytes([*len0, *len1])); + let Some((payload, tail)) = self.payload.split_at_checked(len) else { + self.headers = [].iter(); + return Some(Err(PropertyError::TruncatedValue)); + }; + self.payload = tail; + Some(Ok(Property { id: u16::from_le_bytes([*id0, *id1]), form: u16::from_le_bytes([*form0, *form1]), payload })) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn records_borrow_ordered_payloads_without_deduplicating() { + let stream = [0x4c, 0x20, 2, 0, 0x55, 0, 0x82, 0, 2, 0, 0x55, 0, 0x22, 0, 1, 0, 9, 8, 7]; + let mut records = Properties::new(&stream).unwrap(); + assert_eq!(records.remaining_count(), 2); + assert_eq!(records.next_id(), Some(0x55)); + let first = records.next().unwrap().unwrap(); + assert_eq!(records.next_id(), Some(0x55)); + let second = records.next().unwrap().unwrap(); + assert_eq!(first, Property { id: 0x55, form: 0x82, payload: &[9, 8] }); + assert_eq!(second, Property { id: 0x55, form: 0x22, payload: &[7] }); + assert!(std::ptr::eq(first.payload, &stream[16..18])); + assert!(std::ptr::eq(second.payload, &stream[18..19])); + assert!(records.next().is_none()); + } +} diff --git a/crates/aaf/src/aaf/store.rs b/crates/aaf/src/aaf/store.rs index 859c0ea776..27bfad8560 100644 --- a/crates/aaf/src/aaf/store.rs +++ b/crates/aaf/src/aaf/store.rs @@ -450,28 +450,21 @@ impl R<'_> { } let mut o = Obj::new(e.clsid); let props = self.stream(entry, "properties")?; - if props.len() < 4 { - return Err(bad("short properties stream")); - } - if props[0] != BYTE_ORDER_LE { - return Err(bad("big-endian AAF files are not supported")); - } - let n = rd_u16(&props, 2).unwrap_or(0) as usize; - let mut at = 4 + n * 6; - if at > props.len() { - return Err(bad("truncated property index")); - } + use super::properties::{Properties, Property, PropertyError}; + let framing = |e| match e { + PropertyError::ShortHeader => bad("short properties stream"), + PropertyError::UnsupportedByteOrder => bad("big-endian AAF files are not supported"), + PropertyError::TruncatedIndex => bad("truncated property index"), + PropertyError::TruncatedValue => bad("truncated property value"), + }; + let mut records = Properties::new(&props).map_err(framing)?; // A properties stream can name tens of thousands of ids: do not rescan all earlier ids. - let mut seen = std::collections::HashSet::with_capacity(n); - for i in 0..n { - let (Some(pid), Some(sf), Some(len)) = (rd_u16(&props, 4 + i * 6), rd_u16(&props, 6 + i * 6), rd_u16(&props, 8 + i * 6)) else { - return Err(bad("truncated property index")); - }; + let mut seen = std::collections::HashSet::with_capacity(records.remaining_count()); + while let Some(pid) = records.next_id() { if !seen.insert(pid) { return Err(bad("duplicate property id")); } - let v = props.get(at..at + len as usize).ok_or_else(|| bad("truncated property value"))?; - at += len as usize; + let Property { form: sf, payload: v, .. } = records.next().ok_or_else(|| bad("truncated property index"))?.map_err(framing)?; let value = match sf { SF_STRONG => { let c = self.child(entry, &utf16_of(v))?; diff --git a/crates/develop/Cargo.toml b/crates/develop/Cargo.toml index c66c81faaa..19335b990f 100644 --- a/crates/develop/Cargo.toml +++ b/crates/develop/Cargo.toml @@ -17,6 +17,7 @@ craft-develop-model = { workspace = true } craft-geom = { workspace = true } craft-raw = { workspace = true } serde = { workspace = true } +serde_json = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rayon = { workspace = true } @@ -24,4 +25,3 @@ rayon = { workspace = true } [dev-dependencies] craft-render-parity = { workspace = true } proptest = { workspace = true } -serde_json = { workspace = true } diff --git a/crates/develop/src/camera_raw/local_tone.rs b/crates/develop/src/camera_raw/local_tone.rs new file mode 100644 index 0000000000..33f825b666 --- /dev/null +++ b/crates/develop/src/camera_raw/local_tone.rs @@ -0,0 +1,658 @@ +//! Shadows and Highlights as a local Laplacian filter. +//! +//! Adobe has said Camera Raw's process version 2012 rests on local Laplacian filters (S. Paris, +//! S. W. Hasinoff, J. Kautz, *Local Laplacian Filters: Edge-aware Image Processing with a +//! Laplacian Pyramid*, SIGGRAPH 2011). This follows that paper, in its fast form (M. Aubry et +//! al., *Fast Local Laplacian Filters*, ACM TOG 2014: the remapping sampled at a few reference +//! values, each pyramid coefficient interpolated between them), on the log2 luminance: +//! +//! - **Shadows** raises pixels darker than their surroundings, by an amount set by their own and +//! their surroundings' place in the image's range (1st to 99th percentile); **Highlights** +//! pulls pixels brighter than their surroundings toward them. Differences under a threshold +//! are left alone, so fine detail stays. +//! - Shadows then keeps the image's 99th percentile, Highlights its 1st (Photoshop keeps the +//! brightest content under Shadows and the darkest under Highlights). +//! - A uniform image is unchanged, edges keep no halo, and the result does not depend on the +//! image size. +//! +//! The strengths were fitted to Photoshop 25.4's Camera Raw Filter on ten public-domain photos +//! (black-box measurements, no Adobe code or data). It is an approximation: on those photos the +//! mean error against Photoshop is 2.8–9.4 levels (of 255) where the previous heuristic's was +//! 3.7–14.3. + +use super::util::par_rows; +use super::{Encoding, luma, quantile_rank}; + +/// Spacing of the fast filter's reference values in stops. Its remapping changes within about +/// half a stop, and coefficients interpolated across wider gaps show as contour lines on smooth +/// gradients (12 references over a whole raw's range left visible steps; at an eighth of a stop a +/// ramp's slope varies by under a third, as the remapping itself makes it). +pub const REF_STEP: f32 = 0.125; +/// Most reference values one filter uses. +pub const MAX_REFS: usize = 96; +/// The lowest reference sits at this quantile of the log luminance: the deepest 0.1 % (noise down +/// to the floor) share it instead of stretching the spacing. +pub const REF_LOW_QUANTILE: f32 = 0.001; +/// The filter works on `log2(luminance + LOG_FLOOR)`. +pub const LOG_FLOOR: f32 = 1.0 / 65536.0; +/// The filter runs on a copy at most this many pixels across; the change it makes is brought back +/// to full size by a guided upsampling, so a preview and the full image agree. +pub const WORK_SIDE: usize = 1600; +/// The image range the strengths are placed in: these quantiles of the log luminance averaged +/// over cells of a copy at most [`RANGE_SIDE`] pixels across. +pub const RANGE_QUANTILES: [f32; 2] = [0.01, 0.99]; +/// See [`RANGE_QUANTILES`]. +pub const RANGE_SIDE: usize = 256; +/// Knots of the strength curves over the surroundings' place in the image range (0 … 1). +pub const KNOTS: usize = 5; + +/// Shadows: how far a pixel darker than its surroundings rises, in stops per unit slider, as +/// a function of its own place in the image range (`own`) times a factor of its surroundings' +/// place (`around`); it rises fully once it is `sigma` stops below them. The lift depends on +/// the pixel's tone, not on the size of the difference, so it is the same at every pyramid +/// level and a big edge keeps no halo. Lowering (negative values) is `down` times as strong. +const SHADOWS: Lift = Lift { own: [-0.017, 0.466, 0.886, 1.221, -0.081], around: [4.566, 4.067, 1.088, 0.149, 0.878], sigma: 0.571, down: 0.808 }; +const HIGHLIGHTS: Side = Side { pull: [0.179, 0.141, 0.196, 0.629, 2.07], push: [0.156, 0.08, 0.175, 0.049, 1.261], sigma: 0.05 }; + +/// See [`SHADOWS`]. +struct Lift { + own: [f32; KNOTS], + around: [f32; KNOTS], + sigma: f32, + down: f32, +} + +/// Highlights: strengths per unit slider over the surroundings' place in the image range, for +/// lowering (`pull`, toward the surroundings) and raising (`push`), and the detail threshold in +/// stops. +struct Side { + pull: [f32; KNOTS], + push: [f32; KNOTS], + sigma: f32, +} + +/// Which remapping a [`TonePass`] uses. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ToneKind { + /// Pixels brighter than their surroundings move toward them (or away, for positive values) + /// by the part of the difference past `sigma`. + Highlights, + /// Pixels darker than their surroundings rise (or sink) by an amount set by their own and + /// their surroundings' place in the image range. + Shadows, +} + +/// One pass of the filter resolved for a slider value: everything its remapping reads. +#[derive(Clone, Debug, PartialEq)] +pub struct TonePass { + pub kind: ToneKind, + /// Highlights: the slider / 100. Shadows: its strength (the slider / 100, times `down` when + /// negative). + pub amount: f32, + /// Highlights: the strengths for the slider's direction, then an unused row. Shadows: the + /// curves over the pixel's own (`own`) and its surroundings' (`around`) place. + pub knots: [[f32; KNOTS]; 2], + /// The detail threshold in stops. + pub sigma: f32, + /// The quantile of the log luminance the pass puts back where it was. + pub keep: f32, +} + +/// Shadows and Highlights resolved: Highlights runs first, then Shadows on its result. +#[derive(Clone, Debug, PartialEq)] +pub struct LocalTone { + pub passes: Vec, +} + +impl LocalTone { + /// The passes for the sliders (−100 … 100); `None` when both are 0. + pub fn new(shadows: f32, highlights: f32) -> Option { + let mut passes = Vec::new(); + if highlights != 0.0 { + let amount = highlights.clamp(-100.0, 100.0) / 100.0; + let strengths = if amount < 0.0 { HIGHLIGHTS.pull } else { HIGHLIGHTS.push }; + // Then the darkest content is put back where it was. + passes.push(TonePass { kind: ToneKind::Highlights, amount, knots: [strengths, [0.0; KNOTS]], sigma: HIGHLIGHTS.sigma, keep: 0.01 }); + } + if shadows != 0.0 { + let amount = shadows.clamp(-100.0, 100.0) / 100.0; + let k = if amount > 0.0 { amount } else { amount * SHADOWS.down }; + // Keep the brightest content. + passes.push(TonePass { kind: ToneKind::Shadows, amount: k, knots: [SHADOWS.own, SHADOWS.around], sigma: SHADOWS.sigma, keep: 0.99 }); + } + (!passes.is_empty()).then_some(LocalTone { passes }) + } +} + +impl TonePass { + /// The remapping of log luminance `x` around the reference `g`, in an image range that + /// starts at `lo` and is `span` stops wide. + pub fn remap(&self, x: f32, g: f32, lo: f32, span: f32) -> f32 { + match self.kind { + ToneKind::Highlights => x + knot((g - lo) / span, &self.knots[0]) * self.amount * excess((x - g).max(0.0), self.sigma), + ToneKind::Shadows => { + let below = ((g - x) / self.sigma).clamp(0.0, 1.0); + if below == 0.0 { + return x; + } + let w = below * below * (3.0 - 2.0 * below); + x + self.amount * knot((x - lo) / span, &self.knots[0]) * knot((g - lo) / span, &self.knots[1]) * w + } + } + } + + /// The pass on the log luminance `u`: the filter, then the kept quantile put back. + fn run(&self, u: &Plane) -> Plane { + let (lo, hi) = range(u); + let span = (hi - lo).max(1.0); + let o = llf(u, |x, g| self.remap(x, g, lo, span)); + let shift = quantile(&u.v, self.keep) - quantile(&o.v, self.keep); + Plane { w: o.w, h: o.h, v: o.v.iter().map(|v| v + shift).collect() } + } +} + +/// One channel, `w × h`. +struct Plane { + w: usize, + h: usize, + v: Vec, +} + +/// Mirrors `i` into `0..n` (the edge sample is not repeated). +fn mirror(i: isize, n: usize) -> usize { + let n = n as isize; + if n == 1 { + return 0; + } + let p = 2 * (n - 1); + let m = i.rem_euclid(p); + (if m >= n { p - m } else { m }) as usize +} + +/// The pyramid's binomial kernel. +pub const TAPS: [f32; 5] = [1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0]; + +/// Planes smaller than this run their rows on one thread: the filter builds a whole pyramid per +/// reference (up to 96), and splitting its small levels into one-row tasks cost more in rayon's +/// scheduling than the rows themselves (a fifth of a Shadows render on 36 MP, measured). +const PAR_MIN: usize = 1 << 15; + +/// [`par_rows`] for a plane, on one thread when it is small (see [`PAR_MIN`]). +fn rows(buf: &mut [f32], w: usize, f: impl Fn(usize, &mut [f32]) + Sync + Send) { + if buf.len() < PAR_MIN { + buf.chunks_mut(w.max(1)).enumerate().for_each(|(y, row)| f(y, row)); + } else { + par_rows(buf, w, 1, f); + } +} + +/// The binomial 5-tap blur, sampled every `step` pixels from 0 (1 = full resolution). +fn blur_step(p: &Plane, step: usize) -> Plane { + let (w2, h2) = (p.w.div_ceil(step), p.h.div_ceil(step)); + // Columns first at the kept rows, then rows at the kept columns. Each sum adds the same terms + // in the same order as a `mirror` per tap would, so the result is bit for bit the same; the + // source rows are found once per row and the columns mirrored only near the edges. + let mut tmp = vec![0.0f32; p.w * h2]; + rows(&mut tmp, p.w, |y2, row| { + let y = (y2 * step) as isize; + let src: [&[f32]; 5] = std::array::from_fn(|k| { + let r = mirror(y + k as isize - 2, p.h); + &p.v[r * p.w..(r + 1) * p.w] + }); + for (x, o) in row.iter_mut().enumerate() { + *o = (0..5).map(|k| TAPS[k] * src[k][x]).sum(); + } + }); + let mut out = vec![0.0f32; w2 * h2]; + rows(&mut out, w2, |y2, row| { + let src = &tmp[y2 * p.w..(y2 + 1) * p.w]; + for (x2, o) in row.iter_mut().enumerate() { + let x = x2 * step; + *o = if x >= 2 && x + 2 < p.w { + let s = &src[x - 2..x + 3]; + (0..5).map(|k| TAPS[k] * s[k]).sum() + } else { + (0..5).map(|k| TAPS[k] * src[mirror(x as isize + k as isize - 2, p.w)]).sum() + }; + } + }); + Plane { w: w2, h: h2, v: out } +} + +/// The next coarser level. +fn down(p: &Plane) -> Plane { + blur_step(p, 2) +} + +/// `p` brought up to `w × h`: zeros between samples, then the blur times four. +/// +/// Three samples in four are zero, so their taps are skipped instead of blurring a zero-filled +/// plane: the nonzero terms are added in the same order (skipping `+0.0` terms changes at most the +/// sign of a zero, and the filter only adds and exponentiates these values). +fn up(p: &Plane, w: usize, h: usize) -> Plane { + let (lh, lw) = (p.h.min(h.div_ceil(2)), p.w.min(w.div_ceil(2))); + // The source sample behind index `i` of a zero-stuffed axis of length `n` holding `lim` samples. + let src = |i: isize, n: usize, lim: usize| { + let m = mirror(i, n); + (m.is_multiple_of(2) && m / 2 < lim).then_some(m / 2) + }; + // Columns first, only at the even columns (the odd ones are all zero). + let mut tmp = vec![0.0f32; lw * h]; + if lw > 0 { + rows(&mut tmp, lw, |y, row| { + let taps: [Option<&[f32]>; 5] = std::array::from_fn(|k| src(y as isize + k as isize - 2, h, lh).map(|r| &p.v[r * p.w..r * p.w + lw])); + for (j, o) in row.iter_mut().enumerate() { + *o = (0..5).filter_map(|k| taps[k].map(|s| TAPS[k] * (s[j] * 4.0))).sum(); + } + }); + } + let mut out = vec![0.0f32; w * h]; + rows(&mut out, w, |y, row| { + let t = &tmp[y * lw..(y + 1) * lw]; + for (x, o) in row.iter_mut().enumerate() { + *o = if x >= 2 && x + 2 < w { + // Away from the edges no tap mirrors. + (0..5) + .filter_map(|k| { + let i = x + k - 2; + (i.is_multiple_of(2) && i / 2 < lw).then(|| TAPS[k] * t[i / 2]) + }) + .sum() + } else { + (0..5).filter_map(|k| src(x as isize + k as isize - 2, w, lw).map(|j| TAPS[k] * t[j])).sum() + }; + } + }); + Plane { w, h, v: out } +} + +/// The source rows of [`up`]`(p, w, h)` at output row `y`, one per tap (`None` where the +/// zero-stuffed row is all zeros). +fn up_rows(p: &Plane, h: usize, y: usize) -> [Option; 5] { + let lh = p.h.min(h.div_ceil(2)); + std::array::from_fn(|k| { + let m = mirror(y as isize + k as isize - 2, h); + (m.is_multiple_of(2) && m / 2 < lh).then_some(m / 2) + }) +} + +/// One sample of [`up`]`(p, w, h)`: column `x` of the output row whose [`up_rows`] are `rows`. +/// It adds the same terms in the same order as `up`, so it gives the same bits. +fn up_at(p: &Plane, w: usize, rows: &[Option; 5], x: usize) -> f32 { + let lw = p.w.min(w.div_ceil(2)); + let col = |j: usize| -> f32 { (0..5).filter_map(|k| rows[k].map(|r| TAPS[k] * (p.v[r * p.w + j] * 4.0))).sum() }; + if x >= 2 && x + 2 < w { + // Away from the edges no tap mirrors. + (0..5) + .filter_map(|k| { + let i = x + k - 2; + (i.is_multiple_of(2) && i / 2 < lw).then(|| TAPS[k] * col(i / 2)) + }) + .sum() + } else { + (0..5) + .filter_map(|k| { + let m = mirror(x as isize + k as isize - 2, w); + (m.is_multiple_of(2) && m / 2 < lw).then(|| TAPS[k] * col(m / 2)) + }) + .sum() + } +} + +/// Levels down to about 2 pixels on the short side. +fn depth(w: usize, h: usize) -> usize { + let mut s = w.min(h); + let mut n = 1; + while s > 2 { + s = s.div_ceil(2); + n += 1; + } + n +} + +fn gaussian(p: Plane, n: usize) -> Vec { + let mut g = vec![p]; + for _ in 1..n { + let next = down(&g[g.len() - 1]); + g.push(next); + } + g +} + +/// The local Laplacian filter of `u` with `remap(value, reference)`; the coarsest level is kept. +fn llf(u: &Plane, remap: impl Fn(f32, f32) -> f32 + Sync) -> Plane { + let n = depth(u.w, u.h); + let g = gaussian(Plane { w: u.w, h: u.h, v: u.v.clone() }, n); + // References span the image's tones (see `REF_LOW_QUANTILE`). + let hi = u.v.iter().fold(f32::NEG_INFINITY, |a, &v| a.max(v)); + let lo = quantile(&u.v, REF_LOW_QUANTILE).min(hi); + if hi - lo <= 1e-6 || (hi - lo).is_nan() { + return Plane { w: u.w, h: u.h, v: u.v.clone() }; + } + let refs = (((hi - lo) / REF_STEP).ceil() as usize + 1).clamp(2, MAX_REFS); + let step = (hi - lo) / (refs - 1) as f32; + let mut lap: Vec> = g[..n - 1].iter().map(|p| vec![0.0; p.v.len()]).collect(); + for k in 0..refs { + let r = lo + step * k as f32; + let mut m = Plane { w: u.w, h: u.h, v: u.v.clone() }; + rows(&mut m.v, u.w, |_, row| { + for v in row.iter_mut() { + *v = remap(*v, r); + } + }); + let gr = gaussian(m, n); + for l in 0..n - 1 { + let (gl, fine, lw, lh, coarse) = (&g[l].v, &gr[l].v, g[l].w, g[l].h, &gr[l + 1]); + rows(&mut lap[l], lw, |y, row| { + let taps = up_rows(coarse, lh, y); + for (x, o) in row.iter_mut().enumerate() { + let i = y * lw + x; + let wgt = (1.0 - (gl[i].clamp(lo, hi) - r).abs() / step).max(0.0); + if wgt > 0.0 { + *o += wgt * (fine[i] - up_at(coarse, lw, &taps, x)); + } + } + }); + } + } + let mut o = Plane { w: g[n - 1].w, h: g[n - 1].h, v: g[n - 1].v.clone() }; + for l in (0..n - 1).rev() { + let mut next = up(&o, g[l].w, g[l].h); + for (a, b) in next.v.iter_mut().zip(&lap[l]) { + *a += b; + } + o = next; + } + o +} + +/// The `q` quantile (0 … 1) of `v`. +fn quantile(v: &[f32], q: f32) -> f32 { + let mut s = v.to_vec(); + // Selecting the one element is linear, a full sort is not (5 sorts of the work copy were a + // fifteenth of a render). `total_cmp` ties are bit-identical, so it is the sorted element. + let i = quantile_rank(s.len(), q); + *s.select_nth_unstable_by(i, f32::total_cmp).1 +} + +/// The image range: [`RANGE_QUANTILES`] of the log luminance on a copy at most [`RANGE_SIDE`] +/// pixels across. +fn range(u: &Plane) -> (f32, f32) { + let f = u.w.max(u.h).div_ceil(RANGE_SIDE).max(1); + let (sw, sh) = (u.w.div_ceil(f), u.h.div_ceil(f)); + let mut sum = vec![(0.0f64, 0u32); sw * sh]; + for y in 0..u.h { + for x in 0..u.w { + let c = &mut sum[(y / f) * sw + x / f]; + c.0 += f64::from(u.v[y * u.w + x]); + c.1 += 1; + } + } + let cells: Vec = sum.iter().filter(|c| c.1 > 0).map(|c| (c.0 / f64::from(c.1)) as f32).collect(); + (quantile(&cells, RANGE_QUANTILES[0]), quantile(&cells, RANGE_QUANTILES[1])) +} + +/// `d` past the detail threshold: about 0 below `sigma`, `d − sigma` well above it. +fn excess(d: f32, sigma: f32) -> f32 { + d - sigma * (d / sigma).tanh() +} + +fn knot(t: f32, k: &[f32; KNOTS]) -> f32 { + let x = t.clamp(0.0, 1.0) * (KNOTS - 1) as f32; + let i = (x as usize).min(KNOTS - 2); + k[i] + (k[i + 1] - k[i]) * (x - i as f32) +} + +/// Applies Shadows and Highlights (−100 … 100) to straight RGBA pixels encoded with `enc` +/// (`Encoding::of(DevelopInputs::encoding_gamma)`). The filter is deterministic, so it reads no grain seed. +pub(crate) fn apply(px: &mut [[f32; 4]], w: usize, h: usize, shadows: f32, highlights: f32, enc: Encoding) { + let Some(tone) = LocalTone::new(shadows, highlights) else { return }; + if w < 2 || h < 2 { + return; + } + let u = Plane { w, h, v: px.iter().map(|q| (luma([0, 1, 2].map(|c| enc.decode(q[c]))).max(0.0) + LOG_FLOOR).log2()).collect() }; + // The filter on a copy at most WORK_SIDE across (box-averaged in log). + let f = w.max(h).div_ceil(WORK_SIDE).max(1); + let small = if f == 1 { Plane { w, h, v: u.v.clone() } } else { shrink(&u, f) }; + let mut o = Plane { w: small.w, h: small.h, v: small.v.clone() }; + for pass in &tone.passes { + o = pass.run(&o); + } + // The change in log luminance, at full size. + let change: Vec = if f == 1 { + o.v.iter().zip(&u.v).map(|(a, b)| a - b).collect() + } else { + let d: Vec = o.v.iter().zip(&small.v).map(|(a, b)| a - b).collect(); + guided_upsample(&small, &d, &u) + }; + par_rows(px, w, 1, |y, row| { + for (x, q) in row.iter_mut().enumerate() { + let gain = change[y * w + x].exp2(); + for c in 0..3 { + q[c] = enc.encode(enc.decode(q[c]) * gain); + } + } + }); +} + +/// `u` averaged over `f × f` blocks. +fn shrink(u: &Plane, f: usize) -> Plane { + let (sw, sh) = (u.w.div_ceil(f), u.h.div_ceil(f)); + let mut v = vec![0.0f32; sw * sh]; + par_rows(&mut v, sw, 1, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + let (x0, y0) = (x * f, y * f); + let (x1, y1) = ((x0 + f).min(u.w), (y0 + f).min(u.h)); + let mut s = 0.0f64; + for yy in y0..y1 { + for xx in x0..x1 { + s += f64::from(u.v[yy * u.w + xx]); + } + } + *o = (s / ((x1 - x0) * (y1 - y0)) as f64) as f32; + } + }); + Plane { w: sw, h: sh, v } +} + +/// The change `d` computed on `small` brought to the size of `full`, following its edges: a local +/// linear model of the change against the log luminance (the guided filter of K. He, J. Sun, +/// *Fast Guided Filter*, 2015), fitted on the small copy and evaluated on the full one. +fn guided_upsample(small: &Plane, d: &[f32], full: &Plane) -> Vec { + let (sw, sh) = (small.w, small.h); + let r = 2; + let eps = 0.01; + let mean = |v: &[f32]| super::box_mean(v, sw, sh, r); + let ud: Vec = small.v.iter().zip(d).map(|(a, b)| a * b).collect(); + let uu: Vec = small.v.iter().map(|a| a * a).collect(); + let (mu, md, mud, muu) = (mean(&small.v), mean(d), mean(&ud), mean(&uu)); + let a: Vec = (0..sw * sh).map(|i| (mud[i] - mu[i] * md[i]) / (muu[i] - mu[i] * mu[i] + eps)).collect(); + let b: Vec = (0..sw * sh).map(|i| md[i] - a[i] * mu[i]).collect(); + let (ma, mb) = (mean(&a), mean(&b)); + let (fx, fy) = (sw as f32 / full.w as f32, sh as f32 / full.h as f32); + let mut out = vec![0.0f32; full.w * full.h]; + par_rows(&mut out, full.w, 1, |y, row| { + let sy = (y as f32 + 0.5) * fy - 0.5; + for (x, o) in row.iter_mut().enumerate() { + let sx = (x as f32 + 0.5) * fx - 0.5; + let av = super::util::bilinear(&ma, sw, sh, 1, 0, sx, sy); + let bv = super::util::bilinear(&mb, sw, sh, 1, 0, sx, sy); + *o = av * full.v[y * full.w + x] + bv; + } + }); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const SRGB: Encoding = Encoding(0.0); + + /// The plain blur: a `mirror` per tap over the whole plane, the reference for [`blur_step`]. + fn blur_step_reference(p: &Plane, step: usize) -> Plane { + let (w2, h2) = (p.w.div_ceil(step), p.h.div_ceil(step)); + let mut tmp = vec![0.0f32; p.w * h2]; + for y2 in 0..h2 { + for x in 0..p.w { + tmp[y2 * p.w + x] = (0..5).map(|k| TAPS[k] * p.v[mirror((y2 * step) as isize + k as isize - 2, p.h) * p.w + x]).sum(); + } + } + let mut out = vec![0.0f32; w2 * h2]; + for y2 in 0..h2 { + for x2 in 0..w2 { + out[y2 * w2 + x2] = (0..5).map(|k| TAPS[k] * tmp[y2 * p.w + mirror((x2 * step) as isize + k as isize - 2, p.w)]).sum(); + } + } + Plane { w: w2, h: h2, v: out } + } + + /// The plain upsampling: a zero-stuffed plane blurred whole, the reference for [`up`]. + fn up_reference(p: &Plane, w: usize, h: usize) -> Plane { + let mut z = Plane { w, h, v: vec![0.0; w * h] }; + for y in 0..p.h.min(h.div_ceil(2)) { + for x in 0..p.w.min(w.div_ceil(2)) { + z.v[2 * y * w + 2 * x] = p.v[y * p.w + x] * 4.0; + } + } + blur_step_reference(&z, 1) + } + + fn noise_plane(w: usize, h: usize, seed: u32) -> Plane { + let mut s = seed.wrapping_mul(2_654_435_761).max(1); + let v = (0..w * h) + .map(|_| { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + (s % 20_000) as f32 / 1000.0 - 16.0 + }) + .collect(); + Plane { w, h, v } + } + + #[test] + fn the_fast_pyramid_matches_the_plain_one_exactly() { + // Odd, even, tiny and large-enough-to-run-in-parallel sizes, as the pyramid's levels are. + for (i, (w, h)) in [(1, 1), (1, 7), (2, 2), (3, 5), (5, 3), (8, 6), (37, 23), (64, 64), (301, 211)].into_iter().enumerate() { + let p = noise_plane(w, h, i as u32 + 1); + for step in [1, 2] { + assert_eq!(blur_step(&p, step).v, blur_step_reference(&p, step).v, "blur {w}×{h} step {step}"); + } + for (uw, uh) in [(w * 2, h * 2), (w * 2 - 1, h * 2 - 1), (w * 2, h * 2 - 1), (w.max(2) * 2 - 3, h * 2)] { + let full = up(&p, uw, uh); + assert_eq!(full.v, up_reference(&p, uw, uh).v, "up {w}×{h} → {uw}×{uh}"); + // The filter samples `up` one pixel at a time; every sample has the same bits. + for y in 0..uh { + let taps = up_rows(&p, uh, y); + for x in 0..uw { + assert_eq!(up_at(&p, uw, &taps, x).to_bits(), full.v[y * uw + x].to_bits(), "up_at {w}×{h} → {uw}×{uh} at {x},{y}"); + } + } + } + } + } + + #[test] + fn quantile_is_the_sorted_element() { + let p = noise_plane(301, 211, 9); + let mut v = p.v.clone(); + // Ties and signed zeros, which `total_cmp` orders by their bits. + v.extend([0.0, -0.0, 0.0, -0.0, 3.5, 3.5, f32::MIN_POSITIVE]); + let mut sorted = v.clone(); + sorted.sort_by(f32::total_cmp); + for q in [0.0, 0.001, 0.01, 0.25, 0.5, 0.99, 1.0] { + let want = sorted[((sorted.len() - 1) as f32 * q).round() as usize]; + assert_eq!(quantile(&v, q).to_bits(), want.to_bits(), "q {q}"); + } + } + + fn grey(w: usize, h: usize, f: impl Fn(usize, usize) -> f32) -> Vec<[f32; 4]> { + (0..w * h).map(|i| f(i % w, i / w)).map(|v| [v, v, v, 1.0]).collect() + } + + #[test] + fn a_flat_image_is_unchanged() { + let mut px = grey(64, 48, |_, _| 0.4); + apply(&mut px, 64, 48, 100.0, -100.0, SRGB); + assert!(px.iter().all(|q| (q[0] - 0.4).abs() < 1e-5)); + } + + #[test] + fn shadows_raise_a_dark_area_without_a_halo() { + // A 0.1 | 0.6 step (the dark half is the image's black point, which Photoshop barely + // moves either): the bright half stays, and no halo forms on either side of the edge. + let (w, h) = (256, 128); + let mut px = grey(w, h, |x, _| if x < w / 2 { 0.1 } else { 0.6 }); + apply(&mut px, w, h, 100.0, 0.0, SRGB); + let row = &px[64 * w..65 * w]; + assert!((row[w / 2 + 1][0] - 0.6).abs() < 0.002 && (row[w - 5][0] - 0.6).abs() < 0.002); + let (far, near) = (row[10][0], row[w / 2 - 1][0]); + assert!((far - 0.1).abs() < 0.004 && (far - near).abs() < 0.004, "{far} {near}"); + } + + #[test] + fn grey_moves_as_in_photoshop() { + // Mid-grey with 1 % black (0.015) and white (0.97) corners, Photoshop 25.4: Shadows +100 + // takes the grey from 127.5 to 165.3, Highlights −100 to 89.6 (of 255). + let n = 256; + let image = |c: f32| { + grey(n, n, |x, y| { + if x >= n - 26 && y >= n - 26 { + 0.97 + } else if x >= n - 26 && y < 26 { + 0.015 + } else { + c + } + }) + }; + for (s, hl, want) in [(100.0, 0.0, 165.3), (0.0, -100.0, 89.6)] { + let mut px = image(0.5); + apply(&mut px, n, n, s, hl, SRGB); + let got = px[175 * n + 100][0] * 255.0; + assert!((got - want).abs() < 5.0, "{s} {hl}: {got} vs {want}"); + } + } + + #[test] + fn highlights_lower_a_bright_area_and_keep_the_darkest() { + let (w, h) = (192, 192); + let mut px = grey(w, h, |x, y| if (64..128).contains(&x) && (64..128).contains(&y) { 0.8 } else { 0.2 }); + apply(&mut px, w, h, 0.0, -100.0, SRGB); + assert!(px[96 * w + 96][0] < 0.75, "{}", px[96 * w + 96][0]); + assert!((px[5 * w + 5][0] - 0.2).abs() < 0.01, "{}", px[5 * w + 5][0]); + } + + #[test] + fn smooth_gradients_stay_smooth() { + // A soft ramp over eight stops, as in an out-of-focus background. Coefficients interpolated + // between references too far apart drew contour lines across such ramps (Shadows +100 on + // a D4 raw): the output must rise steadily, without ripples. + let (w, h) = (640, 48); + let mut px = grey(w, h, |x, _| crate::camera_raw::util::linear_to_srgb((x as f32 / (w - 1) as f32 * 8.0 - 9.0).exp2())); + for (s, hl) in [(100.0, 0.0), (0.0, -100.0), (-100.0, 100.0)] { + let mut p = px.clone(); + apply(&mut p, w, h, s, hl, SRGB); + let row: Vec = (0..w).map(|x| crate::camera_raw::util::srgb_to_linear(p[24 * w + x][0]).max(1e-6).log2()).collect(); + let steps: Vec = row.windows(2).map(|d| d[1] - d[0]).collect(); + assert!(steps.iter().all(|d| *d > 0.0), "{s} {hl}: the ramp reverses"); + let jumps: Vec = steps.windows(2).map(|d| (d[1] - d[0]).abs()).collect(); + let ripple = jumps[16..jumps.len() - 16].iter().fold(0.0f32, |a, b| a.max(*b)); + // The ramp rises 0.0125 stops per pixel; its slope may change by a third at most. + assert!(ripple < 0.004, "{s} {hl}: slope jumps by {ripple} stops per pixel"); + } + px.clear(); + } + + #[test] + fn the_result_does_not_depend_on_the_image_size() { + let at = |n: usize| { + let mut px = grey(n, n, |x, y| if x < n / 3 || y < n / 4 { 0.08 } else { 0.7 }); + apply(&mut px, n, n, 70.0, -60.0, SRGB); + [px[(n / 8) * n + n / 8][0], px[(3 * n / 4) * n + 3 * n / 4][0]] + }; + let (a, b) = (at(96), at(384)); + assert!((a[0] - b[0]).abs() < 0.02 && (a[1] - b[1]).abs() < 0.02, "{a:?} {b:?}"); + } +} diff --git a/crates/develop/src/camera_raw/mod.rs b/crates/develop/src/camera_raw/mod.rs new file mode 100644 index 0000000000..0119fa1a08 --- /dev/null +++ b/crates/develop/src/camera_raw/mod.rs @@ -0,0 +1,1317 @@ +//! Filter › Camera Raw Filter: a float develop pipeline over RGB pixels. +//! +//! Stages, in order (each skipped when its controls are neutral, so defaults are an identity): +//! +//! 1. **White balance and exposure** in linear light (the document's values decoded with the sRGB +//! curve as a perceptual working encoding; encoding is undone exactly at the end). +//! 2. **Dehaze**: K. He, J. Sun, X. Tang, *Single Image Haze Removal Using Dark Channel Prior*, +//! CVPR 2009 (dark channel, atmospheric light from its brightest 0.1 %, transmission refined +//! with the guided filter); negative amounts add haze toward the atmospheric light. +//! 3. **Tone** on luminance with colour ratios kept: Highlights / Shadows as exposure changes +//! weighted by an edge-preserving base layer (guided filter: K. He, J. Sun, X. Tang, *Guided +//! Image Filtering*, ECCV 2010), so local contrast survives; Contrast is an S-curve about +//! middle grey; Clarity (large radius, midtone weighted) and Texture (small radius) add +//! band-pass local contrast. Whites / Blacks follow as Photoshop's Camera Raw applies them: +//! image-adaptive global curves measured on Photoshop 25.4 (see `whites_blacks`). +//! 4. **Presence**: Vibrance (weighted toward less saturated colours) and Saturation. +//! 5. **Tone Curve**: parametric regions (Highlights, Lights, Darks, Shadows with movable splits) +//! then point curves (master and per channel), monotone cubic interpolation (F. Fritsch, +//! R. Carlson, *Monotone Piecewise Cubic Interpolation*, SIAM J. Numer. Anal. 1980). +//! 6. **Color Mixer (HSL)**: eight hue bands (red, orange, yellow, green, aqua, blue, purple, +//! magenta) with hat-function weights on the hue circle. +//! 7. **Color Grading**: shadows / midtones / highlights / global wheels (hue, saturation, +//! luminance) with Blending and Balance. +//! 8. **Detail**: sharpening on luminance (unsharp mask with Detail as halo control and Masking as +//! an edge mask) and noise reduction (luminance by guided filter, colour by chroma blur). +//! 9. **Effects**: post-crop vignette (amount, midpoint, roundness, feather, highlights, +//! style) and grain (amount, size, roughness; position-hashed, deterministic). + +#![allow(clippy::needless_range_loop)] // index loops mirror the maths (pixels × channels) +#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))] + +// The settings are the framework's: one model, with its validation and identity rules. +mod types; +mod util; + +pub use types::{GradeWheel as Wheel, MAX_CURVE_POINTS, RawDevelopSettings as CameraRaw, VignetteStyle as StoredVignetteStyle, validate_curve}; + +// PLAN: `develop`, `per_pixel` and `white_black_points` now take `&DevelopInputs`; their callers outside this set's files need it: +// crates/gpu/tests/it/camera_raw.rs and examples/bench_camera_raw.rs (spatial(p) is a free function now), dialogs-w51's +// camera_raw_gpu.rs `CameraRawGpu::develop` (takes the inputs beside `p`), crates/io/src/camera_raw_xmp.rs (`vignette_style` is the +// framework's `VignetteStyle` enum, not a string). Owner: tools-w28 / dialogs-w51 / the io set. +/// What one develop reads besides the settings. PhotoCraft sets these per job (the proxy's scale, the document's +/// transfer curve), so they are not part of the settings the workspace edits and the commands store. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct DevelopInputs { + /// Seeds the grain's noise. + pub seed: u32, + /// Pixel-size multiplier for previews on downsampled proxies (radii in px scale by it). + pub pixel_scale: f32, + /// The document's transfer curve: 0 for sRGB's, else the gamma of a power-law space (1.8 for ProPhoto). Whites and + /// Blacks act on light. + pub encoding_gamma: f32, +} + +impl Default for DevelopInputs { + fn default() -> Self { + DevelopInputs { seed: 0, pixel_scale: 1.0, encoding_gamma: 0.0 } + } +} + +use util::{hash01, linear_to_srgb, par_rows, srgb_to_linear}; + +pub mod local_tone; +mod per_pixel; +pub mod spatial; +mod whites_blacks; + +pub use local_tone::{LocalTone, ToneKind, TonePass}; +pub use per_pixel::{ + CURVE_LUT, Grade, Grain, PerPixel, Vignette, VignetteStyle, WB_STEPS, WhitesBlacks, WhitesBlacksModel, per_pixel, spatial, white_black_points, + whites_blacks_model, +}; +pub use spatial::{Clarity, Dehaze, Texture}; + +/// How the pixels encode light: the sRGB curve (gamma 0) or a pure power law (ProPhoto's 1.8, +/// Adobe RGB's 2.2). The tone controls work on light, so the document's own curve decodes it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Encoding(f32); + +impl Encoding { + pub(crate) fn of(gamma: f32) -> Self { + Encoding(if gamma.is_finite() && gamma > 0.0 { gamma.clamp(0.5, 4.0) } else { 0.0 }) + } + /// A value in this encoding as linear light. + pub(crate) fn decode(self, v: f32) -> f32 { + if self.0 > 0.0 { v.max(0.0).powf(self.0) } else { srgb_to_linear(v) } + } + /// Linear light back into this encoding, the inverse of [`Encoding::decode`]. + pub(crate) fn encode(self, v: f32) -> f32 { + if self.0 > 0.0 { v.max(0.0).powf(1.0 / self.0) } else { linear_to_srgb(v) } + } +} + +fn luma_linear(c: [f32; 3]) -> f32 { + luma(c) +} + +/// Hue band centres of the Color Mixer (degrees). +pub const HSL_BANDS: [f32; 8] = [0.0, 30.0, 60.0, 120.0, 180.0, 240.0, 270.0, 300.0]; + +/// How far a primary turns at Hue ±100 (degrees), as the Color Mixer's hue sliders do. +const CALIBRATION_TURN: f32 = 30.0; + +/// How much of each primary (red, green, blue) a hue is made of: triangular weights around +/// 0°, 120° and 240° that sum to one, so a colour between two primaries follows both. +pub fn calibration_weights(hue: f32) -> [f32; 3] { + let h = hue.rem_euclid(360.0); + let mut w = [0.0f32; 3]; + for (i, centre) in [0.0f32, 120.0, 240.0].iter().enumerate() { + let d = (h - centre).abs().min(360.0 - (h - centre).abs()); + w[i] = (1.0 - d / 120.0).max(0.0); + } + let sum: f32 = w.iter().sum(); + if sum > 1e-6 { w.map(|v| v / sum) } else { [1.0, 0.0, 0.0] } +} + +/// The Calibration panel's primaries on one linear-light pixel: its hue turns by the weighted +/// Hue of the primaries it is made of (±100 is ±30°, positive towards the next primary) and its +/// saturation scales by their weighted Saturation (−100 greys it); the luminance is kept, so +/// neutrals are untouched. +fn calibrate(c: [f32; 3], hue: [f32; 3], sat: [f32; 3]) -> [f32; 3] { + let [h, s, v] = rgb_to_hsv(c.map(|x| x.max(0.0))); + if s <= 1e-5 || v <= 1e-6 { + return c; + } + let w = calibration_weights(h); + let (mut dh, mut ds) = (0.0f32, 0.0f32); + for i in 0..3 { + dh += w[i] * hue[i].clamp(-100.0, 100.0); + ds += w[i] * sat[i].clamp(-100.0, 100.0); + } + let nh = h + dh / 100.0 * CALIBRATION_TURN; + let ns = (s * (1.0 + ds / 100.0)).clamp(0.0, 1.0); + let out = hsv_to_rgb(nh, ns, v); + let (l0, l1) = (luma(c), luma(out)); + if l1 > 1e-6 { out.map(|x| x * l0 / l1) } else { out } +} + +/// Shadows › Tint on one linear-light pixel: `tint` −1 (green) … 1 (magenta), weighted by how +/// dark the pixel is; the luminance is kept. +fn shadow_tint(c: [f32; 3], tint: f32) -> [f32; 3] { + let l = luma(c).max(0.0); + // Linear 0.18 is middle grey: full strength below it, fading out towards white. + let weight = (1.0 - (l / 0.18).sqrt().min(1.0)).powi(2) * 0.5 + (1.0 - l.min(1.0)).powi(4) * 0.5; + let k = tint * 0.12 * weight * (l + 0.02); + let o = [c[0] + k, c[1] - k, c[2] + k].map(|v| v.max(0.0)); + let l2 = luma(o); + if l2 > 1e-6 { o.map(|v| v * l / l2) } else { o } +} + +/// Camera Raw's Auto for the Light panel: Exposure, Contrast, Highlights, Shadows, Whites and +/// Blacks from the image's luminance histogram (`px` in the document's encoding). A well +/// exposed image gets near-zero settings; a dark one more exposure and lifted shadows; one +/// with a crushed or blown end gets Blacks or Whites back from the edge. The other panels are +/// left alone, as Camera Raw's Auto leaves them. +pub fn auto_tone(px: &[[f32; 4]], p: &mut CameraRaw) { + if px.is_empty() { + return; + } + let mut lum: Vec = px.iter().map(|q| luma([q[0], q[1], q[2]]).clamp(0.0, 1.0)).collect(); + lum.sort_by(|a, b| a.total_cmp(b)); + let at = |f: f32| lum[((lum.len() - 1) as f32 * f).round() as usize]; + let (black, shadow, median, light, white) = (at(0.001), at(0.1), at(0.5), at(0.9), at(0.999)); + // Exposure: the median towards middle grey (sRGB 0.46), damped so flat scenes aren't + // forced to it. + let median_lin = srgb_to_linear(median).max(1e-4); + p.exposure = (0.6 * (0.18f32 / median_lin).log2()).clamp(-2.0, 2.0); + // Blacks and Whites bring the ends to the edges without clipping more than Camera Raw does. + p.blacks = ((0.04 - black) * 400.0).clamp(-40.0, 40.0); + p.whites = ((0.96 - white) * 300.0).clamp(-40.0, 40.0); + // Shadows up when the darker tenth is crushed, highlights down when the brighter tenth is + // near white. + p.shadows = ((0.25 - shadow) * 200.0).clamp(0.0, 50.0); + p.highlights = ((light - 0.85) * -300.0).clamp(-50.0, 0.0); + // A little contrast for a flat histogram. + let spread = (light - shadow).max(0.0); + p.contrast = ((0.6 - spread) * 60.0).clamp(0.0, 25.0); + // Shown as Camera Raw shows them: Exposure to a hundredth of a stop, the others whole. + p.exposure = (p.exposure * 100.0).round() / 100.0; + for v in [&mut p.blacks, &mut p.whites, &mut p.shadows, &mut p.highlights, &mut p.contrast] { + *v = v.round(); + } +} + +fn luma(c: [f32; 3]) -> f32 { + 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2] +} + +fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { + let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// Box mean of a single-channel buffer (radius `r`, edge clamped): rows in parallel, then +/// columns in parallel bands with running column sums (cache-friendly, no transposes). +fn box_mean(v: &[f32], w: usize, h: usize, r: usize) -> Vec { + if r == 0 || w == 0 || h == 0 { + return v.to_vec(); + } + let n = (2 * r + 1) as f64; + let mut tmp = vec![0.0f32; w * h]; + par_rows(&mut tmp, w, 1, |y, row| { + let src = &v[y * w..(y + 1) * w]; + let at = |k: i64| src[k.clamp(0, w as i64 - 1) as usize] as f64; + let mut acc: f64 = (-(r as i64)..=r as i64).map(at).sum(); + for (x, o) in row.iter_mut().enumerate() { + *o = (acc / n) as f32; + acc += at(x as i64 + r as i64 + 1) - at(x as i64 - r as i64); + } + }); + const BAND: usize = 256; + let bands = util::par_map(w.div_ceil(BAND), |b| { + let (x0, x1) = (b * BAND, ((b + 1) * BAND).min(w)); + let bw = x1 - x0; + let row = |y: i64| &tmp[y.clamp(0, h as i64 - 1) as usize * w + x0..y.clamp(0, h as i64 - 1) as usize * w + x1]; + let mut acc = vec![0.0f64; bw]; + for y in -(r as i64)..=r as i64 { + for (a, v) in acc.iter_mut().zip(row(y)) { + *a += *v as f64; + } + } + let mut out = vec![0.0f32; bw * h]; + for y in 0..h { + for (o, a) in out[y * bw..(y + 1) * bw].iter_mut().zip(&acc) { + *o = (*a / n) as f32; + } + let (add, sub) = (row(y as i64 + r as i64 + 1), row(y as i64 - r as i64)); + for ((a, p), m) in acc.iter_mut().zip(add).zip(sub) { + *a += (*p - *m) as f64; + } + } + out + }); + let mut out = vec![0.0f32; w * h]; + for (b, band) in bands.iter().enumerate() { + let (x0, x1) = (b * BAND, ((b + 1) * BAND).min(w)); + let bw = x1 - x0; + for y in 0..h { + out[y * w + x0..y * w + x1].copy_from_slice(&band[y * bw..(y + 1) * bw]); + } + } + out +} + +/// Approximate Gaussian (three box passes). +fn gauss(v: &[f32], w: usize, h: usize, sigma: f32) -> Vec { + box_means(v, w, h, &spatial::gauss_radii(sigma)) +} + +/// Box means of radii `radii` in turn. +fn box_means(v: &[f32], w: usize, h: usize, radii: &[usize]) -> Vec { + let mut out = v.to_vec(); + for &r in radii { + out = box_mean(&out, w, h, r); + } + out +} + +/// Fast guided filter (K. He, J. Sun, *Fast Guided Filter*, arXiv 2015): the linear +/// coefficients are computed on a `s×` subsampled copy and upsampled bilinearly, which is +/// visually equivalent for the large radii used by tone controls at a fraction of the cost. +fn guided_fast(i: &[f32], p: &[f32], w: usize, h: usize, r: usize, eps: f32) -> Vec { + let (s, rs) = spatial::fast_guided_steps(r); + if s == 1 { + return guided(i, p, w, h, r, eps); + } + let (sw, sh) = (w.div_ceil(s), h.div_ceil(s)); + let down = |v: &[f32]| -> Vec { + let mut o = vec![0.0f32; sw * sh]; + let mut c = vec![0.0f32; sw * sh]; + for y in 0..h { + for x in 0..w { + let k = (y / s) * sw + x / s; + o[k] += v[y * w + x]; + c[k] += 1.0; + } + } + o.iter().zip(&c).map(|(a, b)| a / b.max(1.0)).collect() + }; + let (si, sp) = (down(i), down(p)); + let mi = box_mean(&si, sw, sh, rs); + let mp = box_mean(&sp, sw, sh, rs); + let ip: Vec = si.iter().zip(&sp).map(|(a, b)| a * b).collect(); + let ii: Vec = si.iter().map(|a| a * a).collect(); + let mip = box_mean(&ip, sw, sh, rs); + let mii = box_mean(&ii, sw, sh, rs); + let a: Vec = (0..sw * sh).map(|k| (mip[k] - mi[k] * mp[k]) / (mii[k] - mi[k] * mi[k] + eps)).collect(); + let b: Vec = (0..sw * sh).map(|k| mp[k] - a[k] * mi[k]).collect(); + let (ma, mb) = (box_mean(&a, sw, sh, rs), box_mean(&b, sw, sh, rs)); + let mut out = vec![0.0f32; w * h]; + let sf = s as f32; + par_rows(&mut out, w, 1, |y, row| { + let fy = (y as f32 + 0.5) / sf - 0.5; + for (x, o) in row.iter_mut().enumerate() { + let fx = (x as f32 + 0.5) / sf - 0.5; + let av = util::bilinear(&ma, sw, sh, 1, 0, fx, fy); + let bv = util::bilinear(&mb, sw, sh, 1, 0, fx, fy); + *o = av * i[y * w + x] + bv; + } + }); + out +} + +/// Guided filter of `p` guided by `i` (He et al. 2010). +fn guided(i: &[f32], p: &[f32], w: usize, h: usize, r: usize, eps: f32) -> Vec { + let mi = box_mean(i, w, h, r); + let mp = box_mean(p, w, h, r); + let ip: Vec = i.iter().zip(p).map(|(a, b)| a * b).collect(); + let ii: Vec = i.iter().map(|a| a * a).collect(); + let mip = box_mean(&ip, w, h, r); + let mii = box_mean(&ii, w, h, r); + let a: Vec = (0..w * h).map(|k| (mip[k] - mi[k] * mp[k]) / (mii[k] - mi[k] * mi[k] + eps)).collect(); + let b: Vec = (0..w * h).map(|k| mp[k] - a[k] * mi[k]).collect(); + let ma = box_mean(&a, w, h, r); + let mb = box_mean(&b, w, h, r); + (0..w * h).map(|k| ma[k] * i[k] + mb[k]).collect() +} + +/// Monotone cubic (Fritsch–Carlson) through `pts` (x ascending, 0..=1), evaluated into a LUT via +/// [`crate::color::spline::MonotoneCurve`]. +pub fn curve_lut(pts: &[[f32; 2]], n: usize) -> Vec { + // Keep the legacy f32 knot selection; normalizing in f64 can drop a saved knot. + let mut p: Vec<[f32; 2]> = pts.iter().map(|q| [q[0] / 255.0, q[1] / 255.0]).collect(); + p.sort_by(|a, b| a[0].total_cmp(&b[0])); + p.dedup_by(|a, b| (a[0] - b[0]).abs() < 1e-6); + if p.len() < 2 || n < 2 { + return (0..n).map(|k| if n <= 1 { 0.0 } else { k as f32 / (n - 1) as f32 }).collect(); + } + let p: Vec<_> = p.into_iter().map(|[x, y]| (f64::from(x), f64::from(y))).collect(); + crate::color::spline::MonotoneCurve::new(&p).to_lut(n).v.into_iter().map(|v| v.clamp(0.0, 1.0)).collect() +} + +/// Migrate a PhotoCraft Camera Raw / `filter.cameraRaw` settings object to shared +/// [`craft_develop_model::DevelopSettings`], stripping PhotoCraft-only transport keys +/// (`layer`, `encodingGamma`, `__cameraRawPsd`) before delegating to +/// [`craft_develop_model::migration::migrate_camera_raw`]. +pub fn migrate_to_develop_settings( + base: &craft_develop_model::DevelopSettings, + fields: &serde_json::Value, +) -> Result { + let Some(obj) = fields.as_object() else { + return craft_develop_model::migration::migrate_camera_raw(base, fields); + }; + let cleaned: serde_json::Map = obj + .iter() + .filter(|(k, _)| !matches!(k.as_str(), "layer" | "encodingGamma" | "__cameraRawPsd")) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + craft_develop_model::migration::migrate_camera_raw(base, &serde_json::Value::Object(cleaned)) +} + +fn lut_eval(lut: &[f32], v: f32) -> f32 { + if !(0.0..=1.0).contains(&v) { + // Extend linearly outside (float documents). + return if v < 0.0 { v + lut[0] } else { lut[lut.len() - 1] + (v - 1.0) }; + } + let x = v * (lut.len() - 1) as f32; + let i = (x as usize).min(lut.len() - 2); + let t = x - i as f32; + lut[i] + (lut[i + 1] - lut[i]) * t +} + +/// Parametric tone curve as a LUT (regions split at `splits`, each slider ±100 moves its region +/// by up to a quarter of the range, smoothly). +fn parametric_lut(p: &CameraRaw, n: usize) -> Vec { + let s = p.curve_splits.map(|v| v.clamp(5.0, 95.0) / 100.0); + let centres = [s[0] / 2.0, (s[0] + s[1]) / 2.0, (s[1] + s[2]) / 2.0, (s[2] + 1.0) / 2.0]; + let amounts = [p.curve_shadows, p.curve_darks, p.curve_lights, p.curve_highlights]; + let widths = [s[0].max(0.1), (s[1] - s[0]).max(0.1), (s[2] - s[1]).max(0.1), (1.0 - s[2]).max(0.1)]; + let mut lut: Vec = (0..n) + .map(|i| { + let x = i as f32 / (n - 1) as f32; + let mut y = x; + for k in 0..4 { + let d = (x - centres[k]) / (widths[k] * 1.2); + let bump = (-d * d * 2.0).exp() * x * (1.0 - x) * 4.0; + y += amounts[k] / 100.0 * 0.25 * bump; + } + y.clamp(0.0, 1.0) + }) + .collect(); + // Keep it monotone. + for i in 1..n { + lut[i] = lut[i].max(lut[i - 1]); + } + lut +} + +fn rgb_to_hsv(c: [f32; 3]) -> [f32; 3] { + let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2])); + let d = mx - mn; + let h = if d <= 1e-9 { + 0.0 + } else if mx == c[0] { + 60.0 * (((c[1] - c[2]) / d).rem_euclid(6.0)) + } else if mx == c[1] { + 60.0 * ((c[2] - c[0]) / d + 2.0) + } else { + 60.0 * ((c[0] - c[1]) / d + 4.0) + }; + [h, if mx > 1e-9 { d / mx } else { 0.0 }, mx] +} + +fn hsv_to_rgb(h: f32, s: f32, v: f32) -> [f32; 3] { + let h = h.rem_euclid(360.0) / 60.0; + let c = v * s; + let x = c * (1.0 - ((h % 2.0) - 1.0).abs()); + let (r, g, b) = match h as u32 { + 0 => (c, x, 0.0), + 1 => (x, c, 0.0), + 2 => (0.0, c, x), + 3 => (0.0, x, c), + 4 => (x, 0.0, c), + _ => (c, 0.0, x), + }; + let m = v - c; + [r + m, g + m, b + m] +} + +/// Weights of the eight HSL bands at hue `h` (hat functions between neighbouring centres). +pub fn band_weights(h: f32) -> [f32; 8] { + let mut w = [0.0f32; 8]; + for k in 0..8 { + let (c, prev, next) = (HSL_BANDS[k], HSL_BANDS[(k + 7) % 8], HSL_BANDS[(k + 1) % 8]); + let diff = (h - c + 540.0).rem_euclid(360.0) - 180.0; + let span = if diff >= 0.0 { (next - c).rem_euclid(360.0) } else { (c - prev).rem_euclid(360.0) }; + w[k] = (1.0 - diff.abs() / span.max(1e-3)).max(0.0); + } + w +} + +#[cfg(test)] +#[test] +fn band_weights_wrap_equivalent_hues_in_both_directions() { + let weights = band_weights(320.0); + assert_eq!(band_weights(-400.0), weights); + assert_eq!(band_weights(680.0), weights); +} + +/// Contrast, Highlights, Shadows, Texture and Clarity (the luminance stage) at rest. +fn local_tone_neutral(p: &CameraRaw) -> bool { + [p.contrast, p.highlights, p.shadows, p.texture, p.clarity].iter().all(|v| *v == 0.0) +} + +/// The Color Mixer at rest. +pub(crate) fn hsl_neutral(p: &CameraRaw) -> bool { + p.hsl_hue.iter().chain(&p.hsl_sat).chain(&p.hsl_lum).all(|v| *v == 0.0) +} + +/// Color Grading at rest. +pub(crate) fn grade_neutral(p: &CameraRaw) -> bool { + [&p.grade_shadows, &p.grade_midtones, &p.grade_highlights, &p.grade_global].iter().all(|w| w.sat == 0.0 && w.lum == 0.0) +} + +/// The Calibration panel at rest. +pub(crate) fn calibration_neutral(p: &CameraRaw) -> bool { + p.shadow_tint == 0.0 && p.calibration_hue.iter().chain(&p.calibration_sat).all(|v| *v == 0.0) +} + +/// The Tone Curve panel at rest. +fn curves_neutral(p: &CameraRaw) -> bool { + [p.curve_highlights, p.curve_lights, p.curve_darks, p.curve_shadows].iter().all(|v| *v == 0.0) + && [&p.point_curve, &p.point_curve_red, &p.point_curve_green, &p.point_curve_blue].iter().all(|c| is_linear(c)) +} + +fn is_linear(c: &[[f32; 2]]) -> bool { + c.len() < 2 || c.iter().all(|p| (p[0] - p[1]).abs() < 1e-3) +} + +/// Camera Raw's white-balance channel gains for Temperature / Tint (−100…100), relative to the +/// as-shot balance: warmer raises red and lowers blue (±35 % at the ends); a negative tint +/// raises green, a positive one lowers it toward magenta (±25 %). An observed approximation of +/// Adobe Camera Raw's sliders, not a colour-temperature model; shared by the filter (in linear +/// RGB) and the raw open (on the camera's white-balance multipliers) so both agree. +pub fn white_balance_gains(temperature: f32, tint: f32) -> [f32; 3] { + let t = temperature / 100.0; + let tn = tint / 100.0; + [1.0 + 0.35 * t, 1.0 - 0.25 * tn, 1.0 - 0.35 * t] +} + +/// Runs the Camera Raw pipeline on straight RGBA pixels (`w × h`, display-encoded RGB). +/// `float` keeps values above 1 (32-bit documents). `inputs` are the job's scale, grain seed and encoding. +pub fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: &DevelopInputs, float: bool) { + if px.is_empty() || p.is_identity() { + return; + } + let ps = inputs.pixel_scale.clamp(0.01, 1.0); + // 1. White balance + exposure in linear light. + if let Some(g) = per_pixel::gains(p) { + par_rows(px, w, 1, |_, row| { + for q in row.iter_mut() { + *q = balance(*q, g); + } + }); + } + // 1b. Calibration: the primaries turned and purer or greyer, and the shadows tinted, in + // linear light (the camera's primaries are what Camera Raw's panel calibrates). + if !calibration_neutral(p) { + let primaries = p.calibration_hue.iter().chain(&p.calibration_sat).any(|v| *v != 0.0); + let tint = p.shadow_tint.clamp(-100.0, 100.0) / 100.0; + par_rows(px, w, 1, |_, row| { + for q in row.iter_mut() { + let c = [srgb_to_linear(q[0]), srgb_to_linear(q[1]), srgb_to_linear(q[2])]; + let mut o = if primaries { calibrate(c, p.calibration_hue, p.calibration_sat) } else { c }; + if tint != 0.0 { + o = shadow_tint(o, tint); + } + for k in 0..3 { + q[k] = linear_to_srgb(o[k].max(0.0)); + } + } + }); + } + // 2. Dehaze. + if let Some(d) = Dehaze::new(p, w, h) { + dehaze(px, w, h, &d); + } + // 3. Tone. Highlights and Shadows: a local Laplacian filter (see `local_tone`). + if p.highlights != 0.0 || p.shadows != 0.0 { + local_tone::apply(px, w, h, p.shadows, p.highlights, Encoding::of(inputs.encoding_gamma)); + } + if !local_tone_neutral(p) && [p.contrast, p.texture, p.clarity].iter().any(|v| *v != 0.0) { + let l: Vec = px.iter().map(|q| luma([q[0], q[1], q[2]]).max(0.0)).collect(); + let lc: Vec = l.iter().map(|v| v.min(1.0)).collect(); + let clarity = Clarity::new(p, w, h); + let texture = Texture::new(p, inputs, w, h); + let clar = clarity.as_ref().map(|c| guided_fast(&lc, &lc, w, h, c.radius, spatial::CLARITY_EPS)); + let tex = texture.as_ref().map(|t| box_means(&lc, w, h, &t.radii)); + let k_con = p.contrast / 100.0 * 0.6; + par_rows(px, w, 1, |y, row| { + for (x, q) in row.iter_mut().enumerate() { + let i = y * w + x; + let l0 = l[i]; + let mut lv = lc[i]; + if let (Some(c), Some(k)) = (&clar, &clarity) { + let mw = 1.0 - (2.0 * lv.clamp(0.0, 1.0) - 1.0).powi(2); + lv += k.amount * (lc[i] - c[i]) * mw; + } + if let (Some(t), Some(k)) = (&tex, &texture) { + lv += k.amount * (lc[i] - t[i]).clamp(-spatial::TEXTURE_LIMIT, spatial::TEXTURE_LIMIT); + } + *q = tone(*q, l0, lc[i], lv, k_con); + } + }); + } + // 3b. Whites and Blacks: global curves adapted to the image's black and white points. + if p.whites != 0.0 || p.blacks != 0.0 { + let enc = Encoding::of(inputs.encoding_gamma); + let (bp, wp) = luminance_points(px, w, h, enc, |q| q); + let (xw, xb) = whites_blacks::amounts(p.whites.clamp(-100.0, 100.0), p.blacks.clamp(-100.0, 100.0), bp, wp); + whites_blacks::apply(px, w, xw, xb, enc); + } + // 4–7: per-pixel colour stages. + let need_color = p.vibrance != 0.0 || p.saturation != 0.0 || !curves_neutral(p) || !hsl_neutral(p) || !grade_neutral(p); + if need_color { + let par = (!(p.curve_highlights == 0.0 && p.curve_lights == 0.0 && p.curve_darks == 0.0 && p.curve_shadows == 0.0)) + .then(|| parametric_lut(p, 1024)); + let pts = |c: &Vec<[f32; 2]>| (!is_linear(c)).then(|| curve_lut(c, 1024)); + let (master, cr, cg, cb) = (pts(&p.point_curve), pts(&p.point_curve_red), pts(&p.point_curve_green), pts(&p.point_curve_blue)); + let hsl = !hsl_neutral(p); + let grade = !grade_neutral(p); + let Grade { tints, lums, blend, balance: bal } = Grade::new(p); + par_rows(px, w, 1, |_, row| { + for q in row.iter_mut() { + let mut c = [q[0], q[1], q[2]]; + if p.vibrance != 0.0 || p.saturation != 0.0 { + let l = luma(c); + let (mx, mn) = (c[0].max(c[1]).max(c[2]), c[0].min(c[1]).min(c[2])); + let sat = if mx > 1e-6 { (mx - mn) / mx } else { 0.0 }; + // Vibrance protects skin-ish hues (oranges) a little, like ACR. + let hue = rgb_to_hsv(c)[0]; + let skin = (1.0 - ((hue - 25.0).abs() / 25.0)).clamp(0.0, 1.0) * 0.5; + let k = 1.0 + p.saturation / 100.0 + p.vibrance / 100.0 * (1.0 - sat) * (1.0 - skin); + c = c.map(|v| l + (v - l) * k.max(0.0)); + } + if let Some(lut) = &par { + c = c.map(|v| lut_eval(lut, v)); + } + if let Some(lut) = &master { + c = c.map(|v| lut_eval(lut, v)); + } + for (ch, lut) in [&cr, &cg, &cb].iter().enumerate() { + if let Some(lut) = lut { + c[ch] = lut_eval(lut, c[ch]); + } + } + if hsl { + let [hh, s, v] = rgb_to_hsv(c.map(|x| x.max(0.0))); + if s > 1e-4 { + let wts = band_weights(hh); + let (mut dh, mut ds, mut dl) = (0.0f32, 0.0f32, 0.0f32); + for k in 0..8 { + dh += wts[k] * p.hsl_hue[k]; + ds += wts[k] * p.hsl_sat[k]; + dl += wts[k] * p.hsl_lum[k]; + } + let nh = hh + dh / 100.0 * 30.0; + let ns = (s * (1.0 + ds / 100.0)).clamp(0.0, 1.0); + let mut out = hsv_to_rgb(nh, ns, v); + // Keep the luminance, then apply the luminance shift weighted by saturation. + let (l0, l1) = (luma(c), luma(out)); + if l1 > 1e-6 { + out = out.map(|x| x * l0 / l1); + } + let k = 2f32.powf(dl / 100.0 * 1.0 * s); + c = out.map(|x| x * k); + } + } + if grade { + let l = luma(c).clamp(0.0, 1.0); + let sh = 1.0 - smoothstep(0.0, 0.5 + bal + blend, l); + let hi = smoothstep(0.5 + bal - blend, 1.0, l); + let mid = (1.0 - sh - hi).max(0.0); + let masks = [sh, mid, hi, 1.0]; + for k in 0..4 { + for ch in 0..3 { + c[ch] += masks[k] * tints[k][ch]; + } + if lums[k] != 0.0 { + let f = 2f32.powf(masks[k] * lums[k] / 100.0 * 0.6); + c = c.map(|x| x * f); + } + } + } + q[0] = c[0]; + q[1] = c[1]; + q[2] = c[2]; + } + }); + } + // 8. Detail. + if p.noise_luminance > 0.0 || p.noise_color > 0.0 || p.sharpen_amount > 0.0 { + detail(px, w, h, p, ps); + } + // 9. Effects. + if p.vignette_amount != 0.0 { + vignette(px, w, h, p); + } + if p.grain_amount > 0.0 { + let Grain { cell, roughness: rough, amount: amt, seed, scale: pscale } = Grain::new(p, inputs); + par_rows(px, w, 1, |y, row| { + for (x, q) in row.iter_mut().enumerate() { + // Sample in full-resolution coordinates so previews match the result. + let (fx, fy) = (x as f32 * pscale / cell, y as f32 * pscale / cell); + let n = value_noise(fx, fy, seed) * (1.0 - rough) + (value_noise(fx * 2.3, fy * 2.3, seed + 7) - 0.0) * rough; + let l = luma([q[0], q[1], q[2]]).clamp(0.0, 1.0); + let g = (n - 0.5) * 2.0 * amt * (0.4 + 2.4 * l * (1.0 - l)); + for c in 0..3 { + q[c] += g; + } + } + }); + } + if !float { + for q in px.iter_mut() { + for c in 0..3 { + q[c] = q[c].clamp(0.0, 1.0); + } + } + } +} + +/// The end of stage 3 on one pixel: Contrast (strength `k_con`) on the luminance `lv` that +/// Clarity and Texture left, then the pixel rescaled to it. `l0` is its luminance, `lc` that +/// clipped to 1. +fn tone(mut q: [f32; 4], l0: f32, lc: f32, mut lv: f32, k_con: f32) -> [f32; 4] { + if k_con != 0.0 { + let tau = std::f32::consts::TAU; + let xx = lv.clamp(0.0, 1.0); + lv += -k_con * (tau * xx).sin() / tau; + } + let lv = lv.max(0.0) + (l0 - lc); + let ratio = if l0 > 1e-5 { lv / l0 } else { 1.0 }; + for c in 0..3 { + q[c] = if l0 > 1e-5 { q[c] * ratio } else { q[c] + (lv - l0) }; + } + q +} + +/// Stage 3 on one pixel when Contrast is its only control. +fn contrast(q: [f32; 4], k_con: f32) -> [f32; 4] { + let l0 = luma([q[0], q[1], q[2]]).max(0.0); + let lc = l0.min(1.0); + tone(q, l0, lc, lc, k_con) +} + +/// Stage 1 on one pixel: white balance and exposure `gains` in linear light. +fn balance(mut q: [f32; 4], g: [f32; 3]) -> [f32; 4] { + for c in 0..3 { + q[c] = linear_to_srgb((srgb_to_linear(q[c]) * g[c]).max(0.0)); + } + q +} + +/// The index of the `q` quantile (0 … 1) among `len` sorted values, as every percentile in the +/// develop picks it. +pub fn quantile_rank(len: usize, q: f32) -> usize { + let last = len.saturating_sub(1); + ((last as f32 * q).round() as usize).min(last) +} + +#[cfg(test)] +#[test] +fn quantile_rank_keeps_the_upper_endpoint_inside_the_sample() { + // This last index rounds up when cast to f32. + let len = 16_777_220; + assert_eq!(quantile_rank(len, 1.0), len - 1); + assert_eq!(quantile_rank(4, 0.5), 2); + assert_eq!(quantile_rank(0, 1.0), 0); +} + +/// The image's black and white points as sRGB-encoded grey levels: the 3rd percentile of the +/// luminance and the 99.5th of the brightest channel, on a copy at most 256 pixels across (so a +/// preview proxy and the full image agree). `map` is applied to each pixel first. +fn luminance_points(px: &[[f32; 4]], w: usize, h: usize, enc: Encoding, map: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> (f32, f32) { + let f = w.max(h).div_ceil(whites_blacks::POINTS_SIDE).max(1); + let (sw, sh) = (w.div_ceil(f), h.div_ceil(f)); + // Each band of `f` rows sums into its own row of cells, in the same order as one pass would. + let bands = util::par_map(sh, |sy| { + let mut sum = vec![[0.0f64; 4]; sw]; + for y in sy * f..((sy + 1) * f).min(h) { + for x in 0..w { + let q = map(px[y * w + x]); + let s = &mut sum[x / f]; + for c in 0..3 { + s[c] += f64::from(enc.decode(q[c]).clamp(0.0, 1.0)); + } + s[3] += 1.0; + } + } + sum + }); + let cells: Vec<[f32; 3]> = bands.iter().flatten().filter(|s| s[3] > 0.0).map(|s| [0, 1, 2].map(|c| (s[c] / s[3]) as f32)).collect(); + if cells.is_empty() { + return (0.0, 1.0); + } + let pct = |mut v: Vec, q: f32| { + v.sort_by(f32::total_cmp); + v[quantile_rank(v.len(), q)] + }; + let bp = pct(cells.iter().map(|c| luma(*c)).collect(), whites_blacks::POINT_QUANTILES[0]); + let wp = pct(cells.iter().map(|c| c[0].max(c[1]).max(c[2])).collect(), whites_blacks::POINT_QUANTILES[1]); + (linear_to_srgb(bp), linear_to_srgb(wp)) +} + +fn value_noise(x: f32, y: f32, seed: u64) -> f32 { + let (xi, yi) = (x.floor(), y.floor()); + let (tx, ty) = (x - xi, y - yi); + let (sx, sy) = (tx * tx * (3.0 - 2.0 * tx), ty * ty * (3.0 - 2.0 * ty)); + let h = |dx: i64, dy: i64| hash01(xi as i64 + dx, yi as i64 + dy, seed); + let top = h(0, 0) + (h(1, 0) - h(0, 0)) * sx; + let bot = h(0, 1) + (h(1, 1) - h(0, 1)) * sx; + top + (bot - top) * sy +} + +/// Dehaze's copy of `px` (`w × h`): each pixel mapped by `map`, clipped to 0 … 1 and averaged over +/// `d.factor × d.factor` blocks, each block summed in raster order. +fn haze_cells(px: &[[f32; 4]], w: usize, h: usize, d: &Dehaze, map: impl Fn([f32; 4]) -> [f32; 4] + Sync) -> Vec<[f32; 3]> { + let (k, [sw, sh]) = (d.factor, d.size); + let bands = util::par_map(sh, |sy| { + let mut small = vec![[0.0f32; 3]; sw]; + let mut cnt = vec![0f32; sw]; + for y in sy * k..((sy + 1) * k).min(h) { + for x in 0..w { + let q = map(px[y * w + x]); + let i = x / k; + for c in 0..3 { + small[i][c] += q[c].clamp(0.0, 1.0); + } + cnt[i] += 1.0; + } + } + small.iter().zip(&cnt).map(|(s, c)| s.map(|v| v / c.max(1.0))).collect::>() + }); + bands.into_iter().flatten().collect() +} + +fn dehaze(px: &mut [[f32; 4]], w: usize, h: usize, d: &Dehaze) { + // Transmission on a ≤ DEHAZE_SIDE px proxy, upsampled. + let (k, [sw, sh], r, amount) = (d.factor, d.size, d.radius, d.amount); + let small = haze_cells(px, w, h, d, |q| q); + // The minimum (or, with `f32::max`, maximum) over each (2r + 1)² window. + let rank_filter = |v: &[f32], start: f32, pick: fn(f32, f32) -> f32| -> Vec { + let mut a = vec![0.0f32; sw * sh]; + for y in 0..sh { + for x in 0..sw { + let (x0, x1) = (x.saturating_sub(r), (x + r).min(sw - 1)); + a[y * sw + x] = (x0..=x1).map(|xx| v[y * sw + xx]).fold(start, pick); + } + } + let mut b = vec![0.0f32; sw * sh]; + for y in 0..sh { + for x in 0..sw { + let (y0, y1) = (y.saturating_sub(r), (y + r).min(sh - 1)); + b[y * sw + x] = (y0..=y1).map(|yy| a[yy * sw + x]).fold(start, pick); + } + } + b + }; + let min_filter = |v: &[f32]| rank_filter(v, f32::MAX, f32::min); + let dark = min_filter(&small.iter().map(|c| c[0].min(c[1]).min(c[2])).collect::>()); + // Atmospheric light: mean colour of the brightest 0.1 % of the dark channel (ties in the + // order of the cells). + let mut idx: Vec = (0..sw * sh).collect(); + idx.sort_by(|&a, &b| dark[b].total_cmp(&dark[a])); + let top = d.top; + let mut air = [0.0f32; 3]; + for &i in &idx[..top] { + for c in 0..3 { + air[c] += small[i][c] / top as f32; + } + } + let air = air.map(|v| v.max(spatial::DEHAZE_AIR_FLOOR)); + let norm_dark = min_filter(&small.iter().map(|c| (c[0] / air[0]).min(c[1] / air[1]).min(c[2] / air[2])).collect::>()); + // Opened (a maximum filter of the same radius after the minimum): the minimum grows every + // dark object by `r`, so sky beside a dark building took its dark channel, counted as + // haze-free and kept a bright halo (#9273). Opening shrinks dark regions back to their + // outline and is still a lower bound of the dark channel over the window. It raises the dark + // channel on average, so the ω weight is scaled to keep the slider's overall strength. + let opened = rank_filter(&norm_dark, f32::MIN, f32::max); + // Summed in f64: an f32 running sum over the copy's few hundred thousand cells drifts by about + // 1e-5, which the low transmission beside haze multiplies up to a visible fraction of a level. + let mean = |v: &[f32]| (v.iter().map(|x| f64::from(*x)).sum::() / v.len().max(1) as f64) as f32; + let weight = spatial::DEHAZE_OMEGA * mean(&norm_dark) / mean(&opened).max(1e-6); + let t_raw: Vec = opened.iter().map(|d| 1.0 - weight * d).collect(); + let guide: Vec = small.iter().map(|c| luma(*c)).collect(); + let t = guided(&guide, &t_raw, sw, sh, d.guide_radius, spatial::DEHAZE_EPS); + let ks = k as f32; + par_rows(px, w, 1, |y, row| { + for (x, q) in row.iter_mut().enumerate() { + let tv = util::bilinear(&t, sw, sh, 1, 0, (x as f32 + 0.5) / ks - 0.5, (y as f32 + 0.5) / ks - 0.5).clamp(spatial::DEHAZE_T_FLOOR, 1.0); + for c in 0..3 { + let i = q[c]; + let j = (i - air[c]) / tv + air[c]; + q[c] = if amount >= 0.0 { i + (j - i) * amount } else { i + (air[c] - i) * (-amount) * 0.5 * (1.0 - tv * 0.5) }; + } + } + }); +} + +fn sharpening_detail(detail: f32) -> f32 { + let detail = if detail.is_nan() { CameraRaw::default().sharpen_detail } else { detail.clamp(0.0, 100.0) }; + detail / 100.0 +} + +fn detail(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, ps: f32) { + // The controls' documented 0..=100 range: raw values drive the filter radii below. + let [nl, nld, nc, ncd] = [p.noise_luminance, p.noise_luminance_detail, p.noise_color, p.noise_color_detail].map(|v| v.clamp(0.0, 100.0)); + // Work in Y + chroma (BT.709 luma, B−Y, R−Y). + let mut y: Vec = px.iter().map(|q| luma([q[0], q[1], q[2]])).collect(); + let mut cb: Vec = px.iter().zip(&y).map(|(q, l)| q[2] - l).collect(); + let mut cr: Vec = px.iter().zip(&y).map(|(q, l)| q[0] - l).collect(); + if nl > 0.0 { + let n = nl / 100.0; + let r = ((1.0 + 3.0 * n) * ps).round().max(1.0) as usize; + let smooth = guided(&y, &y, w, h, r, (n * 0.06).powi(2) + 1e-6); + let keep = nld / 100.0 * 0.5; + for i in 0..w * h { + y[i] = smooth[i] + (y[i] - smooth[i]) * keep; + } + } + if nc > 0.0 { + let sigma = (nc / 100.0 * 6.0 * ps).max(0.3); + let (bcb, bcr) = (gauss(&cb, w, h, sigma), gauss(&cr, w, h, sigma)); + let keep = ncd / 100.0 * 0.3; + for i in 0..w * h { + cb[i] = bcb[i] + (cb[i] - bcb[i]) * keep; + cr[i] = bcr[i] + (cr[i] - bcr[i]) * keep; + } + } + if p.sharpen_amount > 0.0 { + let sigma = (p.sharpen_radius.clamp(0.5, 3.0) * ps).max(0.3); + let blur = gauss(&y, w, h, sigma); + // Masking: an edge mask from the gradient of a smoothed luminance. + let mask: Option> = (p.sharpen_masking > 0.0).then(|| { + let s = gauss(&y, w, h, 1.0 * ps.max(0.5)); + let t = p.sharpen_masking / 100.0 * 0.08; + util::par_map(w * h, |i| { + let (x, yy) = (i % w, i / w); + let gx = s[yy * w + (x + 1).min(w - 1)] - s[yy * w + x.saturating_sub(1)]; + let gy = s[(yy + 1).min(h - 1) * w + x] - s[yy.saturating_sub(1) * w + x]; + smoothstep(t * 0.5, t + 1e-4, gx.hypot(gy)) + }) + }); + let amt = p.sharpen_amount / 100.0 * 1.2; + let det = sharpening_detail(p.sharpen_detail); + for i in 0..w * h { + let hp = y[i] - blur[i]; + // Low Detail damps large (halo-producing) differences. + let limit = 0.03 + det * 0.3; + let hp = hp.clamp(-limit, limit) * (0.5 + 0.5 * det); + let m = mask.as_ref().map_or(1.0, |m| m[i]); + y[i] += amt * hp * m; + } + } + for i in 0..w * h { + let (l, b, r) = (y[i], cb[i], cr[i]); + let (rr, bb) = (r + l, b + l); + let g = (l - 0.2126 * rr - 0.0722 * bb) / 0.7152; + px[i][0] = rr; + px[i][1] = g; + px[i][2] = bb; + } +} + +fn vignette(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw) { + let Vignette { amount: amt, highlights: hl, style, centre: [cx, cy], axes: [ax, ay], power: pw, edges: [edge0, edge1] } = Vignette::new(w, h, p); + par_rows(px, w, 1, |y, row| { + for (x, q) in row.iter_mut().enumerate() { + let (dx, dy) = (((x as f32 + 0.5 - cx) / ax).abs(), ((y as f32 + 0.5 - cy) / ay).abs()); + let r = (dx.powf(pw) + dy.powf(pw)).powf(1.0 / pw); + let m = smoothstep(edge0, edge1, r); + if m <= 0.0 { + continue; + } + let l = luma([q[0], q[1], q[2]]).clamp(0.0, 1.0); + match style { + VignetteStyle::PaintOverlay => { + let target = if amt < 0.0 { 0.0 } else { 1.0 }; + let k = m * amt.abs(); + for c in 0..3 { + q[c] += (target - q[c]) * k; + } + } + _ => { + let mut k = 2f32.powf(amt * 2.0 * m); + if amt < 0.0 && hl > 0.0 { + // Highlights: let bright areas punch through a darkening vignette. + let protect = smoothstep(0.6, 1.0, l) * hl; + k += (1.0 - k) * protect; + } + if style == VignetteStyle::ColorPriority { + let nl = l * k; + for c in 0..3 { + q[c] += nl - l; + } + } else { + for c in 0..3 { + q[c] *= k; + } + } + } + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `CameraRaw` with the named fields set (the type is `#[non_exhaustive]`, so no struct expression), or a copy of a base with them set. + macro_rules! cr { + ($($f:ident : $v:expr),* $(,)?) => {{ + let mut s = CameraRaw::default(); + $(s.$f = $v;)* + s + }}; + ($base:expr => $($f:ident : $v:expr),* $(,)?) => {{ + let mut s: CameraRaw = $base; + $(s.$f = $v;)* + s + }}; + } + + /// [`super::develop`] with the default inputs (full scale, sRGB encoding, seed 0). + fn develop(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, float: bool) { + super::develop(px, w, h, p, &DevelopInputs::default(), float); + } + + /// [`super::per_pixel`] with the default inputs. + fn per_pixel(p: &CameraRaw, w: usize, h: usize, float: bool, points: Option<(f32, f32)>) -> Option { + super::per_pixel(p, &DevelopInputs::default(), w, h, float, points) + } + + #[test] + fn sharpening_detail_stays_in_range_at_the_shared_entry_point() { + for value in [0.0_f32, 25.0, 37.5, 100.0] { + assert_eq!(sharpening_detail(value).to_bits(), (value / 100.0).to_bits()); + } + assert_eq!(sharpening_detail(-1.0), 0.0); + assert_eq!(sharpening_detail(101.0), 1.0); + assert_eq!(sharpening_detail(f32::NAN), sharpening_detail(CameraRaw::default().sharpen_detail)); + assert_eq!(sharpening_detail(f32::NEG_INFINITY), 0.0); + assert_eq!(sharpening_detail(f32::INFINITY), 1.0); + } + + /// #9273: Dehaze clears the haze evenly over a sky, right up to a dark building, instead of + /// leaving a bright halo of uncorrected haze around it. Synthetic scene: a clear sky and a + /// dark tower, hazed with `I = J·t + A·(1 − t)`. + #[test] + fn dehaze_leaves_no_halo_beside_dark_objects() { + let (w, h) = (600usize, 400usize); + let tower = |x: usize, y: usize| (250..350).contains(&x) && y >= 120; + let (t, air) = (0.55f32, [0.9f32, 0.9, 0.9]); + let mut px: Vec<[f32; 4]> = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + let j = if tower(x, y) { [0.06, 0.06, 0.07] } else { [0.35 + 0.1 * y as f32 / h as f32, 0.5, 0.8] }; + let c: [f32; 3] = std::array::from_fn(|k| j[k] * t + air[k] * (1.0 - t)); + [c[0], c[1], c[2], 1.0] + }) + .collect(); + let d = Dehaze::new(&cr! { dehaze: 100.0}, w, h).unwrap(); + dehaze(&mut px, w, h, &d); + let sky = |xs: std::ops::Range| { + let v: Vec = (150..390) + .flat_map(|y| xs.clone().map(move |x| (x, y))) + .map(|(x, y)| luma([px[y * w + x][0], px[y * w + x][1], px[y * w + x][2]])) + .collect(); + v.iter().sum::() / v.len() as f32 + }; + // Sky 1–8 px from the tower against open sky: the haze left beside it, in 8-bit levels. + let halo = (sky(242..250) - sky(20..80)) * 255.0; + // 6.4 levels before the dark channel was opened, under 1 after. + assert!(halo < 3.0, "a {halo:.1}-level halo beside the tower"); + // The open sky is still cleared: darker than the hazy input. + let hazy = luma(std::array::from_fn(|k| [0.4, 0.5, 0.8][k] * t + air[k] * (1.0 - t))); + assert!(sky(20..80) < hazy - 0.02, "{} vs hazy {hazy}", sky(20..80)); + } + + #[test] + fn new_curves_are_validated_but_saved_curves_still_load_and_render() { + for field in ["pointCurve", "pointCurveRed", "pointCurveGreen", "pointCurveBlue"] { + for points in [ + serde_json::json!([[128, 128]]), + serde_json::json!([[255, 255], [0, 0]]), + serde_json::json!([[0, 0], [0, 255]]), + serde_json::json!([[0, -1], [255, 255]]), + serde_json::json!([[0, 0], [256, 255]]), + serde_json::json!([[0, 0], [1e30, 255]]), + serde_json::json!((0..17).map(|i| [i * 15, i * 15]).collect::>()), + ] { + let p: CameraRaw = serde_json::from_value(serde_json::json!({field: points})).unwrap(); + assert!(p.validate().is_err(), "{field}: {points}"); + } + for points in [ + serde_json::json!([]), + serde_json::json!([[0, 0], [255, 255]]), + serde_json::json!((0..16).map(|i| [i * 17, i * 17]).collect::>()), + ] { + let p: CameraRaw = serde_json::from_value(serde_json::json!({field: points})).unwrap(); + assert!(p.validate().is_ok(), "{field}: {points}"); + } + } + assert_eq!(serde_json::from_str::("{}").unwrap(), CameraRaw::default()); + // An older editor could stack two points on one input and exceed 16 points; such a + // saved Smart Filter must still develop instead of silently disappearing. + let mut legacy: Vec<[f32; 2]> = (0..20).map(|i| [i as f32 * 12.0, i as f32 * 12.0]).collect(); + legacy.insert(5, [60.0, 200.0]); + let p: CameraRaw = serde_json::from_value(serde_json::json!({"pointCurve": legacy})).unwrap(); + assert!(p.validate().is_err()); + let edited = cr! { p.clone() => exposure: 1.0}; + assert!(edited.validate_changes(&p).is_ok(), "an unchanged stored curve stays editable"); + let broken = cr! { p.clone() => point_curve: vec![[10.0, 10.0]]}; + assert!(broken.validate_changes(&p).is_err(), "a changed curve is validated"); + let mut px = img(4, 4); + develop(&mut px, 4, 4, &p, false); + assert!(px.iter().flatten().all(|v| v.is_finite())); + } + + fn img(w: usize, h: usize) -> Vec<[f32; 4]> { + (0..w * h) + .map(|i| { + let (x, y) = ((i % w) as f32 / w as f32, (i / w) as f32 / h as f32); + [0.2 + 0.6 * x, 0.3 + 0.4 * y, 0.5 - 0.3 * x * y, 1.0] + }) + .collect() + } + + fn mean(px: &[[f32; 4]], c: usize) -> f32 { + px.iter().map(|q| q[c]).sum::() / px.len() as f32 + } + + #[test] + fn defaults_are_identity() { + let mut a = img(40, 30); + let b = a.clone(); + develop(&mut a, 40, 30, &CameraRaw::default(), false); + assert_eq!(a, b); + } + + #[test] + fn basic_panel_moves_the_right_way() { + let (w, h) = (64, 48); + let base = img(w, h); + let run = |p: CameraRaw| { + let mut a = base.clone(); + develop(&mut a, w, h, &p, false); + a + }; + let warm = run(cr! { temperature: 50.0}); + assert!(mean(&warm, 0) > mean(&base, 0) && mean(&warm, 2) < mean(&base, 2)); + let bright = run(cr! { exposure: 1.0}); + assert!(mean(&bright, 1) > mean(&base, 1) + 0.1); + let shadows = run(cr! { shadows: 100.0}); + let dark_px = |a: &[[f32; 4]]| a[0][1]; + assert!(dark_px(&shadows) > dark_px(&base)); + let hl = run(cr! { highlights: -100.0}); + assert!(hl[w * h - 1][0] < base[w * h - 1][0]); + let con = run(cr! { contrast: 100.0}); + // More contrast: darker darks, brighter brights. + assert!(con[0][1] < base[0][1] && con[w * h - 1][0] > base[w * h - 1][0]); + let desat = run(cr! { saturation: -100.0}); + assert!(desat.iter().all(|q| (q[0] - q[1]).abs() < 1e-4 && (q[1] - q[2]).abs() < 1e-4)); + let vib = run(cr! { vibrance: 100.0}); + let spread = |q: [f32; 4]| q[0].max(q[1]).max(q[2]) - q[0].min(q[1]).min(q[2]); + assert!(spread(vib[w * h / 2]) > spread(base[w * h / 2])); + for p in [cr! { clarity: 80.0}, cr! { texture: 80.0}, cr! { dehaze: 60.0}, cr! { dehaze: -60.0}, cr! { whites: 50.0, blacks: -50.0}] { + let out = run(p.clone()); + assert!(out.iter().all(|q| q[..3].iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))), "{p:?}"); + assert_ne!(out, base); + } + } + + #[test] + fn camera_raw_curve_keeps_legacy_close_knots() { + // The middle knots survive the original f32 normalization and make a sharp step. + let x = 127.5_f32; + let close = f32::from_bits(x.to_bits() + 33); + let lut = curve_lut(&[[0.0, 0.0], [x, 0.0], [close, 255.0], [255.0, 255.0]], 1024); + assert!(lut[256] < 0.01 && lut[767] > 0.99, "expected the legacy step, got {} and {}", lut[256], lut[767]); + } + + #[test] + fn curves_hsl_grading_detail_effects() { + // Monotone cubic LUT through the points. + let lut = curve_lut(&[[0.0, 0.0], [64.0, 40.0], [192.0, 220.0], [255.0, 255.0]], 256); + assert!((lut[64] - 40.0 / 255.0).abs() < 0.01 && (lut[192] - 220.0 / 255.0).abs() < 0.01); + assert!(lut.windows(2).all(|p| p[1] >= p[0])); + // Band weights sum to one everywhere. + for hh in (0..360).step_by(7) { + let s: f32 = band_weights(hh as f32).iter().sum(); + assert!((s - 1.0).abs() < 1e-4, "{hh}: {s}"); + } + let (w, h) = (48, 32); + let reds: Vec<[f32; 4]> = vec![[0.8, 0.2, 0.2, 1.0]; w * h]; + let mut a = reds.clone(); + let mut hs = [0.0; 8]; + hs[0] = -100.0; + develop(&mut a, w, h, &cr! { hsl_sat: hs}, false); + assert!(a[0][0] - a[0][1] < 0.1, "reds desaturated: {:?}", a[0]); + let blues: Vec<[f32; 4]> = vec![[0.2, 0.2, 0.8, 1.0]; w * h]; + let mut b = blues.clone(); + develop(&mut b, w, h, &cr! { hsl_sat: hs}, false); + assert!((b[0][2] - 0.8).abs() < 1e-4, "blues untouched"); + // Grading: blue shadows tint dark pixels, leave bright ones nearly alone. + let mut g: Vec<[f32; 4]> = vec![[0.1, 0.1, 0.1, 1.0], [0.95, 0.95, 0.95, 1.0]]; + develop(&mut g, 2, 1, &cr! { grade_shadows: Wheel { hue: 220.0, sat: 80.0, lum: 0.0 }}, false); + assert!(g[0][2] > g[0][0] + 0.05 && (g[1][2] - g[1][0]).abs() < 0.02, "{g:?}"); + // Point curve + parametric. + let mut c = img(w, h); + develop(&mut c, w, h, &cr! { point_curve: vec![[0.0, 30.0], [255.0, 255.0]], curve_shadows: 50.0}, false); + assert!(c.iter().all(|q| q[1] >= 30.0 / 255.0 - 1e-4)); + // Noise reduction reduces variance; sharpening increases it; grain is deterministic. + let noisy: Vec<[f32; 4]> = (0..w * h) + .map(|i| { + let n = hash01(i as i64, 0, 3) * 0.2; + [0.4 + n, 0.4 + n, 0.4 + n, 1.0] + }) + .collect(); + let var = |a: &[[f32; 4]]| { + let m = mean(a, 1); + a.iter().map(|q| (q[1] - m).powi(2)).sum::() / a.len() as f32 + }; + let mut nr = noisy.clone(); + develop(&mut nr, w, h, &cr! { noise_luminance: 80.0}, false); + assert!(var(&nr) < var(&noisy) * 0.5); + // Out-of-range noise settings are held to their 0..=100 range, not turned into huge radii. + let mut wild = noisy.clone(); + let hostile = cr! { noise_luminance: 1.0e30, noise_color: 1.0e30, noise_luminance_detail: 1.0e30, noise_color_detail: 1.0e30}; + develop(&mut wild, w, h, &hostile, false); + assert!(wild.iter().all(|q| q[0].is_finite())); + let mut sh = noisy.clone(); + develop(&mut sh, w, h, &cr! { sharpen_amount: 100.0}, false); + assert!(var(&sh) > var(&noisy)); + let mut g1 = img(w, h); + let mut g2 = img(w, h); + let gp = cr! { grain_amount: 50.0}; + let seeded = DevelopInputs { seed: 4, ..Default::default() }; + super::develop(&mut g1, w, h, &gp, &seeded, false); + super::develop(&mut g2, w, h, &gp, &seeded, false); + assert_eq!(g1, g2); + assert_ne!(g1, img(w, h)); + // Post-crop vignette darkens corners, leaves the centre. + let flat = vec![[0.5f32, 0.5, 0.5, 1.0]; w * h]; + let mut v = flat.clone(); + develop(&mut v, w, h, &cr! { vignette_amount: -80.0}, false); + assert!(v[0][0] < 0.35 && (v[(h / 2) * w + w / 2][0] - 0.5).abs() < 0.01, "{:?}", v[0]); + } + + #[test] + fn calibration_keeps_the_develop_off_the_per_pixel_gpu_stages() { + // The per-pixel stages (the Camera Raw dialog's GPU preview) don't run Calibration, so + // settings with it must fall back to the CPU develop instead of previewing without it. + for p in [ + cr! { shadow_tint: 40.0}, + cr! { calibration_hue: [0.0, 0.0, 30.0], whites: 20.0}, + cr! { calibration_sat: [-50.0, 0.0, 0.0], exposure: 0.5}, + ] { + assert!(!spatial(&p)); + assert!(per_pixel(&p, 2, 2, false, Some((0.0, 1.0))).is_none(), "{p:?}"); + } + assert!(per_pixel(&cr! { exposure: 0.5}, 2, 2, false, None).is_some()); + } + + #[test] + fn calibration_turns_primaries_keeps_neutrals_and_tints_shadows() { + let w = calibration_weights(0.0); + assert!((w[0] - 1.0).abs() < 1e-6, "pure red is all red primary: {w:?}"); + let w = calibration_weights(60.0); + assert!((w[0] - 0.5).abs() < 1e-6 && (w[1] - 0.5).abs() < 1e-6, "yellow is half red, half green: {w:?}"); + let w = calibration_weights(300.0); + assert!((w[2] - 0.5).abs() < 1e-6 && (w[0] - 0.5).abs() < 1e-6, "magenta wraps round: {w:?}"); + let (none, zero) = ([0.0f32; 3], [0.0f32; 3]); + let grey = calibrate([0.3, 0.3, 0.3], [100.0, -100.0, 50.0], [100.0, -100.0, 100.0]); + assert!(grey.iter().all(|v| (v - 0.3).abs() < 1e-5), "greys are untouched: {grey:?}"); + // Red turned towards green: it gains green, keeps its luminance. + let red = calibrate([0.5, 0.0, 0.0], [100.0, 0.0, 0.0], zero); + assert!(red[1] > 0.05 && (red[1] / red[0] - 0.5).abs() < 0.02 && red[2] < 1e-6, "red turns 30° towards green (orange): {red:?}"); + assert!((luma(red) - luma([0.5, 0.0, 0.0])).abs() < 1e-4, "luminance kept: {red:?}"); + // Blue at saturation −100 is grey; green at −50 is paler. + let blue = calibrate([0.0, 0.0, 0.8], none, [0.0, 0.0, -100.0]); + assert!((blue[0] - blue[1]).abs() < 1e-5 && (blue[1] - blue[2]).abs() < 1e-5, "blue at −100 saturation is grey: {blue:?}"); + let green = calibrate([0.2, 0.8, 0.2], none, [0.0, -50.0, 0.0]); + assert!(green[0] > 0.2 && green[1] < 0.8, "green at −50 is paler: {green:?}"); + // A primary's sliders leave the other primaries alone. + let unchanged = calibrate([0.0, 0.0, 0.8], [100.0, 100.0, 0.0], [100.0, 100.0, 0.0]); + assert!(unchanged.iter().zip([0.0, 0.0, 0.8]).all(|(a, b)| (a - b).abs() < 1e-5), "{unchanged:?}"); + // Shadows tint: magenta lifts red and blue over green in a dark pixel, keeps luminance, + // and leaves white alone. + let dark = shadow_tint([0.02, 0.02, 0.02], 1.0); + assert!(dark[0] > dark[1] && dark[2] > dark[1], "{dark:?}"); + assert!((luma(dark) - 0.02).abs() < 1e-4, "luminance kept: {dark:?}"); + let green = shadow_tint([0.02, 0.02, 0.02], -1.0); + assert!(green[1] > green[0], "{green:?}"); + let white = shadow_tint([1.0, 1.0, 1.0], 1.0); + assert!(white.iter().all(|v| (v - 1.0).abs() < 1e-3), "white is not tinted: {white:?}"); + // Through develop: neutral settings are an identity, a tint changes dark pixels only. + let mut p = CameraRaw::default(); + assert!(p.is_identity()); + p.shadow_tint = 100.0; + assert!(!p.is_identity()); + let mut px = vec![[0.1, 0.1, 0.1, 1.0], [0.95, 0.95, 0.95, 1.0]]; + develop(&mut px, 2, 1, &p, false); + assert!(px[0][0] > px[0][1], "dark grey turns magenta: {:?}", px[0]); + assert!((px[1][0] - px[1][1]).abs() < 0.01, "near-white stays neutral: {:?}", px[1]); + p = CameraRaw::default(); + p.calibration_hue[2] = 100.0; + let mut px = vec![[0.0, 0.0, 0.8, 1.0]]; + develop(&mut px, 1, 1, &p, false); + assert!(px[0][0] > 0.05, "blue turned towards red: {:?}", px[0]); + } + + #[test] + fn auto_tone_brightens_dark_and_darkens_bright_images() { + let mut p = CameraRaw::default(); + auto_tone(&[], &mut p); + assert_eq!(p, CameraRaw::default(), "no pixels: nothing changes"); + let dark: Vec<[f32; 4]> = (0..4096) + .map(|i| { + let v = 0.05 + (i % 64) as f32 / 64.0 * 0.15; + [v, v, v, 1.0] + }) + .collect(); + auto_tone(&dark, &mut p); + assert!(p.exposure > 0.5, "a dark image gets exposure: {}", p.exposure); + assert!(p.shadows > 0.0, "and lifted shadows: {}", p.shadows); + let mut p = CameraRaw::default(); + let bright: Vec<[f32; 4]> = (0..4096) + .map(|i| { + let v = 0.8 + (i % 64) as f32 / 64.0 * 0.19; + [v, v, v, 1.0] + }) + .collect(); + auto_tone(&bright, &mut p); + assert!(p.exposure < -0.5, "a bright image loses exposure: {}", p.exposure); + assert!(p.highlights < 0.0, "and its highlights come down: {}", p.highlights); + let mut p = CameraRaw::default(); + let good: Vec<[f32; 4]> = (0..4096) + .map(|i| { + let v = 0.04 + (i % 64) as f32 / 63.0 * 0.92; + [v, v, v, 1.0] + }) + .collect(); + auto_tone(&good, &mut p); + assert!(p.exposure.abs() < 0.3 && p.blacks.abs() < 10.0 && p.whites.abs() < 10.0, "a full-range image is left nearly alone: {p:?}"); + assert!(p.saturation == 0.0 && hsl_neutral(&p), "other panels untouched"); + } + + #[test] + fn float_documents_keep_overrange() { + let mut a = vec![[2.0f32, 1.5, 0.5, 1.0]; 16]; + develop(&mut a, 4, 4, &cr! { exposure: 0.5}, true); + assert!(a[0][0] > 2.0); + } + + /// A Gaussian narrower than 0.3 px has no box radii, so it returns its input unchanged, and + /// Texture on a proxy that small changes nothing. + #[test] + fn a_gaussian_below_0_3_px_leaves_the_image_alone() { + assert!(spatial::gauss_radii(0.29).is_empty()); + assert!(!spatial::gauss_radii(0.3).is_empty()); + let (w, h) = (64usize, 48usize); + let v: Vec = (0..w * h).map(|i| ((i * 37) % 101) as f32 / 100.0).collect(); + assert_eq!(gauss(&v, w, h, 0.29), v); + assert_eq!(box_means(&v, w, h, &[]), v); + assert_ne!(gauss(&v, w, h, 1.0), v); + let src: Vec<[f32; 4]> = v.iter().map(|&x| [x, 1.0 - x, 0.5 * x, 1.0]).collect(); + let base = cr! { contrast: 10.0}; + let scaled = DevelopInputs { pixel_scale: 0.1, ..Default::default() }; + let (mut plain, mut textured) = (src.clone(), src); + super::develop(&mut plain, w, h, &base, &scaled, false); + super::develop(&mut textured, w, h, &cr! { base => texture: 80.0}, &scaled, false); + assert_eq!(plain, textured); + } +} diff --git a/crates/develop/src/camera_raw/per_pixel.rs b/crates/develop/src/camera_raw/per_pixel.rs new file mode 100644 index 0000000000..9273036bce --- /dev/null +++ b/crates/develop/src/camera_raw/per_pixel.rs @@ -0,0 +1,284 @@ +//! Develop's stages resolved for one image: every constant and table the per-pixel ones use, so +//! another implementation of them (the GPU preview, `photocraft_gpu::CameraRawDevelop`) runs the +//! same maths. [`develop`](super::develop) builds its own constants with the same functions. +//! The spatial stages other than Detail come as their parameters: Dehaze, Clarity and Texture +//! (see [`spatial`](super::spatial)), Shadows and Highlights as a [`LocalTone`]. + +use super::local_tone::{LocalTone, WORK_SIDE}; +use super::spatial::{Clarity, Dehaze, Texture}; +use super::types::VignetteStyle as StoredStyle; +use super::{ + CameraRaw, DevelopInputs, Encoding, Wheel, calibration_neutral, curve_lut, grade_neutral, hsl_neutral, hsv_to_rgb, is_linear, luma, + parametric_lut, white_balance_gains, whites_blacks, +}; + +pub use whites_blacks::Model as WhitesBlacksModel; + +/// Entries of the tone curve tables (parametric and point curves). +pub const CURVE_LUT: usize = 1024; +/// Samples of a Whites or Blacks curve row: grey levels 0, 1/32, …, 1. +pub const WB_STEPS: usize = whites_blacks::STEPS; + +/// White balance and exposure: channel gains in linear light, when the stage is on. +pub(crate) fn gains(p: &CameraRaw) -> Option<[f32; 3]> { + if p.temperature == 0.0 && p.tint == 0.0 && p.exposure == 0.0 { + return None; + } + let g = white_balance_gains(p.temperature, p.tint); + let norm = luma(g); + Some(g.map(|v| v / norm * 2f32.powf(p.exposure))) +} + +/// Contrast's strength, when Contrast is set (with or without Texture and Clarity). +fn contrast(p: &CameraRaw) -> Option { + (p.contrast != 0.0).then_some(p.contrast / 100.0 * 0.6) +} + +/// Whites and Blacks' tables, for an implementation that measures the image's points itself. +pub fn whites_blacks_model() -> WhitesBlacksModel { + whites_blacks::model() +} + +/// Whites and Blacks as two curve rows for the image's amounts. +#[derive(Clone, Debug, PartialEq)] +pub struct WhitesBlacks { + /// The Whites curve over grey levels 0, 1/32, …, 1, when Whites is set. + pub whites: Option<[f32; WB_STEPS]>, + /// The Blacks curve, applied after Whites. + pub blacks: Option<[f32; WB_STEPS]>, + /// The clipping directions (Whites up, Blacks down) curve each channel; the others scale the + /// pixel by the change of its luminance. + pub per_channel: bool, +} + +/// Color Grading's wheels resolved. +#[derive(Clone, Debug, PartialEq)] +pub struct Grade { + /// Colour offsets of the shadows, midtones, highlights and global wheels. + pub tints: [[f32; 3]; 4], + /// Luminance of the same wheels (slider units). + pub lums: [f32; 4], + pub blend: f32, + pub balance: f32, +} + +impl Grade { + pub(crate) fn new(p: &CameraRaw) -> Self { + let tint = |wh: &Wheel| -> [f32; 3] { + let c = hsv_to_rgb(wh.hue, 1.0, 1.0); + let l = luma(c); + [c[0] - l, c[1] - l, c[2] - l].map(|v| v * wh.sat / 100.0 * 0.3) + }; + Grade { + tints: [tint(&p.grade_shadows), tint(&p.grade_midtones), tint(&p.grade_highlights), tint(&p.grade_global)], + lums: [p.grade_shadows.lum, p.grade_midtones.lum, p.grade_highlights.lum, p.grade_global.lum], + blend: 0.15 + p.grade_blending.clamp(0.0, 100.0) / 100.0 * 0.35, + balance: p.grade_balance.clamp(-100.0, 100.0) / 100.0 * 0.25, + } + } +} + +/// The vignette's `vignette_style`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum VignetteStyle { + HighlightPriority, + ColorPriority, + PaintOverlay, +} + +/// The post-crop vignette's shape on a `w × h` frame. +#[derive(Clone, Debug, PartialEq)] +pub struct Vignette { + /// −1 … 1. + pub amount: f32, + /// 0 … 1. + pub highlights: f32, + pub style: VignetteStyle, + /// Frame centre (pixels). + pub centre: [f32; 2], + /// Half axes of the shape (pixels). + pub axes: [f32; 2], + /// Exponent of the superellipse. + pub power: f32, + /// The mask's smoothstep edges in normalised radius. + pub edges: [f32; 2], +} + +impl Vignette { + pub(crate) fn new(w: usize, h: usize, p: &CameraRaw) -> Self { + let mid = p.vignette_midpoint.clamp(0.0, 100.0) / 100.0; + let feather = p.vignette_feather.clamp(0.0, 100.0) / 100.0; + let round = p.vignette_roundness.clamp(-100.0, 100.0) / 100.0; + let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0); + // Roundness: 0 follows the frame's aspect, +1 a circle, −1 a rounded rectangle. + let (ax, ay) = if round >= 0.0 { + let r = cx.min(cy) + (cx.max(cy) - cx.min(cy)) * (1.0 - round); + (if cx >= cy { r } else { cx }, if cy > cx { r } else { cy }) + } else { + (cx, cy) + }; + let inner = 1.0 - mid * 0.8; + Vignette { + amount: p.vignette_amount / 100.0, + highlights: p.vignette_highlights.clamp(0.0, 100.0) / 100.0, + style: match p.vignette_style { + StoredStyle::PaintOverlay => VignetteStyle::PaintOverlay, + StoredStyle::ColorPriority => VignetteStyle::ColorPriority, + _ => VignetteStyle::HighlightPriority, + }, + centre: [cx, cy], + axes: [ax, ay], + power: 2.0 + (-round).max(0.0) * 6.0, + edges: [inner - feather * 0.5 * inner, inner + feather * 0.5 * (1.4 - inner) + 0.02], + } + } +} + +/// Grain: value noise sampled in full-resolution coordinates. +#[derive(Clone, Debug, PartialEq)] +pub struct Grain { + /// Noise cell size (full-resolution pixels). + pub cell: f32, + /// Weight of the finer octave. + pub roughness: f32, + pub amount: f32, + pub seed: u64, + /// Full-resolution pixels per pixel (`1 / pixel_scale`). + pub scale: f32, +} + +impl Grain { + pub(crate) fn new(p: &CameraRaw, inputs: &DevelopInputs) -> Self { + Grain { + cell: 1.0 + p.grain_size / 25.0, + roughness: p.grain_roughness / 100.0, + amount: p.grain_amount / 100.0 * 0.12, + seed: u64::from(inputs.seed), + scale: 1.0 / inputs.pixel_scale.clamp(0.01, 1.0), + } + } +} + +/// Develop's per-pixel stages for one image and settings, in order. `None` stages are off. +#[derive(Clone, Debug, PartialEq)] +pub struct PerPixel { + /// 1. White balance and exposure gains in linear light (sRGB-decoded values). + pub gains: Option<[f32; 3]>, + /// 2. Dehaze. + pub dehaze: Option, + /// 3. Shadows and Highlights: a local Laplacian filter of the whole frame, then each pixel's + /// light scaled by the change of its log luminance. + pub local_tone: Option, + /// 3. Clarity and Texture on the luminance clipped to 1, before Contrast. + pub clarity: Option, + pub texture: Option, + /// 3. Contrast's strength. + pub contrast: Option, + /// 3b. Whites and Blacks, in the document's encoding. + pub whites_blacks: Option, + /// 3b. Whites and Blacks to measure the image's points for (the sliders, −100 … 100), when a + /// spatial stage is set: the points then depend on its output, so whatever runs it + /// measures them and picks the curves from [`whites_blacks_model`]. `whites_blacks` is + /// then `None`. + pub measure_whites_blacks: Option<[f32; 2]>, + /// The document's transfer curve: 0 for sRGB's, else a power-law gamma. + pub encoding: f32, + /// 4. Vibrance and Saturation (slider / 100). + pub presence: Option<[f32; 2]>, + /// 5. The parametric tone curve, [`CURVE_LUT`] entries over 0 … 1. + pub parametric: Option>, + /// 5. Point curves: master, red, green, blue. + pub point: [Option>; 4], + /// 6. Color Mixer hue, saturation and luminance per band. + pub hsl: Option<[[f32; 8]; 3]>, + /// 7. Color Grading. + pub grade: Option, + /// 9. Vignette. + pub vignette: Option, + /// 9. Grain. + pub grain: Option, + /// Clip RGB to 0 … 1 at the end (all but 32-bit documents). + pub clamp: bool, +} + +/// Whether developing needs a stage that reads neighbouring pixels: Dehaze, Shadows and +/// Highlights, Texture, Clarity, sharpening or noise reduction. +pub fn spatial(p: &CameraRaw) -> bool { + p.dehaze != 0.0 || [p.highlights, p.shadows, p.texture, p.clarity].iter().any(|v| *v != 0.0) || detail_on(p) +} + +/// Whether developing needs Detail: sharpening or noise reduction. +fn detail_on(p: &CameraRaw) -> bool { + p.sharpen_amount > 0.0 || p.noise_luminance > 0.0 || p.noise_color > 0.0 +} + +/// The image's black and white points that Whites and Blacks adapt to, for `px` (`w × h`, +/// display-encoded) developed per pixel with `p`: what [`develop`](super::develop) measures +/// after white balance and Contrast. `None` when Whites and Blacks are 0 or `p` needs a +/// spatial stage. +pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: &DevelopInputs) -> Option<(f32, f32)> { + if (p.whites == 0.0 && p.blacks == 0.0) || spatial(p) || px.len() != w.saturating_mul(h) { + return None; + } + let enc = Encoding::of(inputs.encoding_gamma); + let (g, k_con) = (gains(p), contrast(p)); + Some(super::luminance_points(px, w, h, enc, |q| { + let q = g.map_or(q, |g| super::balance(q, g)); + k_con.map_or(q, |k| super::contrast(q, k)) + })) +} + +/// Develop's stages for settings without Detail or Calibration, on a `w × h` image; `points` are +/// the image's [`white_black_points`]. `None` when `p` needs Detail or Calibration (these stages +/// run neither), Shadows or Highlights on a frame wider than the filter's working copy (the +/// develop then filters a reduced copy) or only 2 pixels on its short side, or Whites or Blacks +/// without a spatial stage and without `points`. The points themselves leave Calibration out, so a +/// caller may cache them across Calibration changes. +pub fn per_pixel(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize, float: bool, points: Option<(f32, f32)>) -> Option { + if detail_on(p) || !calibration_neutral(p) { + return None; + } + // The develop leaves frames under 2 pixels on a side alone. + let local_tone = if w >= 2 && h >= 2 { LocalTone::new(p.shadows, p.highlights) } else { None }; + // At 2 pixels on the short side the GPU pass's pyramid has one level, so the CPU develops it. + if local_tone.is_some() && (w.max(h) > WORK_SIDE || w.min(h) <= 2) { + return None; + } + let (dehaze, clarity, texture) = (Dehaze::new(p, w, h), Clarity::new(p, w, h), Texture::new(p, inputs, w, h)); + let spatial = local_tone.is_some() || dehaze.is_some() || clarity.is_some() || texture.is_some(); + let identity = p.is_identity(); + let wb_on = p.whites != 0.0 || p.blacks != 0.0; + let measure_whites_blacks = (wb_on && spatial).then(|| [p.whites.clamp(-100.0, 100.0), p.blacks.clamp(-100.0, 100.0)]); + let whites_blacks = if wb_on && measure_whites_blacks.is_none() { + let (bp, wp) = points?; + let (xw, xb) = whites_blacks::amounts(p.whites.clamp(-100.0, 100.0), p.blacks.clamp(-100.0, 100.0), bp, wp); + (xw != 0.0 || xb != 0.0).then(|| WhitesBlacks { + whites: (xw != 0.0).then(|| whites_blacks::whites_row(xw)), + blacks: (xb != 0.0).then(|| whites_blacks::blacks_row(xb)), + per_channel: xw > 0.0 || xb < 0.0, + }) + } else { + None + }; + let parametric_on = !(p.curve_highlights == 0.0 && p.curve_lights == 0.0 && p.curve_darks == 0.0 && p.curve_shadows == 0.0); + let pts = |c: &Vec<[f32; 2]>| (!is_linear(c)).then(|| curve_lut(c, CURVE_LUT)); + Some(PerPixel { + gains: gains(p), + dehaze, + local_tone, + clarity, + texture, + contrast: contrast(p), + whites_blacks, + measure_whites_blacks, + encoding: Encoding::of(inputs.encoding_gamma).0, + presence: (p.vibrance != 0.0 || p.saturation != 0.0).then_some([p.vibrance / 100.0, p.saturation / 100.0]), + parametric: parametric_on.then(|| parametric_lut(p, CURVE_LUT)), + point: [pts(&p.point_curve), pts(&p.point_curve_red), pts(&p.point_curve_green), pts(&p.point_curve_blue)], + hsl: (!hsl_neutral(p)).then_some([p.hsl_hue, p.hsl_sat, p.hsl_lum]), + grade: (!grade_neutral(p)).then(|| Grade::new(p)), + vignette: (p.vignette_amount != 0.0).then(|| Vignette::new(w, h, p)), + grain: (p.grain_amount > 0.0).then(|| Grain::new(p, inputs)), + clamp: !float && !identity, + }) +} diff --git a/crates/develop/src/camera_raw/spatial.rs b/crates/develop/src/camera_raw/spatial.rs new file mode 100644 index 0000000000..a7b17347f0 --- /dev/null +++ b/crates/develop/src/camera_raw/spatial.rs @@ -0,0 +1,202 @@ +#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))] + +//! Dehaze, Clarity and Texture resolved for one frame: the sizes, radii and constants their +//! filters use, so another implementation of them (the GPU preview, +//! `photocraft_gpu::CameraRawDevelop`) runs the same filters. [`develop`](super::develop) builds +//! its own from the same constructors. +//! +//! - **Dehaze** follows the dark channel prior (K. He, J. Sun, X. Tang, *Single Image Haze Removal +//! Using Dark Channel Prior*, CVPR 2009) on a box-averaged copy at most [`DEHAZE_SIDE`] pixels +//! across, with the transmission refined by a guided filter (K. He, J. Sun, X. Tang, *Guided +//! Image Filtering*, ECCV 2010) and brought back to full size bilinearly. +//! - **Clarity** raises the luminance's difference from a fast guided filter of itself (K. He, +//! J. Sun, *Fast Guided Filter*, arXiv 2015), weighted toward the midtones. +//! - **Texture** raises its difference from a Gaussian blur (three box passes), limited to +//! ±[`TEXTURE_LIMIT`]. + +use super::{CameraRaw, DevelopInputs}; + +/// Dehaze measures the haze on a copy at most this many pixels across. +pub const DEHAZE_SIDE: usize = 768; +/// The dark channel's minimum filter has a radius of the copy's long side over this, at least +/// [`DEHAZE_MIN_RADIUS`]. +pub const DEHAZE_RADIUS_DIVISOR: usize = 60; +/// See [`DEHAZE_RADIUS_DIVISOR`]. +pub const DEHAZE_MIN_RADIUS: usize = 2; +/// The atmospheric light is the mean colour of the brightest 1 / this of the dark channel (at +/// least one cell). +pub const DEHAZE_AIR_FRACTION: usize = 1000; +/// Each channel of the atmospheric light is at least this. +pub const DEHAZE_AIR_FLOOR: f32 = 0.2; +/// The share of the haze the raw transmission removes (the paper's ω). +pub const DEHAZE_OMEGA: f32 = 0.95; +/// The guided filter's regularisation for the transmission. +pub const DEHAZE_EPS: f32 = 1e-3; +/// The transmission is at least this. +pub const DEHAZE_T_FLOOR: f32 = 0.1; +/// Clarity's guided filter regularisation. +pub const CLARITY_EPS: f32 = 0.005; +/// Texture moves the luminance by at most this. +pub const TEXTURE_LIMIT: f32 = 0.1; + +/// Dehaze on a `w × h` frame. +#[derive(Clone, Debug, PartialEq)] +pub struct Dehaze { + /// The slider / 100 (−1 … 1). + pub amount: f32, + /// The copy averages `factor × factor` blocks. + pub factor: usize, + /// The copy's size. + pub size: [usize; 2], + /// The minimum filter's radius. + pub radius: usize, + /// The guided filter's radius. + pub guide_radius: usize, + /// How many of the copy's cells the atmospheric light averages. + pub top: usize, +} + +impl Dehaze { + /// Dehaze for `p` on a `w × h` frame; `None` when it is off. + pub fn new(p: &CameraRaw, w: usize, h: usize) -> Option { + if p.dehaze == 0.0 { + return None; + } + let factor = w.max(h).div_ceil(DEHAZE_SIDE).max(1); + let size = [w.div_ceil(factor), h.div_ceil(factor)]; + let radius = (size[0].max(size[1]) / DEHAZE_RADIUS_DIVISOR).max(DEHAZE_MIN_RADIUS); + Some(Dehaze { + amount: p.dehaze / 100.0, + factor, + size, + radius, + guide_radius: radius * 2, + top: (size[0] * size[1] / DEHAZE_AIR_FRACTION).max(1), + }) + } + + /// The copy the haze is measured on, for `px` (`w × h`, display-encoded) before white balance + /// and exposure (`gains`, as in [`PerPixel`](super::PerPixel)): `size` cells in rows, each the + /// mean light of its block, clipped to 0 … 1. These are exactly the cells + /// [`develop`](super::develop) uses: the brightest of them set the atmospheric light, and a + /// tie between them decides which, so another implementation that computes stage 1 to a few + /// ulps should start from these. Empty when `px` isn't `w × h`. + pub fn cells(&self, px: &[[f32; 4]], w: usize, h: usize, gains: Option<[f32; 3]>) -> Vec<[f32; 3]> { + if px.len() != w.saturating_mul(h) || w.div_ceil(self.factor) != self.size[0] || h.div_ceil(self.factor) != self.size[1] { + return Vec::new(); + } + super::haze_cells(px, w, h, self, |q| gains.map_or(q, |g| super::balance(q, g))) + } +} + +/// Clarity on a `w × h` frame. +#[derive(Clone, Debug, PartialEq)] +pub struct Clarity { + /// The strength: the slider / 100 × 0.8. + pub amount: f32, + /// The guided filter's radius at full size. + pub radius: usize, + /// The fast guided filter works on `subsample × subsample` block means… + pub subsample: usize, + /// …with this radius… + pub sub_radius: usize, + /// …at this size. + pub sub_size: [usize; 2], +} + +impl Clarity { + /// Clarity for `p` on a `w × h` frame; `None` when it is off. + pub fn new(p: &CameraRaw, w: usize, h: usize) -> Option { + if p.clarity == 0.0 { + return None; + } + let radius = ((w.max(h) as f32 * 0.02) as usize).max(3); + let (subsample, sub_radius) = fast_guided_steps(radius); + Some(Clarity { amount: p.clarity / 100.0 * 0.8, radius, subsample, sub_radius, sub_size: [w.div_ceil(subsample), h.div_ceil(subsample)] }) + } +} + +/// The fast guided filter's subsampling and its radius there, for radius `r` at full size. A +/// subsampling of 1 is the plain guided filter at radius `r`. +pub fn fast_guided_steps(r: usize) -> (usize, usize) { + let s = (r / 8).clamp(1, 8); + (s, if s == 1 { r } else { (r / s).max(1) }) +} + +/// Texture on a `w × h` frame. +#[derive(Clone, Debug, PartialEq)] +pub struct Texture { + /// The strength: the slider / 100 × 0.9. + pub amount: f32, + /// The blur's box radii, in order; empty when the blur is too small to change anything. + pub radii: Vec, +} + +impl Texture { + /// Texture for `p` on a `w × h` frame; `None` when it is off. + pub fn new(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize) -> Option { + if p.texture == 0.0 { + return None; + } + let ps = inputs.pixel_scale.clamp(0.01, 1.0); + let sigma = (w.max(h) as f32 * 0.002).max(1.5 * ps); + Some(Texture { amount: p.texture / 100.0 * 0.9, radii: gauss_radii(sigma) }) + } +} + +/// The box radii of develop's Gaussian of `sigma`: none below 0.3. +pub(crate) fn gauss_radii(sigma: f32) -> Vec { + if sigma < 0.3 { + return Vec::new(); + } + super::util::gauss_box_radii(sigma).to_vec() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// `CameraRaw` with the named fields set (the type is `#[non_exhaustive]`, so no struct expression), or a copy of a base with them set. + macro_rules! cr { + ($($f:ident : $v:expr),* $(,)?) => {{ + let mut s = CameraRaw::default(); + $(s.$f = $v;)* + s + }}; + ($base:expr => $($f:ident : $v:expr),* $(,)?) => {{ + let mut s: CameraRaw = $base; + $(s.$f = $v;)* + s + }}; + } + + #[test] + fn stages_resolve_for_the_dialogs_proxy_and_are_off_at_zero() { + let p = cr! { dehaze: 40.0, clarity: -50.0, texture: 50.0}; + let scale = |pixel_scale| DevelopInputs { pixel_scale, ..Default::default() }; + let d = Dehaze::new(&p, 858, 572).unwrap(); + assert_eq!((d.factor, d.size, d.radius, d.guide_radius, d.top), (2, [429, 286], 7, 14, 122)); + let c = Clarity::new(&p, 858, 572).unwrap(); + assert_eq!((c.radius, c.subsample, c.sub_radius, c.sub_size), (17, 2, 8, [429, 286])); + assert!((c.amount + 0.4).abs() < 1e-6); + assert_eq!(Texture::new(&p, &scale(0.143), 858, 572).unwrap().radii, [1, 1, 2]); + // Small frames: the plain guided filter, a blur too narrow to change anything. + assert_eq!(fast_guided_steps(3), (1, 3)); + assert!(Texture::new(&cr! { texture: 10.0}, &scale(0.1), 64, 48).unwrap().radii.is_empty()); + let off = CameraRaw::default(); + assert!( + Dehaze::new(&off, 858, 572).is_none() && Clarity::new(&off, 858, 572).is_none() && Texture::new(&off, &scale(1.0), 858, 572).is_none() + ); + } + + #[test] + fn dehaze_cells_average_blocks_after_white_balance_and_refuse_a_wrong_size() { + let d = Dehaze::new(&cr! { dehaze: 10.0}, 3, 1).unwrap(); + let px = [[0.2, 0.4, 1.5, 1.0], [0.4, 0.0, 0.5, 1.0], [0.9, 0.9, 0.9, 1.0]]; + assert_eq!(d.cells(&px, 3, 1, None), vec![[0.2, 0.4, 1.0], [0.4, 0.0, 0.5], [0.9, 0.9, 0.9]]); + let brighter = d.cells(&px, 3, 1, Some([2.0, 2.0, 2.0])); + assert!(brighter[0][0] > 0.2 && brighter[2] == [1.0; 3]); + assert!(d.cells(&px[..2], 3, 1, None).is_empty()); + assert!(d.cells(&px, 1, 3, None).is_empty()); + } +} diff --git a/crates/develop/src/camera_raw/types.rs b/crates/develop/src/camera_raw/types.rs new file mode 100644 index 0000000000..39eaec9e66 --- /dev/null +++ b/crates/develop/src/camera_raw/types.rs @@ -0,0 +1,252 @@ +//! Camera Raw filter settings model (`CameraRaw` / `RawDevelopSettings`), matching PhotoCraft's +//! stored `.pcraft` / Smart Filter schema. + +use serde::{Deserialize, Serialize}; + +/// One colour grading wheel. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct GradeWheel { + /// Degrees 0..360. + pub hue: f32, + /// 0..=100. + pub sat: f32, + /// -100..=100. + pub lum: f32, +} + +/// What the vignette protects. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum VignetteStyle { + /// Colour priority. + ColorPriority, + /// Paint overlay. + PaintOverlay, + /// Highlight priority; a stored name outside the three reads as this one (serde's fallback is the last variant). + #[default] + #[serde(other)] + HighlightPriority, +} + +/// Most points a point curve accepts from commands and the control channel. +pub const MAX_CURVE_POINTS: usize = 16; + +/// The settings the Camera Raw filter reads: the field set and serde names of PhotoCraft's +/// `CameraRaw`, without its three develop inputs (`seed`, `pixel_scale`, `encoding_gamma`). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +#[non_exhaustive] +pub struct RawDevelopSettings { + pub temperature: f32, + pub tint: f32, + pub exposure: f32, + pub contrast: f32, + pub highlights: f32, + pub shadows: f32, + pub whites: f32, + pub blacks: f32, + pub texture: f32, + pub clarity: f32, + pub dehaze: f32, + pub vibrance: f32, + pub saturation: f32, + pub curve_highlights: f32, + pub curve_lights: f32, + pub curve_darks: f32, + pub curve_shadows: f32, + pub curve_splits: [f32; 3], + pub point_curve: Vec<[f32; 2]>, + pub point_curve_red: Vec<[f32; 2]>, + pub point_curve_green: Vec<[f32; 2]>, + pub point_curve_blue: Vec<[f32; 2]>, + pub hsl_hue: [f32; 8], + pub hsl_sat: [f32; 8], + pub hsl_lum: [f32; 8], + pub grade_shadows: GradeWheel, + pub grade_midtones: GradeWheel, + pub grade_highlights: GradeWheel, + pub grade_global: GradeWheel, + pub grade_blending: f32, + pub grade_balance: f32, + pub sharpen_amount: f32, + pub sharpen_radius: f32, + pub sharpen_detail: f32, + pub sharpen_masking: f32, + pub noise_luminance: f32, + pub noise_luminance_detail: f32, + pub noise_color: f32, + pub noise_color_detail: f32, + pub grain_amount: f32, + pub grain_size: f32, + pub grain_roughness: f32, + pub vignette_amount: f32, + pub vignette_midpoint: f32, + pub vignette_roundness: f32, + pub vignette_feather: f32, + pub vignette_highlights: f32, + pub vignette_style: VignetteStyle, + pub shadow_tint: f32, + pub calibration_hue: [f32; 3], + pub calibration_sat: [f32; 3], +} + +impl Default for RawDevelopSettings { + fn default() -> Self { + RawDevelopSettings { + temperature: 0.0, + tint: 0.0, + exposure: 0.0, + contrast: 0.0, + highlights: 0.0, + shadows: 0.0, + whites: 0.0, + blacks: 0.0, + texture: 0.0, + clarity: 0.0, + dehaze: 0.0, + vibrance: 0.0, + saturation: 0.0, + curve_highlights: 0.0, + curve_lights: 0.0, + curve_darks: 0.0, + curve_shadows: 0.0, + curve_splits: [25.0, 50.0, 75.0], + point_curve: Vec::new(), + point_curve_red: Vec::new(), + point_curve_green: Vec::new(), + point_curve_blue: Vec::new(), + hsl_hue: [0.0; 8], + hsl_sat: [0.0; 8], + hsl_lum: [0.0; 8], + grade_shadows: GradeWheel::default(), + grade_midtones: GradeWheel::default(), + grade_highlights: GradeWheel::default(), + grade_global: GradeWheel::default(), + grade_blending: 50.0, + grade_balance: 0.0, + sharpen_amount: 0.0, + sharpen_radius: 1.0, + sharpen_detail: 25.0, + sharpen_masking: 0.0, + noise_luminance: 0.0, + noise_luminance_detail: 50.0, + noise_color: 0.0, + noise_color_detail: 50.0, + grain_amount: 0.0, + grain_size: 25.0, + grain_roughness: 50.0, + vignette_amount: 0.0, + vignette_midpoint: 50.0, + vignette_roundness: 0.0, + vignette_feather: 50.0, + vignette_highlights: 0.0, + vignette_style: VignetteStyle::HighlightPriority, + shadow_tint: 0.0, + calibration_hue: [0.0; 3], + calibration_sat: [0.0; 3], + } + } +} + +/// Checks a point curve from untrusted input: empty (linear) or 2..=16 finite points in 0..=255 +/// with inputs increasing by at least one level. +pub fn validate_curve(points: &[[f32; 2]]) -> Result<(), String> { + if points.len() == 1 { + return Err("a nonempty curve needs at least two points".into()); + } + if points.len() > MAX_CURVE_POINTS { + return Err(format!("at most {MAX_CURVE_POINTS} curve points")); + } + if !points.iter().flatten().all(|v| v.is_finite() && (0.0..=255.0).contains(v)) { + return Err("curve coordinates must be finite and in 0..=255".into()); + } + if points.windows(2).any(|w| w[1][0] - w[0][0] < 1.0) { + return Err("curve inputs must increase by at least one level".into()); + } + Ok(()) +} + +impl GradeWheel { + fn neutral(&self) -> bool { + self.sat == 0.0 && self.lum == 0.0 + } +} + +fn is_linear(curve: &[[f32; 2]]) -> bool { + curve.len() < 2 || curve.iter().all(|p| (p[0] - p[1]).abs() < 1e-3) +} + +impl RawDevelopSettings { + /// Refuses malformed point curves, naming the first bad one. + pub fn validate(&self) -> Result<(), String> { + for (name, curve) in [ + ("pointCurve", &self.point_curve), + ("pointCurveRed", &self.point_curve_red), + ("pointCurveGreen", &self.point_curve_green), + ("pointCurveBlue", &self.point_curve_blue), + ] { + validate_curve(curve).map_err(|e| format!("{name}: {e}"))?; + } + Ok(()) + } + + /// [`validate`](Self::validate) for an edit of `stored` settings: a curve left as stored is + /// accepted, so editing another control of an older Smart Filter still works. + pub fn validate_changes(&self, stored: &Self) -> Result<(), String> { + for (name, curve, kept) in [ + ("pointCurve", &self.point_curve, &stored.point_curve), + ("pointCurveRed", &self.point_curve_red, &stored.point_curve_red), + ("pointCurveGreen", &self.point_curve_green, &stored.point_curve_green), + ("pointCurveBlue", &self.point_curve_blue, &stored.point_curve_blue), + ] { + if curve != kept { + validate_curve(curve).map_err(|e| format!("{name}: {e}"))?; + } + } + Ok(()) + } + + fn wb_neutral(&self) -> bool { + self.temperature == 0.0 && self.tint == 0.0 && self.exposure == 0.0 + } + + fn tone_neutral(&self) -> bool { + [self.contrast, self.highlights, self.shadows, self.texture, self.clarity, self.whites, self.blacks].iter().all(|v| *v == 0.0) + } + + fn hsl_neutral(&self) -> bool { + self.hsl_hue.iter().chain(&self.hsl_sat).chain(&self.hsl_lum).all(|v| *v == 0.0) + } + + fn grade_neutral(&self) -> bool { + self.grade_shadows.neutral() && self.grade_midtones.neutral() && self.grade_highlights.neutral() && self.grade_global.neutral() + } + + fn calibration_neutral(&self) -> bool { + self.shadow_tint == 0.0 && self.calibration_hue.iter().chain(&self.calibration_sat).all(|v| *v == 0.0) + } + + fn curves_neutral(&self) -> bool { + [self.curve_highlights, self.curve_lights, self.curve_darks, self.curve_shadows].iter().all(|v| *v == 0.0) + && [&self.point_curve, &self.point_curve_red, &self.point_curve_green, &self.point_curve_blue].iter().all(|c| is_linear(c)) + } + + /// Whether every control is neutral, so the settings leave the picture as it is. + pub fn is_identity(&self) -> bool { + self.wb_neutral() + && self.calibration_neutral() + && self.tone_neutral() + && self.dehaze == 0.0 + && self.vibrance == 0.0 + && self.saturation == 0.0 + && self.curves_neutral() + && self.hsl_neutral() + && self.grade_neutral() + && self.sharpen_amount == 0.0 + && self.noise_luminance == 0.0 + && self.noise_color == 0.0 + && self.grain_amount == 0.0 + && self.vignette_amount == 0.0 + } +} diff --git a/crates/develop/src/camera_raw/util.rs b/crates/develop/src/camera_raw/util.rs new file mode 100644 index 0000000000..3b93353009 --- /dev/null +++ b/crates/develop/src/camera_raw/util.rs @@ -0,0 +1,66 @@ +//! Parallel row/map helpers, sRGB transfer, bilinear sampling, hash, and box-blur radii +//! matching PhotoCraft's `photo_util` and `fxutil::gauss_box_radii` bit-for-bit. + +pub(crate) use craft_color::{linear_to_srgb, srgb_to_linear}; + +/// Applies `f(y, row)` to each `w * ch`-wide row (in parallel on native targets). +pub(crate) fn par_rows(buf: &mut [T], w: usize, ch: usize, f: impl Fn(usize, &mut [T]) + Sync + Send) { + let stride = (w * ch).max(1); + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + buf.par_chunks_mut(stride).enumerate().for_each(|(y, row)| f(y, row)); + } + #[cfg(target_arch = "wasm32")] + buf.chunks_mut(stride).enumerate().for_each(|(y, row)| f(y, row)); +} + +/// Maps `f` over `0..n` (in parallel on native targets), keeping order. +pub(crate) fn par_map(n: usize, f: impl Fn(usize) -> T + Sync + Send) -> Vec { + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + (0..n).into_par_iter().map(f).collect() + } + #[cfg(target_arch = "wasm32")] + (0..n).map(f).collect() +} + +pub(crate) fn hash01(x: i64, y: i64, seed: u64) -> f32 { + let mut z = + (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (y as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F) ^ seed.wrapping_mul(0x1656_67B1_9E37_79F9); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^= z >> 31; + (z >> 40) as f32 / (1u64 << 24) as f32 +} + +/// Bilinear sample of channel `c` of a `w × h × ch` buffer, clamped to the edges. +pub(crate) fn bilinear(buf: &[f32], w: usize, h: usize, ch: usize, c: usize, x: f32, y: f32) -> f32 { + let x = x.clamp(0.0, (w - 1) as f32); + let y = y.clamp(0.0, (h - 1) as f32); + let (x0, y0) = (x.floor() as usize, y.floor() as usize); + let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1)); + let (tx, ty) = (x - x0 as f32, y - y0 as f32); + let p = |xx: usize, yy: usize| buf[(yy * w + xx) * ch + c]; + let top = p(x0, y0) + (p(x1, y0) - p(x0, y0)) * tx; + let bot = p(x0, y1) + (p(x1, y1) - p(x0, y1)) * tx; + top + (bot - top) * ty +} + +pub(crate) fn gauss_box_radii(sigma: f32) -> [usize; 3] { + let n = 3.0f32; + let w_ideal = (12.0 * sigma * sigma / n + 1.0).sqrt(); + let mut wl = w_ideal.floor() as i32; + if wl % 2 == 0 { + wl -= 1; + } + let wl = wl.max(1); + let wu = wl + 2; + let m = ((12.0 * sigma * sigma - n * (wl * wl) as f32 - 4.0 * n * wl as f32 - 3.0 * n) / (-4.0 * wl as f32 - 4.0)).round().clamp(0.0, n) as usize; + let mut radii = std::array::from_fn(|i| if i < m { (wl as usize - 1) / 2 } else { (wu as usize - 1) / 2 }); + if radii.iter().all(|&r| r == 0) { + radii[0] = 1; + } + radii +} diff --git a/crates/develop/src/camera_raw/whites_blacks.rs b/crates/develop/src/camera_raw/whites_blacks.rs new file mode 100644 index 0000000000..f6cd3d48ae --- /dev/null +++ b/crates/develop/src/camera_raw/whites_blacks.rs @@ -0,0 +1,494 @@ +//! Whites and Blacks as Adobe Camera Raw (process version 2012) applies them. +//! +//! Measured as a black box on the Camera Raw Filter of Photoshop 25.4: grey blocks with chosen +//! histograms went through the filter by script and came back exactly; no Adobe code or data +//! was used. +//! +//! - Both are global curves of the grey level, applied after Shadows and Highlights, Whites +//! first. On an image whose darkest and lightest percent reach black and white the curve of a +//! slider value `x` is the measured row at `x` of [`WHITES`] or [`BLACKS`]. +//! - The direction that only compresses (Whites down, Blacks up) is that fixed curve on every +//! image. The direction that clips (Whites up, Blacks down) adapts: the row used is +//! `x · A(BP, WP)`. On the block images BP and WP are their darkest and lightest levels; on +//! photographs Photoshop's amounts follow best with BP the 3rd percentile of the luminance and +//! WP the 99.5th of the brightest channel, and Blacks at least 1.2 times. A low +//! white point makes Whites +100 stronger (up to 2.7 times), a raised black point Blacks +//! (up to 1.45 times at −40). Whites rows past +100 come from images where `A > 1`. +//! - Not reproduced: past −40 Photoshop's Blacks grows faster on images with a raised black +//! point (on one spanning 0.6–1 its −100 blacks out everything below 0.74, here below about +//! 0.15); its curves there are not rows of the full-range family. +//! - Colour: the clipping directions act on each channel, the compressing ones scale the pixel +//! by the curve's change of its luminance (closest to Photoshop on saturated colours). + +use super::Encoding; +use super::util::par_rows; + +/// Grey levels the curves are sampled at: 0, 1/32, …, 1 (sRGB-encoded). +pub(crate) const STEPS: usize = 33; +/// The first row's internal amount; rows are [`ROW_STEP`] apart. +const WHITES_FROM: f32 = -100.0; +const BLACKS_FROM: f32 = -100.0; +const ROW_STEP: f32 = 10.0; +/// The image's points are measured on cells of a copy at most this many pixels across. +pub(crate) const POINTS_SIDE: usize = 256; +/// The black point's quantile of the cells' luminance, the white point's of their brightest +/// channel. +pub(crate) const POINT_QUANTILES: [f32; 2] = [0.03, 0.995]; +/// Internal amounts the sliders reach: Whites, then Blacks. +const WHITES_RANGE: [f32; 2] = [-100.0, 270.0]; +const BLACKS_RANGE: [f32; 2] = [-100.0, 100.0]; + +/// Whites and Blacks' tables and how an image's points choose from them, for another +/// implementation (the GPU preview measures the points after Shadows and Highlights itself). +#[derive(Clone, Copy, Debug)] +pub struct Model { + /// Whites curves over grey levels 0, 1/32, …, 1, at internal amounts `whites_from`, + /// `whites_from + row_step`, …. + pub whites: &'static [[f32; STEPS]], + pub whites_from: f32, + /// Blacks curves, likewise. + pub blacks: &'static [[f32; STEPS]], + pub blacks_from: f32, + pub row_step: f32, + /// Black points and white points of the adaptation tables' rows and columns. + pub black_points: &'static [f32], + pub white_points: &'static [f32], + /// How much the clipping directions adapt (Whites up, Blacks down), by black and white point. + pub whites_adapt: &'static [[f32; 8]; 9], + pub blacks_adapt: &'static [[f32; 8]; 9], + /// The least Blacks adaptation on photographs. + pub photo_blacks: f32, + /// Internal amounts the Whites and Blacks sliders reach. + pub whites_range: [f32; 2], + pub blacks_range: [f32; 2], + /// See [`POINTS_SIDE`] and [`POINT_QUANTILES`]. + pub points_side: usize, + pub point_quantiles: [f32; 2], +} + +/// The tables [`amounts`], [`whites_row`] and [`blacks_row`] read. +pub(crate) fn model() -> Model { + Model { + whites: &WHITES, + whites_from: WHITES_FROM, + blacks: &BLACKS, + blacks_from: BLACKS_FROM, + row_step: ROW_STEP, + black_points: &BPS, + white_points: &WPS, + whites_adapt: &AW, + blacks_adapt: &AB, + photo_blacks: PHOTO_BLACKS, + whites_range: WHITES_RANGE, + blacks_range: BLACKS_RANGE, + points_side: POINTS_SIDE, + point_quantiles: POINT_QUANTILES, + } +} +// Measured levels; some happen to lie near π/8 and π/4. +/// Whites curves at internal amounts -100, -90, …, 270 (rows) over grey levels 0, 1/32, …, 1. +#[allow(clippy::approx_constant)] +static WHITES: [[f32; 33]; 38] = [ + [ + 0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1523, 0.1817, 0.2107, 0.2391, 0.2671, 0.2946, 0.3215, 0.3480, 0.3738, 0.3995, 0.4256, 0.4517, + 0.4774, 0.5028, 0.5278, 0.5524, 0.5768, 0.6008, 0.6245, 0.6482, 0.6717, 0.6957, 0.7207, 0.7483, 0.7814, 0.8263, 0.8949, 0.9999, + ], + [ + 0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1523, 0.1817, 0.2107, 0.2392, 0.2672, 0.2947, 0.3217, 0.3482, 0.3742, 0.4000, 0.4263, 0.4526, + 0.4785, 0.5042, 0.5296, 0.5548, 0.5797, 0.6044, 0.6291, 0.6539, 0.6789, 0.7046, 0.7317, 0.7617, 0.7969, 0.8425, 0.9074, 0.9999, + ], + [ + 0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1524, 0.1818, 0.2108, 0.2393, 0.2673, 0.2950, 0.3221, 0.3487, 0.3748, 0.4008, 0.4274, 0.4540, + 0.4803, 0.5064, 0.5323, 0.5580, 0.5837, 0.6093, 0.6350, 0.6610, 0.6875, 0.7149, 0.7438, 0.7756, 0.8122, 0.8576, 0.9184, 0.9999, + ], + [ + 0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1524, 0.1818, 0.2109, 0.2395, 0.2677, 0.2954, 0.3227, 0.3495, 0.3759, 0.4022, 0.4291, 0.4561, + 0.4828, 0.5094, 0.5360, 0.5624, 0.5888, 0.6154, 0.6423, 0.6695, 0.6973, 0.7261, 0.7566, 0.7897, 0.8271, 0.8716, 0.9280, 0.9999, + ], + [ + 0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1525, 0.1820, 0.2111, 0.2398, 0.2682, 0.2961, 0.3237, 0.3508, 0.3775, 0.4042, 0.4317, 0.4591, + 0.4864, 0.5136, 0.5408, 0.5680, 0.5953, 0.6229, 0.6508, 0.6791, 0.7082, 0.7382, 0.7698, 0.8037, 0.8412, 0.8843, 0.9365, 0.9999, + ], + [ + 0.0000, 0.0298, 0.0621, 0.0927, 0.1227, 0.1527, 0.1822, 0.2116, 0.2404, 0.2690, 0.2972, 0.3251, 0.3527, 0.3799, 0.4071, 0.4351, 0.4630, + 0.4910, 0.5189, 0.5469, 0.5749, 0.6031, 0.6316, 0.6605, 0.6899, 0.7199, 0.7509, 0.7832, 0.8174, 0.8544, 0.8958, 0.9439, 0.9999, + ], + [ + 0.0000, 0.0298, 0.0621, 0.0927, 0.1229, 0.1529, 0.1827, 0.2122, 0.2414, 0.2702, 0.2989, 0.3272, 0.3553, 0.3831, 0.4110, 0.4396, 0.4682, + 0.4968, 0.5254, 0.5542, 0.5830, 0.6121, 0.6414, 0.6712, 0.7014, 0.7322, 0.7637, 0.7964, 0.8305, 0.8668, 0.9062, 0.9503, 0.9999, + ], + [ + 0.0000, 0.0298, 0.0622, 0.0928, 0.1231, 0.1534, 0.1834, 0.2132, 0.2427, 0.2720, 0.3011, 0.3300, 0.3587, 0.3872, 0.4160, 0.4452, 0.4745, + 0.5038, 0.5332, 0.5627, 0.5923, 0.6221, 0.6522, 0.6826, 0.7134, 0.7447, 0.7765, 0.8092, 0.8429, 0.8781, 0.9155, 0.9559, 1.0000, + ], + [ + 0.0000, 0.0298, 0.0623, 0.0930, 0.1236, 0.1541, 0.1844, 0.2145, 0.2445, 0.2744, 0.3041, 0.3337, 0.3632, 0.3925, 0.4221, 0.4520, 0.4820, + 0.5120, 0.5421, 0.5723, 0.6026, 0.6330, 0.6636, 0.6946, 0.7257, 0.7572, 0.7890, 0.8214, 0.8545, 0.8885, 0.9237, 0.9608, 1.0000, + ], + [ + 0.0000, 0.0298, 0.0624, 0.0934, 0.1242, 0.1551, 0.1858, 0.2164, 0.2470, 0.2775, 0.3080, 0.3383, 0.3687, 0.3989, 0.4293, 0.4600, 0.4906, + 0.5213, 0.5520, 0.5827, 0.6136, 0.6445, 0.6755, 0.7067, 0.7380, 0.7694, 0.8011, 0.8330, 0.8652, 0.8978, 0.9310, 0.9651, 1.0000, + ], + [ + 0.0000, 0.0312, 0.0625, 0.0938, 0.1250, 0.1562, 0.1875, 0.2188, 0.2500, 0.2812, 0.3125, 0.3438, 0.3750, 0.4062, 0.4375, 0.4688, 0.5000, + 0.5312, 0.5625, 0.5938, 0.6250, 0.6562, 0.6875, 0.7188, 0.7500, 0.7812, 0.8125, 0.8438, 0.8750, 0.9062, 0.9375, 0.9688, 1.0000, + ], + [ + 0.0000, 0.0299, 0.0626, 0.0940, 0.1253, 0.1567, 0.1881, 0.2195, 0.2510, 0.2825, 0.3140, 0.3456, 0.3772, 0.4089, 0.4405, 0.4720, 0.5036, + 0.5351, 0.5667, 0.5983, 0.6298, 0.6613, 0.6929, 0.7244, 0.7559, 0.7874, 0.8189, 0.8503, 0.8816, 0.9128, 0.9438, 0.9742, 1.0000, + ], + [ + 0.0000, 0.0299, 0.0627, 0.0941, 0.1257, 0.1573, 0.1890, 0.2208, 0.2526, 0.2846, 0.3167, 0.3488, 0.3811, 0.4134, 0.4456, 0.4777, 0.5098, + 0.5419, 0.5741, 0.6062, 0.6383, 0.6704, 0.7025, 0.7345, 0.7664, 0.7983, 0.8301, 0.8617, 0.8931, 0.9241, 0.9543, 0.9829, 1.0000, + ], + [ + 0.0000, 0.0299, 0.0628, 0.0944, 0.1262, 0.1582, 0.1903, 0.2225, 0.2550, 0.2876, 0.3204, 0.3534, 0.3867, 0.4200, 0.4529, 0.4858, 0.5186, + 0.5516, 0.5845, 0.6174, 0.6502, 0.6830, 0.7157, 0.7482, 0.7807, 0.8131, 0.8451, 0.8769, 0.9082, 0.9385, 0.9673, 0.9928, 1.0000, + ], + [ + 0.0000, 0.0299, 0.0629, 0.0948, 0.1269, 0.1594, 0.1920, 0.2249, 0.2582, 0.2917, 0.3256, 0.3597, 0.3942, 0.4289, 0.4628, 0.4966, 0.5305, + 0.5644, 0.5983, 0.6321, 0.6658, 0.6994, 0.7327, 0.7660, 0.7989, 0.8316, 0.8639, 0.8956, 0.9263, 0.9553, 0.9815, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0299, 0.0631, 0.0953, 0.1280, 0.1610, 0.1944, 0.2282, 0.2625, 0.2973, 0.3325, 0.3683, 0.4045, 0.4407, 0.4758, 0.5109, 0.5460, + 0.5811, 0.6161, 0.6510, 0.6857, 0.7201, 0.7541, 0.7879, 0.8213, 0.8543, 0.8864, 0.9175, 0.9468, 0.9733, 0.9950, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0299, 0.0633, 0.0961, 0.1293, 0.1632, 0.1976, 0.2327, 0.2684, 0.3048, 0.3419, 0.3798, 0.4183, 0.4562, 0.4928, 0.5294, 0.5660, + 0.6024, 0.6387, 0.6748, 0.7104, 0.7456, 0.7803, 0.8145, 0.8480, 0.8807, 0.9121, 0.9417, 0.9684, 0.9907, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0300, 0.0637, 0.0971, 0.1313, 0.1663, 0.2020, 0.2387, 0.2763, 0.3149, 0.3546, 0.3952, 0.4365, 0.4763, 0.5149, 0.5532, 0.5914, + 0.6294, 0.6670, 0.7041, 0.7406, 0.7763, 0.8113, 0.8456, 0.8788, 0.9104, 0.9401, 0.9667, 0.9888, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0300, 0.0641, 0.0984, 0.1338, 0.1703, 0.2079, 0.2468, 0.2870, 0.3286, 0.3717, 0.4161, 0.4602, 0.5024, 0.5430, 0.5833, 0.6232, + 0.6627, 0.7015, 0.7394, 0.7764, 0.8123, 0.8472, 0.8808, 0.9126, 0.9420, 0.9681, 0.9896, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0302, 0.0647, 0.1003, 0.1374, 0.1760, 0.2160, 0.2579, 0.3016, 0.3472, 0.3949, 0.4436, 0.4908, 0.5355, 0.5784, 0.6207, 0.6622, + 0.7029, 0.7424, 0.7806, 0.8176, 0.8530, 0.8868, 0.9185, 0.9474, 0.9726, 0.9926, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0304, 0.0656, 0.1029, 0.1423, 0.1837, 0.2271, 0.2731, 0.3215, 0.3726, 0.4262, 0.4791, 0.5294, 0.5769, 0.6220, 0.6660, 0.7086, + 0.7498, 0.7893, 0.8272, 0.8631, 0.8969, 0.9281, 0.9560, 0.9795, 0.9967, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0305, 0.0679, 0.1094, 0.1509, 0.1968, 0.2459, 0.2956, 0.3510, 0.4094, 0.4680, 0.5248, 0.5781, 0.6278, 0.6742, 0.7195, 0.7624, + 0.8031, 0.8417, 0.8779, 0.9113, 0.9414, 0.9675, 0.9886, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0306, 0.0702, 0.1160, 0.1623, 0.2144, 0.2709, 0.3243, 0.3885, 0.4556, 0.5199, 0.5807, 0.6369, 0.6884, 0.7355, 0.7799, 0.8217, + 0.8606, 0.8964, 0.9288, 0.9570, 0.9803, 0.9958, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0308, 0.0725, 0.1225, 0.1737, 0.2320, 0.2960, 0.3641, 0.4393, 0.5133, 0.5825, 0.6460, 0.7032, 0.7544, 0.8003, 0.8426, 0.8817, + 0.9168, 0.9475, 0.9733, 0.9924, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0322, 0.0751, 0.1303, 0.1918, 0.2594, 0.3348, 0.4189, 0.5044, 0.5841, 0.6565, 0.7208, 0.7771, 0.8262, 0.8692, 0.9074, 0.9408, + 0.9686, 0.9900, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0331, 0.0818, 0.1482, 0.2171, 0.2977, 0.3892, 0.4865, 0.5779, 0.6602, 0.7322, 0.7943, 0.8470, 0.8915, 0.9286, 0.9600, 0.9844, + 0.9996, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0340, 0.0884, 0.1661, 0.2544, 0.3540, 0.4658, 0.5729, 0.6681, 0.7496, 0.8183, 0.8748, 0.9208, 0.9568, 0.9832, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.3356, 0.5799, 0.6166, 0.6166, 0.6166, 0.6166, 0.6624, 0.7556, 0.8321, 0.8935, 0.9411, 0.9755, 0.9970, 0.9998, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.5007, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.1655, 0.1655, 0.2972, 0.4728, 0.6327, 0.7616, 0.8598, 0.9317, 0.9790, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0457, 0.1830, 0.3836, 0.5790, 0.7379, 0.8549, 0.9360, 0.9869, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0520, 0.2329, 0.4864, 0.6989, 0.8449, 0.9403, 0.9884, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0773, 0.3027, 0.6040, 0.8058, 0.9302, 0.9930, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.1454, 0.4738, 0.7615, 0.9074, 0.9908, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.0000, 0.0964, 0.5416, 0.8589, 0.9897, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.1538, 0.1538, 0.7080, 0.9596, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.8439, 0.8439, 0.8439, 0.9993, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], + [ + 0.9228, 0.9228, 0.9228, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, + ], +]; +/// Blacks curves at internal amounts -100, …, 100 in steps of 10. +#[allow(clippy::approx_constant)] +static BLACKS: [[f32; 33]; 21] = [ + [ + 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0290, 0.0572, 0.0879, 0.1222, 0.1580, 0.1935, 0.2287, 0.2636, 0.2988, 0.3355, 0.3741, + 0.4151, 0.4571, 0.4990, 0.5406, 0.5818, 0.6226, 0.6631, 0.7031, 0.7424, 0.7811, 0.8192, 0.8568, 0.8937, 0.9300, 0.9655, 1.0000, + ], + [ + 0.0000, 0.0000, 0.0000, 0.0000, 0.0015, 0.0363, 0.0640, 0.0956, 0.1300, 0.1651, 0.2000, 0.2345, 0.2686, 0.3026, 0.3369, 0.3727, 0.4105, + 0.4495, 0.4885, 0.5272, 0.5657, 0.6039, 0.6419, 0.6796, 0.7169, 0.7538, 0.7903, 0.8264, 0.8621, 0.8974, 0.9322, 0.9664, 1.0000, + ], + [ + 0.0000, 0.0000, 0.0000, 0.0000, 0.0346, 0.0625, 0.0934, 0.1271, 0.1616, 0.1959, 0.2298, 0.2635, 0.2969, 0.3301, 0.3638, 0.3990, 0.4357, + 0.4727, 0.5094, 0.5460, 0.5824, 0.6187, 0.6547, 0.6906, 0.7262, 0.7615, 0.7965, 0.8313, 0.8657, 0.8998, 0.9336, 0.9671, 1.0000, + ], + [ + 0.0000, 0.0000, 0.0000, 0.0235, 0.0554, 0.0850, 0.1175, 0.1514, 0.1852, 0.2187, 0.2519, 0.2849, 0.3178, 0.3505, 0.3837, 0.4183, 0.4537, + 0.4891, 0.5243, 0.5594, 0.5944, 0.6292, 0.6639, 0.6985, 0.7329, 0.7671, 0.8010, 0.8347, 0.8683, 0.9016, 0.9347, 0.9676, 1.0000, + ], + [ + 0.0000, 0.0000, 0.0020, 0.0438, 0.0724, 0.1035, 0.1365, 0.1699, 0.2030, 0.2359, 0.2686, 0.3011, 0.3336, 0.3659, 0.3986, 0.4327, 0.4669, + 0.5011, 0.5352, 0.5692, 0.6031, 0.6369, 0.6706, 0.7043, 0.7378, 0.7711, 0.8043, 0.8373, 0.8702, 0.9029, 0.9355, 0.9679, 1.0000, + ], + [ + 0.0000, 0.0000, 0.0230, 0.0567, 0.0865, 0.1182, 0.1510, 0.1839, 0.2164, 0.2489, 0.2812, 0.3133, 0.3455, 0.3775, 0.4100, 0.4433, 0.4767, + 0.5100, 0.5433, 0.5765, 0.6096, 0.6426, 0.6756, 0.7086, 0.7414, 0.7741, 0.8067, 0.8392, 0.8716, 0.9039, 0.9361, 0.9682, 1.0000, + ], + [ + 0.0000, 0.0000, 0.0368, 0.0670, 0.0976, 0.1294, 0.1619, 0.1943, 0.2265, 0.2586, 0.2906, 0.3225, 0.3544, 0.3862, 0.4184, 0.4512, 0.4839, + 0.5166, 0.5492, 0.5818, 0.6144, 0.6469, 0.6793, 0.7117, 0.7441, 0.7763, 0.8085, 0.8406, 0.8727, 0.9046, 0.9365, 0.9683, 1.0000, + ], + [ + 0.0000, 0.0000, 0.0444, 0.0749, 0.1058, 0.1377, 0.1699, 0.2020, 0.2339, 0.2657, 0.2975, 0.3292, 0.3609, 0.3926, 0.4245, 0.4568, 0.4891, + 0.5213, 0.5535, 0.5857, 0.6179, 0.6499, 0.6820, 0.7140, 0.7460, 0.7779, 0.8098, 0.8416, 0.8734, 0.9052, 0.9368, 0.9685, 1.0000, + ], + [ + 0.0000, 0.0086, 0.0511, 0.0817, 0.1128, 0.1445, 0.1763, 0.2080, 0.2397, 0.2713, 0.3029, 0.3344, 0.3660, 0.3975, 0.4292, 0.4611, 0.4930, + 0.5249, 0.5567, 0.5886, 0.6204, 0.6522, 0.6839, 0.7157, 0.7475, 0.7791, 0.8108, 0.8424, 0.8740, 0.9056, 0.9371, 0.9686, 1.0000, + ], + [ + 0.0000, 0.0198, 0.0564, 0.0874, 0.1186, 0.1501, 0.1817, 0.2133, 0.2447, 0.2762, 0.3076, 0.3390, 0.3705, 0.4018, 0.4333, 0.4649, 0.4965, + 0.5281, 0.5597, 0.5912, 0.6227, 0.6543, 0.6858, 0.7173, 0.7488, 0.7802, 0.8117, 0.8431, 0.8745, 0.9059, 0.9373, 0.9686, 1.0000, + ], + [ + 0.0000, 0.0312, 0.0625, 0.0938, 0.1250, 0.1562, 0.1875, 0.2188, 0.2500, 0.2812, 0.3125, 0.3438, 0.3750, 0.4062, 0.4375, 0.4688, 0.5000, + 0.5312, 0.5625, 0.5938, 0.6250, 0.6562, 0.6875, 0.7188, 0.7500, 0.7812, 0.8125, 0.8438, 0.8750, 0.9062, 0.9375, 0.9688, 1.0000, + ], + [ + 0.0000, 0.0313, 0.0650, 0.0979, 0.1303, 0.1624, 0.1942, 0.2260, 0.2576, 0.2891, 0.3206, 0.3520, 0.3833, 0.4146, 0.4455, 0.4763, 0.5070, + 0.5378, 0.5684, 0.5991, 0.6298, 0.6605, 0.6912, 0.7219, 0.7526, 0.7833, 0.8141, 0.8450, 0.8758, 0.9067, 0.9377, 0.9688, 1.0000, + ], + [ + 0.0000, 0.0326, 0.0677, 0.1022, 0.1357, 0.1686, 0.2010, 0.2332, 0.2652, 0.2969, 0.3286, 0.3601, 0.3915, 0.4227, 0.4532, 0.4835, 0.5138, + 0.5440, 0.5741, 0.6042, 0.6344, 0.6645, 0.6946, 0.7248, 0.7550, 0.7853, 0.8156, 0.8461, 0.8766, 0.9072, 0.9380, 0.9689, 1.0000, + ], + [ + 0.0000, 0.0341, 0.0706, 0.1066, 0.1413, 0.1749, 0.2079, 0.2405, 0.2728, 0.3048, 0.3366, 0.3682, 0.3996, 0.4307, 0.4608, 0.4906, 0.5203, + 0.5500, 0.5796, 0.6092, 0.6387, 0.6683, 0.6979, 0.7276, 0.7573, 0.7871, 0.8170, 0.8472, 0.8773, 0.9077, 0.9382, 0.9690, 1.0000, + ], + [ + 0.0000, 0.0354, 0.0736, 0.1113, 0.1472, 0.1814, 0.2149, 0.2479, 0.2805, 0.3127, 0.3446, 0.3763, 0.4077, 0.4385, 0.4681, 0.4974, 0.5267, + 0.5558, 0.5849, 0.6139, 0.6429, 0.6720, 0.7011, 0.7303, 0.7595, 0.7889, 0.8184, 0.8481, 0.8780, 0.9081, 0.9384, 0.9690, 1.0000, + ], + [ + 0.0000, 0.0368, 0.0768, 0.1162, 0.1531, 0.1881, 0.2221, 0.2554, 0.2882, 0.3206, 0.3527, 0.3843, 0.4158, 0.4461, 0.4753, 0.5041, 0.5328, + 0.5615, 0.5900, 0.6185, 0.6470, 0.6755, 0.7041, 0.7328, 0.7616, 0.7906, 0.8197, 0.8491, 0.8787, 0.9085, 0.9386, 0.9691, 1.0000, + ], + [ + 0.0000, 0.0381, 0.0802, 0.1214, 0.1593, 0.1949, 0.2293, 0.2630, 0.2961, 0.3286, 0.3607, 0.3924, 0.4236, 0.4536, 0.4823, 0.5106, 0.5388, + 0.5669, 0.5949, 0.6229, 0.6509, 0.6789, 0.7070, 0.7352, 0.7636, 0.7922, 0.8209, 0.8500, 0.8793, 0.9089, 0.9388, 0.9691, 1.0000, + ], + [ + 0.0000, 0.0394, 0.0837, 0.1267, 0.1656, 0.2018, 0.2367, 0.2707, 0.3039, 0.3365, 0.3686, 0.4003, 0.4314, 0.4608, 0.4890, 0.5168, 0.5445, + 0.5721, 0.5996, 0.6271, 0.6546, 0.6822, 0.7098, 0.7375, 0.7655, 0.7937, 0.8221, 0.8509, 0.8799, 0.9092, 0.9390, 0.9692, 1.0000, + ], + [ + 0.0000, 0.0407, 0.0875, 0.1322, 0.1720, 0.2088, 0.2441, 0.2784, 0.3118, 0.3444, 0.3765, 0.4082, 0.4389, 0.4679, 0.4955, 0.5229, 0.5501, + 0.5771, 0.6042, 0.6312, 0.6582, 0.6853, 0.7124, 0.7398, 0.7673, 0.7952, 0.8233, 0.8517, 0.8804, 0.9096, 0.9391, 0.9692, 1.0000, + ], + [ + 0.0000, 0.0421, 0.0915, 0.1379, 0.1786, 0.2160, 0.2516, 0.2861, 0.3196, 0.3523, 0.3844, 0.4159, 0.4462, 0.4747, 0.5019, 0.5287, 0.5554, + 0.5820, 0.6085, 0.6351, 0.6616, 0.6882, 0.7149, 0.7419, 0.7690, 0.7965, 0.8243, 0.8524, 0.8810, 0.9099, 0.9393, 0.9693, 1.0000, + ], + [ + 0.0000, 0.0436, 0.0957, 0.1438, 0.1853, 0.2232, 0.2592, 0.2938, 0.3274, 0.3601, 0.3922, 0.4235, 0.4533, 0.4813, 0.5080, 0.5343, 0.5605, + 0.5866, 0.6127, 0.6387, 0.6648, 0.6910, 0.7173, 0.7439, 0.7707, 0.7978, 0.8253, 0.8532, 0.8815, 0.9102, 0.9394, 0.9693, 1.0000, + ], +]; +const BPS: [f32; 9] = [0.0000, 0.0200, 0.0500, 0.1000, 0.2000, 0.3000, 0.4500, 0.6000, 0.8000]; +const WPS: [f32; 8] = [0.1000, 0.2000, 0.3000, 0.4500, 0.6000, 0.8000, 0.9000, 1.0000]; +static AW: [[f32; 8]; 9] = [ + [1.7750, 2.3875, 2.4000, 2.1625, 1.9438, 1.6125, 1.3875, 1.0000], + [1.8125, 2.5250, 2.3937, 2.1688, 1.9375, 1.6062, 1.3938, 0.9875], + [2.7000, 2.4688, 2.2750, 2.0688, 1.8875, 1.6000, 1.3875, 0.9938], + [2.3250, 2.3250, 2.1875, 1.9750, 1.7937, 1.5188, 1.3250, 1.0437], + [2.0187, 2.0187, 2.0187, 1.8625, 1.7063, 1.4062, 1.2250, 0.9250], + [1.7500, 1.7500, 1.7500, 1.7500, 1.6438, 1.3562, 1.1687, 0.8625], + [1.4937, 1.4937, 1.4937, 1.4937, 1.4937, 1.2875, 1.1000, 0.7875], + [1.1687, 1.1687, 1.1687, 1.1687, 1.1687, 1.1687, 1.0375, 0.7562], + [0.8250, 0.8250, 0.8250, 0.8250, 0.8250, 0.8250, 0.8250, 0.7562], +]; +static AB: [[f32; 8]; 9] = [ + [0.9938, 0.9812, 1.0000, 1.0125, 0.9563, 0.9688, 1.0437, 1.0000], + [1.0437, 1.0250, 1.0125, 1.0000, 1.0000, 1.0375, 1.0000, 0.9938], + [1.2312, 1.2063, 1.1875, 1.1625, 1.1438, 1.1438, 1.1375, 1.1250], + [1.2500, 1.2500, 1.2312, 1.2125, 1.2125, 1.2375, 1.2375, 1.2375], + [1.1750, 1.1750, 1.1750, 1.1750, 1.2063, 1.2688, 1.3125, 1.3375], + [1.1812, 1.1812, 1.1812, 1.1812, 1.2125, 1.2812, 1.3313, 1.4125], + [1.2375, 1.2375, 1.2375, 1.2375, 1.2375, 1.3062, 1.3562, 1.4375], + [1.3250, 1.3250, 1.3250, 1.3250, 1.3250, 1.3250, 1.3687, 1.4500], + [1.3938, 1.3938, 1.3938, 1.3938, 1.3938, 1.3938, 1.3938, 1.4312], +]; + +/// A curve row at a fractional internal amount `x`, at grey level `v` (both interpolated). +fn curve(rows: &[[f32; STEPS]], from: f32, x: f32, v: f32) -> f32 { + if v >= 1.0 { + return 1.0; + } + let r = ((x - from) / ROW_STEP).clamp(0.0, (rows.len() - 1) as f32); + let i = (r as usize).min(rows.len() - 2); + let t = r - i as f32; + let at = |row: &[f32; STEPS]| { + let p = v.max(0.0) * (STEPS - 1) as f32; + let j = (p as usize).min(STEPS - 2); + let s = p - j as f32; + row[j] + (row[j + 1] - row[j]) * s + }; + at(&rows[i]) * (1.0 - t) + at(&rows[i + 1]) * t +} + +/// The curve at a fractional internal amount `x` as one row: `curve(rows, from, x, v)` is this +/// row interpolated at `v`, because both interpolations are linear. +fn row_at(rows: &[[f32; STEPS]], from: f32, x: f32) -> [f32; STEPS] { + let r = ((x - from) / ROW_STEP).clamp(0.0, (rows.len() - 1) as f32); + let i = (r as usize).min(rows.len() - 2); + let t = r - i as f32; + std::array::from_fn(|j| rows[i][j] * (1.0 - t) + rows[i + 1][j] * t) +} + +/// The Whites curve at internal amount `x` as a row over grey levels 0, 1/32, …, 1. +pub(crate) fn whites_row(x: f32) -> [f32; STEPS] { + row_at(&WHITES, WHITES_FROM, x) +} + +/// The Blacks curve at internal amount `x` as a row over grey levels 0, 1/32, …, 1. +pub(crate) fn blacks_row(x: f32) -> [f32; STEPS] { + row_at(&BLACKS, BLACKS_FROM, x) +} + +/// Whites at internal amount `x` (−100 … 270) of grey level `v`. +pub(crate) fn whites(v: f32, x: f32) -> f32 { + curve(&WHITES, WHITES_FROM, x, v) +} + +/// Blacks at internal amount `x` (−100 … 100) of grey level `v`. +pub(crate) fn blacks(v: f32, x: f32) -> f32 { + curve(&BLACKS, BLACKS_FROM, x, v) +} + +/// The least Blacks adaptation on photographs. +const PHOTO_BLACKS: f32 = 1.2; + +/// Bilinear lookup of an adaptation table at black point `bp` and white point `wp`. +fn adapt(table: &[[f32; 8]; 9], bp: f32, wp: f32) -> f32 { + let idx = |grid: &[f32], v: f32| { + let v = v.clamp(grid[0], grid[grid.len() - 1]); + let i = grid.windows(2).position(|w| v <= w[1]).unwrap_or(grid.len() - 2); + (i, (v - grid[i]) / (grid[i + 1] - grid[i])) + }; + let (i, s) = idx(&BPS, bp); + let (j, t) = idx(&WPS, wp); + let row = |i: usize| table[i][j] * (1.0 - t) + table[i][j + 1] * t; + row(i) * (1.0 - s) + row(i + 1) * s +} + +/// The internal amounts of the Whites and Blacks sliders (−100 … 100) for an image whose 1st +/// and 99th luminance percentiles are the grey levels `bp` and `wp` (sRGB-encoded). +pub(crate) fn amounts(whites: f32, blacks: f32, bp: f32, wp: f32) -> (f32, f32) { + let w = if whites > 0.0 { whites * adapt(&AW, bp, wp) } else { whites }; + // On photographs Photoshop's Blacks is about 1.2 times the block images' amount even where + // their black point is 0 (ten public-domain photos: 1.08–1.36). + let b = if blacks < 0.0 { blacks * adapt(&AB, bp, wp).max(PHOTO_BLACKS) } else { blacks }; + (w.clamp(WHITES_RANGE[0], WHITES_RANGE[1]), b.clamp(BLACKS_RANGE[0], BLACKS_RANGE[1])) +} + +/// Applies Whites and Blacks (internal amounts `w`, `b`) to straight RGBA pixels (`width` per +/// row) encoded with `enc`. Values above 1 (float documents) keep their excess. +pub(crate) fn apply(px: &mut [[f32; 4]], width: usize, w: f32, b: f32, enc: Encoding) { + if w == 0.0 && b == 0.0 { + return; + } + // A grey level's new level, both sRGB-encoded. + let grey = |v: f32| { + let v = if w != 0.0 { whites(v, w) } else { v }; + if b != 0.0 { blacks(v, b) } else { v } + }; + let per_channel = w > 0.0 || b < 0.0; + par_rows(px, width, 1, |_, row| { + for q in row.iter_mut() { + let lin = [0, 1, 2].map(|c| enc.decode(q[c])); + if per_channel { + for c in 0..3 { + let over = (lin[c] - 1.0).max(0.0); + q[c] = enc.encode(super::srgb_to_linear(grey(super::linear_to_srgb(lin[c].min(1.0)))) + over); + } + } else { + let y = super::luma_linear(lin).max(0.0); + if y <= 1e-7 { + continue; + } + let y2 = super::srgb_to_linear(grey(super::linear_to_srgb(y.min(1.0)))) + (y - 1.0).max(0.0); + let k = y2 / y; + for c in 0..3 { + q[c] = enc.encode(lin[c] * k); + } + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn full_range_rows_match_photoshop() { + // Photoshop 25.4 on a 64-level block image spanning black to white (sRGB levels). + assert!((whites(97.1 / 255.0, 100.0) * 255.0 - 137.4).abs() < 0.6); + assert!((whites(194.3 / 255.0, -100.0) * 255.0 - 167.6).abs() < 0.6); + assert!((blacks(97.1 / 255.0, -100.0) * 255.0 - 60.0).abs() < 0.6); + assert!((blacks(48.6 / 255.0, 100.0) * 255.0 - 67.0).abs() < 0.6); + // The compressing directions keep black and white. + assert_eq!(whites(1.0, -100.0), 1.0); + assert_eq!(blacks(0.0, 100.0), 0.0); + } + + #[test] + fn the_clipping_directions_adapt_to_the_image() { + // A dark, low-contrast image needs more: Whites +50 acts like +94.5 on [0.05, 0.6]. + let (w, _) = amounts(50.0, 0.0, 0.05, 0.6); + assert!((w - 94.5).abs() < 2.0, "{w}"); + // A raised black point strengthens Blacks −40 to −58 on [0.6, 1]. + let (_, b) = amounts(0.0, -40.0, 0.6, 1.0); + assert!((b + 58.0).abs() < 1.0, "{b}"); + // Never below the photographs' 1.2. + assert!((amounts(0.0, -50.0, 0.0, 1.0).1 + 60.0).abs() < 1e-3); + // The compressing directions never adapt. + assert_eq!(amounts(-50.0, 50.0, 0.3, 0.6), (-50.0, 50.0)); + } +} diff --git a/crates/develop/src/curve.rs b/crates/develop/src/curve.rs index 46b0eef6a7..fd26ad4060 100644 --- a/crates/develop/src/curve.rs +++ b/crates/develop/src/curve.rs @@ -4,6 +4,8 @@ //! separated by three split points. Each region contributes a cosine-windowed bump, summed and //! forced monotone. +pub mod compat; + use crate::color::spline::Lut1; use craft_develop_model::ToneCurve; diff --git a/crates/develop/src/curve/compat.rs b/crates/develop/src/curve/compat.rs new file mode 100644 index 0000000000..d4036e9de2 --- /dev/null +++ b/crates/develop/src/curve/compat.rs @@ -0,0 +1,81 @@ +//! Compatibility operations for projects whose stored adjustments use the Gaussian-region +//! tone curve and unit-slope out-of-range sampling. These are not the newer parametric curve. +//! +//! The formulas came from PhotoCraft's Camera Raw Filter, originally written by Brandon Thomas +//! (storytold/photocraft@aa87012aab6d710b1e1d2ff1654a45e58c09d955). + +/// Compile a four-region curve into a monotonically nondecreasing 0…1 table. +/// +/// `splits` and `amounts` are percentages. Splits are clamped individually to 5…95, not +/// reordered; the amounts are not clamped. Keeps the legacy expression order for stored edits. +/// Returns an empty table if fewer than two samples are requested. +pub fn gaussian_region_lut(splits: [f32; 3], amounts: [f32; 4], len: usize) -> Vec { + if len < 2 { + return Vec::new(); + } + let s = splits.map(|v| v.clamp(5.0, 95.0) / 100.0); + let centres = [s[0] / 2.0, (s[0] + s[1]) / 2.0, (s[1] + s[2]) / 2.0, (s[2] + 1.0) / 2.0]; + let widths = [s[0].max(0.1), (s[1] - s[0]).max(0.1), (s[2] - s[1]).max(0.1), (1.0 - s[2]).max(0.1)]; + let mut lut: Vec = (0..len) + .map(|i| { + let x = i as f32 / (len - 1) as f32; + let mut y = x; + for k in 0..4 { + let d = (x - centres[k]) / (widths[k] * 1.2); + let bump = (-d * d * 2.0).exp() * x * (1.0 - x) * 4.0; + y += amounts[k] / 100.0 * 0.25 * bump; + } + y.clamp(0.0, 1.0) + }) + .collect(); + for i in 1..len { + lut[i] = lut[i].max(lut[i - 1]); + } + lut +} + +/// Interpolate a table on 0…1 and extend its endpoints with slope one outside that interval. +/// Returns the input unchanged for a table with fewer than two entries. +pub fn sample_lut_linear_tails(lut: &[f32], value: f32) -> f32 { + if lut.len() < 2 { + return value; + } + if !(0.0..=1.0).contains(&value) { + return if value < 0.0 { value + lut[0] } else { lut[lut.len() - 1] + (value - 1.0) }; + } + let x = value * (lut.len() - 1) as f32; + let i = (x as usize).min(lut.len() - 2); + let t = x - i as f32; + lut[i] + (lut[i + 1] - lut[i]) * t +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn gaussian_region_lut_keeps_legacy_saved_curve_samples() { + // Synthetic saved sliders and five samples captured with the legacy formula; values are + // decimal here because the platform exp implementation can round the last bit differently. + let lut = gaussian_region_lut([90.0, 5.0, 120.0], [-92.0, 64.0, -35.0, 91.0], 5); + let old = [0.0, 0.030_084_822, 0.330_180_67, 0.543_366_2, 1.0]; + assert_eq!(lut.len(), old.len()); + for (&new, old) in lut.iter().zip(old) { + assert!((new - old).abs() <= 1.0e-6, "{new} != {old}"); + } + let crest = gaussian_region_lut([25.0, 50.0, 75.0], [1400.0, 0.0, -1200.0, 0.0], 1024); + assert!(crest.windows(2).all(|pair| pair[0] <= pair[1])); + assert_eq!((crest[0], crest[crest.len() - 1]), (0.0, 1.0)); + assert!(gaussian_region_lut([0.0; 3], [0.0; 4], 1).is_empty()); + } + + #[test] + fn sample_lut_linear_tails_keeps_legacy_signed_and_hdr_values() { + let lut = [0.125_f32, 0.15625, 0.75]; + for (value, old) in [(-0.5_f32, -0.375_f32), (0.0, 0.125), (0.25, 0.140625), (0.5, 0.15625), (0.75, 0.453125), (1.0, 0.75), (1.5, 1.25)] { + assert_eq!(sample_lut_linear_tails(&lut, value).to_bits(), old.to_bits()); + } + assert!(sample_lut_linear_tails(&lut, f32::NAN).is_nan()); + assert_eq!(sample_lut_linear_tails(&[], -0.5), -0.5); + } +} diff --git a/crates/develop/src/lib.rs b/crates/develop/src/lib.rs index c29723503b..ce376eddc8 100644 --- a/crates/develop/src/lib.rs +++ b/crates/develop/src/lib.rs @@ -4,6 +4,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod auto; +pub mod camera_raw; pub mod color; pub mod colorops; pub mod crystal; diff --git a/crates/drawingml/src/xmlx.rs b/crates/drawingml/src/xmlx.rs index 27fa58dc7d..ccc8a90ec6 100644 --- a/crates/drawingml/src/xmlx.rs +++ b/crates/drawingml/src/xmlx.rs @@ -266,56 +266,7 @@ fn rec_mc(el: &mut El, depth: usize, keep: &dyn Fn(&El) -> bool) { let mut out = Vec::with_capacity(el.children.len()); for c in std::mem::take(&mut el.children) { match c { - Node::El(ac_el) if ac_el.is(ac) => { - if keep(&ac_el) { - out.push(Node::El(ac_el)); - continue; - } - let choice = ac_el.children(Local("Choice")).find(|ch| { - let requires = ch.attr_local("Requires").unwrap_or(""); - let req_ok = requires.split_whitespace().all(|r| SUPPORTED_MC.contains(&r)); - let modelled = !ch.elements().any(|e| e.is(Local("contentPart"))) && (!requires.contains("cx1") || chartex_readable(ch)); - req_ok && modelled - }); - if let Some(b) = choice.or_else(|| ac_el.child(Local("Fallback"))) { - // The branch's namespace declarations (the first usable one of each name, - // in order), indexed by prefix once: each child then looks up the prefixes - // it uses instead of scanning every declaration. - let mut decls: Vec<(&String, &String)> = Vec::new(); - // An oversized declaration still shadows an outer one of its name: its - // content is left unbound rather than bound to the outer namespace. - let mut by_prefix: HashMap<&str, Option> = HashMap::new(); - for (k, v) in b.attrs.iter().chain(ac_el.attrs.iter()) { - let prefix = if k == "xmlns" { Some("") } else { k.strip_prefix("xmlns:") }; - if let Some(p) = prefix - && !by_prefix.contains_key(p) - { - by_prefix.insert(p, (v.len() <= MAX_NS_VALUE).then_some(decls.len())); - if v.len() <= MAX_NS_VALUE { - decls.push((k, v)); - } - } - } - for n in &b.children { - if let Node::El(e) = n { - // Carry the declarations from the branch that its content uses - // (all of them per child made children x declarations copies). - let used = used_prefixes(e); - let have: HashSet<&str> = e.attrs.iter().map(|(a, _)| a.as_str()).collect(); - let mut wanted: Vec = std::iter::once("") - .chain(used.iter().copied()) - .filter_map(|p| by_prefix.get(p).copied().flatten()) - .filter(|&i| decls.get(i).is_some_and(|(k, _)| !have.contains(k.as_str()))) - .collect(); - wanted.sort_unstable(); - wanted.dedup(); - let mut e = e.clone(); - e.attrs.extend(wanted.into_iter().filter_map(|i| decls.get(i)).map(|(k, v)| ((*k).clone(), (*v).clone()))); - out.push(Node::El(e)); - } - } - } - } + Node::El(ac_el) if ac_el.is(ac) => append_mc(ac_el, &mut out, depth, keep), other => out.push(other), } } @@ -326,6 +277,63 @@ fn rec_mc(el: &mut El, depth: usize, keep: &dyn Fn(&El) -> bool) { } } +fn append_mc(mut ac_el: El, out: &mut Vec, depth: usize, keep: &dyn Fn(&El) -> bool) { + if depth > MAX_DEPTH || keep(&ac_el) { + out.push(Node::El(ac_el)); + return; + } + let choice = ac_el.children.iter().position(|node| { + let Node::El(ch) = node else { return false }; + if !ch.is(Local("Choice")) { + return false; + } + let requires = ch.attr_local("Requires").unwrap_or(""); + let req_ok = requires.split_whitespace().all(|r| SUPPORTED_MC.contains(&r)); + let modelled = !ch.elements().any(|e| e.is(Local("contentPart"))) && (!requires.contains("cx1") || chartex_readable(ch)); + req_ok && modelled + }); + let index = choice.or_else(|| ac_el.children.iter().position(|node| matches!(node, Node::El(e) if e.is(Local("Fallback"))))); + let Some(Node::El(branch)) = index.and_then(|i| ac_el.children.get_mut(i)) else { return }; + + // Index branch declarations by prefix once. An oversized declaration still shadows an + // outer one of its name, even though its value will not be copied. + let mut decls: Vec<(&String, &String)> = Vec::new(); + let mut by_prefix: HashMap<&str, Option> = HashMap::new(); + for (k, v) in branch.attrs.iter().chain(ac_el.attrs.iter()) { + let prefix = if k == "xmlns" { Some("") } else { k.strip_prefix("xmlns:") }; + if let Some(p) = prefix + && !by_prefix.contains_key(p) + { + by_prefix.insert(p, (v.len() <= MAX_NS_VALUE).then_some(decls.len())); + if v.len() <= MAX_NS_VALUE { + decls.push((k, v)); + } + } + } + + for node in std::mem::take(&mut branch.children) { + let Node::El(mut e) = node else { continue }; + // Carry only declarations the child uses, in their original order. + let used = used_prefixes(&e); + let have: HashSet<&str> = e.attrs.iter().map(|(a, _)| a.as_str()).collect(); + let mut wanted: Vec = std::iter::once("") + .chain(used.iter().copied()) + .filter_map(|p| by_prefix.get(p).copied().flatten()) + .filter(|&i| decls.get(i).is_some_and(|(k, _)| !have.contains(k.as_str()))) + .collect(); + wanted.sort_unstable(); + wanted.dedup(); + e.attrs.extend(wanted.into_iter().filter_map(|i| decls.get(i)).map(|(k, v)| ((*k).clone(), (*v).clone()))); + + if e.is(Local("AlternateContent")) { + // The final child walk visits contents, so resolve a promoted wrapper here. + append_mc(e, out, depth + 1, keep); + } else { + out.push(Node::El(e)); + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -417,6 +425,23 @@ mod tests { /// The branch's own declaration of a prefix wins over the `AlternateContent`'s; an oversized /// one still shadows it (its content stays unbound); a child's own declaration is left alone. + #[test] + fn direct_nested_mc_branches_keep_namespace_precedence() { + let mut root = parse( + br#" + + + + + + "#, + ) + .unwrap(); + resolve_mc(&mut root); + let item = root.child(Local("item")).unwrap(); + assert_eq!(item.to_xml(), r#""#); + } + #[test] fn mc_branch_declarations_keep_their_precedence() { let long = "u".repeat(MAX_NS_VALUE + 1); diff --git a/crates/exr/src/decode.rs b/crates/exr/src/decode.rs index 4d09aa1992..15b9c9260c 100644 --- a/crates/exr/src/decode.rs +++ b/crates/exr/src/decode.rs @@ -115,13 +115,7 @@ impl Limits { } } -/// How a channel's samples are stored. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SampleType { - F16, - F32, - U32, -} +pub use crate::SampleType; impl SampleType { pub(crate) fn of(t: ExrSample) -> Self { diff --git a/crates/exr/src/deep.rs b/crates/exr/src/deep.rs index ad2ab00b5a..2196d1d776 100644 --- a/crates/exr/src/deep.rs +++ b/crates/exr/src/deep.rs @@ -24,6 +24,7 @@ use half::f16; use crate::channels::ColorLayout; use crate::decode::{Error, Limits, Result, SampleType, check_previews}; +use crate::scanline; fn err(e: impl std::fmt::Display) -> Error { Error::Malformed(e.to_string()) @@ -152,49 +153,6 @@ fn seek_to(cur: &mut Cursor<&[u8]>, pos: u64) -> Result<()> { // --- decompression ---------------------------------------------------------------------------- -/// Undo the ZIP predictor: each byte was stored as its difference to the previous byte plus -/// 128 (so a zero difference is 0x80), modulo 256. Applies to the sample-count table and the -/// sample data alike. -fn differences_to_samples(buf: &mut [u8]) { - if let Some(&first) = buf.first() { - let mut prev = i16::from(first); - for b in buf.iter_mut().skip(1) { - let s = (prev + i16::from(*b) - 128) as u8; - prev = i16::from(s); - *b = s; - } - } -} - -/// Undo the ZIP half-split: the stream is `[first half][second half]` with the second half -/// holding every second byte of the original; weave them back together. The scratch copy is -/// allocated fallibly, so a buffer that passed `max_bytes` but not the allocator is an error. -fn interleave_byte_blocks(buf: &mut [u8]) -> Result<()> { - let half = buf.len().div_ceil(2); - let mut out = alloc_zeroed::(buf.len())?; - let mut k = 0usize; - for i in 0..buf.len() / 2 { - let (a, b) = (buf.get(i).copied(), buf.get(half + i).copied()); - if let (Some(a), Some(b), Some(pair)) = (a, b, out.get_mut(k..k + 2)) { - if let Some(byte) = pair.first_mut() { - *byte = a; - } - if let Some(byte) = pair.get_mut(1) { - *byte = b; - } - } - k += 2; - } - if buf.len() % 2 == 1 && half > 0 { - let last = buf.get(half - 1).copied(); - if let (Some(last), Some(slot)) = (last, out.get_mut(k)) { - *slot = last; - } - } - buf.copy_from_slice(&out); - Ok(()) -} - /// Make room in `out` for `extra` more bytes, `limit` in all. Grows by doubling like `Vec`, /// but never reserves past `limit`: callers admit exactly that size against `max_bytes`, and /// plain doubling reserved up to twice as much. Fallible, so a failed allocation is an error. @@ -211,38 +169,8 @@ fn reserve_up_to(out: &mut Vec, extra: usize, limit: usize, what: &str) -> R Ok(()) } -/// OpenEXR RLE tokens: a negative byte `n` means `-n` literal bytes follow, a non-negative -/// byte `n` means the next byte repeats `n + 1` times (as `ImfRle.cpp` and the `exr` crate). -fn rle_decode(src: &[u8], expected: usize, what: &str) -> Result> { - let mut out = Vec::new(); - reserve_up_to(&mut out, expected.min(1 << 20), expected, what)?; - let mut i = 0; - while i < src.len() { - let count = src[i] as i8; - i += 1; - let n = if count < 0 { (-(count as i32)) as usize } else { count as usize + 1 }; - if out.len().saturating_add(n) > expected { - return Err(err(format!("{what}: RLE data expands past {expected} bytes"))); - } - reserve_up_to(&mut out, n, expected, what)?; - if count < 0 { - let end = i.saturating_add(n); - let run = src.get(i..end.min(src.len())).ok_or_else(|| err(format!("{what}: RLE run points past the compressed data")))?; - if run.len() != n { - return Err(err(format!("{what}: RLE run points past the compressed data"))); - } - out.extend_from_slice(run); - i = end; - } else { - let b = src.get(i).copied().ok_or_else(|| err(format!("{what}: RLE run points past the compressed data")))?; - i += 1; - out.resize(out.len() + n, b); - } - } - if out.len() != expected { - return Err(err(format!("{what}: RLE data expands to {} bytes, expected {expected}", out.len()))); - } - Ok(out) +fn scanline_error(what: &str, error: std::io::Error) -> Error { + if error.kind() == std::io::ErrorKind::OutOfMemory { Error::LimitExceeded(format!("{what}: {error}")) } else { err(format!("{what}: {error}")) } } /// Decompress `what` to exactly `expected` bytes. Like flat blocks, a payload that already @@ -258,10 +186,7 @@ fn decompress(compression: Compression, packed: &[u8], expected: usize, what: &s Compression::Uncompressed => Err(err(format!("{what}: expected {expected} uncompressed bytes, found {}", packed.len()))), Compression::RLE => { // Like ZIPS, RLE runs over the predicted, byte-split stream. - let mut out = rle_decode(packed, expected, what)?; - differences_to_samples(&mut out); - interleave_byte_blocks(&mut out)?; - Ok(out) + scanline::decode_rle(packed, expected).map_err(|error| scanline_error(what, error)) } Compression::ZIP1 => { // Inflate straight into `out`, grown with `reserve_up_to` rather than by @@ -290,9 +215,7 @@ fn decompress(compression: Compression, packed: &[u8], expected: usize, what: &s if out.len() != expected { return Err(err(format!("{what}: zlib data expands to {} bytes, expected {expected}", out.len()))); } - differences_to_samples(&mut out); - interleave_byte_blocks(&mut out)?; - Ok(out) + scanline::undo_byte_prediction(out).map_err(|error| scanline_error(what, error)) } other => Err(unsup(format!("deep data with {other:?} compression (NONE, RLE and ZIPS are supported)"))), } diff --git a/crates/exr/src/lib.rs b/crates/exr/src/lib.rs index f6a5ec236a..1ff2525867 100644 --- a/crates/exr/src/lib.rs +++ b/crates/exr/src/lib.rs @@ -20,11 +20,25 @@ //! - [`stream`]: one flat scan-line part read block by block, for pictures larger than memory. //! - [`cryptomatte_samples`]: a file's Cryptomatte layers and their per-pixel (ID, coverage) ranks. +/// Bounded RLE expansion and inverse byte prediction for EXR blocks. +pub mod scanline; + /// Scanline OpenEXR writer using a caller-supplied linearization table. pub mod rgba8; /// RFC 1950/1951 compression and bounded inflation for EXR chunks. pub mod zlib; +/// Bounded reconstruction of inflated PXR24 scanline blocks. +pub mod pxr24; + +/// How a channel's samples are stored. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SampleType { + F16, + F32, + U32, +} + pub mod channels; pub mod cryptomatte; #[cfg(feature = "decode")] diff --git a/crates/exr/src/pxr24.rs b/crates/exr/src/pxr24.rs new file mode 100644 index 0000000000..396db5c308 --- /dev/null +++ b/crates/exr/src/pxr24.rs @@ -0,0 +1,118 @@ +use crate::SampleType; + +/// Shape of a PXR24 block with full-resolution channels in file order. +#[derive(Clone, Copy, Debug)] +pub struct Layout<'a> { + width: usize, + rows: usize, + channels: &'a [SampleType], + inflated_len: usize, + output_len: usize, +} + +impl<'a> Layout<'a> { + /// Check the dimensions and byte counts against the caller's plain output limit. + pub fn new(width: usize, rows: usize, channels: &'a [SampleType], max_output: usize) -> Option { + if width == 0 || rows == 0 || channels.is_empty() { + return None; + } + let area = width.checked_mul(rows)?; + let (inflated_pixel, output_pixel) = channels.iter().try_fold((0usize, 0usize), |(inflated, output), &channel| { + let (planes, plain) = sample_bytes(channel); + Some((inflated.checked_add(planes)?, output.checked_add(plain)?)) + })?; + let inflated_len = inflated_pixel.checked_mul(area)?; + let output_len = output_pixel.checked_mul(area)?; + (output_len <= max_output).then_some(Self { width, rows, channels, inflated_len, output_len }) + } + + /// Exact number of bytes required from the zlib reader. + pub fn inflated_len(self) -> usize { + self.inflated_len + } + + /// Reconstruct little-endian samples in row, channel and pixel order. + /// + /// Each scanline and channel starts a new horizontal predictor. The stored + /// 24 bits of a FLOAT sample become its high bits, with eight low zero bits. + /// Returns `None` when the plane length is wrong or allocation fails. + pub fn unpack(self, mut input: &[u8]) -> Option> { + if input.len() != self.inflated_len { + return None; + } + let mut output = Vec::new(); + output.try_reserve_exact(self.output_len).ok()?; + for _ in 0..self.rows { + for &channel in self.channels { + let (planes, plain) = sample_bytes(channel); + let (line, rest) = input.split_at_checked(self.width * planes)?; + input = rest; + let mut sample = 0u32; + for x in 0..self.width { + let delta = line[x..].iter().step_by(self.width).fold(0u32, |value, &byte| (value << 8) | u32::from(byte)); + sample = sample.wrapping_add(delta); + let bytes = match channel { + SampleType::F32 => (sample << 8).to_le_bytes(), + SampleType::F16 | SampleType::U32 => sample.to_le_bytes(), + }; + output.extend_from_slice(&bytes[..plain]); + } + } + } + Some(output) + } +} + +fn sample_bytes(channel: SampleType) -> (usize, usize) { + match channel { + SampleType::F16 => (2, 2), + SampleType::F32 => (3, 4), + SampleType::U32 => (4, 4), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const MIXED: [SampleType; 3] = [SampleType::F16, SampleType::F32, SampleType::U32]; + + #[test] + fn mixed_types_wrap_and_reset_across_rows() { + #[rustfmt::skip] + let planes = [ + 0xff, 0x00, 0xfe, 0x03, + 0x7f, 0xff, 0x01, 0xfe, 0x23, 0xdd, + 0xff, 0x00, 0xff, 0x00, 0xff, 0x00, 0xf0, 0x30, + 0x01, 0xff, 0x02, 0xfe, + 0x00, 0xff, 0x00, 0xff, 0x01, 0xfe, + 0x12, 0xff, 0x34, 0xff, 0x56, 0xff, 0x78, 0xff, + ]; + #[rustfmt::skip] + let expected = [ + 0xfe, 0xff, 0x01, 0x00, + 0x00, 0x23, 0x01, 0x7f, 0x00, 0x00, 0x00, 0x7f, + 0xf0, 0xff, 0xff, 0xff, 0x20, 0x00, 0x00, 0x00, + 0x02, 0x01, 0x00, 0x01, + 0x00, 0x01, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, + 0x78, 0x56, 0x34, 0x12, 0x77, 0x56, 0x34, 0x12, + ]; + let layout = Layout::new(2, 2, &MIXED, expected.len()); + assert_eq!(layout.map(Layout::inflated_len), Some(planes.len())); + assert_eq!(layout.and_then(|layout| layout.unpack(&planes)).as_deref(), Some(expected.as_slice())); + } + + #[test] + fn rejects_invalid_shapes_and_plane_lengths() { + assert!(Layout::new(0, 1, &MIXED, 40).is_none()); + assert!(Layout::new(1, 0, &MIXED, 40).is_none()); + assert!(Layout::new(1, 1, &[], 40).is_none()); + assert!(Layout::new(usize::MAX, 2, &MIXED, usize::MAX).is_none()); + assert!(Layout::new(usize::MAX, 1, &MIXED, usize::MAX).is_none()); + assert!(Layout::new(2, 2, &MIXED, 39).is_none()); + let short = Layout::new(2, 2, &MIXED, 40).and_then(|layout| layout.unpack(&[0; 35])); + let long = Layout::new(2, 2, &MIXED, 40).and_then(|layout| layout.unpack(&[0; 37])); + assert!(short.is_none()); + assert!(long.is_none()); + } +} diff --git a/crates/exr/src/scanline.rs b/crates/exr/src/scanline.rs new file mode 100644 index 0000000000..c9edb1097f --- /dev/null +++ b/crates/exr/src/scanline.rs @@ -0,0 +1,92 @@ +//! Byte transforms shared by flat and deep OpenEXR blocks. + +use std::io::{Error, ErrorKind, Result}; + +/// Expand a compressed RLE block to exactly `expected` bytes and undo its +/// byte prediction. The caller checks its chunk limit and handles blocks +/// stored uncompressed before calling this function. +pub fn decode_rle(mut packed: &[u8], expected: usize) -> Result> { + let mut out = Vec::new(); + while let Some((&count, rest)) = packed.split_first() { + let count = count as i8; + let literal = count < 0; + let run = if literal { usize::from(count.unsigned_abs()) } else { count as usize + 1 }; + let Some(end) = out.len().checked_add(run).filter(|&end| end <= expected) else { + return Err(Error::new(ErrorKind::InvalidData, format!("RLE data expands past {expected} bytes"))); + }; + let (data, next) = rest + .split_at_checked(if literal { run } else { 1 }) + .ok_or_else(|| Error::new(ErrorKind::UnexpectedEof, "RLE run points past the compressed data"))?; + + if end > out.capacity() { + let target = out.capacity().saturating_mul(2).max(end).min(expected); + out.try_reserve_exact(target - out.len()) + .map_err(|_| Error::new(ErrorKind::OutOfMemory, format!("cannot allocate {target} RLE bytes")))?; + } + if literal { + out.extend_from_slice(data); + } else if let Some(&value) = data.first() { + out.resize(end, value); + } + packed = next; + } + if out.len() != expected { + return Err(Error::new(ErrorKind::InvalidData, format!("RLE data expands to {} bytes, expected {expected}", out.len()))); + } + undo_byte_prediction(out) +} + +/// Undo RLE/ZIP's byte differences and even/odd split, returning the bytes +/// in their original order. The scratch allocation is fallible and no larger +/// than the already bounded decompressed block. +pub fn undo_byte_prediction(mut bytes: Vec) -> Result> { + if let Some((&mut first, differences)) = bytes.split_first_mut() { + let mut previous = first; + for byte in differences { + *byte = previous.wrapping_add(*byte).wrapping_sub(128); + previous = *byte; + } + } + + let (even, odd) = bytes.split_at(bytes.len().div_ceil(2)); + let mut out = Vec::new(); + out.try_reserve_exact(bytes.len()).map_err(|_| Error::new(ErrorKind::OutOfMemory, format!("cannot allocate {} elements", bytes.len())))?; + for (&even, &odd) in even.iter().zip(odd) { + out.extend([even, odd]); + } + out.extend_from_slice(&even[odd.len()..]); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rle_reverses_wrapping_prediction_and_an_odd_byte_split() { + // Literal 50, repeated delta 128 three times, then three literals. + let rle = [255, 50, 2, 128, 253, 100, 250, 129]; + let expected = [50, 22, 50, 144, 50, 145, 50]; + assert_eq!(decode_rle(&rle, 7).unwrap(), expected); + assert_eq!(undo_byte_prediction(vec![50, 128, 128, 128, 100, 250, 129]).unwrap(), expected); + } + + #[test] + fn rle_handles_maximum_literal_and_repeat_counts() { + let mut rle = vec![128]; + rle.extend([128; 128]); + rle.extend([127, 128]); + assert_eq!(decode_rle(&rle, 256).unwrap(), [128; 256]); + } + + #[test] + fn rle_refuses_short_input_and_wrong_output_sizes() { + for block in [[255], [1]] { + assert_eq!(decode_rle(&block, 2).unwrap_err().kind(), ErrorKind::UnexpectedEof); + } + assert_eq!(decode_rle(&[1, 128], 1).unwrap_err().kind(), ErrorKind::InvalidData); + assert_eq!(decode_rle(&[0, 128], 2).unwrap_err().kind(), ErrorKind::InvalidData); + // A truncated stream does not reserve the declared output size up front. + assert_eq!(decode_rle(&[0, 128], usize::MAX).unwrap_err().kind(), ErrorKind::InvalidData); + } +} diff --git a/crates/image-codecs/Cargo.toml b/crates/image-codecs/Cargo.toml index 46d5103426..bab74d2860 100644 --- a/crates/image-codecs/Cargo.toml +++ b/crates/image-codecs/Cargo.toml @@ -43,7 +43,7 @@ zune-core = "0.5" jpeg-encoder = "0.6" craft-jpeg = { workspace = true } craft-metadata = { workspace = true } -craft-tiff = { workspace = true } +craft-tiff = { workspace = true, features = ["plain-rgba16"] } zune-jpegxl = { version = "=0.5.2", default-features = false, features = ["std"] } craft-heif = { workspace = true, optional = true } craft-jxl = { workspace = true, optional = true, features = ["decode"] } diff --git a/crates/image-codecs/src/codecs/tiff.rs b/crates/image-codecs/src/codecs/tiff.rs index 0f53bb3dab..dc537d2fd9 100644 --- a/crates/image-codecs/src/codecs/tiff.rs +++ b/crates/image-codecs/src/codecs/tiff.rs @@ -257,6 +257,11 @@ macro_rules! custom_colortype { use PhotometricInterpretation as PI; +/// Encode plain classic RGBA16 TIFF for callers that need the legacy file layout. +pub fn encode_plain_rgba16(width: u32, height: u32, samples: &[u16]) -> Result, CodecError> { + craft_tiff::plain::encode_rgba16(width, height, samples).map_err(|error| CodecError::encode(F, error)) +} + mod bands; mod decode; mod encode; diff --git a/crates/image-codecs/src/jpeg_probe.rs b/crates/image-codecs/src/jpeg_probe.rs index 869ae1f691..71b80f687f 100644 --- a/crates/image-codecs/src/jpeg_probe.rs +++ b/crates/image-codecs/src/jpeg_probe.rs @@ -74,6 +74,14 @@ fn be16(b: &[u8], at: usize) -> Option { /// `segment_span` covers the `0xFF` marker byte through the end of the segment payload. pub fn walk_jpeg_segments<'a>( bytes: &'a [u8], + visit: impl FnMut(u8, Range, &'a [u8]) -> Result, +) -> Result<(), JpegProbeError> { + walk_segments(bytes, false, visit) +} + +fn walk_segments<'a>( + bytes: &'a [u8], + stop_at_non_marker: bool, mut visit: impl FnMut(u8, Range, &'a [u8]) -> Result, ) -> Result<(), JpegProbeError> { if bytes.len() < 4 || bytes[0] != 0xFF || bytes[1] != 0xD8 { @@ -82,6 +90,9 @@ pub fn walk_jpeg_segments<'a>( let mut i = 2usize; while let Some(&byte) = bytes.get(i) { if byte != 0xFF { + if stop_at_non_marker { + break; + } i += 1; continue; } @@ -115,6 +126,27 @@ pub fn walk_jpeg_segments<'a>( Ok(()) } +/// EXIF orientation from the first complete APP1 segment prefixed with `Exif\0\0`. +/// +/// Requires consecutive marker prefixes before SOS or EOI. Returns 1 if the +/// first EXIF segment has no readable orientation, or if none is found before +/// the header ends or becomes unreadable. Unlike [`walk_jpeg_segments`], this +/// does not resynchronize past bytes outside a segment. For compatibility, +/// even a marker code of zero is treated as an unknown length-bearing marker. +pub fn strict_exif_orientation(bytes: &[u8]) -> u16 { + let mut orientation = 1; + let _ = walk_segments(bytes, true, |marker, _, segment| { + if marker == 0xE1 + && let Some(exif) = segment.strip_prefix(b"Exif\0\0") + { + orientation = crate::exif_orientation(exif); + return Ok(JpegVisit::Stop); + } + Ok(JpegVisit::Continue) + }); + orientation +} + /// Parse JFIF APP0 density `(x_dpi, y_dpi)` when unit is inches (1) or centimetres (2) and both /// axes are positive. pub fn jfif_dpi(seg: &[u8]) -> Option<(f64, f64)> { @@ -193,6 +225,32 @@ pub fn probe_jpeg(bytes: &[u8]) -> Result { mod tests { use super::*; + #[test] + fn strict_orientation_reads_the_first_exif_app1_before_the_scan() { + const ORIENTATION_6: &[u8] = b"II\x2a\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0\x06\0\0\0\0\0\0\0"; + let mut header = Vec::from(b"\xFF\xD8\xFF\xE1\0\x05XMP".as_slice()); + let app1: &[u8] = b"\xFF\xFF\xE1\0\x22Exif\0\0"; + header.extend_from_slice(app1); + header.extend_from_slice(ORIENTATION_6); + assert_eq!(strict_exif_orientation(&header), 6); + // Preserve the legacy placement scanner’s treatment of a zero marker code. + let mut zero_marker = Vec::from(b"\xFF\xD8\xFF\x00\x00\x02".as_slice()); + zero_marker.extend_from_slice(&header[2..]); + assert_eq!(strict_exif_orientation(&zero_marker), 6); + + let mut interrupted = vec![0xff, 0xd8, 0x01]; + interrupted.extend_from_slice(&header[2..]); + assert_eq!(strict_exif_orientation(&interrupted), 1); + + let mut after_scan = Vec::from(b"\xFF\xD8\xFF\xDA".as_slice()); + after_scan.extend_from_slice(&header[2..]); + assert_eq!(strict_exif_orientation(&after_scan), 1); + + let mut untagged_first = Vec::from(b"\xFF\xD8\xFF\xE1\0\x16Exif\0\0II\x2a\0\x08\0\0\0\0\0\0\0\0\0".as_slice()); + untagged_first.extend_from_slice(&header[2..]); + assert_eq!(strict_exif_orientation(&untagged_first), 1); + } + #[test] fn jpeg_probe_preserves_error_diagnostics() { assert_eq!(probe_jpeg(b"\x89PNG").unwrap_err(), JpegProbeError::NotJpeg); diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index dfe6f11305..a5e572f36d 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -53,7 +53,8 @@ pub use crate::codecs::png::{ encode_pq as encode_png_pq, palette as png_palette, stereo as png_stereo, }; pub use crate::codecs::tiff::{ - PhotoshopTags as TiffPhotoshopTags, TiffBands, photoshop_tags as tiff_photoshop_tags, writes_little_endian as tiff_writes_little_endian, + PhotoshopTags as TiffPhotoshopTags, TiffBands, encode_plain_rgba16 as encode_tiff_plain_rgba16, photoshop_tags as tiff_photoshop_tags, + writes_little_endian as tiff_writes_little_endian, }; pub use crate::codecs::tiff_ifd::{ExtraSampleKind, InkSet, TiffInfo, TiffPage, TiffPageKind}; pub use crate::error::CodecError; diff --git a/crates/image-codecs/src/raw_metadata.rs b/crates/image-codecs/src/raw_metadata.rs index 4573c1281f..17192bccc9 100644 --- a/crates/image-codecs/src/raw_metadata.rs +++ b/crates/image-codecs/src/raw_metadata.rs @@ -1,4 +1,4 @@ -//! Explicit PNG density, verbatim EXIF and JPEG APP metadata helpers for encoded images. +//! Explicit PNG density and sRGB, verbatim EXIF and JPEG APP metadata helpers for encoded images. //! Normal encoder APIs still normalize metadata for upright pixels; callers opt in to these helpers. use crate::{CodecError, Format}; @@ -128,6 +128,35 @@ pub fn png_pixels_per_meter_chunk((x, y): (u32, u32)) -> Result<[u8; 21], CodecE /// and image data as supplied. It bounds the returned file by `max_bytes` and never inflates pixels. pub fn with_png_pixels_per_meter(png: &[u8], resolution: (u32, u32), max_bytes: usize) -> Result, CodecError> { let density = png_pixels_per_meter_chunk(resolution)?; + rewrite_png_header_chunk(png, b"pHYs", &density, max_bytes, "PNG density rewrite") +} + +/// Rendering intent stored in a PNG sRGB chunk. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum SrgbRenderingIntent { + Perceptual = 0, + RelativeColorimetric = 1, + Saturation = 2, + AbsoluteColorimetric = 3, +} + +/// Insert one sRGB chunk after IHDR and remove old sRGB declarations through IEND. +/// +/// The source must already contain sRGB samples. Images with an ICC or cICP color +/// declaration or conflicting legacy gamma or chromaticities are refused. +/// The output is bounded by `max_bytes`. Pixel and other chunk bytes are preserved. +pub fn with_png_srgb(png: &[u8], intent: SrgbRenderingIntent, max_bytes: usize) -> Result, CodecError> { + let mut chunk = [0; 13]; + chunk[..4].copy_from_slice(&1u32.to_be_bytes()); + chunk[4..8].copy_from_slice(b"sRGB"); + chunk[8] = intent as u8; + let crc = crc32fast::hash(&chunk[4..9]); + chunk[9..].copy_from_slice(&crc.to_be_bytes()); + rewrite_png_header_chunk(png, b"sRGB", &chunk, max_bytes, "PNG sRGB rewrite") +} + +fn rewrite_png_header_chunk(png: &[u8], kind: &[u8; 4], replacement: &[u8], max_bytes: usize, operation: &str) -> Result, CodecError> { let header = png .get(..PNG_IHDR_END) .filter(|h| h.starts_with(b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR")) @@ -142,24 +171,35 @@ pub fn with_png_pixels_per_meter(png: &[u8], resolution: (u32, u32), max_bytes: } at += chunk.len(); match &chunk[4..8] { - b"pHYs" => removed += chunk.len(), + name if name == kind => removed += chunk.len(), + b"iCCP" | b"cICP" if kind == b"sRGB" => return Err(error(Format::Png, "PNG already declares an ICC or cICP color profile")), + b"gAMA" if kind == b"sRGB" && &chunk[8..chunk.len() - 4] != 45_455u32.to_be_bytes().as_slice() => { + return Err(error(Format::Png, "PNG gAMA is incompatible with sRGB")); + } + b"cHRM" if kind == b"sRGB" => { + // PNG Third Edition, table 17. The encoded values are scaled by 100,000. + const SRGB_CHROMATICITIES: [u32; 8] = [31_270, 32_900, 64_000, 33_000, 30_000, 60_000, 15_000, 6_000]; + if &chunk[8..chunk.len() - 4] != SRGB_CHROMATICITIES.map(u32::to_be_bytes).as_flattened() { + return Err(error(Format::Png, "PNG cHRM is incompatible with sRGB")); + } + } b"IEND" if chunk.len() == 12 => break at, b"IEND" => return Err(CodecError::malformed(Format::Png, "nonempty IEND")), _ => {} } }; let size = (png.len() - removed) - .checked_add(density.len()) + .checked_add(replacement.len()) .filter(|&size| size <= max_bytes) - .ok_or_else(|| CodecError::LimitExceeded("PNG density rewrite byte budget".into()))?; + .ok_or_else(|| CodecError::LimitExceeded(format!("{operation} byte budget")))?; let mut out = Vec::new(); - out.try_reserve_exact(size).map_err(|_| CodecError::LimitExceeded("PNG density rewrite allocation".into()))?; + out.try_reserve_exact(size).map_err(|_| CodecError::LimitExceeded(format!("{operation} allocation")))?; out.extend_from_slice(header); - out.extend_from_slice(&density); + out.extend_from_slice(replacement); let (datastream, trailing) = png.split_at(end); let mut at = PNG_IHDR_END; while let Some(chunk) = png_chunk_at(datastream, at) { - if &chunk[4..8] != b"pHYs" { + if &chunk[4..8] != kind { out.extend_from_slice(chunk); } at += chunk.len(); @@ -426,6 +466,82 @@ mod tests { assert_eq!(crate::png_probe::pixels_per_meter(&edited), Some(resolution)); } + #[test] + fn png_srgb_rewrite_replaces_duplicates_and_preserves_the_encoded_image() { + let image = crate::Image::from_u8(2, 1, crate::ChannelLayout::Rgba, vec![19, 33, 51, 127, 98, 80, 61, 255]).unwrap(); + let plain = crate::encode(&image, Format::Png, &crate::EncodeOptions::default()).unwrap(); + let old = b"\0\0\0\x01sRGB\0\xae\xce\x1c\xe9"; + let density = png_pixels_per_meter_chunk((11_811, 5_906)).unwrap(); + let iend = plain.len() - 12; + let trailer = b"container trailer"; + let input = [&plain[..33], old, &density, &plain[33..iend], old, &plain[iend..], trailer].concat(); + for (intent, expected_chunk) in [ + (SrgbRenderingIntent::Perceptual, old), + (SrgbRenderingIntent::RelativeColorimetric, b"\0\0\0\x01sRGB\x01\xd9\xc9\x2c\x7f"), + (SrgbRenderingIntent::Saturation, b"\0\0\0\x01sRGB\x02\x40\xc0\x7d\xc5"), + (SrgbRenderingIntent::AbsoluteColorimetric, b"\0\0\0\x01sRGB\x03\x37\xc7\x4d\x53"), + ] { + let expected = [&plain[..33], expected_chunk, &density, &plain[33..], trailer].concat(); + let edited = with_png_srgb(&input, intent, expected.len()).unwrap(); + assert_eq!(edited, expected); + assert_eq!(with_png_srgb(&edited, intent, edited.len()).unwrap(), edited); + assert_eq!(crate::png_probe::pixels_per_meter(&edited), Some((11_811, 5_906))); + let decoded = crate::decode(&edited[..edited.len() - trailer.len()]).unwrap(); + assert_eq!(decoded.data(), image.data()); + } + } + + #[test] + fn png_srgb_rewrite_rejects_profile_conflicts_truncation_and_output_overflow() { + let image = crate::Image::from_u8(1, 1, crate::ChannelLayout::Rgb, vec![15, 20, 35]).unwrap(); + let plain = crate::encode(&image, Format::Png, &crate::EncodeOptions::default()).unwrap(); + let intent = SrgbRenderingIntent::Perceptual; + for end in 0..plain.len() { + assert!(with_png_srgb(&plain[..end], intent, usize::MAX).is_err(), "prefix {end}"); + } + for kind in [b"iCCP", b"cICP"] { + let bytes = [&plain[..33], b"\0\0\0\0", kind, &crc32fast::hash(kind).to_be_bytes(), &plain[33..]].concat(); + assert!(matches!(with_png_srgb(&bytes, intent, usize::MAX), Err(CodecError::Encode { .. }))); + } + assert!(matches!(with_png_srgb(&plain, intent, plain.len() + 12), Err(CodecError::LimitExceeded(_)))); + assert_eq!(with_png_srgb(&plain, intent, plain.len() + 13).unwrap().len(), plain.len() + 13); + } + + #[test] + fn png_srgb_rewrite_requires_compatible_legacy_color_chunks() { + fn chunk(kind: &[u8; 4], payload: &[u8]) -> Vec { + let mut bytes = (payload.len() as u32).to_be_bytes().to_vec(); + bytes.extend_from_slice(kind); + bytes.extend_from_slice(payload); + let crc = crc32fast::hash(&bytes[4..]); + bytes.extend_from_slice(&crc.to_be_bytes()); + bytes + } + + let image = crate::Image::from_u8(1, 1, crate::ChannelLayout::Rgb, vec![15, 20, 35]).unwrap(); + let plain = crate::encode(&image, Format::Png, &crate::EncodeOptions::default()).unwrap(); + let (header, rest) = plain.split_at(33); + let gamma = chunk(b"gAMA", &45_455u32.to_be_bytes()); + let standard = [31_270u32, 32_900, 64_000, 33_000, 30_000, 60_000, 15_000, 6_000]; + let chroma = chunk(b"cHRM", &standard.map(u32::to_be_bytes).concat()); + let compatible = [header, &gamma, &chroma, rest].concat(); + let intent = SrgbRenderingIntent::Perceptual; + let marker = b"\0\0\0\x01sRGB\0\xae\xce\x1c\xe9"; + assert_eq!(with_png_srgb(&compatible, intent, usize::MAX).unwrap(), [header, marker, &gamma, &chroma, rest].concat()); + + let other_gamma = chunk(b"gAMA", &45_454u32.to_be_bytes()); + let mut other_chroma = standard; + other_chroma[7] += 1; + let other_chroma = chunk(b"cHRM", &other_chroma.map(u32::to_be_bytes).concat()); + let incomplete_chroma = chunk(b"cHRM", &standard[..7].iter().flat_map(|value| value.to_be_bytes()).collect::>()); + let conflicts = [(&other_gamma, &chroma), (&gamma, &other_chroma), (&gamma, &incomplete_chroma)]; + let rejected = conflicts.map(|(g, c)| { + let incompatible = [header, g, c, rest].concat(); + matches!(with_png_srgb(&incompatible, intent, usize::MAX), Err(CodecError::Encode { .. })) + }); + assert_eq!(rejected, [true; 3]); + } + #[test] fn jpeg_segments_keep_order_and_enforce_limits() { let parts = jpeg_segments(JpegMetadata { exif: Some(EXIF), xmp: Some(""), icc: Some(&[1, 2]), ppi: Some(300) }).unwrap(); diff --git a/crates/media/src/avi/framed_audio.rs b/crates/media/src/avi/framed_audio.rs new file mode 100644 index 0000000000..189495ed62 --- /dev/null +++ b/crates/media/src/avi/framed_audio.rs @@ -0,0 +1,211 @@ +//! AVI audio chunk boundaries need not match MPEG audio or AC-3 frame boundaries. + +use std::io; + +use super::{ByteSource, Chunk, Error, Result}; +use crate::mpegts::{Codec, FrameInfo, frame_bytes, frame_info}; + +// Indexed chunks can refer to the same file bytes repeatedly. Bound even +// the concatenated length, before making any reads through that index. +const MAX_SCAN_BYTES: u64 = 256 << 20; +const WINDOW: usize = 16 << 10; +const HEADER: usize = 8; + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +struct Position { + chunk: usize, + offset: u32, +} + +impl Position { + fn take(&mut self, chunks: &[Chunk], count: usize) -> Option<(u64, usize)> { + while let Some(chunk) = chunks.get(self.chunk) { + if self.offset < chunk.size { + let start = chunk.offset.checked_add(u64::from(self.offset))?; + let len = count.min((chunk.size - self.offset) as usize); + self.offset += len as u32; + return Some((start, len)); + } + self.chunk += 1; + self.offset = 0; + } + None + } + + fn skip(&mut self, chunks: &[Chunk], mut count: usize) -> Result<()> { + while count != 0 { + let (_, len) = self.take(chunks, count).ok_or_else(short_range)?; + count -= len; + } + Ok(()) + } + + fn read(mut self, source: &(impl ByteSource + ?Sized), chunks: &[Chunk], mut dst: &mut [u8]) -> Result<()> { + while !dst.is_empty() { + let (offset, len) = self.take(chunks, dst.len()).ok_or_else(short_range)?; + let (current, rest) = dst.split_at_mut(len); + source.read_at(offset, current)?; + dst = rest; + } + Ok(()) + } +} + +fn short_range() -> Error { + Error::Io(io::ErrorKind::UnexpectedEof.into()) +} + +/// A complete compressed audio packet in the logical concatenation of an AVI stream's chunks. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct FramedAudioPacket { + start: Position, + len: usize, + /// Sample information from the frame header, when it was readable. + pub info: Option, +} + +impl FramedAudioPacket { + /// Read exactly the packet bytes using the same chunk table used to find the packet. + pub fn read(self, source: &(impl ByteSource + ?Sized), chunks: &[Chunk]) -> Result> { + let mut bytes = Vec::new(); + bytes.try_reserve_exact(self.len).map_err(|_| io::Error::from(io::ErrorKind::OutOfMemory))?; + bytes.resize(self.len, 0); + self.start.read(source, chunks, &mut bytes)?; + Ok(bytes) + } +} + +/// Walk MPEG audio or AC-3 packets across the chunks of one AVI audio stream. +/// +/// The iterator uses a fixed-size window and leaves packet index storage to +/// the caller. It skips unrecognized bytes, omits incomplete frames and +/// stops after reporting a source read error. The scan admits at most four +/// times the source size in logical chunks, with a 256 MiB ceiling. +pub fn framed_audio_packets<'a>( + source: &'a (impl ByteSource + ?Sized), + chunks: &'a [Chunk], + codec: &'a Codec, +) -> Result> + 'a> { + if !matches!(codec, Codec::MpegAudio | Codec::Ac3 | Codec::Eac3) { + return Err(Error::Invalid("unsupported framed AVI audio codec".into())); + } + let budget = source.len().saturating_mul(4).min(MAX_SCAN_BYTES) as usize; + let total = chunks + .iter() + .try_fold(0usize, |sum, chunk| sum.checked_add(chunk.size as usize).filter(|&n| n <= budget)) + .ok_or_else(|| Error::Invalid("AVI framed audio exceeds the scan budget".into()))?; + let mut window = [0; WINDOW]; + let (mut base, mut len, mut pos) = (0usize, 0usize, 0usize); + let mut cursor = Position::default(); + + Ok(std::iter::from_fn(move || { + while pos < total { + let want = HEADER.min(total - pos); + let have = (base + len).saturating_sub(pos); + if have < want { + // Retain a partial header before loading the next window, so + // no chunk bytes are read twice during the scan. + window.copy_within(len - have..len, 0); + base = pos; + len = WINDOW.min(total - pos); + let mut reader = cursor; + if let Err(error) = reader.skip(chunks, have).and_then(|()| reader.read(source, chunks, &mut window[have..len])) { + pos = total; + return Some(Err(error)); + } + } + let head = &window[pos - base..pos - base + want]; + let packet = frame_bytes(codec, head).filter(|&size| size > 0 && size <= total - pos).map(|size| FramedAudioPacket { + start: cursor, + len: size, + info: frame_info(codec, head), + }); + let advance = packet.map_or(1, |packet| packet.len); + if let Err(error) = cursor.skip(chunks, advance) { + pos = total; + return Some(Err(error)); + } + pos += advance; + if let Some(packet) = packet { + return Some(Ok(packet)); + } + } + None + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + struct Source { + bytes: Vec, + read: Cell, + } + + impl ByteSource for Source { + fn len(&self) -> u64 { + self.bytes.len() as u64 + } + + fn read_at(&self, offset: u64, out: &mut [u8]) -> io::Result<()> { + self.read.set(self.read.get() + out.len()); + self.bytes.read_at(offset, out) + } + } + + fn interleave_padding(logical: &[u8], lengths: &[usize]) -> (Source, Vec) { + let mut chunks = Vec::new(); + let mut bytes = Vec::new(); + let mut pos = 0; + for length in lengths.iter().copied().chain(std::iter::once(logical.len())) { + let count = length.min(logical.len() - pos); + chunks.push(Chunk { offset: bytes.len() as u64, size: count as u32, key: true }); + bytes.extend_from_slice(&logical[pos..pos + count]); + bytes.push(0xff); // Bytes between the AVI chunks must not enter the stream. + pos += count; + } + (Source { bytes, read: Cell::new(0) }, chunks) + } + + #[test] + fn split_mpeg_header_and_packet_match_the_original_bytes() { + // Original frame framing, with 128 kb/s Layer III at 48 kHz. + let mut packet = vec![0x12; 384]; + packet[..4].copy_from_slice(&[0xff, 0xfb, 0x94, 0xc0]); + let mut logical = vec![0x22; WINDOW - 3]; + logical.extend_from_slice(&packet); + logical.extend_from_slice(&packet); + logical.extend_from_slice(&packet[..20]); // Incomplete last frame. + let (source, chunks) = interleave_padding(&logical, &[WINDOW - 2, 0, 1, 19, 128]); + let found = framed_audio_packets(&source, &chunks, &Codec::MpegAudio).unwrap().collect::>>().unwrap(); + assert_eq!(source.read.get(), logical.len(), "the small window never rereads bytes"); + assert_eq!(found.len(), 2); + for frame in found { + assert_eq!(frame.info.unwrap().samples, 1152); + assert_eq!(frame.read(&source, &chunks).unwrap(), packet); + } + } + + #[test] + fn ac3_frame_spans_separate_chunks() { + // Original AC-3 test header for a 128-byte, 48 kHz stereo frame. + let mut packet = vec![0; 128]; + packet[..8].copy_from_slice(&[0x0b, 0x77, 0, 0, 0, 0x40, 0x40, 0]); + let (source, chunks) = interleave_padding(&packet, &[1, 6, 2]); + let mut scan = framed_audio_packets(&source, &chunks, &Codec::Ac3).unwrap(); + let frame = scan.next().unwrap().unwrap(); + assert_eq!(frame.info.map(|info| (info.sample_rate, info.channels, info.samples)), Some((48_000, 2, 1536))); + assert_eq!(frame.read(&source, &chunks).unwrap(), packet); + assert!(scan.next().is_none()); + } + + #[test] + fn repeated_index_ranges_cannot_expand_the_scan_budget() { + let source = Source { bytes: vec![0; 64], read: Cell::new(0) }; + let chunks = [Chunk { offset: 0, size: 64, key: true }; 5]; + assert!(matches!(framed_audio_packets(&source, &chunks, &Codec::MpegAudio), Err(Error::Invalid(_)))); + assert_eq!(source.read.get(), 0); + } +} diff --git a/crates/media/src/avi/mod.rs b/crates/media/src/avi/mod.rs index 69e9197058..d813063d30 100644 --- a/crates/media/src/avi/mod.rs +++ b/crates/media/src/avi/mod.rs @@ -18,12 +18,16 @@ #![warn(missing_docs)] +#[cfg(feature = "mpegts")] +mod framed_audio; mod mux; #[cfg(test)] mod mux_tests; #[cfg(test)] mod tests; +#[cfg(feature = "mpegts")] +pub use framed_audio::{FramedAudioPacket, framed_audio_packets}; pub use mux::{AudioSpec, AudioTiming, AviWriter, MuxOptions, StreamSpec, VideoSpec}; pub use crate::source::{ByteSource, ReadSeekSource}; diff --git a/crates/metafile/src/emf.rs b/crates/metafile/src/emf.rs index 39aff6d057..52eb9ea392 100644 --- a/crates/metafile/src/emf.rs +++ b/crates/metafile/src/emf.rs @@ -77,22 +77,15 @@ pub(crate) fn parse(input: Bytes) -> Result<(Canvas, Option), Error> { } /// Device pixels per millimetre on each axis, from `szlDevice` (72) and the device's size: -/// `szlMicrometers` (100) when the header has that extension (a header of 108 bytes or more) and +/// `szlMicrometers` (100) when the fixed header includes that extension and /// it is set, which is a thousand times finer, else `szlMillimeters` (80). fn device_px_per_mm(input: Bytes) -> Option<(f64, f64)> { - let (dw, dh) = (input.i32(72)?, input.i32(76)?); - if dw <= 0 || dh <= 0 { - return None; - } - if input.u32(4)? >= 108 - && let (Some(uw), Some(uh)) = (input.u32(100), input.u32(104)) - && uw > 0 - && uh > 0 - { - return Some((f64::from(dw) * 1000.0 / f64::from(uw), f64::from(dh) * 1000.0 / f64::from(uh))); - } - let (mw, mh) = (input.i32(80)?, input.i32(84)?); - (mw > 0 && mh > 0).then(|| (f64::from(dw) / f64::from(mw), f64::from(dh) / f64::from(mh))) + let facts = crate::units::emf_device(input)?; + let (dw, dh) = (f64::from(facts.pixels.0), f64::from(facts.pixels.1)); + Some(match facts.physical_size { + crate::EmfPhysicalSize::Micrometres(w, h) => (dw * 1000.0 / f64::from(w), dh * 1000.0 / f64::from(h)), + crate::EmfPhysicalSize::Millimetres(w, h) => (dw / f64::from(w), dh / f64::from(h)), + }) } /// The frame from `rclFrame` (offset 24), `szlDevice` (72) and `szlMillimeters` (80) in the header. diff --git a/crates/metafile/src/eof.rs b/crates/metafile/src/eof.rs new file mode 100644 index 0000000000..965360391e --- /dev/null +++ b/crates/metafile/src/eof.rs @@ -0,0 +1,79 @@ +use crate::Kind; +const PLACEABLE_KEY: u32 = 0x9AC6_CDD7; + +/// Whether the stream stops before an EOF record header is recognizable. +/// +/// This is a diagnostic, not validation: a recognizable EOF header ends +/// the scan even if its payload is incomplete. A parser's resource-limit +/// status is independent of this result. +pub fn ends_early(bytes: &[u8], kind: Kind) -> bool { + let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + let u16_at = |at: usize| bytes.get(at..at.checked_add(2)?).map(|b| u16::from_le_bytes([b[0], b[1]])); + let mut at = match kind { + Kind::Emf => 0, + Kind::Wmf => { + let start = if u32_at(0) == Some(PLACEABLE_KEY) { 22 } else { 0 }; + let Some(words) = u16_at(start + 2) else { return true }; + start + usize::from(words) * 2 + } + }; + loop { + let size = match kind { + Kind::Emf => { + let (Some(kind), Some(size)) = (u32_at(at), u32_at(at.saturating_add(4))) else { return true }; + if kind == 14 { + return false; + } + // Records are a multiple of 4 bytes long; reading stops at one that isn't. + if !size.is_multiple_of(4) { + return true; + } + size as usize + } + Kind::Wmf => { + let (Some(words), Some(function)) = (u32_at(at), u16_at(at.saturating_add(4))) else { return true }; + if function == 0 { + return false; + } + (words as usize).saturating_mul(2) + } + }; + if size < 6 { + return true; + } + at = at.saturating_add(size); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn emf_eof_header_is_enough_but_other_records_need_aligned_lengths() { + let mut bytes = [1u32, 8, 14, 20].into_iter().flat_map(u32::to_le_bytes).collect::>(); + assert!(!ends_early(&bytes, Kind::Emf)); + assert!(ends_early(&bytes[..12], Kind::Emf)); + bytes[4] = 9; + assert!(ends_early(&bytes, Kind::Emf)); + bytes[4] = 40; + assert!(ends_early(&bytes, Kind::Emf)); + } + + #[test] + fn wmf_eof_follows_standard_and_placeable_headers() { + for prefix in [0usize, 22] { + let mut bytes = vec![0u8; prefix + 18]; + if prefix == 22 { + bytes[..4].copy_from_slice(&PLACEABLE_KEY.to_le_bytes()); + } + bytes[prefix + 2] = 9; + bytes.extend_from_slice(&[5, 0, 0, 0, 0, 0]); + assert!(!ends_early(&bytes, Kind::Wmf)); + assert!(ends_early(&bytes[..bytes.len() - 1], Kind::Wmf)); + let function = bytes.len() - 2; + bytes[function] = 1; + assert!(ends_early(&bytes, Kind::Wmf)); + } + } +} diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 26a406d312..5e9c4a6703 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -30,6 +30,7 @@ mod geom; mod place; mod size; mod text; +mod units; mod wmf; #[cfg(feature = "write")] @@ -44,9 +45,12 @@ use std::sync::Arc; use bytes::Bytes; use canvas::Raw; use geom::{Op, P}; +mod eof; +pub use eof::ends_early; pub use place::{MAX_BITMAP_SIDE, PlacedClip, PlacedItem, bez_path, crop_window}; pub use size::size; pub use text::{Font, HAlign, SYMBOL_CHARSET, Text, VAlign}; +pub use units::{EmfDevice, EmfPhysicalSize, UnitFacts, unit_facts}; /// Items kept from one file. Past the cap the parse stops and keeps what it has. pub(crate) const MAX_ITEMS: usize = 200_000; diff --git a/crates/metafile/src/units.rs b/crates/metafile/src/units.rs new file mode 100644 index 0000000000..33dc87137b --- /dev/null +++ b/crates/metafile/src/units.rs @@ -0,0 +1,272 @@ +//! Frame and unit facts for consumers that apply their own fallback scale. +//! The WMF map-mode scan is adapted from VectorCraft’s metafile importer. + +use crate::{Kind, MAX_STACK, bytes::Bytes, sniff, wmf::PLACEABLE_KEY}; + +/// File-declared frame and source-unit information; does not assign a default physical scale. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UnitFacts { + /// A placeable WMF with positive frame extents. + WmfPlaceableFrame, + /// Without a placeable frame, a WMF whose drawing records predominantly use legacy map + /// modes 2–6 (LOMETRIC, HIMETRIC, LOENGLISH, HIENGLISH, TWIPS). This compatibility group + /// does not imply a particular physical unit. Ties use the last map mode seen. + WmfMetricMap, + /// Without a placeable frame, a WMF whose drawing records use logical units. + WmfLogical { + /// Positive units per inch from a placeable header, when one is present. + units_per_inch: Option, + }, + Emf { + /// The frame coordinates have positive extents, independently of device calibration. + has_frame: bool, + /// The device calibration, when both axes are positive. + device: Option, + }, +} + +/// The two axes of device calibration in an EMF header. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct EmfDevice { + /// Width and height, in pixels. + pub pixels: (u32, u32), + /// Device width and height, in the units supplied by the header. + pub physical_size: EmfPhysicalSize, +} + +/// The precision of the physical device size supplied by an EMF header. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EmfPhysicalSize { + /// The header's extended micrometre fields were both positive. + Micrometres(u32, u32), + /// The extension was missing or incomplete; the millimetre fields were both positive. + Millimetres(u32, u32), +} + +/// Inspects a recognized WMF or EMF without decoding images, allocating geometry, or assigning +/// a physical size to a file that supplies none. A matching header is not proof that its records +/// parse successfully: use [`crate::parse`] for the actual picture. +pub fn unit_facts(bytes: &[u8]) -> Option { + let b = Bytes(bytes); + Some(match sniff(bytes)? { + Kind::Emf => UnitFacts::Emf { + has_frame: matches!((b.i32(24), b.i32(28), b.i32(32), b.i32(36)), (Some(l), Some(t), Some(r), Some(bt)) if r > l && bt > t), + device: emf_device(b), + }, + Kind::Wmf => { + let placeable = b.u32(0) == Some(PLACEABLE_KEY); + if placeable && matches!((b.i16(6), b.i16(8), b.i16(10), b.i16(12)), (Some(l), Some(t), Some(r), Some(bt)) if r > l && bt > t) { + UnitFacts::WmfPlaceableFrame + } else if wmf_metric(b, if placeable { 22 } else { 0 }) { + UnitFacts::WmfMetricMap + } else { + let units_per_inch = if placeable { b.u16(14).filter(|&inch| inch > 0) } else { None }; + UnitFacts::WmfLogical { units_per_inch } + } + } + }) +} + +// MS-EMF §2.3.4.2: optional description and pixel-format data follow +// the fixed fields. The total record size by itself cannot identify an extension. +fn emf_fixed_header_size(b: Bytes<'_>) -> Option { + let mut end = usize::try_from(b.u32(4)?).ok()?.min(b.0.len()); + if b.u32(60)? != 0 { + end = end.min(usize::try_from(b.u32(64)?).ok()?); + } + // Only inspect the extension-1 descriptor if it fits before any description. + if end >= 100 && b.u32(88)? != 0 { + end = end.min(usize::try_from(b.u32(92)?).ok()?); + } + Some(end) +} + +pub(crate) fn emf_device(b: Bytes<'_>) -> Option { + let positive = |v: i32| u32::try_from(v).ok().filter(|&v| v > 0); + let pixels = (positive(b.i32(72)?)?, positive(b.i32(76)?)?); + let physical_size = if emf_fixed_header_size(b)? >= 108 + && let (Some(w), Some(h)) = (positive(b.i32(100)?), positive(b.i32(104)?)) + { + EmfPhysicalSize::Micrometres(w, h) + } else { + EmfPhysicalSize::Millimetres(positive(b.i32(80)?)?, positive(b.i32(84)?)?) + }; + Some(EmfDevice { pixels, physical_size }) +} + +// Preserve the VectorCraft compatibility scan: count recognized drawing records under the map +// mode in which they appear, skipping suppressed shape and PATBLT classes. This is not replay. +fn wmf_metric(b: Bytes<'_>, start: usize) -> bool { + const SHAPES: [u16; 10] = [0x0213, 0x0324, 0x0325, 0x0418, 0x041B, 0x0538, 0x061C, 0x0817, 0x081A, 0x0830]; + const DRAW: [u16; 5] = [0x0521, 0x0940, 0x0A32, 0x0B41, 0x0F43]; + const MIX_SKIPS: [u16; 2] = [7, 11]; // R2_XORPEN and R2_NOP + const PATCOPY: u32 = 0x00F0_0021; + const BLACKNESS: u32 = 0x0000_0042; + const WHITENESS: u32 = 0x00FF_0062; + let Some(words) = start.checked_add(2).and_then(|at| b.u16(at)) else { return false }; + let mut at = start.saturating_add(usize::from(words) * 2); + let (mut mode, mut mix) = (1, 13); // MM_TEXT, R2_COPYPEN + let metric = |mode: u16| (2..=6).contains(&mode); + let (mut in_metric, mut in_other) = (0usize, 0usize); + let mut saved = Vec::new(); + while let (Some(words), Some(function)) = (b.u32(at), b.u16(at.saturating_add(4))) { + let size = (words as usize).saturating_mul(2); + let Some(next) = at.checked_add(size) else { break }; + if function == 0 || size < 6 || next > b.0.len() { + break; + } + match function { + 0x0103 if size >= 8 => mode = b.u16(at + 6).unwrap_or(mode), // SETMAPMODE + 0x0104 if size >= 8 => mix = b.u16(at + 6).unwrap_or(mix), // SETROP2 + 0x001E => { + // SAVEDC + if saved.len() >= MAX_STACK { + break; + } + saved.push((mode, mix)); + } + 0x0127 if size >= 8 => { + // RESTOREDC + let n = b.i16(at + 6).map_or(0, i32::from); + let level = if n < 0 { saved.len().checked_sub(n.unsigned_abs() as usize) } else { (n as usize).checked_sub(1) }; + if let Some(level) = level + && let Some((m, x)) = saved.get(level).copied() + { + mode = m; + mix = x; + saved.truncate(level); + } + } + f => { + let draws = match f { + _ if DRAW.contains(&f) => true, + _ if SHAPES.contains(&f) => !MIX_SKIPS.contains(&mix), + 0x061D => match b.u32(at + 6).filter(|_| size >= 10) { + // PATBLT + Some(PATCOPY) => !MIX_SKIPS.contains(&mix), + Some(rop) => rop == BLACKNESS || rop == WHITENESS, + None => false, + }, + _ => false, + }; + if draws && metric(mode) { + in_metric += 1; + } else if draws { + in_other += 1; + } + } + } + at = next; + } + if in_metric == in_other { metric(mode) } else { in_metric > in_other } +} + +#[cfg(test)] +mod tests { + use super::*; + + // Spec-generated headers and records; no external fixture bytes. + fn plain_wmf(records: &[(u16, &[u8])]) -> Vec { + let mut bytes = vec![0; 18]; + bytes[..6].copy_from_slice(&[1, 0, 9, 0, 0, 3]); + for (kind, parameters) in records { + bytes.extend_from_slice(&((parameters.len() / 2 + 3) as u32).to_le_bytes()); + bytes.extend_from_slice(&kind.to_le_bytes()); + bytes.extend_from_slice(parameters); + } + bytes + } + + #[test] + fn placeable_bounds_win_or_leave_the_declared_scale_for_logical_units() { + let mut bytes = vec![0; 22]; + bytes[..4].copy_from_slice(&PLACEABLE_KEY.to_le_bytes()); + bytes[10..12].copy_from_slice(&100i16.to_le_bytes()); + bytes[12..14].copy_from_slice(&80i16.to_le_bytes()); + bytes[14..16].copy_from_slice(&720u16.to_le_bytes()); + bytes.extend_from_slice(&plain_wmf(&[(0x0103, &[3, 0])])); + assert_eq!(unit_facts(&bytes), Some(UnitFacts::WmfPlaceableFrame)); + bytes[12..14].fill(0); + assert_eq!(unit_facts(&bytes), Some(UnitFacts::WmfMetricMap)); + bytes[46..48].copy_from_slice(&[1, 0]); + assert_eq!(unit_facts(&bytes), Some(UnitFacts::WmfLogical { units_per_inch: Some(720) })); + bytes[14..16].fill(0); + assert_eq!(unit_facts(&bytes), Some(UnitFacts::WmfLogical { units_per_inch: None })); + assert_eq!(unit_facts(&plain_wmf(&[])), Some(UnitFacts::WmfLogical { units_per_inch: None })); + } + + #[test] + fn wmf_dominance_counts_drawing_modes_and_respects_save_restore() { + let metric = [3, 0]; + let logical = [1, 0]; + let nop = [11, 0]; + let restore = (-1i16).to_le_bytes(); + let line = [20, 0, 10, 0]; + let unsupported_rop = 0x0055_0009u32.to_le_bytes(); + let bytes = plain_wmf(&[ + (0x0103, &metric), + (0x0213, &line), + (0x001E, &[]), + (0x0103, &logical), + (0x0104, &nop), + (0x0213, &line), + (0x0213, &line), + (0x061D, &unsupported_rop), + (0x0127, &restore), + (0x0213, &line), + (0x0103, &logical), + ]); + assert_eq!(unit_facts(&bytes), Some(UnitFacts::WmfMetricMap)); + let mut bytes = plain_wmf(&[(0x0103, &metric)]); + bytes.extend_from_slice(&[4, 0, 0, 0, 3, 1]); // Declares a mode change with a missing parameter. + assert_eq!(unit_facts(&bytes), Some(UnitFacts::WmfMetricMap)); + } + + #[test] + fn emf_frame_and_device_calibration_are_independent_facts() { + let mut bytes = vec![0; 108]; + let set = |buf: &mut [u8], i: usize, value: i32| buf[i..i + 4].copy_from_slice(&value.to_le_bytes()); + for (i, v) in + [(0, 1), (4, 108), (32, 100), (36, 50), (40, 0x464d_4520), (72, 800), (76, 600), (80, 200), (84, 150), (100, 200_150), (104, 149_900)] + { + set(&mut bytes, i, v); + } + let facts = |has_frame, physical_size| Some(UnitFacts::Emf { has_frame, device: Some(EmfDevice { pixels: (800, 600), physical_size }) }); + assert_eq!(unit_facts(&bytes), facts(true, EmfPhysicalSize::Micrometres(200_150, 149_900))); + assert_eq!(unit_facts(&bytes[..104]), facts(true, EmfPhysicalSize::Millimetres(200, 150))); + set(&mut bytes, 100, -1); + assert_eq!(unit_facts(&bytes), facts(true, EmfPhysicalSize::Millimetres(200, 150))); + set(&mut bytes, 100, 200_150); + set(&mut bytes, 104, -1); + assert_eq!(unit_facts(&bytes), facts(true, EmfPhysicalSize::Millimetres(200, 150))); + set(&mut bytes, 104, 149_900); + set(&mut bytes, 4, 88); + set(&mut bytes, 36, 0); + assert_eq!(unit_facts(&bytes), facts(false, EmfPhysicalSize::Millimetres(200, 150))); + set(&mut bytes, 76, -1); + assert_eq!(unit_facts(&bytes), Some(UnitFacts::Emf { has_frame: false, device: None })); + assert_eq!(unit_facts(b"not a metafile"), None); + } + #[test] + fn emf_variable_payloads_do_not_supply_micrometres() { + let mut bytes = vec![0; 148]; + let set = |buf: &mut [u8], i: usize, value: u32| buf[i..i + 4].copy_from_slice(&value.to_le_bytes()); + for (at, value) in [(0, 1), (4, 112), (40, 0x464d_4520), (60, 11), (64, 88), (72, 800), (76, 600), (80, 200), (84, 150)] { + set(&mut bytes, at, value); + } + for (dst, src) in bytes[88..110].as_chunks_mut::<2>().0.iter_mut().zip("app\0title\0\0".encode_utf16()) { + dst.copy_from_slice(&src.to_le_bytes()); + } + let mm = Some(EmfDevice { pixels: (800, 600), physical_size: EmfPhysicalSize::Millimetres(200, 150) }); + assert_eq!(emf_device(Bytes(&bytes)), mm); + + // The same numeric bytes are part of a pixel descriptor in extension 1, + // but are fixed calibration fields when extension 2 precedes that descriptor. + for (at, value) in [(4, 148), (60, 0), (64, 0), (88, 40), (92, 100), (100, 201_000), (104, 151_000)] { + set(&mut bytes, at, value); + } + assert_eq!(emf_device(Bytes(&bytes)), mm); + set(&mut bytes, 92, 108); + assert_eq!(emf_device(Bytes(&bytes)), Some(EmfDevice { pixels: (800, 600), physical_size: EmfPhysicalSize::Micrometres(201_000, 151_000) })); + } +} diff --git a/crates/metafile/src/wmf.rs b/crates/metafile/src/wmf.rs index 62af9c74bd..915d1d229f 100644 --- a/crates/metafile/src/wmf.rs +++ b/crates/metafile/src/wmf.rs @@ -10,7 +10,7 @@ use crate::geom::{self, ArcKind, P}; use crate::text::{ETO_CLIPPED, ETO_OPAQUE, Font, MAX_CHARS, decode_bytes}; use crate::{Error, Frame, MAX_PATH_OPS}; -const PLACEABLE_KEY: u32 = 0x9AC6_CDD7; +pub(crate) const PLACEABLE_KEY: u32 = 0x9AC6_CDD7; const DEFAULT_INCH: f64 = 1440.0; /// A placeable WMF plays into a target sized in points; brushes are laid out in 96-dpi pixels. const PT_PER_PX: f64 = 72.0 / 96.0; diff --git a/crates/plotter/src/hpgl/write.rs b/crates/plotter/src/hpgl/write.rs index 1d1cac34ea..a1b60e9d0d 100644 --- a/crates/plotter/src/hpgl/write.rs +++ b/crates/plotter/src/hpgl/write.rs @@ -94,10 +94,42 @@ pub fn write_hpgl2(pens: &[Pen], paths_per_pen: &[Vec>]) -> Vec< out } +/// HP-GL: `IN;`, each pen's paths as `PU` and `PD`, `PU;SP0;`. +/// +/// The index of each path group plus one is its pen number; empty groups do not +/// renumber later pens. The caller owns coordinate and output-size limits. +/// The original classic serializer is from dotCooCoo (VectorCraft 987dd18a). +pub fn write_hpgl(by_pen: &[Vec>]) -> Vec { + let mut s = String::from("IN;"); + for (i, paths) in by_pen.iter().enumerate().filter(|(_, p)| !p.is_empty()) { + s.push_str(&format!("PU;SP{};", i + 1)); + for path in paths { + let Some(((x, y), rest)) = path.split_first() else { continue }; + s.push_str(&format!("PU{x},{y};PD")); + for (k, (x, y)) in rest.iter().enumerate() { + if k > 0 { + s.push(','); + } + s.push_str(&format!("{x},{y}")); + } + s.push(';'); + } + } + s.push_str("PU;SP0;"); + s.into_bytes() +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn classic_hpgl_keeps_pen_ordinals_and_path_bytes() { + assert_eq!(write_hpgl(&[]), b"IN;PU;SP0;"); + let paths = vec![vec![vec![(0, 0), (9, -3), (5, 1)]], vec![], vec![vec![(4, 1), (0, 2)], vec![(5, -6), (7, 8)]]]; + assert_eq!(write_hpgl(&paths), b"IN;PU;SP1;PU0,0;PD9,-3,5,1;PU;SP3;PU4,1;PD0,2;PU5,-6;PD7,8;PU;SP0;"); + } + #[test] fn pe_numbers_are_raw_bytes_and_paths_lift_the_pen() { let first: &[(i64, i64)] = &[(0, 0), (10, -10)]; diff --git a/crates/pptx/tests/read.rs b/crates/pptx/tests/read.rs index fd03d2d981..44ee293a74 100644 --- a/crates/pptx/tests/read.rs +++ b/crates/pptx/tests/read.rs @@ -1,5 +1,7 @@ //! The reader on small packages written by hand. +mod common; + use craft_opc::{PackageOut, RelsOut}; use craft_pptx::{Defaults, Geom, LayoutType, Master, PhType, Plain, Presentation, ShapeKind, Size}; @@ -105,6 +107,40 @@ fn shape<'a>(p: &'a Presentation, name: &str) -> &'a craft_pptx::Shape { found.unwrap_or_else(|| panic!("no shape {name}")) } +#[test] +fn direct_nested_compatibility_choice_imports_selected_shape() { + let before = sp(20, "Before choice", "", XFRM, "Before"); + let outer_rejected = sp(21, "Outer rejected", "", XFRM, "Outer"); + let selected = sp(22, "Nested selected", "", XFRM, "Selected"); + let inner_rejected = sp(23, "Inner rejected", "", XFRM, "Inner"); + let after = sp(24, "After choice", "", XFRM, "After"); + let nested = format!( + r#"{before} + {outer_rejected} + + {selected} + {inner_rejected} + + {after}"# + ); + let bytes = common::rewrite( + &deck(), + |part, data| { + if part == "ppt/slides/slide1.xml" { + Some(std::str::from_utf8(data).unwrap().replace("", &nested).into_bytes()) + } else { + Some(data.to_vec()) + } + }, + &[], + ); + let p = craft_pptx::import(&bytes, &Plain).unwrap(); + let names: Vec<_> = p.slides[0].shapes.iter().map(|shape| shape.name.as_str()).collect(); + assert!(names.ends_with(&["Before choice", "Nested selected", "After choice"]), "{names:?}"); + assert_eq!(names.iter().filter(|&&name| name == "Nested selected").count(), 1); + assert!(!names.contains(&"Outer rejected") && !names.contains(&"Inner rejected")); +} + #[test] fn a_small_deck_reads_into_the_model() { let bytes = deck(); diff --git a/crates/ps/src/read/lex.rs b/crates/ps/src/read/lex.rs index c8f81add7c..6c08bf5fce 100644 --- a/crates/ps/src/read/lex.rs +++ b/crates/ps/src/read/lex.rs @@ -252,6 +252,13 @@ impl<'a> Lexer<'a> { out.push(b); } b'\\' => self.string_escape(&mut out)?, + // PLRM §3.8 treats an unescaped CR or CRLF as one LF inside a string. + b'\r' => { + if self.peek() == Some(b'\n') { + self.pos += 1; + } + out.push(b'\n'); + } _ => out.push(b), } } @@ -391,6 +398,17 @@ mod tests { assert_eq!(lex.rest(), b"TA"); } + #[test] + fn literal_string_line_endings_preserve_currentfile_data() { + for eol in [b"\n".as_slice(), b"\r", b"\r\n"] { + let source = [b"(first".as_slice(), eol, b"second\\", eol, b"third\\r\\015)", b"\r\nA\r\nB"].concat(); + let mut lex = Lexer::new(&source); + assert_eq!(lex.next(), Ok(Some(Token::Str(b"first\nsecondthird\r\r".to_vec()))), "line ending {eol:?}"); + assert_eq!(lex.rest(), b"\r\nA\r\nB"); + assert_eq!(lex.data(), b"A\r\nB"); + } + } + #[test] fn partial_lines_and_eof() { let mut lex = Lexer::new(b"1 2 add"); diff --git a/crates/sqlite/src/lib.rs b/crates/sqlite/src/lib.rs index 0a43c1fa71..1771113384 100644 --- a/crates/sqlite/src/lib.rs +++ b/crates/sqlite/src/lib.rs @@ -8,6 +8,8 @@ use core::fmt; +pub mod wal; + const MAX_VARINT_BYTES: usize = 9; /// The b-tree cell layouts that carry payload bytes. diff --git a/crates/sqlite/src/wal.rs b/crates/sqlite/src/wal.rs new file mode 100644 index 0000000000..1e236e0e29 --- /dev/null +++ b/crates/sqlite/src/wal.rs @@ -0,0 +1,123 @@ +//! Committed-prefix scanning for SQLite write-ahead logs. +//! Wire algorithm moved from LightCraft (Orthic Labs, 4a427894; Dylan M. Taylor, be760ee5). + +fn be_word(bytes: &[u8], at: usize) -> Result { + let word = bytes.get(at..at + 4).and_then(|s| <[u8; 4]>::try_from(s).ok()).ok_or("truncated WAL")?; + Ok(u32::from_be_bytes(word)) +} + +fn wal_checksum(bytes: &[u8], big: bool, mut sum: (u32, u32)) -> (u32, u32) { + for pair in bytes.as_chunks::<8>().0 { + let first = [pair[0], pair[1], pair[2], pair[3]]; + let second = [pair[4], pair[5], pair[6], pair[7]]; + let (first, second) = + if big { (u32::from_be_bytes(first), u32::from_be_bytes(second)) } else { (u32::from_le_bytes(first), u32::from_le_bytes(second)) }; + sum.0 = sum.0.wrapping_add(first).wrapping_add(sum.1); + sum.1 = sum.1.wrapping_add(second).wrapping_add(sum.0); + } + sum +} + +// SQLite file format §4: validate the live checksum chain in constant space, then overlay +// only its last committed prefix. The forensic timeline materializes EVERY historical +// database snapshot; it must never be used to validate a large, actively used catalog. +/// Returns the byte length through the last checksum-valid commit, or zero if none. +/// An incomplete or uncommitted suffix is not applied; a malformed header errors. +/// The database header supplies the expected page size. Uses constant memory. +pub fn committed_prefix_len(main: &[u8], wal: &[u8]) -> Result { + if wal.is_empty() { + return Ok(0); + } + let header = wal.get(..32).ok_or("truncated WAL header")?; + let magic = be_word(header, 0)?; + if !matches!(magic, 0x377f0682 | 0x377f0683) || be_word(header, 4)? != 3_007_000 { + return Err("invalid WAL header"); + } + let raw_size = main.get(16..18).and_then(|s| <[u8; 2]>::try_from(s).ok()).map(u16::from_be_bytes).ok_or("truncated SQLite header")?; + let size = crate::page_size_from_raw(raw_size).map_err(|_| "WAL page size mismatch")?; + if be_word(header, 8)? != size { + return Err("WAL page size mismatch"); + } + let big = magic == 0x377f0683; + let mut sum = wal_checksum(&header[..24], big, (0, 0)); + if sum != (be_word(header, 24)?, be_word(header, 28)?) { + return Err("invalid WAL header checksum"); + } + let salt = (be_word(header, 16)?, be_word(header, 20)?); + let mut committed = 0; + let stride = size as usize + 24; + for (i, frame) in wal[32..].chunks_exact(stride).enumerate() { + if be_word(frame, 0)? == 0 || salt != (be_word(frame, 8)?, be_word(frame, 12)?) { + break; + } + sum = wal_checksum(&frame[..8], big, sum); + sum = wal_checksum(&frame[24..], big, sum); + if sum != (be_word(frame, 16)?, be_word(frame, 20)?) { + break; + } + if be_word(frame, 4)? != 0 { + committed = 32 + (i + 1) * stride; + } + } + Ok(committed) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn word(bytes: &mut [u8], at: usize, value: u32) { + bytes[at..at + 4].copy_from_slice(&value.to_be_bytes()); + } + + fn fixture(big: bool) -> ([u8; 18], [u8; 32 + 3 * 536]) { + let mut main = [0u8; 18]; + main[16..18].copy_from_slice(&512u16.to_be_bytes()); + let mut wal = [0; 32 + 3 * 536]; + word(&mut wal, 0, if big { 0x377f0683 } else { 0x377f0682 }); + word(&mut wal, 4, 3_007_000); + word(&mut wal, 8, 512); + word(&mut wal, 16, 17); + word(&mut wal, 20, 29); + let mut sum = wal_checksum(&wal[..24], big, (0, 0)); + word(&mut wal, 24, sum.0); + word(&mut wal, 28, sum.1); + for (i, frame) in wal[32..].as_chunks_mut::<536>().0.iter_mut().enumerate() { + word(frame, 0, i as u32 + 1); + word(frame, 4, [1, 3, 0][i]); + word(frame, 8, 17); + word(frame, 12, 29); + frame[24..].fill(i as u8 + 10); + sum = wal_checksum(&frame[..8], big, sum); + sum = wal_checksum(&frame[24..], big, sum); + word(frame, 16, sum.0); + word(frame, 20, sum.1); + } + (main, wal) + } + + #[test] + fn committed_prefix_stops_at_a_frame_checksum_mismatch() { + for big in [false, true] { + let (main, wal) = fixture(big); + let mut second_checksum_wrong = wal; + second_checksum_wrong[32 + 536 + 16] ^= 1; + assert_eq!(committed_prefix_len(&main, &second_checksum_wrong), Ok(32 + 536)); + + let mut first_checksum_wrong = wal; + first_checksum_wrong[32 + 16] ^= 1; + assert_eq!(committed_prefix_len(&main, &first_checksum_wrong), Ok(0)); + } + } + + #[test] + fn committed_prefix_stops_before_uncommitted_or_partial_frame() { + for big in [false, true] { + let (main, wal) = fixture(big); + let committed = 32 + 2 * 536; + assert_eq!(committed_prefix_len(&main, &wal), Ok(committed)); + assert_eq!(committed_prefix_len(&main, &wal[..committed + 23]), Ok(committed)); + assert_eq!(committed_prefix_len(&main, &wal[..32]), Ok(0)); + } + } +} diff --git a/crates/svg/src/path_data.rs b/crates/svg/src/path_data.rs index 16d2f3de5b..2b7ed3afc5 100644 --- a/crates/svg/src/path_data.rs +++ b/crates/svg/src/path_data.rs @@ -194,6 +194,15 @@ impl<'a> Tokenizer<'a> { } } +fn reflected_control(at: Point, previous: Point) -> Point { + let reflect = |coordinate: f64, prior: f64| { + let doubled = coordinate * 2.0; + // If both inputs are finite and doubling overflows, round only the final value. + if doubled.is_infinite() && coordinate.is_finite() && prior.is_finite() { coordinate.mul_add(2.0, -prior) } else { doubled - prior } + }; + Point::new(reflect(at.x, previous.x), reflect(at.y, previous.y)) +} + /// Split `d` into subpaths, resolving relative commands and S/T control reflections while /// raising quadratic (`Q`/`T`) segments to cubics. pub fn parse_path(d: &str) -> Result> { @@ -355,7 +364,7 @@ pub fn parse_path_with_quads(d: &str) -> Result> { cur = p; } b'S' => { - let c1 = prev_cubic.map_or(cur, |c2| cur * 2.0 - c2); + let c1 = prev_cubic.map_or(cur, |c2| reflected_control(cur, c2)); let (c2, p) = (point(args[0], args[1]), point(args[2], args[3])); segs.push(QuadSegment::Cubic(c1, c2, p)); prev_cubic = Some(c2); @@ -370,7 +379,7 @@ pub fn parse_path_with_quads(d: &str) -> Result> { cur = p; } b'T' => { - let reflect = prev_quad.map_or(cur, |q| cur * 2.0 - q); + let reflect = prev_quad.map_or(cur, |q| reflected_control(cur, q)); let p = point(args[0], args[1]); segs.push(QuadSegment::Quad(reflect, p)); prev_quad = Some(reflect); @@ -467,8 +476,13 @@ pub fn elliptical_params(p0: Point, p1: Point, rx: f64, ry: f64, phi: f64, large let angle = |ux: f64, uy: f64, vx: f64, vy: f64| { let dot = ux * vx + uy * vy; let det = ux * vy - uy * vx; - let denom = (ux.hypot(uy) * vx.hypot(vy)).max(f64::MIN_POSITIVE); - (dot / denom).clamp(-1.0, 1.0).acos().copysign(det) + if dot == 0.0 && det == 0.0 { + // Preserve the fallback for a degenerate vector. + std::f64::consts::FRAC_PI_2.copysign(det) + } else { + // The determinant retains tiny angles even when their cosine rounds to one. + det.atan2(dot) + } }; let (ux, uy) = ((x1 - cxp) / rx, (y1 - cyp) / ry); let (vx, vy) = ((-x1 - cxp) / rx, (-y1 - cyp) / ry); @@ -510,6 +524,21 @@ mod tests { ); } + #[test] + fn smooth_cubic_matches_explicit_control_when_doubling_would_overflow() { + let smooth = "M1e308 0 C1e308 1 1e308 2 1e308 3 S1e308 5 1e308 6"; + let explicit = "M1e308 0 C1e308 1 1e308 2 1e308 3 C1e308 4 1e308 5 1e308 6"; + assert_eq!(parse_path(smooth).unwrap(), parse_path(explicit).unwrap()); + } + + #[test] + fn smooth_quadratic_matches_explicit_control_when_doubling_would_overflow() { + let smooth = "M0 -1e308 Q1 -1e308 2 -1e308 T4 -1e308"; + let explicit = "M0 -1e308 Q1 -1e308 2 -1e308 Q3 -1e308 4 -1e308"; + assert_eq!(parse_path_with_quads(smooth).unwrap(), parse_path_with_quads(explicit).unwrap()); + assert_eq!(parse_path(smooth).unwrap(), parse_path(explicit).unwrap()); + } + #[test] fn close_resets_smooth_control_history() { // After Z, S must not reflect the preceding C's control (20,20) → (0,0). @@ -531,6 +560,28 @@ mod tests { assert!((sweep - std::f64::consts::PI).abs() < 1e-10); } + #[test] + fn short_elliptical_arcs_keep_their_sweep_and_endpoints() { + let p0 = Point::ZERO; + let p1 = Point::new(1e-9, 0.0); + let rx = 1.0; + let ry = 2.0; + let short = 2.0 * (p1.x / (2.0 * rx)).asin(); + for large in [false, true] { + for sweep in [false, true] { + let (center, start, delta) = elliptical_params(p0, p1, rx, ry, 0.0, large, sweep).unwrap(); + let magnitude = if large { std::f64::consts::TAU - short } else { short }; + let expected = if sweep { magnitude } else { -magnitude }; + assert!((delta - expected).abs() < 1e-11, "large={large}, sweep={sweep}: {delta} vs {expected}"); + let at = |angle: f64| Point::new(center.x + rx * angle.cos(), center.y + ry * angle.sin()); + for (actual, expected) in [(at(start), p0), (at(start + delta), p1)] { + let error = actual - expected; + assert!(error.x.hypot(error.y) < 1e-11, "{actual:?} vs {expected:?}"); + } + } + } + } + #[test] fn rejects_invalid_tokens_instead_of_returning_a_partial_path() { for input in ["@", "M0 0 L1 1@ L2 2", "M0 0 L1 1@", "M0 0 Z@", "M0 0 L1 1é", "M0 0 L1 1 +", "M0 0 L1 1 .", "M0 0 L1 1 2e+", "M0 0 L1 1 1e999"] diff --git a/crates/svg/src/sniff.rs b/crates/svg/src/sniff.rs index 95e238b895..db4a540afa 100644 --- a/crates/svg/src/sniff.rs +++ b/crates/svg/src/sniff.rs @@ -1,5 +1,7 @@ //! Recognising SVG data by its first bytes, for open, place and paste routes. +use quick_xml::{Error, Reader, errors::SyntaxError, events::Event, name::QName}; + /// How much of the data [`is_svg`] reads. const HEAD: usize = 4096; @@ -9,24 +11,53 @@ pub fn is_svgz(bytes: &[u8]) -> bool { bytes.starts_with(&[0x1f, 0x8b]) } -/// Does `bytes` look like an SVG document? Its first element is ` bool { let head = bytes.get(..bytes.len().min(HEAD)).unwrap_or(bytes); let text = String::from_utf8_lossy(head); - let t = text.trim_start_matches('\u{feff}').trim_start(); - if t.starts_with(" return tag.local_name().as_ref() == b"svg", + Ok(Event::Decl(_) | Event::PI(_) | Event::Comment(_) | Event::DocType(_)) => {} + Err(Error::Syntax( + SyntaxError::UnclosedTag | SyntaxError::UnclosedSingleQuotedAttributeValue | SyntaxError::UnclosedDoubleQuotedAttributeValue, + )) => { + // The prefix can end before the opening tag's closing bracket. + let name = text + .get(reader.error_position() as usize..) + .and_then(|tag| tag.strip_prefix('<')) + .and_then(|tag| tag.split([' ', '\t', '\r', '\n', '/', '>']).next()); + return name.is_some_and(|name| QName(name.as_bytes()).local_name().as_ref() == b"svg"); + } + _ => return false, + } } - (t.starts_with(" -->")); + assert!(!is_svg(b"")); + assert!(!is_svg(b"")); + assert!(!is_svg(b"")); + assert!(is_svg(b"]>")); + assert!(is_svg(b"")); + assert!(is_svg(b"")); @@ -52,6 +83,10 @@ mod tests { let mut late = format!("", " ".repeat(HEAD)).into_bytes(); late.extend_from_slice(b""); assert!(!is_svg(&late)); + for quote in ['\'', '"'] { + let clipped_tag = format!("", "1".repeat(HEAD)); + assert!(is_svg(clipped_tag.as_bytes())); + } // A multi-byte character cut at the end of the head is not a reason to refuse. let mut cut = b"".to_vec(); cut.extend("é".repeat(HEAD).as_bytes()); diff --git a/crates/tga/Cargo.toml b/crates/tga/Cargo.toml index 0c52fef98c..9eda48051a 100644 --- a/crates/tga/Cargo.toml +++ b/crates/tga/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-tga" -description = "Clean-room Truevision Targa (TGA) reader and run-length writer: true-colour, grayscale and colour-mapped pictures, any origin, packets that end with their scan line." +description = "Clean-room Truevision Targa (TGA) reader and writer: true-colour, grayscale and colour-mapped pictures, any origin, packets that end with their scan line." version.workspace = true edition.workspace = true license.workspace = true @@ -12,3 +12,6 @@ workspace = true [dependencies] thiserror = { workspace = true } + +[dev-dependencies] +image = { version = "0.25", default-features = false, features = ["tga"] } diff --git a/crates/tga/src/lib.rs b/crates/tga/src/lib.rs index cf968cf573..3ef2bd46c8 100644 --- a/crates/tga/src/lib.rs +++ b/crates/tga/src/lib.rs @@ -13,7 +13,7 @@ //! (types 10 and 11), rows stored bottom-up (the bottom-left origin every reader assumes, also //! those that ignore the origin bits), alpha bits in the descriptor and the TGA 2.0 footer. A //! packet never crosses a scan line: TGA 2.0 forbids it, and readers that decode a row at a time -//! misread files that do. +//! misread files that do. The top-left writer also supports a footerless, uncompressed compatibility stream. //! //! Input is treated as hostile: the picture size is capped by [`Limits`], and a run-length file //! must be long enough to hold the pixels its header declares before anything is allocated. @@ -430,6 +430,52 @@ fn unpack_rle(mut data: &[u8], pixels: usize, bpp: usize) -> Result> { Ok(out) } +/// Write packed 8-bit grayscale, RGB, or RGBA as a footerless, uncompressed top-left Targa. +/// +/// Rows and pixels arrive in display order. RGB and RGBA are stored as BGR and BGRA; +/// alpha bytes are copied verbatim. Dimensions, sample length, and the one-row conversion +/// buffer are checked before any output is written. The caller owns flushing the sink. +pub fn write_top_left_raw(mut out: impl std::io::Write, width: u32, height: u32, layout: Layout, data: &[u8]) -> Result<()> { + let (image_type, bits, alpha_bits) = match layout { + Layout::Gray => (3, 8, 0), + Layout::Rgb => (2, 24, 0), + Layout::Rgba => (2, 32, 8), + Layout::GrayAlpha => return Err(Error::Encode("footerless writer accepts grayscale, RGB or RGBA".into())), + }; + let (Ok(w), Ok(h)) = (u16::try_from(width), u16::try_from(height)) else { + return Err(Error::Encode(format!("dimensions exceed 65535x65535: {width}x{height}"))); + }; + let bpp = layout.channels(); + let row_len = usize::from(w) * bpp; + if w == 0 || h == 0 || row_len.checked_mul(usize::from(h)) != Some(data.len()) { + return Err(Error::Encode("invalid dimensions or buffer size mismatch".into())); + } + let mut row = Vec::new(); + if bpp >= 3 { + row.try_reserve_exact(row_len).map_err(|_| Error::Encode("row allocation failed".into()))?; + } + let mut header = [0u8; HEADER]; + header[2] = image_type; + header[12..14].copy_from_slice(&w.to_le_bytes()); + header[14..16].copy_from_slice(&h.to_le_bytes()); + header[16] = bits; + header[17] = 0x20 | alpha_bits; + let io_err = |err: std::io::Error| Error::Encode(err.to_string()); + out.write_all(&header).map_err(io_err)?; + if bpp == 1 { + return out.write_all(data).map_err(io_err); + } + for line in data.chunks_exact(row_len) { + row.clear(); + row.extend_from_slice(line); + for pixel in row.chunks_exact_mut(bpp) { + pixel.swap(0, 2); + } + out.write_all(&row).map_err(io_err)?; + } + Ok(()) +} + /// Encodes 8-bit pixels (`height` rows of `width × layout.channels()` bytes, top row first) as a /// run-length encoded Targa. pub fn encode(width: u32, height: u32, layout: Layout, data: &[u8]) -> Result> { diff --git a/crates/tga/src/tests.rs b/crates/tga/src/tests.rs index bec6b69726..12a27a980a 100644 --- a/crates/tga/src/tests.rs +++ b/crates/tga/src/tests.rs @@ -267,3 +267,48 @@ fn aggregate_decode_budget_counts_raw_and_palette_storage() { limits.max_decoded_bytes = 9; assert_eq!(decode(&file, &limits).unwrap().rgba, [255, 0, 0, 255]); } + +#[test] +fn raw_top_left_matches_previous_sequence_encoder_for_every_layout() -> std::result::Result<(), Box> { + use image::{ExtendedColorType, ImageEncoder, codecs::tga::TgaEncoder}; + + // Original generated samples, with distinguishing rows and non-opaque alpha. + for (layout, color, data) in [ + (Layout::Gray, ExtendedColorType::L8, &[9, 19, 40, 80][..]), + (Layout::Rgb, ExtendedColorType::Rgb8, &[3, 5, 8, 13, 21, 34, 55, 89, 144, 150, 190, 247][..]), + (Layout::Rgba, ExtendedColorType::Rgba8, &[3, 5, 8, 13, 21, 34, 55, 89, 144, 150, 190, 247, 17, 31, 127, 1][..]), + ] { + let mut legacy = Vec::new(); + TgaEncoder::new(&mut legacy).disable_rle().write_image(data, 2, 2, color)?; + let mut shared = Vec::new(); + write_top_left_raw(&mut shared, 2, 2, layout, data)?; + assert_eq!(shared, legacy, "{layout:?}"); + assert_eq!(shared.len(), 18 + data.len(), "no footer"); + } + Ok(()) +} + +#[test] +fn raw_top_left_rejects_bad_input_before_touching_the_sink() { + let mut output = Vec::new(); + for (w, h, layout, data) in [ + (0, 1, Layout::Gray, &[][..]), + (1, 0, Layout::Gray, &[][..]), + (u32::from(u16::MAX) + 1, 1, Layout::Rgb, &[][..]), + (u32::from(u16::MAX), u32::from(u16::MAX), Layout::Rgba, &[][..]), + (1, 1, Layout::GrayAlpha, &[1, 2][..]), + (1, 1, Layout::Rgba, &[0; 3][..]), + (1, 1, Layout::Rgba, &[0; 5][..]), + ] { + assert!(write_top_left_raw(&mut output, w, h, layout, data).is_err()); + } + assert!(output.is_empty()); +} + +#[test] +fn raw_top_left_reports_header_and_pixel_write_errors() { + for size in [17, 20] { + let mut bytes = [0; 20]; + assert!(matches!(write_top_left_raw(&mut bytes[..size], 1, 1, Layout::Rgb, &[9, 19, 40]), Err(Error::Encode(_)))); + } +} diff --git a/crates/tiff/Cargo.toml b/crates/tiff/Cargo.toml index 8b5c49b01e..42f71a571d 100644 --- a/crates/tiff/Cargo.toml +++ b/crates/tiff/Cargo.toml @@ -10,9 +10,14 @@ repository.workspace = true [lints] workspace = true +[features] +plain-rgba16 = ["dep:tiff"] + [dependencies] serde = { workspace = true } thiserror = { workspace = true } +tiff = { version = "0.11", default-features = false, optional = true } [dev-dependencies] +image = { version = "0.25", default-features = false, features = ["tiff"] } proptest = { workspace = true } diff --git a/crates/tiff/src/lib.rs b/crates/tiff/src/lib.rs index 5d6d78a213..1a618f39f2 100644 --- a/crates/tiff/src/lib.rs +++ b/crates/tiff/src/lib.rs @@ -28,6 +28,9 @@ pub mod classic; pub mod image; pub mod makernote; pub mod packbits; +/// Plain, uncompressed classic TIFF writing for existing RGBA16 callers. +#[cfg(feature = "plain-rgba16")] +pub mod plain; pub mod probe; mod reader; pub mod tags; diff --git a/crates/tiff/src/plain.rs b/crates/tiff/src/plain.rs new file mode 100644 index 0000000000..ffb664d4e3 --- /dev/null +++ b/crates/tiff/src/plain.rs @@ -0,0 +1,71 @@ +//! The uncompressed, metadata-free compatibility representation for RGBA16 stills. + +use std::io::Cursor; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("invalid dimensions or RGBA16 sample count")] + InvalidInput, + #[error(transparent)] + Tiff(#[from] tiff::TiffError), +} + +/// Encode straight, native-endian RGBA16 samples as an uncompressed classic TIFF with the +/// encoder's default strip layout and no extra tags such as ICC or ExtraSamples. +pub fn encode_rgba16(width: u32, height: u32, samples: &[u16]) -> Result, Error> { + let expected = u64::from(width).checked_mul(u64::from(height)).and_then(|n| n.checked_mul(4)).and_then(|n| usize::try_from(n).ok()); + if width == 0 || height == 0 || expected != Some(samples.len()) { + return Err(Error::InvalidInput); + } + let mut out = Cursor::new(Vec::new()); + tiff::encoder::TiffEncoder::new(&mut out)?.write_image::(width, height, samples)?; + Ok(out.into_inner()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plain_rgba16_keeps_uncompressed_legacy_strips_and_rgba_samples() { + // Self-generated straight RGBA data; tall enough for the encoder's second strip. + let (width, height) = (4, 31_253); + let samples: Vec = std::iter::repeat_n([0x12ab, 0xcdef, 0x3142, 0x8000], (width * height) as usize).flatten().collect(); + let bytes = encode_rgba16(width, height, &samples).unwrap(); + let mut reader = tiff::decoder::Decoder::new(Cursor::new(bytes)).unwrap(); + use tiff::tags::Tag; + assert_eq!(reader.dimensions().unwrap(), (width, height)); + assert_eq!(reader.get_tag_u32(Tag::Compression).unwrap(), 1); + assert_eq!(reader.get_tag_u32_vec(Tag::StripByteCounts).unwrap(), [1_000_000, 96]); + assert!(reader.find_tag(Tag::ExtraSamples).unwrap().is_none()); + assert!(reader.find_tag(Tag::IccProfile).unwrap().is_none()); + let tiff::decoder::DecodingResult::U16(decoded) = reader.read_image().unwrap() else { + panic!("expected native 16-bit samples"); + }; + assert_eq!(decoded, samples); + } + + #[test] + fn plain_rgba16_rejects_malformed_sample_count_and_dimensions() { + assert!(encode_rgba16(0, 1, &[]).is_err()); + assert!(encode_rgba16(1, 1, &[0; 3]).is_err()); + assert!(encode_rgba16(1, 1, &[0; 5]).is_err()); + assert!(encode_rgba16(u32::MAX, u32::MAX, &[]).is_err()); + } + + #[test] + fn plain_rgba16_matches_legacy_writer_bytes() -> Result<(), Box> { + use image::{ExtendedColorType, ImageEncoder, codecs::tiff::TiffEncoder}; + + // Original, generated pixels with distinct channels and alpha. Tall and wide cases + // both exceed one strip and stress the compatibility encoder's strip decisions. + for (w, h) in [(1, 1), (5, 3), (4, 31_253), (5_123, 25)] { + let samples: Vec<_> = (0..w * h * 4).map(|i: u32| i.wrapping_mul(7919).wrapping_add(0x1234) as u16).collect(); + let mut legacy = Cursor::new(Vec::new()); + let packed: Vec = samples.iter().flat_map(|v| v.to_ne_bytes()).collect(); + TiffEncoder::new(&mut legacy).write_image(&packed, w, h, ExtendedColorType::Rgba16)?; + assert!(encode_rgba16(w, h, &samples)? == legacy.into_inner(), "{w}×{h}: TIFF bytes changed"); + } + Ok(()) + } +} diff --git a/crates/usd/src/scene/usda.rs b/crates/usd/src/scene/usda.rs index 40637ea049..be0ef9d0da 100644 --- a/crates/usd/src/scene/usda.rs +++ b/crates/usd/src/scene/usda.rs @@ -346,8 +346,19 @@ impl Parser<'_, '_> { if !self.lx.eat(b'=')? { continue; } + let scalar_external = matches!(key.as_str(), "references" | "payload") && matches!(self.lx.peek()?, Tok::Asset(_)); let mut acc = Acc::default(); self.value(&mut acc, 0)?; + if scalar_external { + // The target and layer offset belong to this external arc, not the next metadata + // entry. External targets must not become references to same-named local prims. + if matches!(self.lx.peek()?, Tok::Path(_)) { + self.value(&mut acc, 0)?; + } + if self.lx.eat(b'(')? { + self.skip_block(b'(', b')')?; + } + } if keep && KEPT_METADATA.contains(&key.as_str()) { out.push((key, acc)); } diff --git a/crates/usd/tests/scene.rs b/crates/usd/tests/scene.rs index d8fa22c7fe..0d944b3223 100644 --- a/crates/usd/tests/scene.rs +++ b/crates/usd/tests/scene.rs @@ -73,6 +73,41 @@ def Xform "World" } "#; +#[test] +fn scalar_external_arcs_keep_following_metadata_and_prims() { + // Original generated layers: external targets must never resolve to the local class. + for key in ["references", "payload"] { + for arc in [ + "@external.usda@", + "@external.usda@", + "@external.usda@ (offset = 10; scale = 2)", + "@external.usda@ (offset = 10; scale = 2)", + ] { + let source = format!( + r#"#usda 1.0 +class Xform "LocalTemplate" {{}} +def Xform "External" ( + prepend {key} = {arc} + active = false +) {{}} +def Xform "Mixed" ( + prepend {key} = [@external.usda@, ] +) {{}} +def Xform "Later" {{}} +"# + ); + let layer = read_layer(source.as_bytes()).unwrap_or_else(|error| panic!("{key} = {arc}: {error}")); + let external = layer.prims.iter().find(|p| p.path == "/External").unwrap(); + assert!(external.references.is_empty(), "{key} = {arc}"); + assert_eq!(external.active, Some(false), "{key} = {arc}"); + let mixed = layer.prims.iter().find(|p| p.path == "/Mixed").unwrap(); + assert_eq!(mixed.references, ["/LocalTemplate"], "{key} = {arc}"); + assert!(layer.prims.iter().any(|p| p.path == "/Later"), "{key} = {arc}"); + assert!(layer.warnings.iter().any(|w| w.contains("external references and payloads")), "{key} = {arc}"); + } + } +} + #[test] fn usda_corpus_overlays_references_coordinates_transforms_and_meshes() { let layer = read_layer(CORPUS_USDA.as_bytes()).unwrap(); diff --git a/crates/video/src/apv/mod.rs b/crates/video/src/apv/mod.rs index a13e5e0f5b..5a12cc4163 100644 --- a/crates/video/src/apv/mod.rs +++ b/crates/video/src/apv/mod.rs @@ -19,6 +19,7 @@ pub mod decode; #[cfg(feature = "apv-encode")] pub mod encode; pub mod header; +mod raw; pub mod tables; #[cfg(feature = "apv-decode")] @@ -26,6 +27,7 @@ pub use decode::{DecodeOptions, decode_frame, decode_frame_into, decode_frame_wi #[cfg(feature = "apv-encode")] pub use encode::{Encoder, EncoderConfig}; pub use header::{AU_SIGNATURE, FrameHeader, split_raw_bitstream, unwrap_au}; +pub use raw::{RawAccessUnit, raw_access_units, sniff_raw_bitstream}; /// APV codec errors. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] diff --git a/crates/video/src/apv/raw.rs b/crates/video/src/apv/raw.rs new file mode 100644 index 0000000000..950cd3eddb --- /dev/null +++ b/crates/video/src/apv/raw.rs @@ -0,0 +1,126 @@ +//! Seekable APV access-unit framing from [RFC 9924 Appendix A]. +//! +//! [RFC 9924 Appendix A]: https://www.rfc-editor.org/rfc/rfc9924.html#appendix-A + +use craft_media::ByteSource; + +use super::header::AU_SIGNATURE; + +/// A complete access unit's byte range, excluding any size prefix. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct RawAccessUnit { + /// Absolute byte offset of the access-unit signature. + pub offset: u64, + /// Access-unit size in bytes. + pub size: u32, +} + +fn prefixed_size(head: &[u8]) -> Option { + let head = head.get(..8)?; + if head[4..] != AU_SIGNATURE { + return None; + } + Some(u32::from_be_bytes(head[..4].try_into().ok()?)) +} + +/// Whether a prefix looks like standalone APV. A bare access-unit signature +/// also matches, for files that store a single unit with no length prefix. +pub fn sniff_raw_bitstream(head: &[u8]) -> bool { + head.starts_with(&AU_SIGNATURE) || prefixed_size(head).is_some_and(|size| size >= 8) +} + +/// Walk the complete units of a standalone APV source without reading payloads. +/// At each boundary this reads only the size prefix and signature. For an +/// unprefixed single unit, it uses the whole source as that unit. +/// +/// A short, invalid or unreadable header ends iteration. This lets playback +/// keep the readable prefix of a truncated file without resynchronizing or +/// interpreting payload bytes as framing. The iterator allocates no index. +pub fn raw_access_units(source: &(impl ByteSource + ?Sized)) -> impl Iterator + '_ { + let len = source.len(); + let mut next = Some(0u64); + std::iter::from_fn(move || { + let start = next.take()?; + let mut head = [0; 8]; + if len.checked_sub(start)? < head.len() as u64 { + return None; + } + source.read_at(start, &mut head).ok()?; + + if let Some(size) = prefixed_size(&head) { + if !(8..u32::MAX).contains(&size) { + return None; + } + let offset = start.checked_add(4)?; + next = Some(offset.checked_add(u64::from(size)).filter(|&end| end <= len)?); + return Some(RawAccessUnit { offset, size }); + } + if start == 0 && head.starts_with(&AU_SIGNATURE) { + return Some(RawAccessUnit { offset: 0, size: u32::try_from(len).ok()? }); + } + None + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + use std::io; + + #[test] + fn seekable_index_reads_only_each_outside_header() { + struct Headers(RefCell>); + + impl ByteSource for Headers { + fn len(&self) -> u64 { + 124 + } + + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + self.0.borrow_mut().push(offset); + let head = match offset { + 0 => b"\0\0\0\x6caPv1", + 112 => b"\0\0\0\x08aPv1", + _ => return Err(io::ErrorKind::UnexpectedEof.into()), + }; + assert_eq!(buf.len(), head.len()); + buf.copy_from_slice(head); + Ok(()) + } + } + + let source = Headers(RefCell::new(Vec::new())); + let mut units = raw_access_units(&source); + assert!(source.0.borrow().is_empty(), "creating an iterator reads no bytes"); + assert_eq!(units.next(), Some(RawAccessUnit { offset: 4, size: 108 })); + assert_eq!(source.0.borrow().as_slice(), &[0]); + assert_eq!(units.next(), Some(RawAccessUnit { offset: 116, size: 8 })); + assert_eq!(units.next(), None); + assert_eq!(source.0.borrow().as_slice(), &[0, 112]); + } + + #[test] + fn complete_prefix_survives_truncation_and_invalid_following_lengths() { + let valid = b"\0\0\0\x08aPv1abcd"; + for tail in [b"junk".as_slice(), b"\0\0\0\x09aPv1xyz", b"\xff\xff\xff\xffaPv1xyz", b"\0\0\0\x07aPv1xyz"] { + let bytes = [valid.as_slice(), tail].concat(); + let mut units = raw_access_units(&bytes); + assert_eq!(units.next(), Some(RawAccessUnit { offset: 4, size: 8 })); + assert_eq!(units.next(), None); + assert_eq!(units.next(), None); + } + } + + #[test] + fn bare_unit_and_prefixed_header_detection_match_the_playback_boundary() { + assert!(sniff_raw_bitstream(b"aPv1")); + assert!(sniff_raw_bitstream(b"\0\0\0\x08aPv1")); + assert!(!sniff_raw_bitstream(b"\0\0\0\x07aPv1")); + assert!(!sniff_raw_bitstream(b"\0\0\0\x08apv1")); + + assert_eq!(raw_access_units(b"aPv1data".as_slice()).next(), Some(RawAccessUnit { offset: 0, size: 8 })); + assert_eq!(raw_access_units(b"aPv1".as_slice()).next(), None); + assert_eq!(raw_access_units(b"\0\0\0\x08aPv1".as_slice()).next(), None); + } +} diff --git a/crates/video/src/mjpeg/mod.rs b/crates/video/src/mjpeg/mod.rs index acd073f6c8..b90f711593 100644 --- a/crates/video/src/mjpeg/mod.rs +++ b/crates/video/src/mjpeg/mod.rs @@ -97,6 +97,10 @@ impl Decoder { self } + pub(crate) fn limit_allocation(&mut self, max_bytes: u64) { + self.limits.max_alloc = self.limits.max_alloc.min(max_bytes); + } + /// Decode one packet. pub fn decode(&self, packet: &[u8]) -> Result