1use crate::clut::Clut;
4use crate::pipeline::{Pipeline, Stage};
5use crate::profile::Profile;
6use crate::transform::link_stages;
7use crate::{CmsError, Intent};
8
9pub const DEFAULT_THRESHOLD: f32 = 4.0;
11
12#[derive(Debug)]
18pub struct GamutCheck {
19 inputs: usize,
20 grid: Option<Clut>,
21 exact: (Pipeline, Pipeline),
22 pub threshold: f32,
23}
24
25impl GamutCheck {
26 pub fn new(src: &Profile, proof: &Profile, threshold: f32) -> Result<GamutCheck, CmsError> {
27 let lab = crate::Builtin::LabD50.profile();
28 let direct = Pipeline::new(
29 src.channels(),
30 link_stages(src, lab, Intent::RelativeColorimetric, false)?,
31 );
32 let mut via = link_stages(src, proof, Intent::RelativeColorimetric, false)?;
33 via.push(Stage::Clamp01);
34 via.extend(link_stages(
35 proof,
36 lab,
37 Intent::RelativeColorimetric,
38 false,
39 )?);
40 let via = Pipeline::new(src.channels(), via);
41 let de = |p: &[f32], o: &mut [f32]| {
42 let (mut a, mut b) = ([0.0f32; 16], [0.0f32; 16]);
43 direct.eval(p, &mut a);
44 via.eval(p, &mut b);
45 let d = |i: usize, s: f32| (a[i] - b[i]) * s;
46 o[0] = (d(0, 100.0).powi(2) + d(1, 255.0).powi(2) + d(2, 255.0).powi(2)).sqrt();
47 };
48 let n = src.channels();
49 let grid = match n {
50 1 => Some(Clut::sample(vec![256], 1, de)),
51 3 => Some(Clut::sample(vec![33; 3], 1, de)),
52 4 => Some(Clut::sample(vec![17; 4], 1, de)),
53 _ => None,
54 };
55 Ok(GamutCheck {
56 inputs: n,
57 grid,
58 exact: (direct, via),
59 threshold,
60 })
61 }
62
63 pub fn inputs(&self) -> usize {
64 self.inputs
65 }
66
67 pub fn delta_e(&self, px: &[f32]) -> f32 {
69 let mut o = [0.0f32; 1];
70 match &self.grid {
71 Some(g) => {
72 let mut c = [0.0f32; 16];
73 for (d, s) in c.iter_mut().zip(&px[..self.inputs]) {
74 *d = s.clamp(0.0, 1.0);
75 }
76 g.eval(&c[..self.inputs], &mut o);
77 }
78 None => {
79 let (mut a, mut b) = ([0.0f32; 16], [0.0f32; 16]);
80 self.exact.0.eval(px, &mut a);
81 self.exact.1.eval(px, &mut b);
82 o[0] = ((a[0] - b[0]) * 100.0)
83 .hypot((a[1] - b[1]) * 255.0)
84 .hypot((a[2] - b[2]) * 255.0);
85 }
86 }
87 o[0]
88 }
89
90 pub fn out_of_gamut(&self, px: &[f32]) -> bool {
91 self.delta_e(px) > self.threshold
92 }
93}