summaryrefslogtreecommitdiff
path: root/libweston/color-lcms/color-profile.c
blob: 5d5af40845764e49736ee87c2c2d7c642b13dbfa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
/*
 * Copyright 2019 Sebastian Wick
 * Copyright 2021 Collabora, Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "config.h"

#include <stdio.h>
#include <string.h>
#include <libweston/libweston.h>

#include "color.h"
#include "color-lcms.h"
#include "color-management.h"
#include "shared/helpers.h"
#include "shared/string-helpers.h"
#include "shared/xalloc.h"
#include "shared/weston-assert.h"

struct xyz_arr_flt {
	float v[3];
};

static double
xyz_dot_prod(const struct xyz_arr_flt a, const struct xyz_arr_flt b)
{
	return (double)a.v[0] * b.v[0] +
	       (double)a.v[1] * b.v[1] +
	       (double)a.v[2] * b.v[2];
}

/**
 * Graeme sketched a linearization method there:
 * https://lists.freedesktop.org/archives/wayland-devel/2019-March/040171.html
 */
static bool
build_eotf_from_clut_profile(cmsContext lcms_ctx,
			     struct lcmsProfilePtr profile,
			     cmsToneCurve *output_eotf[3],
			     int num_points)
{
	int ch, point;
	float *curve_array[3];
	float *red = NULL;
	struct lcmsProfilePtr xyz_profile = { NULL };
	cmsHTRANSFORM transform_rgb_to_xyz = NULL;
	bool ret = false;
	const float div = num_points - 1;

	red = malloc(sizeof(float) * num_points * 3);
	if (!red)
		goto release;

	curve_array[0] = red;
	curve_array[1] = red + num_points;
	curve_array[2] = red + 2 * num_points;

	xyz_profile.p = cmsCreateXYZProfileTHR(lcms_ctx);
	if (!xyz_profile.p)
		goto release;

	transform_rgb_to_xyz = cmsCreateTransformTHR(lcms_ctx, profile.p,
						     TYPE_RGB_FLT, xyz_profile.p,
						     TYPE_XYZ_FLT,
						     INTENT_ABSOLUTE_COLORIMETRIC,
						     0);
	if (!transform_rgb_to_xyz)
		goto release;

	for (ch = 0; ch < 3; ch++) {
		struct xyz_arr_flt prim_xyz_max;
		struct xyz_arr_flt prim_xyz;
		double xyz_square_magnitude;
		float rgb[3] = { 0.0f, 0.0f, 0.0f };

		rgb[ch] = 1.0f;
		cmsDoTransform(transform_rgb_to_xyz, rgb, prim_xyz_max.v, 1);

		/**
		 * Calculate xyz square of magnitude uses single channel 100% and
		 * others are zero.
		 */
		xyz_square_magnitude = xyz_dot_prod(prim_xyz_max, prim_xyz_max);
		/**
		 * Build rgb tone curves
		 */
		for (point = 0; point < num_points; point++) {
			rgb[ch] = (float)point / div;
			cmsDoTransform(transform_rgb_to_xyz, rgb, prim_xyz.v, 1);
			curve_array[ch][point] = xyz_dot_prod(prim_xyz,
							      prim_xyz_max) /
						 xyz_square_magnitude;
		}

		/**
		 * Create LCMS object of rgb tone curves and validate whether
		 * monotonic
		 */
		output_eotf[ch] = cmsBuildTabulatedToneCurveFloat(lcms_ctx,
								  num_points,
								  curve_array[ch]);
		if (!output_eotf[ch])
			goto release;
		if (!cmsIsToneCurveMonotonic(output_eotf[ch])) {
			/**
			 * It is interesting to see how this profile was created.
			 * We assume that such a curve could not be used for linearization
			 * of arbitrary profile.
			 */
			goto release;
		}
	}
	ret = true;

release:
	if (transform_rgb_to_xyz)
		cmsDeleteTransform(transform_rgb_to_xyz);
	if (xyz_profile.p)
		cmsCloseProfile(xyz_profile.p);
	free(red);
	if (ret == false)
		cmsFreeToneCurveTriple(output_eotf);

	return ret;
}

