Coverage Report

Created: 2025-07-11 06:50

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