From b6171972a06685df1404a5f4de4ca85dfbe9d145 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 26 Oct 2026 21:59:08 +0100 Subject: [PATCH 1/3] perf(cms): compute the Gamut Warning mask in parallel GamutCheck gets a bulk mask_rgba that splits the pixels into 16K-pixel chunks on the rayon pool; gamut_mask in the engine calls it instead of a serial per-pixel loop. The per-pixel test is unchanged, so the mask is bit-identical. Fixes #9744 Co-Authored-By: Claude Sonnet 5.5 --- crates/cms/src/gamut.rs | 64 +++++++++++++++++++++++++++++++++ crates/engine/src/color_cmds.rs | 15 ++------ 2 files changed, 66 insertions(+), 13 deletions(-) diff --git a/crates/cms/src/gamut.rs b/crates/cms/src/gamut.rs index 8b1abe1dd3..8e85bf4860 100644 --- a/crates/cms/src/gamut.rs +++ b/crates/cms/src/gamut.rs @@ -9,6 +9,11 @@ use crate::{CmsError, Intent}; /// Default ΔE76 threshold above which a colour counts as out of gamut. pub const DEFAULT_THRESHOLD: f32 = 4.0; +#[cfg(not(target_arch = "wasm32"))] +const PAR_MIN_PIXELS: usize = 16 * 1024; +#[cfg(not(target_arch = "wasm32"))] +const PAR_CHUNK_PIXELS: usize = 16 * 1024; + /// Precomputed out-of-gamut test for colours of `src` against `proof`. /// /// A colour is out of gamut when sending it to the proof device (relative colorimetric, @@ -75,4 +80,63 @@ impl GamutCheck { pub fn out_of_gamut(&self, px: &[f32]) -> bool { self.delta_e(px) > self.threshold } + + /// Out-of-gamut mask for RGBA pixels: `255` where the pixel has alpha > 0 and its first + /// `inputs()` channels are out of gamut, `0` elsewhere. Returns the number of flagged + /// pixels. Only `min(px.len(), mask.len())` pixels are processed. Runs on the rayon pool + /// (not on wasm); the result is identical to calling [`Self::out_of_gamut`] per pixel. + pub fn mask_rgba(&self, px: &[[f32; 4]], mask: &mut [u8]) -> usize { + let n = px.len().min(mask.len()); + let (px, mask) = (&px[..n], &mut mask[..n]); + let run = |p: &[[f32; 4]], m: &mut [u8]| { + let mut count = 0; + for (p, m) in p.iter().zip(m.iter_mut()) { + let hit = p[3] > 0.0 && self.out_of_gamut(&p[..3]); + *m = if hit { 255 } else { 0 }; + count += usize::from(hit); + } + count + }; + #[cfg(not(target_arch = "wasm32"))] + if n >= PAR_MIN_PIXELS { + use rayon::prelude::*; + return px.par_chunks(PAR_CHUNK_PIXELS).zip(mask.par_chunks_mut(PAR_CHUNK_PIXELS)).map(|(p, m)| run(p, m)).sum(); + } + run(px, mask) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Builtin; + + fn image(n: usize) -> Vec<[f32; 4]> { + let mut s = 0x9E37_79B9u32; + let mut rnd = move || { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + (s >> 8) as f32 / (1u32 << 24) as f32 + }; + // Includes out-of-range values and zero alpha. + (0..n).map(|i| [rnd() * 1.2 - 0.1, rnd(), rnd(), if i % 7 == 0 { 0.0 } else { rnd() }]).collect() + } + + #[test] + fn mask_rgba_matches_per_pixel_check() { + let src = Builtin::Srgb.profile(); + // Sizes straddle the parallel threshold and the chunk size, odd ones included. + for (proof, threshold) in [(Builtin::CoatedCmyk, 4.0), (Builtin::CoatedCmyk, 1.5), (Builtin::GrayGamma22, 4.0), (Builtin::DisplayP3, 0.5)] { + let check = GamutCheck::new(src, proof.profile(), threshold).unwrap(); + for n in [0, 1, 1023, 16 * 1024 - 1, 16 * 1024, 16 * 1024 + 1, 50_001] { + let px = image(n); + let want: Vec = px.iter().map(|p| if p[3] > 0.0 && check.out_of_gamut(&p[..3]) { 255 } else { 0 }).collect(); + let mut got = vec![7u8; n]; + let count = check.mask_rgba(&px, &mut got); + assert_eq!(got, want, "{proof:?} threshold {threshold} n {n}"); + assert_eq!(count, want.iter().filter(|&&m| m == 255).count()); + } + } + } } diff --git a/crates/engine/src/color_cmds.rs b/crates/engine/src/color_cmds.rs index 9e9c0aafd3..6823e4183f 100644 --- a/crates/engine/src/color_cmds.rs +++ b/crates/engine/src/color_cmds.rs @@ -900,19 +900,8 @@ pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result Result<(Vec, usize)> { let check = GamutCheck::new(&composite_profile(doc), &setup.profile, threshold).map_err(cms_err)?; let buf = photocraft_compose::flatten(doc); - let mut count = 0; - let mask = buf - .px - .iter() - .map(|p| { - if p[3] > 0.0 && check.out_of_gamut(&p[..3]) { - count += 1; - 255 - } else { - 0 - } - }) - .collect(); + let mut mask = vec![0u8; buf.px.len()]; + let count = check.mask_rgba(&buf.px, &mut mask); Ok((mask, count)) } From 58acaaf499adccfe0080afdc99d5c7ee3a337364 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 27 Oct 2026 19:40:53 +0100 Subject: [PATCH 2/3] fix(cms): reject non-RGB sources in GamutCheck::mask_rgba instead of panicking mask_rgba is fallible now and returns CmsError::Invalid when the check was not built from a 3-channel source profile; a CMYK source used to panic on the first alpha-positive pixel. Regression test added. Co-Authored-By: Claude Sonnet 5.5 --- crates/cms/src/gamut.rs | 36 +++++++++++++++++++++++++-------- crates/engine/src/color_cmds.rs | 2 +- 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/crates/cms/src/gamut.rs b/crates/cms/src/gamut.rs index 8e85bf4860..aee5bb6ddd 100644 --- a/crates/cms/src/gamut.rs +++ b/crates/cms/src/gamut.rs @@ -81,11 +81,19 @@ impl GamutCheck { self.delta_e(px) > self.threshold } - /// Out-of-gamut mask for RGBA pixels: `255` where the pixel has alpha > 0 and its first - /// `inputs()` channels are out of gamut, `0` elsewhere. Returns the number of flagged - /// pixels. Only `min(px.len(), mask.len())` pixels are processed. Runs on the rayon pool - /// (not on wasm); the result is identical to calling [`Self::out_of_gamut`] per pixel. - pub fn mask_rgba(&self, px: &[[f32; 4]], mask: &mut [u8]) -> usize { + /// Out-of-gamut mask for RGBA pixels: `255` where the pixel has alpha > 0 and its RGB + /// channels are out of gamut, `0` elsewhere. Returns the number of flagged pixels. Only + /// `min(px.len(), mask.len())` pixels are processed. Runs on the rayon pool (not on wasm); + /// the result is identical to calling [`Self::out_of_gamut`] per pixel. + /// + /// # Errors + /// [`CmsError::Invalid`] when the check was not built from a three-channel (RGB) source + /// profile: an RGBA pixel carries only three colour channels, so it cannot be tested + /// against a CMYK or gray source. Nothing is written to `mask` in that case. + pub fn mask_rgba(&self, px: &[[f32; 4]], mask: &mut [u8]) -> Result { + if self.inputs != 3 { + return Err(CmsError::Invalid(format!("gamut mask needs a 3-channel (RGB) source profile, got {} channels", self.inputs))); + } let n = px.len().min(mask.len()); let (px, mask) = (&px[..n], &mut mask[..n]); let run = |p: &[[f32; 4]], m: &mut [u8]| { @@ -100,9 +108,9 @@ impl GamutCheck { #[cfg(not(target_arch = "wasm32"))] if n >= PAR_MIN_PIXELS { use rayon::prelude::*; - return px.par_chunks(PAR_CHUNK_PIXELS).zip(mask.par_chunks_mut(PAR_CHUNK_PIXELS)).map(|(p, m)| run(p, m)).sum(); + return Ok(px.par_chunks(PAR_CHUNK_PIXELS).zip(mask.par_chunks_mut(PAR_CHUNK_PIXELS)).map(|(p, m)| run(p, m)).sum()); } - run(px, mask) + Ok(run(px, mask)) } } @@ -133,10 +141,22 @@ mod tests { let px = image(n); let want: Vec = px.iter().map(|p| if p[3] > 0.0 && check.out_of_gamut(&p[..3]) { 255 } else { 0 }).collect(); let mut got = vec![7u8; n]; - let count = check.mask_rgba(&px, &mut got); + let count = check.mask_rgba(&px, &mut got).unwrap(); assert_eq!(got, want, "{proof:?} threshold {threshold} n {n}"); assert_eq!(count, want.iter().filter(|&&m| m == 255).count()); } } } + + #[test] + fn mask_rgba_rejects_non_rgb_source() { + // A CMYK (4-channel) and a gray (1-channel) source cannot be tested from RGBA pixels. + for src in [Builtin::CoatedCmyk, Builtin::GrayGamma22] { + let check = GamutCheck::new(src.profile(), Builtin::Srgb.profile(), 4.0).unwrap(); + let px = image(64); + let mut mask = vec![9u8; 64]; + assert!(matches!(check.mask_rgba(&px, &mut mask), Err(CmsError::Invalid(_))), "{src:?}"); + assert!(mask.iter().all(|&m| m == 9), "mask must stay untouched"); + } + } } diff --git a/crates/engine/src/color_cmds.rs b/crates/engine/src/color_cmds.rs index 6823e4183f..9f3bfef167 100644 --- a/crates/engine/src/color_cmds.rs +++ b/crates/engine/src/color_cmds.rs @@ -901,7 +901,7 @@ pub fn gamut_mask(doc: &Document, setup: &ProofSetup, threshold: f32) -> Result< let check = GamutCheck::new(&composite_profile(doc), &setup.profile, threshold).map_err(cms_err)?; let buf = photocraft_compose::flatten(doc); let mut mask = vec![0u8; buf.px.len()]; - let count = check.mask_rgba(&buf.px, &mut mask); + let count = check.mask_rgba(&buf.px, &mut mask).map_err(cms_err)?; Ok((mask, count)) } From 4b2fae426ff2cf183da2b609590334b33bcb5b41 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 16:24:02 +0100 Subject: [PATCH 3/3] gamut: mask_rgba refuses any non-RGB source profile, including Lab Co-Authored-By: Claude Sonnet 5.5 --- crates/cms/src/gamut.rs | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/crates/cms/src/gamut.rs b/crates/cms/src/gamut.rs index aee5bb6ddd..94818dddb8 100644 --- a/crates/cms/src/gamut.rs +++ b/crates/cms/src/gamut.rs @@ -2,7 +2,7 @@ use crate::clut::Clut; use crate::pipeline::{Pipeline, Stage}; -use crate::profile::Profile; +use crate::profile::{ColorSpace, Profile}; use crate::transform::link_stages; use crate::{CmsError, Intent}; @@ -22,6 +22,7 @@ const PAR_CHUNK_PIXELS: usize = 16 * 1024; #[derive(Debug)] pub struct GamutCheck { inputs: usize, + source_space: ColorSpace, grid: Option, exact: (Pipeline, Pipeline), pub threshold: f32, @@ -49,7 +50,7 @@ impl GamutCheck { 4 => Some(Clut::sample(vec![17; 4], 1, de)), _ => None, }; - Ok(GamutCheck { inputs: n, grid, exact: (direct, via), threshold }) + Ok(GamutCheck { inputs: n, source_space: src.color_space, grid, exact: (direct, via), threshold }) } pub fn inputs(&self) -> usize { @@ -87,12 +88,12 @@ impl GamutCheck { /// the result is identical to calling [`Self::out_of_gamut`] per pixel. /// /// # Errors - /// [`CmsError::Invalid`] when the check was not built from a three-channel (RGB) source - /// profile: an RGBA pixel carries only three colour channels, so it cannot be tested - /// against a CMYK or gray source. Nothing is written to `mask` in that case. + /// [`CmsError::Invalid`] when the check was not built from an RGB source profile: an RGBA + /// pixel carries only RGB colour channels, so it cannot be tested against a CMYK, gray or + /// Lab source. Nothing is written to `mask` in that case. pub fn mask_rgba(&self, px: &[[f32; 4]], mask: &mut [u8]) -> Result { - if self.inputs != 3 { - return Err(CmsError::Invalid(format!("gamut mask needs a 3-channel (RGB) source profile, got {} channels", self.inputs))); + if self.source_space != ColorSpace::Rgb || self.inputs != 3 { + return Err(CmsError::Invalid(format!("gamut mask needs an RGB source profile, got {:?} with {} channels", self.source_space, self.inputs))); } let n = px.len().min(mask.len()); let (px, mask) = (&px[..n], &mut mask[..n]); @@ -150,8 +151,8 @@ mod tests { #[test] fn mask_rgba_rejects_non_rgb_source() { - // A CMYK (4-channel) and a gray (1-channel) source cannot be tested from RGBA pixels. - for src in [Builtin::CoatedCmyk, Builtin::GrayGamma22] { + // A CMYK (4-channel), gray (1-channel) and Lab (3-channel, not RGB) source cannot be tested from RGBA pixels. + for src in [Builtin::CoatedCmyk, Builtin::GrayGamma22, Builtin::LabD50] { let check = GamutCheck::new(src.profile(), Builtin::Srgb.profile(), 4.0).unwrap(); let px = image(64); let mut mask = vec![9u8; 64];