/**
 * Concatenation of two monotonic tone curves.
 * LCMS  API cmsJoinToneCurve does y = Y^-1(X(t)),
 * but want to have y = Y^(X(t))
 */
cmsToneCurve *
lcmsJoinToneCurve(cmsContext context_id, const cmsToneCurve *X,
		  const cmsToneCurve *Y, unsigned int resulting_points)
{
	cmsToneCurve *out = NULL;
	float t, x;
	float *res = NULL;
	unsigned int i;

	res = zalloc(resulting_points * sizeof(float));
	if (res == NULL)
		goto error;

	for (i = 0; i < resulting_points; i++) {
		t = (float)i / (resulting_points - 1);
		x = cmsEvalToneCurveFloat(X, t);
		res[i] = cmsEvalToneCurveFloat(Y, x);
	}

	out = cmsBuildTabulatedToneCurveFloat(context_id, resulting_points, res);

error:
	if (res != NULL)
		free(res);

	return out;
}
/**
 * Extract EOTF from matrix-shaper and cLUT profiles,
 * then invert and concatenate with 'vcgt' curve if it
 * is available.
 */
static bool
ensure_output_profile_extract_icc(struct cmlcms_output_profile_extract *extract,
				  cmsContext lcms_ctx,
				  struct lcmsProfilePtr hProfile,
				  unsigned int num_points,
				  const char **err_msg)
{
	cmsToneCurve *curve = NULL;
	const cmsToneCurve * const *vcgt_curves;
	cmsToneCurve *eotf_curves[3] = {};
	unsigned i;
	cmsTagSignature tags[] = {
			cmsSigRedTRCTag, cmsSigGreenTRCTag, cmsSigBlueTRCTag
	};

	if (cmsIsMatrixShaper(hProfile.p)) {
		/**
		 * Matrix-shaper profiles contain TRC and MatrixColumn tags.
		 * Assumes that AToB or DToB tags do not exist or are
		 * equivalent to TRC + MatrixColumn.
		 * We can take the TRC curves straight as EOTF.
		 */
		for (i = 0 ; i < 3; i++) {
			curve = cmsReadTag(hProfile.p, tags[i]);
			if (!curve) {
				*err_msg = "TRC tag missing from matrix-shaper ICC profile";
				goto fail;
			}
			eotf_curves[i] = cmsDupToneCurve(curve);
			if (!eotf_curves[i]) {
				*err_msg = "out of memory";
				goto fail;
			}
		}
	} else {
		/**
		 * Any other kind of profile goes through approximate
		 * linearization that produces sampled curves.
		 */
		if (!build_eotf_from_clut_profile(lcms_ctx, hProfile,
						  eotf_curves, num_points)) {
			*err_msg = "estimating EOTF failed";
			goto fail;
		}
	}

	extract->eotf.p = cmsCreateLinearizationDeviceLinkTHR(lcms_ctx, cmsSigRgbData, eotf_curves);
	if (!extract->eotf.p) {
		*err_msg = "out of memory";
		goto fail;
	}

	for (i = 0; i < 3; i++) {
		curve = cmsReverseToneCurve(eotf_curves[i]);
		if (!curve) {
			*err_msg = "inverting EOTF failed";
			goto fail;
		}
		extract->output_inv_eotf_vcgt[i] = curve;
	}
	vcgt_curves = cmsReadTag(hProfile.p, cmsSigVcgtTag);
	if (vcgt_curves && vcgt_curves[0] && vcgt_curves[1] && vcgt_curves[2]) {
		for (i = 0; i < 3; i++) {
			curve = lcmsJoinToneCurve(lcms_ctx,
						  extract->output_inv_eotf_vcgt[i],
						  vcgt_curves[i], num_points);
			if (!curve) {
				*err_msg = "joining curves failed";
				goto fail;
			}
			cmsFreeToneCurve(extract->output_inv_eotf_vcgt[i]);
			extract->output_inv_eotf_vcgt[i] = curve;
			extract->vcgt[i] = cmsDupToneCurve(vcgt_curves[i]);
			if (!extract->vcgt[i]) {
				*err_msg = "out of memory";
				goto fail;
			}
		}
	}

	cmsFreeToneCurveTriple(eotf_curves);

	return true;

fail:
	cmsCloseProfile(extract->eotf.p);
	extract->eotf.p = NULL;
	cmsFreeToneCurveTriple(eotf_curves);
	cmsFreeToneCurveTriple(extract->output_inv_eotf_vcgt);
	cmsFreeToneCurveTriple(extract->vcgt);
	return false;
}

