PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Camera RAW: a measured Nikon D4 profile (image area, white level, colour matrix, tone curve) (#1475)
Unemarsd6aeb970ee30
diff --git a/crates/raw/src/cameras.rs b/crates/raw/src/cameras.rsnew file mode 100644index 000000000..0b57a98f5--- /dev/null+++ b/crates/raw/src/cameras.rs@@ -0,0 +1,167 @@+//! Camera profiles measured by PhotoCraft, for raw formats that carry no colour description of+//! their own (DNG does; Nikon NEF does not).+//!+//! Clean-room: every number here comes from our own measurements of the camera's output, never+//! from another converter's tables. A profile gives the image area inside the sensor data (the+//! camera's own JPEG crop), the saturation level, a ForwardMatrix (white-balanced camera → XYZ D50,+//! DNG semantics) and a default tone curve (like DNG ProfileToneCurve).+//!+//! **Nikon D4** (148 uncompressed NEFs from one body, 2023–2026, ISO 100–10000): the sensor data is+//! 4992 × 3292; the camera's full-size JPEG (4928 × 3280) sits at (8, 6), found by aligning the two+//! (2 px of optical black on the left, 50 + 8 on the right show as a purple stripe otherwise). The+//! data is already black-subtracted (the darkest image pixels reach 0). Green saturates at+//! 15546–15672 while red and blue reach 15687–16383, so one level of 15520 makes clipped+//! highlights white without shifting the white balance. Matrix and curve were fitted to the+//! camera's embedded JPEGs (Picture Control Standard, Active D-Lighting off; 52 frames, smooth+//! areas, 4 × 4 means): on 15 held-out frames the development is 7.2/255 per channel off the+//! camera's JPEG on average, against 34 without a profile.++use crate::color::{Calibration, ColorInfo, IDENTITY, Mat3};+use crate::sensor::{Rect, Sensor};++const D4_FORWARD: Mat3 = [[0.644598, 0.0703598, 0.249262], [0.342249, 0.518929, 0.138822], [0.0568265, -0.269568, 1.03795]];+const D4_COLOR: Mat3 = [[0.895936, -0.218092, -0.185988], [-1.09736, 2.06898, -0.0131889], [-0.26977, 0.393884, 0.687829]];+const D4_TONE: [[f32; 2]; 31] = [+ [0.005524272, 0.00285028],+ [0.006569503, 0.00357083],+ [0.0078125, 0.00447912],+ [0.009290681, 0.00605813],+ [0.01104854, 0.00841445],+ [0.01313901, 0.011536],+ [0.015625, 0.0165399],+ [0.01858136, 0.0230234],+ [0.02209709, 0.0319205],+ [0.02627801, 0.0434858],+ [0.03125, 0.0582138],+ [0.03716272, 0.0771963],+ [0.04419417, 0.0993894],+ [0.05255603, 0.125058],+ [0.0625, 0.157207],+ [0.07432544, 0.194929],+ [0.08838835, 0.236109],+ [0.1051121, 0.279155],+ [0.125, 0.329365],+ [0.1486509, 0.388405],+ [0.1767767, 0.457944],+ [0.2102241, 0.52456],+ [0.25, 0.598051],+ [0.2973018, 0.668794],+ [0.3535534, 0.749954],+ [0.4204482, 0.815443],+ [0.5, 0.870167],+ [0.5946036, 0.907869],+ [std::f32::consts::FRAC_1_SQRT_2, 0.939351],+ [0.8408964, 0.970567],+ [1.0, 1.0],+];++struct Profile {+ make: &'static str,+ model: &'static str,+ /// Sensor data size the profile was measured on.+ size: (usize, usize),+ /// The image area: x, y, width, height.+ crop: (usize, usize, usize, usize),+ white: f32,+ /// The black level is known to be 0 (the data is black-subtracted in camera).+ black_zero: bool,+ forward: Mat3,+ color: Mat3,+ tone: &'static [[f32; 2]],+}++const PROFILES: &[Profile] = &[Profile {+ make: "NIKON CORPORATION",+ model: "NIKON D4",+ size: (4992, 3292),+ crop: (8, 6, 4928, 3280),+ white: 15520.0,+ black_zero: true,+ forward: D4_FORWARD,+ color: D4_COLOR,+ tone: &D4_TONE,+}];++/// Applies the measured profile of the camera that made `s`, when there is one.+pub(crate) fn apply(s: &mut Sensor) {+ let (Some(make), Some(model)) = (s.make.as_deref(), s.model.as_deref()) else { return };+ let Some(p) = PROFILES.iter().find(|p| make.trim() == p.make && model.trim() == p.model && (s.width, s.height) == p.size) else { return };+ let (x, y, w, h) = p.crop;+ s.crop = Rect::new(x, y, w, h);+ s.white = [p.white; 3];+ if p.black_zero {+ s.warnings.retain(|w| !w.contains("black level not recorded"));+ }+ s.color = ColorInfo {+ // D50 daylight: the matrices are consistent at the camera's daylight neutral.+ calibrations: vec![Calibration { temperature: 5003.0, color_matrix: p.color, forward_matrix: Some(p.forward), camera_calibration: IDENTITY }],+ ..ColorInfo::default()+ };+ s.tone_curve = p.tone.to_vec();+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::RawFormat;+ use crate::color::apply as mat_apply;+ use crate::sensor::BlackLevels;++ fn nef(model: &str, width: usize, height: usize) -> Sensor {+ Sensor {+ format: RawFormat::Nef,+ make: Some("NIKON CORPORATION".into()),+ model: Some(model.into()),+ width,+ height,+ samples: 1,+ data: Vec::new(),+ cfa: None,+ linearization: None,+ black: BlackLevels::uniform(0.0),+ white: [16383.0; 3],+ active: Rect::new(0, 0, width, height),+ crop: Rect::new(0, 0, width, height),+ color: ColorInfo::default(),+ camera_wb: Some([2.0, 1.0, 1.4]),+ orientation: 1,+ baseline_exposure: 0.0,+ gain_maps: Vec::new(),+ tone_curve: Vec::new(),+ warnings: vec!["NEF: black level not recorded in a documented tag; assumed 0".into()],+ }+ }++ #[test]+ fn a_d4_nef_gets_its_crop_levels_matrix_and_curve() {+ let mut s = nef("NIKON D4", 4992, 3292);+ apply(&mut s);+ assert_eq!(s.crop, Rect::new(8, 6, 4928, 3280));+ assert_eq!(s.white, [15520.0; 3]);+ assert_eq!(s.color.calibrations.len(), 1);+ assert_eq!(s.color.calibrations[0].forward_matrix, Some(D4_FORWARD));+ assert_eq!(s.tone_curve.len(), D4_TONE.len());+ assert!(s.warnings.is_empty(), "the D4's black level is known: {:?}", s.warnings);+ // The profile gives a colour conversion for the as-shot white balance.+ assert!(s.color.balanced_to_xyz_d50([0.5, 1.0, 0.7]).is_some());+ }++ #[test]+ fn other_cameras_and_sizes_are_left_alone() {+ for (model, w, h) in [("NIKON D4S", 4992, 3292), ("NIKON D4", 2496, 1646), ("NIKON D800", 7424, 4924)] {+ let mut s = nef(model, w, h);+ apply(&mut s);+ assert_eq!(s.crop, Rect::new(0, 0, w, h), "{model} {w}x{h}");+ assert!(s.tone_curve.is_empty() && s.color.calibrations.is_empty() && s.white == [16383.0; 3]);+ assert_eq!(s.warnings.len(), 1);+ }+ }++ #[test]+ fn d4_forward_matrix_maps_neutral_to_d50_and_curve_reaches_white() {+ let n = mat_apply(&D4_FORWARD, [1.0; 3]);+ assert!((n[0] - 0.9642).abs() < 1e-3 && (n[1] - 1.0).abs() < 1e-3 && (n[2] - 0.8252).abs() < 1e-3, "{n:?}");+ assert!(D4_TONE.windows(2).all(|w| w[1][0] > w[0][0] && w[1][1] >= w[0][1]), "increasing");+ assert_eq!(D4_TONE.last().map(|p| (p[0], p[1])), Some((1.0, 1.0)));+ }+}diff --git a/crates/raw/src/cr2.rs b/crates/raw/src/cr2.rsindex 05424b503..ee9374719 100644--- a/crates/raw/src/cr2.rs+++ b/crates/raw/src/cr2.rs@@ -285,6 +285,7 @@ pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {orientation: t.tag_uint(&ifd0, tag::ORIENTATION).map(|o| o as u16).filter(|o| (1..=8).contains(o)).unwrap_or(1),baseline_exposure: 0.0,gain_maps: Vec::new(),+ tone_curve: Vec::new(),warnings,})}diff --git a/crates/raw/src/develop.rs b/crates/raw/src/develop.rsindex dbfd8649d..cbddb4e07 100644--- a/crates/raw/src/develop.rs+++ b/crates/raw/src/develop.rs@@ -274,9 +274,9 @@ pub fn develop_sensor(s: &Sensor, opts: &DevelopOptions) -> Result<Developed> {}}- // Camera → ProPhoto, exposure, gamma 1.8, 16 bits.+ // Camera → ProPhoto, exposure, the profile's tone curve, gamma 1.8, 16 bits.let mut out = vec![0u16; w * h * 3];- let lut = GammaLut::new();+ let lut = 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()];@@ -347,8 +347,20 @@ struct GammaLut {const GAMMA_STEPS: usize = 4096;impl GammaLut {+ #[cfg(test)]fn new() -> Self {- GammaLut { table: (0..=GAMMA_STEPS + 1).map(|i| ((i as f32 / GAMMA_STEPS as f32).min(1.0)).powf(2.0 / 1.8) * 65535.0).collect() }+ Self::with_curve(&[])+ }++ /// The gamma-1.8 encoding after a tone curve (see [`Sensor::tone_curve`]; empty: none).+ fn with_curve(curve: &[[f32; 2]]) -> Self {+ let table = (0..=GAMMA_STEPS + 1)+ .map(|i| {+ let s = (i as f32 / GAMMA_STEPS as f32).min(1.0);+ tone(curve, s * s).clamp(0.0, 1.0).powf(1.0 / 1.8) * 65535.0+ })+ .collect();+ GammaLut { table }}#[inline]@@ -362,6 +374,22 @@ impl GammaLut {}}+/// `curve` at linear `v`: linear interpolation between the points in log₂ of the input, a line+/// through 0 below the first point, the last output beyond the last.+fn tone(curve: &[[f32; 2]], v: f32) -> f32 {+ let (Some(first), Some(last)) = (curve.first(), curve.last()) else { return v };+ if v <= first[0] {+ return if first[0] > 0.0 { v * first[1] / first[0] } else { first[1] };+ }+ if v >= last[0] {+ return last[1];+ }+ let i = curve.partition_point(|p| p[0] <= v).clamp(1, curve.len() - 1);+ let ([x0, y0], [x1, y1]) = (curve[i - 1], curve[i]);+ let f = (v.log2() - x0.log2()) / (x1.log2() - x0.log2());+ y0 + (y1 - y0) * f+}+/// 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) {@@ -409,6 +437,22 @@ mod tests {assert_eq!(lut.encode(f32::NAN), 0);}+ #[test]+ fn tone_curve_is_folded_into_the_gamma_table() {+ let code = |v: f32| v.powf(1.0 / 1.8) * 65535.0;+ let lut = GammaLut::with_curve(&[[0.25, 0.5], [1.0, 1.0]]);+ let near = |got: u16, want: f32| (f32::from(got) - want).abs() <= 2.0;+ // On a point, between points (linear in log2 of the input), on the line through 0 below the first.+ assert!(near(lut.encode(0.25), code(0.5)));+ assert!(near(lut.encode(0.5), code(0.75)), "{} vs {}", lut.encode(0.5), code(0.75));+ assert!(near(lut.encode(0.125), code(0.25)));+ assert_eq!(lut.encode(0.0), 0);+ assert_eq!(lut.encode(1.0), 65535);+ assert!((0..1000).map(|i| lut.encode(i as f32 / 999.0)).collect::<Vec<_>>().windows(2).all(|w| w[1] >= w[0]));+ // No curve: the plain gamma 1.8.+ assert!(near(GammaLut::with_curve(&[]).encode(0.25), code(0.25)));+ }+#[test]fn orientations() {// 3×2 image, pixel value = index.diff --git a/crates/raw/src/dng.rs b/crates/raw/src/dng.rsindex f4f324dd4..2ffa1a6dc 100644--- a/crates/raw/src/dng.rs+++ b/crates/raw/src/dng.rs@@ -250,6 +250,7 @@ pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {orientation: t.tag_uint(&ifd0, tag::ORIENTATION).map(|o| o as u16).filter(|o| (1..=8).contains(o)).unwrap_or(1),baseline_exposure: if baseline_exposure.is_finite() { baseline_exposure.clamp(-10.0, 10.0) } else { 0.0 },gain_maps,+ tone_curve: Vec::new(),warnings,})}diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rsindex 7aaede47e..cbe8da500 100644--- a/crates/raw/src/lib.rs+++ b/crates/raw/src/lib.rs@@ -17,6 +17,9 @@//! orientation.//! * [`embedded_preview`] finds the camera's full-size JPEG preview, for//! formats whose sensor data is not decoded yet.+//! * 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).//!//! Decoded today: DNG (uncompressed and lossless-JPEG, strips and tiles, CFA//! and LinearRaw), CR2 (lossless JPEG with Canon slices), uncompressed or@@ -31,6 +34,7 @@#![forbid(unsafe_code)]#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]+mod cameras;mod color;mod cr2;mod demosaic;diff --git a/crates/raw/src/orf.rs b/crates/raw/src/orf.rsindex 84670fe6b..cc5236235 100644--- a/crates/raw/src/orf.rs+++ b/crates/raw/src/orf.rs@@ -149,6 +149,7 @@ pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {orientation: t.tag_uint(&raw, tag::ORIENTATION).map(|o| o as u16).filter(|o| (1..=8).contains(o)).unwrap_or(1),baseline_exposure: 0.0,gain_maps: Vec::new(),+ tone_curve: Vec::new(),warnings,})}diff --git a/crates/raw/src/rw2.rs b/crates/raw/src/rw2.rsindex 6f903140b..805baeb39 100644--- a/crates/raw/src/rw2.rs+++ b/crates/raw/src/rw2.rs@@ -169,6 +169,7 @@ pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {orientation: t.tag_uint(&ifd, tag::ORIENTATION).map(|o| o as u16).filter(|o| (1..=8).contains(o)).unwrap_or(1),baseline_exposure: 0.0,gain_maps: Vec::new(),+ tone_curve: Vec::new(),warnings,})}diff --git a/crates/raw/src/sensor.rs b/crates/raw/src/sensor.rsindex 26ff956b5..dc7ad52f3 100644--- a/crates/raw/src/sensor.rs+++ b/crates/raw/src/sensor.rs@@ -153,6 +153,10 @@ pub struct Sensor {pub baseline_exposure: f64,/// DNG OpcodeList2 gain maps (lens shading), applied to the normalized data.pub gain_maps: Vec<crate::opcodes::GainMap>,+ /// The camera profile's default tone curve (like DNG ProfileToneCurve): increasing `[input,+ /// output]` pairs in linear ProPhoto, applied per channel after the colour conversion and+ /// exposure. Below the first point the curve is a line through 0; empty: no curve.+ pub tone_curve: Vec<[f32; 2]>,pub warnings: Vec<String>,}diff --git a/crates/raw/src/tiffep.rs b/crates/raw/src/tiffep.rsindex 4d26be19b..0f014ea19 100644--- a/crates/raw/src/tiffep.rs+++ b/crates/raw/src/tiffep.rs@@ -193,7 +193,7 @@ pub(crate) fn decode(t: &Tiff, format: RawFormat, limits: &Limits) -> Result<Sen}}let ifd0 = t.ifd_at(t.first_ifd, 0);- Ok(Sensor {+ let mut sensor = Sensor {format,make,model,@@ -212,8 +212,11 @@ pub(crate) fn decode(t: &Tiff, format: RawFormat, limits: &Limits) -> Result<Senorientation: ifd0.and_then(|i| t.tag_uint(&i, tag::ORIENTATION)).map(|o| o as u16).filter(|o| (1..=8).contains(o)).unwrap_or(1),baseline_exposure: 0.0,gain_maps: Vec::new(),+ tone_curve: Vec::new(),warnings,- })+ };+ crate::cameras::apply(&mut sensor);+ Ok(sensor)}#[cfg(test)]