PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Raw: a Nikon maker note's ColorSpace sets the preview colour space (#5987)
Brian Torresf530a9840645
diff --git a/crates/raw/README.md b/crates/raw/README.mdindex bb4815a4f..6fe63bcd6 100644--- a/crates/raw/README.md+++ b/crates/raw/README.md@@ -119,7 +119,11 @@ out). One cell in three is held out: the look is used only when it shows the samthe 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'sembedded 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.+smallest preview at least 512 pixels long, fits and develops in one go. A preview without an ICC+profile is read in the colour space the raw states (`embedded_preview_color_space`): the EXIF+ColorSpace (a Sony body set to Adobe RGB writes Uncalibrated with Interoperability "R03"), else a+Nikon maker note's ColorSpace (0x001E; Nikon writes no EXIF ColorSpace), sRGB when the file says+nothing.Camera Raw's tuned import fits at the default exposure and as-shot white balance first,then applies the user's Exposure, Temperature and Tint to that same rendering.The D5100's measured image area is 4928 × 3264 at (8, 8) in a 4992 × 3280diff --git a/crates/raw/examples/rawinfo.rs b/crates/raw/examples/rawinfo.rsindex b71e2393b..6b1722b72 100644--- a/crates/raw/examples/rawinfo.rs+++ b/crates/raw/examples/rawinfo.rs@@ -9,7 +9,7 @@use std::time::Instant;-use photocraft_raw::{Demosaic, DevelopOptions, decode, develop_sensor, dump_structure, embedded_preview, identify};+use photocraft_raw::{Demosaic, DevelopOptions, decode, develop_sensor, dump_structure, embedded_preview, embedded_preview_color_space, identify};fn main() {let mut args = std::env::args().skip(1);@@ -76,7 +76,13 @@ fn main() {println!("{}", dump_structure(&bytes));}if let Some(p) = embedded_preview(&bytes) {- println!(" preview: {}x{} JPEG, {} bytes", p.width, p.height, p.jpeg.len());+ println!(+ " preview: {}x{} JPEG, {} bytes, colour space stated by the file: {:?}",+ p.width,+ p.height,+ p.jpeg.len(),+ embedded_preview_color_space(&bytes)+ );if let Some(dir) = png.as_ref().filter(|d| std::path::Path::new(d).is_dir()) {let stem = std::path::Path::new(&f).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();let _ = std::fs::write(format!("{dir}/{stem}.preview.jpg"), p.jpeg);diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rsindex d5dd01331..4a8139045 100644--- a/crates/raw/src/preview.rs+++ b/crates/raw/src/preview.rs@@ -107,18 +107,30 @@ pub enum PreviewColorSpace {AdobeRgb,}-/// The colour space the raw's EXIF gives for the camera's JPEG rendering, for a preview that declares none itself:-/// ColorSpace (0xA001) 1 = sRGB, or Uncalibrated (0xFFFF) with the Interoperability IFD's InteropIndex "R03", the-/// DCF option file for Adobe RGB (as a Sony body set to Adobe RGB writes; Exif and DCF specifications). `None` when-/// the file doesn't say, and for a DNG, whose EXIF describes the original capture while its previews are the-/// converter's. A preview's own ICC profile takes precedence over this.+/// Nikon maker note tag ColorSpace: 1 = sRGB, 2 = Adobe RGB (4 = BT.2100, which is not a preview colour space we+/// read), from Nikon's public tag documentation.+const NIKON_COLOR_SPACE: u16 = 0x001E;++/// The colour space the raw states for the camera's JPEG rendering, for a preview that declares none itself:+/// * the EXIF ColorSpace (0xA001) 1 = sRGB, or Uncalibrated (0xFFFF) with the Interoperability IFD's InteropIndex+/// "R03", the DCF option file for Adobe RGB (as a Sony body set to Adobe RGB writes; Exif and DCF specifications);+/// * else, where the EXIF doesn't decide, a Nikon maker note's ColorSpace (0x001E): Nikon bodies write no EXIF+/// ColorSpace, and say Adobe RGB only here.+///+/// `None` when the file doesn't say, and for a DNG, whose EXIF describes the original capture while its previews+/// are the converter's. A preview's own ICC profile takes precedence over this.pub fn embedded_preview_color_space(bytes: &[u8]) -> Option<PreviewColorSpace> {let t = Tiff::new(bytes)?;let ifd0 = t.ifd_at(t.first_ifd, 0)?;if ifd0.has(tag::DNG_VERSION) {return None;}- let exif = t.ifd_at(t.tag_uint(&ifd0, tag::EXIF_IFD)? as usize, 0)?;+ exif_color_space(&t, &ifd0).or_else(|| nikon_color_space(&t))+}++/// The colour space the EXIF IFD gives (see [`embedded_preview_color_space`]).+fn exif_color_space(t: &Tiff<'_>, ifd0: &crate::tiff::Ifd) -> Option<PreviewColorSpace> {+ let exif = t.ifd_at(t.tag_uint(ifd0, tag::EXIF_IFD)? as usize, 0)?;match t.tag_uint(&exif, tag::COLOR_SPACE)? {1 => Some(PreviewColorSpace::Srgb),0xFFFF => {@@ -129,6 +141,16 @@ pub fn embedded_preview_color_space(bytes: &[u8]) -> Option<PreviewColorSpace> {}}+/// The colour space a Nikon maker note gives.+fn nikon_color_space(t: &Tiff<'_>) -> Option<PreviewColorSpace> {+ let (note, ifd) = crate::tiffep::nikon_maker_note(t, &t.all_ifds())?;+ match note.tag_uint(&ifd, NIKON_COLOR_SPACE)? {+ 1 => Some(PreviewColorSpace::Srgb),+ 2 => Some(PreviewColorSpace::AdobeRgb),+ _ => None,+ }+}+#[cfg(test)]mod tests {use super::*;@@ -167,4 +189,95 @@ mod tests {assert_eq!(embedded_preview_color_space(junk), None);}}++ /// The maker note's embedded TIFF stream (`ifd` entries, in the given byte order) behind `header`.+ fn maker_note(header: &[u8], tags: Vec<(u16, Val)>, big_endian: bool) -> Vec<u8> {+ let mut note = TiffBuilder { big_endian, ..Default::default() };+ let ifd = note.ifd(tags);+ note.chain = vec![ifd];+ let mut maker = header.to_vec();+ maker.extend(note.build());+ maker+ }++ /// A raw whose EXIF IFD holds the entries `exif` makes (it may add directories to the builder) and a maker note.+ fn raw_with_note(maker: Vec<u8>, exif: impl FnOnce(&mut TiffBuilder) -> Vec<(u16, Val)>, dng: bool) -> Vec<u8> {+ let mut t = TiffBuilder::default();+ let mut exif = exif(&mut t);+ exif.push((tag::MAKER_NOTE, Val::Undefined(maker)));+ let exif = t.ifd(exif);+ let mut ifd0 = vec![(tag::MAKE, Val::Ascii("NIKON CORPORATION".into())), (tag::EXIF_IFD, Val::Ifds(vec![exif]))];+ if dng {+ ifd0.push((tag::DNG_VERSION, Val::Byte(vec![1, 6, 0, 0])));+ }+ t.chain = vec![t.ifd(ifd0)];+ t.build()+ }++ const NIKON: &[u8] = b"Nikon\0\x02\x10\0\0";++ /// A Nikon raw whose maker note has ColorSpace `color_space` (when given) and whose EXIF IFD holds `exif`.+ fn nikon_raw(color_space: Option<u16>, exif: impl FnOnce(&mut TiffBuilder) -> Vec<(u16, Val)>, big_endian: bool) -> Vec<u8> {+ let tags = color_space.map(|cs| (NIKON_COLOR_SPACE, Val::Short(vec![cs]))).into_iter().chain([(0x0002, Val::Ascii("200".into()))]).collect();+ raw_with_note(maker_note(NIKON, tags, big_endian), exif, false)+ }++ /// EXIF entries for a preview in Adobe RGB the way a Sony body writes it: Uncalibrated, Interoperability "R03".+ fn exif_r03(t: &mut TiffBuilder) -> Vec<(u16, Val)> {+ let interop = t.ifd(vec![(tag::INTEROP_INDEX, Val::Ascii("R03".into()))]);+ vec![(tag::COLOR_SPACE, Val::Short(vec![0xFFFF])), (tag::INTEROP_IFD, Val::Ifds(vec![interop]))]+ }++ /// Nikon bodies write no EXIF ColorSpace; the maker note's ColorSpace (1 sRGB, 2 Adobe RGB) is+ /// what says their JPEG previews are Adobe RGB.+ #[test]+ fn nikon_maker_note_colour_space_of_the_previews() {+ for big_endian in [false, true] {+ assert_eq!(embedded_preview_color_space(&nikon_raw(Some(2), |_| vec![], big_endian)), Some(PreviewColorSpace::AdobeRgb), "be {big_endian}");+ assert_eq!(embedded_preview_color_space(&nikon_raw(Some(1), |_| vec![], big_endian)), Some(PreviewColorSpace::Srgb), "be {big_endian}");+ }+ // BT.2100 (4), unknown values, a note without the tag+ for cs in [Some(4), Some(0), Some(3), Some(0xFFFF), None] {+ assert_eq!(embedded_preview_color_space(&nikon_raw(cs, |_| vec![], false)), None, "{cs:?}");+ }+ }++ /// The EXIF IFD, when it states a colour space, comes before the maker note; when it does not decide, the+ /// maker note does.+ #[test]+ fn exif_colour_space_comes_before_the_nikon_maker_note() {+ // EXIF says sRGB, the note Adobe RGB: EXIF wins.+ let raw = nikon_raw(Some(2), |_| vec![(tag::COLOR_SPACE, Val::Short(vec![1]))], false);+ assert_eq!(embedded_preview_color_space(&raw), Some(PreviewColorSpace::Srgb));+ // EXIF says Adobe RGB (R03), the note sRGB: EXIF wins.+ assert_eq!(embedded_preview_color_space(&nikon_raw(Some(1), exif_r03, false)), Some(PreviewColorSpace::AdobeRgb));+ // EXIF says Uncalibrated without R03, which decides nothing: the note does.+ let raw = nikon_raw(Some(2), |_| vec![(tag::COLOR_SPACE, Val::Short(vec![0xFFFF]))], false);+ assert_eq!(embedded_preview_color_space(&raw), Some(PreviewColorSpace::AdobeRgb));+ }++ /// Only a Nikon maker note is read, and not for a DNG, whose previews are the converter's.+ #[test]+ fn only_a_nikon_maker_note_of_a_non_dng_is_read() {+ let tags = || vec![(NIKON_COLOR_SPACE, Val::Short(vec![2]))];+ assert_eq!(embedded_preview_color_space(&raw_with_note(maker_note(NIKON, tags(), false), |_| vec![], false)), Some(PreviewColorSpace::AdobeRgb));+ assert_eq!(embedded_preview_color_space(&raw_with_note(maker_note(NIKON, tags(), false), |_| vec![], true)), None);+ for header in [&b"OLYMPUS\0II\x03\0"[..], b"SONY DSC \0\0\0", b"Nikon", b""] {+ assert_eq!(embedded_preview_color_space(&raw_with_note(maker_note(header, tags(), false), |_| vec![], false)), None, "{header:?}");+ }+ }++ /// A maker note that is cut short or points outside the file states nothing, and never panics.+ #[test]+ fn a_damaged_nikon_maker_note_states_nothing() {+ let good = maker_note(NIKON, vec![(NIKON_COLOR_SPACE, Val::Short(vec![2]))], false);+ assert_eq!(embedded_preview_color_space(&raw_with_note(good.clone(), |_| vec![], false)), Some(PreviewColorSpace::AdobeRgb));+ for len in 0..good.len() {+ let _ = embedded_preview_color_space(&raw_with_note(good[..len].to_vec(), |_| vec![], false));+ }+ // the embedded TIFF's first-IFD offset (bytes 14..18 of the note) points outside the file+ let mut wild = good.clone();+ wild[14..18].copy_from_slice(&[0xFF; 4]);+ assert_eq!(embedded_preview_color_space(&raw_with_note(wild, |_| vec![], false)), None);+ }}diff --git a/crates/raw/src/tiffep.rs b/crates/raw/src/tiffep.rsindex 25befbdde..d15b64560 100644--- a/crates/raw/src/tiffep.rs+++ b/crates/raw/src/tiffep.rs@@ -66,7 +66,7 @@ pub(crate) fn cfa(t: &Tiff, raw: &Ifd, ifds: &[Ifd]) -> Option<Cfa> {/// Nikon maker note: "Nikon\0", version, then an embedded TIFF header whose/// offsets are relative to itself.-fn nikon_maker_note<'a>(t: &Tiff<'a>, ifds: &[Ifd]) -> Option<(Tiff<'a>, Ifd)> {+pub(crate) fn nikon_maker_note<'a>(t: &Tiff<'a>, ifds: &[Ifd]) -> Option<(Tiff<'a>, Ifd)> {let e = ifds.iter().find_map(|i| i.get(tag::MAKER_NOTE).copied())?;let b = t.raw(&e)?;if !b.starts_with(b"Nikon\0") {diff --git a/crates/raw/tests/hostile.rs b/crates/raw/tests/hostile.rsindex 3212d554e..e376f23e9 100644--- a/crates/raw/tests/hostile.rs+++ b/crates/raw/tests/hostile.rs@@ -1,9 +1,32 @@//! Truncated and corrupted raw files must fail cleanly, never panic, and//! never allocate beyond the limits.-use photocraft_raw::testgen::{Cr2Spec, DngSpec, DngStorage, RafPacking, RafSpec, XTRANS, mosaic, mosaic_cfa, orf, rw2, scene, sony_craw, tiff_ep};+use photocraft_raw::testgen::{+ Cr2Spec, DngSpec, DngStorage, RafPacking, RafSpec, Val, XTRANS, mosaic, mosaic_cfa, nef_compressed, orf, rw2, scene, sony_craw, tiff_ep,+};use photocraft_raw::*;+/// 12-bit samples packed little-endian, `w` per row, rows byte-aligned (Nikon's packed NEF layout).+fn pack12(values: &[u16], w: usize) -> Vec<u8> {+ let mut out = Vec::new();+ for row in values.chunks_exact(w) {+ let (mut acc, mut have) = (0u32, 0u32);+ for v in row {+ acc |= u32::from(*v) << have;+ have += 12;+ while have >= 8 {+ out.push(acc as u8);+ acc >>= 8;+ have -= 8;+ }+ }+ if have > 0 {+ out.push(acc as u8);+ }+ }+ out+}+/// Losslessly encodes 16-bit RGB as a JPEG XL codestream.fn jxl_rgb16(rgb: &[u16], w: usize, h: usize) -> Vec<u8> {use zune_core::{bit_depth::BitDepth, colorspace::ColorSpace, options::EncoderOptions};@@ -84,6 +107,8 @@ fn samples() -> Vec<Vec<u8>> {.build(),);out.push(tiff_ep("NIKON", w, h, &cfa, [0, 1, 1, 2], 12, vec![]));+ // A Nikon NEF (packed 12-bit) whose maker note says the previews are Adobe RGB (ColorSpace 0x001E).+ out.push(nef_compressed(w, h, 12, pack12(&cfa, w), [0, 1, 1, 2], false, vec![(0x0093, Val::Short(vec![6])), (0x001E, Val::Short(vec![2]))]));let codes = mosaic(&scene(64, 6), 64, [0, 1, 1, 2], 256, 1900);out.push(sony_craw(64, 6, &codes, [8000, 10400, 12900, 14100]));out.push(rw2(30, 8, &mosaic(&scene(30, 8), 30, [0, 1, 1, 2], 128, 4095), 12));@@ -126,6 +151,12 @@ fn originals_develop() {}}+#[test]+fn a_seed_states_a_maker_note_colour_space() {+ // The truncation and corruption tests below only exercise the maker-note reader if a seed has one.+ assert!(samples().iter().any(|b| embedded_preview_color_space(b) == Some(PreviewColorSpace::AdobeRgb)));+}+#[test]fn every_truncation_fails_cleanly() {for b in samples() {diff --git a/docs/gaps.md b/docs/gaps.mdindex 9b281d678..6887d7f05 100644--- a/docs/gaps.md+++ b/docs/gaps.md@@ -137,6 +137,11 @@ what an agent can't finish alone.tuning retains the fitted look and applies user gains afterwards. Three D5100 NEFsestablish a guarded 4928 × 3264 image area. This is an estimated rendering, not ameasured D5100 colour calibration; [validation](nikon-nef-development.md).+- **Progress (2026-10-14):** a Nikon NEF's embedded preview takes its colour space from the+ maker note's ColorSpace (0x001E: 1 sRGB, 2 Adobe RGB) when the EXIF states none, so the+ colour fit reads an Adobe RGB preview as Adobe RGB (49 of the 291 public Nikon samples;+ Nikon writes no EXIF ColorSpace); `crates/raw/src/preview.rs`. A raw's preview-fallback+ document is still opened untagged.- **Progress (2026-10-13):** the D90's image area (4288 × 2848 at (10, 10) in a4352 × 2868 plane) is measured by aligning the decoded plane with the camera's ownJPEG, so a D90 NEF opens on the camera's frame instead of the uncropped sensor plane;@@ -297,6 +302,7 @@ what an agent can't finish alone.| 2026-10-16 | minor | G7: Content-Aware Move's live preview covers every selection the command takes (over 256 × 256: a coarse result solved scaled down, then the exact one); TOOL-213-4 done (#6680) || 2026-10-15 | minor | G9: Save in Background off saves in the foreground under a modal progress dialog (#6207); preferences that do nothing 25 → 24 of 169 || 2026-10-14 | minor | G1: a PSD smart object's filter mask shows when the file opens (Photoshop stores the filtered pixels unmasked); export stores them that way too; Photoshop-oracle floor 185 → 188 of 258 |+| 2026-10-14 | minor | G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E); gap remains open || 2026-10-13 | minor | G14: D90 image area measured (4288 × 2848 at (10, 10)); gap remains open || 2026-10-14 | minor | Corpus floors raised to the measured results of the CMYK, Lab, 32-bit, Levels, Threshold, Posterize, feather and pass-through fixes landed together: Photoshop-authored 165 → 185 of 258, io 146 → 148 of 170, psd-tools 242 → 249 of 309 || 2026-10-13 | minor | G1: generated large-file fixtures (20 MP, 150 layers, 2 GB PSD, 4.38 GB PSB) round-trip in io tests/large_files.rs; the 4.38 GB PSB opens on Windows through io (#375 evidence); FILE-216-2 done (#5107) |