PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Camera raw colour fit: read a Sony Adobe RGB preview as Adobe RGB, not sRGB (#3760)
Dennise4e3f00f484a
diff --git a/crates/io/src/raw.rs b/crates/io/src/raw.rsindex 6ff2f5904..7e1f91648 100644--- a/crates/io/src/raw.rs+++ b/crates/io/src/raw.rs@@ -14,7 +14,7 @@ use std::sync::Arc;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 photocraft_raw::{CameraLook, DevelopOptions, Limits, PreviewColorSpace, RawError, Reference, Sensor, WhiteBalance};use crate::flat::image_to_document;use crate::{ImportResult, IoError};@@ -133,10 +133,23 @@ pub fn import_raw(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {/// 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;+/// The colour space of a raw's decoded preview when it is not sRGB: its own ICC profile, else the+/// one the raw's EXIF states (a Sony body set to Adobe RGB writes no profile into the JPEG).+/// `None` means sRGB.+fn preview_profile(raw: &[u8], icc: Option<&[u8]>) -> Result<Option<Cow<'static, Profile>>, String> {+ let src = match icc {+ Some(icc) => Cow::Owned(Profile::parse(icc).map_err(|e| format!("the preview's ICC profile does not parse: {e}"))?),+ None if photocraft_raw::embedded_preview_color_space(raw) == Some(PreviewColorSpace::AdobeRgb) => Cow::Borrowed(Builtin::AdobeRgbCompat.profile()),+ None => return Ok(None),+ };+ Ok((!src.same_colors(Builtin::Srgb.profile())).then_some(src))+}+/// 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.+/// converts it to sRGB when it is in another colour space ([`preview_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);@@ -152,15 +165,11 @@ pub fn fit_preview_look(raw: &[u8], sensor: &Sensor, opts: &DevelopOptions) -> R}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);- }+ if let Some(src) = preview_profile(raw, img.icc.as_deref())? {+ let t = Transform::new(&src, Builtin::Srgb.profile(), 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())}@@ -223,4 +232,29 @@ mod tests {assert_eq!(camera_name(None, Some("X")), "X");assert_eq!(camera_name(Some("Panasonic"), Some("DC-G9")), "Panasonic DC-G9");}++ /// A Sony body set to Adobe RGB says so only in the raw's EXIF (ColorSpace Uncalibrated, InteropIndex "R03"):+ /// its preview, which has no ICC profile, is read as Adobe RGB for the colour fit, not as sRGB.+ #[test]+ fn a_preview_without_a_profile_takes_the_raws_exif_colour_space() {+ use photocraft_raw::testgen::{TiffBuilder, Val};+ let raw = |color_space: u16, index: &str| {+ let mut t = TiffBuilder::default();+ let interop = t.ifd(vec![(0x0001, Val::Ascii(index.into()))]);+ let exif = t.ifd(vec![(0xA001, Val::Short(vec![color_space])), (0xA005, Val::Ifds(vec![interop]))]);+ t.chain = vec![t.ifd(vec![(271, Val::Ascii("SONY".into())), (34665, Val::Ifds(vec![exif]))])];+ t.build()+ };+ let adobe = raw(0xFFFF, "R03");+ let srgb = raw(1, "R98");+ assert!(preview_profile(&adobe, None).unwrap().unwrap().same_colors(Builtin::AdobeRgbCompat.profile()));+ assert!(preview_profile(&srgb, None).unwrap().is_none());+ assert!(preview_profile(b"not a raw", None).unwrap().is_none(), "unstated: sRGB");+ // the preview's own profile wins over the raw's EXIF+ let srgb_icc = Builtin::Srgb.profile().to_bytes().to_vec();+ assert!(preview_profile(&adobe, Some(srgb_icc.as_slice())).unwrap().is_none());+ let p3_icc = Builtin::DisplayP3.profile().to_bytes().to_vec();+ assert!(preview_profile(&srgb, Some(p3_icc.as_slice())).unwrap().unwrap().same_colors(Builtin::DisplayP3.profile()));+ assert!(preview_profile(&adobe, Some(b"not an ICC profile")).is_err());+ }}diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rsindex b9f4f1c6e..9a702f2dd 100644--- a/crates/raw/src/lib.rs+++ b/crates/raw/src/lib.rs@@ -74,7 +74,7 @@ pub use crate::develop::{DevelopOptions, Developed, RawInfo, WhiteBalance, develpub 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, embedded_previews};+pub use crate::preview::{Preview, PreviewColorSpace, embedded_preview, embedded_preview_color_space, embedded_previews};pub use crate::sensor::{BlackLevels, Cfa, Rect, Sensor};use crate::tiff::{Tiff, tag};diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rsindex 400770603..ec0c041fb 100644--- a/crates/raw/src/preview.rs+++ b/crates/raw/src/preview.rs@@ -97,3 +97,72 @@ pub fn embedded_previews(bytes: &[u8]) -> Vec<Preview<'_>> {});found}++/// The colour space a raw file states for its embedded previews, which carry no ICC profile of their own.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PreviewColorSpace {+ Srgb,+ 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.+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)?;+ match t.tag_uint(&exif, tag::COLOR_SPACE)? {+ 1 => Some(PreviewColorSpace::Srgb),+ 0xFFFF => {+ let interop = t.ifd_at(t.tag_uint(&exif, tag::INTEROP_IFD)? as usize, 0)?;+ t.raw(interop.get(tag::INTEROP_INDEX)?)?.starts_with(b"R03").then_some(PreviewColorSpace::AdobeRgb)+ }+ _ => None,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::testgen::{TiffBuilder, Val};++ /// A raw-like TIFF whose EXIF IFD has `color_space` and, when given, an Interoperability IFD with `index`.+ fn raw_with(color_space: Option<u16>, index: Option<&str>, dng: bool) -> Vec<u8> {+ let mut t = TiffBuilder::default();+ let mut exif = Vec::new();+ if let Some(cs) = color_space {+ exif.push((tag::COLOR_SPACE, Val::Short(vec![cs])));+ }+ if let Some(index) = index {+ let interop = t.ifd(vec![(tag::INTEROP_INDEX, Val::Ascii(index.into()))]);+ exif.push((tag::INTEROP_IFD, Val::Ifds(vec![interop])));+ }+ let exif = t.ifd(exif);+ let mut ifd0 = vec![(tag::MAKE, Val::Ascii("SONY".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()+ }++ #[test]+ fn exif_colour_space_of_the_previews() {+ assert_eq!(embedded_preview_color_space(&raw_with(Some(1), Some("R98"), false)), Some(PreviewColorSpace::Srgb));+ assert_eq!(embedded_preview_color_space(&raw_with(Some(0xFFFF), Some("R03"), false)), Some(PreviewColorSpace::AdobeRgb));+ for (cs, index) in [(Some(0xFFFF), Some("R98")), (Some(0xFFFF), None), (Some(2), Some("R03")), (None, Some("R03"))] {+ assert_eq!(embedded_preview_color_space(&raw_with(cs, index, false)), None, "{cs:?} {index:?}");+ }+ // a DNG's previews are the converter's, whatever the capture was+ assert_eq!(embedded_preview_color_space(&raw_with(Some(0xFFFF), Some("R03"), true)), None);+ for junk in [&b""[..], b"II*\0", b"II*\0\x08\0\0\0\xff\xff", b"not a tiff at all"] {+ assert_eq!(embedded_preview_color_space(junk), None);+ }+ }+}diff --git a/crates/raw/src/tiff.rs b/crates/raw/src/tiff.rsindex 17b9b8af7..671ab11fb 100644--- a/crates/raw/src/tiff.rs+++ b/crates/raw/src/tiff.rs@@ -36,6 +36,10 @@ pub(crate) mod tag {pub const EXIF_IFD: u16 = 34665;pub const EXIF_CFA_PATTERN: u16 = 41730;pub const MAKER_NOTE: u16 = 37500;+ pub const COLOR_SPACE: u16 = 40961;+ pub const INTEROP_IFD: u16 = 40965;+ /// In the Interoperability IFD.+ pub const INTEROP_INDEX: u16 = 1;pub const DNG_VERSION: u16 = 50706;pub const UNIQUE_CAMERA_MODEL: u16 = 50708;pub const CFA_PLANE_COLOR: u16 = 50710;diff --git a/crates/raw/tests/hostile.rs b/crates/raw/tests/hostile.rsindex dabe9ffe9..4b91f2f10 100644--- a/crates/raw/tests/hostile.rs+++ b/crates/raw/tests/hostile.rs@@ -88,6 +88,7 @@ fn exercise(b: &[u8]) {let _ = identify(b);let _ = embedded_preview(b);let _ = embedded_previews(b);+ let _ = embedded_preview_color_space(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] {