Debian Codegraph @

.cargo/vendor/moxcms/src/writer.rs

raw
1 /*
2 * // Copyright (c) Radzivon Bartoshyk 3/2025. All rights reserved.
3 * //
4 * // Redistribution and use in source and binary forms, with or without modification,
5 * // are permitted provided that the following conditions are met:
6 * //
7 * // 1. Redistributions of source code must retain the above copyright notice, this
8 * // list of conditions and the following disclaimer.
9 * //
10 * // 2. Redistributions in binary form must reproduce the above copyright notice,
11 * // this list of conditions and the following disclaimer in the documentation
12 * // and/or other materials provided with the distribution.
13 * //
14 * // 3. Neither the name of the copyright holder nor the names of its
15 * // contributors may be used to endorse or promote products derived from
16 * // this software without specific prior written permission.
17 * //
18 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29 use crate::profile::{LutDataType, ProfileHeader};
30 use crate::tag::{TAG_SIZE, Tag, TagTypeDefinition};
31 use crate::trc::ToneReprCurve;
32 use crate::{
33 CicpProfile, CmsError, ColorDateTime, ColorProfile, DataColorSpace, LocalizableString,
34 LutMultidimensionalType, LutStore, LutType, LutWarehouse, Matrix3d, ProfileClass,
35 ProfileSignature, ProfileText, ProfileVersion, Vector3d, ViewingConditions, Xyz, Xyzd,
36 };
37
38 pub(crate) trait FloatToFixedS15Fixed16 {
39 fn to_s15_fixed16(self) -> i32;
40 }
41
42 pub(crate) trait FloatToFixedU8Fixed8 {
43 fn to_u8_fixed8(self) -> u16;
44 }
45
46 // pub(crate) trait FloatToFixedU16 {
47 // fn to_fixed_u16(self) -> u16;
48 // }
49
50 // impl FloatToFixedU16 for f32 {
51 // #[inline]
52 // fn to_fixed_u16(self) -> u16 {
53 // const SCALE: f64 = (1 << 16) as f64;
54 // (self as f64 * SCALE + 0.5)
55 // .floor()
56 // .clamp(u16::MIN as f64, u16::MAX as f64) as u16
57 // }
58 // }
59
60 impl FloatToFixedS15Fixed16 for f32 {
61 #[inline]
62 fn to_s15_fixed16(self) -> i32 {
63 const SCALE: f64 = (1 << 16) as f64;
64 (self as f64 * SCALE + 0.5)
65 .floor()
66 .clamp(i32::MIN as f64, i32::MAX as f64) as i32
67 }
68 }
69
70 impl FloatToFixedS15Fixed16 for f64 {
71 #[inline]
72 fn to_s15_fixed16(self) -> i32 {
73 const SCALE: f64 = (1 << 16) as f64;
74 (self * SCALE + 0.5)
75 .floor()
76 .clamp(i32::MIN as f64, i32::MAX as f64) as i32
77 }
78 }
79
80 #[inline]
81 fn write_u32_be(into: &mut Vec<u8>, value: u32) {
82 let bytes = value.to_be_bytes();
83 into.push(bytes[0]);
84 into.push(bytes[1]);
85 into.push(bytes[2]);
86 into.push(bytes[3]);
87 }
88
89 #[inline]
90 pub(crate) fn write_u16_be(into: &mut Vec<u8>, value: u16) {
91 let bytes = value.to_be_bytes();
92 into.push(bytes[0]);
93 into.push(bytes[1]);
94 }
95
96 #[inline]
97 fn write_i32_be(into: &mut Vec<u8>, value: i32) {
98 let bytes = value.to_be_bytes();
99 into.push(bytes[0]);
100 into.push(bytes[1]);
101 into.push(bytes[2]);
102 into.push(bytes[3]);
103 }
104
105 fn first_two_ascii_bytes(s: &String) -> [u8; 2] {
106 let bytes = s.as_bytes();
107 if bytes.len() >= 2 {
108 bytes[0..2].try_into().unwrap()
109 } else if bytes.len() == 1 {
110 let vec = vec![bytes[0], 0u8];
111 vec.try_into().unwrap()
112 } else {
113 let vec = vec![0u8, 0u8];
114 vec.try_into().unwrap()
115 }
116 }
117
118 /// Writes Multi Localized Unicode
119 #[inline]
120 fn write_mluc(into: &mut Vec<u8>, strings: &[LocalizableString]) -> usize {
121 assert!(!strings.is_empty());
122 let start = into.len();
123 let tag_def: u32 = TagTypeDefinition::MultiLocalizedUnicode.into();
124 write_u32_be(into, tag_def);
125 write_u32_be(into, 0);
126 let number_of_records = strings.len();
127 write_u32_be(into, number_of_records as u32);
128 write_u32_be(into, 12); // Record size, must be 12
129 let lang = first_two_ascii_bytes(&strings[0].language);
130 into.extend_from_slice(&lang);
131 let country = first_two_ascii_bytes(&strings[0].country);
132 into.extend_from_slice(&country);
133 let first_string_len = strings[0].value.len() * 2;
134 write_u32_be(into, first_string_len as u32);
135 let mut first_string_offset = 16 + 12 * strings.len();
136 write_u32_be(into, first_string_offset as u32);
137 first_string_offset += first_string_len;
138 for record in strings.iter().skip(1) {
139 let lang = first_two_ascii_bytes(&record.language);
140 into.extend_from_slice(&lang);
141 let country = first_two_ascii_bytes(&record.country);
142 into.extend_from_slice(&country);
143 let first_string_len = record.value.len() * 2;
144 write_u32_be(into, first_string_len as u32);
145 write_u32_be(into, first_string_offset as u32);
146 first_string_offset += first_string_len;
147 }
148 for record in strings.iter() {
149 for chunk in record.value.encode_utf16() {
150 write_u16_be(into, chunk);
151 }
152 }
153 let end = into.len();
154 end - start
155 }
156
157 #[inline]
158 fn write_string_value(into: &mut Vec<u8>, text: &ProfileText) -> usize {
159 match text {
160 ProfileText::PlainString(text) => {
161 let vec = vec![LocalizableString {
162 language: "en".to_string(),
163 country: "US".to_string(),
164 value: text.clone(),
165 }];
166 write_mluc(into, &vec)
167 }
168 ProfileText::Localizable(localizable) => {
169 if localizable.is_empty() {
170 return 0;
171 }
172 write_mluc(into, localizable)
173 }
174 ProfileText::Description(description) => {
175 let vec = vec![LocalizableString {
176 language: "en".to_string(),
177 country: "US".to_string(),
178 value: description.unicode_string.clone(),
179 }];
180 write_mluc(into, &vec)
181 }
182 }
183 }
184
185 #[inline]
186 fn write_xyz_tag_value(into: &mut Vec<u8>, xyz: Xyzd) {
187 let tag_definition: u32 = TagTypeDefinition::Xyz.into();
188 write_u32_be(into, tag_definition);
189 write_u32_be(into, 0);
190 let x_fixed = xyz.x.to_s15_fixed16();
191 write_i32_be(into, x_fixed);
192 let y_fixed = xyz.y.to_s15_fixed16();
193 write_i32_be(into, y_fixed);
194 let z_fixed = xyz.z.to_s15_fixed16();
195 write_i32_be(into, z_fixed);
196 }
197
198 #[inline]
199 fn write_tag_entry(into: &mut Vec<u8>, tag: Tag, tag_entry: usize, tag_size: usize) {
200 let tag_value: u32 = tag.into();
201 write_u32_be(into, tag_value);
202 write_u32_be(into, tag_entry as u32);
203 write_u32_be(into, tag_size as u32);
204 }
205
206 #[inline]
207 fn write_xyz(into: &mut Vec<u8>, xyz: Xyz) {
208 let x_fixed = xyz.x.to_s15_fixed16();
209 write_i32_be(into, x_fixed);
210 let y_fixed = xyz.y.to_s15_fixed16();
211 write_i32_be(into, y_fixed);
212 let z_fixed = xyz.z.to_s15_fixed16();
213 write_i32_be(into, z_fixed);
214 }
215
216 #[inline]
217 fn write_viewing_conditions_value(
218 into: &mut Vec<u8>,
219 viewing_conditions: &ViewingConditions,
220 ) -> usize {
221 let tag_definition: u32 = TagTypeDefinition::DefViewingConditions.into();
222 write_u32_be(into, tag_definition);
223 write_u32_be(into, 0);
224 write_xyz(into, viewing_conditions.illuminant);
225 write_xyz(into, viewing_conditions.surround);
226 write_u32_be(into, viewing_conditions.observer.into());
227 36
228 }
229
230 fn write_trc_entry(into: &mut Vec<u8>, trc: &ToneReprCurve) -> Result<usize, CmsError> {
231 match trc {
232 ToneReprCurve::Lut(lut) => {
233 let curv: u32 = TagTypeDefinition::LutToneCurve.into();
234 write_u32_be(into, curv);
235 write_u32_be(into, 0);
236 write_u32_be(into, lut.len() as u32);
237 for item in lut.iter() {
238 write_u16_be(into, *item);
239 }
240 Ok(12 + lut.len() * 2)
241 }
242 ToneReprCurve::Parametric(parametric_curve) => {
243 if parametric_curve.len() > 7
244 || parametric_curve.len() == 6
245 || parametric_curve.len() == 2
246 {
247 return Err(CmsError::InvalidProfile);
248 }
249 let para: u32 = TagTypeDefinition::ParametricToneCurve.into();
250 write_u32_be(into, para);
251 write_u32_be(into, 0);
252 if parametric_curve.len() == 1 {
253 write_u16_be(into, 0);
254 } else if parametric_curve.len() == 3 {
255 write_u16_be(into, 1);
256 } else if parametric_curve.len() == 4 {
257 write_u16_be(into, 2);
258 } else if parametric_curve.len() == 5 {
259 write_u16_be(into, 3);
260 } else if parametric_curve.len() == 7 {
261 write_u16_be(into, 4);
262 }
263 write_u16_be(into, 0);
264 for item in parametric_curve.iter() {
265 write_i32_be(into, item.to_s15_fixed16());
266 }
267 Ok(12 + 4 * parametric_curve.len())
268 }
269 }
270 }
271
272 #[inline]
273 fn write_cicp_entry(into: &mut Vec<u8>, cicp: &CicpProfile) {
274 let cicp_tag: u32 = TagTypeDefinition::Cicp.into();
275 write_u32_be(into, cicp_tag);
276 write_u32_be(into, 0);
277 into.push(cicp.color_primaries as u8);
278 into.push(cicp.transfer_characteristics as u8);
279 into.push(cicp.matrix_coefficients as u8);
280 into.push(if cicp.full_range { 1 } else { 0 });
281 }
282
283 fn write_chad(into: &mut Vec<u8>, matrix: Matrix3d) {
284 let arr_type: u32 = TagTypeDefinition::S15Fixed16Array.into();
285 write_u32_be(into, arr_type);
286 write_u32_be(into, 0);
287 write_matrix3d(into, matrix);
288 }
289
290 #[inline]
291 fn write_matrix3d(into: &mut Vec<u8>, v: Matrix3d) {
292 write_i32_be(into, v.v[0][0].to_s15_fixed16());
293 write_i32_be(into, v.v[0][1].to_s15_fixed16());
294 write_i32_be(into, v.v[0][2].to_s15_fixed16());
295
296 write_i32_be(into, v.v[1][0].to_s15_fixed16());
297 write_i32_be(into, v.v[1][1].to_s15_fixed16());
298 write_i32_be(into, v.v[1][2].to_s15_fixed16());
299
300 write_i32_be(into, v.v[2][0].to_s15_fixed16());
301 write_i32_be(into, v.v[2][1].to_s15_fixed16());
302 write_i32_be(into, v.v[2][2].to_s15_fixed16());
303 }
304
305 #[inline]
306 fn write_vector3d(into: &mut Vec<u8>, v: Vector3d) {
307 write_i32_be(into, v.v[0].to_s15_fixed16());
308 write_i32_be(into, v.v[1].to_s15_fixed16());
309 write_i32_be(into, v.v[2].to_s15_fixed16());
310 }
311
312 #[inline]
313 fn write_lut_entry(into: &mut Vec<u8>, lut: &LutDataType) -> Result<usize, CmsError> {
314 if !lut.has_same_kind() {
315 return Err(CmsError::InvalidProfile);
316 }
317 let start = into.len();
318 let lut16_tag: u32 = match &lut.input_table {
319 LutStore::Store8(_) => LutType::Lut8.into(),
320 LutStore::Store16(_) => LutType::Lut16.into(),
321 };
322 write_u32_be(into, lut16_tag);
323 write_u32_be(into, 0);
324 into.push(lut.num_input_channels);
325 into.push(lut.num_output_channels);
326 into.push(lut.num_clut_grid_points);
327 into.push(0);
328 write_matrix3d(into, lut.matrix);
329 write_u16_be(into, lut.num_input_table_entries);
330 write_u16_be(into, lut.num_output_table_entries);
331 match &lut.input_table {
332 LutStore::Store8(input_table) => {
333 for &item in input_table.iter() {
334 into.push(item);
335 }
336 }
337 LutStore::Store16(input_table) => {
338 for &item in input_table.iter() {
339 write_u16_be(into, item);
340 }
341 }
342 }
343 match &lut.clut_table {
344 LutStore::Store8(input_table) => {
345 for &item in input_table.iter() {
346 into.push(item);
347 }
348 }
349 LutStore::Store16(input_table) => {
350 for &item in input_table.iter() {
351 write_u16_be(into, item);
352 }
353 }
354 }
355 match &lut.output_table {
356 LutStore::Store8(input_table) => {
357 for &item in input_table.iter() {
358 into.push(item);
359 }
360 }
361 LutStore::Store16(input_table) => {
362 for &item in input_table.iter() {
363 write_u16_be(into, item);
364 }
365 }
366 }
367 let end = into.len();
368 Ok(end - start)
369 }
370
371 #[inline]
372 fn write_mab_entry(
373 into: &mut Vec<u8>,
374 lut: &LutMultidimensionalType,
375 is_a_to_b: bool,
376 ) -> Result<usize, CmsError> {
377 let start = into.len();
378 let lut16_tag: u32 = if is_a_to_b {
379 LutType::LutMab.into()
380 } else {
381 LutType::LutMba.into()
382 };
383 write_u32_be(into, lut16_tag);
384 write_u32_be(into, 0);
385 into.push(lut.num_input_channels);
386 into.push(lut.num_output_channels);
387 write_u16_be(into, 0);
388 let mut working_offset = 32usize;
389
390 let mut data = Vec::new();
391
392 // Offset to "B curves"
393 if !lut.b_curves.is_empty() {
394 while working_offset % 4 != 0 {
395 data.push(0);
396 working_offset += 1;
397 }
398
399 write_u32_be(into, working_offset as u32);
400
401 for trc in lut.b_curves.iter() {
402 let curve_size = write_trc_entry(&mut data, trc)?;
403 working_offset += curve_size;
404 while working_offset % 4 != 0 {
405 data.push(0);
406 working_offset += 1;
407 }
408 }
409 } else {
410 write_u32_be(into, 0);
411 }
412
413 // Offset to matrix
414 if !lut.m_curves.is_empty() {
415 while working_offset % 4 != 0 {
416 data.push(0);
417 working_offset += 1;
418 }
419
420 write_u32_be(into, working_offset as u32);
421 write_matrix3d(&mut data, lut.matrix);
422 write_vector3d(&mut data, lut.bias);
423 working_offset += 9 * 4 + 3 * 4;
424 // Offset to "M curves"
425 write_u32_be(into, working_offset as u32);
426 for trc in lut.m_curves.iter() {
427 let curve_size = write_trc_entry(&mut data, trc)?;
428 working_offset += curve_size;
429 while working_offset % 4 != 0 {
430 data.push(0);
431 working_offset += 1;
432 }
433 }
434 } else {
435 // Offset to matrix
436 write_u32_be(into, 0);
437 // Offset to "M curves"
438 write_u32_be(into, 0);
439 }
440
441 let mut clut_start = data.len();
442
443 // Offset to CLUT
444 if let Some(clut) = &lut.clut {
445 while working_offset % 4 != 0 {
446 data.push(0);
447 working_offset += 1;
448 }
449
450 clut_start = data.len();
451
452 write_u32_be(into, working_offset as u32);
453
454 // Writing CLUT
455 for &pt in lut.grid_points.iter() {
456 data.push(pt);
457 }
458 data.push(match clut {
459 LutStore::Store8(_) => 1,
460 LutStore::Store16(_) => 2,
461 }); // Entry size
462 data.push(0);
463 data.push(0);
464 data.push(0);
465 match clut {
466 LutStore::Store8(store) => {
467 for &element in store.iter() {
468 data.push(element)
469 }
470 }
471 LutStore::Store16(store) => {
472 for &element in store.iter() {
473 write_u16_be(&mut data, element);
474 }
475 }
476 }
477 } else {
478 write_u32_be(into, 0);
479 }
480
481 let clut_size = data.len() - clut_start;
482 working_offset += clut_size;
483
484 // Offset to "A curves"
485 if !lut.a_curves.is_empty() {
486 while working_offset % 4 != 0 {
487 data.push(0);
488 working_offset += 1;
489 }
490
491 write_u32_be(into, working_offset as u32);
492
493 for trc in lut.a_curves.iter() {
494 let curve_size = write_trc_entry(&mut data, trc)?;
495 working_offset += curve_size;
496 while working_offset % 4 != 0 {
497 data.push(0);
498 working_offset += 1;
499 }
500 }
501 } else {
502 write_u32_be(into, 0);
503 }
504
505 into.extend(data);
506
507 let end = into.len();
508 Ok(end - start)
509 }
510
511 fn write_lut(into: &mut Vec<u8>, lut: &LutWarehouse, is_a_to_b: bool) -> Result<usize, CmsError> {
512 match lut {
513 LutWarehouse::Lut(lut) => Ok(write_lut_entry(into, lut)?),
514 LutWarehouse::Multidimensional(mab) => write_mab_entry(into, mab, is_a_to_b),
515 }
516 }
517
518 impl ProfileHeader {
519 fn encode(&self) -> Vec<u8> {
520 let mut encoder: Vec<u8> = Vec::with_capacity(size_of::<ProfileHeader>());
521 write_u32_be(&mut encoder, self.size); // Size
522 write_u32_be(&mut encoder, 0); // CMM Type
523 write_u32_be(&mut encoder, self.version.into()); // Version Number Type
524 write_u32_be(&mut encoder, self.profile_class.into()); // Profile class
525 write_u32_be(&mut encoder, self.data_color_space.into()); // Data color space
526 write_u32_be(&mut encoder, self.pcs.into()); // PCS
527 self.creation_date_time.encode(&mut encoder); // Date time
528 write_u32_be(&mut encoder, self.signature.into()); // Profile signature
529 write_u32_be(&mut encoder, self.platform);
530 write_u32_be(&mut encoder, self.flags);
531 write_u32_be(&mut encoder, self.device_manufacturer);
532 write_u32_be(&mut encoder, self.device_model);
533 for &i in self.device_attributes.iter() {
534 encoder.push(i);
535 }
536 write_u32_be(&mut encoder, self.rendering_intent.into());
537 write_i32_be(&mut encoder, self.illuminant.x.to_s15_fixed16());
538 write_i32_be(&mut encoder, self.illuminant.y.to_s15_fixed16());
539 write_i32_be(&mut encoder, self.illuminant.z.to_s15_fixed16());
540 write_u32_be(&mut encoder, self.creator);
541 for &i in self.profile_id.iter() {
542 encoder.push(i);
543 }
544 for &i in self.reserved.iter() {
545 encoder.push(i);
546 }
547 write_u32_be(&mut encoder, self.tag_count);
548 encoder
549 }
550 }
551
552 impl ColorProfile {
553 fn writable_tags_count(&self) -> usize {
554 let mut tags_count = 0usize;
555 if self.red_colorant != Xyzd::default() {
556 tags_count += 1;
557 }
558 if self.green_colorant != Xyzd::default() {
559 tags_count += 1;
560 }
561 if self.blue_colorant != Xyzd::default() {
562 tags_count += 1;
563 }
564 if self.red_trc.is_some() {
565 tags_count += 1;
566 }
567 if self.green_trc.is_some() {
568 tags_count += 1;
569 }
570 if self.blue_trc.is_some() {
571 tags_count += 1;
572 }
573 if self.gray_trc.is_some() {
574 tags_count += 1;
575 }
576 if self.cicp.is_some() {
577 tags_count += 1;
578 }
579 if self.media_white_point.is_some() {
580 tags_count += 1;
581 }
582 if self.gamut.is_some() {
583 tags_count += 1;
584 }
585 if self.chromatic_adaptation.is_some() {
586 tags_count += 1;
587 }
588 if self.lut_a_to_b_perceptual.is_some() {
589 tags_count += 1;
590 }
591 if self.lut_a_to_b_colorimetric.is_some() {
592 tags_count += 1;
593 }
594 if self.lut_a_to_b_saturation.is_some() {
595 tags_count += 1;
596 }
597 if self.lut_b_to_a_perceptual.is_some() {
598 tags_count += 1;
599 }
600 if self.lut_b_to_a_colorimetric.is_some() {
601 tags_count += 1;
602 }
603 if self.lut_b_to_a_saturation.is_some() {
604 tags_count += 1;
605 }
606 if self.luminance.is_some() {
607 tags_count += 1;
608 }
609 if let Some(description) = &self.description {
610 if description.has_values() {
611 tags_count += 1;
612 }
613 }
614 if let Some(copyright) = &self.copyright {
615 if copyright.has_values() {
616 tags_count += 1;
617 }
618 }
619 if self.viewing_conditions.is_some() {
620 tags_count += 1;
621 }
622 if let Some(vd) = &self.viewing_conditions_description {
623 if vd.has_values() {
624 tags_count += 1;
625 }
626 }
627 if let Some(vd) = &self.device_model {
628 if vd.has_values() {
629 tags_count += 1;
630 }
631 }
632 if let Some(vd) = &self.device_manufacturer {
633 if vd.has_values() {
634 tags_count += 1;
635 }
636 }
637 tags_count
638 }
639
640 /// Encodes profile
641 pub fn encode(&self) -> Result<Vec<u8>, CmsError> {
642 let mut entries = Vec::new();
643 let tags_count = self.writable_tags_count();
644 let mut tags = Vec::with_capacity(TAG_SIZE * tags_count);
645 let mut base_offset = size_of::<ProfileHeader>() + TAG_SIZE * tags_count;
646 if self.red_colorant != Xyzd::default() {
647 write_tag_entry(&mut tags, Tag::RedXyz, base_offset, 20);
648 write_xyz_tag_value(&mut entries, self.red_colorant);
649 base_offset += 20;
650 }
651 if self.green_colorant != Xyzd::default() {
652 write_tag_entry(&mut tags, Tag::GreenXyz, base_offset, 20);
653 write_xyz_tag_value(&mut entries, self.green_colorant);
654 base_offset += 20;
655 }
656 if self.blue_colorant != Xyzd::default() {
657 write_tag_entry(&mut tags, Tag::BlueXyz, base_offset, 20);
658 write_xyz_tag_value(&mut entries, self.blue_colorant);
659 base_offset += 20;
660 }
661 if let Some(chad) = self.chromatic_adaptation {
662 write_tag_entry(&mut tags, Tag::ChromaticAdaptation, base_offset, 8 + 9 * 4);
663 write_chad(&mut entries, chad);
664 base_offset += 8 + 9 * 4;
665 }
666 if let Some(trc) = &self.red_trc {
667 let entry_size = write_trc_entry(&mut entries, trc)?;
668 write_tag_entry(&mut tags, Tag::RedToneReproduction, base_offset, entry_size);
669 base_offset += entry_size;
670 }
671 if let Some(trc) = &self.green_trc {
672 let entry_size = write_trc_entry(&mut entries, trc)?;
673 write_tag_entry(
674 &mut tags,
675 Tag::GreenToneReproduction,
676 base_offset,
677 entry_size,
678 );
679 base_offset += entry_size;
680 }
681 if let Some(trc) = &self.blue_trc {
682 let entry_size = write_trc_entry(&mut entries, trc)?;
683 write_tag_entry(
684 &mut tags,
685 Tag::BlueToneReproduction,
686 base_offset,
687 entry_size,
688 );
689 base_offset += entry_size;
690 }
691 if let Some(trc) = &self.gray_trc {
692 let entry_size = write_trc_entry(&mut entries, trc)?;
693 write_tag_entry(
694 &mut tags,
695 Tag::GreyToneReproduction,
696 base_offset,
697 entry_size,
698 );
699 base_offset += entry_size;
700 }
701
702 if let Some(media_wp) = self.media_white_point {
703 write_tag_entry(&mut tags, Tag::MediaWhitePoint, base_offset, 20);
704 write_xyz_tag_value(&mut entries, media_wp);
705 base_offset += 20;
706 }
707
708 let has_cicp = self.cicp.is_some();
709
710 // This tag may be present when the data colour space in the profile header is RGB, YCbCr, or XYZ, and the
711 // profile class in the profile header is Input or Display. The tag shall not be present for other data colour spaces
712 // or profile classes indicated in the profile header.
713
714 if let Some(cicp) = &self.cicp {
715 if (self.profile_class == ProfileClass::InputDevice
716 || self.profile_class == ProfileClass::DisplayDevice)
717 && (self.color_space == DataColorSpace::Rgb
718 || self.color_space == DataColorSpace::YCbr
719 || self.color_space == DataColorSpace::Xyz)
720 {
721 write_tag_entry(&mut tags, Tag::CodeIndependentPoints, base_offset, 12);
722 write_cicp_entry(&mut entries, cicp);
723 base_offset += 12;
724 }
725 }
726
727 if let Some(lut) = &self.lut_a_to_b_perceptual {
728 let entry_size = write_lut(&mut entries, lut, true)?;
729 write_tag_entry(
730 &mut tags,
731 Tag::DeviceToPcsLutPerceptual,
732 base_offset,
733 entry_size,
734 );
735 base_offset += entry_size;
736 }
737
738 if let Some(lut) = &self.lut_a_to_b_colorimetric {
739 let entry_size = write_lut(&mut entries, lut, true)?;
740 write_tag_entry(
741 &mut tags,
742 Tag::DeviceToPcsLutColorimetric,
743 base_offset,
744 entry_size,
745 );
746 base_offset += entry_size;
747 }
748
749 if let Some(lut) = &self.lut_a_to_b_saturation {
750 let entry_size = write_lut(&mut entries, lut, true)?;
751 write_tag_entry(
752 &mut tags,
753 Tag::DeviceToPcsLutSaturation,
754 base_offset,
755 entry_size,
756 );
757 base_offset += entry_size;
758 }
759
760 if let Some(lut) = &self.lut_b_to_a_perceptual {
761 let entry_size = write_lut(&mut entries, lut, false)?;
762 write_tag_entry(
763 &mut tags,
764 Tag::PcsToDeviceLutPerceptual,
765 base_offset,
766 entry_size,
767 );
768 base_offset += entry_size;
769 }
770
771 if let Some(lut) = &self.lut_b_to_a_colorimetric {
772 let entry_size = write_lut(&mut entries, lut, false)?;
773 write_tag_entry(
774 &mut tags,
775 Tag::PcsToDeviceLutColorimetric,
776 base_offset,
777 entry_size,
778 );
779 base_offset += entry_size;
780 }
781
782 if let Some(lut) = &self.lut_b_to_a_saturation {
783 let entry_size = write_lut(&mut entries, lut, false)?;
784 write_tag_entry(
785 &mut tags,
786 Tag::PcsToDeviceLutSaturation,
787 base_offset,
788 entry_size,
789 );
790 base_offset += entry_size;
791 }
792
793 if let Some(lut) = &self.gamut {
794 let entry_size = write_lut(&mut entries, lut, false)?;
795 write_tag_entry(&mut tags, Tag::Gamut, base_offset, entry_size);
796 base_offset += entry_size;
797 }
798
799 if let Some(luminance) = self.luminance {
800 write_tag_entry(&mut tags, Tag::Luminance, base_offset, 20);
801 write_xyz_tag_value(&mut entries, luminance);
802 base_offset += 20;
803 }
804
805 if let Some(description) = &self.description {
806 if description.has_values() {
807 let entry_size = write_string_value(&mut entries, description);
808 write_tag_entry(&mut tags, Tag::ProfileDescription, base_offset, entry_size);
809 base_offset += entry_size;
810 }
811 }
812
813 if let Some(copyright) = &self.copyright {
814 if copyright.has_values() {
815 let entry_size = write_string_value(&mut entries, copyright);
816 write_tag_entry(&mut tags, Tag::Copyright, base_offset, entry_size);
817 base_offset += entry_size;
818 }
819 }
820
821 if let Some(vc) = &self.viewing_conditions {
822 let entry_size = write_viewing_conditions_value(&mut entries, vc);
823 write_tag_entry(&mut tags, Tag::ObserverConditions, base_offset, entry_size);
824 base_offset += entry_size;
825 }
826
827 if let Some(vd) = &self.viewing_conditions_description {
828 if vd.has_values() {
829 let entry_size = write_string_value(&mut entries, vd);
830 write_tag_entry(
831 &mut tags,
832 Tag::ViewingConditionsDescription,
833 base_offset,
834 entry_size,
835 );
836 base_offset += entry_size;
837 }
838 }
839
840 if let Some(vd) = &self.device_model {
841 if vd.has_values() {
842 let entry_size = write_string_value(&mut entries, vd);
843 write_tag_entry(&mut tags, Tag::DeviceModel, base_offset, entry_size);
844 base_offset += entry_size;
845 }
846 }
847
848 if let Some(vd) = &self.device_manufacturer {
849 if vd.has_values() {
850 let entry_size = write_string_value(&mut entries, vd);
851 write_tag_entry(&mut tags, Tag::DeviceManufacturer, base_offset, entry_size);
852 // base_offset += entry_size;
853 }
854 }
855
856 tags.extend(entries);
857
858 let profile_header = ProfileHeader {
859 size: size_of::<ProfileHeader>() as u32 + tags.len() as u32,
860 pcs: self.pcs,
861 profile_class: self.profile_class,
862 rendering_intent: self.rendering_intent,
863 cmm_type: 0,
864 version: if has_cicp {
865 ProfileVersion::V4_3
866 } else if self.version_internal < ProfileVersion::V4_0 {
867 ProfileVersion::V4_0
868 } else {
869 self.version_internal
870 },
871 data_color_space: self.color_space,
872 creation_date_time: ColorDateTime::now(),
873 signature: ProfileSignature::Acsp,
874 platform: 0u32,
875 flags: 0u32,
876 device_manufacturer: 0u32,
877 device_model: 0u32,
878 device_attributes: [0u8; 8],
879 illuminant: self.white_point.to_xyz(),
880 creator: 0u32,
881 profile_id: [0u8; 16],
882 reserved: [0u8; 28],
883 tag_count: tags_count as u32,
884 };
885 let mut header = profile_header.encode();
886 header.extend(tags);
887 Ok(header)
888 }
889 }
890
891 impl FloatToFixedU8Fixed8 for f32 {
892 #[inline]
893 fn to_u8_fixed8(self) -> u16 {
894 if self > 255.0 + 255.0 / 256f32 {
895 0xffffu16
896 } else if self < 0.0 {
897 0u16
898 } else {
899 (self * 256.0 + 0.5).floor() as u16
900 }
901 }
902 }
903
904 #[cfg(test)]
905 mod tests {
906 use super::*;
907
908 #[test]
909 fn to_u8_fixed8() {
910 assert_eq!(0, 0f32.to_u8_fixed8());
911 assert_eq!(0x0100, 1f32.to_u8_fixed8());
912 assert_eq!(u16::MAX, (255f32 + (255f32 / 256f32)).to_u8_fixed8());
913 }
914
915 #[test]
916 fn to_s15_fixed16() {
917 assert_eq!(0x80000000u32 as i32, (-32768f32).to_s15_fixed16());
918 assert_eq!(0, 0f32.to_s15_fixed16());
919 assert_eq!(0x10000, 1.0f32.to_s15_fixed16());
920 assert_eq!(
921 i32::MAX,
922 (32767f32 + (65535f32 / 65536f32)).to_s15_fixed16()
923 );
924 }
925 }