• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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   std::shared_ptr<DataStruct> dataStruct = std::make_shared<DataStruct>(kCicpTagSize);
277   dataStruct->write32(Endian_SwapBE32(kTAG_cicp));  // Type signature
278   dataStruct->write32(0);                           // Reserved
279   dataStruct->write8(color_primaries);              // Color primaries
280   dataStruct->write8(transfer_characteristics);     // Transfer characteristics
281   dataStruct->write8(0);                            // RGB matrix
282   dataStruct->write8(1);                            // Full range
283   return dataStruct;
284 }
285 
compute_lut_entry(const Matrix3x3 & src_to_XYZD50,float rgb[3])286 void IccHelper::compute_lut_entry(const Matrix3x3& src_to_XYZD50, float rgb[3]) {
287   // Compute the matrices to convert from source to Rec2020, and from Rec2020 to XYZD50.
288   Matrix3x3 src_to_rec2020;
289   const Matrix3x3 rec2020_to_XYZD50 = kRec2020;
290   {
291     Matrix3x3 XYZD50_to_rec2020;
292     Matrix3x3_invert(&rec2020_to_XYZD50, &XYZD50_to_rec2020);
293     src_to_rec2020 = Matrix3x3_concat(&XYZD50_to_rec2020, &src_to_XYZD50);
294   }
295 
296   // Convert the source signal to linear.
297   for (size_t i = 0; i < kNumChannels; ++i) {
298     rgb[i] = pqOetf(rgb[i]);
299   }
300 
301   // Convert source gamut to Rec2020.
302   Matrix3x3_apply(&src_to_rec2020, rgb);
303 
304   // Compute the luminance of the signal.
305   float L = bt2100Luminance({{{rgb[0], rgb[1], rgb[2]}}});
306 
307   // Compute the tone map gain based on the luminance.
308   float tone_map_gain = compute_tone_map_gain(UHDR_CT_PQ, L);
309 
310   // Apply the tone map gain.
311   for (size_t i = 0; i < kNumChannels; ++i) {
312     rgb[i] *= tone_map_gain;
313   }
314 
315   // Convert from Rec2020-linear to XYZD50.
316   Matrix3x3_apply(&rec2020_to_XYZD50, rgb);
317 }
318 
write_clut(const uint8_t * grid_points,const uint8_t * grid_16)319 std::shared_ptr<DataStruct> IccHelper::write_clut(const uint8_t* grid_points,
320                                                   const uint8_t* grid_16) {
321   uint32_t value_count = kNumChannels;
322   for (uint32_t i = 0; i < kNumChannels; ++i) {
323     value_count *= grid_points[i];
324   }
325 
326   int total_length = 20 + 2 * value_count;
327   total_length = (((total_length + 2) >> 2) << 2);  // 4 aligned
328   std::shared_ptr<DataStruct> dataStruct = std::make_shared<DataStruct>(total_length);
329 
330   for (size_t i = 0; i < 16; ++i) {
331     dataStruct->write8(i < kNumChannels ? grid_points[i] : 0);  // Grid size
332   }
333   dataStruct->write8(2);  // Grid byte width (always 16-bit)
334   dataStruct->write8(0);  // Reserved
335   dataStruct->write8(0);  // Reserved
336   dataStruct->write8(0);  // Reserved
337 
338   for (uint32_t i = 0; i < value_count; ++i) {
339     uint16_t value = reinterpret_cast<const uint16_t*>(grid_16)[i];
340     dataStruct->write16(value);
341   }
342 
343   return dataStruct;
344 }
345 
write_mAB_or_mBA_tag(uint32_t type,bool has_a_curves,const uint8_t * grid_points,const uint8_t * grid_16)346 std::shared_ptr<DataStruct> IccHelper::write_mAB_or_mBA_tag(uint32_t type, bool has_a_curves,
347                                                             const uint8_t* grid_points,
348                                                             const uint8_t* grid_16) {
349   const size_t b_curves_offset = 32;
350   std::shared_ptr<DataStruct> b_curves_data[kNumChannels];
351   std::shared_ptr<DataStruct> a_curves_data[kNumChannels];
352   size_t clut_offset = 0;
353   std::shared_ptr<DataStruct> clut;
354   size_t a_curves_offset = 0;
355 
356   // The "B" curve is required.
357   for (size_t i = 0; i < kNumChannels; ++i) {
358     b_curves_data[i] = write_trc_tag(kLinear_TransFun);
359   }
360 
361   // The "A" curve and CLUT are optional.
362   if (has_a_curves) {
363     clut_offset = b_curves_offset;
364     for (size_t i = 0; i < kNumChannels; ++i) {
365       clut_offset += b_curves_data[i]->getLength();
366     }
367     clut = write_clut(grid_points, grid_16);
368 
369     a_curves_offset = clut_offset + clut->getLength();
370     for (size_t i = 0; i < kNumChannels; ++i) {
371       a_curves_data[i] = write_trc_tag(kLinear_TransFun);
372     }
373   }
374 
375   int total_length = b_curves_offset;
376   for (size_t i = 0; i < kNumChannels; ++i) {
377     total_length += b_curves_data[i]->getLength();
378   }
379   if (has_a_curves) {
380     total_length += clut->getLength();
381     for (size_t i = 0; i < kNumChannels; ++i) {
382       total_length += a_curves_data[i]->getLength();
383     }
384   }
385   std::shared_ptr<DataStruct> dataStruct = std::make_shared<DataStruct>(total_length);
386   dataStruct->write32(Endian_SwapBE32(type));             // Type signature
387   dataStruct->write32(0);                                 // Reserved
388   dataStruct->write8(kNumChannels);                       // Input channels
389   dataStruct->write8(kNumChannels);                       // Output channels
390   dataStruct->write16(0);                                 // Reserved
391   dataStruct->write32(Endian_SwapBE32(b_curves_offset));  // B curve offset
392   dataStruct->write32(Endian_SwapBE32(0));                // Matrix offset (ignored)
393   dataStruct->write32(Endian_SwapBE32(0));                // M curve offset (ignored)
394   dataStruct->write32(Endian_SwapBE32(clut_offset));      // CLUT offset
395   dataStruct->write32(Endian_SwapBE32(a_curves_offset));  // A curve offset
396   for (size_t i = 0; i < kNumChannels; ++i) {
397     if (dataStruct->write(b_curves_data[i]->getData(), b_curves_data[i]->getLength())) {
398       return dataStruct;
399     }
400   }
401   if (has_a_curves) {
402     dataStruct->write(clut->getData(), clut->getLength());
403     for (size_t i = 0; i < kNumChannels; ++i) {
404       dataStruct->write(a_curves_data[i]->getData(), a_curves_data[i]->getLength());
405     }
406   }
407   return dataStruct;
408 }
409 
writeIccProfile(uhdr_color_transfer_t tf,uhdr_color_gamut_t gamut)410 std::shared_ptr<DataStruct> IccHelper::writeIccProfile(uhdr_color_transfer_t tf,
411                                                        uhdr_color_gamut_t gamut) {
412   ICCHeader header;
413 
414   std::vector<std::pair<uint32_t, std::shared_ptr<DataStruct>>> tags;
415 
416   // Compute profile description tag
417   std::string desc = get_desc_string(tf, gamut);
418   tags.emplace_back(kTAG_desc, write_text_tag(desc.c_str()));
419 
420   Matrix3x3 toXYZD50;
421   switch (gamut) {
422     case UHDR_CG_BT_709:
423       toXYZD50 = kSRGB;
424       break;
425     case UHDR_CG_DISPLAY_P3:
426       toXYZD50 = kDisplayP3;
427       break;
428     case UHDR_CG_BT_2100:
429       toXYZD50 = kRec2020;
430       break;
431     default:
432       // Should not fall here.
433       return nullptr;
434   }
435 
436   // Compute primaries.
437   {
438     tags.emplace_back(kTAG_rXYZ,
439                       write_xyz_tag(toXYZD50.vals[0][0], toXYZD50.vals[1][0], toXYZD50.vals[2][0]));
440     tags.emplace_back(kTAG_gXYZ,
441                       write_xyz_tag(toXYZD50.vals[0][1], toXYZD50.vals[1][1], toXYZD50.vals[2][1]));
442     tags.emplace_back(kTAG_bXYZ,
443                       write_xyz_tag(toXYZD50.vals[0][2], toXYZD50.vals[1][2], toXYZD50.vals[2][2]));
444   }
445 
446   // Compute white point tag (must be D50)
447   tags.emplace_back(kTAG_wtpt, write_xyz_tag(kD50_x, kD50_y, kD50_z));
448 
449   // Compute transfer curves.
450   if (tf != UHDR_CT_PQ) {
451     if (tf == UHDR_CT_HLG) {
452       std::vector<uint8_t> trc_table;
453       trc_table.resize(kTrcTableSize * 2);
454       for (uint32_t i = 0; i < kTrcTableSize; ++i) {
455         float x = i / (kTrcTableSize - 1.f);
456         float y = hlgOetf(x);
457         y *= compute_tone_map_gain(tf, y);
458         float_to_table16(y, &trc_table[2 * i]);
459       }
460 
461       tags.emplace_back(kTAG_rTRC,
462                         write_trc_tag(kTrcTableSize, reinterpret_cast<uint8_t*>(trc_table.data())));
463       tags.emplace_back(kTAG_gTRC,
464                         write_trc_tag(kTrcTableSize, reinterpret_cast<uint8_t*>(trc_table.data())));
465       tags.emplace_back(kTAG_bTRC,
466                         write_trc_tag(kTrcTableSize, reinterpret_cast<uint8_t*>(trc_table.data())));
467     } else if (tf == UHDR_CT_SRGB) {
468       tags.emplace_back(kTAG_rTRC, write_trc_tag(kSRGB_TransFun));
469       tags.emplace_back(kTAG_gTRC, write_trc_tag(kSRGB_TransFun));
470       tags.emplace_back(kTAG_bTRC, write_trc_tag(kSRGB_TransFun));
471     } else if (tf == UHDR_CT_LINEAR) {
472       tags.emplace_back(kTAG_rTRC, write_trc_tag(kLinear_TransFun));
473       tags.emplace_back(kTAG_gTRC, write_trc_tag(kLinear_TransFun));
474       tags.emplace_back(kTAG_bTRC, write_trc_tag(kLinear_TransFun));
475     }
476   }
477 
478   // Compute CICP - for hdr images icc profile shall contain cicp.
479   if (tf == UHDR_CT_HLG || tf == UHDR_CT_PQ || tf == UHDR_CT_LINEAR) {
480     // The CICP tag is present in ICC 4.4, so update the header's version.
481     header.version = Endian_SwapBE32(0x04400000);
482 
483     uint32_t color_primaries = kCICPPrimariesUnSpecified;
484     if (gamut == UHDR_CG_BT_709) {
485       color_primaries = kCICPPrimariesSRGB;
486     } else if (gamut == UHDR_CG_DISPLAY_P3) {
487       color_primaries = kCICPPrimariesP3;
488     } else if (gamut == UHDR_CG_BT_2100) {
489       color_primaries = kCICPPrimariesRec2020;
490     }
491 
492     uint32_t transfer_characteristics = kCICPTrfnUnSpecified;
493     if (tf == UHDR_CT_SRGB) {
494       transfer_characteristics = kCICPTrfnSRGB;
495     } else if (tf == UHDR_CT_LINEAR) {
496       transfer_characteristics = kCICPTrfnLinear;
497     } else if (tf == UHDR_CT_PQ) {
498       transfer_characteristics = kCICPTrfnPQ;
499     } else if (tf == UHDR_CT_HLG) {
500       transfer_characteristics = kCICPTrfnHLG;
501     }
502     tags.emplace_back(kTAG_cicp, write_cicp_tag(color_primaries, transfer_characteristics));
503   }
504 
505   // Compute A2B0.
506   if (tf == UHDR_CT_PQ) {
507     std::vector<uint8_t> a2b_grid;
508     a2b_grid.resize(kGridSize * kGridSize * kGridSize * kNumChannels * 2);
509     size_t a2b_grid_index = 0;
510     for (uint32_t r_index = 0; r_index < kGridSize; ++r_index) {
511       for (uint32_t g_index = 0; g_index < kGridSize; ++g_index) {
512         for (uint32_t b_index = 0; b_index < kGridSize; ++b_index) {
513           float rgb[3] = {
514               r_index / (kGridSize - 1.f),
515               g_index / (kGridSize - 1.f),
516               b_index / (kGridSize - 1.f),
517           };
518           compute_lut_entry(toXYZD50, rgb);
519           float_XYZD50_to_grid16_lab(rgb, &a2b_grid[a2b_grid_index]);
520           a2b_grid_index += 6;
521         }
522       }
523     }
524     const uint8_t* grid_16 = reinterpret_cast<const uint8_t*>(a2b_grid.data());
525 
526     uint8_t grid_points[kNumChannels];
527     for (size_t i = 0; i < kNumChannels; ++i) {
528       grid_points[i] = kGridSize;
529     }
530 
531     auto a2b_data = write_mAB_or_mBA_tag(kTAG_mABType,
532                                          /* has_a_curves */ true, grid_points, grid_16);
533     tags.emplace_back(kTAG_A2B0, std::move(a2b_data));
534   }
535 
536   // Compute B2A0.
537   if (tf == UHDR_CT_PQ) {
538     auto b2a_data = write_mAB_or_mBA_tag(kTAG_mBAType,
539                                          /* has_a_curves */ false,
540                                          /* grid_points */ nullptr,
541                                          /* grid_16 */ nullptr);
542     tags.emplace_back(kTAG_B2A0, std::move(b2a_data));
543   }
544 
545   // Compute copyright tag
546   tags.emplace_back(kTAG_cprt, write_text_tag("Google Inc. 2022"));
547 
548   // Compute the size of the profile.
549   size_t tag_data_size = 0;
550   for (const auto& tag : tags) {
551     tag_data_size += tag.second->getLength();
552   }
553   size_t tag_table_size = kICCTagTableEntrySize * tags.size();
554   size_t profile_size = kICCHeaderSize + tag_table_size + tag_data_size;
555 
556   std::shared_ptr<DataStruct> dataStruct =
557       std::make_shared<DataStruct>(profile_size + kICCIdentifierSize);
558 
559   // Write identifier, chunk count, and chunk ID
560   if (!dataStruct->write(kICCIdentifier, sizeof(kICCIdentifier)) || !dataStruct->write8(1) ||
561       !dataStruct->write8(1)) {
562     ALOGE("writeIccProfile(): error in identifier");
563     return dataStruct;
564   }
565 
566   // Write the header.
567   header.data_color_space = Endian_SwapBE32(Signature_RGB);
568   header.pcs = Endian_SwapBE32(tf == UHDR_CT_PQ ? Signature_Lab : Signature_XYZ);
569   header.size = Endian_SwapBE32(profile_size);
570   header.tag_count = Endian_SwapBE32(tags.size());
571 
572   if (!dataStruct->write(&header, sizeof(header))) {
573     ALOGE("writeIccProfile(): error in header");
574     return dataStruct;
575   }
576 
577   // Write the tag table. Track the offset and size of the previous tag to
578   // compute each tag's offset. An empty SkData indicates that the previous
579   // tag is to be reused.
580   uint32_t last_tag_offset = sizeof(header) + tag_table_size;
581   uint32_t last_tag_size = 0;
582   for (const auto& tag : tags) {
583     last_tag_offset = last_tag_offset + last_tag_size;
584     last_tag_size = tag.second->getLength();
585     uint32_t tag_table_entry[3] = {
586         Endian_SwapBE32(tag.first),
587         Endian_SwapBE32(last_tag_offset),
588         Endian_SwapBE32(last_tag_size),
589     };
590     if (!dataStruct->write(tag_table_entry, sizeof(tag_table_entry))) {
591       ALOGE("writeIccProfile(): error in writing tag table");
592       return dataStruct;
593     }
594   }
595 
596   // Write the tags.
597   for (const auto& tag : tags) {
598     if (!dataStruct->write(tag.second->getData(), tag.second->getLength())) {
599       ALOGE("writeIccProfile(): error in writing tags");
600       return dataStruct;
601     }
602   }
603 
604   return dataStruct;
605 }
606 
tagsEqualToMatrix(const Matrix3x3 & matrix,const uint8_t * red_tag,const uint8_t * green_tag,const uint8_t * blue_tag)607 bool IccHelper::tagsEqualToMatrix(const Matrix3x3& matrix, const uint8_t* red_tag,
608                                   const uint8_t* green_tag, const uint8_t* blue_tag) {
609   const float tolerance = 0.001f;
610   Fixed r_x_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(red_tag))[2]);
611   Fixed r_y_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(red_tag))[3]);
612   Fixed r_z_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(red_tag))[4]);
613   float r_x = FixedToFloat(r_x_fixed);
614   float r_y = FixedToFloat(r_y_fixed);
615   float r_z = FixedToFloat(r_z_fixed);
616   if (fabs(r_x - matrix.vals[0][0]) > tolerance || fabs(r_y - matrix.vals[1][0]) > tolerance ||
617       fabs(r_z - matrix.vals[2][0]) > tolerance) {
618     return false;
619   }
620 
621   Fixed g_x_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(green_tag))[2]);
622   Fixed g_y_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(green_tag))[3]);
623   Fixed g_z_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(green_tag))[4]);
624   float g_x = FixedToFloat(g_x_fixed);
625   float g_y = FixedToFloat(g_y_fixed);
626   float g_z = FixedToFloat(g_z_fixed);
627   if (fabs(g_x - matrix.vals[0][1]) > tolerance || fabs(g_y - matrix.vals[1][1]) > tolerance ||
628       fabs(g_z - matrix.vals[2][1]) > tolerance) {
629     return false;
630   }
631 
632   Fixed b_x_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(blue_tag))[2]);
633   Fixed b_y_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(blue_tag))[3]);
634   Fixed b_z_fixed = Endian_SwapBE32(reinterpret_cast<int32_t*>(const_cast<uint8_t*>(blue_tag))[4]);
635   float b_x = FixedToFloat(b_x_fixed);
636   float b_y = FixedToFloat(b_y_fixed);
637   float b_z = FixedToFloat(b_z_fixed);
638   if (fabs(b_x - matrix.vals[0][2]) > tolerance || fabs(b_y - matrix.vals[1][2]) > tolerance ||
639       fabs(b_z - matrix.vals[2][2]) > tolerance) {
640     return false;
641   }
642 
643   return true;
644 }
645 
readIccColorGamut(void * icc_data,size_t icc_size)646 uhdr_color_gamut_t IccHelper::readIccColorGamut(void* icc_data, size_t icc_size) {
647   // Each tag table entry consists of 3 fields of 4 bytes each.
648   static const size_t kTagTableEntrySize = 12;
649 
650   if (icc_data == nullptr || icc_size < sizeof(ICCHeader) + kICCIdentifierSize) {
651     return UHDR_CG_UNSPECIFIED;
652   }
653 
654   if (memcmp(icc_data, kICCIdentifier, sizeof(kICCIdentifier)) != 0) {
655     return UHDR_CG_UNSPECIFIED;
656   }
657 
658   uint8_t* icc_bytes = reinterpret_cast<uint8_t*>(icc_data) + kICCIdentifierSize;
659   auto alignment_needs = alignof(ICCHeader);
660   uint8_t* aligned_block = nullptr;
661   if (((uintptr_t)icc_bytes) % alignment_needs != 0) {
662     aligned_block = static_cast<uint8_t*>(
663         ::operator new[](icc_size - kICCIdentifierSize, std::align_val_t(alignment_needs)));
664     if (!aligned_block) {
665       ALOGE("unable allocate memory, icc parsing failed");
666       return UHDR_CG_UNSPECIFIED;
667     }
668     std::memcpy(aligned_block, icc_bytes, icc_size - kICCIdentifierSize);
669     icc_bytes = aligned_block;
670   }
671   ICCHeader* header = reinterpret_cast<ICCHeader*>(icc_bytes);
672 
673   // Use 0 to indicate not found, since offsets are always relative to start
674   // of ICC data and therefore a tag offset of zero would never be valid.
675   size_t red_primary_offset = 0, green_primary_offset = 0, blue_primary_offset = 0;
676   size_t red_primary_size = 0, green_primary_size = 0, blue_primary_size = 0;
677   size_t cicp_size = 0, cicp_offset = 0;
678   for (size_t tag_idx = 0; tag_idx < Endian_SwapBE32(header->tag_count); ++tag_idx) {
679     if (icc_size < kICCIdentifierSize + sizeof(ICCHeader) + ((tag_idx + 1) * kTagTableEntrySize)) {
680       ALOGE(
681           "Insufficient buffer size during icc parsing. tag index %zu, header %zu, tag size %zu, "
682           "icc size %zu",
683           tag_idx, kICCIdentifierSize + sizeof(ICCHeader), kTagTableEntrySize, icc_size);
684       if (aligned_block) ::operator delete[](aligned_block, std::align_val_t(alignment_needs));
685       return UHDR_CG_UNSPECIFIED;
686     }
687     uint32_t* tag_entry_start =
688         reinterpret_cast<uint32_t*>(icc_bytes + sizeof(ICCHeader) + tag_idx * kTagTableEntrySize);
689     // first 4 bytes are the tag signature, next 4 bytes are the tag offset,
690     // last 4 bytes are the tag length in bytes.
691     if (red_primary_offset == 0 && *tag_entry_start == Endian_SwapBE32(kTAG_rXYZ)) {
692       red_primary_offset = Endian_SwapBE32(*(tag_entry_start + 1));
693       red_primary_size = Endian_SwapBE32(*(tag_entry_start + 2));
694     } else if (green_primary_offset == 0 && *tag_entry_start == Endian_SwapBE32(kTAG_gXYZ)) {
695       green_primary_offset = Endian_SwapBE32(*(tag_entry_start + 1));
696       green_primary_size = Endian_SwapBE32(*(tag_entry_start + 2));
697     } else if (blue_primary_offset == 0 && *tag_entry_start == Endian_SwapBE32(kTAG_bXYZ)) {
698       blue_primary_offset = Endian_SwapBE32(*(tag_entry_start + 1));
699       blue_primary_size = Endian_SwapBE32(*(tag_entry_start + 2));
700     } else if (cicp_offset == 0 && *tag_entry_start == Endian_SwapBE32(kTAG_cicp)) {
701       cicp_offset = Endian_SwapBE32(*(tag_entry_start + 1));
702       cicp_size = Endian_SwapBE32(*(tag_entry_start + 2));
703     }
704   }
705 
706   if (cicp_offset != 0 && cicp_size == kCicpTagSize &&
707       kICCIdentifierSize + cicp_offset + cicp_size <= icc_size) {
708     uint8_t* cicp = icc_bytes + cicp_offset;
709     uint8_t primaries = cicp[8];
710     uhdr_color_gamut_t gamut = UHDR_CG_UNSPECIFIED;
711     if (primaries == kCICPPrimariesSRGB) {
712       gamut = UHDR_CG_BT_709;
713     } else if (primaries == kCICPPrimariesP3) {
714       gamut = UHDR_CG_DISPLAY_P3;
715     } else if (primaries == kCICPPrimariesRec2020) {
716       gamut = UHDR_CG_BT_2100;
717     }
718     if (gamut != UHDR_CG_UNSPECIFIED) {
719       if (aligned_block) ::operator delete[](aligned_block, std::align_val_t(alignment_needs));
720       return gamut;
721     }
722   }
723 
724   if (red_primary_offset == 0 || red_primary_size != kColorantTagSize ||
725       kICCIdentifierSize + red_primary_offset + red_primary_size > icc_size ||
726       green_primary_offset == 0 || green_primary_size != kColorantTagSize ||
727       kICCIdentifierSize + green_primary_offset + green_primary_size > icc_size ||
728       blue_primary_offset == 0 || blue_primary_size != kColorantTagSize ||
729       kICCIdentifierSize + blue_primary_offset + blue_primary_size > icc_size) {
730     if (aligned_block) ::operator delete[](aligned_block, std::align_val_t(alignment_needs));
731     return UHDR_CG_UNSPECIFIED;
732   }
733 
734   uint8_t* red_tag = icc_bytes + red_primary_offset;
735   uint8_t* green_tag = icc_bytes + green_primary_offset;
736   uint8_t* blue_tag = icc_bytes + blue_primary_offset;
737 
738   // Serialize tags as we do on encode and compare what we find to that to
739   // determine the gamut (since we don't have a need yet for full deserialize).
740   uhdr_color_gamut_t gamut = UHDR_CG_UNSPECIFIED;
741   if (tagsEqualToMatrix(kSRGB, red_tag, green_tag, blue_tag)) {
742     gamut = UHDR_CG_BT_709;
743   } else if (tagsEqualToMatrix(kDisplayP3, red_tag, green_tag, blue_tag)) {
744     gamut = UHDR_CG_DISPLAY_P3;
745   } else if (tagsEqualToMatrix(kRec2020, red_tag, green_tag, blue_tag)) {
746     gamut = UHDR_CG_BT_2100;
747   }
748 
749   if (aligned_block) ::operator delete[](aligned_block, std::align_val_t(alignment_needs));
750   // Didn't find a match to one of the profiles we write; indicate the gamut
751   // is unspecified since we don't understand it.
752   return gamut;
753 }
754 
755 }  // namespace ultrahdr
756