bool
ensure_output_profile_extract(struct cmlcms_color_profile *cprof,
			      cmsContext lcms_ctx,
			      unsigned int num_points,
			      const char **err_msg)
{
	bool ret;

	/* Everything already computed */
	if (cprof->extract.eotf.p)
		return true;

	ret = ensure_output_profile_extract_icc(&cprof->extract, lcms_ctx,
						cprof->profile, num_points, err_msg);

	if (ret)
		weston_assert_ptr(cprof->base.cm->compositor, cprof->extract.eotf.p);

	return ret;
}

/* FIXME: sync with spec! */
static bool
validate_icc_profile(struct lcmsProfilePtr profile, char **errmsg)
{
	cmsColorSpaceSignature cs = cmsGetColorSpace(profile.p);
	uint32_t nr_channels = cmsChannelsOf(cs);
	uint8_t version = cmsGetEncodedICCversion(profile.p) >> 24;

	if (version != 2 && version != 4) {
		str_printf(errmsg,
			   "ICC profile major version %d is unsupported, should be 2 or 4.",
			   version);
		return false;
	}

	if (nr_channels != 3) {
		str_printf(errmsg,
			   "ICC profile must contain 3 channels for the color space, not %u.",
			   nr_channels);
		return false;
	}

	if (cmsGetDeviceClass(profile.p) != cmsSigDisplayClass) {
		str_printf(errmsg, "ICC profile is required to be of Display device class, but it is not.");
		return false;
	}

	return true;
}

static struct cmlcms_color_profile *
cmlcms_find_color_profile_by_md5(const struct weston_color_manager_lcms *cm,
				 const struct cmlcms_md5_sum *md5sum)
{
	struct cmlcms_color_profile *cprof;

	wl_list_for_each(cprof, &cm->color_profile_list, link) {
		if (memcmp(cprof->md5sum.bytes,
			   md5sum->bytes, sizeof(md5sum->bytes)) == 0)
			return cprof;
	}

	return NULL;
}

char *
cmlcms_color_profile_print(const struct cmlcms_color_profile *cprof)
{
	char *str;

	str_printf(&str, "  description: %s\n", cprof->base.description);
	abort_oom_if_null(str);

	return str;
}

static struct cmlcms_color_profile *
cmlcms_color_profile_create(struct weston_color_manager_lcms *cm,
			    struct lcmsProfilePtr profile,
			    char *desc,
			    char **errmsg)
{
	struct cmlcms_color_profile *cprof;
	char *str;

	cprof = zalloc(sizeof *cprof);
	if (!cprof)
		return NULL;

	weston_color_profile_init(&cprof->base, &cm->base);
	cprof->base.description = desc;
	cprof->profile = profile;
	cmsGetHeaderProfileID(profile.p, cprof->md5sum.bytes);
	wl_list_insert(&cm->color_profile_list, &cprof->link);

	weston_log_scope_printf(cm->profiles_scope,
				"New color profile: %p\n", cprof);

	str = cmlcms_color_profile_print(cprof);
	weston_log_scope_printf(cm->profiles_scope, "%s", str);
	free(str);

	return cprof;
}

void
cmlcms_color_profile_destroy(struct cmlcms_color_profile *cprof)
{
	struct weston_color_manager_lcms *cm = to_cmlcms(cprof->base.cm);

	wl_list_remove(&cprof->link);
	cmsFreeToneCurveTriple(cprof->extract.vcgt);
	cmsCloseProfile(cprof->extract.eotf.p);
	cmsFreeToneCurveTriple(cprof->extract.output_inv_eotf_vcgt);
	cmsCloseProfile(cprof->profile.p);

	/* Only profiles created from ICC files have these. */
	if (cprof->prof_rofile)
		os_ro_anonymous_file_destroy(cprof->prof_rofile);

	weston_log_scope_printf(cm->profiles_scope, "Destroyed color profile %p. " \
				"Description: %s\n", cprof, cprof->base.description);

	free(cprof->base.description);
	free(cprof);
}

