Coverage Report

Created: 2026-06-16 07:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libjxl/lib/jxl/cms/jxl_cms.cc
Line
Count
Source
1
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
2
//
3
// Use of this source code is governed by a BSD-style
4
// license that can be found in the LICENSE file.
5
6
#include <jxl/cms.h>
7
8
#ifndef JPEGXL_ENABLE_SKCMS
9
#define JPEGXL_ENABLE_SKCMS 0
10
#endif
11
12
#include <jxl/cms_interface.h>
13
#include <jxl/color_encoding.h>
14
#include <jxl/types.h>
15
16
#include <algorithm>
17
#include <array>
18
#include <cmath>
19
#include <cstddef>
20
#include <cstdint>
21
#include <cstring>
22
#include <memory>
23
#include <utility>
24
#include <vector>
25
26
#undef HWY_TARGET_INCLUDE
27
#define HWY_TARGET_INCLUDE "lib/jxl/cms/jxl_cms.cc"
28
#include <hwy/foreach_target.h>
29
#include <hwy/highway.h>
30
31
#include "lib/jxl/base/common.h"
32
#include "lib/jxl/base/compiler_specific.h"
33
#include "lib/jxl/base/matrix_ops.h"
34
#include "lib/jxl/base/printf_macros.h"
35
#include "lib/jxl/base/status.h"
36
#include "lib/jxl/cms/color_encoding_cms.h"
37
#include "lib/jxl/cms/jxl_cms_internal.h"
38
#include "lib/jxl/cms/transfer_functions-inl.h"
39
#include "lib/jxl/color_encoding_internal.h"
40
#if JPEGXL_ENABLE_SKCMS
41
#include "skcms.h"
42
#else  // JPEGXL_ENABLE_SKCMS
43
#include "lcms2.h"
44
#include "lcms2_plugin.h"
45
#include "lib/jxl/base/span.h"
46
#endif  // JPEGXL_ENABLE_SKCMS
47
48
#define JXL_CMS_VERBOSE 0
49
50
// Define these only once. We can't use HWY_ONCE here because it is defined as
51
// 1 only on the last pass.
52
#ifndef LIB_JXL_JXL_CMS_CC
53
#define LIB_JXL_JXL_CMS_CC
54
55
namespace jxl {
56
namespace {
57
58
using ::jxl::cms::ColorEncoding;
59
60
struct JxlCms {
61
#if JPEGXL_ENABLE_SKCMS
62
  IccBytes icc_src, icc_dst;
63
  skcms_ICCProfile profile_src, profile_dst;
64
#else
65
  void* lcms_transform;
66
#endif
67
68
  // These fields are used when the HLG OOTF or inverse OOTF must be applied.
69
  bool apply_hlg_ootf;
70
  size_t hlg_ootf_num_channels;
71
  // Y component of the primaries.
72
  std::array<float, 3> hlg_ootf_luminances;
73
74
  size_t channels_src;
75
  size_t channels_dst;
76
77
  std::vector<float> src_storage;
78
  std::vector<float*> buf_src;
79
  std::vector<float> dst_storage;
80
  std::vector<float*> buf_dst;
81
82
  float intensity_target;
83
  bool skip_lcms = false;
84
  ExtraTF preprocess = ExtraTF::kNone;
85
  ExtraTF postprocess = ExtraTF::kNone;
86
};
87
88
Status ApplyHlgOotf(JxlCms* t, float* JXL_RESTRICT buf, size_t xsize,
89
                    bool forward);
90
}  // namespace
91
}  // namespace jxl
92
93
#endif  // LIB_JXL_JXL_CMS_CC
94
95
HWY_BEFORE_NAMESPACE();
96
namespace jxl {
97
namespace HWY_NAMESPACE {
98
99
#if JXL_CMS_VERBOSE >= 2
100
const size_t kX = 0;  // pixel index, multiplied by 3 for RGB
101
#endif
102
103
// xform_src = UndoGammaCompression(buf_src).
104
Status BeforeTransform(JxlCms* t, const float* buf_src, float* xform_src,
105
0
                       size_t buf_size) {
106
0
  switch (t->preprocess) {
107
0
    case ExtraTF::kNone:
108
0
      JXL_ENSURE(false);  // unreachable
109
0
      break;
110
111
0
    case ExtraTF::kPQ: {
112
0
      HWY_FULL(float) df;
113
0
      TF_PQ tf_pq(t->intensity_target);
114
0
      for (size_t i = 0; i < buf_size; i += Lanes(df)) {
115
0
        const auto val = Load(df, buf_src + i);
116
0
        const auto result = tf_pq.DisplayFromEncoded(df, val);
117
0
        Store(result, df, xform_src + i);
118
0
      }
119
#if JXL_CMS_VERBOSE >= 2
120
      printf("pre in %.4f %.4f %.4f undoPQ %.4f %.4f %.4f\n", buf_src[3 * kX],
121
             buf_src[3 * kX + 1], buf_src[3 * kX + 2], xform_src[3 * kX],
122
             xform_src[3 * kX + 1], xform_src[3 * kX + 2]);
123
#endif
124
0
      break;
125
0
    }
126
127
0
    case ExtraTF::kHLG:
128
0
      for (size_t i = 0; i < buf_size; ++i) {
129
0
        xform_src[i] = static_cast<float>(
130
0
            TF_HLG_Base::DisplayFromEncoded(static_cast<double>(buf_src[i])));
131
0
      }
132
0
      if (t->apply_hlg_ootf) {
133
0
        JXL_RETURN_IF_ERROR(
134
0
            ApplyHlgOotf(t, xform_src, buf_size, /*forward=*/true));
135
0
      }
136
#if JXL_CMS_VERBOSE >= 2
137
      printf("pre in %.4f %.4f %.4f undoHLG %.4f %.4f %.4f\n", buf_src[3 * kX],
138
             buf_src[3 * kX + 1], buf_src[3 * kX + 2], xform_src[3 * kX],
139
             xform_src[3 * kX + 1], xform_src[3 * kX + 2]);
140
#endif
141
0
      break;
142
143
0
    case ExtraTF::kSRGB:
144
0
      HWY_FULL(float) df;
145
0
      for (size_t i = 0; i < buf_size; i += Lanes(df)) {
146
0
        const auto val = Load(df, buf_src + i);
147
0
        const auto result = TF_SRGB().DisplayFromEncoded(val);
148
0
        Store(result, df, xform_src + i);
149
0
      }
150
#if JXL_CMS_VERBOSE >= 2
151
      printf("pre in %.4f %.4f %.4f undoSRGB %.4f %.4f %.4f\n", buf_src[3 * kX],
152
             buf_src[3 * kX + 1], buf_src[3 * kX + 2], xform_src[3 * kX],
153
             xform_src[3 * kX + 1], xform_src[3 * kX + 2]);
154
#endif
155
0
      break;
156
0
  }
157
0
  return true;
158
0
}
Unexecuted instantiation: jxl_cms.cc:jxl::N_SSE4::BeforeTransform(jxl::(anonymous namespace)::JxlCms*, float const*, float*, unsigned long)
Unexecuted instantiation: jxl_cms.cc:jxl::N_AVX2::BeforeTransform(jxl::(anonymous namespace)::JxlCms*, float const*, float*, unsigned long)
Unexecuted instantiation: jxl_cms.cc:jxl::N_AVX3::BeforeTransform(jxl::(anonymous namespace)::JxlCms*, float const*, float*, unsigned long)
Unexecuted instantiation: jxl_cms.cc:jxl::N_AVX3_ZEN4::BeforeTransform(jxl::(anonymous namespace)::JxlCms*, float const*, float*, unsigned long)
Unexecuted instantiation: jxl_cms.cc:jxl::N_AVX3_SPR::BeforeTransform(jxl::(anonymous namespace)::JxlCms*, float const*, float*, unsigned long)
Unexecuted instantiation: jxl_cms.cc:jxl::N_SSE2::BeforeTransform(jxl::(anonymous namespace)::JxlCms*, float const*, float*, unsigned long)
159
160
// Applies gamma compression in-place.
161
0
Status AfterTransform(JxlCms* t, float* JXL_RESTRICT buf_dst, size_t buf_size) {
162
0
  switch (t->postprocess) {
163
0
    case ExtraTF::kNone:
164
0
      JXL_DEBUG_ABORT("Unreachable");
165
0
      break;
166
0
    case ExtraTF::kPQ: {
167
0
      HWY_FULL(float) df;
168
0
      TF_PQ tf_pq(t->intensity_target);
169
0
      for (size_t i = 0; i < buf_size; i += Lanes(df)) {
170
0
        const auto val = Load(df, buf_dst + i);
171
0
        const auto result = tf_pq.EncodedFromDisplay(df, val);
172
0
        Store(result, df, buf_dst + i);
173
0
      }
174
#if JXL_CMS_VERBOSE >= 2
175
      printf("after PQ enc %.4f %.4f %.4f\n", buf_dst[3 * kX],
176
             buf_dst[3 * kX + 1], buf_dst[3 * kX + 2]);
177
#endif
178
0
      break;
179
0
    }
180
0
    case ExtraTF::kHLG:
181
0
      if (t->apply_hlg_ootf) {
182
0
        JXL_RETURN_IF_ERROR(
183
0
            ApplyHlgOotf(t, buf_dst, buf_size, /*forward=*/false));
184
0
      }
185
0
      for (size_t i = 0; i < buf_size; ++i) {
186
0
        buf_dst[i] = static_cast<float>(
187
0
            TF_HLG_Base::EncodedFromDisplay(static_cast<double>(buf_dst[i])));
188
0
      }
189
#if JXL_CMS_VERBOSE >= 2
190
      printf("after HLG enc %.4f %.4f %.4f\n", buf_dst[3 * kX],
191
             buf_dst[3 * kX + 1], buf_dst[3 * kX + 2]);
192
#endif
193
0
      break;
194
0
    case ExtraTF::kSRGB:
195
0
      HWY_FULL(float) df;
196
0
      for (size_t i = 0; i < buf_size; i += Lanes(df)) {
197
0
        const auto val = Load(df, buf_dst + i);
198
0
        const auto result = TF_SRGB().EncodedFromDisplay(df, val);
199
0
        Store(result, df, buf_dst + i);
200
0
      }
201
#if JXL_CMS_VERBOSE >= 2
202
      printf("after SRGB enc %.4f %.4f %.4f\n", buf_dst[3 * kX],
203
             buf_dst[3 * kX + 1], buf_dst[3 * kX + 2]);
204
#endif
205
0
      break;
206
0
  }
207
0
  return true;
208
0
}
Unexecuted instantiation: jxl_cms.cc:jxl::N_SSE4::AfterTransform(jxl::(anonymous namespace)::JxlCms*, float*, unsigned long)
Unexecuted instantiation: jxl_cms.cc:jxl::N_AVX2::AfterTransform(jxl::(anonymous namespace)::JxlCms*, float*, unsigned long)
Unexecuted instantiation: jxl_cms.cc:jxl::N_AVX3::AfterTransform(jxl::(anonymous namespace)::JxlCms*, float*, unsigned long)
Unexecuted instantiation: jxl_cms.cc:jxl::N_AVX3_ZEN4::AfterTransform(jxl::(anonymous namespace)::JxlCms*, float*, unsigned long)
Unexecuted instantiation: jxl_cms.cc:jxl::N_AVX3_SPR::AfterTransform(jxl::(anonymous namespace)::JxlCms*, float*, unsigned long)
Unexecuted instantiation: jxl_cms.cc:jxl::N_SSE2::AfterTransform(jxl::(anonymous namespace)::JxlCms*, float*, unsigned long)
209
210
Status DoColorSpaceTransform(void* cms_data, const size_t thread,
211
                             const float* buf_src, float* buf_dst,
212
0
                             size_t xsize) {
213
  // No lock needed.
214
0
  JxlCms* t = reinterpret_cast<JxlCms*>(cms_data);
215
216
0
  const float* xform_src = buf_src;  // Read-only.
217
0
  if (t->preprocess != ExtraTF::kNone) {
218
0
    float* mutable_xform_src = t->buf_src[thread];  // Writable buffer.
219
0
    JXL_RETURN_IF_ERROR(BeforeTransform(t, buf_src, mutable_xform_src,
220
0
                                        xsize * t->channels_src));
221
0
    xform_src = mutable_xform_src;
222
0
  }
223
224
#if JPEGXL_ENABLE_SKCMS
225
  if (t->channels_src == 1 && !t->skip_lcms) {
226
    // Expand from 1 to 3 channels, starting from the end in case
227
    // xform_src == t->buf_src[thread].
228
    float* mutable_xform_src = t->buf_src[thread];
229
    for (size_t i = 0; i < xsize; ++i) {
230
      const size_t x = xsize - i - 1;
231
      mutable_xform_src[x * 3] = mutable_xform_src[x * 3 + 1] =
232
          mutable_xform_src[x * 3 + 2] = xform_src[x];
233
    }
234
    xform_src = mutable_xform_src;
235
  }
236
#else
237
0
  if (t->channels_src == 4 && !t->skip_lcms) {
238
    // LCMS does CMYK in a weird way: 0 = white, 100 = max ink
239
0
    float* mutable_xform_src = t->buf_src[thread];
240
0
    for (size_t x = 0; x < xsize * 4; ++x) {
241
0
      mutable_xform_src[x] = 100.f - 100.f * mutable_xform_src[x];
242
0
    }
243
0
    xform_src = mutable_xform_src;
244
0
  }
245
0
#endif
246
247
#if JXL_CMS_VERBOSE >= 2
248
  // Save inputs for printing before in-place transforms overwrite them.
249
  const float in0 = xform_src[3 * kX + 0];
250
  const float in1 = xform_src[3 * kX + 1];
251
  const float in2 = xform_src[3 * kX + 2];
252
#endif
253
254
0
  if (t->skip_lcms) {
255
0
    if (buf_dst != xform_src) {
256
0
      memcpy(buf_dst, xform_src, xsize * t->channels_src * sizeof(*buf_dst));
257
0
    }  // else: in-place, no need to copy
258
0
  } else {
259
#if JPEGXL_ENABLE_SKCMS
260
    JXL_ENSURE(
261
        skcms_Transform(xform_src,
262
                        (t->channels_src == 4 ? skcms_PixelFormat_RGBA_ffff
263
                                              : skcms_PixelFormat_RGB_fff),
264
                        skcms_AlphaFormat_Opaque, &t->profile_src, buf_dst,
265
                        skcms_PixelFormat_RGB_fff, skcms_AlphaFormat_Opaque,
266
                        &t->profile_dst, xsize));
267
#else   // JPEGXL_ENABLE_SKCMS
268
0
    cmsDoTransform(t->lcms_transform, xform_src, buf_dst,
269
0
                   static_cast<cmsUInt32Number>(xsize));
270
0
#endif  // JPEGXL_ENABLE_SKCMS
271
0
  }
272
#if JXL_CMS_VERBOSE >= 2
273
  printf("xform skip%d: %.4f %.4f %.4f (%p) -> (%p) %.4f %.4f %.4f\n",
274
         t->skip_lcms, in0, in1, in2, xform_src, buf_dst, buf_dst[3 * kX],
275
         buf_dst[3 * kX + 1], buf_dst[3 * kX + 2]);
276
#endif
277
278
#if JPEGXL_ENABLE_SKCMS
279
  if (t->channels_dst == 1 && !t->skip_lcms) {
280
    // Contract back from 3 to 1 channel, this time forward.
281
    float* grayscale_buf_dst = t->buf_dst[thread];
282
    for (size_t x = 0; x < xsize; ++x) {
283
      grayscale_buf_dst[x] = buf_dst[x * 3];
284
    }
285
    buf_dst = grayscale_buf_dst;
286
  }
287
#endif
288
289
0
  if (t->postprocess != ExtraTF::kNone) {
290
0
    JXL_RETURN_IF_ERROR(AfterTransform(t, buf_dst, xsize * t->channels_dst));
291
0
  }
292
0
  return true;
293
0
}
Unexecuted instantiation: jxl::N_SSE4::DoColorSpaceTransform(void*, unsigned long, float const*, float*, unsigned long)
Unexecuted instantiation: jxl::N_AVX2::DoColorSpaceTransform(void*, unsigned long, float const*, float*, unsigned long)
Unexecuted instantiation: jxl::N_AVX3::DoColorSpaceTransform(void*, unsigned long, float const*, float*, unsigned long)
Unexecuted instantiation: jxl::N_AVX3_ZEN4::DoColorSpaceTransform(void*, unsigned long, float const*, float*, unsigned long)
Unexecuted instantiation: jxl::N_AVX3_SPR::DoColorSpaceTransform(void*, unsigned long, float const*, float*, unsigned long)
Unexecuted instantiation: jxl::N_SSE2::DoColorSpaceTransform(void*, unsigned long, float const*, float*, unsigned long)
294
295
// NOLINTNEXTLINE(google-readability-namespace-comments)
296
}  // namespace HWY_NAMESPACE
297
}  // namespace jxl
298
HWY_AFTER_NAMESPACE();
299
300
#if HWY_ONCE
301
namespace jxl {
302
namespace {
303
304
HWY_EXPORT(DoColorSpaceTransform);
305
int DoColorSpaceTransform(void* t, size_t thread, const float* buf_src,
306
0
                          float* buf_dst, size_t xsize) {
307
0
  return HWY_DYNAMIC_DISPATCH(DoColorSpaceTransform)(t, thread, buf_src,
308
0
                                                     buf_dst, xsize);
309
0
}
310
311
// Define to 1 on OS X as a workaround for older LCMS lacking MD5.
312
#define JXL_CMS_OLD_VERSION 0
313
314
#if JPEGXL_ENABLE_SKCMS
315
316
JXL_MUST_USE_RESULT CIExy CIExyFromXYZ(const Color& XYZ) {
317
  const double factor = 1.0 / static_cast<double>(XYZ[0] + XYZ[1] + XYZ[2]);
318
  CIExy xy;
319
  xy.x = XYZ[0] * factor;
320
  xy.y = XYZ[1] * factor;
321
  return xy;
322
}
323
324
#else  // JPEGXL_ENABLE_SKCMS
325
// (LCMS interface requires xyY but we omit the Y for white points/primaries.)
326
327
0
JXL_MUST_USE_RESULT CIExy CIExyFromxyY(const cmsCIExyY& xyY) {
328
0
  CIExy xy;
329
0
  xy.x = xyY.x;
330
0
  xy.y = xyY.y;
331
0
  return xy;
332
0
}
333
334
0
JXL_MUST_USE_RESULT CIExy CIExyFromXYZ(const cmsCIEXYZ& XYZ) {
335
0
  cmsCIExyY xyY;
336
0
  cmsXYZ2xyY(/*Dest=*/&xyY, /*Source=*/&XYZ);
337
0
  return CIExyFromxyY(xyY);
338
0
}
339
340
0
JXL_MUST_USE_RESULT cmsCIEXYZ D50_XYZ() {
341
  // Quantized D50 as stored in ICC profiles.
342
0
  return {0.96420288, 1.0, 0.82490540};
343
0
}
344
345
// RAII
346
347
struct ContextDeleter {
348
0
  void operator()(void* p) { cmsDeleteContext(static_cast<cmsContext>(p)); }
349
};
350
using Context = std::unique_ptr<void, ContextDeleter>;
351
352
struct ProfileDeleter {
353
0
  void operator()(void* p) { cmsCloseProfile(p); }
354
};
355
using Profile = std::unique_ptr<void, ProfileDeleter>;
356
357
struct TransformDeleter {
358
0
  void operator()(void* p) { cmsDeleteTransform(p); }
359
};
360
using Transform = std::unique_ptr<void, TransformDeleter>;
361
362
struct CurveDeleter {
363
0
  void operator()(cmsToneCurve* p) { cmsFreeToneCurve(p); }
364
};
365
using Curve = std::unique_ptr<cmsToneCurve, CurveDeleter>;
366
367
Status CreateProfileXYZ(const cmsContext context,
368
0
                        Profile* JXL_RESTRICT profile) {
369
0
  profile->reset(cmsCreateXYZProfileTHR(context));
370
0
  if (profile->get() == nullptr) return JXL_FAILURE("Failed to create XYZ");
371
0
  return true;
372
0
}
373
374
#endif  // !JPEGXL_ENABLE_SKCMS
375
376
#if JPEGXL_ENABLE_SKCMS
377
// IMPORTANT: icc must outlive profile.
378
Status DecodeProfile(const uint8_t* icc, size_t size,
379
                     skcms_ICCProfile* const profile) {
380
  if (!skcms_Parse(icc, size, profile)) {
381
    return JXL_FAILURE("Failed to parse ICC profile with %" PRIuS " bytes",
382
                       size);
383
  }
384
  return true;
385
}
386
#else   // JPEGXL_ENABLE_SKCMS
387
Status DecodeProfile(const cmsContext context, Span<const uint8_t> icc,
388
0
                     Profile* profile) {
389
0
  profile->reset(cmsOpenProfileFromMemTHR(context, icc.data(), icc.size()));
390
0
  if (profile->get() == nullptr) {
391
0
    return JXL_FAILURE("Failed to decode profile");
392
0
  }
393
394
  // WARNING: due to the LCMS MD5 issue mentioned above, many existing
395
  // profiles have incorrect MD5, so do not even bother checking them nor
396
  // generating warning clutter.
397
398
0
  return true;
399
0
}
400
#endif  // JPEGXL_ENABLE_SKCMS
401
402
#if JPEGXL_ENABLE_SKCMS
403
404
ColorSpace ColorSpaceFromProfile(const skcms_ICCProfile& profile) {
405
  switch (profile.data_color_space) {
406
    case skcms_Signature_RGB:
407
    case skcms_Signature_CMYK:
408
      // spec says CMYK is encoded as RGB (the kBlack extra channel signals that
409
      // it is actually CMYK)
410
      return ColorSpace::kRGB;
411
    case skcms_Signature_Gray:
412
      return ColorSpace::kGray;
413
    default:
414
      return ColorSpace::kUnknown;
415
  }
416
}
417
418
// vector_out := matmul(matrix, vector_in)
419
void MatrixProduct(const skcms_Matrix3x3& matrix, const Color& vector_in,
420
                   Color& vector_out) {
421
  for (int i = 0; i < 3; ++i) {
422
    vector_out[i] = 0;
423
    for (int j = 0; j < 3; ++j) {
424
      vector_out[i] += matrix.vals[i][j] * vector_in[j];
425
    }
426
  }
427
}
428
429
// Returns white point that was specified when creating the profile.
430
JXL_MUST_USE_RESULT Status UnadaptedWhitePoint(const skcms_ICCProfile& profile,
431
                                               CIExy* out) {
432
  Color media_white_point_XYZ;
433
  if (!skcms_GetWTPT(&profile, media_white_point_XYZ.data())) {
434
    return JXL_FAILURE("ICC profile does not contain WhitePoint tag");
435
  }
436
  skcms_Matrix3x3 CHAD;
437
  if (!skcms_GetCHAD(&profile, &CHAD)) {
438
    // If there is no chromatic adaptation matrix, it means that the white point
439
    // is already unadapted.
440
    *out = CIExyFromXYZ(media_white_point_XYZ);
441
    return true;
442
  }
443
  // Otherwise, it has been adapted to the PCS white point using said matrix,
444
  // and the adaptation needs to be undone.
445
  skcms_Matrix3x3 inverse_CHAD;
446
  if (!skcms_Matrix3x3_invert(&CHAD, &inverse_CHAD)) {
447
    return JXL_FAILURE("Non-invertible ChromaticAdaptation matrix");
448
  }
449
  Color unadapted_white_point_XYZ;
450
  MatrixProduct(inverse_CHAD, media_white_point_XYZ, unadapted_white_point_XYZ);
451
  *out = CIExyFromXYZ(unadapted_white_point_XYZ);
452
  return true;
453
}
454
455
Status IdentifyPrimaries(const skcms_ICCProfile& profile,
456
                         const CIExy& wp_unadapted, ColorEncoding* c) {
457
  if (!c->HasPrimaries()) return true;
458
459
  skcms_Matrix3x3 CHAD;
460
  skcms_Matrix3x3 inverse_CHAD;
461
  if (skcms_GetCHAD(&profile, &CHAD)) {
462
    JXL_RETURN_IF_ERROR(skcms_Matrix3x3_invert(&CHAD, &inverse_CHAD));
463
  } else {
464
    static constexpr skcms_Matrix3x3 kLMSFromXYZ = {
465
        {{0.8951, 0.2664, -0.1614},
466
         {-0.7502, 1.7135, 0.0367},
467
         {0.0389, -0.0685, 1.0296}}};
468
    static constexpr skcms_Matrix3x3 kXYZFromLMS = {
469
        {{0.9869929, -0.1470543, 0.1599627},
470
         {0.4323053, 0.5183603, 0.0492912},
471
         {-0.0085287, 0.0400428, 0.9684867}}};
472
    static constexpr Color kWpD50XYZ{0.96420288, 1.0, 0.82490540};
473
    Color wp_unadapted_XYZ;
474
    JXL_RETURN_IF_ERROR(
475
        CIEXYZFromWhiteCIExy(wp_unadapted.x, wp_unadapted.y, wp_unadapted_XYZ));
476
    Color wp_D50_LMS;
477
    Color wp_unadapted_LMS;
478
    MatrixProduct(kLMSFromXYZ, kWpD50XYZ, wp_D50_LMS);
479
    MatrixProduct(kLMSFromXYZ, wp_unadapted_XYZ, wp_unadapted_LMS);
480
    inverse_CHAD = {{{wp_unadapted_LMS[0] / wp_D50_LMS[0], 0, 0},
481
                     {0, wp_unadapted_LMS[1] / wp_D50_LMS[1], 0},
482
                     {0, 0, wp_unadapted_LMS[2] / wp_D50_LMS[2]}}};
483
    inverse_CHAD = skcms_Matrix3x3_concat(&kXYZFromLMS, &inverse_CHAD);
484
    inverse_CHAD = skcms_Matrix3x3_concat(&inverse_CHAD, &kLMSFromXYZ);
485
  }
486
487
  Color XYZ;
488
  PrimariesCIExy primaries;
489
  CIExy* const chromaticities[] = {&primaries.r, &primaries.g, &primaries.b};
490
  for (int i = 0; i < 3; ++i) {
491
    float RGB[3] = {};
492
    RGB[i] = 1;
493
    skcms_Transform(RGB, skcms_PixelFormat_RGB_fff, skcms_AlphaFormat_Opaque,
494
                    &profile, XYZ.data(), skcms_PixelFormat_RGB_fff,
495
                    skcms_AlphaFormat_Opaque, skcms_XYZD50_profile(), 1);
496
    Color unadapted_XYZ;
497
    MatrixProduct(inverse_CHAD, XYZ, unadapted_XYZ);
498
    *chromaticities[i] = CIExyFromXYZ(unadapted_XYZ);
499
  }
500
  return c->SetPrimaries(primaries);
501
}
502
503
bool IsApproximatelyEqual(const skcms_ICCProfile& profile,
504
                          const ColorEncoding& JXL_RESTRICT c) {
505
  IccBytes bytes;
506
  if (!MaybeCreateProfile(c.ToExternal(), &bytes)) {
507
    return false;
508
  }
509
510
  skcms_ICCProfile profile_test;
511
  if (!DecodeProfile(bytes.data(), bytes.size(), &profile_test)) {
512
    return false;
513
  }
514
515
  if (!skcms_ApproximatelyEqualProfiles(&profile_test, &profile)) {
516
    return false;
517
  }
518
519
  return true;
520
}
521
522
Status DetectTransferFunction(const skcms_ICCProfile& profile,
523
                              ColorEncoding* JXL_RESTRICT c) {
524
  JXL_ENSURE(c->color_space != ColorSpace::kXYB);
525
526
  float gamma[3] = {};
527
  if (profile.has_trc) {
528
    const auto IsGamma = [](const skcms_TransferFunction& tf) {
529
      return tf.a == 1 && tf.b == 0 &&
530
             /* if b and d are zero, it is fine for c not to be */ tf.d == 0 &&
531
             tf.e == 0 && tf.f == 0;
532
    };
533
    for (int i = 0; i < 3; ++i) {
534
      if (profile.trc[i].table_entries == 0 &&
535
          IsGamma(profile.trc->parametric)) {
536
        gamma[i] = 1.f / profile.trc->parametric.g;
537
      } else {
538
        skcms_TransferFunction approximate_tf;
539
        float max_error;
540
        if (skcms_ApproximateCurve(&profile.trc[i], &approximate_tf,
541
                                   &max_error)) {
542
          if (IsGamma(approximate_tf)) {
543
            gamma[i] = 1.f / approximate_tf.g;
544
          }
545
        }
546
      }
547
    }
548
  }
549
  if (gamma[0] != 0 && std::abs(gamma[0] - gamma[1]) < 1e-4f &&
550
      std::abs(gamma[1] - gamma[2]) < 1e-4f) {
551
    if (c->tf.SetGamma(gamma[0])) {
552
      if (IsApproximatelyEqual(profile, *c)) return true;
553
    }
554
  }
555
556
  for (TransferFunction tf : Values<TransferFunction>()) {
557
    // Can only create profile from known transfer function.
558
    if (tf == TransferFunction::kUnknown) continue;
559
    c->tf.SetTransferFunction(tf);
560
    if (IsApproximatelyEqual(profile, *c)) return true;
561
  }
562
563
  c->tf.SetTransferFunction(TransferFunction::kUnknown);
564
  return true;
565
}
566
567
#else  // JPEGXL_ENABLE_SKCMS
568
569
0
uint32_t Type32(const ColorEncoding& c, bool cmyk) {
570
0
  if (cmyk) return TYPE_CMYK_FLT;
571
0
  if (c.color_space == ColorSpace::kGray) return TYPE_GRAY_FLT;
572
0
  return TYPE_RGB_FLT;
573
0
}
574
575
0
uint32_t Type64(const ColorEncoding& c) {
576
0
  if (c.color_space == ColorSpace::kGray) return TYPE_GRAY_DBL;
577
0
  return TYPE_RGB_DBL;
578
0
}
579
580
0
ColorSpace ColorSpaceFromProfile(const Profile& profile) {
581
0
  switch (cmsGetColorSpace(profile.get())) {
582
0
    case cmsSigRgbData:
583
0
    case cmsSigCmykData:
584
0
      return ColorSpace::kRGB;
585
0
    case cmsSigGrayData:
586
0
      return ColorSpace::kGray;
587
0
    default:
588
0
      return ColorSpace::kUnknown;
589
0
  }
590
0
}
591
592
// "profile1" is pre-decoded to save time in DetectTransferFunction.
593
Status ProfileEquivalentToICC(const cmsContext context, const Profile& profile1,
594
0
                              const IccBytes& icc, const ColorEncoding& c) {
595
0
  const uint32_t type_src = Type64(c);
596
597
0
  Profile profile2;
598
0
  JXL_RETURN_IF_ERROR(DecodeProfile(context, Bytes(icc), &profile2));
599
600
0
  Profile profile_xyz;
601
0
  JXL_RETURN_IF_ERROR(CreateProfileXYZ(context, &profile_xyz));
602
603
0
  const uint32_t intent = INTENT_RELATIVE_COLORIMETRIC;
604
0
  const uint32_t flags = cmsFLAGS_NOOPTIMIZE | cmsFLAGS_BLACKPOINTCOMPENSATION |
605
0
                         cmsFLAGS_HIGHRESPRECALC;
606
0
  Transform xform1(cmsCreateTransformTHR(context, profile1.get(), type_src,
607
0
                                         profile_xyz.get(), TYPE_XYZ_DBL,
608
0
                                         intent, flags));
609
0
  Transform xform2(cmsCreateTransformTHR(context, profile2.get(), type_src,
610
0
                                         profile_xyz.get(), TYPE_XYZ_DBL,
611
0
                                         intent, flags));
612
0
  if (xform1 == nullptr || xform2 == nullptr) {
613
0
    return JXL_FAILURE("Failed to create transform");
614
0
  }
615
616
0
  double in[3];
617
0
  double out1[3];
618
0
  double out2[3];
619
620
  // Uniformly spaced samples from very dark to almost fully bright.
621
0
  const double init = 1E-3;
622
0
  const double step = 0.2;
623
624
0
  if (c.color_space == ColorSpace::kGray) {
625
    // Finer sampling and replicate each component.
626
0
    for (in[0] = init; in[0] < 1.0; in[0] += step / 8) {
627
0
      cmsDoTransform(xform1.get(), in, out1, 1);
628
0
      cmsDoTransform(xform2.get(), in, out2, 1);
629
0
      if (!cms::ApproxEq(out1[0], out2[0], 2E-4)) {
630
0
        return false;
631
0
      }
632
0
    }
633
0
  } else {
634
0
    for (in[0] = init; in[0] < 1.0; in[0] += step) {
635
0
      for (in[1] = init; in[1] < 1.0; in[1] += step) {
636
0
        for (in[2] = init; in[2] < 1.0; in[2] += step) {
637
0
          cmsDoTransform(xform1.get(), in, out1, 1);
638
0
          cmsDoTransform(xform2.get(), in, out2, 1);
639
0
          for (size_t i = 0; i < 3; ++i) {
640
0
            if (!cms::ApproxEq(out1[i], out2[i], 2E-4)) {
641
0
              return false;
642
0
            }
643
0
          }
644
0
        }
645
0
      }
646
0
    }
647
0
  }
648
649
0
  return true;
650
0
}
651
652
// Returns white point that was specified when creating the profile.
653
// NOTE: we can't just use cmsSigMediaWhitePointTag because its interpretation
654
// differs between ICC versions.
655
JXL_MUST_USE_RESULT cmsCIEXYZ UnadaptedWhitePoint(const cmsContext context,
656
                                                  const Profile& profile,
657
0
                                                  const ColorEncoding& c) {
658
0
  const cmsCIEXYZ* white_point = static_cast<const cmsCIEXYZ*>(
659
0
      cmsReadTag(profile.get(), cmsSigMediaWhitePointTag));
660
0
  if (white_point != nullptr &&
661
0
      cmsReadTag(profile.get(), cmsSigChromaticAdaptationTag) == nullptr) {
662
    // No chromatic adaptation matrix: the white point is already unadapted.
663
0
    return *white_point;
664
0
  }
665
666
0
  cmsCIEXYZ XYZ = {1.0, 1.0, 1.0};
667
0
  Profile profile_xyz;
668
0
  if (!CreateProfileXYZ(context, &profile_xyz)) return XYZ;
669
  // Array arguments are one per profile.
670
0
  cmsHPROFILE profiles[2] = {profile.get(), profile_xyz.get()};
671
  // Leave white point unchanged - that is what we're trying to extract.
672
0
  cmsUInt32Number intents[2] = {INTENT_ABSOLUTE_COLORIMETRIC,
673
0
                                INTENT_ABSOLUTE_COLORIMETRIC};
674
0
  cmsBool black_compensation[2] = {0, 0};
675
0
  cmsFloat64Number adaption[2] = {0.0, 0.0};
676
  // Only transforming a single pixel, so skip expensive optimizations.
677
0
  cmsUInt32Number flags = cmsFLAGS_NOOPTIMIZE | cmsFLAGS_HIGHRESPRECALC;
678
0
  Transform xform(cmsCreateExtendedTransform(
679
0
      context, 2, profiles, black_compensation, intents, adaption, nullptr, 0,
680
0
      Type64(c), TYPE_XYZ_DBL, flags));
681
0
  if (!xform) return XYZ;  // TODO(lode): return error
682
683
  // xy are relative, so magnitude does not matter if we ignore output Y.
684
0
  const cmsFloat64Number in[3] = {1.0, 1.0, 1.0};
685
0
  cmsDoTransform(xform.get(), in, &XYZ.X, 1);
686
0
  return XYZ;
687
0
}
688
689
Status IdentifyPrimaries(const cmsContext context, const Profile& profile,
690
0
                         const cmsCIEXYZ& wp_unadapted, ColorEncoding* c) {
691
0
  if (!c->HasPrimaries()) return true;
692
0
  if (ColorSpaceFromProfile(profile) == ColorSpace::kUnknown) return true;
693
694
  // These were adapted to the profile illuminant before storing in the profile.
695
0
  const cmsCIEXYZ* adapted_r = static_cast<const cmsCIEXYZ*>(
696
0
      cmsReadTag(profile.get(), cmsSigRedColorantTag));
697
0
  const cmsCIEXYZ* adapted_g = static_cast<const cmsCIEXYZ*>(
698
0
      cmsReadTag(profile.get(), cmsSigGreenColorantTag));
699
0
  const cmsCIEXYZ* adapted_b = static_cast<const cmsCIEXYZ*>(
700
0
      cmsReadTag(profile.get(), cmsSigBlueColorantTag));
701
702
0
  cmsCIEXYZ converted_rgb[3];
703
0
  if (adapted_r == nullptr || adapted_g == nullptr || adapted_b == nullptr) {
704
    // No colorant tag, determine the XYZ coordinates of the primaries by
705
    // converting from the colorspace.
706
0
    Profile profile_xyz;
707
0
    if (!CreateProfileXYZ(context, &profile_xyz)) {
708
0
      return JXL_FAILURE("Failed to retrieve colorants");
709
0
    }
710
    // Array arguments are one per profile.
711
0
    cmsHPROFILE profiles[2] = {profile.get(), profile_xyz.get()};
712
0
    cmsUInt32Number intents[2] = {INTENT_RELATIVE_COLORIMETRIC,
713
0
                                  INTENT_RELATIVE_COLORIMETRIC};
714
0
    cmsBool black_compensation[2] = {0, 0};
715
0
    cmsFloat64Number adaption[2] = {0.0, 0.0};
716
    // Only transforming three pixels, so skip expensive optimizations.
717
0
    cmsUInt32Number flags = cmsFLAGS_NOOPTIMIZE | cmsFLAGS_HIGHRESPRECALC;
718
0
    Transform xform(cmsCreateExtendedTransform(
719
0
        context, 2, profiles, black_compensation, intents, adaption, nullptr, 0,
720
0
        Type64(*c), TYPE_XYZ_DBL, flags));
721
0
    if (!xform) return JXL_FAILURE("Failed to retrieve colorants");
722
723
0
    const cmsFloat64Number in[9] = {1.0, 0.0, 0.0, 0.0, 1.0,
724
0
                                    0.0, 0.0, 0.0, 1.0};
725
0
    cmsDoTransform(xform.get(), in, &converted_rgb->X, 3);
726
0
    adapted_r = &converted_rgb[0];
727
0
    adapted_g = &converted_rgb[1];
728
0
    adapted_b = &converted_rgb[2];
729
0
  }
730
731
  // TODO(janwas): no longer assume Bradford and D50.
732
  // Undo the chromatic adaptation.
733
0
  const cmsCIEXYZ d50 = D50_XYZ();
734
735
0
  cmsCIEXYZ r, g, b;
736
0
  cmsAdaptToIlluminant(&r, &d50, &wp_unadapted, adapted_r);
737
0
  cmsAdaptToIlluminant(&g, &d50, &wp_unadapted, adapted_g);
738
0
  cmsAdaptToIlluminant(&b, &d50, &wp_unadapted, adapted_b);
739
740
0
  const PrimariesCIExy rgb = {CIExyFromXYZ(r), CIExyFromXYZ(g),
741
0
                              CIExyFromXYZ(b)};
742
0
  return c->SetPrimaries(rgb);
743
0
}
744
745
Status DetectTransferFunction(const cmsContext context, const Profile& profile,
746
0
                              ColorEncoding* JXL_RESTRICT c) {
747
0
  JXL_ENSURE(c->color_space != ColorSpace::kXYB);
748
749
0
  float gamma = 0;
750
0
  if (const auto* gray_trc = reinterpret_cast<const cmsToneCurve*>(
751
0
          cmsReadTag(profile.get(), cmsSigGrayTRCTag))) {
752
0
    const double estimated_gamma =
753
0
        cmsEstimateGamma(gray_trc, /*precision=*/1e-4);
754
0
    if (estimated_gamma > 0) {
755
0
      gamma = 1. / estimated_gamma;
756
0
    }
757
0
  } else {
758
0
    float rgb_gamma[3] = {};
759
0
    int i = 0;
760
0
    for (const auto tag :
761
0
         {cmsSigRedTRCTag, cmsSigGreenTRCTag, cmsSigBlueTRCTag}) {
762
0
      if (const auto* trc = reinterpret_cast<const cmsToneCurve*>(
763
0
              cmsReadTag(profile.get(), tag))) {
764
0
        const double estimated_gamma =
765
0
            cmsEstimateGamma(trc, /*precision=*/1e-4);
766
0
        if (estimated_gamma > 0) {
767
0
          rgb_gamma[i] = 1. / estimated_gamma;
768
0
        }
769
0
      }
770
0
      ++i;
771
0
    }
772
0
    if (rgb_gamma[0] != 0 && std::abs(rgb_gamma[0] - rgb_gamma[1]) < 1e-4f &&
773
0
        std::abs(rgb_gamma[1] - rgb_gamma[2]) < 1e-4f) {
774
0
      gamma = rgb_gamma[0];
775
0
    }
776
0
  }
777
778
0
  if (gamma != 0 && c->tf.SetGamma(gamma)) {
779
0
    IccBytes icc_test;
780
0
    if (MaybeCreateProfile(c->ToExternal(), &icc_test) &&
781
0
        ProfileEquivalentToICC(context, profile, icc_test, *c)) {
782
0
      return true;
783
0
    }
784
0
  }
785
786
0
  for (TransferFunction tf : Values<TransferFunction>()) {
787
    // Can only create profile from known transfer function.
788
0
    if (tf == TransferFunction::kUnknown) continue;
789
790
0
    c->tf.SetTransferFunction(tf);
791
792
0
    IccBytes icc_test;
793
0
    if (MaybeCreateProfile(c->ToExternal(), &icc_test) &&
794
0
        ProfileEquivalentToICC(context, profile, icc_test, *c)) {
795
0
      return true;
796
0
    }
797
0
  }
798
799
0
  c->tf.SetTransferFunction(TransferFunction::kUnknown);
800
0
  return true;
801
0
}
802
803
0
void ErrorHandler(cmsContext context, cmsUInt32Number code, const char* text) {
804
0
  JXL_WARNING("LCMS error %u: %s", code, text);
805
0
}
806
807
// Returns a context for the current thread, creating it if necessary.
808
0
cmsContext GetContext() {
809
0
  static thread_local Context context_;
810
0
  if (context_ == nullptr) {
811
0
    context_.reset(cmsCreateContext(nullptr, nullptr));
812
0
    JXL_DASSERT(context_ != nullptr);
813
814
0
    cmsSetLogErrorHandlerTHR(static_cast<cmsContext>(context_.get()), &ErrorHandler);
815
0
  }
816
0
  return static_cast<cmsContext>(context_.get());
817
0
}
818
819
#endif  // JPEGXL_ENABLE_SKCMS
820
821
Status GetPrimariesLuminances(const ColorEncoding& encoding,
822
0
                              float luminances[3]) {
823
  // Explanation:
824
  // We know that the three primaries must sum to white:
825
  //
826
  // [Xr, Xg, Xb;     [1;     [Xw;
827
  //  Yr, Yg, Yb;  ×   1;  =   Yw;
828
  //  Zr, Zg, Zb]      1]      Zw]
829
  //
830
  // By noting that X = x·(X+Y+Z), Y = y·(X+Y+Z) and Z = z·(X+Y+Z) (note the
831
  // lower case indicating chromaticity), and factoring the totals (X+Y+Z) out
832
  // of the left matrix and into the all-ones vector, we get:
833
  //
834
  // [xr, xg, xb;     [Xr + Yr + Zr;     [Xw;
835
  //  yr, yg, yb;  ×   Xg + Yg + Zg;  =   Yw;
836
  //  zr, zg, zb]      Xb + Yb + Zb]      Zw]
837
  //
838
  // Which makes it apparent that we can compute those totals as:
839
  //
840
  //                  [Xr + Yr + Zr;     inv([xr, xg, xb;      [Xw;
841
  //                   Xg + Yg + Zg;  =       yr, yg, yb;   ×   Yw;
842
  //                   Xb + Yb + Zb]          zr, zg, zb])      Zw]
843
  //
844
  // From there, by multiplying each total by its corresponding y, we get Y for
845
  // that primary.
846
847
0
  Color white_XYZ;
848
0
  CIExy wp = encoding.GetWhitePoint();
849
0
  JXL_RETURN_IF_ERROR(CIEXYZFromWhiteCIExy(wp.x, wp.y, white_XYZ));
850
851
0
  PrimariesCIExy primaries;
852
0
  JXL_RETURN_IF_ERROR(encoding.GetPrimaries(primaries));
853
0
  Matrix3x3d chromaticities{
854
0
      {{primaries.r.x, primaries.g.x, primaries.b.x},
855
0
       {primaries.r.y, primaries.g.y, primaries.b.y},
856
0
       {1 - primaries.r.x - primaries.r.y, 1 - primaries.g.x - primaries.g.y,
857
0
        1 - primaries.b.x - primaries.b.y}}};
858
0
  JXL_RETURN_IF_ERROR(Inv3x3Matrix(chromaticities));
859
0
  const double ys[3] = {primaries.r.y, primaries.g.y, primaries.b.y};
860
0
  for (size_t i = 0; i < 3; ++i) {
861
0
    luminances[i] = ys[i] * (chromaticities[i][0] * white_XYZ[0] +
862
0
                             chromaticities[i][1] * white_XYZ[1] +
863
0
                             chromaticities[i][2] * white_XYZ[2]);
864
0
  }
865
0
  return true;
866
0
}
867
868
Status ApplyHlgOotf(JxlCms* t, float* JXL_RESTRICT buf, size_t xsize,
869
0
                    bool forward) {
870
0
  if (295 <= t->intensity_target && t->intensity_target <= 305) {
871
    // The gamma is approximately 1 so this can essentially be skipped.
872
0
    return true;
873
0
  }
874
0
  float gamma = 1.2f * std::pow(1.111f, std::log2(t->intensity_target * 1e-3f));
875
0
  if (!forward) gamma = 1.f / gamma;
876
877
0
  switch (t->hlg_ootf_num_channels) {
878
0
    case 1:
879
0
      for (size_t x = 0; x < xsize; ++x) {
880
0
        buf[x] = std::pow(buf[x], gamma);
881
0
      }
882
0
      break;
883
884
0
    case 3:
885
0
      for (size_t x = 0; x < xsize; x += 3) {
886
0
        const float luminance = buf[x] * t->hlg_ootf_luminances[0] +
887
0
                                buf[x + 1] * t->hlg_ootf_luminances[1] +
888
0
                                buf[x + 2] * t->hlg_ootf_luminances[2];
889
0
        const float ratio = std::pow(luminance, gamma - 1);
890
0
        if (std::isfinite(ratio)) {
891
0
          buf[x] *= ratio;
892
0
          buf[x + 1] *= ratio;
893
0
          buf[x + 2] *= ratio;
894
0
          if (forward && gamma < 1) {
895
            // If gamma < 1, the ratio above will be > 1 which can push bright
896
            // saturated highlights out of gamut. There are several possible
897
            // ways to bring them back in-gamut; this one preserves hue and
898
            // saturation at the slight expense of luminance. If !forward, the
899
            // previously-applied forward OOTF with gamma > 1 already pushed
900
            // those highlights down and we are simply putting them back where
901
            // they were so this is not necessary.
902
0
            const float maximum =
903
0
                std::max(buf[x], std::max(buf[x + 1], buf[x + 2]));
904
0
            if (maximum > 1) {
905
0
              const float normalizer = 1.f / maximum;
906
0
              buf[x] *= normalizer;
907
0
              buf[x + 1] *= normalizer;
908
0
              buf[x + 2] *= normalizer;
909
0
            }
910
0
          }
911
0
        }
912
0
      }
913
0
      break;
914
915
0
    default:
916
0
      return JXL_FAILURE("HLG OOTF not implemented for %" PRIuS " channels",
917
0
                         t->hlg_ootf_num_channels);
918
0
  }
919
0
  return true;
920
0
}
921
922
0
bool IsKnownTransferFunction(jxl::cms::TransferFunction tf) {
923
0
  using TF = jxl::cms::TransferFunction;
924
  // All but kUnknown
925
0
  return tf == TF::k709 || tf == TF::kLinear || tf == TF::kSRGB ||
926
0
         tf == TF::kPQ || tf == TF::kDCI || tf == TF::kHLG;
927
0
}
928
929
constexpr uint8_t kColorPrimariesP3_D65 = 12;
930
931
0
bool IsKnownColorPrimaries(uint8_t color_primaries) {
932
0
  using P = jxl::cms::Primaries;
933
  // All but kCustom
934
0
  if (color_primaries == kColorPrimariesP3_D65) return true;
935
0
  const auto p = static_cast<Primaries>(color_primaries);
936
0
  return p == P::kSRGB || p == P::k2100 || p == P::kP3;
937
0
}
938
939
bool ApplyCICP(const uint8_t color_primaries,
940
               const uint8_t transfer_characteristics,
941
               const uint8_t matrix_coefficients, const uint8_t full_range,
942
0
               ColorEncoding* JXL_RESTRICT c) {
943
0
  if (matrix_coefficients != 0) return false;
944
0
  if (full_range != 1) return false;
945
946
0
  const auto primaries = static_cast<Primaries>(color_primaries);
947
0
  const auto tf = static_cast<TransferFunction>(transfer_characteristics);
948
0
  if (!IsKnownTransferFunction(tf)) return false;
949
0
  if (!IsKnownColorPrimaries(color_primaries)) return false;
950
0
  c->color_space = ColorSpace::kRGB;
951
0
  c->tf.SetTransferFunction(tf);
952
0
  if (primaries == Primaries::kP3) {
953
0
    c->white_point = WhitePoint::kDCI;
954
0
    c->primaries = Primaries::kP3;
955
0
  } else if (color_primaries == kColorPrimariesP3_D65) {
956
0
    c->white_point = WhitePoint::kD65;
957
0
    c->primaries = Primaries::kP3;
958
0
  } else {
959
0
    c->white_point = WhitePoint::kD65;
960
0
    c->primaries = primaries;
961
0
  }
962
0
  return true;
963
0
}
964
965
JXL_BOOL JxlCmsSetFieldsFromICC(void* user_data, const uint8_t* icc_data,
966
                                size_t icc_size, JxlColorEncoding* c,
967
0
                                JXL_BOOL* cmyk) {
968
0
  if (c == nullptr) return JXL_FALSE;
969
0
  if (cmyk == nullptr) return JXL_FALSE;
970
971
0
  *cmyk = JXL_FALSE;
972
973
  // In case parsing fails, mark the ColorEncoding as invalid.
974
0
  c->color_space = JXL_COLOR_SPACE_UNKNOWN;
975
0
  c->transfer_function = JXL_TRANSFER_FUNCTION_UNKNOWN;
976
977
0
  if (icc_size == 0) return JXL_FAILURE("Empty ICC profile");
978
979
0
  ColorEncoding c_enc;
980
981
#if JPEGXL_ENABLE_SKCMS
982
  if (icc_size < 128) {
983
    return JXL_FAILURE("ICC file too small");
984
  }
985
986
  skcms_ICCProfile profile;
987
  JXL_RETURN_IF_ERROR(skcms_Parse(icc_data, icc_size, &profile));
988
989
  // skcms does not return the rendering intent, so get it from the file. It
990
  // should be encoded as big-endian 32-bit integer in bytes 60..63.
991
  uint32_t big_endian_rendering_intent = icc_data[67] + (icc_data[66] << 8) +
992
                                         (icc_data[65] << 16) +
993
                                         (icc_data[64] << 24);
994
  // Some files encode rendering intent as little endian, which is not spec
995
  // compliant. However we accept those with a warning.
996
  uint32_t little_endian_rendering_intent = (icc_data[67] << 24) +
997
                                            (icc_data[66] << 16) +
998
                                            (icc_data[65] << 8) + icc_data[64];
999
  uint32_t candidate_rendering_intent =
1000
      std::min(big_endian_rendering_intent, little_endian_rendering_intent);
1001
  if (candidate_rendering_intent != big_endian_rendering_intent) {
1002
    JXL_WARNING(
1003
        "Invalid rendering intent bytes: [0x%02X 0x%02X 0x%02X 0x%02X], "
1004
        "assuming %u was meant",
1005
        icc_data[64], icc_data[65], icc_data[66], icc_data[67],
1006
        candidate_rendering_intent);
1007
  }
1008
  if (candidate_rendering_intent > 3) {
1009
    return JXL_FAILURE("Invalid rendering intent %u\n",
1010
                       candidate_rendering_intent);
1011
  }
1012
  // ICC and RenderingIntent have the same values (0..3).
1013
  c_enc.rendering_intent =
1014
      static_cast<RenderingIntent>(candidate_rendering_intent);
1015
1016
  if (profile.has_CICP &&
1017
      ApplyCICP(profile.CICP.color_primaries,
1018
                profile.CICP.transfer_characteristics,
1019
                profile.CICP.matrix_coefficients,
1020
                profile.CICP.video_full_range_flag, &c_enc)) {
1021
    *c = c_enc.ToExternal();
1022
    return JXL_TRUE;
1023
  }
1024
1025
  c_enc.color_space = ColorSpaceFromProfile(profile);
1026
  *cmyk = TO_JXL_BOOL(profile.data_color_space == skcms_Signature_CMYK);
1027
1028
  CIExy wp_unadapted;
1029
  JXL_RETURN_IF_ERROR(UnadaptedWhitePoint(profile, &wp_unadapted));
1030
  JXL_RETURN_IF_ERROR(c_enc.SetWhitePoint(wp_unadapted));
1031
1032
  // Relies on color_space.
1033
  JXL_RETURN_IF_ERROR(IdentifyPrimaries(profile, wp_unadapted, &c_enc));
1034
1035
  // Relies on color_space/white point/primaries being set already.
1036
  JXL_RETURN_IF_ERROR(DetectTransferFunction(profile, &c_enc));
1037
#else  // JPEGXL_ENABLE_SKCMS
1038
1039
0
  const cmsContext context = GetContext();
1040
1041
0
  Profile profile;
1042
0
  JXL_RETURN_IF_ERROR(
1043
0
      DecodeProfile(context, Bytes(icc_data, icc_size), &profile));
1044
1045
0
  const cmsUInt32Number rendering_intent32 =
1046
0
      cmsGetHeaderRenderingIntent(profile.get());
1047
0
  if (rendering_intent32 > 3) {
1048
0
    return JXL_FAILURE("Invalid rendering intent %u\n", rendering_intent32);
1049
0
  }
1050
  // ICC and RenderingIntent have the same values (0..3).
1051
0
  c_enc.rendering_intent = static_cast<RenderingIntent>(rendering_intent32);
1052
1053
0
  static constexpr size_t kCICPSize = 12;
1054
0
  static constexpr auto kCICPSignature =
1055
0
      static_cast<cmsTagSignature>(0x63696370);
1056
0
  uint8_t cicp_buffer[kCICPSize];
1057
0
  if (cmsReadRawTag(profile.get(), kCICPSignature, cicp_buffer, kCICPSize) ==
1058
0
          kCICPSize &&
1059
0
      ApplyCICP(cicp_buffer[8], cicp_buffer[9], cicp_buffer[10],
1060
0
                cicp_buffer[11], &c_enc)) {
1061
0
    *c = c_enc.ToExternal();
1062
0
    return JXL_TRUE;
1063
0
  }
1064
1065
0
  c_enc.color_space = ColorSpaceFromProfile(profile);
1066
0
  if (cmsGetColorSpace(profile.get()) == cmsSigCmykData) {
1067
0
    *cmyk = JXL_TRUE;
1068
0
    *c = c_enc.ToExternal();
1069
0
    return JXL_TRUE;
1070
0
  }
1071
1072
0
  const cmsCIEXYZ wp_unadapted = UnadaptedWhitePoint(context, profile, c_enc);
1073
0
  JXL_RETURN_IF_ERROR(c_enc.SetWhitePoint(CIExyFromXYZ(wp_unadapted)));
1074
1075
  // Relies on color_space.
1076
0
  JXL_RETURN_IF_ERROR(
1077
0
      IdentifyPrimaries(context, profile, wp_unadapted, &c_enc));
1078
1079
  // Relies on color_space/white point/primaries being set already.
1080
0
  JXL_RETURN_IF_ERROR(DetectTransferFunction(context, profile, &c_enc));
1081
1082
0
#endif  // JPEGXL_ENABLE_SKCMS
1083
1084
0
  *c = c_enc.ToExternal();
1085
0
  return JXL_TRUE;
1086
0
}
1087
1088
}  // namespace
1089
1090
namespace {
1091
1092
0
void JxlCmsDestroy(void* cms_data) {
1093
0
  if (cms_data == nullptr) return;
1094
0
  JxlCms* t = reinterpret_cast<JxlCms*>(cms_data);
1095
0
#if !JPEGXL_ENABLE_SKCMS
1096
0
  TransformDeleter()(t->lcms_transform);
1097
0
#endif
1098
0
  delete t;
1099
0
}
1100
1101
void AllocateBuffer(size_t length, size_t num_threads,
1102
0
                    std::vector<float>* storage, std::vector<float*>* view) {
1103
0
  constexpr size_t kAlign = 128 / sizeof(float);
1104
0
  size_t stride = RoundUpTo(length, kAlign);
1105
0
  storage->resize(stride * num_threads + kAlign);
1106
0
  intptr_t addr = reinterpret_cast<intptr_t>(storage->data());
1107
0
  size_t offset =
1108
0
      (RoundUpTo(addr, kAlign * sizeof(float)) - addr) / sizeof(float);
1109
0
  view->clear();
1110
0
  view->reserve(num_threads);
1111
0
  for (size_t i = 0; i < num_threads; ++i) {
1112
0
    view->emplace_back(storage->data() + offset + i * stride);
1113
0
  }
1114
0
}
1115
1116
void* JxlCmsInit(void* init_data, size_t num_threads, size_t xsize,
1117
                 const JxlColorProfile* input, const JxlColorProfile* output,
1118
0
                 float intensity_target) {
1119
0
  if (init_data == nullptr) {
1120
0
    JXL_NOTIFY_ERROR("JxlCmsInit: init_data is nullptr");
1121
0
    return nullptr;
1122
0
  }
1123
0
  const auto* cms = static_cast<const JxlCmsInterface*>(init_data);
1124
0
  auto t = jxl::make_unique<JxlCms>();
1125
0
  IccBytes icc_src;
1126
0
  IccBytes icc_dst;
1127
0
  if (input->icc.size == 0) {
1128
0
    JXL_NOTIFY_ERROR("JxlCmsInit: empty input ICC");
1129
0
    return nullptr;
1130
0
  }
1131
0
  if (output->icc.size == 0) {
1132
0
    JXL_NOTIFY_ERROR("JxlCmsInit: empty OUTPUT ICC");
1133
0
    return nullptr;
1134
0
  }
1135
0
  icc_src.assign(input->icc.data, input->icc.data + input->icc.size);
1136
0
  ColorEncoding c_src;
1137
0
  if (!c_src.SetFieldsFromICC(std::move(icc_src), *cms)) {
1138
0
    JXL_NOTIFY_ERROR("JxlCmsInit: failed to parse input ICC");
1139
0
    return nullptr;
1140
0
  }
1141
0
  icc_dst.assign(output->icc.data, output->icc.data + output->icc.size);
1142
0
  ColorEncoding c_dst;
1143
0
  if (!c_dst.SetFieldsFromICC(std::move(icc_dst), *cms)) {
1144
0
    JXL_NOTIFY_ERROR("JxlCmsInit: failed to parse output ICC");
1145
0
    return nullptr;
1146
0
  }
1147
#if JXL_CMS_VERBOSE
1148
  printf("%s -> %s\n", Description(c_src).c_str(), Description(c_dst).c_str());
1149
#endif
1150
1151
#if JPEGXL_ENABLE_SKCMS
1152
  if (!DecodeProfile(input->icc.data, input->icc.size, &t->profile_src)) {
1153
    JXL_NOTIFY_ERROR("JxlCmsInit: skcms failed to parse input ICC");
1154
    return nullptr;
1155
  }
1156
  if (!DecodeProfile(output->icc.data, output->icc.size, &t->profile_dst)) {
1157
    JXL_NOTIFY_ERROR("JxlCmsInit: skcms failed to parse output ICC");
1158
    return nullptr;
1159
  }
1160
#else   // JPEGXL_ENABLE_SKCMS
1161
0
  const cmsContext context = GetContext();
1162
0
  Profile profile_src, profile_dst;
1163
0
  if (!DecodeProfile(context, Bytes(c_src.icc), &profile_src)) {
1164
0
    JXL_NOTIFY_ERROR("JxlCmsInit: lcms failed to parse input ICC");
1165
0
    return nullptr;
1166
0
  }
1167
0
  if (!DecodeProfile(context, Bytes(c_dst.icc), &profile_dst)) {
1168
0
    JXL_NOTIFY_ERROR("JxlCmsInit: lcms failed to parse output ICC");
1169
0
    return nullptr;
1170
0
  }
1171
0
#endif  // JPEGXL_ENABLE_SKCMS
1172
1173
0
  t->skip_lcms = false;
1174
0
  if (c_src.SameColorEncoding(c_dst)) {
1175
0
    t->skip_lcms = true;
1176
#if JXL_CMS_VERBOSE
1177
    printf("Skip CMS\n");
1178
#endif
1179
0
  }
1180
1181
0
  t->apply_hlg_ootf = c_src.tf.IsHLG() != c_dst.tf.IsHLG();
1182
0
  if (t->apply_hlg_ootf) {
1183
0
    const ColorEncoding* c_hlg = c_src.tf.IsHLG() ? &c_src : &c_dst;
1184
0
    t->hlg_ootf_num_channels = c_hlg->Channels();
1185
0
    if (t->hlg_ootf_num_channels == 3 &&
1186
0
        !GetPrimariesLuminances(*c_hlg, t->hlg_ootf_luminances.data())) {
1187
0
      JXL_NOTIFY_ERROR(
1188
0
          "JxlCmsInit: failed to compute the luminances of primaries");
1189
0
      return nullptr;
1190
0
    }
1191
0
  }
1192
1193
  // Special-case SRGB <=> linear if the primaries / white point are the same,
1194
  // or any conversion where PQ or HLG is involved:
1195
0
  bool src_linear = c_src.tf.IsLinear();
1196
0
  const bool dst_linear = c_dst.tf.IsLinear();
1197
1198
0
  if (c_src.tf.IsPQ() || c_src.tf.IsHLG() ||
1199
0
      (c_src.tf.IsSRGB() && dst_linear && c_src.SameColorSpace(c_dst))) {
1200
    // Construct new profile as if the data were already/still linear.
1201
0
    ColorEncoding c_linear_src = c_src;
1202
0
    c_linear_src.tf.SetTransferFunction(TransferFunction::kLinear);
1203
#if JPEGXL_ENABLE_SKCMS
1204
    skcms_ICCProfile new_src;
1205
#else   // JPEGXL_ENABLE_SKCMS
1206
0
    Profile new_src;
1207
0
#endif  // JPEGXL_ENABLE_SKCMS
1208
        // Only enable ExtraTF if profile creation succeeded.
1209
0
    if (MaybeCreateProfile(c_linear_src.ToExternal(), &icc_src) &&
1210
#if JPEGXL_ENABLE_SKCMS
1211
        DecodeProfile(icc_src.data(), icc_src.size(), &new_src)) {
1212
#else   // JPEGXL_ENABLE_SKCMS
1213
0
        DecodeProfile(context, Bytes(icc_src), &new_src)) {
1214
0
#endif  // JPEGXL_ENABLE_SKCMS
1215
#if JXL_CMS_VERBOSE
1216
      printf("Special HLG/PQ/sRGB -> linear\n");
1217
#endif
1218
#if JPEGXL_ENABLE_SKCMS
1219
      t->icc_src = std::move(icc_src);
1220
      t->profile_src = new_src;
1221
#else   // JPEGXL_ENABLE_SKCMS
1222
0
      profile_src.swap(new_src);
1223
0
#endif  // JPEGXL_ENABLE_SKCMS
1224
0
      t->preprocess = c_src.tf.IsSRGB()
1225
0
                          ? ExtraTF::kSRGB
1226
0
                          : (c_src.tf.IsPQ() ? ExtraTF::kPQ : ExtraTF::kHLG);
1227
0
      c_src = c_linear_src;
1228
0
      src_linear = true;
1229
0
    } else {
1230
0
      if (t->apply_hlg_ootf) {
1231
0
        JXL_NOTIFY_ERROR(
1232
0
            "Failed to create extra linear source profile, and HLG OOTF "
1233
0
            "required");
1234
0
        return nullptr;
1235
0
      }
1236
0
      JXL_WARNING("Failed to create extra linear destination profile");
1237
0
    }
1238
0
  }
1239
1240
0
  if (c_dst.tf.IsPQ() || c_dst.tf.IsHLG() ||
1241
0
      (c_dst.tf.IsSRGB() && src_linear && c_src.SameColorSpace(c_dst))) {
1242
0
    ColorEncoding c_linear_dst = c_dst;
1243
0
    c_linear_dst.tf.SetTransferFunction(TransferFunction::kLinear);
1244
#if JPEGXL_ENABLE_SKCMS
1245
    skcms_ICCProfile new_dst;
1246
#else   // JPEGXL_ENABLE_SKCMS
1247
0
    Profile new_dst;
1248
0
#endif  // JPEGXL_ENABLE_SKCMS
1249
    // Only enable ExtraTF if profile creation succeeded.
1250
0
    if (MaybeCreateProfile(c_linear_dst.ToExternal(), &icc_dst) &&
1251
#if JPEGXL_ENABLE_SKCMS
1252
        DecodeProfile(icc_dst.data(), icc_dst.size(), &new_dst)) {
1253
#else   // JPEGXL_ENABLE_SKCMS
1254
0
        DecodeProfile(context, Bytes(icc_dst), &new_dst)) {
1255
0
#endif  // JPEGXL_ENABLE_SKCMS
1256
#if JXL_CMS_VERBOSE
1257
      printf("Special linear -> HLG/PQ/sRGB\n");
1258
#endif
1259
#if JPEGXL_ENABLE_SKCMS
1260
      t->icc_dst = std::move(icc_dst);
1261
      t->profile_dst = new_dst;
1262
#else   // JPEGXL_ENABLE_SKCMS
1263
0
      profile_dst.swap(new_dst);
1264
0
#endif  // JPEGXL_ENABLE_SKCMS
1265
0
      t->postprocess = c_dst.tf.IsSRGB()
1266
0
                           ? ExtraTF::kSRGB
1267
0
                           : (c_dst.tf.IsPQ() ? ExtraTF::kPQ : ExtraTF::kHLG);
1268
0
      c_dst = c_linear_dst;
1269
0
    } else {
1270
0
      if (t->apply_hlg_ootf) {
1271
0
        JXL_NOTIFY_ERROR(
1272
0
            "Failed to create extra linear destination profile, and inverse "
1273
0
            "HLG OOTF required");
1274
0
        return nullptr;
1275
0
      }
1276
0
      JXL_WARNING("Failed to create extra linear destination profile");
1277
0
    }
1278
0
  }
1279
1280
0
  if (c_src.SameColorEncoding(c_dst)) {
1281
#if JXL_CMS_VERBOSE
1282
    printf("Same intermediary linear profiles, skipping CMS\n");
1283
#endif
1284
0
    t->skip_lcms = true;
1285
0
  }
1286
1287
#if JPEGXL_ENABLE_SKCMS
1288
  if (!skcms_MakeUsableAsDestination(&t->profile_dst)) {
1289
    JXL_NOTIFY_ERROR(
1290
        "Failed to make %s usable as a color transform destination",
1291
        ColorEncodingDescription(c_dst.ToExternal()).c_str());
1292
    return nullptr;
1293
  }
1294
#endif  // JPEGXL_ENABLE_SKCMS
1295
1296
  // Not including alpha channel (copied separately).
1297
0
  const size_t channels_src = (c_src.cmyk ? 4 : c_src.Channels());
1298
0
  const size_t channels_dst = c_dst.Channels();
1299
#if JXL_CMS_VERBOSE
1300
  printf("Channels: %" PRIuS "; Threads: %" PRIuS "\n", channels_src,
1301
         num_threads);
1302
#endif
1303
1304
0
#if !JPEGXL_ENABLE_SKCMS
1305
  // Type includes color space (XYZ vs RGB), so can be different.
1306
0
  const uint32_t type_src = Type32(c_src, channels_src == 4);
1307
0
  const uint32_t type_dst = Type32(c_dst, false);
1308
0
  const uint32_t intent = static_cast<uint32_t>(c_dst.rendering_intent);
1309
  // Use cmsFLAGS_NOCACHE to disable the 1-pixel cache and make calling
1310
  // cmsDoTransform() thread-safe.
1311
0
  const uint32_t flags = cmsFLAGS_NOCACHE | cmsFLAGS_BLACKPOINTCOMPENSATION |
1312
0
                         cmsFLAGS_HIGHRESPRECALC;
1313
0
  t->lcms_transform =
1314
0
      cmsCreateTransformTHR(context, profile_src.get(), type_src,
1315
0
                            profile_dst.get(), type_dst, intent, flags);
1316
0
  if (t->lcms_transform == nullptr) {
1317
0
    JXL_NOTIFY_ERROR("Failed to create transform");
1318
0
    return nullptr;
1319
0
  }
1320
0
#endif  // !JPEGXL_ENABLE_SKCMS
1321
1322
  // Ideally LCMS would convert directly from External to Image3. However,
1323
  // cmsDoTransformLineStride only accepts 32-bit BytesPerPlaneIn, whereas our
1324
  // planes can be more than 4 GiB apart. Hence, transform inputs/outputs must
1325
  // be interleaved. Calling cmsDoTransform for each pixel is expensive
1326
  // (indirect call). We therefore transform rows, which requires per-thread
1327
  // buffers. To avoid separate allocations, we use the rows of an image.
1328
  // Because LCMS apparently also cannot handle <= 16 bit inputs and 32-bit
1329
  // outputs (or vice versa), we use floating point input/output.
1330
0
  t->channels_src = channels_src;
1331
0
  t->channels_dst = channels_dst;
1332
0
#if !JPEGXL_ENABLE_SKCMS
1333
0
  size_t actual_channels_src = channels_src;
1334
0
  size_t actual_channels_dst = channels_dst;
1335
#else
1336
  // SkiaCMS doesn't support grayscale float buffers, so we create space for RGB
1337
  // float buffers anyway.
1338
  size_t actual_channels_src = (channels_src == 4 ? 4 : 3);
1339
  size_t actual_channels_dst = 3;
1340
#endif
1341
0
  AllocateBuffer(xsize * actual_channels_src, num_threads, &t->src_storage,
1342
0
                 &t->buf_src);
1343
0
  AllocateBuffer(xsize * actual_channels_dst, num_threads, &t->dst_storage,
1344
0
                 &t->buf_dst);
1345
0
  t->intensity_target = intensity_target;
1346
0
  return t.release();
1347
0
}
1348
1349
0
float* JxlCmsGetSrcBuf(void* cms_data, size_t thread) {
1350
0
  JxlCms* t = reinterpret_cast<JxlCms*>(cms_data);
1351
0
  return t->buf_src[thread];
1352
0
}
1353
1354
0
float* JxlCmsGetDstBuf(void* cms_data, size_t thread) {
1355
0
  JxlCms* t = reinterpret_cast<JxlCms*>(cms_data);
1356
0
  return t->buf_dst[thread];
1357
0
}
1358
1359
}  // namespace
1360
1361
extern "C" {
1362
1363
4.62k
JXL_CMS_EXPORT const JxlCmsInterface* JxlGetDefaultCms() {
1364
4.62k
  static constexpr JxlCmsInterface kInterface = {
1365
4.62k
      /*set_fields_data=*/nullptr,
1366
4.62k
      /*set_fields_from_icc=*/&JxlCmsSetFieldsFromICC,
1367
4.62k
      /*init_data=*/const_cast<void*>(static_cast<const void*>(&kInterface)),
1368
4.62k
      /*init=*/&JxlCmsInit,
1369
4.62k
      /*get_src_buf=*/&JxlCmsGetSrcBuf,
1370
4.62k
      /*get_dst_buf=*/&JxlCmsGetDstBuf,
1371
4.62k
      /*run=*/&DoColorSpaceTransform,
1372
4.62k
      /*destroy=*/&JxlCmsDestroy};
1373
4.62k
  return &kInterface;
1374
4.62k
}
1375
1376
}  // extern "C"
1377
1378
}  // namespace jxl
1379
#endif  // HWY_ONCE