Debian Codegraph @

rust/icc/FFI.rs

raw
1 // Copyright 2025 Google LLC
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 //! ICC profile parser FFI bindings.
6 //!
7 //! Provides C++ bindings for parsing ICC profiles using moxcms. All parsing
8 //! happens in Rust for memory safety, then validated data is converted to
9 //! skcms-compatible structures for color transformations.
10
11 // No `use moxcms::...` nor `use ffi::...` because we want the code to explicitly
12 // spell out if it means types from the moxcms crate vs types from the ffi module.
13
14 #[cxx::bridge(namespace = "rust_icc")]
15 mod ffi {
16 /// Color space types (matches skcms_Signature enum values).
17 #[repr(u32)]
18 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
19 enum skcms_Signature {
20 skcms_Signature_CMYK = 0x434D594B,
21 skcms_Signature_Gray = 0x47524159,
22 skcms_Signature_RGB = 0x52474220,
23 skcms_Signature_Lab = 0x4C616220,
24 skcms_Signature_XYZ = 0x58595A20,
25 skcms_Signature_CIELUV = 0x4C757620,
26 skcms_Signature_YCbCr = 0x59436272,
27 skcms_Signature_CIEYxy = 0x59787920,
28 skcms_Signature_HSV = 0x48535620,
29 skcms_Signature_HLS = 0x484C5320,
30 skcms_Signature_CMY = 0x434D5920,
31 skcms_Signature_2CLR = 0x32434C52,
32 skcms_Signature_3CLR = 0x33434C52,
33 skcms_Signature_4CLR = 0x34434C52,
34 skcms_Signature_5CLR = 0x35434C52,
35 skcms_Signature_6CLR = 0x36434C52,
36 skcms_Signature_7CLR = 0x37434C52,
37 skcms_Signature_8CLR = 0x38434C52,
38 skcms_Signature_9CLR = 0x39434C52,
39 skcms_Signature_10CLR = 0x41434C52,
40 skcms_Signature_11CLR = 0x42434C52,
41 skcms_Signature_12CLR = 0x43434C52,
42 skcms_Signature_13CLR = 0x44434C52,
43 skcms_Signature_14CLR = 0x45434C52,
44 skcms_Signature_15CLR = 0x46434C52,
45 }
46
47 // Extern enum definition to assure that CXX will generate static
48 // assertions to verify that the enum values match between Rust and C++.
49 extern "C++" {
50 include!("modules/skcms/skcms.h");
51
52 #[namespace = ""]
53 type skcms_Signature;
54 }
55
56 // The types below re-define C structs defined in `skcms_public.h`.
57 // The type definitions below have to be manually kept in-sync with the ones
58 // in `skcms_public.h`. Some guardrails exist, but they are not 100% accurate:
59 //
60 // * `static_assert`s in `rust/icc/FFI.cpp` verify that the 2 types are
61 // `std::is_layout_compatible` (this won't catch if the order of two
62 // field definitions is swapped for fields of the same type)
63 // * Tests in `tests/RustIccTest.cpp` verify round-tripping
64 // (this should catch issues with order of *known* fields)
65 //
66 // TODO(https://crbug.com/462751628): If all Skia clients using Rust codecs
67 // support `bindgen`, then it may be possible to avoid duplicating / redefining
68 // the types below.
69
70 /// 3x3 matrix for color space transforms (matches skcms_Matrix3x3).
71 struct Matrix3x3 {
72 vals: [[f32; 3]; 3],
73 }
74
75 /// Transfer function parameters (matches skcms_TransferFunction).
76 #[derive(Clone, Copy, Default)]
77 struct TransferFunction {
78 g: f32,
79 a: f32,
80 b: f32,
81 c: f32,
82 d: f32,
83 e: f32,
84 f: f32,
85 }
86
87 /// CICP color metadata (matches skcms_CICP).
88 #[derive(Clone, Copy)]
89 struct Cicp {
90 color_primaries: u8,
91 transfer_characteristics: u8,
92 matrix_coefficients: u8,
93 video_full_range_flag: u8,
94 }
95
96 /// Curve for LUT transforms - parametric or table-based (matches skcms_Curve).
97 struct Curve {
98 table_entries: u32, // 0 = parametric, >0 = table
99 parametric: TransferFunction,
100 table_data: Vec<u8>, // u16 values as bytes (little-endian) for tables
101 }
102
103 /// Device-to-PCS transform (matches skcms_A2B).
104 struct A2B {
105 input_curves: Vec<Curve>,
106 input_channels: u32,
107 grid_points: [u8; 4],
108 grid_data: Vec<u8>,
109 is_16bit_grid: bool,
110 matrix_curves: Vec<Curve>,
111 matrix: Matrix3x3,
112 matrix_bias: [f32; 3],
113 matrix_channels: u32,
114 output_curves: Vec<Curve>,
115 output_channels: u32,
116 }
117
118 /// PCS-to-device transform (matches skcms_B2A).
119 struct B2A {
120 /// Required: 3 1D "B" curves. Always present.
121 input_curves: Vec<Curve>,
122 input_channels: u32,
123
124 /// Optional: 3x4 matrix followed by 3 1D "M" curves.
125 /// If matrix_channels == 0, matrix and curves are skipped.
126 matrix: Matrix3x3,
127 matrix_bias: [f32; 3],
128 matrix_curves: Vec<Curve>,
129 matrix_channels: u32,
130
131 /// Optional: N-D CLUT followed by N 1D "A" curves.
132 /// If output_channels == 0, CLUT and curves are skipped.
133 grid_points: [u8; 4],
134 grid_data: Vec<u8>,
135 is_16bit_grid: bool,
136 output_curves: Vec<Curve>,
137 output_channels: u32,
138 }
139
140 /// Parsed ICC profile data.
141 struct IccProfile {
142 data_color_space: skcms_Signature,
143 connection_space: skcms_Signature,
144 to_xyzd50: Matrix3x3,
145 has_to_xyzd50: bool,
146 trc: [TransferFunction; 3],
147 has_trc: bool,
148 cicp: Cicp,
149 has_cicp: bool,
150 a2b: A2B,
151 has_a2b: bool,
152 b2a: B2A,
153 has_b2a: bool,
154 }
155
156 // C++ wrapper for skcms_ApproximateCurve.
157 // Using cxx::bridge for compile-time type safety.
158 // The C++ side (FFI.cpp) wraps skcms_ApproximateCurve, so any signature changes
159 // in skcms will cause a compile error rather than silent ABI breakage.
160 unsafe extern "C++" {
161 include!("rust/icc/FFI.h");
162
163 #[cxx_name = "ApproximateCurveWrapper"]
164 fn approximate_curve_wrapper(
165 table: &[u16],
166 out_approx: &mut TransferFunction,
167 out_max_error: &mut f32,
168 ) -> bool;
169 }
170
171 extern "Rust" {
172 /// Parses ICC profile from `data`. If successful, returns `true`
173 /// and writes result to `out`. If failure, returns `false`.
174 fn parse_icc_profile(data: &[u8], out: &mut IccProfile) -> bool;
175 }
176 }
177
178 /// Identifies whether we're parsing an A2B or B2A tag from the ICC profile.
179 /// This affects encoding factors applied during matrix conversion.
180 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
181 enum LutTagType {
182 /// A2B tag (device-to-PCS transform)
183 A2B,
184 /// B2A tag (PCS-to-device transform)
185 B2A,
186 }
187
188 /// Parses ICC profile from `data`. If successful, returns `true`
189 /// and writes result to `out`. If failure, returns `false`.
190 pub fn parse_icc_profile(data: &[u8], out: &mut ffi::IccProfile) -> bool {
191 // Parse with moxcms (it validates size, signature, etc.)
192 let Ok(profile) = moxcms::ColorProfile::new_from_slice(data) else {
193 return false;
194 };
195
196 // Convert moxcms DataColorSpace to our skcms_Signature enum
197 // NOTE: This match is intentionally exhaustive (no catch-all pattern).
198 // If moxcms adds new DataColorSpace variants, this will fail to compile,
199 // forcing us to consciously decide how to map the new variant.
200 out.data_color_space = match profile.color_space {
201 moxcms::DataColorSpace::Xyz => ffi::skcms_Signature::skcms_Signature_XYZ,
202 moxcms::DataColorSpace::Lab => ffi::skcms_Signature::skcms_Signature_Lab,
203 moxcms::DataColorSpace::Luv => ffi::skcms_Signature::skcms_Signature_CIELUV,
204 moxcms::DataColorSpace::YCbr => ffi::skcms_Signature::skcms_Signature_YCbCr,
205 moxcms::DataColorSpace::Yxy => ffi::skcms_Signature::skcms_Signature_CIEYxy,
206 moxcms::DataColorSpace::Rgb => ffi::skcms_Signature::skcms_Signature_RGB,
207 moxcms::DataColorSpace::Gray => ffi::skcms_Signature::skcms_Signature_Gray,
208 moxcms::DataColorSpace::Hsv => ffi::skcms_Signature::skcms_Signature_HSV,
209 moxcms::DataColorSpace::Hls => ffi::skcms_Signature::skcms_Signature_HLS,
210 moxcms::DataColorSpace::Cmyk => ffi::skcms_Signature::skcms_Signature_CMYK,
211 moxcms::DataColorSpace::Cmy => ffi::skcms_Signature::skcms_Signature_CMY,
212 // Multi-channel color spaces recognized by skcms
213 moxcms::DataColorSpace::Color2 => ffi::skcms_Signature::skcms_Signature_2CLR,
214 moxcms::DataColorSpace::Color3 => ffi::skcms_Signature::skcms_Signature_3CLR,
215 moxcms::DataColorSpace::Color4 => ffi::skcms_Signature::skcms_Signature_4CLR,
216 moxcms::DataColorSpace::Color5 => ffi::skcms_Signature::skcms_Signature_5CLR,
217 moxcms::DataColorSpace::Color6 => ffi::skcms_Signature::skcms_Signature_6CLR,
218 moxcms::DataColorSpace::Color7 => ffi::skcms_Signature::skcms_Signature_7CLR,
219 moxcms::DataColorSpace::Color8 => ffi::skcms_Signature::skcms_Signature_8CLR,
220 moxcms::DataColorSpace::Color9 => ffi::skcms_Signature::skcms_Signature_9CLR,
221 moxcms::DataColorSpace::Color10 => ffi::skcms_Signature::skcms_Signature_10CLR,
222 moxcms::DataColorSpace::Color11 => ffi::skcms_Signature::skcms_Signature_11CLR,
223 moxcms::DataColorSpace::Color12 => ffi::skcms_Signature::skcms_Signature_12CLR,
224 moxcms::DataColorSpace::Color13 => ffi::skcms_Signature::skcms_Signature_13CLR,
225 moxcms::DataColorSpace::Color14 => ffi::skcms_Signature::skcms_Signature_14CLR,
226 moxcms::DataColorSpace::Color15 => ffi::skcms_Signature::skcms_Signature_15CLR,
227 };
228
229 // Profile Connection Space (PCS) must be XYZ or Lab per ICC spec.
230 // skcms only supports these two PCS values. Reject profiles with other values
231 // to match skcms_ParseWithA2BPriority behavior.
232 out.connection_space = match profile.pcs {
233 moxcms::DataColorSpace::Xyz => ffi::skcms_Signature::skcms_Signature_XYZ,
234 moxcms::DataColorSpace::Lab => ffi::skcms_Signature::skcms_Signature_Lab,
235 _ => return false, // Reject unsupported PCS
236 };
237
238 let matrix = profile.colorant_matrix();
239 out.to_xyzd50 = matrix3d_to_ffi(&matrix);
240 out.has_to_xyzd50 = is_valid_colorant_matrix(&matrix);
241
242 out.has_trc = false;
243 if let Some(gray_trc) = &profile.gray_trc {
244 if let Some(tf) = convert_trc_to_transfer_function(gray_trc) {
245 out.trc = [tf, tf, tf];
246 out.has_trc = true;
247 }
248 } else if let (Some(r_trc), Some(g_trc), Some(b_trc)) =
249 (&profile.red_trc, &profile.green_trc, &profile.blue_trc)
250 {
251 if let (Some(r_tf), Some(g_tf), Some(b_tf)) = (
252 convert_trc_to_transfer_function(r_trc),
253 convert_trc_to_transfer_function(g_trc),
254 convert_trc_to_transfer_function(b_trc),
255 ) {
256 out.trc = [r_tf, g_tf, b_tf];
257 out.has_trc = true;
258 }
259 }
260
261 out.has_cicp = false;
262 if let Some(cicp) = &profile.cicp {
263 out.cicp = ffi::Cicp {
264 color_primaries: cicp.color_primaries as u8,
265 transfer_characteristics: cicp.transfer_characteristics as u8,
266 matrix_coefficients: cicp.matrix_coefficients as u8,
267 video_full_range_flag: if cicp.full_range { 1 } else { 0 },
268 };
269 out.has_cicp = true;
270 }
271
272 // Extract A2B transform (device-to-PCS with LUTs)
273 out.has_a2b = false;
274 if let Some(ref lut) = profile
275 .lut_a_to_b_perceptual
276 .as_ref()
277 .or(profile.lut_a_to_b_colorimetric.as_ref())
278 .or(profile.lut_a_to_b_saturation.as_ref())
279 {
280 if let Some(a2b) = convert_to_a2b(lut, profile.pcs, LutTagType::A2B) {
281 out.a2b = a2b;
282 out.has_a2b = true;
283 }
284 }
285
286 // Extract B2A transform (PCS-to-device with LUTs)
287 out.has_b2a = false;
288 if let Some(ref lut) = profile
289 .lut_b_to_a_perceptual
290 .as_ref()
291 .or(profile.lut_b_to_a_colorimetric.as_ref())
292 .or(profile.lut_b_to_a_saturation.as_ref())
293 {
294 if let Some(a2b_data) = convert_to_a2b(lut, profile.pcs, LutTagType::B2A) {
295 out.b2a = a2b_to_b2a(a2b_data);
296 out.has_b2a = true;
297 }
298 }
299
300 true
301 }
302
303 /// Convert Vec<u16> to Vec<u8> in little-endian byte order.
304 fn u16_vec_to_bytes(values: &[u16]) -> Vec<u8> {
305 let mut bytes = Vec::with_capacity(values.len() * 2);
306 for value in values {
307 bytes.extend(value.to_le_bytes());
308 }
309 bytes
310 }
311
312 /// Validate colorant matrix: each column must have at least one non-zero value.
313 /// Each column represents a colorant's contribution to XYZ (red, green, blue).
314 /// An all-zero column would mean that colorant contributes nothing, which is invalid.
315 /// moxcms returns a zero matrix when colorant tags (rXYZ, gXYZ, bXYZ) are missing.
316 fn is_valid_colorant_matrix(matrix: &moxcms::Matrix3d) -> bool {
317 let column_has_value = |col: usize| -> bool {
318 matrix.v[0][col] != 0.0 || matrix.v[1][col] != 0.0 || matrix.v[2][col] != 0.0
319 };
320 column_has_value(0) && column_has_value(1) && column_has_value(2)
321 }
322
323 /// Convert moxcms Matrix3d to FFI Matrix3x3.
324 fn matrix3d_to_ffi(matrix: &moxcms::Matrix3d) -> ffi::Matrix3x3 {
325 ffi::Matrix3x3 {
326 vals: [
327 [
328 matrix.v[0][0] as f32,
329 matrix.v[0][1] as f32,
330 matrix.v[0][2] as f32,
331 ],
332 [
333 matrix.v[1][0] as f32,
334 matrix.v[1][1] as f32,
335 matrix.v[1][2] as f32,
336 ],
337 [
338 matrix.v[2][0] as f32,
339 matrix.v[2][1] as f32,
340 matrix.v[2][2] as f32,
341 ],
342 ],
343 }
344 }
345
346 /// Convert LutStore to Vec<u16>, scaling 8-bit values to 16-bit range if needed.
347 fn lut_store_to_u16(store: &moxcms::LutStore) -> Vec<u16> {
348 match store {
349 moxcms::LutStore::Store8(data) => data
350 .iter()
351 .map(|&v| {
352 let v16 = v as u16;
353 (v16 << 8) | v16
354 })
355 .collect(),
356 moxcms::LutStore::Store16(data) => data.clone(),
357 }
358 }
359
360 /// Split a flat table into per-channel curves.
361 /// Returns empty Vec if table is too small for the expected layout.
362 fn split_table_to_curves(
363 table_data: &[u16],
364 entries_per_channel: usize,
365 num_channels: usize,
366 ) -> Vec<ffi::Curve> {
367 if table_data.is_empty() || table_data.len() < entries_per_channel * num_channels {
368 return Vec::new();
369 }
370
371 (0..num_channels)
372 .map(|ch| {
373 let start = ch * entries_per_channel;
374 let end = start + entries_per_channel;
375 let channel_table = &table_data[start..end];
376
377 ffi::Curve {
378 table_entries: entries_per_channel as u32,
379 parametric: ffi::TransferFunction::default(),
380 table_data: u16_vec_to_bytes(channel_table),
381 }
382 })
383 .collect()
384 }
385
386 /// Convert A2B structure to B2A by reversing the transform direction.
387 /// B2A is the inverse of A2B: output curves become input, input curves become output.
388 fn a2b_to_b2a(a2b: ffi::A2B) -> ffi::B2A {
389 ffi::B2A {
390 input_curves: a2b.output_curves,
391 input_channels: a2b.output_channels,
392 matrix: a2b.matrix,
393 matrix_bias: a2b.matrix_bias,
394 matrix_curves: a2b.matrix_curves,
395 matrix_channels: a2b.matrix_channels,
396 grid_points: a2b.grid_points,
397 grid_data: a2b.grid_data,
398 is_16bit_grid: a2b.is_16bit_grid,
399 output_curves: a2b.input_curves,
400 output_channels: a2b.input_channels,
401 }
402 }
403
404 /// Convert LutStore grid data to bytes.
405 /// Returns (grid_data, is_16bit_grid).
406 fn convert_grid_data(clut: &moxcms::LutStore) -> (Vec<u8>, bool) {
407 use moxcms::LutStore;
408 match clut {
409 LutStore::Store8(data) => (data.clone(), false),
410 LutStore::Store16(data) => (u16_vec_to_bytes(data), true),
411 }
412 }
413
414 /// Apply encoding factor to matrix and bias for PCS XYZ conversion.
415 /// Modifies matrix and bias in place.
416 ///
417 /// skcms applies different encoding factors for A2B vs B2A tags when PCS is XYZ.
418 /// See modules/skcms/skcms.cc read_tag_mab (A2B) and read_tag_mba() (B2A)
419 fn apply_encoding_factor(
420 matrix: &mut ffi::Matrix3x3,
421 matrix_bias: &mut [f32; 3],
422 pcs: moxcms::DataColorSpace,
423 tag_type: LutTagType,
424 ) {
425 if !matches!(pcs, moxcms::DataColorSpace::Xyz) {
426 return;
427 }
428
429 let encoding_factor = match tag_type {
430 LutTagType::A2B => 65535.0 / 32768.0,
431 LutTagType::B2A => 32768.0 / 65535.0,
432 };
433
434 for i in 0..3 {
435 for j in 0..3 {
436 matrix.vals[i][j] *= encoding_factor;
437 }
438 matrix_bias[i] *= encoding_factor;
439 }
440 }
441
442 /// Convert moxcms ParametricCurve to FFI TransferFunction.
443 fn parametric_curve_to_transfer_function(curve: &moxcms::ParametricCurve) -> ffi::TransferFunction {
444 ffi::TransferFunction {
445 g: curve.g,
446 a: curve.a,
447 b: curve.b,
448 c: curve.c,
449 d: curve.d,
450 e: curve.e,
451 f: curve.f,
452 }
453 }
454
455 /// Convert moxcms ToneReprCurve to FFI Curve structure.
456 /// Supports both parametric and table-based curves.
457 /// Returns None if the curve is empty or invalid.
458 fn convert_to_curve(trc: &moxcms::ToneReprCurve) -> Option<ffi::Curve> {
459 use moxcms::ToneReprCurve;
460
461 match trc {
462 ToneReprCurve::Parametric(params) => {
463 moxcms::ParametricCurve::new(params).map(|curve| ffi::Curve {
464 table_entries: 0,
465 parametric: parametric_curve_to_transfer_function(&curve),
466 table_data: Vec::new(),
467 })
468 }
469 ToneReprCurve::Lut(table) => {
470 if table.is_empty() {
471 return Some(ffi::Curve {
472 table_entries: 0,
473 parametric: ffi::TransferFunction {
474 g: 1.0,
475 a: 1.0,
476 b: 0.0,
477 c: 0.0,
478 d: 0.0,
479 e: 0.0,
480 f: 0.0,
481 },
482 table_data: Vec::new(),
483 });
484 }
485
486 Some(ffi::Curve {
487 table_entries: table.len() as u32,
488 parametric: ffi::TransferFunction::default(),
489 table_data: u16_vec_to_bytes(table),
490 })
491 }
492 }
493 }
494
495 /// Convert moxcms LutWarehouse to A2B structure.
496 /// Returns None if the LUT cannot be converted.
497 fn convert_to_a2b(
498 lut: &moxcms::LutWarehouse,
499 pcs: moxcms::DataColorSpace,
500 tag_type: LutTagType,
501 ) -> Option<ffi::A2B> {
502 use moxcms::LutWarehouse;
503
504 match lut {
505 LutWarehouse::Multidimensional(mdt) => {
506 let input_curves: Vec<ffi::Curve> = mdt
507 .a_curves
508 .iter()
509 .filter_map(|c| convert_to_curve(c))
510 .collect();
511
512 let (grid_data, is_16bit_grid) = if let Some(ref clut) = mdt.clut {
513 convert_grid_data(clut)
514 } else {
515 (Vec::new(), false)
516 };
517
518 let matrix_curves: Vec<ffi::Curve> = mdt
519 .m_curves
520 .iter()
521 .filter_map(|c| convert_to_curve(c))
522 .collect();
523
524 let mut matrix = matrix3d_to_ffi(&mdt.matrix);
525 let mut matrix_bias = [
526 mdt.bias.v[0] as f32,
527 mdt.bias.v[1] as f32,
528 mdt.bias.v[2] as f32,
529 ];
530 apply_encoding_factor(&mut matrix, &mut matrix_bias, pcs, tag_type);
531
532 let output_curves: Vec<ffi::Curve> = mdt
533 .b_curves
534 .iter()
535 .filter_map(|c| convert_to_curve(c))
536 .collect();
537
538 let grid_points: [u8; 4] = mdt.grid_points[..4].try_into().unwrap();
539
540 let matrix_channels = if matrix_curves.is_empty() { 0 } else { 3 };
541
542 if output_curves.is_empty() {
543 return None;
544 }
545
546 // If there is no CLUT, input and output channels must match
547 // and we set input_channels to 0 to signal "skip this stage"
548 let (final_input_channels, final_input_curves) = if grid_data.is_empty() {
549 if mdt.num_input_channels != mdt.num_output_channels {
550 return None;
551 }
552 (0, Vec::new())
553 } else {
554 if input_curves.is_empty() {
555 return None;
556 }
557 (mdt.num_input_channels as u32, input_curves)
558 };
559
560 Some(ffi::A2B {
561 input_curves: final_input_curves,
562 input_channels: final_input_channels,
563 grid_points,
564 grid_data,
565 is_16bit_grid,
566 matrix_curves,
567 matrix,
568 matrix_bias,
569 matrix_channels,
570 output_curves,
571 output_channels: mdt.num_output_channels as u32,
572 })
573 }
574 LutWarehouse::Lut(ldt) => {
575 // Legacy Lut8Type/Lut16Type (mft1/mft2 tags)
576 // Similar structure to Multidimensional, but uses uniform grid size
577
578 let input_curves: Vec<ffi::Curve> = {
579 let curve_data = lut_store_to_u16(&ldt.input_table);
580 split_table_to_curves(
581 &curve_data,
582 ldt.num_input_table_entries as usize,
583 ldt.num_input_channels as usize,
584 )
585 };
586
587 let (grid_data, is_16bit_grid) = convert_grid_data(&ldt.clut_table);
588
589 let grid_size = ldt.num_clut_grid_points;
590 let grid_points: [u8; 4] = match ldt.num_input_channels {
591 3 => [grid_size, grid_size, grid_size, 0],
592 4 => [grid_size, grid_size, grid_size, grid_size],
593 _ => [grid_size, 0, 0, 0], // 1D or 2D case
594 };
595
596 let mut matrix = matrix3d_to_ffi(&ldt.matrix);
597 // Legacy LUT matrix is typically applied post-CLUT, so bias is zero
598 let mut matrix_bias = [0.0, 0.0, 0.0];
599 apply_encoding_factor(&mut matrix, &mut matrix_bias, pcs, tag_type);
600
601 let output_curves: Vec<ffi::Curve> = {
602 let curve_data = lut_store_to_u16(&ldt.output_table);
603 split_table_to_curves(
604 &curve_data,
605 ldt.num_output_table_entries as usize,
606 ldt.num_output_channels as usize,
607 )
608 };
609
610 let matrix_curves: Vec<ffi::Curve> = Vec::new();
611 let matrix_channels = 0;
612
613 Some(ffi::A2B {
614 input_curves,
615 input_channels: ldt.num_input_channels as u32,
616 grid_points,
617 grid_data,
618 is_16bit_grid,
619 matrix_curves,
620 matrix,
621 matrix_bias,
622 matrix_channels,
623 output_curves,
624 output_channels: ldt.num_output_channels as u32,
625 })
626 }
627 }
628 }
629
630 /// Convert moxcms ToneReprCurve to skcms-compatible TransferFunction.
631 /// Returns None if the curve cannot be represented as a parametric function.
632 fn convert_trc_to_transfer_function(trc: &moxcms::ToneReprCurve) -> Option<ffi::TransferFunction> {
633 use moxcms::ToneReprCurve;
634
635 match trc {
636 ToneReprCurve::Parametric(params) => {
637 // moxcms parametric curve: Vec<f32> with 7 parameters (g, a, b, c, d, e, f)
638 // Matches skcms transfer function layout
639 moxcms::ParametricCurve::new(params)
640 .map(|curve| parametric_curve_to_transfer_function(&curve))
641 }
642 ToneReprCurve::Lut(table) => {
643 // In ICC, a single u16 value represents gamma in 8.8 fixed-point
644 if table.len() == 1 {
645 let gamma = table[0] as f32 / 256.0;
646 Some(ffi::TransferFunction {
647 g: gamma,
648 a: 1.0,
649 b: 0.0,
650 c: 0.0,
651 d: 0.0,
652 e: 0.0,
653 f: 0.0,
654 })
655 } else if !table.is_empty() {
656 // Multi-entry table: use skcms_ApproximateCurve to fit a parametric function
657 let mut approx = ffi::TransferFunction::default();
658 let mut max_error: f32 = 0.0;
659
660 if ffi::approximate_curve_wrapper(table, &mut approx, &mut max_error) {
661 Some(approx)
662 } else {
663 None
664 }
665 } else {
666 None
667 }
668 }
669 }
670 }
671
672 #[cfg(test)]
673 mod tests {
674 use super::*;
675
676 /// Helper to create an empty IccProfile for testing
677 fn empty_icc_profile() -> ffi::IccProfile {
678 ffi::IccProfile {
679 data_color_space: ffi::skcms_Signature::skcms_Signature_RGB,
680 connection_space: ffi::skcms_Signature::skcms_Signature_XYZ,
681 to_xyzd50: ffi::Matrix3x3 {
682 vals: [[0.0; 3]; 3],
683 },
684 has_to_xyzd50: false,
685 trc: [ffi::TransferFunction::default(); 3],
686 has_trc: false,
687 cicp: ffi::Cicp {
688 color_primaries: 0,
689 transfer_characteristics: 0,
690 matrix_coefficients: 0,
691 video_full_range_flag: 0,
692 },
693 has_cicp: false,
694 a2b: empty_a2b(),
695 has_a2b: false,
696 b2a: empty_b2a(),
697 has_b2a: false,
698 }
699 }
700
701 fn empty_a2b() -> ffi::A2B {
702 ffi::A2B {
703 input_curves: Vec::new(),
704 input_channels: 0,
705 grid_points: [0; 4],
706 grid_data: Vec::new(),
707 is_16bit_grid: false,
708 matrix_curves: Vec::new(),
709 matrix: ffi::Matrix3x3 {
710 vals: [[0.0; 3]; 3],
711 },
712 matrix_bias: [0.0; 3],
713 matrix_channels: 0,
714 output_curves: Vec::new(),
715 output_channels: 0,
716 }
717 }
718
719 fn empty_b2a() -> ffi::B2A {
720 ffi::B2A {
721 input_curves: Vec::new(),
722 input_channels: 0,
723 matrix: ffi::Matrix3x3 {
724 vals: [[0.0; 3]; 3],
725 },
726 matrix_bias: [0.0; 3],
727 matrix_curves: Vec::new(),
728 matrix_channels: 0,
729 grid_points: [0; 4],
730 grid_data: Vec::new(),
731 is_16bit_grid: false,
732 output_curves: Vec::new(),
733 output_channels: 0,
734 }
735 }
736
737 #[test]
738 fn test_empty_profile() {
739 let mut out = empty_icc_profile();
740 let result = parse_icc_profile(&[], &mut out);
741 assert!(!result);
742 }
743
744 #[test]
745 fn test_too_short() {
746 let mut out = empty_icc_profile();
747 let result = parse_icc_profile(&[0; 39], &mut out);
748 assert!(!result);
749 }
750
751 #[test]
752 fn test_invalid_signature() {
753 let mut data = vec![0u8; 128];
754 // Put wrong signature at offset 36
755 data[36..40].copy_from_slice(b"badd");
756
757 let mut out = empty_icc_profile();
758 let result = parse_icc_profile(&data, &mut out);
759 assert!(!result);
760 }
761
762 #[test]
763 fn test_valid_signature_invalid_profile() {
764 let mut data = vec![0u8; 128];
765 // Put correct ICC signature "acsp" at offset 36
766 data[36..40].copy_from_slice(b"acsp");
767
768 let mut out = empty_icc_profile();
769 let result = parse_icc_profile(&data, &mut out);
770 // This will fail moxcms parsing since it's not a real ICC profile
771 assert!(!result);
772 }
773
774 #[test]
775 fn test_valid_profile() {
776 // Sample from AdobeRGB1998.icc - a real 560-byte ICC profile
777 let data: [u8; 560] = [
778 0x00, 0x00, 0x02, 0x30, 0x41, 0x44, 0x42, 0x45, 0x02, 0x10, 0x00, 0x00, 0x6d, 0x6e,
779 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20, 0x07, 0xd0, 0x00, 0x08,
780 0x00, 0x0b, 0x00, 0x13, 0x00, 0x33, 0x00, 0x3b, 0x61, 0x63, 0x73, 0x70, 0x41, 0x50,
781 0x50, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x6e, 0x6f, 0x6e, 0x65, 0x00, 0x00, 0x00, 0x00,
782 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
783 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x41, 0x44, 0x42, 0x45,
784 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
785 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
786 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
787 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x00, 0xfc,
788 0x00, 0x00, 0x00, 0x32, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x30, 0x00, 0x00,
789 0x00, 0x6b, 0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x01, 0x9c, 0x00, 0x00, 0x00, 0x14,
790 0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x01, 0xb0, 0x00, 0x00, 0x00, 0x14, 0x72, 0x54,
791 0x52, 0x43, 0x00, 0x00, 0x01, 0xc4, 0x00, 0x00, 0x00, 0x0e, 0x67, 0x54, 0x52, 0x43,
792 0x00, 0x00, 0x01, 0xd4, 0x00, 0x00, 0x00, 0x0e, 0x62, 0x54, 0x52, 0x43, 0x00, 0x00,
793 0x01, 0xe4, 0x00, 0x00, 0x00, 0x0e, 0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x01, 0xf4,
794 0x00, 0x00, 0x00, 0x14, 0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x02, 0x08, 0x00, 0x00,
795 0x00, 0x14, 0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x02, 0x1c, 0x00, 0x00, 0x00, 0x14,
796 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, 0x43, 0x6f, 0x70, 0x79, 0x72, 0x69,
797 0x67, 0x68, 0x74, 0x20, 0x32, 0x30, 0x30, 0x30, 0x20, 0x41, 0x64, 0x6f, 0x62, 0x65,
798 0x20, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x73, 0x20, 0x49, 0x6e, 0x63, 0x6f, 0x72,
799 0x70, 0x6f, 0x72, 0x61, 0x74, 0x65, 0x64, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63,
800 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x41, 0x64, 0x6f, 0x62, 0x65, 0x20,
801 0x52, 0x47, 0x42, 0x20, 0x28, 0x31, 0x39, 0x39, 0x38, 0x29, 0x00, 0x00, 0x00, 0x00,
802 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
803 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
804 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
805 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
806 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
807 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00,
808 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x16, 0xcc, 0x58, 0x59,
809 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
810 0x00, 0x00, 0x00, 0x00, 0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
811 0x00, 0x01, 0x02, 0x33, 0x00, 0x00, 0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00,
812 0x00, 0x00, 0x00, 0x01, 0x02, 0x33, 0x00, 0x00, 0x63, 0x75, 0x72, 0x76, 0x00, 0x00,
813 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x33, 0x00, 0x00, 0x58, 0x59, 0x5a, 0x20,
814 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9c, 0x18, 0x00, 0x00, 0x4f, 0xa5, 0x00, 0x00,
815 0x04, 0xfc, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x34, 0x8d,
816 0x00, 0x00, 0xa0, 0x2c, 0x00, 0x00, 0x0f, 0x95, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00,
817 0x00, 0x00, 0x00, 0x00, 0x26, 0x31, 0x00, 0x00, 0x10, 0x2f, 0x00, 0x00, 0xbe, 0x9c,
818 ];
819
820 let mut out = empty_icc_profile();
821 let result = parse_icc_profile(&data, &mut out);
822 assert!(result, "Failed to parse valid ICC profile");
823 assert_eq!(
824 out.data_color_space,
825 ffi::skcms_Signature::skcms_Signature_RGB
826 );
827 assert_eq!(
828 out.connection_space,
829 ffi::skcms_Signature::skcms_Signature_XYZ
830 );
831
832 // AdobeRGB has toXYZD50 matrix and TRCs
833 assert!(out.has_to_xyzd50, "AdobeRGB should have toXYZD50 matrix");
834 assert!(out.has_trc, "AdobeRGB should have TRCs");
835
836 // Verify the TRCs are gamma 2.2 (encoded as 563 in 8.8 fixed point = 2.199...)
837 assert!(
838 (out.trc[0].g - 2.2).abs() < 0.01,
839 "Red TRC should be ~2.2, got {}",
840 out.trc[0].g
841 );
842 }
843
844 #[test]
845 fn test_approximate_curve_linear() {
846 let table: Vec<u16> = (0..=255).map(|i| (i as u16) * 257).collect();
847
848 let mut approx = ffi::TransferFunction::default();
849 let mut max_error: f32 = 0.0;
850
851 let success = ffi::approximate_curve_wrapper(&table, &mut approx, &mut max_error);
852 assert!(success, "Should successfully approximate linear curve");
853
854 // Linear curve should have g ≈ 1.0, a ≈ 1.0, b ≈ 0.0
855 assert!(
856 (approx.g - 1.0).abs() < 0.1,
857 "Linear curve gamma should be ~1.0, got {}",
858 approx.g
859 );
860 assert!(max_error < 0.01, "Linear curve error should be very small");
861 }
862
863 #[test]
864 fn test_approximate_curve_gamma() {
865 let table: Vec<u16> = (0..=255)
866 .map(|i| {
867 let x = i as f32 / 255.0;
868 let y = x.powf(2.2);
869 (y * 65535.0) as u16
870 })
871 .collect();
872
873 let mut approx = ffi::TransferFunction::default();
874 let mut max_error: f32 = 0.0;
875
876 // For testing, use the C++ wrapper directly
877 let success = ffi::approximate_curve_wrapper(&table, &mut approx, &mut max_error);
878 assert!(success, "Should successfully approximate gamma curve");
879
880 // skcms_ApproximateCurve may not fit gamma curves perfectly
881 // Allow a reasonable tolerance since approximation trades off accuracy
882 assert!(
883 (approx.g - 2.2).abs() < 0.5,
884 "Gamma curve should be roughly ~2.2, got {}",
885 approx.g
886 );
887 }
888
889 #[test]
890 fn test_convert_legacy_lut_basic() {
891 use moxcms::{LutDataType, LutStore, LutType, LutWarehouse, Matrix3d};
892
893 // Create a simple legacy LUT with 3 input channels, 3 output channels
894 let ldt = LutDataType {
895 num_input_channels: 3,
896 num_output_channels: 3,
897 num_clut_grid_points: 2, // 2x2x2 grid
898 matrix: Matrix3d {
899 v: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
900 },
901 num_input_table_entries: 256,
902 num_output_table_entries: 256,
903 // Create identity input tables (3 channels * 256 entries)
904 input_table: LutStore::Store16(
905 (0..3)
906 .flat_map(|_| (0..256).map(|i| (i as u16) * 257))
907 .collect(),
908 ),
909 // Create simple CLUT (2^3 * 3 = 24 values)
910 clut_table: LutStore::Store16(vec![
911 0, 0, 0, // [0,0,0] -> [0,0,0]
912 65535, 0, 0, // [1,0,0] -> [1,0,0]
913 0, 65535, 0, // [0,1,0] -> [0,1,0]
914 65535, 65535, 0, // [1,1,0] -> [1,1,0]
915 0, 0, 65535, // [0,0,1] -> [0,0,1]
916 65535, 0, 65535, // [1,0,1] -> [1,0,1]
917 0, 65535, 65535, // [0,1,1] -> [0,1,1]
918 65535, 65535, 65535, // [1,1,1] -> [1,1,1]
919 ]),
920 // Create identity output tables (3 channels * 256 entries)
921 output_table: LutStore::Store16(
922 (0..3)
923 .flat_map(|_| (0..256).map(|i| (i as u16) * 257))
924 .collect(),
925 ),
926 lut_type: LutType::Lut16,
927 };
928
929 let lut_warehouse = LutWarehouse::Lut(ldt);
930 let result = convert_to_a2b(&lut_warehouse, moxcms::DataColorSpace::Lab, LutTagType::A2B);
931
932 assert!(result.is_some(), "Should successfully convert legacy LUT");
933 let a2b = result.unwrap();
934
935 // Verify channel counts
936 assert_eq!(a2b.input_channels, 3);
937 assert_eq!(a2b.output_channels, 3);
938
939 // Verify grid points (uniform 2x2x2 for 3 input channels)
940 assert_eq!(a2b.grid_points, [2, 2, 2, 0]);
941
942 // Verify 3 input curves (one per channel)
943 assert_eq!(a2b.input_curves.len(), 3);
944 assert_eq!(a2b.input_curves[0].table_entries, 256);
945
946 // Verify 3 output curves (one per channel)
947 assert_eq!(a2b.output_curves.len(), 3);
948 assert_eq!(a2b.output_curves[0].table_entries, 256);
949
950 // Verify no matrix curves (legacy LUT doesn't have M curves)
951 assert_eq!(a2b.matrix_curves.len(), 0);
952 assert_eq!(a2b.matrix_channels, 0);
953
954 // Verify grid data is present and 16-bit
955 assert!(!a2b.grid_data.is_empty());
956 assert!(a2b.is_16bit_grid);
957
958 // Verify matrix is identity
959 assert_eq!(a2b.matrix.vals[0][0], 1.0);
960 assert_eq!(a2b.matrix.vals[1][1], 1.0);
961 assert_eq!(a2b.matrix.vals[2][2], 1.0);
962
963 // Verify bias is zero
964 assert_eq!(a2b.matrix_bias, [0.0, 0.0, 0.0]);
965 }
966
967 #[test]
968 fn test_convert_legacy_lut_8bit() {
969 use moxcms::{LutDataType, LutStore, LutType, LutWarehouse, Matrix3d};
970
971 // Create legacy 8-bit LUT
972 let ldt = LutDataType {
973 num_input_channels: 3,
974 num_output_channels: 3,
975 num_clut_grid_points: 3, // 3x3x3 grid
976 matrix: Matrix3d {
977 v: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
978 },
979 num_input_table_entries: 256,
980 num_output_table_entries: 256,
981 // Use 8-bit storage
982 input_table: LutStore::Store8((0..3).flat_map(|_| (0..256).map(|i| i as u8)).collect()),
983 clut_table: LutStore::Store8(vec![128; 3 * 3 * 3 * 3]), // 3^3 entries * 3 channels
984 output_table: LutStore::Store8(
985 (0..3).flat_map(|_| (0..256).map(|i| i as u8)).collect(),
986 ),
987 lut_type: LutType::Lut8,
988 };
989
990 let lut_warehouse = LutWarehouse::Lut(ldt);
991 let result = convert_to_a2b(&lut_warehouse, moxcms::DataColorSpace::Lab, LutTagType::A2B);
992
993 assert!(
994 result.is_some(),
995 "Should successfully convert 8-bit legacy LUT"
996 );
997 let a2b = result.unwrap();
998
999 // Verify grid data is 8-bit
1000 assert!(!a2b.is_16bit_grid);
1001 assert!(!a2b.grid_data.is_empty());
1002
1003 // Verify input/output curves converted from 8-bit to 16-bit
1004 assert_eq!(a2b.input_curves.len(), 3);
1005 assert_eq!(a2b.output_curves.len(), 3);
1006
1007 // Each curve should have 256 entries * 2 bytes per entry
1008 assert_eq!(a2b.input_curves[0].table_data.len(), 256 * 2);
1009 }
1010
1011 #[test]
1012 fn test_convert_legacy_lut_4channel() {
1013 use moxcms::{LutDataType, LutStore, LutType, LutWarehouse, Matrix3d};
1014
1015 // Create 4-channel (CMYK) legacy LUT
1016 let ldt = LutDataType {
1017 num_input_channels: 4,
1018 num_output_channels: 3,
1019 num_clut_grid_points: 2, // 2x2x2x2 grid for 4 channels
1020 matrix: Matrix3d {
1021 v: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
1022 },
1023 num_input_table_entries: 256,
1024 num_output_table_entries: 256,
1025 input_table: LutStore::Store16(
1026 (0..4)
1027 .flat_map(|_| (0..256).map(|i| (i as u16) * 257))
1028 .collect(),
1029 ),
1030 // 2^4 * 3 = 48 values
1031 clut_table: LutStore::Store16(vec![32768; 16 * 3]),
1032 output_table: LutStore::Store16(
1033 (0..3)
1034 .flat_map(|_| (0..256).map(|i| (i as u16) * 257))
1035 .collect(),
1036 ),
1037 lut_type: LutType::Lut16,
1038 };
1039
1040 let lut_warehouse = LutWarehouse::Lut(ldt);
1041 let result = convert_to_a2b(&lut_warehouse, moxcms::DataColorSpace::Lab, LutTagType::A2B);
1042
1043 assert!(
1044 result.is_some(),
1045 "Should successfully convert 4-channel legacy LUT"
1046 );
1047 let a2b = result.unwrap();
1048
1049 // Verify 4 input channels
1050 assert_eq!(a2b.input_channels, 4);
1051 assert_eq!(a2b.input_curves.len(), 4);
1052
1053 // Verify grid points for 4D CLUT
1054 assert_eq!(a2b.grid_points, [2, 2, 2, 2]);
1055
1056 // Verify 3 output channels (to XYZ/Lab)
1057 assert_eq!(a2b.output_channels, 3);
1058 assert_eq!(a2b.output_curves.len(), 3);
1059 }
1060
1061 #[test]
1062 fn test_convert_legacy_lut_empty_tables() {
1063 use moxcms::{LutDataType, LutStore, LutType, LutWarehouse, Matrix3d};
1064
1065 // Create LUT with empty input/output tables
1066 let ldt = LutDataType {
1067 num_input_channels: 3,
1068 num_output_channels: 3,
1069 num_clut_grid_points: 2,
1070 matrix: Matrix3d {
1071 v: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
1072 },
1073 num_input_table_entries: 256,
1074 num_output_table_entries: 256,
1075 input_table: LutStore::Store16(Vec::new()), // Empty
1076 clut_table: LutStore::Store16(vec![0; 8 * 3]),
1077 output_table: LutStore::Store16(Vec::new()), // Empty
1078 lut_type: LutType::Lut16,
1079 };
1080
1081 let lut_warehouse = LutWarehouse::Lut(ldt);
1082 let result = convert_to_a2b(&lut_warehouse, moxcms::DataColorSpace::Lab, LutTagType::A2B);
1083
1084 assert!(result.is_some(), "Should handle empty tables gracefully");
1085 let a2b = result.unwrap();
1086
1087 // Should have empty curve vectors
1088 assert_eq!(a2b.input_curves.len(), 0);
1089 assert_eq!(a2b.output_curves.len(), 0);
1090
1091 // But still valid channel counts and grid
1092 assert_eq!(a2b.input_channels, 3);
1093 assert_eq!(a2b.output_channels, 3);
1094 assert_eq!(a2b.grid_points, [2, 2, 2, 0]);
1095 }
1096
1097 #[test]
1098 fn test_convert_legacy_lut_non_identity_matrix() {
1099 use moxcms::{LutDataType, LutStore, LutType, LutWarehouse, Matrix3d};
1100
1101 // Create LUT with non-identity matrix
1102 let ldt = LutDataType {
1103 num_input_channels: 3,
1104 num_output_channels: 3,
1105 num_clut_grid_points: 2,
1106 matrix: Matrix3d {
1107 v: [
1108 [0.4124, 0.3576, 0.1805],
1109 [0.2126, 0.7152, 0.0722],
1110 [0.0193, 0.1192, 0.9505],
1111 ],
1112 },
1113 num_input_table_entries: 256,
1114 num_output_table_entries: 256,
1115 input_table: LutStore::Store16(
1116 (0..3)
1117 .flat_map(|_| (0..256).map(|i| (i as u16) * 257))
1118 .collect(),
1119 ),
1120 clut_table: LutStore::Store16(vec![32768; 8 * 3]),
1121 output_table: LutStore::Store16(
1122 (0..3)
1123 .flat_map(|_| (0..256).map(|i| (i as u16) * 257))
1124 .collect(),
1125 ),
1126 lut_type: LutType::Lut16,
1127 };
1128
1129 let lut_warehouse = LutWarehouse::Lut(ldt);
1130 let result = convert_to_a2b(&lut_warehouse, moxcms::DataColorSpace::Lab, LutTagType::A2B);
1131
1132 assert!(result.is_some(), "Should convert LUT with custom matrix");
1133 let a2b = result.unwrap();
1134
1135 // Verify matrix values (sRGB to XYZ-like)
1136 assert!((a2b.matrix.vals[0][0] - 0.4124).abs() < 0.001);
1137 assert!((a2b.matrix.vals[1][1] - 0.7152).abs() < 0.001);
1138 assert!((a2b.matrix.vals[2][2] - 0.9505).abs() < 0.001);
1139
1140 assert_eq!(a2b.matrix_bias, [0.0, 0.0, 0.0]);
1141 }
1142
1143 #[test]
1144 fn test_u16_vec_to_bytes() {
1145 let values: Vec<u16> = vec![0x0000, 0x00FF, 0xFF00, 0xFFFF];
1146 let bytes = u16_vec_to_bytes(&values);
1147
1148 assert_eq!(bytes.len(), 8);
1149
1150 assert_eq!(bytes[0..2], [0x00, 0x00]);
1151 assert_eq!(bytes[2..4], [0xFF, 0x00]);
1152 assert_eq!(bytes[4..6], [0x00, 0xFF]);
1153 assert_eq!(bytes[6..8], [0xFF, 0xFF]);
1154 }
1155 }