struct cmlcms_color_profile *
ref_cprof(struct cmlcms_color_profile *cprof)
{
	if (!cprof)
		return NULL;

	weston_color_profile_ref(&cprof->base);
	return  cprof;
}

void
unref_cprof(struct cmlcms_color_profile *cprof)
{
	if (!cprof)
		return;

	weston_color_profile_unref(&cprof->base);
}

static char *
make_icc_file_description(struct lcmsProfilePtr profile,
			  const struct cmlcms_md5_sum *md5sum,
			  const char *name_part)
{
	char md5sum_str[sizeof(md5sum->bytes) * 2 + 1];
	char *desc;
	size_t i;

	for (i = 0; i < sizeof(md5sum->bytes); i++) {
		snprintf(md5sum_str + 2 * i, sizeof(md5sum_str) - 2 * i,
			 "%02x", md5sum->bytes[i]);
	}

	str_printf(&desc, "ICCv%.1f %s %s", cmsGetProfileVersion(profile.p),
		   name_part, md5sum_str);

	return desc;
}

/**
 *
 * Build stock profile which available for clients unaware of color management
 */
bool
cmlcms_create_stock_profile(struct weston_color_manager_lcms *cm)
{
	struct lcmsProfilePtr profile;
	struct cmlcms_md5_sum md5sum;
	char *desc = NULL;
	const char *err_msg = NULL;

	profile.p = cmsCreate_sRGBProfileTHR(cm->lcms_ctx);
	if (!profile.p) {
		weston_log("color-lcms: error: cmsCreate_sRGBProfileTHR failed\n");
		return false;
	}
	if (!cmsMD5computeID(profile.p)) {
		weston_log("Failed to compute MD5 for ICC profile\n");
		goto err_close;
	}

	cmsGetHeaderProfileID(profile.p, md5sum.bytes);
	desc = make_icc_file_description(profile, &md5sum, "sRGB stock");
	if (!desc)
		goto err_close;

	cm->sRGB_profile = cmlcms_color_profile_create(cm, profile, desc, NULL);
	if (!cm->sRGB_profile)
		goto err_close;

	if (!ensure_output_profile_extract(cm->sRGB_profile, cm->lcms_ctx,
					   cmlcms_reasonable_1D_points(), &err_msg))
		goto err_close;

	return true;

err_close:
	if (err_msg)
		weston_log("%s\n", err_msg);

	free(desc);
	cmsCloseProfile(profile.p);
	return false;
}

struct weston_color_profile *
cmlcms_ref_stock_sRGB_color_profile(struct weston_color_manager *cm_base)
{
	struct weston_color_manager_lcms *cm = to_cmlcms(cm_base);
	struct cmlcms_color_profile *cprof;

	cprof = ref_cprof(cm->sRGB_profile);

	return &cprof->base;
}

