xref: /aosp_15_r20/external/libultrahdr/lib/src/icc.cpp (revision 89a0ef05262152531a00a15832a2d3b1e3990773)
1 /*
2  * Copyright 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <cstring>
18 #include <cmath>
19 
20 #include "ultrahdr/ultrahdrcommon.h"
21 #include "ultrahdr/icc.h"
22 
23 namespace ultrahdr {
24 
Matrix3x3_apply(const Matrix3x3 * m,float * x)25 static void Matrix3x3_apply(const Matrix3x3* m, float* x) {
26   float y0 = x[0] * m->vals[0][0] + x[1] * m->vals[0][1] + x[2] * m->vals[0][2];
27   float y1 = x[0] * m->vals[1][0] + x[1] * m->vals[1][1] + x[2] * m->vals[1][2];
28   float y2 = x[0] * m->vals[2][0] + x[1] * m->vals[2][1] + x[2] * m->vals[2][2];
29   x[0] = y0;
30   x[1] = y1;
31   x[2] = y2;
32 }
33 
Matrix3x3_invert(const Matrix3x3 * src,Matrix3x3 * dst)34 bool Matrix3x3_invert(const Matrix3x3* src, Matrix3x3* dst) {
35   double a00 = src->vals[0][0];
36   double a01 = src->vals[1][0];
37   double a02 = src->vals[2][0];
38   double a10 = src->vals[0][1];
39   double a11 = src->vals[1][1];
40   double a12 = src->vals[2][1];
41   double a20 = src->vals[0][2];
42   double a21 = src->vals[1][2];
43   double a22 = src->vals[2][2];
44 
45   double b0 = a00 * a11 - a01 * a10;
46   double b1 = a00 * a12 - a02 * a10;
47   double b2 = a01 * a12 - a02 * a11;
48   double b3 = a20;
49   double b4 = a21;
50   double b5 = a22;
51 
52   double determinant = b0 * b5 - b1 * b4 + b2 * b3;
53 
54   if (determinant == 0) {
55     return false;
56   }
57 
58   double invdet = 1.0 / determinant;
59   if (invdet > +FLT_MAX || invdet < -FLT_MAX || !isfinitef_((float)invdet)) {
60     return false;
61   }
62 
63   b0 *= invdet;
64   b1 *= invdet;
65   b2 *= invdet;
66   b3 *= invdet;
67   b4 *= invdet;
68   b5 *= invdet;
69 
70   dst->vals[0][0] = (float)(a11 * b5 - a12 * b4);
71   dst->vals[1][0] = (float)(a02 * b4 - a01 * b5);
72   dst->vals[2][0] = (float)(+b2);
73   dst->vals[0][1] = (float)(a12 * b3 - a10 * b5);
74   dst->vals[1][1] = (float)(a00 * b5 - a02 * b3);
75   dst->vals[2][1] = (float)(-b1);
76   dst->vals[0][2] = (float)(a10 * b4 - a11 * b3);
77   dst->vals[1][2] = (float)(a01 * b3 - a00 * b4);
78   dst->vals[2][2] = (float)(+b0);
79 
80   for (int r = 0; r < 3; ++r)
81     for (int c = 0; c < 3; ++c) {
82       if (!isfinitef_(dst->vals[r][c])) {
83         return false;
84       }
85     }
86   return true;
87 }
88 
Matrix3x3_concat(const Matrix3x3 * A,const Matrix3x3 * B)89 static Matrix3x3 Matrix3x3_concat(const Matrix3x3* A, const Matrix3x3* B) {
90   Matrix3x3 m = {{{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}};
91   for (int r = 0; r < 3; r++)
92     for (int c = 0; c < 3; c++) {
93       m.vals[r][c] = A->vals[r][0] * B->vals[0][c] + A->vals[r][1] * B->vals[1][c] +
94                      A->vals[r][2] * B->vals[2][c];
95     }
96   return m;
97 }
98 
float_XYZD50_to_grid16_lab(const float * xyz_float,uint8_t * grid16_lab)99 static void float_XYZD50_to_grid16_lab(const float* xyz_float, uint8_t* grid16_lab) {
100   float v[3] = {
101       xyz_float[0] / kD50_x,
102       xyz_float[1] / kD50_y,
103       xyz_float[2] / kD50_z,
104   };
105   for (size_t i = 0; i < 3; ++i) {
106     v[i] = v[i] > 0.008856f ? cbrtf(v[i]) : v[i] * 7.787f + (16 / 116.0f);
107   }
108   const float L = v[1] * 116.0f - 16.0f;
109   const float a = (v[0] - v[1]) * 500.0f;
110   const float b = (v[1] - v[2]) * 200.0f;
111   const float Lab_unorm[3] = {
112       L * (1 / 100.f),
113       (a + 128.0f) * (1 / 255.0f),
114       (b + 128.0f) * (1 / 255.0f),
115   };
116   // This will encode L=1 as 0xFFFF. This matches how skcms will interpret the
117   // table, but the spec appears to indicate that the value should be 0xFF00.
118   // https://crbug.com/skia/13807
119   for (size_t i = 0; i < 3; ++i) {
120     reinterpret_cast<uint16_t*>(grid16_lab)[i] =
121         Endian_SwapBE16(float_round_to_unorm16(Lab_unorm[i]));
122   }
123 }
124 
get_desc_string(const uhdr_color_transfer_t tf,const uhdr_color_gamut_t gamut)125 std::string IccHelper::get_desc_string(const uhdr_color_transfer_t tf,
126                                        const uhdr_color_gamut_t gamut) {
127   std::string result;
128   switch (gamut) {
129     case UHDR_CG_BT_709:
130       result += "sRGB";
131       break;
132     case UHDR_CG_DISPLAY_P3:
133       result += "Display P3";
134       break;
135     case UHDR_CG_BT_2100:
136       result += "Rec2020";
137       break;
138     default:
139       result += "Unknown";
140       break;
141   }
142   result += " Gamut with ";
143   switch (tf) {
144     case UHDR_CT_SRGB:
145       result += "sRGB";
146       break;
147     case UHDR_CT_LINEAR:
148       result += "Linear";
149       break;
150     case UHDR_CT_PQ:
151       result += "PQ";
152       break;
153     case UHDR_CT_HLG:
154       result += "HLG";
155       break;
156     default:
157       result += "Unknown";
158       break;
159   }
160   result += " Transfer";
161   return result;
162 }
163 
write_text_tag(const char * text)164 std::shared_ptr<DataStruct> IccHelper::write_text_tag(const char* text) {
165   uint32_t text_length = strlen(text);
166   uint32_t header[] = {
167       Endian_SwapBE32(kTAG_TextType),                       // Type signature
168       0,                                                    // Reserved
169       Endian_SwapBE32(1),                                   // Number of records
170       Endian_SwapBE32(12),                                  // Record size (must be 12)
171       Endian_SwapBE32(SetFourByteTag('e', 'n', 'U', 'S')),  // English USA
172       Endian_SwapBE32(2 * text_length),                     // Length of string in bytes
173       Endian_SwapBE32(28),                                  // Offset of string
174   };
175 
176   uint32_t total_length = text_length * 2 + sizeof(header);
177   total_length = (((total_length + 2) >> 2) << 2);  // 4 aligned
178   std::shared_ptr<DataStruct> dataStruct = std::make_shared<DataStruct>(total_length);
179 
180   if (!dataStruct->write(header, sizeof(header))) {
181     ALOGE("write_text_tag(): error in writing data");
182     return dataStruct;
183   }
184 
185   for (size_t i = 0; i < text_length; i++) {
186     // Convert ASCII to big-endian UTF-16.
187     dataStruct->write8(0);
188     dataStruct->write8(text[i]);
189   }
190 
191   return dataStruct;
192 }
193 
write_xyz_tag(float x,float y,float z)194 std::shared_ptr<DataStruct> IccHelper::write_xyz_tag(float x, float y, float z) {
195   uint32_t data[] = {
196       Endian_SwapBE32(kXYZ_PCSSpace),
197       0,
198       static_cast<uint32_t>(Endian_SwapBE32(float_round_to_fixed(x))),
199       static_cast<uint32_t>(Endian_SwapBE32(float_round_to_fixed(y))),
200       static_cast<uint32_t>(Endian_SwapBE32(float_round_to_fixed(z))),
201   };
202   std::shared_ptr<DataStruct> dataStruct = std::make_shared<DataStruct>(sizeof(data));
203   dataStruct->write(&data, sizeof(data));
204   return dataStruct;
205 }
206 
write_trc_tag(const int table_entries,const void * table_16)207 std::shared_ptr<DataStruct> IccHelper::write_trc_tag(const int table_entries,
208                                                      const void* table_16) {
209   int total_length = 4 + 4 + 4 + table_entries * 2;
210   total_length = (((total_length + 2) >> 2) << 2);  // 4 aligned
211   std::shared_ptr<DataStruct> dataStruct = std::make_shared<DataStruct>(total_length);
212   dataStruct->write32(Endian_SwapBE32(kTAG_CurveType));  // Type
213   dataStruct->write32(0);                                // Reserved
214   dataStruct->write32(Endian_SwapBE32(table_entries));   // Value count
215   for (int i = 0; i < table_entries; ++i) {
216     uint16_t value = reinterpret_cast<const uint16_t*>(table_16)[i];
217     dataStruct->write16(value);
218   }
219   return dataStruct;
220 }
221 
write_trc_tag(const TransferFunction & fn)222 std::shared_ptr<DataStruct> IccHelper::write_trc_tag(const TransferFunction& fn) {
223   if (fn.a == 1.f && fn.b == 0.f && fn.c == 0.f && fn.d == 0.f && fn.e == 0.f && fn.f == 0.f) {
224     int total_length = 16;
225     std::shared_ptr<DataStruct> dataStruct = std::make_shared<DataStruct>(total_length);
226     dataStruct->write32(Endian_SwapBE32(kTAG_ParaCurveType));  // Type
227     dataStruct->write32(0);                                    // Reserved
228     dataStruct->write32(Endian_SwapBE16(kExponential_ParaCurveType));
229     dataStruct->write32(Endian_SwapBE32(float_round_to_fixed(fn.g)));
230     return dataStruct;
231   }
232 
233   int total_length = 40;
234   std::shared_ptr<DataStruct> dataStruct = std::make_shared<DataStruct>(total_length);
235   dataStruct->write32(Endian_SwapBE32(kTAG_ParaCurveType));  // Type
236   dataStruct->write32(0);                                    // Reserved
237   dataStruct->write32(Endian_SwapBE16(kGABCDEF_ParaCurveType));
238   dataStruct->write32(Endian_SwapBE32(float_round_to_fixed(fn.g)));
239   dataStruct->write32(Endian_SwapBE32(float_round_to_fixed(fn.a)));
240   dataStruct->write32(Endian_SwapBE32(float_round_to_fixed(fn.b)));
241   dataStruct->write32(Endian_SwapBE32(float_round_to_fixed(fn.c)));
242   dataStruct->write32(Endian_SwapBE32(float_round_to_fixed(fn.d)));
243   dataStruct->write32(Endian_SwapBE32(float_round_to_fixed(fn.e)));
244   dataStruct->write32(Endian_SwapBE32(float_round_to_fixed(fn.f)));
245   return dataStruct;
246 }
247 
compute_tone_map_gain(const uhdr_color_transfer_t tf,float L)248 float IccHelper::compute_tone_map_gain(const uhdr_color_transfer_t tf, float L) {
249   if (L <= 0.f) {
250     return 1.f;
251   }
252   if (tf == UHDR_CT_PQ) {
253     // The PQ transfer function will map to the range [0, 1]. Linearly scale
254     // it up to the range [0, 10,000/203]. We will then tone map that back
255     // down to [0, 1].
256     constexpr float kInputMaxLuminance = 10000 / 203.f;
257     constexpr float kOutputMaxLuminance = 1.0;
258     L *= kInputMaxLuminance;
259 
260     // Compute the tone map gain which will tone map from 10,000/203 to 1.0.
261     constexpr float kToneMapA = kOutputMaxLuminance / (kInputMaxLuminance * kInputMaxLuminance);
262     constexpr float kToneMapB = 1.f / kOutputMaxLuminance;
263     return kInputMaxLuminance * (1.f + kToneMapA * L) / (1.f + kToneMapB * L);
264   }
265   if (tf == UHDR_CT_HLG) {
266     // Let Lw be the brightness of the display in nits.
267     constexpr float Lw = 203.f;
268     const float gamma = 1.2f + 0.42f * std::log(Lw / 1000.f) / std::log(10.f);
269     return std::pow(L, gamma - 1.f);
270   }
271   return 1.f;
272 }
273 
write_cicp_tag(uint32_t color_primaries,uint32_t transfer_characteristics)274 std::shared_ptr<DataStruct> IccHelper::write_cicp_tag(uint32_t color_primaries,
275                                                       uint32_t transfer_characteristics) {
276   int total_length = 12;  // 4 + 4 + 1 + 1 + 1 + 1
277   std::shared_ptr<DataStruct> dataStruct = std::make_shared<DataStruct>(total_length);
278   dataStruct->write32(Endian_SwapBE32(kTAG_cicp));  // Type signature
279   dataStruct->write32(0);                           // Reserved
280   dataStruct->write8(color_primaries);              // Color primaries
281   dataStruct->write8(transfer_characteristics);     // Transfer characteristics
282   dataStruct->write8(0);                            // RGB matrix
283   dataStruct->write8(1);                            // Full range
284   return dataStruct;
285 }
286 
compute_lut_entry(const Matrix3x3 & src_to_XYZD50,float rgb[3])287 void IccHelper::compute_lut_entry(const Matrix3x3& src_to_XYZD50, float rgb[3]) {
288   // Compute the matrices to convert from source to Rec2020, and from Rec2020 to XYZD50.
289   Matrix3x3 src_to_rec2020;
290   const Matrix3x3 rec2020_to_XYZD50 = kRec2020;
291   {
292     Matrix3x3 XYZD50_to_rec2020;
293     Matrix3x3_invert(&rec2020_to_XYZD50, &XYZD50_to_rec2020);
294     src_to_rec2020 = Matrix3x3_concat(&XYZD50_to_rec2020, &src_to_XYZD50);
295   }
296 
297   // Convert the source signal to linear.
298   for (size_t i = 0; i < kNumChannels; ++i) {
299     rgb[i] = pqOetf(rgb[i]);
300   }
301 
302   // Convert source gamut to Rec2020.
303   Matrix3x3_apply(&src_to_rec2020, rgb);
304 
305   // Compute the luminance of the signal.
306   float L = bt2100Luminance({{{rgb[0], rgb[1], rgb[2]}}});
307 
308   // Compute the tone map gain based on the luminance.
309   float tone_map_gain = compute_tone_map_gain(UHDR_CT_PQ, L);
310 
311   // Apply the tone map gain.
312   for (size_t i = 0; i < kNumChannels; ++i) {
313     rgb[i] *= tone_map_gain;
314   }
315 
316   // Convert from Rec2020-linear to XYZD50.
317   Matrix3x3_apply(&rec2020_to_XYZD50, rgb);
318 }
319 
write_clut(const uint8_t * grid_points,const uint8_t * grid_16)320 std::shared_ptr<DataStruct> IccHelper::write_clut(const uint8_t* grid_points,
321                                                   const uint8_t* grid_16) {
322   uint32_t value_count = kNumChannels;
323   for (uint32_t i = 0; i < kNumChannels; ++i) {
324     value_count *= grid_points[i];
325   }
326 
327   int total_length = 20 + 2 * value_count;
328   total_length = (((total_length + 2) >> 2) << 2);  // 4 aligned
329   std::shared_ptr<DataStruct> dataStruct = std::make_shared<DataStruct>(total_length);
330 
331   for (size_t i = 0; i < 16; ++i) {
332     dataStruct->write8(i < kNumChannels ? grid_points[i] : 0);  // Grid size
333   }
334   dataStruct->write8(2);  // Grid byte width (always 16-bit)
335   dataStruct->write8(0);  // Reserved
336   dataStruct->write8(0);  // Reserved
337   dataStruct->write8(0);  // Reserved
338 
339   for (uint32_t i = 0; i < value_count; ++i) {
340     uint16_t value = reinterpret_cast<const uint16_t*>(grid_16)[i];
341     dataStruct->write16(value);
342   }
343 
344   return dataStruct;
345 }
346 
write_mAB_or_mBA_tag(uint32_t type,bool has_a_curves,const uint8_t * grid_points,const uint8_t * grid_16)347 std::shared_ptr<DataStruct> IccHelper::write_mAB_or_mBA_tag(uint32_t type, bool has_a_curves,
348                                                             const uint8_t* grid_points,
349                                                             const uint8_t* grid_16) {
350   const size_t b_curves_offset = 32;
351   std::shared_ptr<DataStruct> b_curves_data[kNumChannels];
352   std::shared_ptr<DataStruct> a_curves_data[kNumChannels];
353   size_t clut_offset = 0;
354   std::shared_ptr<DataStruct> clut;
355   size_t a_curves_offset = 0;
356 
357   // The "B" curve is required.
358   for (size_t i = 0; i < kNumChannels; ++i) {
359     b_curves_data[i] = write_trc_tag(kLinear_TransFun);
360   }
361 
362   // The "A" curve and CLUT are optional.
363   if (has_a_curves) {
364     clut_offset = b_curves_offset;
365     for (size_t i = 0; i < kNumChannels; ++i) {
366       clut_offset += b_curves_data[i]->getLength();
367     }
368     clut = write_clut(grid_points, grid_16);
369 
370     a_curves_offset = clut_offset + clut->getLength();
371     for (size_t i = 0; i < kNumChannels; ++i) {
372       a_curves_data[i] = write_trc_tag(kLinear_TransFun);
373     }
374   }
375 
376   int total_length = b_curves_offset;
377   for (size_t i = 0; i < kNumChannels; ++i) {
378     total_length += b_curves_data[i]->getLength();
379   }
380   if (has_a_curves) {
381     total_length += clut->getLength();
382     for (size_t i = 0; i < kNumChannels; ++i) {
383       total_length += a_curves_data[i]->getLength();
384     }
385   }
386   std::shared_ptr<DataStruct> dataStruct = std::make_shared<DataStruct>(total_length);
387   dataStruct->write32(Endian_SwapBE32(type));             // Type signature
388   dataStruct->write32(0);                                 // Reserved
389   dataStruct->write8(kNumChannels);                       // Input channels
390   dataStruct->write8(kNumChannels);                       // Output channels
391   dataStruct->write16(0);                                 // Reserved
392   dataStruct->write32(Endian_SwapBE32(b_curves_offset));  // B curve offset
393   dataStruct->write32(Endian_SwapBE32(0));                // Matrix offset (ignored)
394   dataStruct->write32(Endian_SwapBE32(0));                // M curve offset (ignored)
395   dataStruct->write32(Endian_SwapBE32(clut_offset));      // CLUT offset
396   dataStruct->write32(Endian_SwapBE32(a_curves_offset));  // A curve offset
397   for (size_t i = 0; i < kNumChannels; ++i) {
398     if (dataStruct->write(b_curves_data[i]->getData(), b_curves_data[i]->getLength())) {
399       return dataStruct;
400     }
401   }
402   if (has_a_curves) {
403     dataStruct->write(clut->getData(), clut->getLength());
404     for (size_t i = 0; i < kNumChannels; ++i) {
405       dataStruct->write(a_curves_data[i]->getData(), a_curves_data[i]->getLength());
406     }
407   }
408   return dataStruct;
409 }
410 
writeIccProfile(uhdr_color_transfer_t tf,uhdr_color_gamut_t gamut)411 std::shared_ptr<DataStruct> IccHelper::writeIccProfile(uhdr_color_transfer_t tf,
412                                                        uhdr_color_gamut_t gamut) {
413   ICCHeader header;
414 
415   std::vector<std::pair<uint32_t, std::shared_ptr<DataStruct>>> tags;
416 
417   // Compute profile description tag
418   std::string desc = get_desc_string(tf, gamut);
419 
420   tags.emplace_back(kTAG_desc, write_text_tag(desc.c_str()));
421 
422   Matrix3x3 toXYZD50;
423   switch (gamut) {
424     case UHDR_CG_BT_709:
425       toXYZD50 = kSRGB;
426       break;
427     case UHDR_CG_DISPLAY_P3:
428       toXYZD50 = kDisplayP3;
429       break;
430     case UHDR_CG_BT_2100:
431       toXYZD50 = kRec2020;
432       break;
433     default:
434       // Should not fall here.
435       return nullptr;
436   }
437 
438   // Compute primaries.
439   {
440     tags.emplace_back(kTAG_rXYZ,
441                       write_xyz_tag(toXYZD50.vals[0][0], toXYZD50.vals[1][0], toXYZD50.vals[2][0]));
442     tags.emplace_back(kTAG_gXYZ,
443                       write_xyz_tag(toXYZD50.vals[0][1], toXYZD50.vals[1][1], toXYZD50.vals[2][1]));
444     tags.emplace_back(kTAG_bXYZ,
445                       write_xyz_tag(toXYZD50.vals[0][2], toXYZD50.vals[1][2], toXYZD50.vals[2][2]));
446   }
447 
448   // Compute white point tag (must be D50)
449   tags.emplace_back(kTAG_wtpt, write_xyz_tag(kD50_x, kD50_y, kD50_z));
450 
451   // Compute transfer curves.
452   if (tf != UHDR_CT_PQ) {
453     if (tf == UHDR_CT_HLG) {
454       std::vector<uint8_t> trc_table;
455       trc_table.resize(kTrcTableSize * 2);
456       for (uint32_t i = 0; i < kTrcTableSize; ++i) {
457         float x = i / (kTrcTableSize - 1.f);
458         float y = hlgOetf(x);
459         y *= compute_tone_map_gain(tf, y);
460         float_to_table16(y, &trc_table[2 * i]);
461       }
462 
463       tags.emplace_back(kTAG_rTRC,
464                         write_trc_tag(kTrcTableSize, reinterpret_cast<uint8_t*>(trc_table.data())));
465       tags.emplace_back(kTAG_gTRC,
466                         write_trc_tag(kTrcTableSize, reinterpret_cast<uint8_t*>(trc_table.data())));
467       tags.emplace_back(kTAG_bTRC,
468                         write_trc_tag(kTrcTableSize, reinterpret_cast<uint8_t*>(trc_table.data())));
469     } else {
470       tags.emplace_back(kTAG_rTRC, write_trc_tag(kSRGB_TransFun));
471       tags.emplace_back(kTAG_gTRC, write_trc_tag(kSRGB_TransFun));
472       tags.emplace_back(kTAG_bTRC, write_trc_tag(kSRGB_TransFun));
473     }
474   }
475 
476   // Compute CICP.
477   if (tf == UHDR_CT_HLG || tf == UHDR_CT_PQ) {
478     // The CICP tag is present in ICC 4.4, so update the header's version.
479     header.version = Endian_SwapBE32(0x04400000);
480 
481     uint32_t color_primaries = 0;
482     if (gamut == UHDR_CG_BT_709) {
483       color_primaries = kCICPPrimariesSRGB;
484     } else if (gamut == UHDR_CG_DISPLAY_P3) {
485       color_primaries = kCICPPrimariesP3;
486     }
487 
488     uint32_t transfer_characteristics = 0;
489     if (tf == UHDR_CT_SRGB) {
490       transfer_characteristics = kCICPTrfnSRGB;
491     } else if (tf == UHDR_CT_LINEAR) {
492       transfer_characteristics = kCICPTrfnLinear;
493     } else if (tf == UHDR_CT_PQ) {
494       transfer_characteristics = kCICPTrfnPQ;
495     } else if (tf == UHDR_CT_HLG) {
496       transfer_characteristics = kCICPTrfnHLG;
497     }
498     tags.emplace_back(kTAG_cicp, write_cicp_tag(color_primaries, transfer_characteristics));
499   }
500 
501   // Compute A2B0.
502   if (tf == UHDR_CT_PQ) {
503     std::vector<uint8_t> a2b_grid;
504     a2b_grid.resize(kGridSize * kGridSize * kGridSize * kNumChannels * 2);
505     size_t a2b_grid_index = 0;
506     for (uint32_t r_index = 0; r_index < kGridSize; ++r_index) {
507       for (uint32_t g_index = 0; g_index < kGridSize; ++g_index) {
508         for (uint32_t b_index = 0; b_index < kGridSize; ++b_index) {
509           float rgb[3] = {
510               r_index / (kGridSize - 1.f),
511               g_index / (kGridSize - 1.f),
512               b_index / (kGridSize - 1.f),
513           };
514           compute_lut_entry(toXYZD50, rgb);
515           float_XYZD50_to_grid16_lab(rgb, &a2b_grid[a2b_grid_index]);
516           a2b_grid_index += 6;
517         }
518       }
519     }
520     const uint8_t* grid_16 = reinterpret_cast<const uint8_t*>(a2b_grid.data());
521 
522     uint8_t grid_points[kNumChannels];
523     for (size_t i = 0; i < kNumChannels; ++i) {
524       grid_points[i] = kGridSize;
525     }
526 
527     auto a2b_data = write_mAB_or_mBA_tag(kTAG_mABType,
528                                          /* has_a_curves */ true, grid_points, grid_16);
529     tags.emplace_back(kTAG_A2B0, std::move(a2b_data));
530   }
531 
532   // Compute B2A0.
533   if (tf == UHDR_CT_PQ) {
534     auto b2a_data = write_mAB_or_mBA_tag(kTAG_mBAType,
535                                          /* has_a_curves */ false,
536                                          /* grid_points */ nullptr,
537                                          /* grid_16 */ nullptr);
538     tags.emplace_back(kTAG_B2A0, std::move(b2a_data));
539   }
540 
541   // Compute copyright tag
542   tags.emplace_back(kTAG_cprt, write_text_tag("Google Inc. 2022"));
543 
544   // Compute the size of the profile.
545   size_t tag_data_size = 0;
546   for (const auto& tag : tags) {
547     tag_data_size += tag.second->getLength();
548   }
549   size_t tag_table_size = kICCTagTableEntrySize * tags.size();
550   size_t profile_size = kICCHeaderSize + tag_table_size + tag_data_size;
551 
552   std::shared_ptr<DataStruct> dataStruct =
553       std::make_shared<DataStruct>(profile_size + kICCIdentifierSize);
554 
555   // Write identifier, chunk count, and chunk ID
556   if (!dataStruct->write(kICCIdentifier, sizeof(kICCIdentifier)) || !dataStruct->write8(1) ||
557       !dataStruct->write8(1)) {
558     ALOGE("writeIccProfile(): error in identifier");
559     return dataStruct;
560   }
561 
562   // Write the header.
563   header.data_color_space = Endian_SwapBE32(Signature_RGB);
564   header.pcs = Endian_SwapBE32(tf == UHDR_CT_PQ ? Signature_Lab : Signature_XYZ);
565   header.size = Endian_SwapBE32(profile_size);
566   header.tag_count = Endian_SwapBE32(tags.size());
567 
568   if (!dataStruct->write(&header, sizeof(header))) {
569     ALOGE("writeIccProfile(): error in header");
570     return dataStruct;
571   }
572 
573   // Write the tag table. Track the offset and size of the previous tag to
574   // compute each tag's offset. An empty SkData indicates that the previous
575   // tag is to be reused.
576   uint32_t last_tag_offset = sizeof(header) + tag_table_size;
577   uint32_t last_tag_size = 0;
578   for (const auto& tag : tags) {
579     last_tag_offset = last_tag_offset + last_tag_size;
580     last_tag_size = tag.second->getLength();
581     uint32_t tag_table_entry[3] = {
582         Endian_SwapBE32(tag.first),
583         Endian_SwapBE32(last_tag_offset),
584         Endian_SwapBE32(last_tag_size),
585     };
586     if (!dataStruct->write(tag_table_entry, sizeof(tag_table_entry))) {
587       ALOGE("writeIccProfile(): error in writing tag table");
588       return dataStruct;
589     }
590   }
591 
592   // Write the tags.
593   for (const auto& tag : tags) {
594     if (!dataStruct->write(tag.second->getData(), tag.second->getLength())) {
595       ALOGE("writeIccProfile(): error in writing tags");
596       return dataStruct;
597     }
598   }
599 
600   return dataStruct;
601 }
602 
tagsEqualToMatrix(const Matrix3x3 & matrix,const uint8_t * red_tag,const uint8_t * green_tag,const uint8_t * blue_tag)603 bool IccHelper::tagsEqualToMatrix(const Matrix3x3& matrix, const uint8_t* red_tag,
604                                   const uint8_t* green_tag, const uint8_t* blue_tag) {
605   const float tolerance = 0.001;
606   Fixed r_x_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(red_tag))[2]);
607   Fixed r_y_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(red_tag))[3]);
608   Fixed r_z_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(red_tag))[4]);
609   float r_x = FixedToFloat(r_x_fixed);
610   float r_y = FixedToFloat(r_y_fixed);
611   float r_z = FixedToFloat(r_z_fixed);
612   if (fabs(r_x - matrix.vals[0][0]) > tolerance || fabs(r_y - matrix.vals[1][0]) > tolerance ||
613       fabs(r_z - matrix.vals[2][0]) > tolerance) {
614     return false;
615   }
616 
617   Fixed g_x_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(green_tag))[2]);
618   Fixed g_y_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(green_tag))[3]);
619   Fixed g_z_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(green_tag))[4]);
620   float g_x = FixedToFloat(g_x_fixed);
621   float g_y = FixedToFloat(g_y_fixed);
622   float g_z = FixedToFloat(g_z_fixed);
623   if (fabs(g_x - matrix.vals[0][1]) > tolerance || fabs(g_y - matrix.vals[1][1]) > tolerance ||
624       fabs(g_z - matrix.vals[2][1]) > tolerance) {
625     return false;
626   }
627 
628   Fixed b_x_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(blue_tag))[2]);
629   Fixed b_y_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(blue_tag))[3]);
630   Fixed b_z_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(blue_tag))[4]);
631   float b_x = FixedToFloat(b_x_fixed);
632   float b_y = FixedToFloat(b_y_fixed);
633   float b_z = FixedToFloat(b_z_fixed);
634   if (fabs(b_x - matrix.vals[0][2]) > tolerance || fabs(b_y - matrix.vals[1][2]) > tolerance ||
635       fabs(b_z - matrix.vals[2][2]) > tolerance) {
636     return false;
637   }
638 
639   return true;
640 }
641 
readIccColorGamut(void * icc_data,size_t icc_size)642 uhdr_color_gamut_t IccHelper::readIccColorGamut(void* icc_data, size_t icc_size) {
643   // Each tag table entry consists of 3 fields of 4 bytes each.
644   static const size_t kTagTableEntrySize = 12;
645 
646   if (icc_data == nullptr || icc_size < sizeof(ICCHeader) + kICCIdentifierSize) {
647     return UHDR_CG_UNSPECIFIED;
648   }
649 
650   if (memcmp(icc_data, kICCIdentifier, sizeof(kICCIdentifier)) != 0) {
651     return UHDR_CG_UNSPECIFIED;
652   }
653 
654   uint8_t* icc_bytes = reinterpret_cast<uint8_t*>(icc_data) + kICCIdentifierSize;
655   auto alignment_needs = alignof(ICCHeader);
656   uint8_t* aligned_block = nullptr;
657   if (((uintptr_t)icc_bytes) % alignment_needs != 0) {
658     aligned_block = static_cast<uint8_t*>(
659         ::operator new[](icc_size - kICCIdentifierSize, std::align_val_t(alignment_needs)));
660     if (!aligned_block) {
661       ALOGE("unable allocate memory, icc parsing failed");
662       return UHDR_CG_UNSPECIFIED;
663     }
664     std::memcpy(aligned_block, icc_bytes, icc_size - kICCIdentifierSize);
665     icc_bytes = aligned_block;
666   }
667   ICCHeader* header = reinterpret_cast<ICCHeader*>(icc_bytes);
668 
669   // Use 0 to indicate not found, since offsets are always relative to start
670   // of ICC data and therefore a tag offset of zero would never be valid.
671   size_t red_primary_offset = 0, green_primary_offset = 0, blue_primary_offset = 0;
672   size_t red_primary_size = 0, green_primary_size = 0, blue_primary_size = 0;
673   for (size_t tag_idx = 0; tag_idx < Endian_SwapBE32(header->tag_count); ++tag_idx) {
674     if (icc_size < kICCIdentifierSize + sizeof(ICCHeader) + ((tag_idx + 1) * kTagTableEntrySize)) {
675       ALOGE(
676           "Insufficient buffer size during icc parsing. tag index %zu, header %zu, tag size %zu, "
677           "icc size %zu",
678           tag_idx, kICCIdentifierSize + sizeof(ICCHeader), kTagTableEntrySize, icc_size);
679       if (aligned_block) ::operator delete[](aligned_block, std::align_val_t(alignment_needs));
680       return UHDR_CG_UNSPECIFIED;
681     }
682     uint32_t* tag_entry_start =
683         reinterpret_cast<uint32_t*>(icc_bytes + sizeof(ICCHeader) + tag_idx * kTagTableEntrySize);
684     // first 4 bytes are the tag signature, next 4 bytes are the tag offset,
685     // last 4 bytes are the tag length in bytes.
686     if (red_primary_offset == 0 && *tag_entry_start == Endian_SwapBE32(kTAG_rXYZ)) {
687       red_primary_offset = Endian_SwapBE32(*(tag_entry_start + 1));
688       red_primary_size = Endian_SwapBE32(*(tag_entry_start + 2));
689     } else if (green_primary_offset == 0 && *tag_entry_start == Endian_SwapBE32(kTAG_gXYZ)) {
690       green_primary_offset = Endian_SwapBE32(*(tag_entry_start + 1));
691       green_primary_size = Endian_SwapBE32(*(tag_entry_start + 2));
692     } else if (blue_primary_offset == 0 && *tag_entry_start == Endian_SwapBE32(kTAG_bXYZ)) {
693       blue_primary_offset = Endian_SwapBE32(*(tag_entry_start + 1));
694       blue_primary_size = Endian_SwapBE32(*(tag_entry_start + 2));
695     }
696   }
697 
698   if (red_primary_offset == 0 || red_primary_size != kColorantTagSize ||
699       kICCIdentifierSize + red_primary_offset + red_primary_size > icc_size ||
700       green_primary_offset == 0 || green_primary_size != kColorantTagSize ||
701       kICCIdentifierSize + green_primary_offset + green_primary_size > icc_size ||
702       blue_primary_offset == 0 || blue_primary_size != kColorantTagSize ||
703       kICCIdentifierSize + blue_primary_offset + blue_primary_size > icc_size) {
704     if (aligned_block) ::operator delete[](aligned_block, std::align_val_t(alignment_needs));
705     return UHDR_CG_UNSPECIFIED;
706   }
707 
708   uint8_t* red_tag = icc_bytes + red_primary_offset;
709   uint8_t* green_tag = icc_bytes + green_primary_offset;
710   uint8_t* blue_tag = icc_bytes + blue_primary_offset;
711 
712   // Serialize tags as we do on encode and compare what we find to that to
713   // determine the gamut (since we don't have a need yet for full deserialize).
714   uhdr_color_gamut_t gamut = UHDR_CG_UNSPECIFIED;
715   if (tagsEqualToMatrix(kSRGB, red_tag, green_tag, blue_tag)) {
716     gamut = UHDR_CG_BT_709;
717   } else if (tagsEqualToMatrix(kDisplayP3, red_tag, green_tag, blue_tag)) {
718     gamut = UHDR_CG_DISPLAY_P3;
719   } else if (tagsEqualToMatrix(kRec2020, red_tag, green_tag, blue_tag)) {
720     gamut = UHDR_CG_BT_2100;
721   }
722 
723   if (aligned_block) ::operator delete[](aligned_block, std::align_val_t(alignment_needs));
724   // Didn't find a match to one of the profiles we write; indicate the gamut
725   // is unspecified since we don't understand it.
726   return gamut;
727 }
728 
729 }  // namespace ultrahdr
730