Debian Codegraph @

src/encode/SkICC.cpp

raw
1 /*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "include/encode/SkICC.h"
9
10 #include "include/core/SkColorSpace.h"
11 #include "include/core/SkData.h"
12 #include "include/core/SkFourByteTag.h"
13 #include "include/core/SkStream.h"
14 #include "include/core/SkString.h"
15 #include "include/core/SkTypes.h"
16 #include "include/private/base/SkFixed.h"
17 #include "include/private/base/SkFloatingPoint.h"
18 #include "modules/skcms/skcms.h"
19 #include "src/base/SkAutoMalloc.h"
20 #include "src/base/SkEndian.h"
21 #include "src/core/SkMD5.h"
22 #include "src/core/SkStreamPriv.h"
23 #include "src/encode/SkICCPriv.h"
24
25 #include <algorithm>
26 #include <cmath>
27 #include <cstring>
28 #include <string>
29 #include <utility>
30 #include <vector>
31
32 namespace {
33
34 // The number of input and output channels.
35 constexpr size_t kNumChannels = 3;
36
37 // The D50 illuminant.
38 constexpr float kD50_x = 0.9642f;
39 constexpr float kD50_y = 1.0000f;
40 constexpr float kD50_z = 0.8249f;
41
42 // This is like SkFloatToFixed, but rounds to nearest, preserving as much accuracy as possible
43 // when going float -> fixed -> float (it has the same accuracy when going fixed -> float -> fixed).
44 // The use of double is necessary to accommodate the full potential 32-bit mantissa of the 16.16
45 // SkFixed value, and so avoiding rounding problems with float. Also, see the comment in SkFixed.h.
46 SkFixed float_round_to_fixed(float x) {
47 return sk_float_saturate2int((float)floor((double)x * SK_Fixed1 + 0.5));
48 }
49
50 // Convert a float to a uInt16Number, with 0.0 mapping go 0 and 1.0 mapping to |one|.
51 uint16_t float_to_uInt16Number(float x, uint16_t one) {
52 x = x * one + 0.5f;
53 if (x > one) return one;
54 if (x < 0) return 0;
55 return static_cast<uint16_t>(x);
56 }
57
58 // The uInt16Number used by curveType has 1.0 map to 0xFFFF. See section "10.6. curveType".
59 constexpr uint16_t kOne16CurveType = 0xFFFF;
60
61 // The uInt16Number used to encoude XYZ values has 1.0 map to 0x8000. See section "6.3.4.2 General
62 // PCS encoding" and Table 11.
63 constexpr uint16_t kOne16XYZ = 0x8000;
64
65 struct ICCHeader {
66 // Size of the profile (computed)
67 uint32_t size;
68
69 // Preferred CMM type (ignored)
70 uint32_t cmm_type = 0;
71
72 // Version 4.3 or 4.4 if CICP is included.
73 uint32_t version = SkEndian_SwapBE32(0x04300000);
74
75 // Display device profile
76 uint32_t profile_class = SkEndian_SwapBE32(kDisplay_Profile);
77
78 // RGB input color space;
79 uint32_t data_color_space = SkEndian_SwapBE32(kRGB_ColorSpace);
80
81 // Profile connection space.
82 uint32_t pcs = SkEndian_SwapBE32(kXYZ_PCSSpace);
83
84 // Date and time (ignored)
85 uint16_t creation_date_year = SkEndian_SwapBE16(2016);
86 uint16_t creation_date_month = SkEndian_SwapBE16(1); // 1-12
87 uint16_t creation_date_day = SkEndian_SwapBE16(1); // 1-31
88 uint16_t creation_date_hours = 0; // 0-23
89 uint16_t creation_date_minutes = 0; // 0-59
90 uint16_t creation_date_seconds = 0; // 0-59
91
92 // Profile signature
93 uint32_t signature = SkEndian_SwapBE32(kACSP_Signature);
94
95 // Platform target (ignored)
96 uint32_t platform = 0;
97
98 // Flags: not embedded, can be used independently
99 uint32_t flags = 0x00000000;
100
101 // Device manufacturer (ignored)
102 uint32_t device_manufacturer = 0;
103
104 // Device model (ignored)
105 uint32_t device_model = 0;
106
107 // Device attributes (ignored)
108 uint8_t device_attributes[8] = {0};
109
110 // Relative colorimetric rendering intent
111 uint32_t rendering_intent = SkEndian_SwapBE32(1);
112
113 // D50 standard illuminant (X, Y, Z)
114 uint32_t illuminant_X = SkEndian_SwapBE32(float_round_to_fixed(kD50_x));
115 uint32_t illuminant_Y = SkEndian_SwapBE32(float_round_to_fixed(kD50_y));
116 uint32_t illuminant_Z = SkEndian_SwapBE32(float_round_to_fixed(kD50_z));
117
118 // Profile creator (ignored)
119 uint32_t creator = 0;
120
121 // Profile id checksum (ignored)
122 uint8_t profile_id[16] = {0};
123
124 // Reserved (ignored)
125 uint8_t reserved[28] = {0};
126
127 // Technically not part of header, but required
128 uint32_t tag_count = 0;
129 };
130
131 sk_sp<SkData> write_xyz_tag(float x, float y, float z) {
132 uint32_t data[] = {
133 SkEndian_SwapBE32(kXYZ_PCSSpace),
134 0,
135 SkEndian_SwapBE32(float_round_to_fixed(x)),
136 SkEndian_SwapBE32(float_round_to_fixed(y)),
137 SkEndian_SwapBE32(float_round_to_fixed(z)),
138 };
139 return SkData::MakeWithCopy(data, sizeof(data));
140 }
141
142 sk_sp<SkData> write_matrix(const skcms_Matrix3x4* matrix) {
143 uint32_t data[12];
144 // See layout details in section "10.12.5 Matrix".
145 size_t k = 0;
146 for (int i = 0; i < 3; ++i) {
147 for (int j = 0; j < 3; ++j) {
148 data[k++] = SkEndian_SwapBE32(float_round_to_fixed(matrix->vals[i][j]));
149 }
150 }
151 for (int i = 0; i < 3; ++i) {
152 data[k++] = SkEndian_SwapBE32(float_round_to_fixed(matrix->vals[i][3]));
153 }
154 return SkData::MakeWithCopy(data, sizeof(data));
155 }
156
157 bool nearly_equal(float x, float y) {
158 // A note on why I chose this tolerance: transfer_fn_almost_equal() uses a
159 // tolerance of 0.001f, which doesn't seem to be enough to distinguish
160 // between similar transfer functions, for example: gamma2.2 and sRGB.
161 //
162 // If the tolerance is 0.0f, then this we can't distinguish between two
163 // different encodings of what is clearly the same colorspace. Some
164 // experimentation with example files lead to this number:
165 static constexpr float kTolerance = 1.0f / (1 << 11);
166 return ::fabsf(x - y) <= kTolerance;
167 }
168
169 bool nearly_equal(const skcms_TransferFunction& u,
170 const skcms_TransferFunction& v) {
171 return nearly_equal(u.g, v.g)
172 && nearly_equal(u.a, v.a)
173 && nearly_equal(u.b, v.b)
174 && nearly_equal(u.c, v.c)
175 && nearly_equal(u.d, v.d)
176 && nearly_equal(u.e, v.e)
177 && nearly_equal(u.f, v.f);
178 }
179
180 bool nearly_equal(const skcms_Matrix3x3& u, const skcms_Matrix3x3& v) {
181 for (int r = 0; r < 3; r++) {
182 for (int c = 0; c < 3; c++) {
183 if (!nearly_equal(u.vals[r][c], v.vals[r][c])) {
184 return false;
185 }
186 }
187 }
188 return true;
189 }
190
191 constexpr uint32_t kCICPPrimariesSRGB = 1;
192 constexpr uint32_t kCICPPrimariesP3 = 12;
193 constexpr uint32_t kCICPPrimariesRec2020 = 9;
194
195 uint32_t get_cicp_primaries(const skcms_Matrix3x3& toXYZD50) {
196 if (nearly_equal(toXYZD50, SkNamedGamut::kSRGB)) {
197 return kCICPPrimariesSRGB;
198 } else if (nearly_equal(toXYZD50, SkNamedGamut::kDisplayP3)) {
199 return kCICPPrimariesP3;
200 } else if (nearly_equal(toXYZD50, SkNamedGamut::kRec2020)) {
201 return kCICPPrimariesRec2020;
202 }
203 return 0;
204 }
205
206 constexpr uint32_t kCICPTrfnSRGB = 1;
207 constexpr uint32_t kCICPTrfn2Dot2 = 4;
208 constexpr uint32_t kCICPTrfnLinear = 8;
209 constexpr uint32_t kCICPTrfnPQ = 16;
210 constexpr uint32_t kCICPTrfnHLG = 18;
211
212 uint32_t get_cicp_trfn(const skcms_TransferFunction& fn) {
213 switch (skcms_TransferFunction_getType(&fn)) {
214 default:
215 return 0;
216 case skcms_TFType_sRGBish:
217 if (nearly_equal(fn, SkNamedTransferFn::kSRGB)) {
218 return kCICPTrfnSRGB;
219 } else if (nearly_equal(fn, SkNamedTransferFn::k2Dot2)) {
220 return kCICPTrfn2Dot2;
221 } else if (nearly_equal(fn, SkNamedTransferFn::kLinear)) {
222 return kCICPTrfnLinear;
223 }
224 break;
225 case skcms_TFType_PQ:
226 case skcms_TFType_PQish:
227 // All PQ transfer functions are mapped to the single PQ value,
228 // ignoring their SDR white level.
229 return kCICPTrfnPQ;
230 case skcms_TFType_HLG:
231 case skcms_TFType_HLGish:
232 // All HLG transfer functions are mapped to the single HLG value.
233 return kCICPTrfnHLG;
234 case skcms_TFType_HLGinvish:
235 return 0;
236 }
237 return 0;
238 }
239
240 std::string get_desc_string(const skcms_TransferFunction& fn,
241 const skcms_Matrix3x3& toXYZD50) {
242 const uint32_t cicp_trfn = get_cicp_trfn(fn);
243 const uint32_t cicp_primaries = get_cicp_primaries(toXYZD50);
244
245 // Use a unique string for sRGB.
246 if (cicp_trfn == kCICPPrimariesSRGB && cicp_primaries == kCICPTrfnSRGB) {
247 return "sRGB";
248 }
249
250 // If available, use the named CICP primaries and transfer function.
251 if (cicp_primaries && cicp_trfn) {
252 std::string result;
253 switch (cicp_primaries) {
254 case kCICPPrimariesSRGB:
255 result += "sRGB";
256 break;
257 case kCICPPrimariesP3:
258 result += "Display P3";
259 break;
260 case kCICPPrimariesRec2020:
261 result += "Rec2020";
262 break;
263 default:
264 result += "Unknown";
265 break;
266 }
267 result += " Gamut with ";
268 switch (cicp_trfn) {
269 case kCICPTrfnSRGB:
270 result += "sRGB";
271 break;
272 case kCICPTrfnLinear:
273 result += "Linear";
274 break;
275 case kCICPTrfn2Dot2:
276 result += "2.2";
277 break;
278 case kCICPTrfnPQ:
279 result += "PQ";
280 break;
281 case kCICPTrfnHLG:
282 result += "HLG";
283 break;
284 default:
285 result += "Unknown";
286 break;
287 }
288 result += " Transfer";
289 return result;
290 }
291
292 // Fall back to a prefix plus md5 hash.
293 SkMD5 md5;
294 md5.write(&toXYZD50, sizeof(toXYZD50));
295 md5.write(&fn, sizeof(fn));
296 SkMD5::Digest digest = md5.finish();
297 return std::string("Google/Skia/") + digest.toHexString().c_str();
298 }
299
300 sk_sp<SkData> write_text_tag(const char* text) {
301 uint32_t text_length = strlen(text);
302 uint32_t header[] = {
303 SkEndian_SwapBE32(kTAG_TextType), // Type signature
304 0, // Reserved
305 SkEndian_SwapBE32(1), // Number of records
306 SkEndian_SwapBE32(12), // Record size (must be 12)
307 SkEndian_SwapBE32(SkSetFourByteTag('e', 'n', 'U', 'S')), // English USA
308 SkEndian_SwapBE32(2 * text_length), // Length of string in bytes
309 SkEndian_SwapBE32(28), // Offset of string
310 };
311 SkDynamicMemoryWStream s;
312 s.write(header, sizeof(header));
313 for (size_t i = 0; i < text_length; i++) {
314 // Convert ASCII to big-endian UTF-16.
315 s.write8(0);
316 s.write8(text[i]);
317 }
318 s.padToAlign4();
319 return s.detachAsData();
320 }
321
322 // Write a CICP tag.
323 sk_sp<SkData> write_cicp_tag(const skcms_CICP& cicp) {
324 SkDynamicMemoryWStream s;
325 SkStreamPriv::WriteU32BE(&s, kTAG_cicp); // Type signature
326 SkStreamPriv::WriteU32BE(&s, 0); // Reserved
327 s.write8(cicp.color_primaries); // Color primaries
328 s.write8(cicp.transfer_characteristics); // Transfer characteristics
329 s.write8(cicp.matrix_coefficients); // RGB matrix
330 s.write8(cicp.video_full_range_flag); // Full range
331 return s.detachAsData();
332 }
333
334 constexpr float kToneMapInputMax = 1000.f / 203.f;
335 constexpr float kToneMapOutputMax = 1.f;
336
337 // Scalar tone map gain function.
338 float tone_map_gain(float x) {
339 // The PQ transfer function will map to the range [0, 1]. Linearly scale
340 // it up to the range [0, 1,000/203]. We will then tone map that back
341 // down to [0, 1].
342 constexpr float kToneMapA = kToneMapOutputMax / (kToneMapInputMax * kToneMapInputMax);
343 constexpr float kToneMapB = 1.f / kToneMapOutputMax;
344 return (1.f + kToneMapA * x) / (1.f + kToneMapB * x);
345 }
346
347 // Scalar tone map inverse function
348 float tone_map_inverse(float y) {
349 constexpr float kToneMapA = kToneMapOutputMax / (kToneMapInputMax * kToneMapInputMax);
350 constexpr float kToneMapB = 1.f / kToneMapOutputMax;
351
352 // This is a quadratic equation of the form a*x*x + b*x + c = 0
353 const float a = kToneMapA;
354 const float b = (1 - kToneMapB * y);
355 const float c = -y;
356 const float discriminant = b * b - 4.f * a * c;
357 if (discriminant < 0.f) {
358 return 0.f;
359 }
360 return (-b + sqrtf(discriminant)) / (2.f * a);
361 }
362
363 // Evaluate PQ and HLG transfer functions without tonemapping. The maximum returned value is
364 // kToneMapInputMax.
365 float hdr_trfn_eval(const skcms_TransferFunction& fn, float x) {
366 if (skcms_TransferFunction_isHLGish(&fn) || skcms_TransferFunction_isHLG(&fn)) {
367 // For HLG this curve is the inverse OETF and then a per-channel OOTF.
368 x = skcms_TransferFunction_eval(&SkNamedTransferFn::kHLG, x);
369 x *= std::pow(x, 0.2);
370 } else if (skcms_TransferFunction_isPQish(&fn) || skcms_TransferFunction_isPQ(&fn)) {
371 // For PQ this is the EOTF, scaled so that 1,000 nits maps to 1.0.
372 x = 10.f * skcms_TransferFunction_eval(&SkNamedTransferFn::kPQ, x);
373 x = std::min(x, 1.f);
374 }
375
376 // Scale x so that 203 nits maps to 1.0.
377 x *= kToneMapInputMax;
378 return x;
379 }
380
381 // Write a lookup table based 1D curve.
382 sk_sp<SkData> write_trc_tag(const skcms_Curve& trc) {
383 SkDynamicMemoryWStream s;
384 if (trc.table_entries) {
385 SkStreamPriv::WriteU32BE(&s, kTAG_CurveType); // Type
386 SkStreamPriv::WriteU32BE(&s, 0); // Reserved
387 SkStreamPriv::WriteU32BE(&s, trc.table_entries); // Value count
388 for (uint32_t i = 0; i < trc.table_entries; ++i) {
389 uint16_t value = reinterpret_cast<const uint16_t*>(trc.table_16)[i];
390 s.write16(value);
391 }
392 } else {
393 SkStreamPriv::WriteU32BE(&s, kTAG_ParaCurveType); // Type
394 s.write32(0); // Reserved
395 const auto& fn = trc.parametric;
396 SkASSERT(skcms_TransferFunction_isSRGBish(&fn));
397 if (fn.a == 1.f && fn.b == 0.f && fn.c == 0.f && fn.d == 0.f && fn.e == 0.f &&
398 fn.f == 0.f) {
399 SkStreamPriv::WriteU16BE(&s, kExponential_ParaCurveType);
400 SkStreamPriv::WriteU16BE(&s, 0);
401 SkStreamPriv::WriteU32BE(&s, float_round_to_fixed(fn.g));
402 } else {
403 SkStreamPriv::WriteU16BE(&s, kGABCDEF_ParaCurveType);
404 SkStreamPriv::WriteU16BE(&s, 0);
405 SkStreamPriv::WriteU32BE(&s, float_round_to_fixed(fn.g));
406 SkStreamPriv::WriteU32BE(&s, float_round_to_fixed(fn.a));
407 SkStreamPriv::WriteU32BE(&s, float_round_to_fixed(fn.b));
408 SkStreamPriv::WriteU32BE(&s, float_round_to_fixed(fn.c));
409 SkStreamPriv::WriteU32BE(&s, float_round_to_fixed(fn.d));
410 SkStreamPriv::WriteU32BE(&s, float_round_to_fixed(fn.e));
411 SkStreamPriv::WriteU32BE(&s, float_round_to_fixed(fn.f));
412 }
413 }
414 s.padToAlign4();
415 return s.detachAsData();
416 }
417
418 sk_sp<SkData> write_clut(const uint8_t* grid_points, const uint8_t* grid_16) {
419 SkDynamicMemoryWStream s;
420 for (size_t i = 0; i < 16; ++i) {
421 s.write8(i < kNumChannels ? grid_points[i] : 0); // Grid size
422 }
423 s.write8(2); // Grid byte width (always 16-bit)
424 s.write8(0); // Reserved
425 s.write8(0); // Reserved
426 s.write8(0); // Reserved
427
428 uint32_t value_count = kNumChannels;
429 for (uint32_t i = 0; i < kNumChannels; ++i) {
430 value_count *= grid_points[i];
431 }
432 for (uint32_t i = 0; i < value_count; ++i) {
433 uint16_t value = reinterpret_cast<const uint16_t*>(grid_16)[i];
434 s.write16(value);
435 }
436 s.padToAlign4();
437 return s.detachAsData();
438 }
439
440 // Write an A2B or B2A tag.
441 sk_sp<SkData> write_mAB_or_mBA_tag(uint32_t type,
442 const skcms_Curve* b_curves,
443 const skcms_Curve* a_curves,
444 const uint8_t* grid_points,
445 const uint8_t* grid_16,
446 const skcms_Curve* m_curves,
447 const skcms_Matrix3x4* matrix) {
448 size_t offset = 32;
449
450 // The "B" curve is required.
451 size_t b_curves_offset = offset;
452 sk_sp<SkData> b_curves_data[kNumChannels];
453 SkASSERT(b_curves);
454 for (size_t i = 0; i < kNumChannels; ++i) {
455 b_curves_data[i] = write_trc_tag(b_curves[i]);
456 SkASSERT(b_curves_data[i]);
457 offset += b_curves_data[i]->size();
458 }
459
460 // The CLUT.
461 size_t clut_offset = 0;
462 sk_sp<SkData> clut;
463 if (grid_points) {
464 SkASSERT(grid_16);
465 clut_offset = offset;
466 clut = write_clut(grid_points, grid_16);
467 SkASSERT(clut);
468 offset += clut->size();
469 }
470
471 // The "A" curves.
472 size_t a_curves_offset = 0;
473 sk_sp<SkData> a_curves_data[kNumChannels];
474 if (a_curves) {
475 SkASSERT(grid_points);
476 SkASSERT(grid_16);
477 a_curves_offset = offset;
478 for (size_t i = 0; i < kNumChannels; ++i) {
479 a_curves_data[i] = write_trc_tag(a_curves[i]);
480 SkASSERT(a_curves_data[i]);
481 offset += a_curves_data[i]->size();
482 }
483 }
484
485 // The matrix.
486 size_t matrix_offset = 0;
487 sk_sp<SkData> matrix_data;
488 if (matrix) {
489 SkASSERT(m_curves);
490 matrix_offset = offset;
491 matrix_data = write_matrix(matrix);
492 offset += matrix_data->size();
493 }
494
495 // The "M" curves.
496 size_t m_curves_offset = 0;
497 sk_sp<SkData> m_curves_data[kNumChannels];
498 if (m_curves) {
499 SkASSERT(matrix);
500 m_curves_offset = offset;
501 for (size_t i = 0; i < kNumChannels; ++i) {
502 m_curves_data[i] = write_trc_tag(m_curves[i]);
503 SkASSERT(a_curves_data[i]);
504 offset += m_curves_data[i]->size();
505 }
506 }
507
508 SkDynamicMemoryWStream s;
509 SkStreamPriv::WriteU32BE(&s, type); // Type signature
510 s.write32(0); // Reserved
511 s.write8(kNumChannels); // Input channels
512 s.write8(kNumChannels); // Output channels
513 s.write16(0); // Reserved
514 SkStreamPriv::WriteU32BE(&s, b_curves_offset); // B curve offset
515 SkStreamPriv::WriteU32BE(&s, matrix_offset); // Matrix offset
516 SkStreamPriv::WriteU32BE(&s, m_curves_offset); // M curve offset
517 SkStreamPriv::WriteU32BE(&s, clut_offset); // CLUT offset
518 SkStreamPriv::WriteU32BE(&s, a_curves_offset); // A curve offset
519 SkASSERT(s.bytesWritten() == b_curves_offset);
520 for (size_t i = 0; i < kNumChannels; ++i) {
521 s.write(b_curves_data[i]->data(), b_curves_data[i]->size());
522 }
523 if (clut) {
524 SkASSERT(s.bytesWritten() == clut_offset);
525 s.write(clut->data(), clut->size());
526 }
527 if (a_curves) {
528 SkASSERT(s.bytesWritten() == a_curves_offset);
529 for (size_t i = 0; i < kNumChannels; ++i) {
530 s.write(a_curves_data[i]->data(), a_curves_data[i]->size());
531 }
532 }
533 if (matrix_data) {
534 SkASSERT(s.bytesWritten() == matrix_offset);
535 s.write(matrix_data->data(), matrix_data->size());
536 }
537 if (m_curves) {
538 SkASSERT(s.bytesWritten() == m_curves_offset);
539 for (size_t i = 0; i < kNumChannels; ++i) {
540 s.write(m_curves_data[i]->data(), m_curves_data[i]->size());
541 }
542 }
543 return s.detachAsData();
544 }
545
546 } // namespace
547
548 sk_sp<SkData> SkWriteICCProfile(const skcms_ICCProfile* profile, const char* desc) {
549 ICCHeader header;
550
551 std::vector<std::pair<uint32_t, sk_sp<SkData>>> tags;
552
553 // Compute primaries.
554 if (profile->has_toXYZD50) {
555 const auto& m = profile->toXYZD50;
556 tags.emplace_back(kTAG_rXYZ, write_xyz_tag(m.vals[0][0], m.vals[1][0], m.vals[2][0]));
557 tags.emplace_back(kTAG_gXYZ, write_xyz_tag(m.vals[0][1], m.vals[1][1], m.vals[2][1]));
558 tags.emplace_back(kTAG_bXYZ, write_xyz_tag(m.vals[0][2], m.vals[1][2], m.vals[2][2]));
559 }
560
561 // Compute white point tag (must be D50)
562 tags.emplace_back(kTAG_wtpt, write_xyz_tag(kD50_x, kD50_y, kD50_z));
563
564 // Compute transfer curves.
565 if (profile->has_trc) {
566 tags.emplace_back(kTAG_rTRC, write_trc_tag(profile->trc[0]));
567
568 // Use empty data to indicate that the entry should use the previous tag's
569 // data.
570 if (!memcmp(&profile->trc[1], &profile->trc[0], sizeof(profile->trc[0]))) {
571 tags.emplace_back(kTAG_gTRC, SkData::MakeEmpty());
572 } else {
573 tags.emplace_back(kTAG_gTRC, write_trc_tag(profile->trc[1]));
574 }
575
576 if (!memcmp(&profile->trc[2], &profile->trc[1], sizeof(profile->trc[1]))) {
577 tags.emplace_back(kTAG_bTRC, SkData::MakeEmpty());
578 } else {
579 tags.emplace_back(kTAG_bTRC, write_trc_tag(profile->trc[2]));
580 }
581 }
582
583 // Compute CICP.
584 if (profile->has_CICP) {
585 // The CICP tag is present in ICC 4.4, so update the header's version.
586 header.version = SkEndian_SwapBE32(0x04400000);
587 tags.emplace_back(kTAG_cicp, write_cicp_tag(profile->CICP));
588 }
589
590 // Compute A2B0.
591 if (profile->has_A2B) {
592 const auto& a2b = profile->A2B;
593 SkASSERT(a2b.output_channels == kNumChannels);
594 auto a2b_data = write_mAB_or_mBA_tag(kTAG_mABType,
595 a2b.output_curves,
596 a2b.input_channels ? a2b.input_curves : nullptr,
597 a2b.input_channels ? a2b.grid_points : nullptr,
598 a2b.input_channels ? a2b.grid_16 : nullptr,
599 a2b.matrix_channels ? a2b.matrix_curves : nullptr,
600 a2b.matrix_channels ? &a2b.matrix : nullptr);
601 tags.emplace_back(kTAG_A2B0, std::move(a2b_data));
602 }
603
604 // Compute B2A0.
605 if (profile->has_B2A) {
606 const auto& b2a = profile->B2A;
607 SkASSERT(b2a.input_channels == kNumChannels);
608 auto b2a_data = write_mAB_or_mBA_tag(kTAG_mBAType,
609 b2a.input_curves,
610 b2a.output_channels ? b2a.input_curves : nullptr,
611 b2a.output_channels ? b2a.grid_points : nullptr,
612 b2a.output_channels ? b2a.grid_16 : nullptr,
613 b2a.matrix_channels ? b2a.matrix_curves : nullptr,
614 b2a.matrix_channels ? &b2a.matrix : nullptr);
615 tags.emplace_back(kTAG_B2A0, std::move(b2a_data));
616 }
617
618 // Compute copyright tag
619 tags.emplace_back(kTAG_cprt, write_text_tag("Google Inc. 2016"));
620
621 // Ensure that the desc isn't empty https://crbug.com/329032158
622 std::string generatedDesc;
623 if (!desc || *desc == '\0') {
624 SkMD5 md5;
625 for (const auto& tag : tags) {
626 md5.write(&tag.first, sizeof(tag.first));
627 md5.write(tag.second->bytes(), tag.second->size());
628 }
629 SkMD5::Digest digest = md5.finish();
630 generatedDesc = std::string("Google/Skia/") + digest.toHexString().c_str();
631 desc = generatedDesc.c_str();
632 }
633 // Compute profile description tag
634 tags.emplace(tags.begin(), kTAG_desc, write_text_tag(desc));
635
636 // Compute the size of the profile.
637 size_t tag_data_size = 0;
638 for (const auto& tag : tags) {
639 tag_data_size += tag.second->size();
640 }
641 size_t tag_table_size = kICCTagTableEntrySize * tags.size();
642 size_t profile_size = kICCHeaderSize + tag_table_size + tag_data_size;
643
644 // Write the header.
645 header.data_color_space = SkEndian_SwapBE32(profile->data_color_space);
646 header.pcs = SkEndian_SwapBE32(profile->pcs);
647 header.size = SkEndian_SwapBE32(profile_size);
648 header.tag_count = SkEndian_SwapBE32(tags.size());
649
650 SkAutoMalloc profile_data(profile_size);
651 uint8_t* ptr = (uint8_t*)profile_data.get();
652 memcpy(ptr, &header, sizeof(header));
653 ptr += sizeof(header);
654
655 // Write the tag table. Track the offset and size of the previous tag to
656 // compute each tag's offset. An empty SkData indicates that the previous
657 // tag is to be reused.
658 size_t last_tag_offset = sizeof(header) + tag_table_size;
659 size_t last_tag_size = 0;
660 for (const auto& tag : tags) {
661 if (!tag.second->empty()) {
662 last_tag_offset = last_tag_offset + last_tag_size;
663 last_tag_size = tag.second->size();
664 }
665 uint32_t tag_table_entry[3] = {
666 SkEndian_SwapBE32(tag.first),
667 SkEndian_SwapBE32(last_tag_offset),
668 SkEndian_SwapBE32(last_tag_size),
669 };
670 memcpy(ptr, tag_table_entry, sizeof(tag_table_entry));
671 ptr += sizeof(tag_table_entry);
672 }
673
674 // Write the tags.
675 for (const auto& tag : tags) {
676 if (tag.second->empty()) continue;
677 memcpy(ptr, tag.second->data(), tag.second->size());
678 ptr += tag.second->size();
679 }
680
681 SkASSERT(profile_size == static_cast<size_t>(ptr - (uint8_t*)profile_data.get()));
682 return SkData::MakeFromMalloc(profile_data.release(), profile_size);
683 }
684
685 sk_sp<SkData> SkWriteICCProfile(const skcms_TransferFunction& fn, const skcms_Matrix3x3& toXYZD50) {
686 skcms_ICCProfile profile;
687 memset(&profile, 0, sizeof(profile));
688 std::vector<uint16_t> trc_table;
689 std::vector<uint16_t> a2b_grid;
690
691 profile.data_color_space = skcms_Signature_RGB;
692 profile.pcs = skcms_Signature_XYZ;
693
694 // Populate toXYZD50.
695 {
696 profile.has_toXYZD50 = true;
697 profile.toXYZD50 = toXYZD50;
698 }
699
700 // Populate the analytic TRC for sRGB-like curves.
701 if (skcms_TransferFunction_isSRGBish(&fn)) {
702 profile.has_trc = true;
703 profile.trc[0].table_entries = 0;
704 profile.trc[0].parametric = fn;
705 memcpy(&profile.trc[1], &profile.trc[0], sizeof(profile.trc[0]));
706 memcpy(&profile.trc[2], &profile.trc[0], sizeof(profile.trc[0]));
707 }
708
709 // Populate A2B (PQ and HLG only).
710 if (skcms_TransferFunction_isPQish(&fn) || skcms_TransferFunction_isHLGish(&fn) ||
711 skcms_TransferFunction_isPQ(&fn) || skcms_TransferFunction_isHLG(&fn)) {
712 // Populate a 1D curve to perform per-channel conversion to linear and tone mapping.
713 constexpr uint32_t kTrcTableSize = 65;
714 trc_table.resize(kTrcTableSize);
715 for (uint32_t i = 0; i < kTrcTableSize; ++i) {
716 float x = i / (kTrcTableSize - 1.f);
717 x = hdr_trfn_eval(fn, x);
718 x *= tone_map_gain(x);
719 trc_table[i] = SkEndian_SwapBE16(float_to_uInt16Number(x, kOne16CurveType));
720 }
721
722 // Populate the grid with a 3D LUT to do cross-channel tone mapping.
723 constexpr uint32_t kGridSize = 11;
724 a2b_grid.resize(kGridSize * kGridSize * kGridSize * kNumChannels);
725 size_t a2b_grid_index = 0;
726 for (uint32_t r_index = 0; r_index < kGridSize; ++r_index) {
727 for (uint32_t g_index = 0; g_index < kGridSize; ++g_index) {
728 for (uint32_t b_index = 0; b_index < kGridSize; ++b_index) {
729 float rgb[3] = {
730 r_index / (kGridSize - 1.f),
731 g_index / (kGridSize - 1.f),
732 b_index / (kGridSize - 1.f),
733 };
734
735 // Un-apply the per-channel tone mapping.
736 for (auto& c : rgb) {
737 c = tone_map_inverse(c);
738 }
739
740 // For HLG, mix the channels according to the OOTF.
741 if (skcms_TransferFunction_isHLGish(&fn) || skcms_TransferFunction_isHLG(&fn)) {
742 // Scale to [0, 1].
743 for (auto& c : rgb) {
744 c /= kToneMapInputMax;
745 }
746
747 // Un-apply the per-channel OOTF.
748 for (auto& c : rgb) {
749 c = std::pow(c, 1 / 1.2);
750 }
751
752 // Re-apply the cross-channel OOTF.
753 float Y = 0.2627f * rgb[0] + 0.6780f * rgb[1] + 0.0593f * rgb[2];
754 for (auto& c : rgb) {
755 c *= std::pow(Y, 0.2);
756 }
757
758 // Scale back up to 1.0 being 1,000/203.
759 for (auto& c : rgb) {
760 c *= kToneMapInputMax;
761 }
762 }
763
764 // Apply tone mapping to take 1,000/203 to 1.0.
765 {
766 float max_rgb = std::max(std::max(rgb[0], rgb[1]), rgb[2]);
767 for (auto& c : rgb) {
768 c *= tone_map_gain(0.5 * (c + max_rgb));
769 c = std::min(c, 1.f);
770 }
771 }
772
773 // Write the result to the LUT.
774 for (const auto& c : rgb) {
775 a2b_grid[a2b_grid_index++] =
776 SkEndian_SwapBE16(float_to_uInt16Number(c, kOne16XYZ));
777 }
778 }
779 }
780 }
781
782 // Populate A2B as this tone mapping.
783 profile.has_A2B = true;
784 profile.A2B.input_channels = kNumChannels;
785 profile.A2B.output_channels = kNumChannels;
786 profile.A2B.matrix_channels = kNumChannels;
787 for (size_t i = 0; i < kNumChannels; ++i) {
788 profile.A2B.grid_points[i] = kGridSize;
789 // Set the input curve to convert to linear pre-OOTF space.
790 profile.A2B.input_curves[i].table_entries = kTrcTableSize;
791 profile.A2B.input_curves[i].table_16 = reinterpret_cast<uint8_t*>(trc_table.data());
792 // The output and matrix curves are the identity.
793 profile.A2B.output_curves[i].parametric = SkNamedTransferFn::kLinear;
794 profile.A2B.matrix_curves[i].parametric = SkNamedTransferFn::kLinear;
795 // Set the matrix to convert from the primaries to XYZD50.
796 for (size_t j = 0; j < 3; ++j) {
797 profile.A2B.matrix.vals[i][j] = toXYZD50.vals[i][j];
798 }
799 profile.A2B.matrix.vals[i][3] = 0.f;
800 }
801 profile.A2B.grid_16 = reinterpret_cast<const uint8_t*>(a2b_grid.data());
802
803 // Populate B2A as the identity.
804 profile.has_B2A = true;
805 profile.B2A.input_channels = kNumChannels;
806 for (size_t i = 0; i < 3; ++i) {
807 profile.B2A.input_curves[i].parametric = SkNamedTransferFn::kLinear;
808 }
809 }
810
811 // Populate CICP.
812 if (skcms_TransferFunction_isHLGish(&fn) || skcms_TransferFunction_isPQish(&fn) ||
813 skcms_TransferFunction_isHLG(&fn) || skcms_TransferFunction_isPQ(&fn)) {
814 profile.has_CICP = true;
815 profile.CICP.color_primaries = get_cicp_primaries(toXYZD50);
816 profile.CICP.transfer_characteristics = get_cicp_trfn(fn);
817 profile.CICP.matrix_coefficients = 0;
818 profile.CICP.video_full_range_flag = 1;
819 SkASSERT(profile.CICP.color_primaries);
820 SkASSERT(profile.CICP.transfer_characteristics);
821 }
822
823 std::string description = get_desc_string(fn, toXYZD50);
824 return SkWriteICCProfile(&profile, description.c_str());
825 }