Skip to content

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

raw: fit non-DNG colour to the camera's embedded JPEG (#2135)

Gert Pellin - GPE303b7849e8ae
diff --git a/crates/io/examples/rawlook.rs b/crates/io/examples/rawlook.rs
new file mode 100644
index 000000000..dfec1a6ef
--- /dev/null
+++ b/crates/io/examples/rawlook.rs
@@ -0,0 +1,237 @@
+//! Measure the camera-JPEG colour fit on real raw files: times the fit, compares the
+//! neutral fallback and the fitted look with the camera's embedded JPEG (mean CIE76 ΔE in
+//! sRGB-clipped Lab D50, measured on the full develop output against the largest preview,
+//! independently of the fit's own grid) and can write 1200-px sRGB PNGs of both renderings
+//! and of the JPEG.
+//!
+//! ```sh
+//! cargo run --release -p photocraft-io --example rawlook -- [--png DIR] FILE...
+//! cargo run --release -p photocraft-io --example rawlook -- --synthetic # time a 24 MP synthetic NEF
+//! ```
+
+use std::time::Instant;
+
+use photocraft_cms::{Builtin, Intent, Transform};
+use photocraft_codecs::{self as codecs, ChannelLayout, EncodeOptions, Format, Image};
+use photocraft_raw::{DevelopOptions, develop_sensor};
+
+/// Box-downsamples interleaved RGB to at most `edge` pixels on the long side.
+fn shrink(px: &[f32], w: usize, h: usize, edge: usize) -> (Vec<f32>, usize, usize) {
+ let f = w.max(h).div_ceil(edge).max(1);
+ let (ow, oh) = (w / f, h / f);
+ let mut out = vec![0.0f32; ow * oh * 3];
+ for y in 0..oh * f {
+ for x in 0..ow * f {
+ let (i, o) = ((y * w + x) * 3, ((y / f) * ow + x / f) * 3);
+ for k in 0..3 {
+ out[o + k] += px[i + k];
+ }
+ }
+ }
+ let n = (f * f) as f32;
+ out.iter_mut().for_each(|v| *v /= n);
+ (out, ow, oh)
+}
+
+/// Resamples to exactly `tw × th` by box averaging over the matching source area.
+fn resample(px: &[f32], w: usize, h: usize, tw: usize, th: usize) -> Vec<f32> {
+ let mut out = vec![0.0f32; tw * th * 3];
+ for ty in 0..th {
+ let (y0, y1) = (ty * h / th, ((ty + 1) * h / th).max(ty * h / th + 1));
+ for tx in 0..tw {
+ let (x0, x1) = (tx * w / tw, ((tx + 1) * w / tw).max(tx * w / tw + 1));
+ let mut s = [0.0f32; 3];
+ for y in y0..y1 {
+ for x in x0..x1 {
+ for k in 0..3 {
+ s[k] += px[(y * w + x) * 3 + k];
+ }
+ }
+ }
+ let n = ((y1 - y0) * (x1 - x0)) as f32;
+ for k in 0..3 {
+ out[(ty * tw + tx) * 3 + k] = s[k] / n;
+ }
+ }
+ }
+ out
+}
+
+fn lin(v: f32) -> f64 {
+ let v = f64::from(v);
+ if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
+}
+
+/// Lab (D50) of display sRGB 0..1 (Bradford-adapted sRGB → XYZ D50).
+fn lab(p: &[f32]) -> [f64; 3] {
+ let m = [[0.4360747, 0.3850649, 0.1430804], [0.2225045, 0.7168786, 0.0606169], [0.0139322, 0.0971045, 0.7141733]];
+ let l = [lin(p[0]), lin(p[1]), lin(p[2])];
+ let xyz: [f64; 3] = std::array::from_fn(|i| m[i][0] * l[0] + m[i][1] * l[1] + m[i][2] * l[2]);
+ let w = [0.9642, 1.0, 0.8249];
+ let f = |t: f64| if t > 216.0 / 24389.0 { t.cbrt() } else { (24389.0 / 27.0 * t + 16.0) / 116.0 };
+ let [fx, fy, fz] = [0, 1, 2].map(|k| f(xyz[k] / w[k]));
+ [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)]
+}
+
+fn mean_de(a: &[f32], b: &[f32]) -> f64 {
+ let n = a.len() / 3;
+ a.as_chunks::<3>()
+ .0
+ .iter()
+ .zip(b.as_chunks::<3>().0)
+ .map(|(p, q)| {
+ let (x, y) = (lab(p), lab(q));
+ ((x[0] - y[0]).powi(2) + (x[1] - y[1]).powi(2) + (x[2] - y[2]).powi(2)).sqrt()
+ })
+ .sum::<f64>()
+ / n as f64
+}
+
+/// Developed ProPhoto 16-bit → display sRGB 0..1.
+fn to_srgb(rgb: &[u16]) -> Vec<f32> {
+ let t = Transform::new(Builtin::ProPhotoCompat.profile(), Builtin::Srgb.profile(), Intent::RelativeColorimetric, false).expect("transform");
+ let mut out = vec![0u16; rgb.len()];
+ t.convert_u16(rgb, 3, &mut out, 3, false);
+ out.iter().map(|v| f32::from(*v) / 65535.0).collect()
+}
+
+fn write_png(path: &str, px: &[f32], w: usize, h: usize) {
+ let (s, sw, sh) = shrink(px, w, h, 1200);
+ let bytes: Vec<u8> = s.iter().map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8).collect();
+ let img = Image::from_u8(sw as u32, sh as u32, ChannelLayout::Rgb, bytes).expect("image");
+ std::fs::write(path, codecs::encode(&img, Format::Png, &EncodeOptions::default()).expect("png")).expect("write");
+}
+
+/// Times the fit on a synthetic 6034×4012 NEF-like raw with a 1632×1086 camera-style preview.
+fn synthetic() {
+ use photocraft_raw::testgen::{TiffBuilder, Val, mosaic};
+ let (w, h) = (6034usize, 4012usize);
+ let colours: Vec<[f32; 3]> = (0..96u32).map(|i| [0.1 + 0.05 * (i % 9) as f32, 0.1 + 0.04 * (i % 11) as f32, 0.1 + 0.06 * (i % 7) as f32]).collect();
+ let at = |x: usize, y: usize| {
+ let ramp = 0.15 + 0.85 * ((x * 12) % w) as f32 / w as f32;
+ colours[(y * 8 / h) * 12 + x * 12 / w].map(|v| v * ramp)
+ };
+ let cam: Vec<[f32; 3]> = (0..w * h).map(|i| at(i % w, i / w)).collect();
+ let data = mosaic(&cam, w, [0, 1, 1, 2], 0, 4095);
+ drop(cam);
+ let (pw, ph) = (1632usize, 1086usize);
+ let px: Vec<u8> = (0..pw * ph)
+ .flat_map(|i| {
+ let c = at((i % pw) * w / pw, (i / pw) * h / ph);
+ c.map(|v| {
+ let v = (1.6 * v / (1.0 + 0.6 * v)).clamp(0.0, 1.0);
+ ((if v <= 0.0031308 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }) * 255.0).round() as u8
+ })
+ })
+ .collect();
+ let jpeg =
+ codecs::encode(&Image::from_u8(pw as u32, ph as u32, ChannelLayout::Rgb, px).expect("image"), Format::Jpeg, &EncodeOptions::default()).expect("jpeg");
+ let mut t = TiffBuilder::default();
+ let strip = t.blob(data.iter().flat_map(|v| v.to_le_bytes()).collect());
+ let raw = t.ifd(vec![
+ (256, Val::Long(vec![w as u32])),
+ (257, Val::Long(vec![h as u32])),
+ (258, Val::Short(vec![12])),
+ (259, Val::Short(vec![1])),
+ (262, Val::Short(vec![32803])),
+ (273, Val::Blobs(vec![strip])),
+ (277, Val::Short(vec![1])),
+ (278, Val::Long(vec![h as u32])),
+ (279, Val::Long(vec![(data.len() * 2) as u32])),
+ (33421, Val::Short(vec![2, 2])),
+ (33422, Val::Byte(vec![0, 1, 1, 2])),
+ ]);
+ let len = jpeg.len() as u32;
+ let jb = t.blob(jpeg);
+ let ifd0 =
+ t.ifd(vec![(271, Val::Ascii("NIKON CORPORATION".into())), (330, Val::Ifds(vec![raw])), (513, Val::Blobs(vec![jb])), (514, Val::Long(vec![len]))]);
+ t.chain = vec![ifd0];
+ let bytes = t.build();
+ let opts = DevelopOptions::default();
+ let sensor = photocraft_raw::decode(&bytes, &opts.limits).expect("decode");
+ let _ = photocraft_io::raw::fit_preview_look(&bytes, &sensor, &opts);
+ let mut times: Vec<f64> = (0..7)
+ .map(|_| {
+ let t = Instant::now();
+ let r = photocraft_io::raw::fit_preview_look(&bytes, &sensor, &opts);
+ assert!(r.is_ok(), "{r:?}");
+ t.elapsed().as_secs_f64() * 1e3
+ })
+ .collect();
+ times.sort_by(f64::total_cmp);
+ let p = photocraft_raw::embedded_preview(&bytes).expect("preview");
+ let t = Instant::now();
+ let img = codecs::decode_as(Format::Jpeg, p.jpeg).expect("jpeg");
+ let dec = t.elapsed().as_secs_f64() * 1e3;
+ let r = photocraft_raw::Reference { width: img.width(), height: img.height(), rgb: img.data() };
+ let t = Instant::now();
+ let _ = photocraft_raw::fit_look(&sensor, &opts, &r);
+ println!(" preview decode {dec:.1} ms, fit_look {:.1} ms", t.elapsed().as_secs_f64() * 1e3);
+ println!("synthetic {w}x{h}: preview decode + fit median {:.1} ms (min {:.1}, max {:.1})", times[3], times[0], times[6]);
+}
+
+fn main() {
+ let mut args = std::env::args().skip(1);
+ let mut png: Option<String> = None;
+ let mut files = Vec::new();
+ while let Some(a) = args.next() {
+ match a.as_str() {
+ "--png" => png = args.next(),
+ "--synthetic" => {
+ synthetic();
+ return;
+ }
+ _ => files.push(a),
+ }
+ }
+ println!("| file | fit | ΔE grid fallback → fit | ΔE full fallback → fit | fit ms | develop ms |");
+ println!("|---|---|---|---|---|---|");
+ for f in files {
+ let bytes = std::fs::read(&f).expect("read");
+ let name = std::path::Path::new(&f).file_stem().and_then(|s| s.to_str()).unwrap_or("raw").to_string();
+ let opts = DevelopOptions::default();
+ let sensor = photocraft_raw::decode(&bytes, &opts.limits).expect("decode");
+ // Warm up (thread pool), then time the fit.
+ let _ = photocraft_io::raw::fit_preview_look(&bytes, &sensor, &opts);
+ let t = Instant::now();
+ let fit = photocraft_io::raw::fit_preview_look(&bytes, &sensor, &opts);
+ let fit_ms = t.elapsed().as_secs_f64() * 1e3;
+ let before = develop_sensor(&sensor, &opts).expect("develop");
+ let t = Instant::now();
+ let after = match &fit {
+ Ok(look) => Some(develop_sensor(&sensor, &DevelopOptions { camera_look: Some(look.clone()), ..opts.clone() }).expect("develop")),
+ Err(_) => None,
+ };
+ let dev_ms = t.elapsed().as_secs_f64() * 1e3;
+ // Independent check against the largest preview.
+ let p = photocraft_raw::embedded_preview(&bytes).expect("preview");
+ let raw_jpeg = codecs::decode_as_with(Format::Jpeg, p.jpeg, &codecs::DecodeOptions { keep_orientation: true, ..Default::default() }).expect("jpeg");
+ let own = raw_jpeg.meta.exif.as_deref().map_or(1, codecs::exif_orientation);
+ let o = if own != 1 { own } else { codecs::exif_orientation(&bytes) };
+ let jpeg = raw_jpeg.oriented(o).expect("orient").converted(ChannelLayout::Rgb, photocraft_codecs::SampleType::U8).into_owned();
+ let (jw, jh) = (jpeg.width() as usize, jpeg.height() as usize);
+ let jpx: Vec<f32> = jpeg.data().iter().map(|v| f32::from(*v) / 255.0).collect();
+ let (dw, dh) = (before.width as usize, before.height as usize);
+ let (gw, gh) = (300, (300 * dh).div_ceil(dw));
+ let jref = resample(&jpx, jw, jh, gw, gh);
+ let b = to_srgb(&before.rgb);
+ let de_before = mean_de(&resample(&b, dw, dh, gw, gh), &jref);
+ let a = after.as_ref().map(|d| to_srgb(&d.rgb));
+ let de_after = a.as_ref().map(|a| mean_de(&resample(a, dw, dh, gw, gh), &jref));
+ let (verdict, grid) = match &fit {
+ Ok(l) => ("used".to_string(), format!("{:.1} → {:.1}", l.delta_e_fallback, l.delta_e)),
+ Err(e) => (format!("rejected: {e}"), "-".into()),
+ };
+ println!("| {name} | {verdict} | {grid} | {de_before:.1} → {} | {fit_ms:.0} | {dev_ms:.0} |", de_after.map_or("-".into(), |v| format!("{v:.1}")));
+ if let Ok(l) = &fit {
+ eprintln!("{name}: to_xyz {:?}\n tone {:?}", l.to_xyz, l.tone.as_ref().map(|t| t.knots()));
+ }
+ if let Some(dir) = &png {
+ write_png(&format!("{dir}/{name}-before.png"), &b, dw, dh);
+ if let Some(a) = &a {
+ write_png(&format!("{dir}/{name}-after.png"), a, dw, dh);
+ }
+ write_png(&format!("{dir}/{name}-camera-jpeg.png"), &jpx, jw, jh);
+ }
+ }
+}
diff --git a/crates/io/src/raw.rs b/crates/io/src/raw.rs
index dc3299c51..bf7f0892e 100644
--- a/crates/io/src/raw.rs
+++ b/crates/io/src/raw.rs
@@ -2,11 +2,19 @@
//! in ProPhoto RGB (the embedded profile is the built-in ProPhoto-compatible
//! profile), or, for raw variants not decoded yet, the camera's embedded
//! JPEG preview with a warning.
-
+//!
+//! Files without colour calibration (everything but DNG) get their colour
+//! from the camera's own embedded JPEG: `photocraft-raw` cannot decode JPEG,
+//! so the preview is decoded here and handed to [`photocraft_raw::fit_look`],
+//! which fits a matrix and tone curve and keeps the neutral fallback when the
+//! fit is not clearly better.
+
+use std::borrow::Cow;
use std::sync::Arc;
-use photocraft_codecs::{self as codecs, ChannelLayout, Format, Image};
-use photocraft_raw::{DevelopOptions, Limits, RawError, WhiteBalance};
+use photocraft_cms::{Builtin, Intent, Profile, Transform};
+use photocraft_codecs::{self as codecs, ChannelLayout, Format, Image, SampleType};
+use photocraft_raw::{CameraLook, DevelopOptions, Limits, RawError, Reference, Sensor, WhiteBalance};
use crate::flat::image_to_document;
use crate::{ImportResult, IoError};
@@ -115,14 +123,64 @@ pub fn import_raw(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {
import_raw_with(name, bytes, &DevelopOptions { limits: limits(), ..Default::default() })
}
+/// Smallest preview long edge preferred for the colour fit (a smaller preview decodes faster;
+/// the fit grid is at most `PROXY_EDGE` cells and wants about two pixels per cell).
+const FIT_PREVIEW_EDGE: u32 = 2 * photocraft_raw::PROXY_EDGE as u32;
+
+/// Fits the colour of a decoded raw to the camera's embedded JPEG (see
+/// [`photocraft_raw::fit_look`]): picks the smallest preview at least
+/// `FIT_PREVIEW_EDGE` pixels long (else the largest), decodes it, turns it upright and
+/// converts it to sRGB when it carries another ICC profile. `Err` says why there is no fit.
+pub fn fit_preview_look(raw: &[u8], sensor: &Sensor, opts: &DevelopOptions) -> Result<CameraLook, String> {
+ let previews = photocraft_raw::embedded_previews(raw);
+ let long = |p: &photocraft_raw::Preview| p.width.max(p.height);
+ let pick = previews
+ .iter()
+ .filter(|p| long(p) >= FIT_PREVIEW_EDGE)
+ .min_by_key(|p| long(p))
+ .or_else(|| previews.iter().max_by_key(|p| long(p)))
+ .ok_or("no embedded JPEG preview")?;
+ let img = upright_preview(raw, pick.jpeg).map_err(|e| format!("the embedded preview does not decode: {e}"))?;
+ if img.layout() != ChannelLayout::Rgb || img.sample_type() != SampleType::U8 {
+ return Err("the embedded preview is not 8-bit RGB".into());
+ }
+ let (w, h) = img.dimensions();
+ let mut rgb: Cow<[u8]> = Cow::Borrowed(img.data());
+ if let Some(icc) = img.icc.as_deref() {
+ let srgb = Builtin::Srgb.profile();
+ let src = Profile::parse(icc).map_err(|e| format!("the preview's ICC profile does not parse: {e}"))?;
+ if !src.same_colors(srgb) {
+ let t = Transform::new(&src, srgb, Intent::RelativeColorimetric, false).map_err(|e| e.to_string())?;
+ let mut out = vec![0u8; rgb.len()];
+ t.convert_u8(&rgb, 3, &mut out, 3, false);
+ rgb = Cow::Owned(out);
+ }
+ }
+ photocraft_raw::fit_look(sensor, opts, &Reference { width: w, height: h, rgb: &rgb }).map_err(|e| e.to_string())
+}
+
+/// Decodes and develops; a file without colour calibration gets a look fitted to its preview.
+fn develop_fitted(bytes: &[u8], opts: &DevelopOptions) -> Result<photocraft_raw::Developed, RawError> {
+ let sensor = photocraft_raw::decode(bytes, &opts.limits)?;
+ let mut opts = Cow::Borrowed(opts);
+ if opts.camera_look.is_none()
+ && sensor.color.calibrations.is_empty()
+ && let Ok(look) = fit_preview_look(bytes, &sensor, &opts)
+ {
+ opts.to_mut().camera_look = Some(look);
+ }
+ photocraft_raw::develop_sensor(&sensor, &opts)
+}
+
/// In the import note of a raw developed from its sensor data with the default settings (not of
/// a preview fallback): what the open-time Camera Raw dialog looks for.
pub const DEVELOPED_NOTE: &str = "developed with default settings";
-/// Develops a raw file with explicit settings.
+/// Develops a raw file with explicit settings. Without `opts.camera_look`, a file without
+/// colour calibration gets one fitted to its embedded JPEG when that clearly helps.
pub fn import_raw_with(name: &str, bytes: &[u8], opts: &DevelopOptions) -> Result<ImportResult, IoError> {
let format = photocraft_raw::identify(bytes).map(|f| f.name()).unwrap_or("camera raw");
- match photocraft_raw::develop(bytes, opts) {
+ match develop_fitted(bytes, opts) {
Ok(dev) => {
let summary = format!("{DEVELOPED_NOTE} ({} demosaic, as-shot white balance)", opts.demosaic.id());
developed_document(name, format, dev, &summary)
diff --git a/crates/io/tests/raw.rs b/crates/io/tests/raw.rs
index afb2ff382..eb449a90a 100644
--- a/crates/io/tests/raw.rs
+++ b/crates/io/tests/raw.rs
@@ -89,3 +89,127 @@ fn truncated_raws_do_not_panic() {
let _ = import("x.nef", &b[..n]);
}
}
+
+/// Camera-space patches, each with a tonal ramp.
+fn patches(w: usize, h: usize) -> Vec<[f32; 3]> {
+ let mut seed = 99u32;
+ let mut rnd = || {
+ seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
+ (seed >> 8) as f32 / (1u32 << 24) as f32
+ };
+ let colours: Vec<[f32; 3]> = (0..96).map(|_| [0.12 + 0.5 * rnd(), 0.12 + 0.5 * rnd(), 0.12 + 0.5 * rnd()]).collect();
+ (0..w * h)
+ .map(|i| {
+ let (x, y) = (i % w, i / w);
+ let ramp = 0.15 + 0.85 * ((x * 12) % w) as f32 / w as f32;
+ colours[(y * 8 / h) * 12 + x * 12 / w].map(|v| v * ramp)
+ })
+ .collect()
+}
+
+/// A "camera JPEG" of `cam`: more saturated than sRGB primaries, with a brightening curve.
+fn camera_rendering(cam: &[[f32; 3]], w: usize, h: usize) -> Vec<u8> {
+ let k = [[1.3f32, -0.2, -0.1], [-0.15, 1.25, -0.1], [0.0, -0.25, 1.25]];
+ let px: Vec<u8> = cam
+ .iter()
+ .flat_map(|c| {
+ (0..3).map(move |i| {
+ let v = (k[i][0] * c[0] + k[i][1] * c[1] + k[i][2] * c[2]).clamp(0.0, 1.0);
+ let v = 1.6 * v / (1.0 + 0.6 * v);
+ let e = if v <= 0.0031308 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 };
+ (e * 255.0).round() as u8
+ })
+ })
+ .collect();
+ jpeg(Image::from_u8(w as u32, h as u32, ChannelLayout::Rgb, px).unwrap())
+}
+
+fn jpeg(img: Image) -> Vec<u8> {
+ photocraft_codecs::encode(&img, Format::Jpeg, &EncodeOptions { jpeg_quality: 95, ..Default::default() }).unwrap()
+}
+
+/// An uncompressed NEF-like raw of `cam` with an optional JPEG preview in IFD0.
+fn nef_uncompressed(cam: &[[f32; 3]], w: usize, h: usize, preview: Option<Vec<u8>>) -> Vec<u8> {
+ let data = mosaic(cam, w, [0, 1, 1, 2], 0, 4095);
+ let mut t = TiffBuilder::default();
+ let strip = t.blob(data.iter().flat_map(|v| v.to_le_bytes()).collect());
+ let raw = t.ifd(vec![
+ (254, Val::Long(vec![0])),
+ (256, Val::Long(vec![w as u32])),
+ (257, Val::Long(vec![h as u32])),
+ (258, Val::Short(vec![12])),
+ (259, Val::Short(vec![1])),
+ (262, Val::Short(vec![32803])),
+ (273, Val::Blobs(vec![strip])),
+ (277, Val::Short(vec![1])),
+ (278, Val::Long(vec![h as u32])),
+ (279, Val::Long(vec![(data.len() * 2) as u32])),
+ (33421, Val::Short(vec![2, 2])),
+ (33422, Val::Byte(vec![0, 1, 1, 2])),
+ ]);
+ let mut ifd0 = vec![(271, Val::Ascii("NIKON CORPORATION".into())), (330, Val::Ifds(vec![raw]))];
+ if let Some(j) = preview {
+ let len = j.len() as u32;
+ let b = t.blob(j);
+ ifd0.extend([(513, Val::Blobs(vec![b])), (514, Val::Long(vec![len]))]);
+ }
+ let ifd0 = t.ifd(ifd0);
+ t.chain = vec![ifd0];
+ t.build()
+}
+
+fn fitted(warnings: &[String]) -> bool {
+ warnings.iter().any(|w| w.contains("fitted to the camera's embedded JPEG"))
+}
+
+fn fallback(warnings: &[String]) -> bool {
+ warnings.iter().any(|w| w.contains("sRGB primaries"))
+}
+
+#[test]
+fn uncalibrated_raw_takes_its_colour_from_the_camera_jpeg() {
+ let (w, h) = (480, 320);
+ let cam = patches(w, h);
+ let r = import("DSC_0002.NEF", &nef_uncompressed(&cam, w, h, Some(camera_rendering(&cam, w, h)))).unwrap();
+ assert!(fitted(&r.warnings) && !fallback(&r.warnings), "{:?}", r.warnings);
+ assert_eq!((r.document.size.width, r.document.size.height), (480, 320));
+ assert_eq!(r.document.depth, SampleType::U16);
+}
+
+#[test]
+fn unusable_previews_keep_the_neutral_fallback() {
+ let (w, h) = (480, 320);
+ let cam = patches(w, h);
+ let mut seed = 5u32;
+ let noise: Vec<u8> = (0..w * h * 3)
+ .map(|_| {
+ seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12345);
+ (seed >> 16) as u8
+ })
+ .collect();
+ let mut garbage = jpeg(Image::from_u8(64, 48, ChannelLayout::Rgb, vec![90; 64 * 48 * 3]).unwrap());
+ let sos = garbage.windows(2).rposition(|p| p == [0xFF, 0xDA]).unwrap();
+ garbage.truncate(sos + 8);
+ garbage.extend(std::iter::repeat_n(0xAB, 200));
+ let previews = [
+ None,
+ Some(jpeg(Image::from_u8(w as u32, h as u32, ChannelLayout::Rgb, noise).unwrap())),
+ Some(jpeg(Image::from_u8(240, 240, ChannelLayout::Rgb, vec![128; 240 * 240 * 3]).unwrap())),
+ Some(jpeg(Image::from_u8(w as u32, h as u32, ChannelLayout::Gray, vec![128; w * h]).unwrap())),
+ Some(garbage),
+ ];
+ for (i, p) in previews.into_iter().enumerate() {
+ let r = import("DSC_0003.NEF", &nef_uncompressed(&cam, w, h, p)).unwrap();
+ assert!(fallback(&r.warnings) && !fitted(&r.warnings), "preview {i}: {:?}", r.warnings);
+ }
+}
+
+#[test]
+fn truncated_raws_with_a_fittable_preview_do_not_panic() {
+ let (w, h) = (96, 64);
+ let cam = patches(w, h);
+ let b = nef_uncompressed(&cam, w, h, Some(camera_rendering(&cam, w, h)));
+ for n in (0..b.len()).step_by(211) {
+ let _ = import("x.nef", &b[..n]);
+ }
+}
diff --git a/crates/raw/README.md b/crates/raw/README.md
index 2f85f5e87..519746927 100644
--- a/crates/raw/README.md
+++ b/crates/raw/README.md
@@ -50,6 +50,11 @@ Implemented only from public specifications, papers and observation of files:
gradient-weighted green interpolation (Lu & Tan, "Color filter array demosaicking: new method
and performance measures", IEEE TIP 2003) with edge-aware colour differences.
* McCamy's CCT approximation (1992); the Bradford chromatic adaptation transform.
+* Per-file colour from the camera's embedded JPEG (`fit_look`, `src/look.rs`): the method follows
+ the prose description in LightCraft's `docs/camera-preview-colour.md` (storytold/lightcraft#165,
+ Apache-2.0, same organisation); no LightCraft code was used. Pool-adjacent-violators isotonic
+ regression (Ayer et al., 1955), Tukey's biweight (Beaton & Tukey, 1974), ridge regression
+ (Hoerl & Kennard, 1970) and the CIE 1976 L\*a\*b\* colour difference.
No code from dcraw, LibRaw, rawspeed, rawler, rawloader or darktable was read or used, and no
camera colour tables were copied.
@@ -81,17 +86,44 @@ camera colour tables were copied.
3. Demosaic: `Bilinear`, `Mhc` (Malvar–He–Cutler) or `Ahd` (default) for Bayer; non-Bayer CFAs
(X-Trans) always use the edge-directed generic method (`demosaic_cfa`).
4. Camera → XYZ (D50) per the DNG specification (ColorMatrix interpolated by the white's
- correlated colour temperature, or ForwardMatrix), → linear ProPhoto; exposure
- (BaselineExposure + user EV); gamma 1.8; 16 bits.
+ correlated colour temperature, or ForwardMatrix), or a camera look fitted to the embedded JPEG,
+ → linear ProPhoto; exposure (BaselineExposure + user EV); the look's tone curve; gamma 1.8;
+ 16 bits.
5. Orientation.
-Files without colour calibration (CR2, NEF, ARW, RW2, ORF, RAF…) use a documented neutral fallback: the
-white-balanced camera channels are treated as linear sRGB primaries (colours are plausible but
-less saturated than a calibrated profile; converting to DNG gives calibrated colour). No tone
-curve is applied: the result is a scene-referred rendering, flatter than a camera JPEG.
+Files without colour calibration (CR2, NEF, ARW, RW2, ORF, RAF…) have no camera matrix. Every one of
+them carries a JPEG the camera rendered from the same sensor data, so `fit_look` estimates the
+camera's rendering per file: both the sensor data (white-balanced as `develop` does) and the
+decoded JPEG are reduced to a common grid of at most 256 cells on the long edge, and a 3×3
+camera → ProPhoto matrix plus one monotone tone curve (applied per channel after exposure) are fitted
+so that the developed raw matches the JPEG, by alternating isotonic regression for the curve and
+weighted, ridge-regularised least squares for the matrix (residuals scaled to approximate L\*,
+Tukey biweights against misaligned edges and local tone mapping; clipped and near-black cells left
+out). One cell in three is held out: the look is used only when it shows the same picture in colour,
+the matrix is plausible and the held-out mean CIE76 ΔE drops to at most 85 % of the fallback's.
+Pass it as `DevelopOptions::camera_look`; `develop` then notes "colour fitted to the camera's
+embedded JPEG (mean ΔE …)". The crate cannot decode JPEG itself: `photocraft-io` decodes the
+smallest preview at least 512 pixels long, fits and develops in one go.
+
+Without a usable fit (no preview, an unrelated, monochrome or differently shaped one, or a fit that
+does not clearly help) the documented neutral fallback stays: the white-balanced camera channels are
+treated as linear sRGB primaries, with no tone curve (plausible but flat, greyish colours; converting
+to DNG gives calibrated colour), and `develop` says so.
+
+Measured on 8 Nikon D3200 NEFs (12-bit lossy compressed, indoor scenes) against each file's
+embedded JPEG (mean CIE76 ΔE, 300-pixel grid, full develop output in sRGB): fallback 11.6–26.0,
+fitted 1.0–7.5; all 8 fits were accepted. The highest remaining errors are shots where the camera
+brightened shadows locally (Active D-Lighting), which one global curve cannot follow. The fit
+(preview decode included) takes about 50–70 ms on a 24 MP file. It is an estimate of the camera's
+look, not a measured calibration: picture styles and hue-dependent rendering are approximated.
## Tools
`cargo run --release -p photocraft-raw --example rawinfo -- [--dump] [--demosaic ahd] [--png DIR] FILE...`
prints what was decoded, times decode and develop, and can write sRGB PNG previews and the
embedded JPEG previews.
+
+`cargo run --release -p photocraft-io --example rawlook -- [--png DIR] FILE...` times the
+camera-JPEG colour fit, reports ΔE against the embedded JPEG with the neutral fallback and with the
+fit, and can write 1200-pixel sRGB PNGs of both and of the JPEG; `--synthetic` times it on a
+generated 24 MP file.
diff --git a/crates/raw/src/develop.rs b/crates/raw/src/develop.rs
index 228df6be6..3c562dc28 100644
--- a/crates/raw/src/develop.rs
+++ b/crates/raw/src/develop.rs
@@ -5,6 +5,7 @@
use crate::color::{self, Mat3};
use crate::demosaic::{Demosaic, PAD, Padded, Pattern, demosaic, demosaic_cfa};
use crate::error::{RawError, Result};
+use crate::look::{CameraLook, ToneCurve};
use crate::sensor::Sensor;
use crate::{Limits, RawFormat, par};
@@ -30,11 +31,21 @@ pub struct DevelopOptions {
/// Apply the file's orientation (rotate / flip the pixels).
pub orient: bool,
pub limits: Limits,
+ /// A colour rendering fitted to the camera's own JPEG ([`crate::fit_look`]). When set it
+ /// replaces the file's colour calibration (or the neutral fallback) and adds its tone curve.
+ pub camera_look: Option<CameraLook>,
}
impl Default for DevelopOptions {
fn default() -> Self {
- DevelopOptions { demosaic: Demosaic::default(), white_balance: WhiteBalance::default(), exposure: 0.0, orient: true, limits: Limits::default() }
+ DevelopOptions {
+ demosaic: Demosaic::default(),
+ white_balance: WhiteBalance::default(),
+ exposure: 0.0,
+ orient: true,
+ limits: Limits::default(),
+ camera_look: None,
+ }
}
}
@@ -70,14 +81,19 @@ pub struct Developed {
}
/// Linearization + black/white scaling for one sample (pre white balance), 0..1.
-struct Scale<'a> {
+pub(crate) struct Scale<'a> {
s: &'a Sensor,
lin: Option<&'a [u16]>,
}
-impl Scale<'_> {
+impl<'a> Scale<'a> {
+ /// The scale for `s` (lazily: `lin` is the sensor's linearization table).
+ pub(crate) fn new(s: &'a Sensor) -> Self {
+ Scale { s, lin: s.linearization.as_deref() }
+ }
+
#[inline]
- fn value(&self, x: usize, y: usize, sample: usize) -> f32 {
+ pub(crate) fn value(&self, x: usize, y: usize, sample: usize) -> f32 {
let s = self.s;
let raw = s.data[(y * s.width + x) * s.samples + sample];
let v = match self.lin {
@@ -140,22 +156,9 @@ fn normalize(n: [f64; 3]) -> Option<[f64; 3]> {
(m > 0.0 && n.iter().all(|v| v.is_finite() && *v > 1e-4)).then(|| n.map(|v| v / m))
}
-/// Develops sensor data.
-pub fn develop_sensor(s: &Sensor, opts: &DevelopOptions) -> Result<Developed> {
- let c = s.crop;
- if c.is_empty() || c.x + c.width > s.width || c.y + c.height > s.height || s.data.len() < s.width * s.height * s.samples {
- return Err(RawError::malformed("crop lies outside the sensor data"));
- }
- if s.samples != 1 && s.samples != 3 {
- return Err(RawError::unsupported(format!("{} samples per pixel", s.samples)));
- }
- // Working buffers: one f32 plane plus f32 RGB plus u16 RGB per pixel, and
- // a green plane for non-Bayer patterns.
- let bayer = s.cfa.as_ref().is_none_or(|cfa| cfa.is_bayer());
- opts.limits.check(c.width as u64, c.height as u64, if bayer { 4 + 12 + 6 } else { 4 + 4 + 12 + 6 })?;
- let mut warnings = s.warnings.clone();
- let sc = Scale { s, lin: s.linearization.as_deref() };
-
+/// The camera-space neutral (max component 1) for `opts.white_balance`, as
+/// [`develop_sensor`] uses it (the same white balance [`crate::fit_look`] balances with).
+pub(crate) fn resolve_neutral(s: &Sensor, opts: &DevelopOptions, sc: &Scale, warnings: &mut Vec<String>) -> Result<[f64; 3]> {
// White balance: camera-space neutral, max component 1.
let as_shot = s
.color
@@ -163,25 +166,53 @@ pub fn develop_sensor(s: &Sensor, opts: &DevelopOptions) -> Result<Developed> {
.or_else(|| s.color.as_shot_white_xy.and_then(|xy| s.color.xy_to_neutral(xy)))
.or_else(|| s.camera_wb.map(|m| m.map(|v| 1.0 / v)))
.and_then(normalize);
- let neutral = match opts.white_balance {
+ Ok(match opts.white_balance {
WhiteBalance::AsShot => match as_shot {
Some(n) => n,
None => {
warnings.push("no as-shot white balance in the file; estimated automatically (grey world)".into());
- grey_world(s, &sc)
+ grey_world(s, sc)
}
},
- WhiteBalance::Auto => grey_world(s, &sc),
+ WhiteBalance::Auto => grey_world(s, sc),
WhiteBalance::Multipliers(m) => {
normalize(m.map(|v| 1.0 / v)).ok_or_else(|| RawError::Malformed("white-balance multipliers must be positive".into()))?
}
- };
+ })
+}
+
+/// Develops sensor data.
+pub fn develop_sensor(s: &Sensor, opts: &DevelopOptions) -> Result<Developed> {
+ let c = s.crop;
+ if c.is_empty() || c.x + c.width > s.width || c.y + c.height > s.height || s.data.len() < s.width * s.height * s.samples {
+ return Err(RawError::malformed("crop lies outside the sensor data"));
+ }
+ if s.samples != 1 && s.samples != 3 {
+ return Err(RawError::unsupported(format!("{} samples per pixel", s.samples)));
+ }
+ // Working buffers: one f32 plane plus f32 RGB plus u16 RGB per pixel, and
+ // a green plane for non-Bayer patterns.
+ let bayer = s.cfa.as_ref().is_none_or(|cfa| cfa.is_bayer());
+ opts.limits.check(c.width as u64, c.height as u64, if bayer { 4 + 12 + 6 } else { 4 + 4 + 12 + 6 })?;
+ let mut warnings = s.warnings.clone();
+ let sc = Scale::new(s);
+
+ let neutral = resolve_neutral(s, opts, &sc, &mut warnings)?;
let mult = neutral.map(|v| (1.0 / v) as f32);
- // Balanced camera → XYZ D50.
- let to_xyz: Mat3 = match s.color.balanced_to_xyz_d50(neutral) {
- Some(m) => m,
- None => {
+ // Balanced camera → XYZ D50: a look fitted to the camera's JPEG, the file's calibration,
+ // or the neutral fallback.
+ let look = opts.camera_look.as_ref().filter(|l| l.is_usable());
+ if opts.camera_look.is_some() && look.is_none() {
+ warnings.push("the supplied camera look is not usable (non-finite or singular); ignored".into());
+ }
+ let to_xyz: Mat3 = match (look, s.color.balanced_to_xyz_d50(neutral)) {
+ (Some(l), _) => {
+ warnings.push(l.note());
+ l.to_xyz
+ }
+ (None, Some(m)) => m,
+ (None, None) => {
if s.format != RawFormat::Dng {
warnings.push("no colour calibration for this camera; camera colours are treated as sRGB primaries".into());
}
@@ -288,9 +319,12 @@ pub fn develop_sensor(s: &Sensor, opts: &DevelopOptions) -> Result<Developed> {
}
}
- // Camera → ProPhoto, exposure, the profile's tone curve, gamma 1.8, 16 bits.
+ // Camera → ProPhoto, exposure, the look's tone curve, gamma 1.8, 16 bits.
let mut out = vec![0u16; w * h * 3];
- let lut = GammaLut::with_curve(&s.tone_curve);
+ let lut = match look {
+ Some(l) => GammaLut::with_tone(l.tone.as_ref()),
+ None => GammaLut::with_curve(&s.tone_curve),
+ };
par::chunks_mut(&mut out, band * w * 3, |b, chunk| {
let start = b * band * w * 3;
let src = &rgb[start..start + chunk.len()];
@@ -377,6 +411,20 @@ impl GammaLut {
GammaLut { table }
}
+ /// The gamma-1.8 encoding after a fitted [`ToneCurve`] (`None`: none, plain gamma 1.8).
+ fn with_tone(tone: Option<&ToneCurve>) -> Self {
+ let table = (0..=GAMMA_STEPS + 1)
+ .map(|i| {
+ let s = (i as f64 / GAMMA_STEPS as f64).min(1.0);
+ match tone {
+ Some(t) => (t.eval(s * s).powf(1.0 / 1.8) * 65535.0) as f32,
+ None => (s as f32).powf(2.0 / 1.8) * 65535.0,
+ }
+ })
+ .collect();
+ GammaLut { table }
+ }
+
#[inline]
fn encode(&self, v: f32) -> u16 {
let v = if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) };
@@ -404,6 +452,22 @@ fn tone(curve: &[[f32; 2]], v: f32) -> f32 {
y0 + (y1 - y0) * f
}
+/// The source position in a `w × h` image of output pixel (`x2`, `y2`) after
+/// applying TIFF orientation `o` (output in range when the input is).
+pub(crate) fn source_xy(o: u16, w: usize, h: usize, x2: usize, y2: usize) -> (usize, usize) {
+ let (wl, hl) = (w.saturating_sub(1), h.saturating_sub(1));
+ match o {
+ 2 => (wl.saturating_sub(x2), y2),
+ 3 => (wl.saturating_sub(x2), hl.saturating_sub(y2)),
+ 4 => (x2, hl.saturating_sub(y2)),
+ 5 => (y2, x2),
+ 6 => (y2, hl.saturating_sub(x2)),
+ 7 => (wl.saturating_sub(y2), hl.saturating_sub(x2)),
+ 8 => (wl.saturating_sub(y2), x2),
+ _ => (x2, y2),
+ }
+}
+
/// Applies a TIFF orientation (1–8) to interleaved RGB.
pub(crate) fn orient(src: Vec<u16>, w: usize, h: usize, o: u16) -> (Vec<u16>, usize, usize) {
if !(2..=8).contains(&o) {
diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs
index deffcc9f2..b9f4f1c6e 100644
--- a/crates/raw/src/lib.rs
+++ b/crates/raw/src/lib.rs
@@ -16,7 +16,12 @@
//! highlight clipping, demosaicing, camera → XYZ → ProPhoto, exposure and
//! orientation.
//! * [`embedded_preview`] finds the camera's full-size JPEG preview, for
-//! formats whose sensor data is not decoded yet.
+//! formats whose sensor data is not decoded yet; [`embedded_previews`] lists
+//! every preview.
+//! * [`fit_look`] fits a per-file colour matrix and tone curve ([`CameraLook`])
+//! to the camera's own (decoded) JPEG, for files without colour calibration
+//! (method after LightCraft's `docs/camera-preview-colour.md`,
+//! storytold/lightcraft#165); pass it in [`DevelopOptions::camera_look`].
//! * Raws that carry no colour description (NEF) take a camera profile we
//! measured from the camera's own output when there is one (`cameras.rs`:
//! image area, levels, ForwardMatrix, tone curve; the Nikon D4 so far).
@@ -47,6 +52,7 @@ mod dng;
mod error;
mod jxl;
mod ljpeg;
+mod look;
mod nefc;
mod opcodes;
mod orf;
@@ -66,8 +72,9 @@ pub use crate::color::{Calibration, ColorInfo, Mat3};
pub use crate::demosaic::Demosaic;
pub use crate::develop::{DevelopOptions, Developed, RawInfo, WhiteBalance, develop_sensor};
pub use crate::error::RawError;
+pub use crate::look::{CameraLook, LookRejected, PROXY_EDGE, Reference, ToneCurve, fit_look};
pub use crate::opcodes::GainMap;
-pub use crate::preview::{Preview, embedded_preview};
+pub use crate::preview::{Preview, embedded_preview, embedded_previews};
pub use crate::sensor::{BlackLevels, Cfa, Rect, Sensor};
use crate::tiff::{Tiff, tag};
diff --git a/crates/raw/src/look.rs b/crates/raw/src/look.rs
new file mode 100644
index 000000000..98d2c3802
--- /dev/null
+++ b/crates/raw/src/look.rs
@@ -0,0 +1,892 @@
+//! A per-file colour rendering ("camera look") fitted to the camera's own
+//! embedded JPEG, for raw files without colour calibration (NEF, ARW, CR2,
+//! RW2, ORF…), where the neutral fallback (camera channels treated as sRGB
+//! primaries, no tone curve) renders flat, grey and slightly green.
+//!
+//! Method (after LightCraft's prose description in `docs/camera-preview-colour.md`,
+//! storytold/lightcraft#165; this is an independent implementation against this
+//! crate's pipeline): both the sensor data and the camera JPEG are reduced to a
+//! common grid of at most [`PROXY_EDGE`] cells on the long edge, over the whole
+//! (upright) frame. Each cell pairs the white-balanced camera RGB `c` (the same
+//! white balance [`crate::develop`] applies) with the JPEG's colour in linear
+//! ProPhoto RGB `y`. The model is the develop pipeline itself:
+//!
+//! ```text
+//! y ≈ f(M · c) M: 3×3, scaled so the balanced white keeps the exposure gain's luminance
+//! f: one monotone tone curve, applied per channel to linear ProPhoto
+//! ```
+//!
+//! fitted by alternating: `f` by binned (square-root domain), pool-adjacent-
+//! violators isotonic regression of `y` on `M · c`, through (0, 0) and (1, 1);
+//! `M` by weighted least squares of `f⁻¹(y)` on `c`, weighted so the residual
+//! approximates a CIE L* difference, ridge-pulled toward the neutral fallback,
+//! with Tukey biweights against misaligned edges and local tone mapping. The
+//! ridge starts weak and is strengthened when the matrix comes out implausible
+//! (scenes with little colour keep the fallback's saturation while the neutral
+//! axis, the camera's rendering of white, still follows the JPEG). Cells with a
+//! clipped sensor sample, clipped or near-black JPEG pixels are left out of the
+//! fit; cells on strong edges get less weight.
+//!
+//! The reference must show the same picture (lightness correlation ≥ 0.7 with
+//! the raw) in colour (≥ 2 % of the cells with chroma above 4). One cell in
+//! three is held out. The look is accepted only when its matrix is plausible
+//! (relative to the gain: diagonal 0.2–3, off-diagonals within ±2, rows summing
+//! to 0.6–1.6, determinant above 0.05) and it lowers the held-out mean CIE76 ΔE
+//! (Lab D50) to at most 85 % of the neutral fallback's. This is a per-file
+//! estimate of the camera's rendering, not a measured calibration: picture
+//! styles, local tone mapping (Active D-Lighting and the like) and
+//! hue-dependent rendering are approximated by one matrix and one curve.
+
+use std::fmt;
+
+use crate::color::{self, Mat3};
+use crate::develop::{DevelopOptions, Scale, resolve_neutral, source_xy};
+use crate::par;
+use crate::sensor::Sensor;
+
+/// Long edge of the fit grid, in cells.
+pub const PROXY_EDGE: usize = 256;
+
+/// The camera's rendering of the picture: upright, interleaved 8-bit sRGB.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Reference<'a> {
+ pub width: u32,
+ pub height: u32,
+ /// `width * height * 3` samples.
+ pub rgb: &'a [u8],
+}
+
+/// A monotone tone curve on linear values 0..1, piecewise linear between knots
+/// in the square-root domain. Always passes through (0, 0) and (1, 1).
+#[derive(Debug, Clone, PartialEq)]
+pub struct ToneCurve {
+ /// Knots `(sqrt x, sqrt y)`, x strictly and y weakly increasing, from (0, 0) to (1, 1).
+ knots: Vec<[f64; 2]>,
+}
+
+impl ToneCurve {
+ /// Most knots a curve may have.
+ pub const MAX_KNOTS: usize = 256;
+
+ /// A curve through linear-light knots `(x, y)`: 2 to [`Self::MAX_KNOTS`] finite
+ /// points in 0..1, x strictly increasing, y not decreasing, starting at (0, 0)
+ /// and ending at (1, 1). `None` otherwise.
+ pub fn new(knots: &[[f64; 2]]) -> Option<ToneCurve> {
+ if knots.len() < 2 || knots.len() > Self::MAX_KNOTS {
+ return None;
+ }
+ let ok = knots.iter().all(|k| k.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)))
+ && knots.windows(2).all(|w| w[1][0] > w[0][0] && w[1][1] >= w[0][1])
+ && knots.first().is_some_and(|k| k[0] == 0.0 && k[1] == 0.0)
+ && knots.last().is_some_and(|k| k[0] == 1.0 && k[1] == 1.0);
+ ok.then(|| ToneCurve { knots: knots.iter().map(|k| [k[0].sqrt(), k[1].sqrt()]).collect() })
+ }
+
+ /// The knots in linear light.
+ pub fn knots(&self) -> Vec<[f64; 2]> {
+ self.knots.iter().map(|k| [k[0] * k[0], k[1] * k[1]]).collect()
+ }
+
+ /// `f(x)` for linear `x` (clamped to 0..1).
+ pub fn eval(&self, x: f64) -> f64 {
+ let t = if x.is_nan() { 0.0 } else { x.clamp(0.0, 1.0).sqrt() };
+ let s = interp(&self.knots, t, 0, 1);
+ s * s
+ }
+
+ /// `f⁻¹(y)` (the lowest `x` where a flat part repeats `y`).
+ #[cfg(test)]
+ fn inverse(&self, y: f64) -> f64 {
+ self.inverse_and_slope(y).0
+ }
+
+ /// `(x, f'(x))` for `x = f⁻¹(y)`, from one segment lookup: with `sx = sqrt x`,
+ /// `sy = sqrt y` and segment slope `k = dsy/dsx`, `f'(x) = k · sy / sx`.
+ fn inverse_and_slope(&self, y: f64) -> (f64, f64) {
+ let t = if y.is_nan() { 0.0 } else { y.clamp(0.0, 1.0).sqrt() };
+ let k = &self.knots;
+ let i = k.partition_point(|p| p[1] < t).clamp(1, k.len().saturating_sub(1).max(1));
+ let (Some(a), Some(b)) = (k.get(i - 1), k.get(i)) else { return (y, 1.0) };
+ let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
+ if dy <= 0.0 || dx <= 0.0 {
+ return (a[0] * a[0], 0.0);
+ }
+ let sx = a[0] + dx * ((t - a[1]) / dy).clamp(0.0, 1.0);
+ let slope = dy / dx;
+ let d = if sx > 1e-9 { slope * t / sx } else { slope * slope };
+ (sx * sx, d)
+ }
+}
+
+/// Piecewise-linear interpolation of coordinate `to` at `t` on coordinate `from`
+/// (both increasing; the first segment that reaches `t` wins).
+fn interp(k: &[[f64; 2]], t: f64, from: usize, to: usize) -> f64 {
+ let i = k.partition_point(|p| p[from] < t).clamp(1, k.len().saturating_sub(1).max(1));
+ match (k.get(i - 1), k.get(i)) {
+ (Some(a), Some(b)) => {
+ let d = b[from] - a[from];
+ if d <= 0.0 { a[to] } else { a[to] + (b[to] - a[to]) * ((t - a[from]) / d).clamp(0.0, 1.0) }
+ }
+ _ => t,
+ }
+}
+
+/// A colour rendering fitted to the camera's JPEG: use it through
+/// [`DevelopOptions::camera_look`].
+#[derive(Debug, Clone, PartialEq)]
+pub struct CameraLook {
+ /// White-balanced camera RGB → XYZ (D50), white mapping to D50 with Y = 1.
+ pub to_xyz: Mat3,
+ /// Tone curve applied per channel to linear ProPhoto RGB after exposure.
+ pub tone: Option<ToneCurve>,
+ /// Mean CIE76 ΔE against the camera JPEG on the fit grid, with this look.
+ pub delta_e: f64,
+ /// The same with the neutral fallback (no calibration, no tone curve).
+ pub delta_e_fallback: f64,
+}
+
+impl CameraLook {
+ /// Finite, bounded and invertible, with a positive white luminance.
+ pub(crate) fn is_usable(&self) -> bool {
+ let m = &self.to_xyz;
+ m.iter().flatten().all(|v| v.is_finite() && v.abs() < 64.0) && color::invert(m).is_some() && color::apply(m, [1.0; 3])[1] > 1e-3
+ }
+
+ /// The note `develop` reports.
+ pub(crate) fn note(&self) -> String {
+ format!("colour fitted to the camera's embedded JPEG (mean ΔE {:.1} against it; {:.1} with the neutral fallback)", self.delta_e, self.delta_e_fallback)
+ }
+}
+
+/// Why no look was fitted (the neutral fallback stays).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct LookRejected(pub String);
+
+impl fmt::Display for LookRejected {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "colour not fitted to the camera JPEG: {}", self.0)
+ }
+}
+
+impl std::error::Error for LookRejected {}
+
+fn reject<T>(why: impl Into<String>) -> Result<T, LookRejected> {
+ Err(LookRejected(why.into()))
+}
+
+/// One grid cell.
+#[derive(Debug, Clone, Copy, Default)]
+struct Cell {
+ /// White-balanced camera RGB, 0..1.
+ cam: [f64; 3],
+ /// Any sampled sensor value at or near clipping.
+ cam_clipped: bool,
+ /// The JPEG's colour, linear ProPhoto RGB.
+ rgb: [f64; 3],
+ /// Luminance (Y, D50) of `rgb`.
+ lum: f64,
+ /// Fraction of the cell's JPEG pixels with a channel at 250 or more.
+ ref_clipped: f64,
+ /// Weight from the JPEG's local contrast (edges count less).
+ edge_weight: f64,
+}
+
+/// Fits a [`CameraLook`] so that developing `s` with `opts` (white balance,
+/// baseline exposure) matches the camera's `reference` rendering of it.
+pub fn fit_look(s: &Sensor, opts: &DevelopOptions, reference: &Reference) -> Result<CameraLook, LookRejected> {
+ let (gw, cells) = grid(s, opts, reference)?;
+ fit_cells(&cells, gw, s.baseline_exposure)
+}
+
+/// The upright fit grid: (width in cells, cells row-major).
+fn grid(s: &Sensor, opts: &DevelopOptions, r: &Reference) -> Result<(usize, Vec<Cell>), LookRejected> {
+ let c = s.crop;
+ let in_data = c.x.checked_add(c.width).is_some_and(|v| v <= s.width) && c.y.checked_add(c.height).is_some_and(|v| v <= s.height);
+ let need = s.width.checked_mul(s.height).and_then(|v| v.checked_mul(s.samples));
+ if c.is_empty() || !in_data || need.is_none_or(|n| s.data.len() < n) {
+ return reject("the crop lies outside the sensor data");
+ }
+ if !(s.samples == 3 || (s.samples == 1 && s.cfa.is_some())) {
+ return reject("unsupported sensor layout");
+ }
+ let (rw, rh) = (r.width as usize, r.height as usize);
+ if rw < 32 || rh < 32 || rw.checked_mul(rh).and_then(|n| n.checked_mul(3)) != Some(r.rgb.len()) {
+ return reject("the reference image is too small or its buffer does not match its size");
+ }
+ let swap = (5..=8).contains(&s.orientation);
+ let (uw, uh) = if swap { (c.height, c.width) } else { (c.width, c.height) };
+ let aspect = (rw as f64 / rh as f64) / (uw as f64 / uh as f64);
+ if !(aspect.is_finite() && (aspect.ln()).abs() <= 0.03) {
+ return reject(format!("the reference ({rw}x{rh}) does not have the raw frame's shape ({uw}x{uh})"));
+ }
+ // Cells at least 4 sensor pixels and 2 reference pixels across.
+ let long = uw.max(uh);
+ let edge = PROXY_EDGE.min(long / 4).min(rw.max(rh) / 2);
+ let gw_up = (uw * edge).div_ceil(long).max(1);
+ let gh_up = (uh * edge).div_ceil(long).max(1);
+ if gw_up < 16 || gh_up < 16 {
+ return reject("the image is too small to fit");
+ }
+ let mut warnings = Vec::new();
+ let neutral = resolve_neutral(s, opts, &Scale::new(s), &mut warnings).map_err(|e| LookRejected(e.to_string()))?;
+ let mult = neutral.map(|v| 1.0 / v);
+
+ // Sensor-orientation grid.
+ let (gw, gh) = if swap { (gh_up, gw_up) } else { (gw_up, gh_up) };
+ let sc = Scale::new(s);
+ let rows = par::map(gh, |j| {
+ let (y0, y1) = (c.y + j * c.height / gh, c.y + (j + 1) * c.height / gh);
+ (0..gw)
+ .map(|i| {
+ let (x0, x1) = (c.x + i * c.width / gw, c.x + (i + 1) * c.width / gw);
+ sensor_cell(s, &sc, mult, x0, x1, y0, y1)
+ })
+ .collect::<Vec<_>>()
+ });
+ let sensor_cells: Vec<Option<([f64; 3], bool)>> = rows.into_iter().flatten().collect();
+
+ // Reference cells, upright; then pair with the oriented sensor cells.
+ let lut: Vec<f64> = (0..256).map(|v| srgb_to_linear(v as f64 / 255.0)).collect();
+ let to_pro = color::mul(&color::xyz_d50_to_prophoto(), &color::srgb_to_xyz_d50());
+ let pro_to_xyz = color::rgb_to_xyz(color::ROMM, color::D50_XY);
+ let ref_rows = par::map(gh_up, |j| {
+ let (y0, y1) = (j * rh / gh_up, ((j + 1) * rh / gh_up).max(j * rh / gh_up + 1));
+ (0..gw_up)
+ .map(|i| {
+ let (x0, x1) = (i * rw / gw_up, ((i + 1) * rw / gw_up).max(i * rw / gw_up + 1));
+ reference_cell(r, &lut, x0, x1.min(rw), y0, y1.min(rh))
+ })
+ .collect::<Vec<_>>()
+ });
+ let mut cells = Vec::with_capacity(gw_up * gh_up);
+ for (j, row) in ref_rows.into_iter().enumerate() {
+ for (i, rc) in row.into_iter().enumerate() {
+ let (sx, sy) = source_xy(s.orientation, gw, gh, i, j);
+ let Some(Some((cam, cam_clipped))) = sensor_cells.get(sy * gw + sx).copied() else {
+ cells.push(Cell { cam_clipped: true, ..Default::default() });
+ continue;
+ };
+ let Some((srgb, ref_clipped, edge_weight)) = rc else {
+ cells.push(Cell { cam_clipped: true, ..Default::default() });
+ continue;
+ };
+ let rgb = color::apply(&to_pro, srgb);
+ let lum = color::apply(&pro_to_xyz, rgb)[1];
+ cells.push(Cell { cam, cam_clipped, rgb, lum, ref_clipped, edge_weight });
+ }
+ }
+ Ok((gw_up, cells))
+}
+
+/// Mean white-balanced camera RGB over `x0..x1 × y0..y1` (sampling at most
+/// about 8 × 8 Bayer quads), and whether any sample was near clipping.
+fn sensor_cell(s: &Sensor, sc: &Scale, mult: [f64; 3], x0: usize, x1: usize, y0: usize, y1: usize) -> Option<([f64; 3], bool)> {
+ let step = |a: usize, b: usize| b.saturating_sub(a).div_ceil(16).max(1) * 2;
+ let (sx, sy) = (step(x0, x1), step(y0, y1));
+ let mut sum = [0.0f64; 3];
+ let mut n = [0u32; 3];
+ let mut clipped = false;
+ let mut add = |ch: usize, v: f32| {
+ let v = f64::from(v);
+ let b = v * mult.get(ch).copied().unwrap_or(1.0);
+ clipped |= v >= 0.98 || b >= 0.98;
+ if let (Some(s), Some(k)) = (sum.get_mut(ch), n.get_mut(ch)) {
+ *s += b.clamp(0.0, 1.0);
+ *k += 1;
+ }
+ };
+ let mut y = y0;
+ while y < y1 {
+ let mut x = x0;
+ while x < x1 {
+ for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
+ let (px, py) = (x + dx, y + dy);
+ if px >= x1 || py >= y1 {
+ continue;
+ }
+ match &s.cfa {
+ Some(cfa) if s.samples == 1 => add(usize::from(cfa.color(px, py)).min(2), sc.value(px, py, 0)),
+ _ => (0..3).for_each(|k| add(k, sc.value(px, py, k))),
+ }
+ }
+ x += sx;
+ }
+ y += sy;
+ }
+ (n.iter().all(|k| *k > 0)).then(|| ([0, 1, 2].map(|c| sum[c] / f64::from(n[c])), clipped))
+}
+
+/// Mean linear sRGB of a reference box, the fraction of its pixels with a
+/// clipped channel and an edge weight from its luminance spread.
+fn reference_cell(r: &Reference, lut: &[f64], x0: usize, x1: usize, y0: usize, y1: usize) -> Option<([f64; 3], f64, f64)> {
+ let rw = r.width as usize;
+ let mut sum = [0.0f64; 3];
+ let (mut l1, mut l2, mut n, mut clipped) = (0.0f64, 0.0f64, 0usize, 0usize);
+ for y in y0..y1 {
+ let row = r.rgb.get((y * rw + x0) * 3..(y * rw + x1) * 3)?;
+ for p in row.as_chunks::<3>().0 {
+ let v = p.map(|b| lut.get(usize::from(b)).copied().unwrap_or(0.0));
+ for k in 0..3 {
+ sum[k] += v[k];
+ }
+ let l = 0.2126 * v[0] + 0.7152 * v[1] + 0.0722 * v[2];
+ l1 += l;
+ l2 += l * l;
+ n += 1;
+ clipped += usize::from(p.iter().any(|b| *b >= 250));
+ }
+ }
+ if n == 0 {
+ return None;
+ }
+ let nf = n as f64;
+ let mean = l1 / nf;
+ let sd = (l2 / nf - mean * mean).max(0.0).sqrt();
+ let cv = sd / (mean + 0.01);
+ Some((sum.map(|v| v / nf), clipped as f64 / nf, 1.0 / (1.0 + (cv / 0.15).powi(2))))
+}
+
+fn srgb_to_linear(v: f64) -> f64 {
+ if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
+}
+
+/// A training / evaluation sample.
+#[derive(Debug, Clone, Copy)]
+struct Sample {
+ cam: [f64; 3],
+ rgb: [f64; 3],
+ /// Luminance (Y, D50) of `rgb` and its [`perceptual`] scale.
+ lum: f64,
+ perceptual: f64,
+ weight: f64,
+}
+
+/// CIE L*a*b* (D50) of linear ProPhoto RGB.
+struct Lab {
+ to_xyz: Mat3,
+ white: [f64; 3],
+}
+
+impl Lab {
+ fn new() -> Self {
+ let to_xyz = color::rgb_to_xyz(color::ROMM, color::D50_XY);
+ Lab { white: color::apply(&to_xyz, [1.0; 3]), to_xyz }
+ }
+
+ fn lab(&self, rgb: [f64; 3]) -> [f64; 3] {
+ let xyz = color::apply(&self.to_xyz, rgb);
+ let f = |t: f64| if t > 216.0 / 24389.0 { t.cbrt() } else { (24389.0 / 27.0 * t + 16.0) / 116.0 };
+ let [fx, fy, fz] = [0, 1, 2].map(|k| f(xyz[k] / self.white[k]));
+ [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)]
+ }
+
+ fn delta_e(&self, a: [f64; 3], b: [f64; 3]) -> f64 {
+ let (p, q) = (self.lab(a), self.lab(b));
+ ((p[0] - q[0]).powi(2) + (p[1] - q[1]).powi(2) + (p[2] - q[2]).powi(2)).sqrt()
+ }
+}
+
+/// The develop pipeline's output for one sample (clipped to 0..1 like the 16-bit encode).
+fn render(m: &Mat3, tone: Option<&ToneCurve>, cam: [f64; 3]) -> [f64; 3] {
+ color::apply(m, cam).map(|v| {
+ let v = if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
+ tone.map_or(v, |t| t.eval(v))
+ })
+}
+
+fn mean_delta_e(lab: &Lab, samples: &[&Sample], m: &Mat3, tone: Option<&ToneCurve>) -> f64 {
+ if samples.is_empty() {
+ return f64::INFINITY;
+ }
+ let parts = par::map(samples.len().div_ceil(CHUNK), |ci| {
+ let lo = ci * CHUNK;
+ let chunk = samples.get(lo..(lo + CHUNK).min(samples.len())).unwrap_or(&[]);
+ chunk.iter().map(|s| lab.delta_e(render(m, tone, s.cam), s.rgb)).sum::<f64>()
+ });
+ parts.iter().sum::<f64>() / samples.len() as f64
+}
+
+/// Error-weight scale turning a linear difference near luminance `lum` into
+/// roughly L* units (dL*/dY = 116/3 · Y^(-2/3)).
+fn perceptual(lum: f64) -> f64 {
+ (116.0 / 3.0) * (lum.max(0.0) + 0.008).powf(-2.0 / 3.0)
+}
+
+fn fit_cells(cells: &[Cell], gw: usize, baseline_exposure: f64) -> Result<CameraLook, LookRejected> {
+ let gain = 2f64.powf(if baseline_exposure.is_finite() { baseline_exposure.clamp(-10.0, 10.0) } else { 0.0 });
+ let fallback = color::scale(&color::mul(&color::xyz_d50_to_prophoto(), &color::srgb_to_xyz_d50()), gain);
+ let lab = Lab::new();
+
+ let mut train = Vec::new();
+ let mut test = Vec::new();
+ let mut all = Vec::new();
+ for (k, c) in cells.iter().enumerate() {
+ if !c.cam.iter().chain(&c.rgb).all(|v| v.is_finite()) {
+ continue;
+ }
+ let s = Sample { cam: c.cam, rgb: c.rgb, lum: c.lum, perceptual: perceptual(c.lum), weight: c.edge_weight };
+ all.push(s);
+ let usable = !c.cam_clipped && c.ref_clipped < 0.01 && c.lum > 0.002 && c.cam.iter().all(|v| *v > 1e-4) && c.edge_weight > 0.05;
+ if !usable {
+ continue;
+ }
+ let (x, y) = (k % gw.max(1), k / gw.max(1));
+ if (x + 2 * y) % 3 == 0 { test.push(s) } else { train.push(s) }
+ }
+ if train.len() < 300 || test.len() < 100 {
+ return reject(format!("too few usable cells ({} + {} held out)", train.len(), test.len()));
+ }
+
+ // The reference must show this picture (its lightness follows the raw's) in colour.
+ let usable: Vec<&Sample> = train.iter().chain(&test).collect();
+ let pairs: Vec<(f64, f64)> =
+ usable.iter().map(|s| (color::apply(&PRO_TO_XYZ_Y_ROW, color::apply(&fallback, s.cam))[0].max(0.0).sqrt(), s.lum.max(0.0).sqrt())).collect();
+ let r = correlation(&pairs);
+ if r.is_nan() || r < 0.7 {
+ return reject(format!("the reference does not match the raw picture (lightness correlation {r:.2})"));
+ }
+ let coloured = usable.iter().filter(|s| {
+ let l = lab.lab(s.rgb);
+ l[1].hypot(l[2]) > 4.0
+ });
+ if coloured.count() * 50 < usable.len() {
+ return reject("the reference is (nearly) colourless");
+ }
+
+ // Weakest ridge first; a stronger pull toward the fallback when the matrix comes out
+ // implausible (little colour in the scene, or a rendering a matrix can't follow).
+ let test_refs: Vec<&Sample> = test.iter().collect();
+ let held_fallback = mean_delta_e(&lab, &test_refs, &fallback, None);
+ let mut why = String::new();
+ let mut found = None;
+ for ridge in RIDGES {
+ let (m, tone) = fit_model(&train, &fallback, gain, ridge)?;
+ let rel = color::scale(&m, 1.0 / gain);
+ if !plausible(&rel) {
+ why = format!("implausible matrix {rel:?}");
+ continue;
+ }
+ let held_fit = mean_delta_e(&lab, &test_refs, &m, Some(&tone));
+ if held_fit.is_nan() || held_fit > 0.85 * held_fallback {
+ why = format!("the fit does not improve enough on the neutral fallback (held-out ΔE {held_fit:.1} vs {held_fallback:.1})");
+ continue;
+ }
+ found = Some((m, rel, tone));
+ break;
+ }
+ let Some((m, rel, tone)) = found else { return reject(why) };
+ let all_refs: Vec<&Sample> = all.iter().collect();
+ let delta_e = mean_delta_e(&lab, &all_refs, &m, Some(&tone));
+ let delta_e_fallback = mean_delta_e(&lab, &all_refs, &fallback, None);
+
+ let to_xyz = color::mul(&color::rgb_to_xyz(color::ROMM, color::D50_XY), &rel);
+ let look = CameraLook { to_xyz, tone: Some(tone), delta_e, delta_e_fallback };
+ if !look.is_usable() {
+ return reject("the fitted matrix is not usable");
+ }
+ Ok(look)
+}
+
+/// Ridge strengths tried in turn (see [`fit_matrix`]).
+const RIDGES: [f64; 3] = [0.01, 0.05, 0.15];
+
+/// Alternates tone-curve and matrix fits with Tukey reweighting.
+fn fit_model(train: &[Sample], fallback: &Mat3, gain: f64, ridge: f64) -> Result<(Mat3, ToneCurve), LookRejected> {
+ let no_curve = || LookRejected("no tone curve could be fitted".into());
+ let mut m = *fallback;
+ let mut robust = vec![1.0f64; train.len()];
+ let mut tone = fit_curve(train, &robust, &m).ok_or_else(no_curve)?;
+ for _ in 0..6 {
+ m = fit_matrix(train, &robust, &tone, fallback, gain, ridge);
+ tone = fit_curve(train, &robust, &m).ok_or_else(no_curve)?;
+ update_robust(train, &mut robust, &m, &tone);
+ }
+ Ok((m, tone))
+}
+
+/// A plausible white-balanced camera → ProPhoto matrix (exposure removed): moderate
+/// diagonal and cross-talk, rows summing to about 1 (neutrals stay near neutral), not
+/// mirrored or collapsed.
+fn plausible(rel: &Mat3) -> bool {
+ let entries = (0..3).all(|i| {
+ (0..3).all(|j| {
+ let v = rel[i][j];
+ if i == j { (0.2..=3.0).contains(&v) } else { v.abs() <= 2.0 }
+ })
+ });
+ let [[a, b, c], [d, e, f], [g, h, i]] = *rel;
+ let det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
+ let sums = rel.iter().all(|r| (0.6..=1.6).contains(&(r[0] + r[1] + r[2])));
+ entries && sums && det > 0.05
+}
+
+/// Pearson correlation of `(a, b)` pairs (NaN without spread).
+fn correlation(p: &[(f64, f64)]) -> f64 {
+ let n = p.len() as f64;
+ let (ma, mb) = (p.iter().map(|v| v.0).sum::<f64>() / n, p.iter().map(|v| v.1).sum::<f64>() / n);
+ let (mut sab, mut saa, mut sbb) = (0.0, 0.0, 0.0);
+ for (a, b) in p {
+ sab += (a - ma) * (b - mb);
+ saa += (a - ma).powi(2);
+ sbb += (b - mb).powi(2);
+ }
+ sab / (saa * sbb).sqrt()
+}
+
+/// Bins of the tone-curve fit, uniform in `sqrt(x)`.
+const CURVE_BINS: usize = 32;
+
+/// Fits the tone curve to `(M · cam, rgb)` pairs of all channels, by weighted
+/// bin means in the square-root domain made monotone (pool adjacent violators).
+fn fit_curve(samples: &[Sample], robust: &[f64], m: &Mat3) -> Option<ToneCurve> {
+ let mut bins = [[0.0f64; 3]; CURVE_BINS]; // weight, Σ w·sqrt(x), Σ w·sqrt(y)
+ let mut total = 0.0;
+ for (s, r) in samples.iter().zip(robust) {
+ let x = color::apply(m, s.cam);
+ let w = s.weight * r;
+ if w <= 0.0 {
+ continue;
+ }
+ for (&xv, &yv) in x.iter().zip(&s.rgb) {
+ if !(xv > 1e-5 && xv < 1.0 && yv.is_finite()) {
+ continue;
+ }
+ let (sx, sy) = (xv.sqrt(), yv.clamp(0.0, 1.0).sqrt());
+ let b = ((sx * CURVE_BINS as f64) as usize).min(CURVE_BINS - 1);
+ if let Some(bin) = bins.get_mut(b) {
+ bin[0] += w;
+ bin[1] += w * sx;
+ bin[2] += w * sy;
+ total += w;
+ }
+ }
+ }
+ if total.is_nan() || total <= 0.0 {
+ return None;
+ }
+ // (weight, sqrt x, sqrt y) of the populated bins, then PAVA on y.
+ let mut pts: Vec<[f64; 3]> = bins.iter().filter(|b| b[0] > total * 2e-4).map(|b| [b[0], b[1] / b[0], b[2] / b[0]]).collect();
+ if pts.len() < 4 {
+ return None;
+ }
+ let mut blocks: Vec<(f64, f64, usize)> = Vec::new(); // (weight, mean y, count)
+ for p in &pts {
+ blocks.push((p[0], p[2], 1));
+ while blocks.len() >= 2 {
+ let (Some(&b), Some(&a)) = (blocks.last(), blocks.get(blocks.len() - 2)) else { break };
+ if a.1 <= b.1 {
+ break;
+ }
+ blocks.truncate(blocks.len() - 2);
+ let w = a.0 + b.0;
+ blocks.push((w, (a.0 * a.1 + b.0 * b.1) / w, a.2 + b.2));
+ }
+ }
+ let mut i = 0;
+ for (_, y, n) in blocks {
+ for p in pts.iter_mut().skip(i).take(n) {
+ p[2] = y;
+ }
+ i += n;
+ }
+ let mut knots = vec![[0.0, 0.0]];
+ for p in &pts {
+ let (x, y) = (p[1] * p[1], (p[2] * p[2]).clamp(0.0, 1.0));
+ let Some(&[px, py]) = knots.last() else { continue };
+ if x > px + 1e-6 && x < 1.0 - 1e-6 {
+ knots.push([x, y.max(py)]);
+ }
+ }
+ knots.push([1.0, 1.0]);
+ ToneCurve::new(&knots)
+}
+
+/// Samples per parallel chunk of the least-squares accumulation.
+const CHUNK: usize = 4096;
+
+/// Weighted least squares for `M` from `f⁻¹(rgb)` on `cam`, ridge-pulled toward
+/// `prior`, then scaled so the balanced white keeps luminance `gain` (a matrix
+/// and a curve could otherwise trade exposure).
+///
+/// The ridge makes colour differences of `ridge` × the level weigh as much as the
+/// prior, so scenes with little colour keep the neutral fallback's saturation while
+/// the well-determined neutral axis (the camera's rendering of white) follows the data.
+fn fit_matrix(samples: &[Sample], robust: &[f64], tone: &ToneCurve, prior: &Mat3, gain: f64, ridge: f64) -> Mat3 {
+ // Per row: normal matrix, right-hand side, level.
+ type Normal = [([[f64; 3]; 3], [f64; 3], f64); 3];
+ let parts: Vec<Normal> = par::map(samples.len().div_ceil(CHUNK), |ci| {
+ let mut acc: Normal = [([[0.0; 3]; 3], [0.0; 3], 0.0); 3];
+ let lo = ci * CHUNK;
+ let chunk = samples.get(lo..(lo + CHUNK).min(samples.len())).unwrap_or(&[]);
+ let rob = robust.get(lo..(lo + CHUNK).min(robust.len())).unwrap_or(&[]);
+ for (s, r) in chunk.iter().zip(rob) {
+ let c = s.cam;
+ let level = ((c[0] + c[1] + c[2]) / 3.0).powi(2);
+ for (i, (a, b, l)) in acc.iter_mut().enumerate() {
+ let y = s.rgb[i];
+ if !(y > 0.0 && y < 0.995) {
+ continue;
+ }
+ let (t, slope) = tone.inverse_and_slope(y);
+ let q = slope * s.perceptual;
+ let w = s.weight * r * q * q;
+ if !(w.is_finite() && w > 0.0) {
+ continue;
+ }
+ *l += w * level;
+ for j in 0..3 {
+ for k in 0..3 {
+ a[j][k] += w * c[j] * c[k];
+ }
+ b[j] += w * c[j] * t;
+ }
+ }
+ }
+ acc
+ });
+ let mut out = *prior;
+ for (i, row) in out.iter_mut().enumerate() {
+ let (mut a, mut b, mut level) = ([[0.0f64; 3]; 3], [0.0f64; 3], 0.0);
+ for p in &parts {
+ let (pa, pb, pl) = &p[i];
+ for j in 0..3 {
+ for k in 0..3 {
+ a[j][k] += pa[j][k];
+ }
+ b[j] += pb[j];
+ }
+ level += pl;
+ }
+ let lambda = ridge * ridge * level + 1e-12;
+ for j in 0..3 {
+ a[j][j] += lambda;
+ b[j] += lambda * prior[i][j];
+ }
+ if let Some(inv) = color::invert(&a) {
+ let x = color::apply(&inv, b);
+ if x.iter().all(|v| v.is_finite()) {
+ *row = x;
+ }
+ }
+ }
+ let white_y = color::apply(&PRO_TO_XYZ_Y_ROW, color::apply(&out, [1.0; 3]))[0];
+ if white_y.is_finite() && white_y > 1e-6 { color::scale(&out, gain / white_y) } else { *prior }
+}
+
+/// The Y row of linear ProPhoto → XYZ (other rows zero), for luminance.
+const PRO_TO_XYZ_Y_ROW: Mat3 = [[0.288_040, 0.711_874, 0.000_086], [0.0; 3], [0.0; 3]];
+
+/// Tukey biweights from each sample's L*-scaled residual.
+fn update_robust(samples: &[Sample], robust: &mut [f64], m: &Mat3, tone: &ToneCurve) {
+ let err: Vec<f64> = par::map(samples.len().div_ceil(CHUNK), |ci| {
+ let lo = ci * CHUNK;
+ let chunk = samples.get(lo..(lo + CHUNK).min(samples.len())).unwrap_or(&[]);
+ chunk
+ .iter()
+ .map(|s| {
+ let o = render(m, Some(tone), s.cam);
+ ((0..3).map(|k| (o[k] - s.rgb[k]).powi(2)).sum::<f64>()).sqrt() * s.perceptual
+ })
+ .collect::<Vec<_>>()
+ })
+ .into_iter()
+ .flatten()
+ .collect();
+ let mut sorted: Vec<f64> = err.iter().copied().filter(|v| v.is_finite()).collect();
+ if sorted.is_empty() {
+ return;
+ }
+ let mid = sorted.len() / 2;
+ let (_, median, _) = sorted.select_nth_unstable_by(mid, f64::total_cmp);
+ let c = 4.685 * (1.4826 * *median).max(0.5);
+ for (r, e) in robust.iter_mut().zip(&err) {
+ let u = e / c;
+ *r = if u.is_finite() && u < 1.0 { (1.0 - u * u).powi(2) } else { 0.0 };
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn tone_curve_validates_and_interpolates() {
+ assert!(ToneCurve::new(&[[0.0, 0.0]]).is_none());
+ assert!(ToneCurve::new(&[[0.0, 0.0], [0.5, 0.4], [0.5, 0.6], [1.0, 1.0]]).is_none());
+ assert!(ToneCurve::new(&[[0.0, 0.0], [0.5, 0.6], [0.7, 0.4], [1.0, 1.0]]).is_none());
+ assert!(ToneCurve::new(&[[0.0, 0.0], [0.5, f64::NAN], [1.0, 1.0]]).is_none());
+ assert!(ToneCurve::new(&[[0.1, 0.0], [1.0, 1.0]]).is_none());
+ let t = ToneCurve::new(&[[0.0, 0.0], [0.04, 0.16], [1.0, 1.0]]).unwrap();
+ assert!((t.eval(0.04) - 0.16).abs() < 1e-12);
+ assert!((t.eval(0.01) - 0.04).abs() < 1e-12); // sqrt-domain line through the origin
+ assert_eq!(t.eval(-1.0), 0.0);
+ assert_eq!(t.eval(2.0), 1.0);
+ assert_eq!(t.eval(f64::NAN), 0.0);
+ assert!((t.inverse(0.16) - 0.04).abs() < 1e-12);
+ let (x, d) = t.inverse_and_slope(0.5);
+ assert!((t.eval(x) - 0.5).abs() < 1e-12);
+ let num = (t.eval(x + 1e-6) - t.eval(x - 1e-6)) / 2e-6;
+ assert!((d - num).abs() < 1e-6 * num.max(1.0), "{d} vs {num}");
+ let k = t.knots();
+ assert!((k[1][0] - 0.04).abs() < 1e-12 && (k[1][1] - 0.16).abs() < 1e-12);
+ }
+
+ /// Camera-space patches with a tonal ramp inside each patch.
+ fn patches(w: usize, h: usize) -> Vec<[f32; 3]> {
+ let mut seed = 12345u32;
+ let mut rnd = || {
+ seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
+ (seed >> 8) as f32 / (1u32 << 24) as f32
+ };
+ let (pw, ph) = (12, 8);
+ let colours: Vec<[f32; 3]> = (0..pw * ph).map(|_| [0.15 + 0.45 * rnd(), 0.15 + 0.45 * rnd(), 0.15 + 0.45 * rnd()]).collect();
+ (0..w * h)
+ .map(|i| {
+ let (x, y) = (i % w, i / w);
+ let (px, py) = (x * pw / w, y * ph / h);
+ let ramp = 0.15 + 0.85 * ((x * pw) % w) as f32 / w as f32;
+ colours[py * pw + px].map(|v| v * ramp)
+ })
+ .collect()
+ }
+
+ const WB: [f64; 3] = [1.5, 1.0, 1.25];
+
+ /// A NEF-like raw of `cam` (balanced by `WB`) and its JPEG-like rendering through
+ /// `pro = f(m · balanced)` in linear ProPhoto, encoded as 8-bit sRGB.
+ fn shot(w: usize, h: usize, m: &Mat3) -> (Sensor, Vec<u8>) {
+ let cam: Vec<[f32; 3]> = patches(w, h).iter().map(|p| [0, 1, 2].map(|k| p[k] / WB[k] as f32)).collect();
+ let data = crate::testgen::mosaic(&cam, w, [0, 1, 1, 2], 0, 4095);
+ let b = crate::testgen::tiff_ep("NIKON CORPORATION", w, h, &data, [0, 1, 1, 2], 12, vec![]);
+ let s = crate::decode(&b, &crate::Limits::default()).unwrap();
+ let to_srgb = color::invert(&color::srgb_to_xyz_d50()).unwrap();
+ let pro_to_srgb = color::mul(&to_srgb, &color::rgb_to_xyz(color::ROMM, color::D50_XY));
+ let f = |x: f64| 1.6 * x / (1.0 + 0.6 * x);
+ let enc = |v: f64| {
+ let v = v.clamp(0.0, 1.0);
+ let e = if v <= 0.0031308 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 };
+ (e * 255.0).round() as u8
+ };
+ let rgb = cam
+ .iter()
+ .flat_map(|p| {
+ let bal = [0, 1, 2].map(|k| f64::from(p[k]) * WB[k]);
+ let pro = color::apply(m, bal).map(|v| f(v.clamp(0.0, 1.0)));
+ color::apply(&pro_to_srgb, pro).map(enc)
+ })
+ .collect();
+ (s, rgb)
+ }
+
+ fn wb_opts() -> DevelopOptions {
+ DevelopOptions { white_balance: crate::WhiteBalance::Multipliers(WB), ..Default::default() }
+ }
+
+ /// The true balanced camera → ProPhoto matrix of the synthetic camera: sRGB primaries
+ /// with a saturating twist (rows sum to 1).
+ fn true_matrix() -> Mat3 {
+ let k = [[1.35, -0.25, -0.1], [-0.15, 1.25, -0.1], [0.0, -0.3, 1.3]];
+ color::mul(&color::mul(&color::xyz_d50_to_prophoto(), &color::srgb_to_xyz_d50()), &k)
+ }
+
+ #[test]
+ fn recovers_a_known_matrix_and_curve() {
+ let (w, h) = (480, 320);
+ let m = true_matrix();
+ let (s, rgb) = shot(w, h, &m);
+ let look = fit_look(&s, &wb_opts(), &Reference { width: w as u32, height: h as u32, rgb: &rgb }).unwrap();
+ let fitted = color::mul(&color::xyz_d50_to_prophoto(), &look.to_xyz);
+ for i in 0..3 {
+ for j in 0..3 {
+ assert!((fitted[i][j] - m[i][j]).abs() < 0.06, "{fitted:?} vs {m:?}");
+ }
+ }
+ let tone = look.tone.as_ref().unwrap();
+ for x in [0.02, 0.1, 0.3, 0.6] {
+ let want = 1.6 * x / (1.0 + 0.6 * x);
+ assert!((tone.eval(x) - want).abs() < 0.03, "f({x}) = {} vs {want}", tone.eval(x));
+ }
+ assert!(look.delta_e < 1.5 && look.delta_e < 0.2 * look.delta_e_fallback, "{look:?}");
+
+ // Developing with the look replaces the fallback warning by the note.
+ let d = crate::develop_sensor(&s, &DevelopOptions { camera_look: Some(look), ..wb_opts() }).unwrap();
+ assert!(d.warnings.iter().any(|w| w.contains("fitted to the camera's embedded JPEG")), "{:?}", d.warnings);
+ assert!(!d.warnings.iter().any(|w| w.contains("sRGB primaries")), "{:?}", d.warnings);
+ let plain = crate::develop_sensor(&s, &wb_opts()).unwrap();
+ assert!(plain.warnings.iter().any(|w| w.contains("sRGB primaries")));
+ assert_ne!(d.rgb, plain.rgb);
+ }
+
+ #[test]
+ fn follows_the_raw_orientation() {
+ let (w, h) = (480, 320);
+ let m = true_matrix();
+ let (mut s, rgb) = shot(w, h, &m);
+ // Stored sideways (orientation 6: rotate 90° clockwise to view); the JPEG is upright.
+ s.orientation = 6;
+ let mut up = vec![0u8; rgb.len()];
+ for y2 in 0..w {
+ for x2 in 0..h {
+ let (x, y) = source_xy(6, w, h, x2, y2);
+ let (o, i) = ((y2 * h + x2) * 3, (y * w + x) * 3);
+ up[o..o + 3].copy_from_slice(&rgb[i..i + 3]);
+ }
+ }
+ let look = fit_look(&s, &wb_opts(), &Reference { width: h as u32, height: w as u32, rgb: &up }).unwrap();
+ assert!(look.delta_e < 1.5, "{look:?}");
+ // The un-rotated JPEG has the wrong shape.
+ assert!(fit_look(&s, &wb_opts(), &Reference { width: w as u32, height: h as u32, rgb: &rgb }).is_err());
+ }
+
+ #[test]
+ fn unusable_references_keep_the_fallback() {
+ let (w, h) = (480, 320);
+ let (s, rgb) = shot(w, h, &true_matrix());
+ let opts = wb_opts();
+ let fit = |r: Reference| fit_look(&s, &opts, &r);
+ // Noise unrelated to the picture.
+ let mut seed = 7u32;
+ let noise: Vec<u8> = (0..rgb.len())
+ .map(|_| {
+ seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12345);
+ (seed >> 16) as u8
+ })
+ .collect();
+ assert!(fit(Reference { width: w as u32, height: h as u32, rgb: &noise }).is_err());
+ // A flat grey picture.
+ let grey = vec![118u8; rgb.len()];
+ assert!(fit(Reference { width: w as u32, height: h as u32, rgb: &grey }).is_err());
+ // Another shape, a short buffer, a tiny or empty image, absurd sizes.
+ assert!(fit(Reference { width: 320, height: 320, rgb: &rgb[..320 * 320 * 3] }).is_err());
+ assert!(fit(Reference { width: w as u32, height: h as u32, rgb: &rgb[..rgb.len() - 1] }).is_err());
+ assert!(fit(Reference { width: 12, height: 8, rgb: &rgb[..12 * 8 * 3] }).is_err());
+ assert!(fit(Reference { width: 0, height: 0, rgb: &[] }).is_err());
+ assert!(fit(Reference { width: u32::MAX, height: u32::MAX, rgb: &rgb }).is_err());
+ // A sensor whose crop lies outside its data, or a tiny one.
+ let mut bad = s.clone();
+ bad.crop.width += 10;
+ assert!(fit_look(&bad, &opts, &Reference { width: w as u32, height: h as u32, rgb: &rgb }).is_err());
+ let mut short = s.clone();
+ short.data.truncate(100);
+ assert!(fit_look(&short, &opts, &Reference { width: w as u32, height: h as u32, rgb: &rgb }).is_err());
+ }
+
+ #[test]
+ fn develop_ignores_an_unusable_look() {
+ let (s, _) = shot(64, 48, &true_matrix());
+ for to_xyz in [[[f64::NAN; 3]; 3], [[0.0; 3]; 3], [[1e9, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]] {
+ let look = CameraLook { to_xyz, tone: None, delta_e: 1.0, delta_e_fallback: 2.0 };
+ let d = crate::develop_sensor(&s, &DevelopOptions { camera_look: Some(look), ..wb_opts() }).unwrap();
+ assert!(d.warnings.iter().any(|w| w.contains("not usable")), "{:?}", d.warnings);
+ assert!(d.warnings.iter().any(|w| w.contains("sRGB primaries")), "{:?}", d.warnings);
+ }
+ }
+
+ #[test]
+ fn identity_curve_and_fallback_have_zero_error_on_their_own_rendering() {
+ let lab = Lab::new();
+ assert!(lab.delta_e([0.2, 0.3, 0.4], [0.2, 0.3, 0.4]) < 1e-12);
+ let w = lab.lab([1.0; 3]);
+ assert!((w[0] - 100.0).abs() < 1e-9 && w[1].abs() < 1e-9 && w[2].abs() < 1e-9, "{w:?}");
+ }
+}
diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rs
index bdf9e2461..400770603 100644
--- a/crates/raw/src/preview.rs
+++ b/crates/raw/src/preview.rs
@@ -49,6 +49,12 @@ fn candidate(data: &[u8], offset: usize, len: usize) -> Option<Preview<'_>> {
/// The largest embedded JPEG preview of a raw file (TIFF-based raws and RAF).
pub fn embedded_preview(bytes: &[u8]) -> Option<Preview<'_>> {
+ embedded_previews(bytes).into_iter().max_by_key(|p| u64::from(p.width) * u64::from(p.height))
+}
+
+/// Every embedded DCT-JPEG preview of a raw file, each stream once (cameras often store a
+/// full-size and a smaller rendering of the same picture).
+pub fn embedded_previews(bytes: &[u8]) -> Vec<Preview<'_>> {
let mut found: Vec<Preview> = Vec::new();
if bytes.starts_with(crate::raf::MAGIC) {
// RAF header: big-endian JPEG offset and length at bytes 84 and 88.
@@ -82,5 +88,12 @@ pub fn embedded_preview(bytes: &[u8]) -> Option<Preview<'_>> {
}
}
}
- found.into_iter().max_by_key(|p| u64::from(p.width) * u64::from(p.height))
+ let mut seen = Vec::new();
+ found.retain(|p| {
+ let key = (p.jpeg.as_ptr() as usize, p.jpeg.len());
+ let new = !seen.contains(&key);
+ seen.push(key);
+ new
+ });
+ found
}
diff --git a/crates/raw/tests/hostile.rs b/crates/raw/tests/hostile.rs
index d932181d0..2317aa5c5 100644
--- a/crates/raw/tests/hostile.rs
+++ b/crates/raw/tests/hostile.rs
@@ -77,11 +77,18 @@ fn samples() -> Vec<Vec<u8>> {
fn exercise(b: &[u8]) {
let _ = identify(b);
let _ = embedded_preview(b);
+ let _ = embedded_previews(b);
let opts = DevelopOptions { limits: Limits { max_alloc: 64 << 20, ..Limits::default() }, ..Default::default() };
if let Ok(s) = decode(b, &opts.limits) {
for m in [Demosaic::Bilinear, Demosaic::Ahd] {
let _ = develop_sensor(&s, &DevelopOptions { demosaic: m, ..opts.clone() });
}
+ // A colour fit against a gradient of the crop's (capped) shape, then a develop with it.
+ let (w, h) = (s.crop.width.min(256), s.crop.height.min(256));
+ let rgb: Vec<u8> = (0..w * h * 3).map(|i| (i * 7 % 251) as u8).collect();
+ if let Ok(look) = fit_look(&s, &opts, &Reference { width: w as u32, height: h as u32, rgb: &rgb }) {
+ let _ = develop_sensor(&s, &DevelopOptions { camera_look: Some(look), ..opts.clone() });
+ }
}
}
diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md
index c2b1d23f2..e8ff48fef 100644
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@ -437,7 +437,7 @@ filled bar. This extends UI reachability and does not claim Photoshop-authored s
| Colour management | Colour-managed canvas (document → monitor), embedded CMYK profiles, linear EXR/HDR, 16-bit float canvas | medium-high | Monitor profile follows only at launch. |
| Performance | 14k+ px on the GPU at ~⅓ the memory; adjustment preview 285 ms → 4–9 ms; font-size edits 297 ms → 4.6 ms; 2026-10-07: 30 MP TIFF open (banded, parallel strip/tile decode) Deflate 345 → 32 ms, LZW 428 → 43 ms, BigTIFF and every IFD readable; 2026-10-09: 4.2 MP Indexed Color, 256 colours, full-resolution CPU preview p50 3018 → 1061 ms (Ryzen AI 7 350, three measured runs; GPU upload excluded); 2026-10-10: Liquify 3500×2200, 800 px brush, visible 1:1 crop 3.20 → 3.63 ms p50 (5 runs) while refreshing ~9× as many pixels | medium-high on rasters | Complex layout documents still laggy (#125/#128); >16384 px GPU tiling in progress (#49). Liquify now displays source-resolution detail above 100% zoom; its ≤1 ms update target is not met (3.73 ms p95 on a Windows run; GPU upload excluded). Native Indexed Color previews run on one background worker with stale-result rejection; large palettes can still take about a second to compute. Web previews remain synchronous. |
| Stability | Never-crash lint series, crash guard, `panic_hunt` fuzzing in the gate | medium-high | No field crash data yet. |
-| Camera RAW | DNG, CR2, Sony ARW (lossless + compressed), Nikon NEF (lossless + lossy compressed), RW2, uncompressed ORF; 2026-10-09: uncompressed Fujifilm RAF, Bayer and X-Trans (edge-directed X-Trans demosaic; 26 MP X-Trans develop 306 ms on 12 cores) | medium | CR3, compressed RAF, Nikon "lossy after split" and calibrated colour for non-DNG cameras (no Fuji colour calibration: neutral fallback) still open (#50). |
+| Camera RAW | DNG, CR2, Sony ARW (lossless + compressed), Nikon NEF (lossless + lossy compressed), RW2, uncompressed ORF; 2026-10-09: uncompressed Fujifilm RAF, Bayer and X-Trans (edge-directed X-Trans demosaic; 26 MP X-Trans develop 306 ms on 12 cores) | medium | CR3, compressed RAF and Nikon "lossy after split" still open (#50). Non-DNG cameras have no calibration: their colour (matrix + tone curve) is fitted per file to the camera's embedded JPEG, with the neutral sRGB-primaries fallback when the fit doesn't clearly help (2026-10-08: 8 D3200 NEFs, mean ΔE vs the camera JPEG 11.6–26.0 → 1.0–7.5); measured per-model calibration still open. |
| AI / generative | none | ~0% | Deferred by decision (#41). |
| Ecosystem | Sandboxed WebAssembly plug-ins instead of .8BF; no ExtendScript/UXP/.atn; no Adobe Fonts/Libraries/cloud docs | low | By design for 8BF; scripting compatibility open. |
| Platforms | macOS (notarized), Windows, Linux (AppImage/deb/rpm/Flatpak bundle), web | medium-high | Flathub later (#173); Windows signing material pending. |