Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_graphics/src/icc/transform.rs

11.3 KiB, 5 runs

created by r1870400018:68835, 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//! A colour transform between two profiles, built once and keyed by what it was built from.
2//!
3//! A [`Transform`] takes a colour of a source space to XYZ (D50), compensates for the difference
4//! between the two media in XYZ, and takes the result to the destination space: through the output
5//! lookup table of a CMYK profile, by way of Lab, or through the inverse grey curve of a grey one.
6//! It follows LittleCMS 2: the intent picks the table (`A2B0` or `B2A0` for perceptual, `1` for
7//! relative colorimetric and for absolute, `2` for saturation, the first table standing in for one
8//! the profile lacks), absolute colorimetric scales XYZ by the ratio of the two media whites, and
9//! the other intents scale it between the two black points when black-point compensation is on.
10//! Compensation is forced on for perceptual and saturation when the destination is a version 4
11//! profile, as the built-in spaces are, and is never applied to absolute colorimetric.
12//!
13//! The transform has an identity, [`Transform::id`], a function of the two profiles' identities, the
14//! intent and the compensation, so that a cache can hold one transform for each distinct request.
15//!
16//! # What is refused
17//!
18//! An RGB destination, a CMYK profile whose connection space is XYZ, and a CMYK profile without the
19//! table the transform needs.
20//!
21//! # Images
22//!
23//! [`crate::icc::grid::Grid`] samples an RGB source on a 33-step lattice, so that a bitmap is
24//! converted by interpolation rather than by the full pipeline for each pixel. A CMYK destination's
25//! output table is a lattice of its own, with creases where the inks turn, and no coarser lattice
26//! follows them, so the grid holds the colour as Lab and the table is read exactly.
27//!
28//! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\
29//! Anthropic Claude
30
31use crate::icc::{
32 builtin,
33 grid::Grid,
34 lab::{
35 self,
36 D50,
37 },
38 matrix::{
39 Grey,
40 RgbMatrix,
41 },
42 read::{
43 Class,
44 Lut,
45 Profile,
46 Space,
47 fnv64,
48 },
49};
50
51use oxedyne_fe2o3_core::prelude::*;
52
53use std::sync::OnceLock;
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub enum Intent {
57 Perceptual,
58 Relative,
59 Saturation,
60 Absolute,
61}
62
63impl Intent {
64 /// The index of the `A2B` or `B2A` table this intent reads.
65 pub fn tag(self) -> usize {
66 match self {
67 Self::Perceptual => 0,
68 Self::Relative => 1,
69 Self::Saturation => 2,
70 Self::Absolute => 1,
71 }
72 }
73
74 fn code(self) -> u8 {
75 match self {
76 Self::Perceptual => 0,
77 Self::Relative => 1,
78 Self::Saturation => 2,
79 Self::Absolute => 3,
80 }
81 }
82}
83
84// What a device colour is made of.
85#[derive(Clone, Debug)]
86pub enum Kind {
87 Rgb(RgbMatrix),
88 Grey(Grey),
89 Cmyk(Box<Profile>),
90}
91
92/// A colour space ready to be one end of a transform.
93#[derive(Clone, Debug)]
94pub struct Dev {
95 pub kind: Kind,
96 pub id: u64,
97 pub v4: bool, // version 4 or built in, so perceptual compensates
98 pub white: [f64; 3], // the media white, D50 where the profile gives none
99 pub name: String,
100}
101
102impl Dev {
103 /// The built-in sRGB space.
104 pub fn srgb() -> Outcome<Self> {
105 Ok(Self {
106 kind: Kind::Rgb(res!(builtin::srgb())),
107 id: fnv64(b"oxedyne_fe2o3_graphics::icc::builtin::srgb"),
108 v4: true,
109 white: D50,
110 name: "sRGB (built in)".to_string(),
111 })
112 }
113
114 /// The built-in sGray space.
115 pub fn sgray() -> Self {
116 Self {
117 kind: Kind::Grey(builtin::sgray()),
118 id: fnv64(b"oxedyne_fe2o3_graphics::icc::builtin::sgray"),
119 v4: true,
120 white: D50,
121 name: "sGray (built in)".to_string(),
122 }
123 }
124
125 /// The space of a profile: its matrix path, its grey curve, or its tables.
126 pub fn from_profile(p: &Profile) -> Outcome<Self> {
127 let kind = match p.head.space {
128 Space::Rgb => Kind::Rgb(res!(RgbMatrix::read(p))),
129 Space::Gray => Kind::Grey(res!(Grey::read(p))),
130 Space::Cmyk => {
131 if p.head.pcs != Space::Lab {
132 return Err(err!(
133 "Profile '{}' is a CMYK profile with a {:?} connection space, and the \
134 table path here is of a Lab one.", p.name, p.head.pcs;
135 Invalid, Input, Mismatch));
136 }
137 Kind::Cmyk(Box::new(p.clone()))
138 },
139 other => return Err(err!(
140 "Profile '{}' is a {:?} profile, and a transform is made of RGB, grey and CMYK ones.",
141 p.name, other; Invalid, Input, Mismatch)),
142 };
143 let v2_display = p.head.major < 4 && p.head.class == Class::Display;
144 Ok(Self {
145 kind,
146 id: p.id,
147 v4: p.head.major >= 4,
148 white: match p.wtpt {
149 Some(w) if !v2_display => w,
150 _ => D50,
151 },
152 name: p.name.clone(),
153 })
154 }
155
156 // The XYZ of the darkest colour the space can show, as a source.
157 fn black_src(&self, intent: Intent) -> [f64; 3] {
158 match &self.kind {
159 Kind::Rgb(m) => lab::dark_colorant(m.xyz([0.0; 3])),
160 Kind::Grey(g) => {
161 let y = g.y(0.0);
162 lab::dark_colorant([D50[0] * y, D50[1] * y, D50[2] * y])
163 },
164 Kind::Cmyk(p) => lab::cmyk_black_src(p, intent),
165 }
166 }
167
168 // The same as a destination, where a CMYK profile's ink limits show.
169 fn black_dst(&self, intent: Intent) -> [f64; 3] {
170 match &self.kind {
171 Kind::Cmyk(p) => lab::cmyk_black_dst(p, intent),
172 _ => self.black_src(intent),
173 }
174 }
175
176 fn channels(&self) -> usize {
177 match &self.kind {
178 Kind::Rgb(_) => 3,
179 Kind::Grey(_) => 1,
180 Kind::Cmyk(_) => 4,
181 }
182 }
183}
184
185/// A conversion from one space to another, at one intent and one setting of compensation.
186#[derive(Debug)]
187pub struct Transform {
188 src: Dev,
189 dst: Dev,
190 intent: Intent,
191 bpc: bool, // as applied, after the forcing and the exemption
192 scale: [f64; 3], // XYZ is scaled by these, then offset
193 off: [f64; 3],
194 id: u64,
195 grid: OnceLock<Grid>,
196}
197
198impl Transform {
199 /// Builds the transform, refusing a pair of spaces it cannot join.
200 pub fn new(src: &Dev, dst: &Dev, intent: Intent, bpc: bool) -> Outcome<Self> {
201 if let Kind::Rgb(_) = dst.kind {
202 return Err(err!(
203 "A transform to the RGB space '{}' is not made: the destination is a grey or CMYK one.",
204 dst.name; Invalid, Input, Unimplemented));
205 }
206 if let Kind::Cmyk(p) = &src.kind {
207 if lab::pick(&p.a2b, intent.tag()).is_none() {
208 return Err(err!(
209 "Profile '{}' has no 'A2B{}' or 'A2B0' table to take its CMYK to Lab.",
210 p.name, intent.tag(); Invalid, Input, Missing));
211 }
212 }
213 if let Kind::Cmyk(p) = &dst.kind {
214 if lab::pick(&p.b2a, intent.tag()).is_none() {
215 return Err(err!(
216 "Profile '{}' has no 'B2A{}' or 'B2A0' table to take Lab to its CMYK.",
217 p.name, intent.tag(); Invalid, Input, Missing));
218 }
219 }
220 let bpc = bpc_forced(dst, intent).unwrap_or(bpc);
221 let mut scale = [1.0; 3];
222 let mut off = [0.0; 3];
223 if intent == Intent::Absolute {
224 for i in 0..3 {
225 scale[i] = src.white[i] / dst.white[i];
226 }
227 } else if bpc {
228 let (bi, bo) = (src.black_src(intent), dst.black_dst(intent));
229 if bi != bo {
230 for i in 0..3 {
231 let t = bi[i] - D50[i];
232 scale[i] = (bo[i] - D50[i]) / t;
233 off[i] = -D50[i] * (bo[i] - bi[i]) / t;
234 }
235 }
236 }
237 let mut key = Vec::with_capacity(18);
238 key.extend_from_slice(&src.id.to_be_bytes());
239 key.extend_from_slice(&dst.id.to_be_bytes());
240 key.push(intent.code());
241 key.push(bpc as u8);
242 Ok(Self {
243 src: src.clone(),
244 dst: dst.clone(),
245 intent,
246 bpc,
247 scale,
248 off,
249 id: fnv64(&key),
250 grid: OnceLock::new(),
251 })
252 }
253
254 /// The identity a cache holds the transform by: of the two profiles, the intent and the compensation.
255 pub fn id(&self) -> u64 {
256 self.id
257 }
258
259 pub fn intent(&self) -> Intent {
260 self.intent
261 }
262
263 /// Is black-point compensation applied, whether asked for or forced?
264 pub fn bpc(&self) -> bool {
265 self.bpc
266 }
267
268 pub fn src(&self) -> &Dev {
269 &self.src
270 }
271
272 pub fn dst(&self) -> &Dev {
273 &self.dst
274 }
275
276 /// The destination colour of the source colour `v`, whose first channels are read; all as
277 /// fractions of full scale, and only the destination's channels meaningful.
278 pub fn eval(&self, v: [f64; 4]) -> [f64; 4] {
279 let x = self.pcs(v);
280 match &self.dst.kind {
281 Kind::Cmyk(_) => match self.tail() {
282 Some(b) => {
283 let e = lab::lab_enc(b.bits, lab::xyz_to_lab(x));
284 b.eval([e[0], e[1], e[2], 0.0])
285 },
286 None => [0.0; 4], // refused by new
287 },
288 Kind::Grey(g) => [g.level(x[1]), 0.0, 0.0, 0.0],
289 Kind::Rgb(_) => [0.0; 4], // refused by new
290 }
291 }
292
293 // The source colour `v` as XYZ (D50), scaled and offset for the intent and the compensation.
294 fn pcs(&self, v: [f64; 4]) -> [f64; 3] {
295 let xyz = match &self.src.kind {
296 Kind::Rgb(m) => m.xyz([v[0], v[1], v[2]]),
297 Kind::Grey(g) => {
298 let y = g.y(v[0]);
299 [D50[0] * y, D50[1] * y, D50[2] * y]
300 },
301 Kind::Cmyk(p) => match lab::pick(&p.a2b, self.intent.tag()) {
302 Some(a) => {
303 let g = a.eval(v);
304 lab::lab_to_xyz(lab::lab_dec(a.bits, [g[0], g[1], g[2]]))
305 },
306 None => [0.0; 3], // refused by new
307 },
308 };
309 let mut x = [0.0; 3];
310 for i in 0..3 {
311 x[i] = xyz[i] * self.scale[i] + self.off[i];
312 }
313 x
314 }
315
316 // The table that takes Lab to the inks, where the destination is CMYK.
317 pub(crate) fn tail(&self) -> Option<&Lut> {
318 match &self.dst.kind {
319 Kind::Cmyk(p) => lab::pick(&p.b2a, self.intent.tag()),
320 _ => None,
321 }
322 }
323
324 // What the image grid holds for the source colour `v`: the colour in the table's Lab encoding
325 // where the destination has a table, which the grid then reads exactly, else the result.
326 pub(crate) fn node(&self, v: [f64; 4]) -> [f64; 4] {
327 match self.tail() {
328 Some(b) => {
329 let e = lab::lab_enc(b.bits, lab::xyz_to_lab(self.pcs(v)));
330 [e[0], e[1], e[2], 0.0]
331 },
332 None => self.eval(v),
333 }
334 }
335
336 fn shape(&self, nin: usize, nout: usize) -> Outcome<()> {
337 let (a, b) = (self.src.channels(), self.dst.channels());
338 if a != nin || b != nout {
339 return Err(err!(
340 "The transform from '{}' ({} channels) to '{}' ({} channels) was asked to convert \
341 {} channels to {}.", self.src.name, a, self.dst.name, b, nin, nout;
342 Invalid, Input, Mismatch));
343 }
344 Ok(())
345 }
346
347 /// RGB to CMYK, as `f32` in 0..=1.
348 pub fn rgb_to_cmyk(&self, rgb: [f64; 3]) -> Outcome<[f32; 4]> {
349 res!(self.shape(3, 4));
350 Ok(to_f32(self.eval([rgb[0], rgb[1], rgb[2], 0.0])))
351 }
352
353 /// A grey level to CMYK through the profiles, which makes a rich black; `grey_to_k` makes K alone.
354 pub fn grey_to_cmyk(&self, g: f64) -> Outcome<[f32; 4]> {
355 res!(self.shape(1, 4));
356 Ok(to_f32(self.eval([g, 0.0, 0.0, 0.0])))
357 }
358
359 /// CMYK to a grey level in 0..=1.
360 pub fn cmyk_to_grey(&self, cmyk: [f64; 4]) -> Outcome<f32> {
361 res!(self.shape(4, 1));
362 Ok(self.eval(cmyk)[0] as f32)
363 }
364
365 /// RGB to a grey level in 0..=1.
366 pub fn rgb_to_grey(&self, rgb: [f64; 3]) -> Outcome<f32> {
367 res!(self.shape(3, 1));
368 Ok(self.eval([rgb[0], rgb[1], rgb[2], 0.0])[0] as f32)
369 }
370
371 /// The image grid of an RGB source, built on first use.
372 pub fn grid(&self) -> Outcome<&Grid> {
373 res!(self.shape(3, self.dst.channels()));
374 Ok(self.grid.get_or_init(|| Grid::build(self)))
375 }
376}
377
378/// The black point compensation a transform into `dst` at `intent` applies whatever it is asked, none when it
379/// does as it is asked. The absolute intent never compensates, and perceptual and saturation always compensate
380/// into a version 4 profile, as LittleCMS has it.
381pub fn bpc_forced(dst: &Dev, intent: Intent) -> Option<bool> {
382 match intent {
383 Intent::Absolute => Some(false),
384 Intent::Perceptual | Intent::Saturation if dst.v4 => Some(true),
385 _ => None,
386 }
387}
388
389fn to_f32(v: [f64; 4]) -> [f32; 4] {
390 [v[0] as f32, v[1] as f32, v[2] as f32, v[3] as f32]
391}
392
393/// A grey level as K alone, the black of a page whose greys are printed with the black ink only.
394pub fn grey_to_k(g: f64) -> [f32; 4] {
395 [0.0, 0.0, 0.0, (1.0 - g.clamp(0.0, 1.0)) as f32]
396}