PhotoCraft: An open-source, photo editor written by scratch in pure Rust
TIFF: read and write CIE L*a*b* (CIELab, ICCLab); Lab documents stay Lab (#4949)
Gert Pellin - GPE1a4f86795887
diff --git a/crates/codecs/src/codecs/tiff.rs b/crates/codecs/src/codecs/tiff.rsindex 5e09a68ec..9528fec9c 100644--- a/crates/codecs/src/codecs/tiff.rs+++ b/crates/codecs/src/codecs/tiff.rs@@ -532,17 +532,24 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr} else {None};+ // CIE L*a*b*: CIELab (8; a* and b* signed) and ICCLab (9; a* and b* offset) are handed to the+ // `tiff` crate as RGB, then labelled Lab with a* and b* in PhotoCraft's encoding+ // (`convert_ab`).+ let lab = matches!(photometric, 8 | 9);+ if lab && (spp < 3 || !matches!(src, Src::U8 | Src::U16)) {+ return Err(CodecError::unsupported(F, format!("Lab image with {spp} samples of {bits} bits")));+ }// TIFF 6.0 lets any extra sample be the alpha (#1349). For RGB and CMYK the `tiff` crate// returns the alpha only when it is the first extra sample: otherwise it is asked for every// sample (as multiband gray) and the colour and alpha samples are picked here. An alpha// position past the samples the file has is ignored.let color = match photometric {- 2 => 3,+ 2 | 8 | 9 => 3,5 => 4,_ => 1,};let alpha_at = extra.iter().position(|&e| e == 1 || e == 2).filter(|&a| (color + a as u64) < spp);- let all_samples = palette.is_none() && matches!(photometric, 2 | 5) && alpha_at.is_some_and(|a| a > 0);+ let all_samples = palette.is_none() && matches!(photometric, 2 | 5 | 8 | 9) && alpha_at.is_some_and(|a| a > 0);let mut patches: Vec<(u64, Vec<u8>)> = Vec::new();let encode_u = |v: u64, len: usize| -> Vec<u8> {let b = if f.le { v.to_le_bytes() } else { v.to_be_bytes() };@@ -557,14 +564,14 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr// The directory is seen as the last of its chain: the chain was walked already, and a// cycle through it must not fail this page.patches.push((dir.next_at, vec![0; if f.big { 8 } else { 4 }]));- if invert || palette.is_some() || all_samples {+ if invert || palette.is_some() || all_samples || lab {let e = photometric_entry.ok_or_else(|| err("missing PhotometricInterpretation"))?;let len = match e.ty {3 if e.count == 1 => 2,4 if e.count == 1 => 4,_ => return Err(err("malformed PhotometricInterpretation")),};- patches.push((e.value_at, encode_u(1, len)));+ patches.push((e.value_at, encode_u(if lab && !all_samples { 2 } else { 1 }, len)));}let tl = {@@ -585,7 +592,7 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecEr_ if palette.is_some() => (ChannelLayout::Rgb, 1),tiff::ColorType::Gray(_) => (ChannelLayout::Gray, 1),tiff::ColorType::Multiband { num_samples, .. } if all_samples => {- (if photometric == 2 { ChannelLayout::Rgba } else { ChannelLayout::CmykA }, usize::from(num_samples))+ (if photometric == 5 { ChannelLayout::CmykA } else { ChannelLayout::Rgba }, usize::from(num_samples))}tiff::ColorType::Multiband { num_samples, .. } if photometric <= 1 => {(if gray_alpha { ChannelLayout::GrayA } else { ChannelLayout::Gray }, usize::from(num_samples))@@ -596,6 +603,12 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecErtiff::ColorType::CMYKA(_) => (ChannelLayout::CmykA, 5),other => return Err(CodecError::unsupported(F, format!("colour type {other:?}"))),};+ let out_layout = match out_layout {+ ChannelLayout::Rgb if lab => ChannelLayout::Lab,+ ChannelLayout::Rgba if lab => ChannelLayout::LabA,+ _ if lab => return Err(err("Lab image that does not read as three colour samples")),+ l => l,+ };let chunk_spp = if planar { 1 } else { chunk_spp };// The sample (chunky) or plane (planar) that holds the alpha: the colour samples come first.let alpha_sample = out_layout.color_channels() + alpha_at.unwrap_or(0);@@ -676,6 +689,9 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecErif tally.decoded == 0 && tally.missing > 0 {return Err(err("the image data is missing (cut off or past the end of the file)"));}+ if lab {+ convert_ab(&mut data, out_layout.channels(), out, photometric == 8, false);+ }let mut img = Image::from_raw(w, h, out_layout, out, data)?;if tally.missing > 0 {img.warnings.push(DecodeWarning::Truncated { format: F });@@ -683,6 +699,35 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result<Image, CodecErOk(img)}+/// The a* and b* samples (1 and 2 of every pixel) of a Lab image between the file's encoding and+/// PhotoCraft's (8 bits: `a + 128`; 16 bits: `(a + 128) · 257`). In the file, CIELab holds them+/// signed (8 bits: `a`; 16 bits: `a · 256`) and ICCLab offset (8 bits: `a + 128`; 16 bits:+/// `(a + 128) · 256`). `to_file` picks the direction; samples are native-endian.+fn convert_ab(data: &mut [u8], channels: usize, sample: SampleType, signed: bool, to_file: bool) {+ match sample {+ SampleType::U8 if signed => data.chunks_exact_mut(channels).for_each(|px| {+ px[1] ^= 0x80;+ px[2] ^= 0x80;+ }),+ SampleType::U16 => data.chunks_exact_mut(channels * 2).for_each(|px| {+ for c in [1, 2] {+ let v = u16::from_ne_bytes([px[2 * c], px[2 * c + 1]]);+ // The file's value as `a · 256` (signed) and back.+ let file_a256 = |v: u16| if signed { f64::from(v as i16) } else { f64::from(v) - 32768.0 };+ let out = if to_file {+ let a256 = (f64::from(v) - 32896.0) * 256.0 / 257.0;+ let a256 = a256.round().clamp(-32768.0, 32767.0);+ if signed { (a256 as i16) as u16 } else { (a256 + 32768.0) as u16 }+ } else {+ (file_a256(v) * 257.0 / 256.0 + 32896.0).round().clamp(0.0, 65535.0) as u16+ };+ px[2 * c..2 * c + 2].copy_from_slice(&out.to_ne_bytes());+ }+ }),+ _ => {}+ }+}+/// A zero-filled buffer, allocated fallibly. On native targets the zeroing (and the first/// touch of every page, which dominates on a fresh multi-hundred-megabyte buffer) is spread over/// all cores.@@ -1021,6 +1066,11 @@ custom_colortype!(GrayA16, u16, PI::BlackIsZero, &[16, 16], &[SampleFormat::Uintcustom_colortype!(GrayA32F, f32, PI::BlackIsZero, &[32, 32], &[SampleFormat::IEEEFP; 2], float);custom_colortype!(CmykA16, u16, PI::CMYK, &[16; 5], &[SampleFormat::Uint; 5], int);custom_colortype!(CmykA32F, f32, PI::CMYK, &[32; 5], &[SampleFormat::IEEEFP; 5], float);+// CIELab as Photoshop writes it: a* and b* signed, the sample format left unsigned.+custom_colortype!(Lab8, u8, PI::CIELab, &[8; 3], &[SampleFormat::Uint; 3], int);+custom_colortype!(Lab16, u16, PI::CIELab, &[16; 3], &[SampleFormat::Uint; 3], int);+custom_colortype!(LabA8, u8, PI::CIELab, &[8; 4], &[SampleFormat::Uint; 4], int);+custom_colortype!(LabA16, u16, PI::CIELab, &[16; 4], &[SampleFormat::Uint; 4], int);struct TagSet<'a> {icc: Option<&'a [u8]>,@@ -1119,6 +1169,20 @@ fn write_image<K: TiffKind>(enc: &mut TiffEncoder<&mut Cursor<Vec<u8>>, K>, img:(L::CmykA, S::U8) => write_one::<colortype::CMYKA8, K>(enc, w, h, d8, tags),(L::CmykA, S::U16) => write_one::<CmykA16, K>(enc, w, h, &u16s(), tags),(L::CmykA, S::F32) => write_one::<CmykA32F, K>(enc, w, h, &f32s(), tags),+ (L::Lab | L::LabA, _) => {+ // CIELab has no float form: 32-bit Lab is written with 16 bits.+ let sample = if img.sample_type() == S::U8 { S::U8 } else { S::U16 };+ let mut file = img.convert(img.layout(), sample);+ let channels = file.layout().channels();+ convert_ab(file.data_mut(), channels, sample, true, true);+ let u16s = || file.to_u16_samples().unwrap_or_default();+ match (file.layout(), sample) {+ (L::Lab, S::U8) => write_one::<Lab8, K>(enc, w, h, file.data(), tags),+ (L::Lab, _) => write_one::<Lab16, K>(enc, w, h, &u16s(), tags),+ (_, S::U8) => write_one::<LabA8, K>(enc, w, h, file.data(), tags),+ _ => write_one::<LabA16, K>(enc, w, h, &u16s(), tags),+ }+ }(l, s) => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unsupported {l:?} {s:?}")).into()),}}diff --git a/crates/codecs/src/fidelity.rs b/crates/codecs/src/fidelity.rsindex 08153dfba..594735edb 100644--- a/crates/codecs/src/fidelity.rs+++ b/crates/codecs/src/fidelity.rs@@ -30,6 +30,10 @@ pub enum FidelityWarning {CmykConverted {to: ChannelLayout,},+ /// L*a*b* data will be converted to another model (sRGB, D50 to D65).+ LabConverted {+ to: ChannelLayout,+ },/// Colour data will be reduced to grayscale.ColorToGray,/// The image will be quantized to a 256-colour palette.@@ -84,6 +88,7 @@ impl fmt::Display for FidelityWarning {CmykConverted { to } => {write!(f, "CMYK will be converted to {to:?} (not colour-managed)")}+ LabConverted { to } => write!(f, "Lab will be converted to {to:?} (sRGB)"),ColorToGray => write!(f, "colour will be converted to grayscale"),PaletteQuantized => write!(f, "colours will be quantized to a 256-colour palette"),LossyCompression => write!(f, "lossy compression"),@@ -129,8 +134,8 @@ fn pick_layout(src: ChannelLayout, layouts: &[ChannelLayout], alpha: bool) -> Chif layouts.contains(&cand) {return cand;}- // CMYK falls back to RGB; gray expands to RGB.- if cand.is_cmyk() || cand.is_gray() {+ // CMYK and Lab fall back to RGB; gray expands to RGB.+ if cand.is_cmyk() || cand.is_lab() || cand.is_gray() {cand = if cand.has_alpha() { ChannelLayout::Rgba } else { ChannelLayout::Rgb };}if layouts.contains(&cand) {@@ -158,6 +163,8 @@ pub(crate) fn plan(image: &Image, format: Format, opts: &EncodeOptions) -> Planlayout: if layout == ChannelLayout::GrayA { ChannelLayout::Gray } else { pick_layout(layout, c.layouts, c.alpha) },sample: crate::codecs::dpx::plan_sample(opts.dpx_bits, sample),},+ // CIELab has no float form: float Lab is written with 16 bits.+ Format::Tiff if layout.is_lab() && sample.is_float() => Plan { layout: pick_layout(layout, c.layouts, c.alpha), sample: SampleType::U16 },_ => Plan { layout: pick_layout(layout, c.layouts, c.alpha), sample: pick_sample(sample, c.depths) },}}@@ -210,6 +217,9 @@ pub fn fidelity_warnings_with(image: &Image, format: Format, opts: &EncodeOptionif sl.is_cmyk() && !p.layout.is_cmyk() {w.push(W::CmykConverted { to: p.layout });}+ if sl.is_lab() && !p.layout.is_lab() {+ w.push(W::LabConverted { to: p.layout });+ }if !sl.is_gray() && p.layout.is_gray() {w.push(W::ColorToGray);}diff --git a/crates/codecs/src/format.rs b/crates/codecs/src/format.rsindex 2d330cc97..fa2e1e6cb 100644--- a/crates/codecs/src/format.rs+++ b/crates/codecs/src/format.rs@@ -99,6 +99,8 @@ use SampleType as S;const RGB_GRAY: &[ChannelLayout] = &[L::Gray, L::GrayA, L::Rgb, L::Rgba];const ALL_LAYOUTS: &[ChannelLayout] = &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L::Cmyk, L::CmykA];+/// TIFF also stores CIE L*a*b* (CIELab).+const TIFF_LAYOUTS: &[ChannelLayout] = &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L::Cmyk, L::CmykA, L::Lab, L::LabA];impl Format {/// Every format known to the crate (enabled or not).@@ -244,7 +246,7 @@ pub fn caps(format: Format) -> FormatCaps {FormatCaps { depths: &[S::U8, S::U16], layouts: RGB_GRAY, icc: true, exif: true, xmp: true, dpi: true, text: true, animation: true, ..base }}Format::Jpeg => FormatCaps { layouts: &[L::Gray, L::Rgb, L::Cmyk], alpha: false, icc: true, exif: true, xmp: true, dpi: true, lossy: true, ..base },- Format::Tiff => FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: ALL_LAYOUTS, icc: true, exif: true, xmp: true, dpi: true, text: true, ..base },+ Format::Tiff => FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: TIFF_LAYOUTS, icc: true, exif: true, xmp: true, dpi: true, text: true, ..base },Format::WebP => FormatCaps { icc: true, exif: true, xmp: true, animation: true, ..base },Format::Gif => FormatCaps { layouts: &[L::Rgba], animation: true, lossy: true, ..base },Format::Bmp => base,diff --git a/crates/codecs/src/image.rs b/crates/codecs/src/image.rsindex db59d4fa6..98168d59d 100644--- a/crates/codecs/src/image.rs+++ b/crates/codecs/src/image.rs@@ -21,19 +21,31 @@ pub enum ChannelLayout {/// Ink amounts, `0 = no ink`, `max = full ink` (not Adobe-inverted).Cmyk,CmykA,+ /// CIE L*a*b* (D50), as PhotoCraft's Lab documents hold it: L* 0..100 as 0..1, a* and b*+ /// −128..127 as `(v + 128) / 255` (Photoshop's unsigned encoding).+ Lab,+ LabA,}impl ChannelLayout {- pub const ALL: [ChannelLayout; 6] =- [ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb, ChannelLayout::Rgba, ChannelLayout::Cmyk, ChannelLayout::CmykA];+ pub const ALL: [ChannelLayout; 8] = [+ ChannelLayout::Gray,+ ChannelLayout::GrayA,+ ChannelLayout::Rgb,+ ChannelLayout::Rgba,+ ChannelLayout::Cmyk,+ ChannelLayout::CmykA,+ ChannelLayout::Lab,+ ChannelLayout::LabA,+ ];/// Total number of channels including alpha.pub const fn channels(self) -> usize {match self {ChannelLayout::Gray => 1,ChannelLayout::GrayA => 2,- ChannelLayout::Rgb => 3,- ChannelLayout::Rgba | ChannelLayout::Cmyk => 4,+ ChannelLayout::Rgb | ChannelLayout::Lab => 3,+ ChannelLayout::Rgba | ChannelLayout::Cmyk | ChannelLayout::LabA => 4,ChannelLayout::CmykA => 5,}}@@ -44,7 +56,7 @@ impl ChannelLayout {}pub const fn has_alpha(self) -> bool {- matches!(self, ChannelLayout::GrayA | ChannelLayout::Rgba | ChannelLayout::CmykA)+ matches!(self, ChannelLayout::GrayA | ChannelLayout::Rgba | ChannelLayout::CmykA | ChannelLayout::LabA)}pub const fn is_gray(self) -> bool {@@ -59,12 +71,17 @@ impl ChannelLayout {matches!(self, ChannelLayout::Cmyk | ChannelLayout::CmykA)}+ pub const fn is_lab(self) -> bool {+ matches!(self, ChannelLayout::Lab | ChannelLayout::LabA)+ }+/// The same colour model with alpha added.pub const fn with_alpha(self) -> Self {match self {ChannelLayout::Gray | ChannelLayout::GrayA => ChannelLayout::GrayA,ChannelLayout::Rgb | ChannelLayout::Rgba => ChannelLayout::Rgba,ChannelLayout::Cmyk | ChannelLayout::CmykA => ChannelLayout::CmykA,+ ChannelLayout::Lab | ChannelLayout::LabA => ChannelLayout::LabA,}}@@ -74,12 +91,13 @@ impl ChannelLayout {ChannelLayout::Gray | ChannelLayout::GrayA => ChannelLayout::Gray,ChannelLayout::Rgb | ChannelLayout::Rgba => ChannelLayout::Rgb,ChannelLayout::Cmyk | ChannelLayout::CmykA => ChannelLayout::Cmyk,+ ChannelLayout::Lab | ChannelLayout::LabA => ChannelLayout::Lab,}}/// `true` if both layouts share a colour model (ignoring alpha).pub const fn same_model(self, other: Self) -> bool {- (self.is_gray() && other.is_gray()) || (self.is_rgb() && other.is_rgb()) || (self.is_cmyk() && other.is_cmyk())+ (self.is_gray() && other.is_gray()) || (self.is_rgb() && other.is_rgb()) || (self.is_cmyk() && other.is_cmyk()) || (self.is_lab() && other.is_lab())}}@@ -723,6 +741,7 @@ pub(crate) fn convert_layout(src: &[f32], from: ChannelLayout, to: ChannelLayoutChannelLayout::Gray | ChannelLayout::GrayA => [color[0]; 3],ChannelLayout::Rgb | ChannelLayout::Rgba => [color[0], color[1], color[2]],ChannelLayout::Cmyk | ChannelLayout::CmykA => cmyk_to_rgb(color[0], color[1], color[2], color[3]),+ ChannelLayout::Lab | ChannelLayout::LabA => crate::lab::lab_to_srgb([color[0], color[1], color[2]]),};match to {ChannelLayout::Gray | ChannelLayout::GrayA => {@@ -730,6 +749,7 @@ pub(crate) fn convert_layout(src: &[f32], from: ChannelLayout, to: ChannelLayout}ChannelLayout::Rgb | ChannelLayout::Rgba => out.extend_from_slice(&rgb),ChannelLayout::Cmyk | ChannelLayout::CmykA => out.extend_from_slice(&rgb_to_cmyk(rgb[0], rgb[1], rgb[2])),+ ChannelLayout::Lab | ChannelLayout::LabA => out.extend_from_slice(&crate::lab::srgb_to_lab(rgb)),}}if to.has_alpha() {diff --git a/crates/codecs/src/lab.rs b/crates/codecs/src/lab.rsnew file mode 100644index 000000000..c53ab4c33--- /dev/null+++ b/crates/codecs/src/lab.rs@@ -0,0 +1,56 @@+//! CIE L*a*b* (D50) ⇄ encoded sRGB for [`crate::ChannelLayout::Lab`] samples, the same formulas+//! and constants as `photocraft-color` (this crate stays standalone). Samples are normalized as+//! PhotoCraft holds Lab: L* 0..100 as 0..1, a* and b* −128..127 as `(v + 128) / 255`.++const D50: [f32; 3] = [0.964_22, 1.0, 0.825_21];+/// Linear sRGB → D50 XYZ (Bradford-adapted, as in the ICC sRGB profile).+const SRGB_TO_XYZ_D50: [[f32; 3]; 3] = [[0.436_074, 0.385_064, 0.143_080], [0.222_504, 0.716_878, 0.060_618], [0.013_932, 0.097_104, 0.714_173]];+/// D50 XYZ → linear sRGB.+const XYZ_D50_TO_SRGB: [[f32; 3]; 3] = [[3.133_856, -1.616_867, -0.490_615], [-0.978_768, 1.916_142, 0.033_454], [0.071_945, -0.228_991, 1.405_243]];++fn mul(m: &[[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] {+ m.map(|r| r[0] * v[0] + r[1] * v[1] + r[2] * v[2])+}++fn to_linear(v: f32) -> f32 {+ if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }+}++fn to_encoded(v: f32) -> f32 {+ if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }+}++/// Normalized Lab → encoded sRGB in 0..1 (out-of-gamut colours clipped).+pub(crate) fn lab_to_srgb(n: [f32; 3]) -> [f32; 3] {+ let (l, a, b) = (n[0] * 100.0, n[1] * 255.0 - 128.0, n[2] * 255.0 - 128.0);+ let fy = (l + 16.0) / 116.0;+ let (fx, fz) = (fy + a / 500.0, fy - b / 200.0);+ let finv = |t: f32| if t > 6.0 / 29.0 { t * t * t } else { 3.0 * (6.0f32 / 29.0).powi(2) * (t - 4.0 / 29.0) };+ let xyz = [finv(fx) * D50[0], finv(fy) * D50[1], finv(fz) * D50[2]];+ mul(&XYZ_D50_TO_SRGB, xyz).map(|v| to_encoded(v.clamp(0.0, 1.0)))+}++/// Encoded sRGB → normalized Lab.+pub(crate) fn srgb_to_lab(rgb: [f32; 3]) -> [f32; 3] {+ let xyz = mul(&SRGB_TO_XYZ_D50, rgb.map(|v| to_linear(v.clamp(0.0, 1.0))));+ let f = |t: f32| if t > (6.0f32 / 29.0).powi(3) { t.cbrt() } else { t / (3.0 * (6.0f32 / 29.0).powi(2)) + 4.0 / 29.0 };+ let (fx, fy, fz) = (f(xyz[0] / D50[0]), f(xyz[1] / D50[1]), f(xyz[2] / D50[2]));+ let (l, a, b) = (116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz));+ [(l / 100.0).clamp(0.0, 1.0), ((a + 128.0) / 255.0).clamp(0.0, 1.0), ((b + 128.0) / 255.0).clamp(0.0, 1.0)]+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn white_black_and_round_trips() {+ let w = srgb_to_lab([1.0; 3]);+ assert!((w[0] - 1.0).abs() < 1e-3 && (w[1] - 128.0 / 255.0).abs() < 1e-3 && (w[2] - 128.0 / 255.0).abs() < 1e-3, "{w:?}");+ assert!(srgb_to_lab([0.0; 3])[0].abs() < 1e-4);+ for rgb in [[0.2, 0.5, 0.8], [0.9, 0.1, 0.3], [0.5; 3]] {+ let back = lab_to_srgb(srgb_to_lab(rgb));+ assert!(rgb.iter().zip(back).all(|(a, b)| (a - b).abs() < 2e-3), "{rgb:?} → {back:?}");+ }+ }+}diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rsindex eb010a758..86611599d 100644--- a/crates/codecs/src/lib.rs+++ b/crates/codecs/src/lib.rs@@ -19,6 +19,7 @@ pub mod exif_color;mod fidelity;mod format;mod image;+mod lab;mod options;pub mod orientation;pub mod resolution;diff --git a/crates/codecs/tests/fidelity.rs b/crates/codecs/tests/fidelity.rsindex 6a7002fc2..93b0236fd 100644--- a/crates/codecs/tests/fidelity.rs+++ b/crates/codecs/tests/fidelity.rs@@ -21,7 +21,13 @@ fn png_u16_rgba_is_clean() {fn tiff_is_clean_for_all_integer_and_f32_layouts() {for l in ChannelLayout::ALL {for s in [SampleType::U8, SampleType::U16, SampleType::F32, SampleType::F16] {- assert!(warns(&test_image(l, s), Format::Tiff).is_empty(), "{l:?} {s:?}");+ let w = warns(&test_image(l, s), Format::Tiff);+ if l.is_lab() && s.is_float() {+ // CIELab has no float form: it is written with 16 bits, and says so.+ assert_eq!(w, vec![FidelityWarning::DepthReduced { from: s, to: SampleType::U16 }], "{l:?} {s:?}");+ } else {+ assert!(w.is_empty(), "{l:?} {s:?}");+ }}}}@@ -178,6 +184,7 @@ fn every_warning_has_a_message() {W::AlphaDiscarded,W::AlphaBinarized,W::CmykConverted { to: ChannelLayout::Rgb },+ W::LabConverted { to: ChannelLayout::Rgb },W::ColorToGray,W::PaletteQuantized,W::LossyCompression,@@ -209,6 +216,8 @@ fn warnings_match_actual_roundtrip_behaviour() {assert_eq!(w.contains(&W::AlphaDiscarded), alpha_lost, "{f:?} {l:?} {s:?}");let cmyk_lost = l.is_cmyk() && !back.layout().is_cmyk();assert_eq!(w.iter().any(|w| matches!(w, W::CmykConverted { .. })), cmyk_lost, "{f:?} {l:?} {s:?}");+ let lab_lost = l.is_lab() && !back.layout().is_lab();+ assert_eq!(w.iter().any(|w| matches!(w, W::LabConverted { .. })), lab_lost, "{f:?} {l:?} {s:?}");}}}diff --git a/crates/codecs/tests/roundtrip.rs b/crates/codecs/tests/roundtrip.rsindex 4cb50c005..7918d313b 100644--- a/crates/codecs/tests/roundtrip.rs+++ b/crates/codecs/tests/roundtrip.rs@@ -196,6 +196,14 @@ fn tiff_all_compressions_lossless() {for comp in [TiffCompression::None, TiffCompression::Lzw, TiffCompression::Deflate, TiffCompression::PackBits] {let opts = EncodeOptions { tiff_compression: comp, ..Default::default() };let back = decode(&encode(&img, Format::Tiff, &opts).unwrap()).unwrap();+ if layout.is_lab() && sample != SampleType::U8 {+ // CIELab holds a* and b* as 256·a at 16 bits and has no float form: 16-bit and+ // float Lab come back within one 16-bit step (the PSD's 16-bit Lab does the same).+ let (a, b) = (img.to_normalized(), back.convert(layout, sample).to_normalized());+ let worst = a.iter().zip(&b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max);+ assert!(worst <= 1.5 / 65535.0, "{layout:?} {sample:?} {comp:?}: {worst}");+ continue;+ }assert_eq!(back, img.clone().with_meta(back.meta.clone()), "{layout:?} {sample:?} {comp:?}");}}diff --git a/crates/codecs/tests/tiff_lab.rs b/crates/codecs/tests/tiff_lab.rsnew file mode 100644index 000000000..7076633ef--- /dev/null+++ b/crates/codecs/tests/tiff_lab.rs@@ -0,0 +1,76 @@+//! CIE L*a*b* TIFFs: CIELab (PhotometricInterpretation 8) as Photoshop writes it, with a* and b*+//! signed, and ICCLab (9) with them offset, both read into the Lab layout (a* and b* as+//! `(a + 128) / 255`).++use photocraft_codecs::*;++/// One Lab pixel in the codec's normalized form.+fn lab(l: f32, a: f32, b: f32) -> [f32; 3] {+ [l / 100.0, (a + 128.0) / 255.0, (b + 128.0) / 255.0]+}++fn image(sample: SampleType) -> Image {+ let px: Vec<f32> = [lab(50.0, 50.0, -30.0), lab(100.0, 0.0, 0.0)].concat();+ Image::from_normalized(2, 1, ChannelLayout::Lab, sample, &px).unwrap()+}++fn uncompressed(img: &Image) -> Vec<u8> {+ encode(img, Format::Tiff, &EncodeOptions { tiff_compression: TiffCompression::None, ..Default::default() }).unwrap()+}++fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {+ hay.windows(needle.len()).position(|w| w == needle)+}++#[test]+fn eight_bit_cielab_holds_a_and_b_signed() {+ let file = uncompressed(&image(SampleType::U8));+ // L* 50 → 128, a* 50, b* −30 as a signed byte; then white with neutral a* and b*.+ assert!(find(&file, &[128, 50, (-30i8) as u8, 255, 0, 0]).is_some(), "CIELab samples");+ let back = decode(&file).unwrap();+ assert_eq!((back.layout(), back.sample_type()), (ChannelLayout::Lab, SampleType::U8));+ assert_eq!(back.data(), image(SampleType::U8).data());+}++#[test]+fn sixteen_bit_cielab_holds_256_a() {+ let file = uncompressed(&image(SampleType::U16));+ let le = &file[..2] == b"II";+ let u16b = |v: u16| if le { v.to_le_bytes() } else { v.to_be_bytes() };+ // a* 50 → 12800, b* −30 → −7680, white's a* and b* 0.+ let want: Vec<u8> = [32768u16, 12800, (-7680i16) as u16, 65535, 0, 0].iter().flat_map(|v| u16b(*v)).collect();+ assert!(find(&file, &want).is_some(), "CIELab samples");+ let back = decode(&file).unwrap();+ assert_eq!((back.layout(), back.sample_type()), (ChannelLayout::Lab, SampleType::U16));+ let (a, b) = (image(SampleType::U16).to_normalized(), back.to_normalized());+ assert!(a.iter().zip(&b).all(|(x, y)| (x - y).abs() <= 1.5 / 65535.0), "{a:?} {b:?}");+}++#[test]+fn icclab_reads_with_offset_a_and_b() {+ // The CIELab file turned into ICCLab: PhotometricInterpretation 9, a* and b* + 128.+ let mut file = uncompressed(&image(SampleType::U8));+ let at = find(&file, &[128, 50, (-30i8) as u8, 255, 0, 0]).unwrap();+ for i in [1, 2, 4, 5] {+ file[at + i] ^= 0x80;+ }+ let le = &file[..2] == b"II";+ let entry: Vec<u8> = if le { [262u16.to_le_bytes(), 3u16.to_le_bytes()].concat() } else { [262u16.to_be_bytes(), 3u16.to_be_bytes()].concat() };+ let e = find(&file, &entry).expect("PhotometricInterpretation entry");+ let nine = if le { 9u16.to_le_bytes() } else { 9u16.to_be_bytes() };+ file[e + 8..e + 10].copy_from_slice(&nine);+ let back = decode(&file).unwrap();+ assert_eq!(back.layout(), ChannelLayout::Lab);+ assert_eq!(back.data(), image(SampleType::U8).data());+}++#[test]+fn lab_converts_to_rgb_for_other_formats() {+ // White and a saturated orange-red; PNG has no Lab, so the encoder plan converts to RGB.+ let img = image(SampleType::U8);+ let png = decode(&encode(&img, Format::Png, &EncodeOptions::default()).unwrap()).unwrap();+ assert!(png.layout().is_rgb());+ let p = png.to_rgba8();+ assert_eq!(&p[4..7], &[255, 255, 255], "white");+ assert!(p[0] > 180 && p[1] < 120 && p[2] > 140, "L 50, a 50, b −30 is a magenta-ish purple: {:?}", &p[..3]);+}diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rsindex 54fe96090..f61c28a40 100644--- a/crates/io/src/flat.rs+++ b/crates/io/src/flat.rs@@ -206,6 +206,7 @@ pub(crate) fn image_to_document(name: &str, img: &Image) -> Result<ImportResult,ChannelLayout::Gray | ChannelLayout::GrayA => (ColorMode::Grayscale, ChannelLayout::GrayA),ChannelLayout::Rgb | ChannelLayout::Rgba => (ColorMode::Rgb, ChannelLayout::Rgba),ChannelLayout::Cmyk | ChannelLayout::CmykA => (ColorMode::Cmyk, ChannelLayout::CmykA),+ ChannelLayout::Lab | ChannelLayout::LabA => (ColorMode::Lab, ChannelLayout::LabA),};let (depth, csample) = match img.sample_type() {CSample::U8 => (SampleType::U8, CSample::U8),@@ -249,6 +250,7 @@ pub(crate) fn image_surface(img: &Image, target_layout: ChannelLayout, csample:let mode = match target_layout {ChannelLayout::Gray | ChannelLayout::GrayA => ColorMode::Grayscale,ChannelLayout::Cmyk | ChannelLayout::CmykA => ColorMode::Cmyk,+ ChannelLayout::Lab | ChannelLayout::LabA => ColorMode::Lab,_ => ColorMode::Rgb,};let depth = match csample {@@ -301,6 +303,8 @@ pub(crate) fn layout_for(mode: ColorMode, alpha: bool) -> ChannelLayout {(ColorMode::Grayscale, true) => ChannelLayout::GrayA,(ColorMode::Cmyk, false) => ChannelLayout::Cmyk,(ColorMode::Cmyk, true) => ChannelLayout::CmykA,+ (ColorMode::Lab, false) => ChannelLayout::Lab,+ (ColorMode::Lab, true) => ChannelLayout::LabA,(_, false) => ChannelLayout::Rgb,(_, true) => ChannelLayout::Rgba,}@@ -316,18 +320,19 @@ pub(crate) fn csample(s: SampleType) -> CSample {/// Renders the document to a flat codec image (native pixels when possible).pub fn document_to_image(doc: &Document, warnings: &mut Vec<String>) -> Result<Image, IoError> {- document_to_image_for(doc, warnings, true)+ document_to_image_for(doc, warnings, true, false)}-fn document_to_image_for(doc: &Document, warnings: &mut Vec<String>, cmyk_target: bool) -> Result<Image, IoError> {+/// `cmyk_target` / `lab_target`: the format stores CMYK / Lab pixels.+fn document_to_image_for(doc: &Document, warnings: &mut Vec<String>, cmyk_target: bool, lab_target: bool) -> Result<Image, IoError> {let (w, h) = (doc.size.width, doc.size.height);let canvas = doc.bounds();let fmt = doc.pixel_format();let n = (w as usize) * (h as usize);- // Lab has no flat-format layout here: Lab documents always go through the composite, which- // flattens nothing when there is a single plain layer.+ // A Lab document keeps its pixels only for a format that stores Lab (TIFF); for the others it+ // goes through the sRGB composite, which flattens nothing when there is a single plain layer.let single = single_layer(doc);- let native = single.filter(|_| fmt.mode != ColorMode::Lab);+ let native = single.filter(|_| fmt.mode != ColorMode::Lab || lab_target);let mut icc = doc.icc_profile.as_ref().map(|i| i.to_vec());let img = if let Some(s) = native {// Native path: keep model and depth. The surface's encoded samples are the codec's raw@@ -526,7 +531,8 @@ pub(crate) fn export_flat_with(doc: &Document, format: Format, opts: &ExportOpti}let mut warnings = Vec::new();let cmyk_target = format.caps().layouts.iter().any(|layout| layout.is_cmyk());- let mut img = document_to_image_for(doc, &mut warnings, cmyk_target)?;+ let lab_target = format.caps().layouts.iter().any(|layout| layout.is_lab());+ let mut img = document_to_image_for(doc, &mut warnings, cmyk_target, lab_target)?;ctl.check().map_err(|_| IoError::Cancelled)?;ctl.progress(composite_share(format));if opts.xmp == XmpEmbed::None {diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rsindex 8a5810e92..3cd8de5b4 100644--- a/crates/io/src/tiff_layers.rs+++ b/crates/io/src/tiff_layers.rs@@ -93,6 +93,7 @@ pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8]) -> Result<IChannelLayout::Gray | ChannelLayout::GrayA => (PsdMode::Grayscale, 1),ChannelLayout::Rgb | ChannelLayout::Rgba => (PsdMode::Rgb, 3),ChannelLayout::Cmyk | ChannelLayout::CmykA => (PsdMode::Cmyk, 4),+ ChannelLayout::Lab | ChannelLayout::LabA => (PsdMode::Lab, 3),};let depth = match img.sample_type() {CSample::U8 => 8,diff --git a/crates/io/tests/flat.rs b/crates/io/tests/flat.rsindex 163ab8b3a..b82b41ffc 100644--- a/crates/io/tests/flat.rs+++ b/crates/io/tests/flat.rs@@ -982,14 +982,32 @@ fn tga_default_bits_follow_the_alpha_channels() {assert_eq!((TgaBits::from_bits(24), TgaBits::from_bits(32), TgaBits::from_bits(16)), (Some(TgaBits::Bits24), Some(TgaBits::Bits32), None));}+#[test]+fn a_lab_document_is_written_as_a_lab_tiff_and_opens_as_lab() {+ // #4936: TIFF stores CIE L*a*b* (CIELab): a Lab document with one layer keeps its pixels.+ for depth in [SampleType::U8, SampleType::U16] {+ let d = single(ColorMode::Lab, depth, false);+ let r = export(&d, "tif", &ExportOptions::default()).unwrap();+ assert!(r.warnings.iter().all(|w| !w.contains("sRGB") && !w.contains("flattened")), "{depth:?}: {:?}", r.warnings);+ let back = import("x.tif", &r.bytes).unwrap().document;+ assert_eq!((back.mode, back.depth), (ColorMode::Lab, depth));+ pixels_eq(&d, &back, if depth == SampleType::U8 { 0.0 } else { 1.5 / 65535.0 });+ }+ // Other formats still go through sRGB.+ let r = export(&single(ColorMode::Lab, SampleType::U8, false), "png", &ExportOptions::default()).unwrap();+ assert!(r.warnings.iter().any(|w| w.contains("sRGB")), "{:?}", r.warnings);+}+#[test]fn a_lab_document_with_one_layer_is_not_reported_as_flattened() {- // Lab always goes through the sRGB composite, but a lone layer loses nothing to it.+ // A lone layer loses nothing: TIFF keeps it as Lab, the others go through the sRGB composite.let d = single(ColorMode::Lab, SampleType::U8, false);for ext in ["tif", "png", "jpg"] {let r = export(&d, ext, &ExportOptions::default()).unwrap();assert!(r.warnings.iter().all(|w| !w.contains("flattened")), "{ext}: {:?}", r.warnings);- assert!(r.warnings.iter().any(|w| w.contains("Lab composite written as sRGB")), "{ext}: {:?}", r.warnings);+ if ext != "tif" {+ assert!(r.warnings.iter().any(|w| w.contains("Lab composite written as sRGB")), "{ext}: {:?}", r.warnings);+ }}// Two layers are flattened, and say so.let mut two = single(ColorMode::Lab, SampleType::U8, false);