From 7107fb8daf5a1255706bc13da805b36fd3b9e9b6 Mon Sep 17 00:00:00 2001 From: Ken Mantle Date: Tue, 17 Nov 2026 14:14:51 -0500 Subject: [PATCH] =?UTF-8?q?cms:=20keep=20black-only=20CMYK=20black-only=20?= =?UTF-8?q?across=20CMYK=20=E2=86=92=20CMYK=20transforms=20(#2029)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * cms: keep black-only CMYK black-only across CMYK to CMYK transforms Opt-in BlackPreserving: a colour with exactly zero C, M and Y converts to exactly (0, 0, 0, K'), K' matching the source K-only L* in the destination (both ramps sampled at construction with the transform's intent and BPC). Transform itself is unchanged. Adapted from icccer (MIT, same author) black_preserve.rs at 08ca16ab. Co-Authored-By: Claude Opus 5.5 * cms: map black past the destination maximum to exactly K = 1 between samples Co-Authored-By: Claude Opus 5.5 * cms: README says the K-ramp check is sampled Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: KenM76 Co-authored-by: Claude Opus 5.5 --- crates/cms/README.md | 6 + crates/cms/src/black.rs | 205 ++++++++++++++++++++++++++++++++++ crates/cms/src/black_tests.rs | 149 ++++++++++++++++++++++++ crates/cms/src/lib.rs | 2 + 4 files changed, 362 insertions(+) create mode 100644 crates/cms/src/black.rs create mode 100644 crates/cms/src/black_tests.rs diff --git a/crates/cms/README.md b/crates/cms/README.md index 71f3146d5..cbee391cd 100644 --- a/crates/cms/README.md +++ b/crates/cms/README.md @@ -81,6 +81,12 @@ Buffers are checked once per call, before any pixel is written. the exact and float paths compare each pixel with white; all other colours are left as the profiles give them. With a profile whose white falls between its nodes (`coated-cmyk`: 0.4 % C), the last step to white is that much larger than its neighbours. +* Black preservation (opt-in, `BlackPreserving`): for CMYK → CMYK, a colour with exactly zero + C, M and Y comes out as exactly `(0, 0, 0, K')`, where `K'` is the destination black whose + K-only L* equals the source's (both K ramps sampled at 1024 points when the transform is + built, with its intent and BPC). The test is exact zero, so an input with any chromatic ink + takes the ordinary path. Absolute colorimetric, non-CMYK profiles and K ramps that reverse at + one of the 1024 samples are refused (a reversal between samples is not detected). ## Built-in profiles (all CC0-1.0, generated by this crate) diff --git a/crates/cms/src/black.rs b/crates/cms/src/black.rs new file mode 100644 index 000000000..f80defeef --- /dev/null +++ b/crates/cms/src/black.rs @@ -0,0 +1,205 @@ +//! K-only black preservation for CMYK → CMYK transforms. +//! +//! A CMYK → CMYK transform goes through the three-component PCS, so black alone (C = M = Y = 0) +//! comes out as a four-ink mix. ISO 32000-2 §8.6.5.7 notes that this loses fidelity in the black +//! component. ICC defines no black preservation; this is a named policy the caller opts into. +//! +//! [`BlackPreserving`] converts like its [`Transform`], except that a colour with exactly zero +//! cyan, magenta and yellow becomes exactly `(0, 0, 0, K')`. `K'` is the destination black whose +//! K-only L* equals the source's, both measured to Lab with the transform's own intent and BPC +//! setting: both ramps are sampled once, at construction, and the destination ramp is inverted. +//! A source black darker than the destination's maximum black maps to K = 1. The test is exact zero, so the transform is discontinuous at C = M = Y = 0: an input +//! with any chromatic ink takes the ordinary path. + +use crate::transform::{Transform, TransformOptions}; +use crate::{Builtin, CmsError, ColorSpace, Intent, Profile, invalid_arg}; + +/// Samples along each K-only ramp. Linear interpolation between samples of a smooth ramp is far +/// below the 16-bit quantum. +const K_SAMPLES: usize = 1024; +/// Slack for the monotonicity checks (L* units, K units). +const MONOTONIC_EPS: f64 = 1e-6; + +/// A CMYK → CMYK transform that keeps black-only colours black-only. +#[derive(Debug)] +pub struct BlackPreserving { + transform: Transform, + /// Destination K for source K at `i / (K_SAMPLES - 1)`; `K_SAMPLES` values in `[0, 1]`. + curve: Vec, + /// Source K from which the source black is at least as dark as the destination's darkest: + /// mapped to exactly 1. Infinite when the destination's black is the darker. + saturate: f32, + /// The mapping at the 256 8-bit source codes, already quantised. + curve8: [u8; 256], +} + +impl BlackPreserving { + /// Transform from `src` to `dst` with black preservation. + /// + /// Errors with [`CmsError::InvalidArgument`] when either profile is not CMYK or the intent is + /// absolute colorimetric (which reproduces the source's paper and black, so there is no + /// black to map), and with [`CmsError::Unsupported`] when a profile's K-only ramp is not + /// monotonic at its 1024 samples (black that gets lighter as K rises has no equal-lightness + /// inverse; a reversal between samples is not detected). Other errors + /// are those of [`Transform::with_options`]. + pub fn new(src: &Profile, dst: &Profile, opts: TransformOptions) -> Result { + if src.color_space != ColorSpace::Cmyk || dst.color_space != ColorSpace::Cmyk { + return Err(invalid_arg("black preservation needs CMYK source and destination profiles")); + } + if opts.intent == Intent::AbsoluteColorimetric { + return Err(invalid_arg("black preservation does not apply to absolute colorimetric")); + } + let transform = Transform::with_options(src, dst, opts)?; + let src_l = k_ramp_lightness(src, opts)?; + let dst_l = k_ramp_lightness(dst, opts)?; + let (curve, saturate) = k_curve(&src_l, &dst_l)?; + let mut curve8 = [0u8; 256]; + for (code, slot) in curve8.iter_mut().enumerate() { + *slot = quantise(map(&curve, saturate, code as f32 / 255.0), 255.0) as u8; + } + Ok(BlackPreserving { transform, curve, saturate, curve8 }) + } + + /// The ordinary transform, which every colour with chromatic ink goes through. Converting with + /// it directly does not preserve black. + pub fn transform(&self) -> &Transform { + &self.transform + } + + /// Destination K for a black-only source colour of `k` (clamped to `[0, 1]`). + pub fn map_k(&self, k: f32) -> f32 { + map(&self.curve, self.saturate, k) + } + + /// Exact evaluation of one colour; slices as in [`Transform::eval`]. + pub fn eval(&self, input: &[f32], out: &mut [f32]) -> Result<(), CmsError> { + self.transform.eval(input, out)?; + self.patch_one(input, out); + Ok(()) + } + + /// Lookup-table evaluation of one colour; slices as in [`Transform::eval`]. + pub fn eval_fast(&self, input: &[f32], out: &mut [f32]) -> Result<(), CmsError> { + self.transform.eval_fast(input, out)?; + self.patch_one(input, out); + Ok(()) + } + + /// Converts float pixels; layout and errors as in [`Transform::convert_f32`]. + pub fn convert_f32(&self, src: &[f32], src_stride: usize, dst: &mut [f32], dst_stride: usize, copy_extra: bool) -> Result<(), CmsError> { + self.transform.convert_f32(src, src_stride, dst, dst_stride, copy_extra)?; + for (s, d) in src.chunks_exact(src_stride).zip(dst.chunks_exact_mut(dst_stride)) { + self.patch_one(s, d); + } + Ok(()) + } + + /// Converts 8-bit pixels; layout and errors as in [`Transform::convert_u8`]. + pub fn convert_u8(&self, src: &[u8], src_stride: usize, dst: &mut [u8], dst_stride: usize, copy_extra: bool) -> Result<(), CmsError> { + self.transform.convert_u8(src, src_stride, dst, dst_stride, copy_extra)?; + for (s, d) in src.chunks_exact(src_stride).zip(dst.chunks_exact_mut(dst_stride)) { + if let ([0, 0, 0, k, ..], [c, m, y, kd, ..]) = (s, d) { + (*c, *m, *y) = (0, 0, 0); + *kd = self.curve8[usize::from(*k)]; + } + } + Ok(()) + } + + /// Converts 16-bit pixels; layout and errors as in [`Transform::convert_u16`]. + pub fn convert_u16(&self, src: &[u16], src_stride: usize, dst: &mut [u16], dst_stride: usize, copy_extra: bool) -> Result<(), CmsError> { + self.transform.convert_u16(src, src_stride, dst, dst_stride, copy_extra)?; + for (s, d) in src.chunks_exact(src_stride).zip(dst.chunks_exact_mut(dst_stride)) { + if let ([0, 0, 0, k, ..], [c, m, y, kd, ..]) = (s, d) { + (*c, *m, *y) = (0, 0, 0); + *kd = quantise(self.map_k(f32::from(*k) / 65535.0), 65535.0) as u16; + } + } + Ok(()) + } + + fn patch_one(&self, input: &[f32], out: &mut [f32]) { + if let ([0.0, 0.0, 0.0, k, ..], [c, m, y, kd, ..]) = (input, out) { + (*c, *m, *y) = (0.0, 0.0, 0.0); + *kd = self.map_k(*k); + } + } +} + +/// The sampled mapping from the source to the destination K-only ramp, and the source K at +/// which the destination's darkest black is reached (the `saturate` field). +fn k_curve(src_l: &[f64], dst_l: &[f64]) -> Result<(Vec, f32), CmsError> { + let curve: Vec = src_l.iter().map(|&l| invert(dst_l, l) as f32).collect(); + if !curve.windows(2).all(|w| f64::from(w[0]) - f64::from(w[1]) <= MONOTONIC_EPS) { + return Err(CmsError::Unsupported("black preservation: the K mapping is not monotonic".into())); + } + let saturate = match (src_l.last(), dst_l.last()) { + (Some(&s), Some(&d)) if s < d => invert(src_l, d) as f32, + _ => f32::INFINITY, + }; + Ok((curve, saturate)) +} + +/// L* of `p`'s K-only ramp at `K_SAMPLES` points, light to dark; refused when it is not +/// non-increasing. +fn k_ramp_lightness(p: &Profile, opts: TransformOptions) -> Result, CmsError> { + let to_lab = Transform::with_options(p, Builtin::LabD50.profile(), TransformOptions { precise_float: true, ..opts })?; + let mut ramp = Vec::with_capacity(K_SAMPLES); + let mut lab = [0.0f32; 3]; + for i in 0..K_SAMPLES { + let k = i as f32 / (K_SAMPLES - 1) as f32; + to_lab.eval(&[0.0, 0.0, 0.0, k], &mut lab)?; + ramp.push(f64::from(lab[0]) * 100.0); + } + if !ramp.iter().all(|l| l.is_finite()) || !ramp.windows(2).all(|w| w[1] - w[0] <= MONOTONIC_EPS) { + return Err(CmsError::Unsupported("black preservation: a K-only ramp is not monotonic".into())); + } + Ok(ramp) +} + +/// The K in `[0, 1]` at which the non-increasing `ramp` reaches `target`, clamped to its ends. +fn invert(ramp: &[f64], target: f64) -> f64 { + let (Some(&first), Some(&last)) = (ramp.first(), ramp.last()) else { return 0.0 }; + if ramp.len() < 2 || target >= first { + return 0.0; + } + if target <= last { + return 1.0; + } + // ramp[lo] > target >= ramp[hi] + let (mut lo, mut hi) = (0usize, ramp.len() - 1); + while hi - lo > 1 { + let mid = lo + (hi - lo) / 2; + if ramp.get(mid).is_some_and(|&v| v > target) { + lo = mid; + } else { + hi = mid; + } + } + let (a, b) = (ramp.get(lo).copied().unwrap_or(first), ramp.get(hi).copied().unwrap_or(last)); + let t = if a - b > MONOTONIC_EPS { (a - target) / (a - b) } else { 0.0 }; + (lo as f64 + t) / (ramp.len() - 1) as f64 +} + +/// Linear interpolation in `curve` (samples over `[0, 1]`) at `k`, clamped; 1 from `saturate`. +fn map(curve: &[f32], saturate: f32, k: f32) -> f32 { + let Some(&last) = curve.last() else { return 0.0 }; + let k = if k.is_nan() { 0.0 } else { k.clamp(0.0, 1.0) }; + if k >= saturate { + return 1.0; + } + let x = k * (curve.len() - 1) as f32; + let i = x.floor() as usize; + match (curve.get(i), curve.get(i + 1)) { + (Some(&a), Some(&b)) => a + (b - a) * (x - i as f32), + _ => last, + } +} + +fn quantise(v: f32, max: f32) -> f32 { + (v.clamp(0.0, 1.0) * max + 0.5).floor() +} + +#[cfg(test)] +#[path = "black_tests.rs"] +mod tests; diff --git a/crates/cms/src/black_tests.rs b/crates/cms/src/black_tests.rs new file mode 100644 index 000000000..8752cdaa2 --- /dev/null +++ b/crates/cms/src/black_tests.rs @@ -0,0 +1,149 @@ +use super::*; + +fn coated() -> &'static Profile { + Builtin::CoatedCmyk.profile() +} +fn fogra() -> &'static Profile { + Builtin::CoatedFogra39.profile() +} +fn opts() -> TransformOptions { + TransformOptions::default() +} + +/// L* of a CMYK colour under `p`, measured as the transform with `o` measures it. +fn lightness(p: &Profile, o: TransformOptions, cmyk: [f32; 4]) -> f32 { + let t = Transform::with_options(p, Builtin::LabD50.profile(), o).unwrap(); + let mut lab = [0.0f32; 3]; + t.eval(&cmyk, &mut lab).unwrap(); + lab[0] * 100.0 +} + +#[test] +fn the_plain_transform_turns_black_into_four_inks() { + // What the policy is for: without it, black alone gains chromatic ink across presses. + let t = Transform::with_options(coated(), fogra(), opts()).unwrap(); + let mut out = [0.0f32; 4]; + t.eval(&[0.0, 0.0, 0.0, 0.5], &mut out).unwrap(); + assert!(out[..3].iter().any(|v| *v > 0.01), "{out:?}"); +} + +#[test] +fn black_only_stays_black_only_on_every_path() { + for (src, dst) in [(coated(), fogra()), (fogra(), coated()), (fogra(), fogra())] { + let bp = BlackPreserving::new(src, dst, opts()).unwrap(); + for k in [0.0f32, 0.1, 0.5, 0.9, 1.0] { + for fast in [false, true] { + let mut out = [1.0f32; 4]; + if fast { bp.eval_fast(&[0.0, 0.0, 0.0, k], &mut out) } else { bp.eval(&[0.0, 0.0, 0.0, k], &mut out) }.unwrap(); + assert_eq!(out[..3], [0.0; 3], "k {k} fast {fast}"); + assert_eq!(out[3], bp.map_k(k)); + } + } + let src8: Vec = (0..=255u8).flat_map(|k| [0, 0, 0, k, 7]).collect(); + let mut dst8 = vec![0u8; src8.len()]; + bp.convert_u8(&src8, 5, &mut dst8, 5, true).unwrap(); + for (k, px) in dst8.as_chunks::<5>().0.iter().enumerate() { + assert_eq!(px[..3], [0; 3], "u8 k {k}"); + assert!((f32::from(px[3]) - bp.map_k(k as f32 / 255.0) * 255.0).abs() <= 0.5, "u8 k {k}: {}", px[3]); + assert_eq!(px[4], 7, "extra channel copied"); + } + let src16: Vec = (0..=64u16).flat_map(|k| [0, 0, 0, k * 1023]).collect(); + let mut dst16 = vec![0u16; src16.len()]; + bp.convert_u16(&src16, 4, &mut dst16, 4, false).unwrap(); + for (px, k) in dst16.as_chunks::<4>().0.iter().zip(src16.as_chunks::<4>().0) { + assert_eq!(px[..3], [0; 3], "u16 {k:?}"); + assert!((f32::from(px[3]) - bp.map_k(f32::from(k[3]) / 65535.0) * 65535.0).abs() <= 0.5, "u16 {k:?}: {}", px[3]); + } + let srcf: Vec = (0..=10).flat_map(|k| [0.0, 0.0, 0.0, k as f32 / 10.0]).collect(); + let mut dstf = vec![0.0f32; srcf.len()]; + bp.convert_f32(&srcf, 4, &mut dstf, 4, false).unwrap(); + for (px, k) in dstf.as_chunks::<4>().0.iter().zip(srcf.as_chunks::<4>().0) { + assert_eq!(*px, [0.0, 0.0, 0.0, bp.map_k(k[3])], "f32 {k:?}"); + } + } +} + +#[test] +fn the_destination_black_matches_the_source_lightness() { + // Measured worst error over 201 K steps, both directions, both intents, BPC on and off: + // 0.007 L*. + for intent in [Intent::RelativeColorimetric, Intent::Perceptual] { + for bpc in [true, false] { + let o = TransformOptions { intent, bpc, ..opts() }; + for (src, dst) in [(coated(), fogra()), (fogra(), coated())] { + let bp = BlackPreserving::new(src, dst, o).unwrap(); + let dst_black = lightness(dst, o, [0.0, 0.0, 0.0, 1.0]); + for k in [0.1f32, 0.3, 0.5, 0.7, 0.9, 1.0] { + let want = lightness(src, o, [0.0, 0.0, 0.0, k]); + if want <= dst_black { + assert_eq!(bp.map_k(k), 1.0, "darker than the destination's black clamps to K = 1"); + continue; + } + let got = lightness(dst, o, [0.0, 0.0, 0.0, bp.map_k(k)]); + assert!((got - want).abs() < 0.02, "{intent:?} bpc {bpc} k {k}: L* {got} for {want}"); + } + assert_eq!(bp.map_k(0.0), 0.0, "paper stays paper"); + assert!(bp.map_k(1.0) > 0.95, "full black stays near full black: {}", bp.map_k(1.0)); + assert!(bp.map_k(0.25) < bp.map_k(0.75)); + } + } + } + let same = BlackPreserving::new(fogra(), fogra(), opts()).unwrap(); + for k in [0.0f32, 0.2, 0.6, 1.0] { + assert!((same.map_k(k) - k).abs() < 1e-3, "{k} -> {}", same.map_k(k)); + } +} + +#[test] +fn colours_with_any_chromatic_ink_take_the_ordinary_path() { + let bp = BlackPreserving::new(coated(), fogra(), opts()).unwrap(); + for input in [[1e-6f32, 0.0, 0.0, 0.5], [0.0, 0.2, 0.0, 0.5], [0.3, 0.3, 0.3, 0.0], [0.0, 0.0, 1.0, 1.0]] { + let (mut a, mut b) = ([0.0f32; 4], [0.0f32; 4]); + bp.eval(&input, &mut a).unwrap(); + bp.transform().eval(&input, &mut b).unwrap(); + assert_eq!(a, b, "{input:?}"); + } + let src = [1u8, 0, 0, 128, 0, 1, 0, 128]; + let (mut a, mut b) = ([0u8; 8], [0u8; 8]); + bp.convert_u8(&src, 4, &mut a, 4, false).unwrap(); + bp.transform().convert_u8(&src, 4, &mut b, 4, false).unwrap(); + assert_eq!(a, b); +} + +#[test] +fn refusals_and_hostile_values() { + let srgb = Builtin::Srgb.profile(); + assert!(matches!(BlackPreserving::new(srgb, fogra(), opts()), Err(CmsError::InvalidArgument(_)))); + assert!(matches!(BlackPreserving::new(fogra(), srgb, opts()), Err(CmsError::InvalidArgument(_)))); + let abs = TransformOptions { intent: Intent::AbsoluteColorimetric, ..opts() }; + assert!(matches!(BlackPreserving::new(fogra(), coated(), abs), Err(CmsError::InvalidArgument(_)))); + let bp = BlackPreserving::new(coated(), fogra(), opts()).unwrap(); + for k in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0, 2.0] { + assert!((0.0..=1.0).contains(&bp.map_k(k)), "{k}"); + } + let mut out = [0.0f32; 4]; + assert!(bp.eval(&[0.0; 3], &mut out).is_err(), "short input"); + assert!(bp.convert_u8(&[0, 0, 0, 9, 0], 4, &mut [0u8; 4], 4, false).is_err(), "partial pixel"); + assert_eq!(invert(&[], 50.0), 0.0); + assert_eq!(invert(&[100.0], 50.0), 0.0); + assert_eq!(invert(&[100.0, 0.0], 150.0), 0.0); + assert_eq!(invert(&[100.0, 0.0], -5.0), 1.0); + assert!((invert(&[100.0, 50.0, 0.0], 25.0) - 0.75).abs() < 1e-12); + assert_eq!(map(&[], f32::INFINITY, 0.5), 0.0); +} + +#[test] +fn black_beyond_the_destination_maximum_maps_to_full_black_between_samples() { + // Source L* = 100 (1 - K), destination L* = 100 - 50 K: from K = 0.5 the source is darker + // than any destination black, and 0.5 falls between the 1024 samples. + let ramp = |f: fn(f64) -> f64| (0..K_SAMPLES).map(|i| f(i as f64 / (K_SAMPLES - 1) as f64)).collect::>(); + let (src, dst) = (ramp(|k| 100.0 * (1.0 - k)), ramp(|k| 100.0 - 50.0 * k)); + let (curve, saturate) = k_curve(&src, &dst).unwrap(); + assert!((saturate - 0.5).abs() < 1e-6, "{saturate}"); + for k in [0.5001f32, 0.6, 1.0] { + assert_eq!(map(&curve, saturate, k), 1.0, "{k}"); + } + assert!((map(&curve, saturate, 0.25) - 0.5).abs() < 1e-4); + let (_, never) = k_curve(&dst, &src).unwrap(); + assert_eq!(never, f32::INFINITY, "a lighter source never saturates"); +} diff --git a/crates/cms/src/lib.rs b/crates/cms/src/lib.rs index b082f67a5..38f926dcf 100644 --- a/crates/cms/src/lib.rs +++ b/crates/cms/src/lib.rs @@ -19,6 +19,7 @@ //! CIE 15, and Adobe's published black point compensation paper. #![forbid(unsafe_code)] +pub mod black; pub mod builtin; mod builtin_v2; pub mod clut; @@ -39,6 +40,7 @@ pub mod transform; mod write; pub mod write_v2; +pub use black::BlackPreserving; pub use builtin::Builtin; pub use clut::Clut; pub use curve::Curve;