bool
cmlcms_get_color_profile_from_icc(struct weston_color_manager *cm_base,
				  const void *icc_data,
				  size_t icc_len,
				  const char *name_part,
				  struct weston_color_profile **cprof_out,
				  char **errmsg)
{
	struct weston_color_manager_lcms *cm = to_cmlcms(cm_base);
	struct lcmsProfilePtr profile;
	struct cmlcms_md5_sum md5sum;
	struct cmlcms_color_profile *cprof = NULL;
	char *desc = NULL;

	if (!icc_data || icc_len < 1) {
		str_printf(errmsg, "No ICC data.");
		return false;
	}
	if (icc_len >= UINT32_MAX) {
		str_printf(errmsg, "Too much ICC data.");
		return false;
	}

	profile.p = cmsOpenProfileFromMemTHR(cm->lcms_ctx, icc_data, icc_len);
	if (!profile.p) {
		str_printf(errmsg, "ICC data not understood.");
		return false;
	}

	if (!validate_icc_profile(profile, errmsg))
		goto err_close;

	if (!cmsMD5computeID(profile.p)) {
		str_printf(errmsg, "Failed to compute MD5 for ICC profile.");
		goto err_close;
	}

	cmsGetHeaderProfileID(profile.p, md5sum.bytes);
	cprof = cmlcms_find_color_profile_by_md5(cm, &md5sum);
	if (cprof) {
		*cprof_out = weston_color_profile_ref(&cprof->base);
		cmsCloseProfile(profile.p);
		return true;
	}

	desc = make_icc_file_description(profile, &md5sum, name_part);
	if (!desc)
		goto err_close;

	cprof = cmlcms_color_profile_create(cm, profile, desc, errmsg);
	if (!cprof)
		goto err_close;

	cprof->prof_rofile = os_ro_anonymous_file_create(icc_len, icc_data);
	if (!cprof->prof_rofile)
		goto err_close;

	*cprof_out = &cprof->base;
	return true;

err_close:
	if (cprof)
		cmlcms_color_profile_destroy(cprof);
	free(desc);
	cmsCloseProfile(profile.p);
	return false;
}

bool
cmlcms_send_image_desc_info(struct cm_image_desc_info *cm_image_desc_info,
			    struct weston_color_profile *cprof_base)
{
	struct weston_color_manager_lcms *cm = to_cmlcms(cprof_base->cm);
	struct weston_compositor *compositor = cm->base.compositor;
	struct cmlcms_color_profile *cprof = to_cmlcms_cprof(cprof_base);
	const struct weston_color_primaries_info *primaries_info;
	const struct weston_color_tf_info *tf_info;
        int32_t fd;
        uint32_t len;

	if (cprof->prof_rofile) {
		/* ICC-based color profile, so just send the ICC file fd. If we
		 * get an error (negative fd), the helper will send the proper
		 * error to the client. */
		fd = os_ro_anonymous_file_get_fd(cprof->prof_rofile,
						 RO_ANONYMOUS_FILE_MAPMODE_PRIVATE);
		if (fd < 0) {
			weston_cm_send_icc_file(cm_image_desc_info, -1, 0);
			return false;
		}

		len = os_ro_anonymous_file_size(cprof->prof_rofile);
		weston_assert_uint32_gt(compositor, len, 0);

		weston_cm_send_icc_file(cm_image_desc_info, fd, len);

		os_ro_anonymous_file_put_fd(fd);
	} else {
		/* TODO: we still don't support parametric color profiles that
		 * are not the stock one. This should change when we start
		 * advertising parametric image description support in our
		 * color-management protocol implementation. */
		if (cprof != cm->sRGB_profile)
			weston_assert_not_reached(compositor, "we don't support parametric " \
						  "cprof's that are not the stock sRGB one");

		/* Stock sRGB color profile. TODO: when we add support for
		 * parametric color profiles, the stock sRGB will be crafted
		 * using parameters, instead of cmsCreate_sRGBProfileTHR()
		 * (which we currently use). So we'll get the parameters
		 * directly from it, instead of hardcoding as we are doing here.
		 * We don't get the parameters from the stock sRGB color profile
		 * because it is not trivial to retrieve that from LittleCMS. */

		/* Send the H.273 ColourPrimaries code point that matches the
		 * Rec709 primaries and the D65 white point. */
		primaries_info = weston_color_primaries_info_from(compositor,
								  WESTON_PRIMARIES_CICP_SRGB);
		weston_cm_send_primaries_named(cm_image_desc_info, primaries_info);

		/* These are the Rec709 primaries and D65 white point. */
		weston_cm_send_primaries(cm_image_desc_info,
					 &primaries_info->color_gamut);

		/* sRGB transfer function. */
		tf_info = weston_color_tf_info_from(compositor, WESTON_TF_GAMMA22);
		weston_cm_send_tf_named(cm_image_desc_info, tf_info);
	}

	return true;
}

void
cmlcms_destroy_color_profile(struct weston_color_profile *cprof_base)
{
	struct cmlcms_color_profile *cprof = to_cmlcms_cprof(cprof_base);

	cmlcms_color_profile_destroy(cprof);
}