mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Camera raw colour fit: read a Sony Adobe RGB preview as Adobe RGB, not sRGB (#3760)
The per-file colour fit (`fit_preview_look`) converted the embedded JPEG to sRGB only when the JPEG carried an ICC profile, and otherwise read it as sRGB. A Sony body set to Adobe RGB writes no profile into its previews; it states the colour space only in the raw's EXIF (ColorSpace Uncalibrated with InteropIndex "R03", the DCF option file for Adobe RGB). The fit then targeted a desaturated, hue-shifted reference, and the developed raw came out that way. `photocraft_raw::embedded_preview_color_space` reads that EXIF (sRGB, Adobe RGB or unstated; never for a DNG, whose previews are the converter's), and `preview_profile` uses it when the preview has no ICC profile of its own. A preview's own profile still wins. LightCraft reads the same tags for the same reason (storytold/lightcraft#778). Measured on 19 private Sony ILCE-1M2 ARWs, all shot in Adobe RGB, against the camera's JPEG read as Adobe RGB (median CIE76 ΔE at 240 px): full-frame 400 mm shots against blue sky 5.6-7.0 → 1.5-2.4, their mean a* offset +4.3…+4.9 → +0.7…+1.1; every file improved, mean of the medians 4.9 → 2.2. Tests: `exif_colour_space_of_the_previews` (sRGB, Adobe RGB; R98, a missing interop IFD, other values, a DNG and junk are unstated) and `a_preview_without_a_profile_takes_the_raws_exif_colour_space` (fails without the EXIF fallback; the preview's own ICC profile wins). The hostile-input harness calls the new function. Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
81bff2aaa4
commit
e4e3f00f48
5 files changed
+120
-12
No files matched your search
+45
-11
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -74,7 +74,7 @@ pub use crate::develop::{DevelopOptions, Developed, RawInfo, WhiteBalance, devel
|
||||
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, 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};
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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] {
|
||||
|
||||
Reference in new issue
Block a user