From 1956e6fc903448a1d6dae8182e01dcc2503ceafd Mon Sep 17 00:00:00 2001
From: Richard Hughes <richard@hughsie.com>
Date: Wed, 3 Apr 2013 20:31:52 +0100
Subject: [PATCH 1/3] Add initial color management framework code

ICC profiles can now be specified in weston.ini for each output.
---
 configure.ac         |   7 +++
 src/Makefile.am      |   6 +-
 src/cms.c            | 106 ++++++++++++++++++++++++++++++++++
 src/cms.h            |  83 +++++++++++++++++++++++++++
 src/compositor-drm.c | 158 ++++++++++++++++++++++++++++++++++++++++++++++++++-
 src/compositor.h     |  26 +++++++++
 weston.ini           |   1 +
 7 files changed, 383 insertions(+), 4 deletions(-)
 create mode 100644 src/cms.c
 create mode 100644 src/cms.h

diff --git a/configure.ac b/configure.ac
index 71d0978..16ed8c9 100644
--- a/configure.ac
+++ b/configure.ac
@@ -258,6 +258,13 @@ if test "x$have_libunwind" = xyes; then
 fi
 AM_CONDITIONAL(HAVE_LIBUNWIND, [test "x$have_libunwind" = xyes])
 
+PKG_CHECK_MODULES(LCMS, lcms2,
+                  [have_lcms=yes], [have_lcms=no])
+if test "x$have_lcms" = xyes; then
+       AC_DEFINE(HAVE_LCMS, 1, [Have lcms support])
+fi
+AM_CONDITIONAL(HAVE_LCMS, [test "x$have_lcms" = xyes])
+
 WAYLAND_SCANNER_RULES(['$(top_srcdir)/protocol'])
 
 AC_CONFIG_FILES([Makefile
diff --git a/src/Makefile.am b/src/Makefile.am
index 1839a0e..02d6183 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -8,8 +8,8 @@ AM_CPPFLAGS =					\
 	-DLIBEXECDIR='"$(libexecdir)"'
 
 weston_LDFLAGS = -export-dynamic
-weston_CFLAGS = $(GCC_CFLAGS) $(COMPOSITOR_CFLAGS) $(LIBUNWIND_CFLAGS)
-weston_LDADD = $(COMPOSITOR_LIBS) $(LIBUNWIND_LIBS) \
+weston_CFLAGS = $(GCC_CFLAGS) $(COMPOSITOR_CFLAGS) $(LIBUNWIND_CFLAGS) $(LCMS_CFLAGS)
+weston_LDADD = $(COMPOSITOR_LIBS) $(LIBUNWIND_LIBS) $(LCMS_LIBS) \
 	$(DLOPEN_LIBS) -lm ../shared/libshared.la
 
 weston_SOURCES =				\
@@ -19,6 +19,8 @@ weston_SOURCES =				\
 	compositor.h				\
 	filter.c				\
 	filter.h				\
+	cms.c					\
+	cms.h					\
 	screenshooter.c				\
 	screenshooter-protocol.c		\
 	screenshooter-server-protocol.h		\
diff --git a/src/cms.c b/src/cms.c
new file mode 100644
index 0000000..bb6cce4
--- /dev/null
+++ b/src/cms.c
@@ -0,0 +1,106 @@
+/*
+ * Copyright © 2013 Richard Hughes
+ *
+ * Permission to use, copy, modify, distribute, and sell this software and
+ * its documentation for any purpose is hereby granted without fee, provided
+ * that the above copyright notice appear in all copies and that both that
+ * copyright notice and this permission notice appear in supporting
+ * documentation, and that the name of the copyright holders not be used in
+ * advertising or publicity pertaining to distribution of the software
+ * without specific, written prior permission.  The copyright holders make
+ * no representations about the suitability of this software for any
+ * purpose.  It is provided "as is" without express or implied warranty.
+ *
+ * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
+ * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
+ * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
+ * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+ * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+#ifdef HAVE_LCMS
+#include <lcms2.h>
+#endif
+
+#include "compositor.h"
+#include "cms.h"
+
+WL_EXPORT int
+weston_cms_output_added(struct weston_compositor *ec,
+			struct weston_output *o,
+			enum weston_color_manager_flags flags)
+{
+	if (!ec->cms)
+		return 0;
+	if (!ec->cms->output_added)
+		return 0;
+	return ec->cms->output_added(ec->cms, o, flags);
+}
+
+WL_EXPORT int
+weston_cms_output_removed(struct weston_compositor *ec,
+			  struct weston_output *o,
+			  enum weston_color_manager_flags flags)
+{
+	if (!ec->cms)
+		return 0;
+	if (!ec->cms->output_removed)
+		return 0;
+	return ec->cms->output_removed(ec->cms, o, flags);
+}
+
+WL_EXPORT void
+weston_cms_destroy_profile(struct weston_color_profile *p)
+{
+	if (!p)
+		return;
+	if (!p->destroy)
+		return;
+	p->destroy(p);
+}
+
+#ifdef HAVE_LCMS
+static void
+weston_cms_local_profile_destroy(struct weston_color_profile *p)
+{
+	cmsCloseProfile(p->lcms_handle);
+	free(p->filename);
+	free(p);
+}
+#endif
+
+/* if retval == 0 then @p is set, free with weston_cms_destroy_profile() */
+WL_EXPORT int
+weston_cms_create_local_profile(const char *filename,
+				struct weston_color_profile **p)
+{
+#ifdef HAVE_LCMS
+	int rc = 0;
+	cmsHPROFILE lcms_profile;
+
+	lcms_profile = cmsOpenProfileFromFile(filename, "r");
+	if (!lcms_profile) {
+		rc = -1;
+		goto out;
+	}
+	*p = calloc(sizeof(struct weston_color_profile), 1);
+	(*p)->user_data = NULL;
+	(*p)->destroy = weston_cms_local_profile_destroy;
+	(*p)->filename = strdup(filename);
+	(*p)->lcms_handle = lcms_profile;
+out:
+	return rc;
+#else
+	return -1;
+#endif
+}
diff --git a/src/cms.h b/src/cms.h
new file mode 100644
index 0000000..cead2c7
--- /dev/null
+++ b/src/cms.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright © 2013 Richard Hughes
+ *
+ * Permission to use, copy, modify, distribute, and sell this software and
+ * its documentation for any purpose is hereby granted without fee, provided
+ * that the above copyright notice appear in all copies and that both that
+ * copyright notice and this permission notice appear in supporting
+ * documentation, and that the name of the copyright holders not be used in
+ * advertising or publicity pertaining to distribution of the software
+ * without specific, written prior permission.  The copyright holders make
+ * no representations about the suitability of this software for any
+ * purpose.  It is provided "as is" without express or implied warranty.
+ *
+ * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
+ * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
+ * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
+ * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+ * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#ifndef _WESTON_CMS_H_
+#define _WESTON_CMS_H_
+
+#include "compositor.h"
+
+/* General overview on how to be a CMS plugin:
+ *
+ * First, some nomenclature:
+ *
+ *  CMF:       Color management framework, i.e. "Use foo.icc for device $bar"
+ *  CMM:       Color management module that converts pixel colors, which is
+ *             usually lcms2 on any modern OS.
+ *  CMS:       Color management system that encompasses both a CMF and CMM.
+ *  ICC:       International Color Consortium, the people that define the
+ *             binary encoding of a .icc file.
+ *  VCGT:      Video Card Gamma Tag. An Apple extension to the ICC specification
+ *             that allows the calibration state to be stored in the ICC profile
+ *  Output:    Physical port with a display attached, e.g. LVDS1
+ *
+ * As a CMF is probably something you don't want or need on an embeded install
+ * these functions will not be called if the icc_profile key is set for a
+ * specific [output] section in weston.ini
+ *
+ * Most desktop environments want the CMF to decide what profile to use in
+ * different situations, so that displays can be profiled and also so that
+ * the ICC profiles can be changed at runtime depending on the task or ambient
+ * environment.
+ *
+ * The CMF can be selected using the 'cms' key in the [core] section.
+ * More than one CMF being specified is alowed, but will lead to problems if
+ * both try to assign profiles for the same outputs.
+ *
+ * The general idea is the compositor creates an output which is registered
+ * with the CMS using weston_cms_output_added(). This is expected to call
+ * the ->set_color_profile() vfunc on the output with the prepared object
+ * of type weston_color_profile, or NULL if there is no color profile to apply.
+ *
+ * If the CMF can detect that the assigned ICC profile has changed for a
+ * specific output, then it can call the ->set_color_profile() vfunc at any
+ * time until weston_cms_output_removed() is called.
+ *
+ * The set_color_profile() vfunc is expected to set the output calibration
+ * state, typically by uploading the VCGT data to the graphics card using
+ * drmModeCrtcSetGamma()
+ */
+
+int
+weston_cms_output_added(struct weston_compositor *ec,
+			struct weston_output *o,
+			enum weston_color_manager_flags flags);
+int
+weston_cms_output_removed(struct weston_compositor *ec,
+			  struct weston_output *o,
+			  enum weston_color_manager_flags flags);
+int
+weston_cms_create_local_profile(const char *filename,
+			        struct weston_color_profile **p);
+void
+weston_cms_destroy_profile(struct weston_color_profile *p);
+
+#endif
diff --git a/src/compositor-drm.c b/src/compositor-drm.c
index f055118..4f8f856 100644
--- a/src/compositor-drm.c
+++ b/src/compositor-drm.c
@@ -21,6 +21,10 @@
  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  */
 
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
 #define _GNU_SOURCE
 
 #include <errno.h>
@@ -30,6 +34,9 @@
 #include <unistd.h>
 #include <linux/input.h>
 #include <assert.h>
+#ifdef HAVE_LCMS
+#include <lcms2.h>
+#endif
 
 #include <xf86drm.h>
 #include <xf86drmMode.h>
@@ -42,11 +49,13 @@
 #include "compositor.h"
 #include "evdev.h"
 #include "launcher-util.h"
+#include "cms.h"
 
 static int option_current_mode = 0;
 static char *output_name;
 static char *output_mode;
 static char *output_transform;
+static char *output_icc_profile;
 static struct wl_list configured_output_list;
 
 enum output_config {
@@ -66,6 +75,7 @@ struct drm_configured_output {
 	drmModeModeInfo crtc_mode;
 	enum output_config config;
 	struct wl_list link;
+	struct weston_color_profile *color_profile;
 };
 
 struct drm_compositor {
@@ -140,6 +150,7 @@ struct drm_output {
 	int current_cursor;
 	struct drm_fb *current, *next;
 	struct backlight *backlight;
+	struct weston_color_profile *color_profile;
 };
 
 /*
@@ -371,6 +382,102 @@ drm_output_render(struct drm_output *output, pixman_region32_t *damage)
 }
 
 static void
+drm_output_set_color_profile(struct weston_output *output_base,
+			     struct weston_color_profile *profile)
+{
+	struct drm_output *output = (struct drm_output *) output_base;
+#ifdef HAVE_LCMS
+	struct drm_compositor *compositor = (struct drm_compositor *) output->base.compositor;
+	cmsFloat32Number in;
+	const cmsToneCurve **vcgt;
+	int i;
+	int rc;
+	int size;
+	uint16_t *red = NULL;
+	uint16_t *green = NULL;
+	uint16_t *blue = NULL;
+#endif
+
+	/* save new profile */
+	if (output->color_profile == profile)
+		return;
+	if (output->color_profile)
+		weston_cms_destroy_profile(output->color_profile);
+	output->color_profile = profile;
+
+	/* anything to apply */
+	if (!output->color_profile)
+		return;
+	if (!output->original_crtc)
+		return;
+	weston_log("Using ICC profile %s\n",
+		   output->color_profile->filename);
+#ifdef HAVE_LCMS
+	vcgt = cmsReadTag (output->color_profile->lcms_handle, cmsSigVcgtTag);
+	if (vcgt == NULL || vcgt[0] == NULL)
+		return;
+
+	size = output->original_crtc->gamma_size;
+	red = calloc(sizeof(uint16_t), size);
+	green = calloc(sizeof(uint16_t), size);
+	blue = calloc(sizeof(uint16_t), size);
+	for (i = 0; i < size; i++) {
+		in = (cmsFloat32Number) i / (cmsFloat32Number) (size - 1);
+		red[i] = cmsEvalToneCurveFloat(vcgt[0], in) * (double) 0xffff;
+		green[i] = cmsEvalToneCurveFloat(vcgt[1], in) * (double) 0xffff;
+		blue[i] = cmsEvalToneCurveFloat(vcgt[2], in) * (double) 0xffff;
+	}
+	rc = drmModeCrtcSetGamma(compositor->drm.fd,
+				 output->crtc_id,
+				 size,
+				 red, green, blue);
+	if (rc)
+		weston_log("set gamma failed: %m\n");
+
+	free(red);
+	free(green);
+	free(blue);
+#endif
+}
+
+static void
+drm_output_gamma_reset(struct drm_compositor *compositor,
+		       struct drm_output *output)
+{
+	int i;
+	int ret;
+	int size;
+	uint16_t *blue = NULL;
+	uint16_t *green = NULL;
+	uint16_t *red = NULL;
+	uint32_t tmp;
+
+	if (!output->color_profile)
+		return;
+	if (!output->original_crtc)
+		return;
+
+	size = output->original_crtc->gamma_size;
+	red = calloc(sizeof(uint16_t), size);
+	green = calloc(sizeof(uint16_t), size);
+	blue = calloc(sizeof(uint16_t), size);
+	for (i = 0; i < size; i++) {
+		tmp = (uint32_t) 0xffff * (uint32_t) i / (uint32_t) (size - 1);
+		red[i] = green[i] = blue[i] = tmp;
+	}
+	ret = drmModeCrtcSetGamma(compositor->drm.fd,
+				  output->crtc_id,
+				  size,
+				  red, green, blue);
+	if (ret)
+		weston_log("reset gamma failed: %m\n");
+
+	free(red);
+	free(green);
+	free(blue);
+}
+
+static void
 drm_output_repaint(struct weston_output *output_base,
 		   pixman_region32_t *damage)
 {
@@ -396,6 +503,7 @@ drm_output_repaint(struct weston_output *output_base,
 			weston_log("set mode failed: %m\n");
 			return;
 		}
+		drm_output_set_color_profile(output_base, output->color_profile);
 	}
 
 	if (drmModePageFlip(compositor->drm.fd, output->crtc_id,
@@ -867,7 +975,11 @@ drm_output_destroy(struct weston_output *output_base)
 	/* Turn off hardware cursor */
 	drmModeSetCursor(c->drm.fd, output->crtc_id, 0, 0, 0);
 
+	/* Remove CMS device */
+	weston_cms_output_removed(&c->base, &output->base, 0);
+
 	/* Restore original CRTC state */
+	drm_output_gamma_reset (c, output);
 	drmModeSetCrtc(c->drm.fd, origcrtc->crtc_id, origcrtc->buffer_id,
 		       origcrtc->x, origcrtc->y,
 		       &output->connector_id, 1, &origcrtc->mode);
@@ -1332,6 +1444,7 @@ create_output_for_connector(struct drm_compositor *ec,
 	int i;
 	char name[32];
 	const char *type_name;
+	enum weston_color_manager_flags cm_flags = 0;
 
 	i = find_crtc_for_connector(ec, resources, connector);
 	if (i < 0) {
@@ -1398,6 +1511,18 @@ create_output_for_connector(struct drm_compositor *ec,
 		}
 	}
 
+	/* get the ICC profile for the device from the CMS, *unless* there is
+	 * a hardcoded profile specified in [output] */
+	if (o && o->color_profile) {
+		weston_log("Using hardcoded ICC profile %s\n",
+			   o->color_profile->filename);
+		output->color_profile = o->color_profile;
+	} else {
+		weston_cms_output_added(&ec->base, &output->base, cm_flags);
+		if (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)
+			cm_flags &= WESTON_COLOR_MANAGER_FLAG_OUTPUT_INTERNAL;
+	}
+
 	if (o && o->config == OUTPUT_CONFIG_OFF) {
 		weston_log("Disabling output %s\n", o->name);
 
@@ -1488,6 +1613,8 @@ create_output_for_connector(struct drm_compositor *ec,
 		output->base.backlight_current = drm_get_backlight(output);
 	}
 
+	output->base.set_color_profile = drm_output_set_color_profile;
+
 	weston_output_init(&output->base, &ec->base, x, y,
 			   connector->mmWidth, connector->mmHeight,
 			   o ? o->transform : WL_OUTPUT_TRANSFORM_NORMAL);
@@ -2046,6 +2173,7 @@ evdev_input_destroy(struct weston_seat *seat_base)
 static void
 drm_free_configured_output(struct drm_configured_output *output)
 {
+	weston_cms_destroy_profile(output->color_profile);
 	free(output->name);
 	free(output->mode);
 	free(output);
@@ -2492,21 +2620,42 @@ drm_output_set_transform(struct drm_configured_output *output)
 }
 
 static void
+drm_output_set_icc_profile(struct drm_configured_output *output)
+{
+	int rc;
+
+	if (!output_icc_profile) {
+		output->color_profile = NULL;
+		return;
+	}
+	rc = weston_cms_create_local_profile(output_icc_profile,
+					     &output->color_profile);
+	if (rc == 0) {
+		weston_log("Using hardcoded profile \"%s\" for output %s\n",
+			   output_icc_profile, output_name);
+	} else {
+		weston_log("Failed to load profile \"%s\" for output %s\n",
+			   output_icc_profile, output_name);
+	}
+}
+
+static void
 output_section_done(void *data)
 {
 	struct drm_configured_output *output;
 
 	output = malloc(sizeof *output);
 
-	if (!output || !output_name || (output_name[0] == 'X') ||
-					(!output_mode && !output_transform)) {
+	if (!output || !output_name) {
 		free(output_name);
 		free(output_mode);
 		free(output_transform);
+		free(output_icc_profile);
 		free(output);
 		output_name = NULL;
 		output_mode = NULL;
 		output_transform = NULL;
+		output_icc_profile = NULL;
 		return;
 	}
 
@@ -2534,12 +2683,16 @@ output_section_done(void *data)
 	}
 
 	drm_output_set_transform(output);
+	drm_output_set_icc_profile(output);
 
 	wl_list_insert(&configured_output_list, &output->link);
 
 	if (output_transform)
 		free(output_transform);
 	output_transform = NULL;
+	if (output_icc_profile)
+		free(output_icc_profile);
+	output_icc_profile = NULL;
 }
 
 WL_EXPORT struct weston_compositor *
@@ -2564,6 +2717,7 @@ backend_init(struct wl_display *display, int argc, char *argv[],
 		{ "name", CONFIG_KEY_STRING, &output_name },
 		{ "mode", CONFIG_KEY_STRING, &output_mode },
 		{ "transform", CONFIG_KEY_STRING, &output_transform },
+		{ "icc_profile", CONFIG_KEY_STRING, &output_icc_profile },
 	};
 
 	const struct config_section config_section[] = {
diff --git a/src/compositor.h b/src/compositor.h
index 740009c..0172efd 100644
--- a/src/compositor.h
+++ b/src/compositor.h
@@ -151,6 +151,13 @@ enum dpms_enum {
 	WESTON_DPMS_OFF
 };
 
+struct weston_color_profile {
+	char	*filename;
+	void	*lcms_handle;
+	void	*user_data;
+	void	 (*destroy)		(struct weston_color_profile *p);
+};
+
 struct weston_output {
 	uint32_t id;
 
@@ -193,6 +200,8 @@ struct weston_output {
 	uint32_t backlight_current;
 	void (*set_backlight)(struct weston_output *output, uint32_t value);
 	void (*set_dpms)(struct weston_output *output, enum dpms_enum level);
+
+	void (*set_color_profile)(struct weston_output *output, struct weston_color_profile *profile);
 };
 
 struct weston_xkb_info {
@@ -282,6 +291,21 @@ struct weston_renderer {
 	void (*destroy_surface)(struct weston_surface *surface);
 };
 
+enum weston_color_manager_flags {
+	WESTON_COLOR_MANAGER_FLAG_OUTPUT_INTERNAL = 1,
+};
+
+struct weston_color_manager {
+	void	*state;
+	void	(*destroy)		(struct weston_compositor *c);
+	int	(*output_added)		(struct weston_color_manager *cm,
+					 struct weston_output *o,
+					 enum weston_color_manager_flags flags);
+	int	(*output_removed)	(struct weston_color_manager *cm,
+					 struct weston_output *o,
+					 enum weston_color_manager_flags flags);
+};
+
 struct weston_compositor {
 	struct wl_signal destroy_signal;
 
@@ -370,6 +394,8 @@ struct weston_compositor {
 	struct xkb_rule_names xkb_names;
 	struct xkb_context *xkb_context;
 	struct weston_xkb_info xkb_info;
+
+	struct weston_color_manager *cms;
 };
 
 struct weston_region {
diff --git a/weston.ini b/weston.ini
index 0015255..9edc30c 100644
--- a/weston.ini
+++ b/weston.ini
@@ -40,6 +40,7 @@ duration=600
 #name=LVDS1
 #mode=1680x1050
 #transform=90
+#icc_profile=/usr/share/color/icc/colord/Bluish.icc
 
 #[output]
 #name=VGA1
-- 
1.8.2

