Oregami
Repositories/oxedyne/fe2o3

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

21.8 KiB, 1 run

created by r1870400018:68833, 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 reader of ICC profiles: the header, the tag table, and the handful of tags a colour transform
2//! is built from.
3//!
4//! Every read is checked against the tag's declared offset and size, and every tag against the
5//! length of the file, before a byte is taken or a table allocated. A profile that is cut short, or
6//! whose tag directory points past its own end, is refused with a message naming the tag and the
7//! profile; nothing is read from a neighbour's bytes instead.
8//!
9//! # What is read
10//!
11//! The header; the tag table; and, of the tags in it, `desc`, `wtpt`, `chad`, the colorants
12//! `rXYZ gXYZ bXYZ`, the curves `rTRC gTRC bTRC kTRC` (`curv`, and `para` of a version 4 profile),
13//! and the lookup tables `A2B0 A2B1 A2B2` and `B2A0 B2A1 B2A2` of types `mft1` and `mft2`. The tables
14//! are kept as the integers the file holds, with the shape that says how to walk them; this module
15//! does no interpolation.
16//!
17//! # What is refused
18//!
19//! The multi-process-element tables `mAB` and `mBA` of a version 4 profile, which this reader does
20//! not read; a truncated profile or tag; a lookup table whose channel counts do not fit the
21//! profile's data space and connection space; a profile of a version other than 2 or 4. A profile
22//! that is refused is never replaced by another.
23//!
24//! # References
25//!
26//! ICC.1:2004-10 (version 4.2) for the header (§7.2), the tag table (§7.3) and the tag types
27//! (§10); ICC.1:2001-04 (version 2.4) §6.5.5 and §6.5.6 for the `lut8` and `lut16` layouts and
28//! the legacy 16-bit Lab encoding (annex A.3).
29//!
30//! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\
31//! Anthropic Claude
32
33use oxedyne_fe2o3_core::prelude::*;
34
35// Header and tag table geometry.
36const HEAD_LEN: usize = 128; // the profile header
37const ENTRY_LEN: usize = 12; // signature, offset, size
38const MAX_CH: usize = 4; // the widest lookup table a colour transform here uses
39
40pub type Sig = [u8; 4];
41
42/// FNV-1a over `bytes`, 64 bits: a stable key for a cache, not a defence against forgery.
43pub fn fnv64(bytes: &[u8]) -> u64 {
44 let mut h = 0xcbf2_9ce4_8422_2325u64;
45 for b in bytes {
46 h ^= *b as u64;
47 h = h.wrapping_mul(0x0000_0100_0000_01b3);
48 }
49 h
50}
51
52/// Names a signature for a message, with any byte outside printable ASCII shown as `?`.
53pub fn sig_str(sig: Sig) -> String {
54 sig.iter().map(|b| if (0x20..0x7f).contains(b) { *b as char } else { '?' }).collect()
55}
56
57// What the profile is for.
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub enum Class {
60 Input,
61 Display,
62 Output,
63 Link,
64 Abstract,
65 Space,
66 Named,
67 Other(Sig),
68}
69
70impl Class {
71 fn from_sig(sig: Sig) -> Self {
72 match &sig {
73 b"scnr" => Self::Input,
74 b"mntr" => Self::Display,
75 b"prtr" => Self::Output,
76 b"link" => Self::Link,
77 b"abst" => Self::Abstract,
78 b"spac" => Self::Space,
79 b"nmcl" => Self::Named,
80 _ => Self::Other(sig),
81 }
82 }
83}
84
85// A colour space: the profile's own, or the connection space.
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub enum Space {
88 Xyz,
89 Lab,
90 Rgb,
91 Gray,
92 Cmyk,
93 Other(Sig),
94}
95
96impl Space {
97 fn from_sig(sig: Sig) -> Self {
98 match &sig {
99 b"XYZ " => Self::Xyz,
100 b"Lab " => Self::Lab,
101 b"RGB " => Self::Rgb,
102 b"GRAY" => Self::Gray,
103 b"CMYK" => Self::Cmyk,
104 _ => Self::Other(sig),
105 }
106 }
107
108 /// The number of channels a colour in this space has, where this reader knows it.
109 pub fn channels(&self) -> Option<usize> {
110 match self {
111 Self::Xyz | Self::Lab | Self::Rgb => Some(3),
112 Self::Gray => Some(1),
113 Self::Cmyk => Some(4),
114 Self::Other(_) => None,
115 }
116 }
117}
118
119#[derive(Clone, Debug)]
120pub struct Header {
121 pub size: u32, // the profile's length in bytes, as it declares it
122 pub major: u8,
123 pub minor: u8,
124 pub class: Class,
125 pub space: Space, // the data colour space
126 pub pcs: Space, // the profile connection space
127 pub intent: u32, // the rendering intent the profile prefers
128 pub illum: [f64; 3], // the PCS illuminant, D50 in every profile in use
129}
130
131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
132pub struct TagEntry {
133 pub sig: Sig,
134 pub off: usize,
135 pub len: usize,
136}
137
138// A tone curve from 0..1 to 0..1.
139#[derive(Clone, Debug, PartialEq)]
140pub enum Curve {
141 Identity,
142 Gamma(f64), // curv with one entry, u8Fixed8
143 Table(Vec<u16>), // curv with two or more entries, sampled evenly
144 Para { func: u16, p: [f64; 7] }, // para, parameters g a b c d e f in that order
145}
146
147impl Curve {
148 /// The curve's value at `x`, which is clamped to `0..=1` as the result is.
149 pub fn eval(&self, x: f64) -> f64 {
150 let x = x.clamp(0.0, 1.0);
151 let y = match self {
152 Self::Identity => x,
153 Self::Gamma(g) => x.powf(*g),
154 Self::Table(t) if t.len() < 2 => x, // the reader never makes one
155 Self::Table(t) => {
156 let at = x * (t.len() - 1) as f64;
157 let i = (at.floor() as usize).min(t.len() - 2);
158 let f = at - i as f64;
159 let lo = t[i] as f64 / 65535.0;
160 let hi = t[i + 1] as f64 / 65535.0;
161 lo + (hi - lo) * f
162 },
163 Self::Para { func, p } => {
164 let (g, a, b, c, d, e, f) = (p[0], p[1], p[2], p[3], p[4], p[5], p[6]);
165 let base = (a * x + b).max(0.0);
166 match func {
167 0 => x.powf(g),
168 1 => if x >= -b / a { base.powf(g) } else { 0.0 },
169 2 => if x >= -b / a { base.powf(g) + c } else { c },
170 3 => if x >= d { base.powf(g) } else { c * x },
171 _ => if x >= d { base.powf(g) + e } else { c * x + f },
172 }
173 },
174 };
175 y.clamp(0.0, 1.0)
176 }
177
178 /// Does the curve end no lower than it starts?
179 ///
180 /// A tone reproduction curve that falls has no inverse worth taking.
181 pub fn rises(&self) -> bool {
182 self.eval(0.0) <= self.eval(1.0)
183 }
184
185 /// The smallest `x` with `eval(x) = y` on a curve that [`Curve::rises`].
186 ///
187 /// Each kind of curve has a closed form. The candidate is checked against the curve, and a
188 /// curve that is not monotone, or whose parameters have no closed form, is bisected instead.
189 pub fn inverse(&self, y: f64) -> f64 {
190 let y = y.clamp(0.0, 1.0);
191 match self.closed(y) {
192 Some(x) if (self.eval(x) - y).abs() < 1e-9 => x,
193 _ => self.bisect(y),
194 }
195 }
196
197 // The closed form of the inverse, where there is one.
198 fn closed(&self, y: f64) -> Option<f64> {
199 let x = match self {
200 Self::Identity => y,
201 Self::Gamma(g) if *g > 0.0 => y.powf(1.0 / g),
202 Self::Gamma(_) => return None,
203 Self::Table(t) if t.len() < 2 => y,
204 Self::Table(t) => {
205 // The first node at or above y, in a table that rises.
206 let k = t.partition_point(|v| (*v as f64) / 65535.0 < y);
207 if k == 0 { return Some(0.0); }
208 if k == t.len() { return Some(1.0); }
209 let (lo, hi) = (t[k - 1] as f64 / 65535.0, t[k] as f64 / 65535.0);
210 ((k - 1) as f64 + (y - lo) / (hi - lo)) / (t.len() - 1) as f64
211 },
212 Self::Para { func, p } => {
213 let (g, a, b, c, d, e, f) = (p[0], p[1], p[2], p[3], p[4], p[5], p[6]);
214 if g <= 0.0 { return None; }
215 // The power branch inverted: (a x + b)^g + off = y.
216 let pow = |off: f64| if a > 0.0 && y > off { Some(((y - off).powf(1.0 / g) - b) / a) } else { None };
217 match func {
218 0 => y.powf(1.0 / g),
219 1 => if y > 0.0 { pow(0.0)? } else { 0.0 },
220 2 => if y > c { pow(c)? } else { 0.0 },
221 3 => if c > 0.0 && y < c * d { y / c } else { pow(0.0)? },
222 _ => if c != 0.0 && y < c * d + f { (y - f) / c } else { pow(e)? },
223 }
224 },
225 };
226 Some(x.clamp(0.0, 1.0))
227 }
228
229 // The smallest `x` with `eval(x) = y` by bisection, for any curve that rises.
230 fn bisect(&self, y: f64) -> f64 {
231 let (mut lo, mut hi) = (0.0f64, 1.0f64);
232 for _ in 0..60 {
233 let mid = 0.5 * (lo + hi);
234 if self.eval(mid) < y { lo = mid; } else { hi = mid; }
235 }
236 0.5 * (lo + hi)
237 }
238}
239
240#[derive(Clone, Debug)]
241pub struct Lut {
242 pub bits: u8, // 8 for mft1, 16 for mft2
243 pub nin: usize,
244 pub nout: usize,
245 pub grid: usize, // lattice nodes along each input axis
246 pub mat: [f64; 9], // row major; applies to XYZ input only
247 pub lab_in: bool, // is the input side Lab, which LittleCMS interpolates trilinearly
248 pub ine: usize, // entries in each input curve
249 pub oute: usize, // entries in each output curve
250 pub ins: Vec<u16>, // nin curves of ine entries
251 pub clut: Vec<u16>, // grid^nin nodes of nout values, the first input slowest
252 pub outs: Vec<u16>, // nout curves of oute entries
253}
254
255impl Lut {
256 /// The largest value a table entry can hold, 255 or 65535.
257 pub fn max(&self) -> f64 {
258 if self.bits == 8 { 255.0 } else { 65535.0 }
259 }
260
261 /// The `nout` values of the lattice node at `idx`, one index per input, the first input slowest.
262 pub fn node(&self, idx: &[usize]) -> Outcome<&[u16]> {
263 if idx.len() != self.nin {
264 return Err(err!(
265 "A lookup table of {} inputs was asked for a node of {} indices.",
266 self.nin, idx.len(); Invalid, Input, Mismatch));
267 }
268 let mut at = 0usize;
269 for i in idx {
270 if *i >= self.grid {
271 return Err(err!(
272 "Index {} is beyond the {} nodes of a lookup table axis.", i, self.grid;
273 Invalid, Input, Index));
274 }
275 at = at * self.grid + *i;
276 }
277 let a = at * self.nout;
278 match self.clut.get(a..a + self.nout) {
279 Some(s) => Ok(s),
280 None => Err(err!(
281 "Node {} lies outside a lookup table of {} entries.", at, self.clut.len();
282 Invalid, Input, Index)),
283 }
284 }
285
286 /// A Lab colour in the version 2 encoding of this table, as L*, a*, b*.
287 ///
288 /// A lut16 holds the legacy encoding, where L* of 100 is 0xFF00 and a* or b* of zero is 0x8000;
289 /// a lut8 holds L* of 100 as 255 and a* or b* of zero as 128.
290 pub fn lab(&self, v: [u16; 3]) -> [f64; 3] {
291 let (l, a, b) = (v[0] as f64, v[1] as f64, v[2] as f64);
292 if self.bits == 8 {
293 [l * 100.0 / 255.0, a - 128.0, b - 128.0]
294 } else {
295 [l * 100.0 / 65280.0, a / 256.0 - 128.0, b / 256.0 - 128.0]
296 }
297 }
298}
299
300#[derive(Clone, Debug)]
301pub struct Profile {
302 pub name: String, // what the caller calls it, quoted in every message
303 pub id: u64, // FNV-1a of the profile's bytes, the identity a transform is cached by
304 pub head: Header,
305 pub tags: Vec<TagEntry>,
306 pub desc: Option<String>,
307 pub wtpt: Option<[f64; 3]>,
308 pub chad: Option<[f64; 9]>, // row major
309 pub cols: [Option<[f64; 3]>; 3], // rXYZ gXYZ bXYZ
310 pub trcs: [Option<Curve>; 3], // rTRC gTRC bTRC
311 pub ktrc: Option<Curve>,
312 pub a2b: [Option<Lut>; 3], // A2B0 A2B1 A2B2
313 pub b2a: [Option<Lut>; 3], // B2A0 B2A1 B2A2
314}
315
316// A view of one tag's bytes, whose every read is checked against its length.
317struct Rd<'a> {
318 b: &'a [u8],
319 what: &'a str,
320}
321
322impl<'a> Rd<'a> {
323 fn take(&self, at: usize, n: usize) -> Outcome<&'a [u8]> {
324 match at.checked_add(n).and_then(|end| self.b.get(at..end)) {
325 Some(s) => Ok(s),
326 None => Err(err!(
327 "The {} is {} bytes and is truncated: a read of {} bytes at byte {} runs past \
328 its end.", self.what, self.b.len(), n, at; Invalid, Input, Decode, Size)),
329 }
330 }
331
332 fn sig(&self, at: usize) -> Outcome<Sig> {
333 let s = res!(self.take(at, 4));
334 Ok([s[0], s[1], s[2], s[3]])
335 }
336
337 fn u8(&self, at: usize) -> Outcome<u8> {
338 Ok(res!(self.take(at, 1))[0])
339 }
340
341 fn u16(&self, at: usize) -> Outcome<u16> {
342 let s = res!(self.take(at, 2));
343 Ok(u16::from_be_bytes([s[0], s[1]]))
344 }
345
346 fn u32(&self, at: usize) -> Outcome<u32> {
347 let s = res!(self.take(at, 4));
348 Ok(u32::from_be_bytes([s[0], s[1], s[2], s[3]]))
349 }
350
351 // An s15Fixed16 number.
352 fn s15(&self, at: usize) -> Outcome<f64> {
353 let s = res!(self.take(at, 4));
354 Ok(i32::from_be_bytes([s[0], s[1], s[2], s[3]]) as f64 / 65536.0)
355 }
356
357 fn xyz(&self, at: usize) -> Outcome<[f64; 3]> {
358 Ok([res!(self.s15(at)), res!(self.s15(at + 4)), res!(self.s15(at + 8))])
359 }
360
361 // The 16-bit big-endian run of `n` values at `at`.
362 fn run16(&self, at: usize, n: usize) -> Outcome<Vec<u16>> {
363 let len = res!(n.checked_mul(2).ok_or_else(|| err!(
364 "The {} asks for {} 16-bit values, more than a profile can hold.", self.what, n;
365 Invalid, Input, Decode, Size)));
366 let s = res!(self.take(at, len));
367 Ok(s.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect())
368 }
369
370 fn run8(&self, at: usize, n: usize) -> Outcome<Vec<u16>> {
371 let s = res!(self.take(at, n));
372 Ok(s.iter().map(|b| *b as u16).collect())
373 }
374}
375
376impl Profile {
377 /// Reads a profile from `data`; `name` is what every message calls it.
378 pub fn read(name: &str, data: &[u8]) -> Outcome<Self> {
379 let head = res!(read_header(name, data));
380 let size = head.size as usize;
381 let whole = match data.get(..size) {
382 Some(s) => s,
383 None => return Err(err!(
384 "Profile '{}' is truncated: its header declares {} bytes and {} are present.",
385 name, size, data.len(); Invalid, Input, Decode, Size)),
386 };
387 let tags = res!(read_table(name, whole));
388
389 let mut p = Self {
390 name: name.to_string(),
391 id: fnv64(whole),
392 head,
393 tags,
394 desc: None,
395 wtpt: None,
396 chad: None,
397 cols: [None, None, None],
398 trcs: [None, None, None],
399 ktrc: None,
400 a2b: [None, None, None],
401 b2a: [None, None, None],
402 };
403 p.desc = res!(with_tag(name, whole, &p.tags, *b"desc", read_text)).flatten();
404 p.wtpt = res!(with_tag(name, whole, &p.tags, *b"wtpt", read_xyz));
405 p.chad = res!(with_tag(name, whole, &p.tags, *b"chad", read_chad));
406 for (i, sig) in [*b"rXYZ", *b"gXYZ", *b"bXYZ"].into_iter().enumerate() {
407 p.cols[i] = res!(with_tag(name, whole, &p.tags, sig, read_xyz));
408 }
409 for (i, sig) in [*b"rTRC", *b"gTRC", *b"bTRC"].into_iter().enumerate() {
410 p.trcs[i] = res!(with_tag(name, whole, &p.tags, sig, read_curve));
411 }
412 p.ktrc = res!(with_tag(name, whole, &p.tags, *b"kTRC", read_curve));
413 for (i, sig) in [*b"A2B0", *b"A2B1", *b"A2B2"].into_iter().enumerate() {
414 p.a2b[i] = res!(with_tag(name, whole, &p.tags, sig, read_lut));
415 if let Some(lut) = &mut p.a2b[i] {
416 res!(check_lut(name, sig, lut, &p.head, true));
417 lut.lab_in = p.head.space == Space::Lab;
418 }
419 }
420 for (i, sig) in [*b"B2A0", *b"B2A1", *b"B2A2"].into_iter().enumerate() {
421 p.b2a[i] = res!(with_tag(name, whole, &p.tags, sig, read_lut));
422 if let Some(lut) = &mut p.b2a[i] {
423 res!(check_lut(name, sig, lut, &p.head, false));
424 lut.lab_in = p.head.pcs == Space::Lab;
425 }
426 }
427 Ok(p)
428 }
429
430 /// Does the tag table hold `sig`?
431 pub fn has(&self, sig: Sig) -> bool {
432 self.tags.iter().any(|e| e.sig == sig)
433 }
434}
435
436fn read_header(name: &str, data: &[u8]) -> Outcome<Header> {
437 let what = fmt!("header of profile '{}'", name);
438 let h = match data.get(..HEAD_LEN) {
439 Some(h) => h,
440 None => return Err(err!(
441 "Profile '{}' is truncated: {} bytes are present and its header alone is {}.",
442 name, data.len(), HEAD_LEN; Invalid, Input, Decode, Size)),
443 };
444 let rd = Rd { b: h, what: &what };
445 if res!(rd.sig(36)) != *b"acsp" {
446 return Err(err!(
447 "Profile '{}' lacks the 'acsp' signature at byte 36, so it is not an ICC profile.",
448 name; Invalid, Input, Decode));
449 }
450 let size = res!(rd.u32(0));
451 if (size as usize) < HEAD_LEN + 4 {
452 return Err(err!(
453 "Profile '{}' declares a length of {} bytes, which cannot hold a header and a tag count.",
454 name, size; Invalid, Input, Decode, Size));
455 }
456 let major = res!(rd.u8(8));
457 let minor = res!(rd.u8(9)) >> 4;
458 if major != 2 && major != 4 {
459 return Err(err!(
460 "Profile '{}' is version {}.{}, and this reader reads versions 2 and 4.",
461 name, major, minor; Invalid, Input, Decode, NoImpl));
462 }
463 Ok(Header {
464 size,
465 major,
466 minor,
467 class: Class::from_sig(res!(rd.sig(12))),
468 space: Space::from_sig(res!(rd.sig(16))),
469 pcs: Space::from_sig(res!(rd.sig(20))),
470 intent: res!(rd.u32(64)),
471 illum: res!(rd.xyz(68)),
472 })
473}
474
475fn read_table(name: &str, whole: &[u8]) -> Outcome<Vec<TagEntry>> {
476 let what = fmt!("tag table of profile '{}'", name);
477 let rd = Rd { b: whole, what: &what };
478 let n = res!(rd.u32(HEAD_LEN)) as usize;
479 let mut tags = Vec::new();
480 for i in 0..n {
481 let at = HEAD_LEN + 4 + i * ENTRY_LEN;
482 let sig = res!(rd.sig(at));
483 let off = res!(rd.u32(at + 4)) as usize;
484 let len = res!(rd.u32(at + 8)) as usize;
485 match off.checked_add(len) {
486 Some(end) if end <= whole.len() => (),
487 _ => return Err(err!(
488 "Tag '{}' of profile '{}' runs from byte {} for {} bytes, past the profile's end \
489 at {}, so the profile is truncated.", sig_str(sig), name, off, len, whole.len();
490 Invalid, Input, Decode, Size)),
491 }
492 tags.push(TagEntry { sig, off, len });
493 }
494 Ok(tags)
495}
496
497// Reads the first tag named `sig` with `f`, handing it a view bounded by the tag's declared size.
498fn with_tag<T>(
499 name: &str,
500 whole: &[u8],
501 tags: &[TagEntry],
502 sig: Sig,
503 f: impl FnOnce(&Rd) -> Outcome<T>,
504)
505 -> Outcome<Option<T>>
506{
507 let e = match tags.iter().find(|e| e.sig == sig) {
508 Some(e) => e,
509 None => return Ok(None),
510 };
511 let what = fmt!("tag '{}' of profile '{}'", sig_str(sig), name);
512 let b = match whole.get(e.off..e.off + e.len) {
513 Some(b) => b,
514 None => return Err(err!(
515 "The {} lies outside the profile.", what; Invalid, Input, Decode, Size)),
516 };
517 Ok(Some(res!(f(&Rd { b, what: &what }))))
518}
519
520fn read_xyz(rd: &Rd) -> Outcome<[f64; 3]> {
521 let kind = res!(rd.sig(0));
522 if kind != *b"XYZ " {
523 return Err(err!(
524 "The {} is of type '{}', and an XYZ number tag is of type 'XYZ '.",
525 rd.what, sig_str(kind); Invalid, Input, Decode));
526 }
527 rd.xyz(8)
528}
529
530fn read_chad(rd: &Rd) -> Outcome<[f64; 9]> {
531 let kind = res!(rd.sig(0));
532 if kind != *b"sf32" {
533 return Err(err!(
534 "The {} is of type '{}', and a chromatic adaptation tag is of type 'sf32'.",
535 rd.what, sig_str(kind); Invalid, Input, Decode));
536 }
537 let mut m = [0.0; 9];
538 for (i, v) in m.iter_mut().enumerate() {
539 *v = res!(rd.s15(8 + 4 * i));
540 }
541 Ok(m)
542}
543
544// The description, from a version 2 `desc` or a version 4 `mluc`; any other type reads as none.
545fn read_text(rd: &Rd) -> Outcome<Option<String>> {
546 let kind = res!(rd.sig(0));
547 if kind == *b"desc" {
548 let n = res!(rd.u32(8)) as usize;
549 let s = res!(rd.take(12, n));
550 let end = s.iter().position(|b| *b == 0).unwrap_or(s.len());
551 return Ok(Some(String::from_utf8_lossy(&s[..end]).into_owned()));
552 }
553 if kind == *b"mluc" {
554 let count = res!(rd.u32(8));
555 if count == 0 {
556 return Ok(None);
557 }
558 // The first record: language, country, byte length, byte offset from the tag's start.
559 let len = res!(rd.u32(20)) as usize;
560 let off = res!(rd.u32(24)) as usize;
561 let s = res!(rd.take(off, len));
562 let units: Vec<u16> = s.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect();
563 return Ok(Some(String::from_utf16_lossy(&units)));
564 }
565 Ok(None)
566}
567
568fn read_curve(rd: &Rd) -> Outcome<Curve> {
569 let kind = res!(rd.sig(0));
570 if kind == *b"curv" {
571 let n = res!(rd.u32(8)) as usize;
572 return match n {
573 0 => Ok(Curve::Identity),
574 1 => Ok(Curve::Gamma(res!(rd.u16(12)) as f64 / 256.0)),
575 _ => Ok(Curve::Table(res!(rd.run16(12, n)))),
576 };
577 }
578 if kind == *b"para" {
579 let func = res!(rd.u16(8));
580 let count = match func {
581 0 => 1,
582 1 => 3,
583 2 => 4,
584 3 => 5,
585 4 => 7,
586 _ => return Err(err!(
587 "The {} is a parametric curve of function type {}, and the types are 0 to 4.",
588 rd.what, func; Invalid, Input, Decode, NoImpl)),
589 };
590 let mut p = [0.0; 7];
591 for (i, v) in p.iter_mut().enumerate().take(count) {
592 *v = res!(rd.s15(12 + 4 * i));
593 }
594 if (func == 1 || func == 2) && p[1] == 0.0 {
595 return Err(err!(
596 "The {} is a parametric curve of function type {} with a = 0, which has no \
597 threshold -b/a.", rd.what, func; Invalid, Input, Decode));
598 }
599 return Ok(Curve::Para { func, p });
600 }
601 Err(err!(
602 "The {} is of type '{}', and this reader reads a curve of type 'curv' or 'para'.",
603 rd.what, sig_str(kind); Invalid, Input, Decode, NoImpl))
604}
605
606fn read_lut(rd: &Rd) -> Outcome<Lut> {
607 let kind = res!(rd.sig(0));
608 let bits = match &kind {
609 b"mft1" => 8u8,
610 b"mft2" => 16u8,
611 b"mAB " | b"mBA " => return Err(err!(
612 "The {} is of type '{}', a multi-process-element table of a version 4 profile, which \
613 this reader does not read. No other profile is substituted for it.",
614 rd.what, sig_str(kind); Invalid, Input, Decode, NoImpl)),
615 _ => return Err(err!(
616 "The {} is of type '{}', and this reader reads a lookup table of type 'mft1' or \
617 'mft2'.", rd.what, sig_str(kind); Invalid, Input, Decode, NoImpl)),
618 };
619 let nin = res!(rd.u8(8)) as usize;
620 let nout = res!(rd.u8(9)) as usize;
621 let grid = res!(rd.u8(10)) as usize;
622 if nin == 0 || nin > MAX_CH || nout == 0 || nout > MAX_CH || grid < 2 {
623 return Err(err!(
624 "The {} has {} input and {} output channels and {} nodes an axis, and this reader \
625 reads 1 to {} channels and 2 or more nodes.", rd.what, nin, nout, grid, MAX_CH;
626 Invalid, Input, Decode, NoImpl));
627 }
628 let mut mat = [0.0; 9];
629 for (i, v) in mat.iter_mut().enumerate() {
630 *v = res!(rd.s15(12 + 4 * i));
631 }
632 let (ine, oute, start) = if bits == 8 {
633 (256usize, 256usize, 48usize)
634 } else {
635 let ine = res!(rd.u16(48)) as usize;
636 let oute = res!(rd.u16(50)) as usize;
637 if ine < 2 || oute < 2 {
638 return Err(err!(
639 "The {} has curves of {} input and {} output entries, and a curve needs 2 or more.",
640 rd.what, ine, oute; Invalid, Input, Decode));
641 }
642 (ine, oute, 52usize)
643 };
644 let width = (bits / 8) as usize;
645 let nodes = res!(grid.checked_pow(nin as u32).ok_or_else(|| err!(
646 "The {} has {} nodes on each of {} axes, more than a profile can hold.",
647 rd.what, grid, nin; Invalid, Input, Decode, Size)));
648 let n_in = nin * ine;
649 let n_clut = res!(nodes.checked_mul(nout).ok_or_else(|| err!(
650 "The {} has {} nodes of {} values, more than a profile can hold.",
651 rd.what, nodes, nout; Invalid, Input, Decode, Size)));
652 let n_out = nout * oute;
653 let read = |at: usize, n: usize| if bits == 8 { rd.run8(at, n) } else { rd.run16(at, n) };
654 let ins = res!(read(start, n_in));
655 let clut = res!(read(start + n_in * width, n_clut));
656 let outs = res!(read(start + (n_in + n_clut) * width, n_out));
657 Ok(Lut { bits, nin, nout, grid, mat, lab_in: false, ine, oute, ins, clut, outs })
658}
659
660// Does a lookup table's shape fit the profile it is in?
661fn check_lut(name: &str, sig: Sig, lut: &Lut, head: &Header, a2b: bool) -> Outcome<()> {
662 let (dev_side, pcs_side) = if a2b { (lut.nin, lut.nout) } else { (lut.nout, lut.nin) };
663 let dev_want = head.space.channels();
664 let pcs_want = head.pcs.channels();
665 if dev_want.map_or(false, |n| n != dev_side) || pcs_want.map_or(false, |n| n != pcs_side) {
666 return Err(err!(
667 "Tag '{}' of profile '{}' maps {} channels to {}, which does not fit a {:?} profile \
668 with a {:?} connection space.", sig_str(sig), name, lut.nin, lut.nout, head.space,
669 head.pcs; Invalid, Input, Decode, Mismatch));
670 }
671 Ok(())
672}