Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_graphics/tests/icc/xform.rs

15.8 KiB, 1 run

created by r1870400018:68839, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! Transforms between profiles, held against LittleCMS 2.17 (`transicc`) to one level in 255 on
2//! every channel of every swatch, for each of the four intents with black-point compensation on and
3//! off. The numbers are in `xform_data.rs`, made by `tools/icc/fixtures.sh xform`.
4//!
5//! FOGRA39L Coated is the bundled CMYK profile and its tests always run. Ghostscript's profiles are
6//! read from their system path by the `#[ignore]`d tests, which are run with `--ignored`.
7//!
8//! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\
9//! Anthropic Claude
10
11use super::{
12 GS,
13 fogra_bytes,
14 system,
15};
16
17use oxedyne_fe2o3_core::prelude::*;
18use oxedyne_fe2o3_graphics::icc::{
19 lab,
20 read::{
21 Curve,
22 Profile,
23 },
24 transform::{
25 Dev,
26 Intent,
27 Transform,
28 grey_to_k,
29 },
30};
31
32#[path = "xform_data.rs"]
33#[allow(non_upper_case_globals)]
34mod data;
35
36const ONE: f64 = 1.0 / 255.0;
37
38// The intents and settings of compensation, in the order the fixture script makes them.
39macro_rules! seven {
40 ($a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr, $g:expr) => {
41 [
42 ("T0", Intent::Perceptual, false, $a),
43 ("T0B", Intent::Perceptual, true, $b),
44 ("T1", Intent::Relative, false, $c),
45 ("T1B", Intent::Relative, true, $d),
46 ("T2", Intent::Saturation, false, $e),
47 ("T2B", Intent::Saturation, true, $f),
48 ("T3", Intent::Absolute, false, $g),
49 ]
50 };
51}
52
53// The swatches of the fixture script: a 3-step cube, red slowest, eight greys and eight colours.
54fn swatches() -> Vec<[f64; 3]> {
55 let mut v = Vec::new();
56 for r in [0, 128, 255] {
57 for g in [0, 128, 255] {
58 for b in [0, 128, 255] {
59 v.push([r, g, b]);
60 }
61 }
62 }
63 for g in [16, 48, 80, 112, 160, 192, 224, 240] {
64 v.push([g, g, g]);
65 }
66 v.extend([
67 [224, 172, 105], [91, 155, 213], [96, 153, 60], [110, 20, 30],
68 [240, 200, 220], [128, 128, 0], [0, 128, 128], [101, 67, 33],
69 ]);
70 v.iter().map(|c| [c[0] as f64 / 255.0, c[1] as f64 / 255.0, c[2] as f64 / 255.0]).collect()
71}
72
73fn cmyks() -> Vec<[f64; 4]> {
74 let mut v: Vec<[f64; 4]> = [0.0, 25.0, 50.0, 75.0, 100.0].iter().map(|k| [0.0, 0.0, 0.0, *k]).collect();
75 v.extend([
76 [100.0, 0.0, 0.0, 0.0], [0.0, 100.0, 0.0, 0.0], [0.0, 0.0, 100.0, 0.0], [100.0, 100.0, 100.0, 0.0],
77 [100.0, 100.0, 100.0, 100.0], [50.0, 50.0, 50.0, 0.0], [0.0, 50.0, 100.0, 20.0],
78 ]);
79 v.iter().map(|c| [c[0] / 100.0, c[1] / 100.0, c[2] / 100.0, c[3] / 100.0]).collect()
80}
81
82fn greys() -> Vec<f64> {
83 [0.0, 32.0, 64.0, 96.0, 128.0, 160.0, 192.0, 224.0, 255.0].iter().map(|g| g / 255.0).collect()
84}
85
86fn fogra() -> Outcome<Dev> {
87 let b = res!(fogra_bytes());
88 Dev::from_profile(&res!(Profile::read("FOGRA39L_coated.icc", &b)))
89}
90
91fn gs(name: &str) -> Outcome<Dev> {
92 Dev::from_profile(&res!(system(GS, name)))
93}
94
95fn report(tag: &str, worst: f64, at: usize) {
96 eprintln!("{}: worst channel error {:.5} ({:.2} of 255) at swatch {}", tag, worst, worst * 255.0, at);
97 assert!(worst <= ONE, "{}: a channel is {:.2} levels from LittleCMS at swatch {}", tag, worst * 255.0, at);
98}
99
100fn rgb_to_cmyk_set(dst: &Dev, name: &str, sets: &[(&str, Intent, bool, &[[f64; 4]])]) -> Outcome<()> {
101 let src = res!(Dev::srgb());
102 let ins = swatches();
103 for (tag, intent, bpc, want) in sets {
104 assert_eq!(want.len(), ins.len(), "{} {}: the fixture and the swatches differ in length", name, tag);
105 let t = res!(Transform::new(&src, dst, *intent, *bpc));
106 let (mut worst, mut at) = (0.0f64, 0);
107 for (i, (c, w)) in ins.iter().zip(*want).enumerate() {
108 let got = res!(t.rgb_to_cmyk(*c));
109 for j in 0..4 {
110 let e = (got[j] as f64 - w[j] / 100.0).abs();
111 if e > worst {
112 (worst, at) = (e, i);
113 eprintln!("{} {}: swatch {} {:?} gives {:?}, LittleCMS {:?}", name, tag, i, c, got, w);
114 }
115 }
116 }
117 report(&format!("{} {}", name, tag), worst, at);
118 }
119 Ok(())
120}
121
122fn grey_set<F: Fn(&Transform, usize) -> Outcome<f32>>(
123 src: &Dev,
124 dst: &Dev,
125 name: &str,
126 n: usize,
127 sets: &[(&str, Intent, bool, &[f64])],
128 f: F,
129) -> Outcome<()> {
130 for (tag, intent, bpc, want) in sets {
131 assert_eq!(want.len(), n, "{} {}: the fixture and the swatches differ in length", name, tag);
132 let t = res!(Transform::new(src, dst, *intent, *bpc));
133 let (mut worst, mut at) = (0.0f64, 0);
134 for i in 0..n {
135 let e = (res!(f(&t, i)) as f64 - want[i] / 255.0).abs();
136 if e > worst {
137 (worst, at) = (e, i);
138 }
139 }
140 report(&format!("{} {}", name, tag), worst, at);
141 }
142 Ok(())
143}
144
145#[test]
146fn test_fogra39l_rgb_to_cmyk_is_within_one_level_of_lcms_for_every_intent_and_compensation() -> Outcome<()> {
147 let sets = seven!(
148 data::FOGRA_T0, data::FOGRA_T0B, data::FOGRA_T1, data::FOGRA_T1B,
149 data::FOGRA_T2, data::FOGRA_T2B, data::FOGRA_T3
150 );
151 rgb_to_cmyk_set(&res!(fogra()), "FOGRA39L", &sets)
152}
153
154#[test]
155fn test_the_perceptual_black_with_compensation_is_the_black_lcms_gives() -> Outcome<()> {
156 // sRGB black through FOGRA39L, perceptual, compensated and not; the first swatch of each set.
157 let (src, dst) = (res!(Dev::srgb()), res!(fogra()));
158 let t = res!(Transform::new(&src, &dst, Intent::Perceptual, true));
159 let k = res!(t.rgb_to_cmyk([0.0; 3]));
160 let want = data::FOGRA_T0B[0];
161 for j in 0..4 {
162 near(k[j] as f64, want[j] / 100.0, ONE, "compensated black");
163 }
164 let plain = res!(Transform::new(&src, &dst, Intent::Perceptual, false));
165 let p = res!(plain.rgb_to_cmyk([0.0; 3]));
166 let want = data::FOGRA_T0[0];
167 for j in 0..4 {
168 near(p[j] as f64, want[j] / 100.0, ONE, "uncompensated black");
169 }
170 // The two differ, so the fixture can tell compensation from none.
171 assert!((0..4).any(|j| (k[j] - p[j]).abs() as f64 > 2.0 * ONE), "{:?} and {:?} should differ", k, p);
172 Ok(())
173}
174
175fn near(got: f64, want: f64, tol: f64, what: &str) {
176 assert!((got - want).abs() <= tol, "{}: got {}, want {} (tolerance {})", what, got, want, tol);
177}
178
179// Destination XYZ and source L* of the three intents, as `cmsDetectDestinationBlackPoint` and
180// `cmsDetectBlackPoint` give them (called from python through ctypes).
181fn black_points(p: &Profile, dst: [[f64; 3]; 2], dst_l: [f64; 2], src_l: [f64; 2]) {
182 let (i0, i1) = (Intent::Perceptual, Intent::Relative);
183 for (intent, xyz, l) in [(i0, dst[0], dst_l[0]), (i1, dst[1], dst_l[1]), (Intent::Saturation, dst[0], dst_l[0])] {
184 let got = lab::cmyk_black_dst(p, intent);
185 for j in 0..3 {
186 near(got[j], xyz[j], 2e-5, &format!("{:?} destination black XYZ[{}]", intent, j));
187 }
188 near(lab::xyz_to_lab(got)[0], l, 0.03, &format!("{:?} destination black L*", intent));
189 }
190 for (intent, l) in [(i0, src_l[0]), (i1, src_l[1]), (Intent::Saturation, src_l[0])] {
191 near(lab::xyz_to_lab(lab::cmyk_black_src(p, intent))[0], l, 0.03, &format!("{:?} source black L*", intent));
192 }
193}
194
195#[test]
196fn test_fogra39l_black_points_are_those_lcms_detects() -> Outcome<()> {
197 let b = res!(fogra_bytes());
198 let p = res!(Profile::read("FOGRA39L_coated.icc", &b));
199 black_points(&p, [[0.010406, 0.010792, 0.008902], [0.010303, 0.010685, 0.008814]], [9.6346, 9.5496], [9.8192, 9.5496]);
200 Ok(())
201}
202
203#[test]
204#[ignore = "reads Ghostscript's AGPL profiles from /usr/share/color/icc/ghostscript"]
205fn test_ghostscript_default_cmyk_black_points_are_those_lcms_detects() -> Outcome<()> {
206 let p = res!(system(GS, "default_cmyk.icc"));
207 black_points(&p, [[0.020524, 0.021286, 0.017559], [0.021208, 0.021995, 0.018144]], [16.1482, 16.5012], [11.7724, 16.5012]);
208 Ok(())
209}
210
211#[test]
212#[ignore = "reads Ghostscript's AGPL profiles from /usr/share/color/icc/ghostscript"]
213fn test_ghostscript_swop_rgb_to_cmyk_is_within_one_level_of_lcms() -> Outcome<()> {
214 let sets = seven!(
215 data::SWOP_T0, data::SWOP_T0B, data::SWOP_T1, data::SWOP_T1B,
216 data::SWOP_T2, data::SWOP_T2B, data::SWOP_T3
217 );
218 rgb_to_cmyk_set(&res!(gs("default_cmyk.icc")), "SWOP", &sets)
219}
220
221#[test]
222#[ignore = "reads Ghostscript's AGPL profiles from /usr/share/color/icc/ghostscript"]
223fn test_ghostscript_rgb_cmyk_and_grey_conversions_to_grey_and_from_grey_are_within_one_level_of_lcms() -> Outcome<()> {
224 let (srgb, grey, cmyk) = (res!(Dev::srgb()), res!(gs("default_gray.icc")), res!(gs("default_cmyk.icc")));
225 let fogra = res!(fogra());
226 let rgb = swatches();
227 let sets = seven!(
228 data::RGB_GREY_T0, data::RGB_GREY_T0B, data::RGB_GREY_T1, data::RGB_GREY_T1B,
229 data::RGB_GREY_T2, data::RGB_GREY_T2B, data::RGB_GREY_T3
230 );
231 res!(grey_set(&srgb, &grey, "RGB to grey", rgb.len(), &sets, |t, i| t.rgb_to_grey(rgb[i])));
232 let ink = cmyks();
233 let sets = seven!(
234 data::CMYK_GREY_T0, data::CMYK_GREY_T0B, data::CMYK_GREY_T1, data::CMYK_GREY_T1B,
235 data::CMYK_GREY_T2, data::CMYK_GREY_T2B, data::CMYK_GREY_T3
236 );
237 res!(grey_set(&cmyk, &grey, "CMYK to grey", ink.len(), &sets, |t, i| t.cmyk_to_grey(ink[i])));
238 // Grey to FOGRA39L, the rich path: four values each, so held to the same level here.
239 let lv = greys();
240 let sets = seven!(
241 data::GREY_FOGRA_T0, data::GREY_FOGRA_T0B, data::GREY_FOGRA_T1, data::GREY_FOGRA_T1B,
242 data::GREY_FOGRA_T2, data::GREY_FOGRA_T2B, data::GREY_FOGRA_T3
243 );
244 for (tag, intent, bpc, want) in sets {
245 let t = res!(Transform::new(&grey, &fogra, intent, bpc));
246 let (mut worst, mut at) = (0.0f64, 0);
247 for (i, g) in lv.iter().enumerate() {
248 let got = res!(t.grey_to_cmyk(*g));
249 for j in 0..4 {
250 let e = (got[j] as f64 - want[i][j] / 100.0).abs();
251 if e > worst {
252 (worst, at) = (e, i);
253 }
254 }
255 }
256 report(&format!("grey to FOGRA39L {}", tag), worst, at);
257 }
258 Ok(())
259}
260
261#[test]
262fn test_k_alone_is_one_minus_the_level() {
263 assert_eq!(grey_to_k(0.0), [0.0, 0.0, 0.0, 1.0]);
264 assert_eq!(grey_to_k(1.0), [0.0; 4]);
265 assert_eq!(grey_to_k(0.25)[3], 0.75);
266 assert_eq!(grey_to_k(3.0)[3], 0.0);
267}
268
269// The image grid of `src` to `dst` against the exact path, over the swatches, a 17-step cube and 3000
270// random colours, for three intents.
271fn grid_within_two_levels(name: &str, src: &Dev, dst: &Dev) -> Outcome<()> {
272 let mut seed = 0x2545_f491_4f6c_dd1du64;
273 let mut next = move || {
274 seed ^= seed << 13;
275 seed ^= seed >> 7;
276 seed ^= seed << 17;
277 (seed >> 11) as f64 / (1u64 << 53) as f64
278 };
279 let mut pts: Vec<[f64; 3]> = swatches();
280 for r in 0..17 {
281 for g in 0..17 {
282 for b in 0..17 {
283 pts.push([r as f64 / 16.0, g as f64 / 16.0, b as f64 / 16.0]);
284 }
285 }
286 }
287 for _ in 0..3000 {
288 pts.push([next(), next(), next()]);
289 }
290 for (intent, bpc) in [(Intent::Perceptual, true), (Intent::Relative, false), (Intent::Absolute, false)] {
291 let t = res!(Transform::new(src, dst, intent, bpc));
292 let grid = res!(t.grid());
293 assert!(std::ptr::eq(grid, res!(t.grid())), "the grid is built once");
294 let (mut worst, mut at) = (0.0f64, [0.0; 3]);
295 for p in &pts {
296 let (e, x) = (grid.eval(*p), t.eval([p[0], p[1], p[2], 0.0]));
297 for j in 0..4 {
298 let d = (e[j] as f64 - x[j]).abs();
299 if d > worst {
300 (worst, at) = (d, *p);
301 }
302 }
303 }
304 eprintln!("grid {} {:?} {}: worst error {:.5} ({:.2} of 255) at {:?}", name, intent, bpc, worst, worst * 255.0, at);
305 assert!(worst <= 2.0 * ONE, "the grid is {:.2} levels from the exact path at {:?}", worst * 255.0, at);
306 // The bulk converter is the same arithmetic.
307 let px = [0u8, 0, 0, 255, 255, 255, 12, 200, 99];
308 let out = res!(grid.convert8(&px));
309 assert_eq!(out.len(), 3);
310 assert_eq!(out[2], grid.eval([12.0 / 255.0, 200.0 / 255.0, 99.0 / 255.0]));
311 assert!(grid.convert8(&px[..8]).is_err());
312 }
313 Ok(())
314}
315
316#[test]
317fn test_the_grid_is_within_two_levels_of_the_exact_path() -> Outcome<()> {
318 grid_within_two_levels("FOGRA39L", &res!(Dev::srgb()), &res!(fogra()))
319}
320
321#[test]
322#[ignore = "reads Ghostscript's AGPL profiles from /usr/share/color/icc/ghostscript"]
323fn test_the_ghostscript_grids_are_within_two_levels_of_the_exact_path() -> Outcome<()> {
324 let (cmyk, rgb) = (res!(gs("default_cmyk.icc")), res!(gs("default_rgb.icc")));
325 res!(grid_within_two_levels("SWOP from sRGB", &res!(Dev::srgb()), &cmyk));
326 grid_within_two_levels("SWOP from default RGB", &rgb, &cmyk)
327}
328
329#[test]
330fn test_a_table_with_lab_input_is_read_trilinearly() -> Outcome<()> {
331 let b = res!(fogra_bytes());
332 let p = res!(Profile::read("FOGRA39L_coated.icc", &b));
333 let lut = res!(p.b2a[0].as_ref().ok_or_else(|| err!("FOGRA39L has no B2A0."; Missing)));
334 assert!(lut.lab_in, "the table that takes Lab to the inks has a Lab input");
335 assert!(p.a2b.iter().flatten().all(|t| !t.lab_in), "a table that takes inks to Lab does not");
336 // Lab of sRGB (128, 128, 0), where a tetrahedral reading gives 22.18 4.64 100 51.71.
337 let e = lab::lab_enc(lut.bits, [52.1498, -9.4467, 56.0227]);
338 let got = lut.eval([e[0], e[1], e[2], 0.0]);
339 let want = [28.2597, 11.2871, 99.9313, 44.9683]; // LittleCMS 2.17, in per cent
340 for j in 0..4 {
341 assert!((got[j] * 100.0 - want[j]).abs() < 0.1, "ink {}: {:.4} against LittleCMS's {:.4}", j, got[j] * 100.0, want[j]);
342 }
343 Ok(())
344}
345
346#[test]
347fn test_a_transform_is_identified_by_its_profiles_intent_and_compensation() -> Outcome<()> {
348 let (srgb, fogra) = (res!(Dev::srgb()), res!(fogra()));
349 let id = |s: &Dev, d: &Dev, i, b| Transform::new(s, d, i, b).map(|t| t.id());
350 let base = res!(id(&srgb, &fogra, Intent::Relative, false));
351 assert_eq!(base, res!(id(&srgb, &fogra, Intent::Relative, false)), "the same request, the same identity");
352 assert_ne!(base, res!(id(&srgb, &fogra, Intent::Relative, true)));
353 assert_ne!(base, res!(id(&srgb, &fogra, Intent::Perceptual, false)));
354 assert_ne!(base, res!(id(&srgb, &fogra, Intent::Saturation, false)));
355 assert_ne!(base, res!(id(&srgb, &fogra, Intent::Absolute, false)));
356 assert_ne!(base, res!(id(&srgb, &Dev::sgray(), Intent::Relative, false)));
357 assert_ne!(base, res!(id(&Dev::sgray(), &fogra, Intent::Relative, false)));
358 // Absolute colorimetric is never compensated, so asking for it changes nothing.
359 assert_eq!(
360 res!(id(&srgb, &fogra, Intent::Absolute, false)),
361 res!(id(&srgb, &fogra, Intent::Absolute, true)),
362 );
363 // A version 4 destination compensates perceptual whether asked or not.
364 let (g, s) = (Dev::sgray(), &srgb);
365 assert_eq!(res!(id(s, &g, Intent::Perceptual, false)), res!(id(s, &g, Intent::Perceptual, true)));
366 assert!(res!(Transform::new(s, &g, Intent::Perceptual, false)).bpc());
367 assert!(!res!(Transform::new(s, &fogra, Intent::Perceptual, false)).bpc());
368 Ok(())
369}
370
371#[test]
372fn test_a_transform_that_is_not_made_is_refused_by_name() -> Outcome<()> {
373 let (srgb, fogra) = (res!(Dev::srgb()), res!(fogra()));
374 let e = format!("{}", Transform::new(&fogra, &srgb, Intent::Relative, false).unwrap_err());
375 assert!(e.contains("sRGB"), "{}", e);
376 let t = res!(Transform::new(&srgb, &fogra, Intent::Relative, false));
377 let e = format!("{}", t.cmyk_to_grey([0.0; 4]).unwrap_err());
378 assert!(e.contains("sRGB") && e.contains("FOGRA39L"), "{}", e);
379 assert!(t.grey_to_cmyk(0.5).is_err());
380 assert!(res!(Transform::new(&Dev::sgray(), &fogra, Intent::Relative, false)).rgb_to_cmyk([0.0; 3]).is_err());
381 Ok(())
382}
383
384// The reference inverse: bisection, as the curve did before it had closed forms.
385fn bisect(c: &Curve, y: f64) -> f64 {
386 let (mut lo, mut hi) = (0.0f64, 1.0f64);
387 for _ in 0..60 {
388 let mid = 0.5 * (lo + hi);
389 if c.eval(mid) < y { lo = mid; } else { hi = mid; }
390 }
391 0.5 * (lo + hi)
392}
393
394#[test]
395fn test_a_curves_inverse_agrees_with_bisection() {
396 let table: Vec<u16> = (0..256).map(|i| ((i as f64 / 255.0).powf(1.8) * 65535.0).round() as u16).collect();
397 let para = |func: u16, p: [f64; 7]| Curve::Para { func, p };
398 // (curve, strictly rising)
399 let curves = [
400 (Curve::Identity, true),
401 (Curve::Gamma(2.2), true),
402 (Curve::Gamma(1.0 / 2.2), true),
403 (Curve::Table(table), true),
404 (Curve::Table(vec![0, 0, 100, 40000, 40000, 65535]), false),
405 (para(0, [2.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]), true),
406 (para(1, [2.0, 0.9, 0.1, 0.0, 0.0, 0.0, 0.0]), false),
407 (para(2, [2.0, 0.9, 0.1, 0.05, 0.0, 0.0, 0.0]), false),
408 (para(3, [2.4, 1.0 / 1.055, 0.055 / 1.055, 1.0 / 12.92, 0.04045, 0.0, 0.0]), true),
409 (para(4, [2.2, 0.95, 0.05, 0.1, 0.1, 0.02, 0.0]), false),
410 ];
411 for (k, (c, rising)) in curves.iter().enumerate() {
412 for i in 0..=200 {
413 let y = i as f64 / 200.0;
414 let (x, r) = (c.inverse(y), bisect(c, y));
415 assert!((0.0..=1.0).contains(&x), "curve {} y {}: inverse {} is outside 0..1", k, y, x);
416 let (a, b) = (c.eval(x), c.eval(r));
417 assert!((a - b).abs() < 1e-6, "curve {} y {}: eval(inverse) {} against bisection's {}", k, y, a, b);
418 if *rising {
419 assert!((x - r).abs() < 1e-6, "curve {} y {}: inverse {} against bisection's {}", k, y, x, r);
420 }
421 }
422 }
423}