e4e93d3c4da529226f1f4ba0367bc6fb292286be
[blender.git] / source / blender / imbuf / intern / colormanagement.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2012 by Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Xavier Thomas,
24  *                 Lukas Toenne,
25  *                 Sergey Sharybin
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  *
29  */
30
31 /** \file blender/imbuf/intern/colormanagement.c
32  *  \ingroup imbuf
33  */
34
35 #include "IMB_colormanagement.h"
36 #include "IMB_colormanagement_intern.h"
37
38 #include <string.h>
39 #include <math.h>
40
41 #include "DNA_color_types.h"
42 #include "DNA_image_types.h"
43 #include "DNA_movieclip_types.h"
44 #include "DNA_scene_types.h"
45 #include "DNA_space_types.h"
46
47 #include "IMB_imbuf.h"
48 #include "IMB_imbuf_types.h"
49 #include "IMB_filetype.h"
50 #include "IMB_moviecache.h"
51
52 #include "MEM_guardedalloc.h"
53
54 #include "BLI_blenlib.h"
55 #include "BLI_math.h"
56 #include "BLI_math_color.h"
57 #include "BLI_string.h"
58 #include "BLI_threads.h"
59 #include "BLI_rect.h"
60
61 #include "BKE_appdir.h"
62 #include "BKE_colortools.h"
63 #include "BKE_context.h"
64 #include "BKE_image.h"
65 #include "BKE_main.h"
66
67 #include "RNA_define.h"
68
69 #include <ocio_capi.h>
70
71 /*********************** Global declarations *************************/
72
73 #define DISPLAY_BUFFER_CHANNELS 4
74
75 /* ** list of all supported color spaces, displays and views */
76 static char global_role_scene_linear[MAX_COLORSPACE_NAME];
77 static char global_role_color_picking[MAX_COLORSPACE_NAME];
78 static char global_role_texture_painting[MAX_COLORSPACE_NAME];
79 static char global_role_default_byte[MAX_COLORSPACE_NAME];
80 static char global_role_default_float[MAX_COLORSPACE_NAME];
81 static char global_role_default_sequencer[MAX_COLORSPACE_NAME];
82
83 static ListBase global_colorspaces = {NULL, NULL};
84 static ListBase global_displays = {NULL, NULL};
85 static ListBase global_views = {NULL, NULL};
86 static ListBase global_looks = {NULL, NULL};
87
88 static int global_tot_colorspace = 0;
89 static int global_tot_display = 0;
90 static int global_tot_view = 0;
91 static int global_tot_looks = 0;
92
93 /* Set to ITU-BT.709 / sRGB primaries weight. Brute force stupid, but only
94  * option with no colormanagement in place.
95  */
96 float imbuf_luma_coefficients[3] = { 0.2126f, 0.7152f, 0.0722f };
97
98 /* lock used by pre-cached processors getters, so processor wouldn't
99  * be created several times
100  * LOCK_COLORMANAGE can not be used since this mutex could be needed to
101  * be locked before pre-cached processor are creating
102  */
103 static pthread_mutex_t processor_lock = BLI_MUTEX_INITIALIZER;
104
105 typedef struct ColormanageProcessor {
106         OCIO_ConstProcessorRcPtr *processor;
107         CurveMapping *curve_mapping;
108         bool is_data_result;
109 } ColormanageProcessor;
110
111 static struct global_glsl_state {
112         /* Actual processor used for GLSL baked LUTs. */
113         OCIO_ConstProcessorRcPtr *processor;
114
115         /* Settings of processor for comparison. */
116         char look[MAX_COLORSPACE_NAME];
117         char view[MAX_COLORSPACE_NAME];
118         char display[MAX_COLORSPACE_NAME];
119         char input[MAX_COLORSPACE_NAME];
120         float exposure, gamma;
121
122         CurveMapping *curve_mapping, *orig_curve_mapping;
123         bool use_curve_mapping;
124         int curve_mapping_timestamp;
125         OCIO_CurveMappingSettings curve_mapping_settings;
126
127         /* Container for GLSL state needed for OCIO module. */
128         struct OCIO_GLSLDrawState *ocio_glsl_state;
129         struct OCIO_GLSLDrawState *transform_ocio_glsl_state;
130 } global_glsl_state;
131
132 /*********************** Color managed cache *************************/
133
134 /* Cache Implementation Notes
135  * ==========================
136  *
137  * All color management cache stuff is stored in two properties of
138  * image buffers:
139  *
140  *   1. display_buffer_flags
141  *
142  *      This is a bit field which used to mark calculated transformations
143  *      for particular image buffer. Index inside of this array means index
144  *      of a color managed display. Element with given index matches view
145  *      transformations applied for a given display. So if bit B of array
146  *      element B is set to 1, this means display buffer with display index
147  *      of A and view transform of B was ever calculated for this imbuf.
148  *
149  *      In contrast with indices in global lists of displays and views this
150  *      indices are 0-based, not 1-based. This is needed to save some bytes
151  *      of memory.
152  *
153  *   2. colormanage_cache
154  *
155  *      This is a pointer to a structure which holds all data which is
156  *      needed for color management cache to work.
157  *
158  *      It contains two parts:
159  *        - data
160  *        - moviecache
161  *
162  *      Data field is used to store additional information about cached
163  *      buffers which affects on whether cached buffer could be used.
164  *      This data can't go to cache key because changes in this data
165  *      shouldn't lead extra buffers adding to cache, it shall
166  *      invalidate cached images.
167  *
168  *      Currently such a data contains only exposure and gamma, but
169  *      would likely extended further.
170  *
171  *      data field is not null only for elements of cache, not used for
172  *      original image buffers.
173  *
174  *      Color management cache is using generic MovieCache implementation
175  *      to make it easier to deal with memory limitation.
176  *
177  *      Currently color management is using the same memory limitation
178  *      pool as sequencer and clip editor are using which means color
179  *      managed buffers would be removed from the cache as soon as new
180  *      frames are loading for the movie clip and there's no space in
181  *      cache.
182  *
183  *      Every image buffer has got own movie cache instance, which
184  *      means keys for color managed buffers could be really simple
185  *      and look up in this cache would be fast and independent from
186  *      overall amount of color managed images.
187  */
188
189 /* NOTE: ColormanageCacheViewSettings and ColormanageCacheDisplaySettings are
190  *       quite the same as ColorManagedViewSettings and ColorManageDisplaySettings
191  *       but they holds indexes of all transformations and color spaces, not
192  *       their names.
193  *
194  *       This helps avoid extra colorspace / display / view lookup without
195  *       requiring to pass all variables which affects on display buffer
196  *       to color management cache system and keeps calls small and nice.
197  */
198 typedef struct ColormanageCacheViewSettings {
199         int flag;
200         int look;
201         int view;
202         float exposure;
203         float gamma;
204         float dither;
205         CurveMapping *curve_mapping;
206 } ColormanageCacheViewSettings;
207
208 typedef struct ColormanageCacheDisplaySettings {
209         int display;
210 } ColormanageCacheDisplaySettings;
211
212 typedef struct ColormanageCacheKey {
213         int view;            /* view transformation used for display buffer */
214         int display;         /* display device name */
215 } ColormanageCacheKey;
216
217 typedef struct ColormnaageCacheData {
218         int flag;        /* view flags of cached buffer */
219         int look;        /* Additional artistics transform */
220         float exposure;  /* exposure value cached buffer is calculated with */
221         float gamma;     /* gamma value cached buffer is calculated with */
222         float dither;    /* dither value cached buffer is calculated with */
223         CurveMapping *curve_mapping;  /* curve mapping used for cached buffer */
224         int curve_mapping_timestamp;  /* time stamp of curve mapping used for cached buffer */
225 } ColormnaageCacheData;
226
227 typedef struct ColormanageCache {
228         struct MovieCache *moviecache;
229
230         ColormnaageCacheData *data;
231 } ColormanageCache;
232
233 static struct MovieCache *colormanage_moviecache_get(const ImBuf *ibuf)
234 {
235         if (!ibuf->colormanage_cache)
236                 return NULL;
237
238         return ibuf->colormanage_cache->moviecache;
239 }
240
241 static ColormnaageCacheData *colormanage_cachedata_get(const ImBuf *ibuf)
242 {
243         if (!ibuf->colormanage_cache)
244                 return NULL;
245
246         return ibuf->colormanage_cache->data;
247 }
248
249 static unsigned int colormanage_hashhash(const void *key_v)
250 {
251         const ColormanageCacheKey *key = key_v;
252
253         unsigned int rval = (key->display << 16) | (key->view % 0xffff);
254
255         return rval;
256 }
257
258 static bool colormanage_hashcmp(const void *av, const void *bv)
259 {
260         const ColormanageCacheKey *a = av;
261         const ColormanageCacheKey *b = bv;
262
263         return ((a->view != b->view) ||
264                 (a->display != b->display));
265 }
266
267 static struct MovieCache *colormanage_moviecache_ensure(ImBuf *ibuf)
268 {
269         if (!ibuf->colormanage_cache)
270                 ibuf->colormanage_cache = MEM_callocN(sizeof(ColormanageCache), "imbuf colormanage cache");
271
272         if (!ibuf->colormanage_cache->moviecache) {
273                 struct MovieCache *moviecache;
274
275                 moviecache = IMB_moviecache_create("colormanage cache", sizeof(ColormanageCacheKey),
276                                                    colormanage_hashhash, colormanage_hashcmp);
277
278                 ibuf->colormanage_cache->moviecache = moviecache;
279         }
280
281         return ibuf->colormanage_cache->moviecache;
282 }
283
284 static void colormanage_cachedata_set(ImBuf *ibuf, ColormnaageCacheData *data)
285 {
286         if (!ibuf->colormanage_cache)
287                 ibuf->colormanage_cache = MEM_callocN(sizeof(ColormanageCache), "imbuf colormanage cache");
288
289         ibuf->colormanage_cache->data = data;
290 }
291
292 static void colormanage_view_settings_to_cache(ImBuf *ibuf,
293                                                ColormanageCacheViewSettings *cache_view_settings,
294                                                const ColorManagedViewSettings *view_settings)
295 {
296         int look = IMB_colormanagement_look_get_named_index(view_settings->look);
297         int view = IMB_colormanagement_view_get_named_index(view_settings->view_transform);
298
299         cache_view_settings->look = look;
300         cache_view_settings->view = view;
301         cache_view_settings->exposure = view_settings->exposure;
302         cache_view_settings->gamma = view_settings->gamma;
303         cache_view_settings->dither = ibuf->dither;
304         cache_view_settings->flag = view_settings->flag;
305         cache_view_settings->curve_mapping = view_settings->curve_mapping;
306 }
307
308 static void colormanage_display_settings_to_cache(ColormanageCacheDisplaySettings *cache_display_settings,
309                                                   const ColorManagedDisplaySettings *display_settings)
310 {
311         int display = IMB_colormanagement_display_get_named_index(display_settings->display_device);
312
313         cache_display_settings->display = display;
314 }
315
316 static void colormanage_settings_to_key(ColormanageCacheKey *key,
317                                         const ColormanageCacheViewSettings *view_settings,
318                                         const ColormanageCacheDisplaySettings *display_settings)
319 {
320         key->view = view_settings->view;
321         key->display = display_settings->display;
322 }
323
324 static ImBuf *colormanage_cache_get_ibuf(ImBuf *ibuf, ColormanageCacheKey *key, void **cache_handle)
325 {
326         ImBuf *cache_ibuf;
327         struct MovieCache *moviecache = colormanage_moviecache_get(ibuf);
328
329         if (!moviecache) {
330                 /* if there's no moviecache it means no color management was applied on given image buffer before */
331
332                 return NULL;
333         }
334
335         *cache_handle = NULL;
336
337         cache_ibuf = IMB_moviecache_get(moviecache, key);
338
339         *cache_handle = cache_ibuf;
340
341         return cache_ibuf;
342 }
343
344 static unsigned char *colormanage_cache_get(ImBuf *ibuf, const ColormanageCacheViewSettings *view_settings,
345                                             const ColormanageCacheDisplaySettings *display_settings,
346                                             void **cache_handle)
347 {
348         ColormanageCacheKey key;
349         ImBuf *cache_ibuf;
350         int view_flag = 1 << (view_settings->view - 1);
351         CurveMapping *curve_mapping = view_settings->curve_mapping;
352         int curve_mapping_timestamp = curve_mapping ? curve_mapping->changed_timestamp : 0;
353
354         colormanage_settings_to_key(&key, view_settings, display_settings);
355
356         /* check whether image was marked as dirty for requested transform */
357         if ((ibuf->display_buffer_flags[display_settings->display - 1] & view_flag) == 0) {
358                 return NULL;
359         }
360
361         cache_ibuf = colormanage_cache_get_ibuf(ibuf, &key, cache_handle);
362
363         if (cache_ibuf) {
364                 ColormnaageCacheData *cache_data;
365
366                 BLI_assert(cache_ibuf->x == ibuf->x &&
367                            cache_ibuf->y == ibuf->y);
368
369                 /* only buffers with different color space conversions are being stored
370                  * in cache separately. buffer which were used only different exposure/gamma
371                  * are re-suing the same cached buffer
372                  *
373                  * check here which exposure/gamma/curve was used for cached buffer and if they're
374                  * different from requested buffer should be re-generated
375                  */
376                 cache_data = colormanage_cachedata_get(cache_ibuf);
377
378                 if (cache_data->look != view_settings->look ||
379                     cache_data->exposure != view_settings->exposure ||
380                     cache_data->gamma != view_settings->gamma ||
381                     cache_data->dither != view_settings->dither ||
382                     cache_data->flag != view_settings->flag ||
383                     cache_data->curve_mapping != curve_mapping ||
384                     cache_data->curve_mapping_timestamp != curve_mapping_timestamp)
385                 {
386                         *cache_handle = NULL;
387
388                         IMB_freeImBuf(cache_ibuf);
389
390                         return NULL;
391                 }
392
393                 return (unsigned char *) cache_ibuf->rect;
394         }
395
396         return NULL;
397 }
398
399 static void colormanage_cache_put(ImBuf *ibuf, const ColormanageCacheViewSettings *view_settings,
400                                   const ColormanageCacheDisplaySettings *display_settings,
401                                   unsigned char *display_buffer, void **cache_handle)
402 {
403         ColormanageCacheKey key;
404         ImBuf *cache_ibuf;
405         ColormnaageCacheData *cache_data;
406         int view_flag = 1 << (view_settings->view - 1);
407         struct MovieCache *moviecache = colormanage_moviecache_ensure(ibuf);
408         CurveMapping *curve_mapping = view_settings->curve_mapping;
409         int curve_mapping_timestamp = curve_mapping ? curve_mapping->changed_timestamp : 0;
410
411         colormanage_settings_to_key(&key, view_settings, display_settings);
412
413         /* mark display buffer as valid */
414         ibuf->display_buffer_flags[display_settings->display - 1] |= view_flag;
415
416         /* buffer itself */
417         cache_ibuf = IMB_allocImBuf(ibuf->x, ibuf->y, ibuf->planes, 0);
418         cache_ibuf->rect = (unsigned int *) display_buffer;
419
420         cache_ibuf->mall |= IB_rect;
421         cache_ibuf->flags |= IB_rect;
422
423         /* store data which is needed to check whether cached buffer could be used for color managed display settings */
424         cache_data = MEM_callocN(sizeof(ColormnaageCacheData), "color manage cache imbuf data");
425         cache_data->look = view_settings->look;
426         cache_data->exposure = view_settings->exposure;
427         cache_data->gamma = view_settings->gamma;
428         cache_data->dither = view_settings->dither;
429         cache_data->flag = view_settings->flag;
430         cache_data->curve_mapping = curve_mapping;
431         cache_data->curve_mapping_timestamp = curve_mapping_timestamp;
432
433         colormanage_cachedata_set(cache_ibuf, cache_data);
434
435         *cache_handle = cache_ibuf;
436
437         IMB_moviecache_put(moviecache, &key, cache_ibuf);
438 }
439
440 static void colormanage_cache_handle_release(void *cache_handle)
441 {
442         ImBuf *cache_ibuf = cache_handle;
443
444         IMB_freeImBuf(cache_ibuf);
445 }
446
447 /*********************** Initialization / De-initialization *************************/
448
449 static void colormanage_role_color_space_name_get(OCIO_ConstConfigRcPtr *config, char *colorspace_name, const char *role, const char *backup_role)
450 {
451         OCIO_ConstColorSpaceRcPtr *ociocs;
452
453         ociocs = OCIO_configGetColorSpace(config, role);
454
455         if (!ociocs && backup_role)
456                 ociocs = OCIO_configGetColorSpace(config, backup_role);
457
458         if (ociocs) {
459                 const char *name = OCIO_colorSpaceGetName(ociocs);
460
461                 /* assume function was called with buffer properly allocated to MAX_COLORSPACE_NAME chars */
462                 BLI_strncpy(colorspace_name, name, MAX_COLORSPACE_NAME);
463                 OCIO_colorSpaceRelease(ociocs);
464         }
465         else {
466                 printf("Color management: Error could not find role %s role.\n", role);
467         }
468 }
469
470 static void colormanage_load_config(OCIO_ConstConfigRcPtr *config)
471 {
472         int tot_colorspace, tot_display, tot_display_view, tot_looks;
473         int index, viewindex, viewindex2;
474         const char *name;
475
476         /* get roles */
477         colormanage_role_color_space_name_get(config, global_role_scene_linear, OCIO_ROLE_SCENE_LINEAR, NULL);
478         colormanage_role_color_space_name_get(config, global_role_color_picking, OCIO_ROLE_COLOR_PICKING, NULL);
479         colormanage_role_color_space_name_get(config, global_role_texture_painting, OCIO_ROLE_TEXTURE_PAINT, NULL);
480         colormanage_role_color_space_name_get(config, global_role_default_sequencer, OCIO_ROLE_DEFAULT_SEQUENCER, OCIO_ROLE_SCENE_LINEAR);
481         colormanage_role_color_space_name_get(config, global_role_default_byte, OCIO_ROLE_DEFAULT_BYTE, OCIO_ROLE_TEXTURE_PAINT);
482         colormanage_role_color_space_name_get(config, global_role_default_float, OCIO_ROLE_DEFAULT_FLOAT, OCIO_ROLE_SCENE_LINEAR);
483
484         /* load colorspaces */
485         tot_colorspace = OCIO_configGetNumColorSpaces(config);
486         for (index = 0 ; index < tot_colorspace; index++) {
487                 OCIO_ConstColorSpaceRcPtr *ocio_colorspace;
488                 const char *description;
489                 bool is_invertible, is_data;
490
491                 name = OCIO_configGetColorSpaceNameByIndex(config, index);
492
493                 ocio_colorspace = OCIO_configGetColorSpace(config, name);
494                 description = OCIO_colorSpaceGetDescription(ocio_colorspace);
495                 is_invertible = OCIO_colorSpaceIsInvertible(ocio_colorspace);
496                 is_data = OCIO_colorSpaceIsData(ocio_colorspace);
497
498                 colormanage_colorspace_add(name, description, is_invertible, is_data);
499
500                 OCIO_colorSpaceRelease(ocio_colorspace);
501         }
502
503         /* load displays */
504         viewindex2 = 0;
505         tot_display = OCIO_configGetNumDisplays(config);
506
507         for (index = 0 ; index < tot_display; index++) {
508                 const char *displayname;
509                 ColorManagedDisplay *display;
510
511                 displayname = OCIO_configGetDisplay(config, index);
512
513                 display = colormanage_display_add(displayname);
514
515                 /* load views */
516                 tot_display_view = OCIO_configGetNumViews(config, displayname);
517                 for (viewindex = 0 ; viewindex < tot_display_view; viewindex++, viewindex2++) {
518                         const char *viewname;
519                         ColorManagedView *view;
520                         LinkData *display_view;
521
522                         viewname = OCIO_configGetView(config, displayname, viewindex);
523
524                         /* first check if view transform with given name was already loaded */
525                         view = colormanage_view_get_named(viewname);
526
527                         if (!view) {
528                                 view = colormanage_view_add(viewname);
529                         }
530
531                         display_view = BLI_genericNodeN(view);
532
533                         BLI_addtail(&display->views, display_view);
534                 }
535         }
536
537         global_tot_display = tot_display;
538
539         /* load looks */
540         tot_looks = OCIO_configGetNumLooks(config);
541         colormanage_look_add("None", "", true);
542         for (index = 0; index < tot_looks; index++) {
543                 OCIO_ConstLookRcPtr *ocio_look;
544                 const char *process_space;
545
546                 name = OCIO_configGetLookNameByIndex(config, index);
547                 ocio_look = OCIO_configGetLook(config, name);
548                 process_space = OCIO_lookGetProcessSpace(ocio_look);
549                 OCIO_lookRelease(ocio_look);
550
551                 colormanage_look_add(name, process_space, false);
552         }
553
554         /* Load luminance coefficients. */
555         OCIO_configGetDefaultLumaCoefs(config, imbuf_luma_coefficients);
556 }
557
558 static void colormanage_free_config(void)
559 {
560         ColorSpace *colorspace;
561         ColorManagedDisplay *display;
562
563         /* free color spaces */
564         colorspace = global_colorspaces.first;
565         while (colorspace) {
566                 ColorSpace *colorspace_next = colorspace->next;
567
568                 /* free precomputer processors */
569                 if (colorspace->to_scene_linear)
570                         OCIO_processorRelease((OCIO_ConstProcessorRcPtr *) colorspace->to_scene_linear);
571
572                 if (colorspace->from_scene_linear)
573                         OCIO_processorRelease((OCIO_ConstProcessorRcPtr *) colorspace->from_scene_linear);
574
575                 /* free color space itself */
576                 MEM_freeN(colorspace);
577
578                 colorspace = colorspace_next;
579         }
580         BLI_listbase_clear(&global_colorspaces);
581         global_tot_colorspace = 0;
582
583         /* free displays */
584         display = global_displays.first;
585         while (display) {
586                 ColorManagedDisplay *display_next = display->next;
587
588                 /* free precomputer processors */
589                 if (display->to_scene_linear)
590                         OCIO_processorRelease((OCIO_ConstProcessorRcPtr *) display->to_scene_linear);
591
592                 if (display->from_scene_linear)
593                         OCIO_processorRelease((OCIO_ConstProcessorRcPtr *) display->from_scene_linear);
594
595                 /* free list of views */
596                 BLI_freelistN(&display->views);
597
598                 MEM_freeN(display);
599                 display = display_next;
600         }
601         BLI_listbase_clear(&global_displays);
602         global_tot_display = 0;
603
604         /* free views */
605         BLI_freelistN(&global_views);
606         global_tot_view = 0;
607
608         /* free looks */
609         BLI_freelistN(&global_looks);
610         global_tot_looks = 0;
611
612         OCIO_exit();
613 }
614
615 void colormanagement_init(void)
616 {
617         const char *ocio_env;
618         const char *configdir;
619         char configfile[FILE_MAX];
620         OCIO_ConstConfigRcPtr *config = NULL;
621
622         OCIO_init();
623
624         ocio_env = getenv("OCIO");
625
626         if (ocio_env && ocio_env[0] != '\0') {
627                 config = OCIO_configCreateFromEnv();
628                 if (config != NULL) {
629                         printf("Color management: Using %s as a configuration file\n", ocio_env);
630                 }
631         }
632
633         if (config == NULL) {
634                 configdir = BKE_appdir_folder_id(BLENDER_DATAFILES, "colormanagement");
635
636                 if (configdir) {
637                         BLI_join_dirfile(configfile, sizeof(configfile), configdir, BCM_CONFIG_FILE);
638
639 #ifdef WIN32
640                         {
641                                 /* quite a hack to support loading configuration from path with non-acii symbols */
642
643                                 char short_name[256];
644                                 BLI_get_short_name(short_name, configfile);
645                                 config = OCIO_configCreateFromFile(short_name);
646                         }
647 #else
648                         config = OCIO_configCreateFromFile(configfile);
649 #endif
650                 }
651         }
652
653         if (config == NULL) {
654                 printf("Color management: using fallback mode for management\n");
655
656                 config = OCIO_configCreateFallback();
657         }
658
659         if (config) {
660                 OCIO_setCurrentConfig(config);
661
662                 colormanage_load_config(config);
663
664                 OCIO_configRelease(config);
665         }
666
667         /* If there're no valid display/views, use fallback mode. */
668         if (global_tot_display == 0 || global_tot_view == 0) {
669                 printf("Color management: no displays/views in the config, using fallback mode instead\n");
670
671                 /* Free old config. */
672                 colormanage_free_config();
673
674                 /* Initialize fallback config. */
675                 config = OCIO_configCreateFallback();
676                 colormanage_load_config(config);
677         }
678
679         BLI_init_srgb_conversion();
680 }
681
682 void colormanagement_exit(void)
683 {
684         if (global_glsl_state.processor)
685                 OCIO_processorRelease(global_glsl_state.processor);
686
687         if (global_glsl_state.curve_mapping)
688                 curvemapping_free(global_glsl_state.curve_mapping);
689
690         if (global_glsl_state.curve_mapping_settings.lut)
691                 MEM_freeN(global_glsl_state.curve_mapping_settings.lut);
692
693         if (global_glsl_state.ocio_glsl_state)
694                 OCIO_freeOGLState(global_glsl_state.ocio_glsl_state);
695
696         if (global_glsl_state.transform_ocio_glsl_state)
697                 OCIO_freeOGLState(global_glsl_state.transform_ocio_glsl_state);
698
699         colormanage_free_config();
700 }
701
702 /*********************** Internal functions *************************/
703
704 void colormanage_cache_free(ImBuf *ibuf)
705 {
706         if (ibuf->display_buffer_flags) {
707                 MEM_freeN(ibuf->display_buffer_flags);
708
709                 ibuf->display_buffer_flags = NULL;
710         }
711
712         if (ibuf->colormanage_cache) {
713                 ColormnaageCacheData *cache_data = colormanage_cachedata_get(ibuf);
714                 struct MovieCache *moviecache = colormanage_moviecache_get(ibuf);
715
716                 if (cache_data) {
717                         MEM_freeN(cache_data);
718                 }
719
720                 if (moviecache) {
721                         IMB_moviecache_free(moviecache);
722                 }
723
724                 MEM_freeN(ibuf->colormanage_cache);
725
726                 ibuf->colormanage_cache = NULL;
727         }
728 }
729
730 void IMB_colormanagement_display_settings_from_ctx(const bContext *C,
731                                                    ColorManagedViewSettings **view_settings_r,
732                                                    ColorManagedDisplaySettings **display_settings_r)
733 {
734         Scene *scene = CTX_data_scene(C);
735         SpaceImage *sima = CTX_wm_space_image(C);
736
737         *view_settings_r = &scene->view_settings;
738         *display_settings_r = &scene->display_settings;
739
740         if (sima && sima->image) {
741                 if ((sima->image->flag & IMA_VIEW_AS_RENDER) == 0)
742                         *view_settings_r = NULL;
743         }
744 }
745
746 const char *IMB_colormanagement_get_display_colorspace_name(const ColorManagedViewSettings *view_settings,
747                                                             const ColorManagedDisplaySettings *display_settings)
748 {
749         OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
750
751         const char *display = display_settings->display_device;
752         const char *view = view_settings->view_transform;
753         const char *colorspace_name;
754
755         colorspace_name = OCIO_configGetDisplayColorSpaceName(config, display, view);
756
757         OCIO_configRelease(config);
758
759         return colorspace_name;
760 }
761
762 static ColorSpace *display_transform_get_colorspace(const ColorManagedViewSettings *view_settings,
763                                                     const ColorManagedDisplaySettings *display_settings)
764 {
765         const char *colorspace_name = IMB_colormanagement_get_display_colorspace_name(view_settings, display_settings);
766
767         if (colorspace_name)
768                 return colormanage_colorspace_get_named(colorspace_name);
769
770         return NULL;
771 }
772
773 static OCIO_ConstProcessorRcPtr *create_display_buffer_processor(const char *look,
774                                                                  const char *view_transform,
775                                                                  const char *display,
776                                                                  float exposure, float gamma,
777                                                                  const char *from_colorspace)
778 {
779         OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
780         OCIO_DisplayTransformRcPtr *dt;
781         OCIO_ConstProcessorRcPtr *processor;
782         ColorManagedLook *look_descr = colormanage_look_get_named(look);
783
784         dt = OCIO_createDisplayTransform();
785
786         OCIO_displayTransformSetInputColorSpaceName(dt, from_colorspace);
787         OCIO_displayTransformSetView(dt, view_transform);
788         OCIO_displayTransformSetDisplay(dt, display);
789
790         if (look_descr->is_noop == false) {
791                 OCIO_displayTransformSetLooksOverrideEnabled(dt, true);
792                 OCIO_displayTransformSetLooksOverride(dt, look);
793         }
794
795         /* fstop exposure control */
796         if (exposure != 0.0f) {
797                 OCIO_MatrixTransformRcPtr *mt;
798                 float gain = powf(2.0f, exposure);
799                 const float scale4f[] = {gain, gain, gain, 1.0f};
800                 float m44[16], offset4[4];
801
802                 OCIO_matrixTransformScale(m44, offset4, scale4f);
803                 mt = OCIO_createMatrixTransform();
804                 OCIO_matrixTransformSetValue(mt, m44, offset4);
805                 OCIO_displayTransformSetLinearCC(dt, (OCIO_ConstTransformRcPtr *) mt);
806
807                 OCIO_matrixTransformRelease(mt);
808         }
809
810         /* post-display gamma transform */
811         if (gamma != 1.0f) {
812                 OCIO_ExponentTransformRcPtr *et;
813                 float exponent = 1.0f / MAX2(FLT_EPSILON, gamma);
814                 const float exponent4f[] = {exponent, exponent, exponent, exponent};
815
816                 et = OCIO_createExponentTransform();
817                 OCIO_exponentTransformSetValue(et, exponent4f);
818                 OCIO_displayTransformSetDisplayCC(dt, (OCIO_ConstTransformRcPtr *) et);
819
820                 OCIO_exponentTransformRelease(et);
821         }
822
823         processor = OCIO_configGetProcessor(config, (OCIO_ConstTransformRcPtr *) dt);
824
825         OCIO_displayTransformRelease(dt);
826         OCIO_configRelease(config);
827
828         return processor;
829 }
830
831 static OCIO_ConstProcessorRcPtr *create_colorspace_transform_processor(const char *from_colorspace,
832                                                                        const char *to_colorspace)
833 {
834         OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
835         OCIO_ConstProcessorRcPtr *processor;
836
837         processor = OCIO_configGetProcessorWithNames(config, from_colorspace, to_colorspace);
838
839         OCIO_configRelease(config);
840
841         return processor;
842 }
843
844 static OCIO_ConstProcessorRcPtr *colorspace_to_scene_linear_processor(ColorSpace *colorspace)
845 {
846         if (colorspace->to_scene_linear == NULL) {
847                 BLI_mutex_lock(&processor_lock);
848
849                 if (colorspace->to_scene_linear == NULL) {
850                         OCIO_ConstProcessorRcPtr *to_scene_linear;
851                         to_scene_linear = create_colorspace_transform_processor(colorspace->name, global_role_scene_linear);
852                         colorspace->to_scene_linear = (struct OCIO_ConstProcessorRcPtr *) to_scene_linear;
853                 }
854
855                 BLI_mutex_unlock(&processor_lock);
856         }
857
858         return (OCIO_ConstProcessorRcPtr *) colorspace->to_scene_linear;
859 }
860
861 static OCIO_ConstProcessorRcPtr *colorspace_from_scene_linear_processor(ColorSpace *colorspace)
862 {
863         if (colorspace->from_scene_linear == NULL) {
864                 BLI_mutex_lock(&processor_lock);
865
866                 if (colorspace->from_scene_linear == NULL) {
867                         OCIO_ConstProcessorRcPtr *from_scene_linear;
868                         from_scene_linear = create_colorspace_transform_processor(global_role_scene_linear, colorspace->name);
869                         colorspace->from_scene_linear = (struct OCIO_ConstProcessorRcPtr *) from_scene_linear;
870                 }
871
872                 BLI_mutex_unlock(&processor_lock);
873         }
874
875         return (OCIO_ConstProcessorRcPtr *) colorspace->from_scene_linear;
876 }
877
878 static OCIO_ConstProcessorRcPtr *display_from_scene_linear_processor(ColorManagedDisplay *display)
879 {
880         if (display->from_scene_linear == NULL) {
881                 BLI_mutex_lock(&processor_lock);
882
883                 if (display->from_scene_linear == NULL) {
884                         const char *view_name = colormanage_view_get_default_name(display);
885                         OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
886                         OCIO_ConstProcessorRcPtr *processor = NULL;
887
888                         if (view_name && config) {
889                                 const char *view_colorspace = OCIO_configGetDisplayColorSpaceName(config, display->name, view_name);
890                                 processor = OCIO_configGetProcessorWithNames(config, global_role_scene_linear, view_colorspace);
891
892                                 OCIO_configRelease(config);
893                         }
894
895                         display->from_scene_linear = (struct OCIO_ConstProcessorRcPtr *) processor;
896                 }
897
898                 BLI_mutex_unlock(&processor_lock);
899         }
900
901         return (OCIO_ConstProcessorRcPtr *) display->from_scene_linear;
902 }
903
904 static OCIO_ConstProcessorRcPtr *display_to_scene_linear_processor(ColorManagedDisplay *display)
905 {
906         if (display->to_scene_linear == NULL) {
907                 BLI_mutex_lock(&processor_lock);
908
909                 if (display->to_scene_linear == NULL) {
910                         const char *view_name = colormanage_view_get_default_name(display);
911                         OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
912                         OCIO_ConstProcessorRcPtr *processor = NULL;
913
914                         if (view_name && config) {
915                                 const char *view_colorspace = OCIO_configGetDisplayColorSpaceName(config, display->name, view_name);
916                                 processor = OCIO_configGetProcessorWithNames(config, view_colorspace, global_role_scene_linear);
917
918                                 OCIO_configRelease(config);
919                         }
920
921                         display->to_scene_linear = (struct OCIO_ConstProcessorRcPtr *) processor;
922                 }
923
924                 BLI_mutex_unlock(&processor_lock);
925         }
926
927         return (OCIO_ConstProcessorRcPtr *) display->to_scene_linear;
928 }
929
930 static void init_default_view_settings(const ColorManagedDisplaySettings *display_settings,
931                                        ColorManagedViewSettings *view_settings)
932 {
933         ColorManagedDisplay *display;
934         ColorManagedView *default_view = NULL;
935
936         display = colormanage_display_get_named(display_settings->display_device);
937
938         if (display)
939                 default_view = colormanage_view_get_default(display);
940
941         if (default_view)
942                 BLI_strncpy(view_settings->view_transform, default_view->name, sizeof(view_settings->view_transform));
943         else
944                 view_settings->view_transform[0] = '\0';
945
946         BLI_strncpy(view_settings->look, "None", sizeof(view_settings->look));
947         view_settings->flag = 0;
948         view_settings->gamma = 1.0f;
949         view_settings->exposure = 0.0f;
950         view_settings->curve_mapping = NULL;
951 }
952
953 static void curve_mapping_apply_pixel(CurveMapping *curve_mapping, float *pixel, int channels)
954 {
955         if (channels == 1) {
956                 pixel[0] = curvemap_evaluateF(curve_mapping->cm, pixel[0]);
957         }
958         else if (channels == 2) {
959                 pixel[0] = curvemap_evaluateF(curve_mapping->cm, pixel[0]);
960                 pixel[1] = curvemap_evaluateF(curve_mapping->cm, pixel[1]);
961         }
962         else {
963                 curvemapping_evaluate_premulRGBF(curve_mapping, pixel, pixel);
964         }
965 }
966
967 void colorspace_set_default_role(char *colorspace, int size, int role)
968 {
969         if (colorspace && colorspace[0] == '\0') {
970                 const char *role_colorspace;
971
972                 role_colorspace = IMB_colormanagement_role_colorspace_name_get(role);
973
974                 BLI_strncpy(colorspace, role_colorspace, size);
975         }
976 }
977
978 void colormanage_imbuf_set_default_spaces(ImBuf *ibuf)
979 {
980         ibuf->rect_colorspace = colormanage_colorspace_get_named(global_role_default_byte);
981 }
982
983 void colormanage_imbuf_make_linear(ImBuf *ibuf, const char *from_colorspace)
984 {
985         ColorSpace *colorspace = colormanage_colorspace_get_named(from_colorspace);
986
987         if (colorspace && colorspace->is_data) {
988                 ibuf->colormanage_flag |= IMB_COLORMANAGE_IS_DATA;
989                 return;
990         }
991
992         if (ibuf->rect_float) {
993                 const char *to_colorspace = global_role_scene_linear;
994
995                 if (ibuf->rect)
996                         imb_freerectImBuf(ibuf);
997
998                 IMB_colormanagement_transform(ibuf->rect_float, ibuf->x, ibuf->y, ibuf->channels,
999                                               from_colorspace, to_colorspace, true);
1000         }
1001 }
1002
1003 /*********************** Generic functions *************************/
1004
1005 static void colormanage_check_display_settings(ColorManagedDisplaySettings *display_settings, const char *what,
1006                                                const ColorManagedDisplay *default_display)
1007 {
1008         if (display_settings->display_device[0] == '\0') {
1009                 BLI_strncpy(display_settings->display_device, default_display->name, sizeof(display_settings->display_device));
1010         }
1011         else {
1012                 ColorManagedDisplay *display = colormanage_display_get_named(display_settings->display_device);
1013
1014                 if (!display) {
1015                         printf("Color management: display \"%s\" used by %s not found, setting to default (\"%s\").\n",
1016                                display_settings->display_device, what, default_display->name);
1017
1018                         BLI_strncpy(display_settings->display_device, default_display->name,
1019                                     sizeof(display_settings->display_device));
1020                 }
1021         }
1022 }
1023
1024 static void colormanage_check_view_settings(ColorManagedDisplaySettings *display_settings,
1025                                             ColorManagedViewSettings *view_settings, const char *what)
1026 {
1027         ColorManagedDisplay *display;
1028         ColorManagedView *default_view = NULL;
1029         ColorManagedLook *default_look = (ColorManagedLook *) global_looks.first;
1030
1031         if (view_settings->view_transform[0] == '\0') {
1032                 display = colormanage_display_get_named(display_settings->display_device);
1033
1034                 if (display)
1035                         default_view = colormanage_view_get_default(display);
1036
1037                 if (default_view)
1038                         BLI_strncpy(view_settings->view_transform, default_view->name, sizeof(view_settings->view_transform));
1039         }
1040         else {
1041                 ColorManagedView *view = colormanage_view_get_named(view_settings->view_transform);
1042
1043                 if (!view) {
1044                         display = colormanage_display_get_named(display_settings->display_device);
1045
1046                         if (display)
1047                                 default_view = colormanage_view_get_default(display);
1048
1049                         if (default_view) {
1050                                 printf("Color management: %s view \"%s\" not found, setting default \"%s\".\n",
1051                                        what, view_settings->view_transform, default_view->name);
1052
1053                                 BLI_strncpy(view_settings->view_transform, default_view->name, sizeof(view_settings->view_transform));
1054                         }
1055                 }
1056         }
1057
1058         if (view_settings->look[0] == '\0') {
1059                 BLI_strncpy(view_settings->look, default_look->name, sizeof(view_settings->look));
1060         }
1061         else {
1062                 ColorManagedLook *look = colormanage_look_get_named(view_settings->look);
1063                 if (look == NULL) {
1064                         printf("Color management: %s look \"%s\" not found, setting default \"%s\".\n",
1065                                what, view_settings->look, default_look->name);
1066
1067                         BLI_strncpy(view_settings->look, default_look->name, sizeof(view_settings->look));
1068                 }
1069         }
1070
1071         /* OCIO_TODO: move to do_versions() */
1072         if (view_settings->exposure == 0.0f && view_settings->gamma == 0.0f) {
1073                 view_settings->exposure = 0.0f;
1074                 view_settings->gamma = 1.0f;
1075         }
1076 }
1077
1078 static void colormanage_check_colorspace_settings(ColorManagedColorspaceSettings *colorspace_settings, const char *what)
1079 {
1080         if (colorspace_settings->name[0] == '\0') {
1081                 /* pass */
1082         }
1083         else {
1084                 ColorSpace *colorspace = colormanage_colorspace_get_named(colorspace_settings->name);
1085
1086                 if (!colorspace) {
1087                         printf("Color management: %s colorspace \"%s\" not found, will use default instead.\n",
1088                                what, colorspace_settings->name);
1089
1090                         BLI_strncpy(colorspace_settings->name, "", sizeof(colorspace_settings->name));
1091                 }
1092         }
1093
1094         (void) what;
1095 }
1096
1097 void IMB_colormanagement_check_file_config(Main *bmain)
1098 {
1099         Scene *scene;
1100         Image *image;
1101         MovieClip *clip;
1102
1103         ColorManagedDisplay *default_display;
1104
1105         default_display = colormanage_display_get_default();
1106
1107         if (!default_display) {
1108                 /* happens when OCIO configuration is incorrect */
1109                 return;
1110         }
1111
1112         for (scene = bmain->scene.first; scene; scene = scene->id.next) {
1113                 ColorManagedColorspaceSettings *sequencer_colorspace_settings;
1114
1115                 colormanage_check_display_settings(&scene->display_settings, "scene", default_display);
1116                 colormanage_check_view_settings(&scene->display_settings, &scene->view_settings, "scene");
1117
1118                 sequencer_colorspace_settings = &scene->sequencer_colorspace_settings;
1119
1120                 colormanage_check_colorspace_settings(sequencer_colorspace_settings, "sequencer");
1121
1122                 if (sequencer_colorspace_settings->name[0] == '\0') {
1123                         BLI_strncpy(sequencer_colorspace_settings->name, global_role_default_sequencer, MAX_COLORSPACE_NAME);
1124                 }
1125         }
1126
1127         /* ** check input color space settings ** */
1128
1129         for (image = bmain->image.first; image; image = image->id.next) {
1130                 colormanage_check_colorspace_settings(&image->colorspace_settings, "image");
1131         }
1132
1133         for (clip = bmain->movieclip.first; clip; clip = clip->id.next) {
1134                 colormanage_check_colorspace_settings(&clip->colorspace_settings, "clip");
1135         }
1136 }
1137
1138 void IMB_colormanagement_validate_settings(ColorManagedDisplaySettings *display_settings,
1139                                            ColorManagedViewSettings *view_settings)
1140 {
1141         ColorManagedDisplay *display;
1142         ColorManagedView *default_view = NULL;
1143         LinkData *view_link;
1144
1145         display = colormanage_display_get_named(display_settings->display_device);
1146
1147         default_view = colormanage_view_get_default(display);
1148
1149         for (view_link = display->views.first; view_link; view_link = view_link->next) {
1150                 ColorManagedView *view = view_link->data;
1151
1152                 if (STREQ(view->name, view_settings->view_transform))
1153                         break;
1154         }
1155
1156         if (view_link == NULL && default_view)
1157                 BLI_strncpy(view_settings->view_transform, default_view->name, sizeof(view_settings->view_transform));
1158 }
1159
1160 const char *IMB_colormanagement_role_colorspace_name_get(int role)
1161 {
1162         switch (role) {
1163                 case COLOR_ROLE_SCENE_LINEAR:
1164                         return global_role_scene_linear;
1165                 case COLOR_ROLE_COLOR_PICKING:
1166                         return global_role_color_picking;
1167                 case COLOR_ROLE_TEXTURE_PAINTING:
1168                         return global_role_texture_painting;
1169                 case COLOR_ROLE_DEFAULT_SEQUENCER:
1170                         return global_role_default_sequencer;
1171                 case COLOR_ROLE_DEFAULT_FLOAT:
1172                         return global_role_default_float;
1173                 case COLOR_ROLE_DEFAULT_BYTE:
1174                         return global_role_default_byte;
1175                 default:
1176                         printf("Unknown role was passed to %s\n", __func__);
1177                         BLI_assert(0);
1178                         break;
1179         }
1180
1181         return NULL;
1182 }
1183
1184 void IMB_colormanagement_check_is_data(ImBuf *ibuf, const char *name)
1185 {
1186         ColorSpace *colorspace = colormanage_colorspace_get_named(name);
1187
1188         if (colorspace && colorspace->is_data)
1189                 ibuf->colormanage_flag |= IMB_COLORMANAGE_IS_DATA;
1190         else
1191                 ibuf->colormanage_flag &= ~IMB_COLORMANAGE_IS_DATA;
1192 }
1193
1194 void IMB_colormanagement_assign_float_colorspace(ImBuf *ibuf, const char *name)
1195 {
1196         ColorSpace *colorspace = colormanage_colorspace_get_named(name);
1197
1198         ibuf->float_colorspace = colorspace;
1199
1200         if (colorspace && colorspace->is_data)
1201                 ibuf->colormanage_flag |= IMB_COLORMANAGE_IS_DATA;
1202         else
1203                 ibuf->colormanage_flag &= ~IMB_COLORMANAGE_IS_DATA;
1204 }
1205
1206 void IMB_colormanagement_assign_rect_colorspace(ImBuf *ibuf, const char *name)
1207 {
1208         ColorSpace *colorspace = colormanage_colorspace_get_named(name);
1209
1210         ibuf->rect_colorspace = colorspace;
1211
1212         if (colorspace && colorspace->is_data)
1213                 ibuf->colormanage_flag |= IMB_COLORMANAGE_IS_DATA;
1214         else
1215                 ibuf->colormanage_flag &= ~IMB_COLORMANAGE_IS_DATA;
1216 }
1217
1218 const char *IMB_colormanagement_get_float_colorspace(ImBuf *ibuf)
1219 {
1220         if (ibuf->float_colorspace) {
1221                 return ibuf->float_colorspace->name;
1222         }
1223         else {
1224                 return IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_SCENE_LINEAR);
1225         }
1226 }
1227
1228 const char *IMB_colormanagement_get_rect_colorspace(ImBuf *ibuf)
1229 {
1230         return ibuf->rect_colorspace->name;
1231 }
1232
1233 /*********************** Threaded display buffer transform routines *************************/
1234
1235 typedef struct DisplayBufferThread {
1236         ColormanageProcessor *cm_processor;
1237
1238         const float *buffer;
1239         unsigned char *byte_buffer;
1240
1241         float *display_buffer;
1242         unsigned char *display_buffer_byte;
1243
1244         int width;
1245         int start_line;
1246         int tot_line;
1247
1248         int channels;
1249         float dither;
1250         bool is_data;
1251
1252         const char *byte_colorspace;
1253         const char *float_colorspace;
1254 } DisplayBufferThread;
1255
1256 typedef struct DisplayBufferInitData {
1257         ImBuf *ibuf;
1258         ColormanageProcessor *cm_processor;
1259         const float *buffer;
1260         unsigned char *byte_buffer;
1261
1262         float *display_buffer;
1263         unsigned char *display_buffer_byte;
1264
1265         int width;
1266
1267         const char *byte_colorspace;
1268         const char *float_colorspace;
1269 } DisplayBufferInitData;
1270
1271 static void display_buffer_init_handle(void *handle_v, int start_line, int tot_line, void *init_data_v)
1272 {
1273         DisplayBufferThread *handle = (DisplayBufferThread *) handle_v;
1274         DisplayBufferInitData *init_data = (DisplayBufferInitData *) init_data_v;
1275         ImBuf *ibuf = init_data->ibuf;
1276
1277         int channels = ibuf->channels;
1278         float dither = ibuf->dither;
1279         bool is_data = (ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA) != 0;
1280
1281         size_t offset = ((size_t)channels) * start_line * ibuf->x;
1282         size_t display_buffer_byte_offset = ((size_t)DISPLAY_BUFFER_CHANNELS) * start_line * ibuf->x;
1283
1284         memset(handle, 0, sizeof(DisplayBufferThread));
1285
1286         handle->cm_processor = init_data->cm_processor;
1287
1288         if (init_data->buffer)
1289                 handle->buffer = init_data->buffer + offset;
1290
1291         if (init_data->byte_buffer)
1292                 handle->byte_buffer = init_data->byte_buffer + offset;
1293
1294         if (init_data->display_buffer)
1295                 handle->display_buffer = init_data->display_buffer + offset;
1296
1297         if (init_data->display_buffer_byte)
1298                 handle->display_buffer_byte = init_data->display_buffer_byte + display_buffer_byte_offset;
1299
1300         handle->width = ibuf->x;
1301
1302         handle->start_line = start_line;
1303         handle->tot_line = tot_line;
1304
1305         handle->channels = channels;
1306         handle->dither = dither;
1307         handle->is_data = is_data;
1308
1309         handle->byte_colorspace = init_data->byte_colorspace;
1310         handle->float_colorspace = init_data->float_colorspace;
1311 }
1312
1313 static void display_buffer_apply_get_linear_buffer(DisplayBufferThread *handle, int height,
1314                                                    float *linear_buffer, bool *is_straight_alpha)
1315 {
1316         int channels = handle->channels;
1317         int width = handle->width;
1318
1319         size_t buffer_size = ((size_t)channels) * width * height;
1320
1321         bool is_data = handle->is_data;
1322         bool is_data_display = handle->cm_processor->is_data_result;
1323
1324         if (!handle->buffer) {
1325                 unsigned char *byte_buffer = handle->byte_buffer;
1326
1327                 const char *from_colorspace = handle->byte_colorspace;
1328                 const char *to_colorspace = global_role_scene_linear;
1329
1330                 float *fp;
1331                 unsigned char *cp;
1332                 const size_t i_last = ((size_t)width) * height;
1333                 size_t i;
1334
1335                 /* first convert byte buffer to float, keep in image space */
1336                 for (i = 0, fp = linear_buffer, cp = byte_buffer;
1337                      i != i_last;
1338                      i++, fp += channels, cp += channels)
1339                 {
1340                         if (channels == 3) {
1341                                 rgb_uchar_to_float(fp, cp);
1342                         }
1343                         else if (channels == 4) {
1344                                 rgba_uchar_to_float(fp, cp);
1345                         }
1346                         else {
1347                                 BLI_assert(!"Buffers of 3 or 4 channels are only supported here");
1348                         }
1349                 }
1350
1351                 if (!is_data && !is_data_display) {
1352                         /* convert float buffer to scene linear space */
1353                         IMB_colormanagement_transform(linear_buffer, width, height, channels,
1354                                                       from_colorspace, to_colorspace, false);
1355                 }
1356
1357                 *is_straight_alpha = true;
1358         }
1359         else if (handle->float_colorspace) {
1360                 /* currently float is non-linear only in sequencer, which is working
1361                  * in it's own color space even to handle float buffers.
1362                  * This color space is the same for byte and float images.
1363                  * Need to convert float buffer to linear space before applying display transform
1364                  */
1365
1366                 const char *from_colorspace = handle->float_colorspace;
1367                 const char *to_colorspace = global_role_scene_linear;
1368
1369                 memcpy(linear_buffer, handle->buffer, buffer_size * sizeof(float));
1370
1371                 if (!is_data && !is_data_display) {
1372                         IMB_colormanagement_transform(linear_buffer, width, height, channels,
1373                                                       from_colorspace, to_colorspace, true);
1374                 }
1375
1376                 *is_straight_alpha = false;
1377         }
1378         else {
1379                 /* some processors would want to modify float original buffer
1380                  * before converting it into display byte buffer, so we need to
1381                  * make sure original's ImBuf buffers wouldn't be modified by
1382                  * using duplicated buffer here
1383                  */
1384
1385                 memcpy(linear_buffer, handle->buffer, buffer_size * sizeof(float));
1386
1387                 *is_straight_alpha = false;
1388         }
1389 }
1390
1391 static void *do_display_buffer_apply_thread(void *handle_v)
1392 {
1393         DisplayBufferThread *handle = (DisplayBufferThread *) handle_v;
1394         ColormanageProcessor *cm_processor = handle->cm_processor;
1395         float *display_buffer = handle->display_buffer;
1396         unsigned char *display_buffer_byte = handle->display_buffer_byte;
1397         int channels = handle->channels;
1398         int width = handle->width;
1399         int height = handle->tot_line;
1400         float dither = handle->dither;
1401         bool is_data = handle->is_data;
1402
1403         if (cm_processor == NULL) {
1404                 if (display_buffer_byte) {
1405                         IMB_buffer_byte_from_byte(display_buffer_byte, handle->byte_buffer, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
1406                                                   false, width, height, width, width);
1407                 }
1408
1409                 if (display_buffer) {
1410                         IMB_buffer_float_from_byte(display_buffer, handle->byte_buffer, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
1411                                                    false, width, height, width, width);
1412                 }
1413         }
1414         else {
1415                 bool is_straight_alpha, predivide;
1416                 float *linear_buffer = MEM_mallocN(((size_t)channels) * width * height * sizeof(float),
1417                                                    "color conversion linear buffer");
1418
1419                 display_buffer_apply_get_linear_buffer(handle, height, linear_buffer, &is_straight_alpha);
1420
1421                 predivide = is_straight_alpha == false;
1422
1423                 if (is_data) {
1424                         /* special case for data buffers - no color space conversions,
1425                          * only generate byte buffers
1426                          */
1427                 }
1428                 else {
1429                         /* apply processor */
1430                         IMB_colormanagement_processor_apply(cm_processor, linear_buffer, width, height, channels,
1431                                                             predivide);
1432                 }
1433
1434                 /* copy result to output buffers */
1435                 if (display_buffer_byte) {
1436                         /* do conversion */
1437                         IMB_buffer_byte_from_float(display_buffer_byte, linear_buffer,
1438                                                    channels, dither, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
1439                                                    predivide, width, height, width, width);
1440                 }
1441
1442                 if (display_buffer) {
1443                         memcpy(display_buffer, linear_buffer, ((size_t)width) * height * channels * sizeof(float));
1444
1445                         if (is_straight_alpha && channels == 4) {
1446                                 const size_t i_last = ((size_t)width) * height;
1447                                 size_t i;
1448                                 float *fp;
1449
1450                                 for (i = 0, fp = display_buffer;
1451                                      i != i_last;
1452                                      i++, fp += channels)
1453                                 {
1454                                         straight_to_premul_v4(fp);
1455                                 }
1456                         }
1457                 }
1458
1459                 MEM_freeN(linear_buffer);
1460         }
1461
1462         return NULL;
1463 }
1464
1465 static void display_buffer_apply_threaded(ImBuf *ibuf, float *buffer, unsigned char *byte_buffer, float *display_buffer,
1466                                           unsigned char *display_buffer_byte, ColormanageProcessor *cm_processor)
1467 {
1468         DisplayBufferInitData init_data;
1469
1470         init_data.ibuf = ibuf;
1471         init_data.cm_processor = cm_processor;
1472         init_data.buffer = buffer;
1473         init_data.byte_buffer = byte_buffer;
1474         init_data.display_buffer = display_buffer;
1475         init_data.display_buffer_byte = display_buffer_byte;
1476
1477         if (ibuf->rect_colorspace != NULL) {
1478                 init_data.byte_colorspace = ibuf->rect_colorspace->name;
1479         }
1480         else {
1481                 /* happens for viewer images, which are not so simple to determine where to
1482                  * set image buffer's color spaces
1483                  */
1484                 init_data.byte_colorspace = global_role_default_byte;
1485         }
1486
1487         if (ibuf->float_colorspace != NULL) {
1488                 /* sequencer stores float buffers in non-linear space */
1489                 init_data.float_colorspace = ibuf->float_colorspace->name;
1490         }
1491         else {
1492                 init_data.float_colorspace = NULL;
1493         }
1494
1495         IMB_processor_apply_threaded(ibuf->y, sizeof(DisplayBufferThread), &init_data,
1496                                      display_buffer_init_handle, do_display_buffer_apply_thread);
1497 }
1498
1499 static bool is_ibuf_rect_in_display_space(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
1500                                           const ColorManagedDisplaySettings *display_settings)
1501 {
1502         if ((view_settings->flag & COLORMANAGE_VIEW_USE_CURVES) == 0 &&
1503             view_settings->exposure == 0.0f &&
1504             view_settings->gamma == 1.0f)
1505         {
1506                 const char *from_colorspace = ibuf->rect_colorspace->name;
1507                 const char *to_colorspace = IMB_colormanagement_get_display_colorspace_name(view_settings, display_settings);
1508
1509                 if (to_colorspace && STREQ(from_colorspace, to_colorspace))
1510                         return true;
1511         }
1512
1513         return false;
1514 }
1515
1516 static void colormanage_display_buffer_process_ex(ImBuf *ibuf, float *display_buffer, unsigned char *display_buffer_byte,
1517                                                   const ColorManagedViewSettings *view_settings,
1518                                                   const ColorManagedDisplaySettings *display_settings)
1519 {
1520         ColormanageProcessor *cm_processor = NULL;
1521         bool skip_transform = false;
1522
1523         /* if we're going to transform byte buffer, check whether transformation would
1524          * happen to the same color space as byte buffer itself is
1525          * this would save byte -> float -> byte conversions making display buffer
1526          * computation noticeable faster
1527          */
1528         if (ibuf->rect_float == NULL && ibuf->rect_colorspace) {
1529                 skip_transform = is_ibuf_rect_in_display_space(ibuf, view_settings, display_settings);
1530         }
1531
1532         if (skip_transform == false)
1533                 cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1534
1535         display_buffer_apply_threaded(ibuf, ibuf->rect_float, (unsigned char *) ibuf->rect,
1536                                       display_buffer, display_buffer_byte, cm_processor);
1537
1538         if (cm_processor)
1539                 IMB_colormanagement_processor_free(cm_processor);
1540 }
1541
1542 static void colormanage_display_buffer_process(ImBuf *ibuf, unsigned char *display_buffer,
1543                                                const ColorManagedViewSettings *view_settings,
1544                                                const ColorManagedDisplaySettings *display_settings)
1545 {
1546         colormanage_display_buffer_process_ex(ibuf, NULL, display_buffer, view_settings, display_settings);
1547 }
1548
1549 /*********************** Threaded processor transform routines *************************/
1550
1551 typedef struct ProcessorTransformThread {
1552         ColormanageProcessor *cm_processor;
1553         float *buffer;
1554         int width;
1555         int start_line;
1556         int tot_line;
1557         int channels;
1558         bool predivide;
1559 } ProcessorTransformThread;
1560
1561 typedef struct ProcessorTransformInit {
1562         ColormanageProcessor *cm_processor;
1563         float *buffer;
1564         int width;
1565         int height;
1566         int channels;
1567         bool predivide;
1568 } ProcessorTransformInitData;
1569
1570 static void processor_transform_init_handle(void *handle_v, int start_line, int tot_line, void *init_data_v)
1571 {
1572         ProcessorTransformThread *handle = (ProcessorTransformThread *) handle_v;
1573         ProcessorTransformInitData *init_data = (ProcessorTransformInitData *) init_data_v;
1574
1575         int channels = init_data->channels;
1576         int width = init_data->width;
1577         bool predivide = init_data->predivide;
1578
1579         size_t offset = ((size_t)channels) * start_line * width;
1580
1581         memset(handle, 0, sizeof(ProcessorTransformThread));
1582
1583         handle->cm_processor = init_data->cm_processor;
1584
1585         handle->buffer = init_data->buffer + offset;
1586
1587         handle->width = width;
1588
1589         handle->start_line = start_line;
1590         handle->tot_line = tot_line;
1591
1592         handle->channels = channels;
1593         handle->predivide = predivide;
1594 }
1595
1596 static void *do_processor_transform_thread(void *handle_v)
1597 {
1598         ProcessorTransformThread *handle = (ProcessorTransformThread *) handle_v;
1599         float *buffer = handle->buffer;
1600         int channels = handle->channels;
1601         int width = handle->width;
1602         int height = handle->tot_line;
1603         bool predivide = handle->predivide;
1604
1605         IMB_colormanagement_processor_apply(handle->cm_processor, buffer, width, height, channels, predivide);
1606
1607         return NULL;
1608 }
1609
1610 static void processor_transform_apply_threaded(float *buffer, int width, int height, int channels,
1611                                                ColormanageProcessor *cm_processor, bool predivide)
1612 {
1613         ProcessorTransformInitData init_data;
1614
1615         init_data.cm_processor = cm_processor;
1616         init_data.buffer = buffer;
1617         init_data.width = width;
1618         init_data.height = height;
1619         init_data.channels = channels;
1620         init_data.predivide = predivide;
1621
1622         IMB_processor_apply_threaded(height, sizeof(ProcessorTransformThread), &init_data,
1623                                      processor_transform_init_handle, do_processor_transform_thread);
1624 }
1625
1626 /*********************** Color space transformation functions *************************/
1627
1628 /* convert the whole buffer from specified by name color space to another - internal implementation */
1629 static void colormanagement_transform_ex(float *buffer, int width, int height, int channels, const char *from_colorspace,
1630                                          const char *to_colorspace, bool predivide, bool do_threaded)
1631 {
1632         ColormanageProcessor *cm_processor;
1633
1634         if (from_colorspace[0] == '\0') {
1635                 return;
1636         }
1637
1638         if (STREQ(from_colorspace, to_colorspace)) {
1639                 /* if source and destination color spaces are identical, skip
1640                  * threading overhead and simply do nothing
1641                  */
1642                 return;
1643         }
1644
1645         cm_processor = IMB_colormanagement_colorspace_processor_new(from_colorspace, to_colorspace);
1646
1647         if (do_threaded)
1648                 processor_transform_apply_threaded(buffer, width, height, channels, cm_processor, predivide);
1649         else
1650                 IMB_colormanagement_processor_apply(cm_processor, buffer, width, height, channels, predivide);
1651
1652         IMB_colormanagement_processor_free(cm_processor);
1653 }
1654
1655 /* convert the whole buffer from specified by name color space to another */
1656 void IMB_colormanagement_transform(float *buffer, int width, int height, int channels,
1657                                    const char *from_colorspace, const char *to_colorspace, bool predivide)
1658 {
1659         colormanagement_transform_ex(buffer, width, height, channels, from_colorspace, to_colorspace, predivide, false);
1660 }
1661
1662 /* convert the whole buffer from specified by name color space to another
1663  * will do threaded conversion
1664  */
1665 void IMB_colormanagement_transform_threaded(float *buffer, int width, int height, int channels,
1666                                             const char *from_colorspace, const char *to_colorspace, bool predivide)
1667 {
1668         colormanagement_transform_ex(buffer, width, height, channels, from_colorspace, to_colorspace, predivide, true);
1669 }
1670
1671 void IMB_colormanagement_transform_v4(float pixel[4], const char *from_colorspace, const char *to_colorspace)
1672 {
1673         ColormanageProcessor *cm_processor;
1674
1675         if (from_colorspace[0] == '\0') {
1676                 return;
1677         }
1678
1679         if (STREQ(from_colorspace, to_colorspace)) {
1680                 /* if source and destination color spaces are identical, skip
1681                  * threading overhead and simply do nothing
1682                  */
1683                 return;
1684         }
1685
1686         cm_processor = IMB_colormanagement_colorspace_processor_new(from_colorspace, to_colorspace);
1687
1688         IMB_colormanagement_processor_apply_v4(cm_processor, pixel);
1689
1690         IMB_colormanagement_processor_free(cm_processor);
1691 }
1692
1693 /* convert pixel from specified by descriptor color space to scene linear
1694  * used by performance-critical areas such as renderer and baker
1695  */
1696 void IMB_colormanagement_colorspace_to_scene_linear_v3(float pixel[3], ColorSpace *colorspace)
1697 {
1698         OCIO_ConstProcessorRcPtr *processor;
1699
1700         if (!colorspace) {
1701                 /* should never happen */
1702                 printf("%s: perform conversion from unknown color space\n", __func__);
1703                 return;
1704         }
1705
1706         processor = colorspace_to_scene_linear_processor(colorspace);
1707
1708         if (processor)
1709                 OCIO_processorApplyRGB(processor, pixel);
1710 }
1711
1712 /* same as above, but converts colors in opposite direction */
1713 void IMB_colormanagement_scene_linear_to_colorspace_v3(float pixel[3], ColorSpace *colorspace)
1714 {
1715         OCIO_ConstProcessorRcPtr *processor;
1716
1717         if (!colorspace) {
1718                 /* should never happen */
1719                 printf("%s: perform conversion from unknown color space\n", __func__);
1720                 return;
1721         }
1722
1723         processor = colorspace_from_scene_linear_processor(colorspace);
1724
1725         if (processor)
1726                 OCIO_processorApplyRGB(processor, pixel);
1727 }
1728
1729 void IMB_colormanagement_colorspace_to_scene_linear_v4(float pixel[4], bool predivide, ColorSpace *colorspace)
1730 {
1731         OCIO_ConstProcessorRcPtr *processor;
1732
1733         if (!colorspace) {
1734                 /* should never happen */
1735                 printf("%s: perform conversion from unknown color space\n", __func__);
1736                 return;
1737         }
1738
1739         processor = colorspace_to_scene_linear_processor(colorspace);
1740
1741         if (processor) {
1742                 if (predivide)
1743                         OCIO_processorApplyRGBA_predivide(processor, pixel);
1744                 else
1745                         OCIO_processorApplyRGBA(processor, pixel);
1746         }
1747 }
1748
1749 void IMB_colormanagement_colorspace_to_scene_linear(float *buffer, int width, int height, int channels, struct ColorSpace *colorspace, bool predivide)
1750 {
1751         OCIO_ConstProcessorRcPtr *processor;
1752
1753         if (!colorspace) {
1754                 /* should never happen */
1755                 printf("%s: perform conversion from unknown color space\n", __func__);
1756                 return;
1757         }
1758
1759         processor = colorspace_to_scene_linear_processor(colorspace);
1760
1761         if (processor) {
1762                 OCIO_PackedImageDesc *img;
1763
1764                 img = OCIO_createOCIO_PackedImageDesc(
1765                         buffer, width, height, channels, sizeof(float),
1766                         (size_t)channels * sizeof(float),
1767                         (size_t)channels * sizeof(float) * width);
1768
1769                 if (predivide)
1770                         OCIO_processorApply_predivide(processor, img);
1771                 else
1772                         OCIO_processorApply(processor, img);
1773
1774                 OCIO_PackedImageDescRelease(img);
1775         }
1776 }
1777
1778 /* convert pixel from scene linear to display space using default view
1779  * used by performance-critical areas such as color-related widgets where we want to reduce
1780  * amount of per-widget allocations
1781  */
1782 void IMB_colormanagement_scene_linear_to_display_v3(float pixel[3], ColorManagedDisplay *display)
1783 {
1784         OCIO_ConstProcessorRcPtr *processor;
1785
1786         processor = display_from_scene_linear_processor(display);
1787
1788         if (processor)
1789                 OCIO_processorApplyRGB(processor, pixel);
1790 }
1791
1792 /* same as above, but converts color in opposite direction */
1793 void IMB_colormanagement_display_to_scene_linear_v3(float pixel[3], ColorManagedDisplay *display)
1794 {
1795         OCIO_ConstProcessorRcPtr *processor;
1796
1797         processor = display_to_scene_linear_processor(display);
1798
1799         if (processor)
1800                 OCIO_processorApplyRGB(processor, pixel);
1801 }
1802
1803 void IMB_colormanagement_pixel_to_display_space_v4(float result[4], const float pixel[4],
1804                                                    const ColorManagedViewSettings *view_settings,
1805                                                    const ColorManagedDisplaySettings *display_settings)
1806 {
1807         ColormanageProcessor *cm_processor;
1808
1809         copy_v4_v4(result, pixel);
1810
1811         cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1812         IMB_colormanagement_processor_apply_v4(cm_processor, result);
1813         IMB_colormanagement_processor_free(cm_processor);
1814 }
1815
1816 void IMB_colormanagement_pixel_to_display_space_v3(float result[3], const float pixel[3],
1817                                                    const ColorManagedViewSettings *view_settings,
1818                                                    const ColorManagedDisplaySettings *display_settings)
1819 {
1820         ColormanageProcessor *cm_processor;
1821
1822         copy_v3_v3(result, pixel);
1823
1824         cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1825         IMB_colormanagement_processor_apply_v3(cm_processor, result);
1826         IMB_colormanagement_processor_free(cm_processor);
1827 }
1828
1829 static void colormanagement_imbuf_make_display_space(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
1830                                                      const ColorManagedDisplaySettings *display_settings, bool make_byte)
1831 {
1832         if (!ibuf->rect && make_byte)
1833                 imb_addrectImBuf(ibuf);
1834
1835         colormanage_display_buffer_process_ex(ibuf, ibuf->rect_float, (unsigned char *)ibuf->rect,
1836                                               view_settings, display_settings);
1837 }
1838
1839 void IMB_colormanagement_imbuf_make_display_space(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
1840                                                   const ColorManagedDisplaySettings *display_settings)
1841 {
1842         colormanagement_imbuf_make_display_space(ibuf, view_settings, display_settings, false);
1843 }
1844
1845 /* prepare image buffer to be saved on disk, applying color management if needed
1846  * color management would be applied if image is saving as render result and if
1847  * file format is not expecting float buffer to be in linear space (currently
1848  * JPEG2000 and TIFF are such formats -- they're storing image as float but
1849  * file itself stores applied color space).
1850  *
1851  * Both byte and float buffers would contain applied color space, and result's
1852  * float_colorspace would be set to display color space. This should be checked
1853  * in image format write callback and if float_colorspace is not NULL, no color
1854  * space transformation should be applied on this buffer.
1855  */
1856 ImBuf *IMB_colormanagement_imbuf_for_write(ImBuf *ibuf, bool save_as_render, bool allocate_result, const ColorManagedViewSettings *view_settings,
1857                                            const ColorManagedDisplaySettings *display_settings, ImageFormatData *image_format_data)
1858 {
1859         ImBuf *colormanaged_ibuf = ibuf;
1860         bool do_colormanagement;
1861         bool is_movie = BKE_imtype_is_movie(image_format_data->imtype);
1862         bool requires_linear_float = BKE_imtype_requires_linear_float(image_format_data->imtype);
1863         bool do_alpha_under = image_format_data->planes != R_IMF_PLANES_RGBA;
1864
1865         if (ibuf->rect_float && ibuf->rect &&
1866             (ibuf->userflags & (IB_DISPLAY_BUFFER_INVALID | IB_RECT_INVALID)) != 0)
1867         {
1868                 IMB_rect_from_float(ibuf);
1869                 ibuf->userflags &= ~(IB_RECT_INVALID | IB_DISPLAY_BUFFER_INVALID);
1870         }
1871
1872         do_colormanagement = save_as_render && (is_movie || !requires_linear_float);
1873
1874         if (do_colormanagement || do_alpha_under) {
1875                 if (allocate_result) {
1876                         colormanaged_ibuf = IMB_dupImBuf(ibuf);
1877                 }
1878                 else {
1879                         /* render pipeline is constructing image buffer itself, but it's re-using byte and float buffers from render result
1880                          * make copy of this buffers here sine this buffers would be transformed to other color space here
1881                          */
1882
1883                         if (ibuf->rect && (ibuf->mall & IB_rect) == 0) {
1884                                 ibuf->rect = MEM_dupallocN(ibuf->rect);
1885                                 ibuf->mall |= IB_rect;
1886                         }
1887
1888                         if (ibuf->rect_float && (ibuf->mall & IB_rectfloat) == 0) {
1889                                 ibuf->rect_float = MEM_dupallocN(ibuf->rect_float);
1890                                 ibuf->mall |= IB_rectfloat;
1891                         }
1892                 }
1893         }
1894
1895         /* If we're saving from RGBA to RGB buffer then it's not
1896          * so much useful to just ignore alpha -- it leads to bad
1897          * artifacts especially when saving byte images.
1898          *
1899          * What we do here is we're overlaying our image on top of
1900          * background color (which is currently black).
1901          *
1902          * This is quite much the same as what Gimp does and it
1903          * seems to be what artists expects from saving.
1904          *
1905          * Do a conversion here, so image format writers could
1906          * happily assume all the alpha tricks were made already.
1907          * helps keep things locally here, not spreading it to
1908          * all possible image writers we've got.
1909          */
1910         if (do_alpha_under) {
1911                 float color[3] = {0, 0, 0};
1912
1913                 if (colormanaged_ibuf->rect_float && colormanaged_ibuf->channels == 4) {
1914                         IMB_alpha_under_color_float(colormanaged_ibuf->rect_float, colormanaged_ibuf->x,
1915                                                     colormanaged_ibuf->y, color);
1916                 }
1917
1918                 if (colormanaged_ibuf->rect) {
1919                         IMB_alpha_under_color_byte((unsigned char *)colormanaged_ibuf->rect,
1920                                                    colormanaged_ibuf->x, colormanaged_ibuf->y,
1921                                                    color);
1922                 }
1923         }
1924
1925         if (do_colormanagement) {
1926                 bool make_byte = false;
1927                 const ImFileType *type;
1928
1929                 /* for proper check whether byte buffer is required by a format or not
1930                  * should be pretty safe since this image buffer is supposed to be used for
1931                  * saving only and ftype would be overwritten a bit later by BKE_imbuf_write
1932                  */
1933                 colormanaged_ibuf->ftype = BKE_image_imtype_to_ftype(image_format_data->imtype, &colormanaged_ibuf->foptions);
1934
1935                 /* if file format isn't able to handle float buffer itself,
1936                  * we need to allocate byte buffer and store color managed
1937                  * image there
1938                  */
1939                 for (type = IMB_FILE_TYPES; type < IMB_FILE_TYPES_LAST; type++) {
1940                         if (type->save && type->ftype(type, colormanaged_ibuf)) {
1941                                 if ((type->flag & IM_FTYPE_FLOAT) == 0)
1942                                         make_byte = true;
1943
1944                                 break;
1945                         }
1946                 }
1947
1948                 /* perform color space conversions */
1949                 colormanagement_imbuf_make_display_space(colormanaged_ibuf, view_settings, display_settings, make_byte);
1950
1951                 if (colormanaged_ibuf->rect_float) {
1952                         /* float buffer isn't linear anymore,
1953                          * image format write callback should check for this flag and assume
1954                          * no space conversion should happen if ibuf->float_colorspace != NULL
1955                          */
1956                         colormanaged_ibuf->float_colorspace = display_transform_get_colorspace(view_settings, display_settings);
1957                 }
1958         }
1959
1960         return colormanaged_ibuf;
1961 }
1962
1963 void IMB_colormanagement_buffer_make_display_space(float *buffer, unsigned char *display_buffer,
1964                                                    int width, int height, int channels, float dither,
1965                                                    const ColorManagedViewSettings *view_settings,
1966                                                    const ColorManagedDisplaySettings *display_settings)
1967 {
1968         ColormanageProcessor *cm_processor;
1969         size_t float_buffer_size = ((size_t)width) * height * channels * sizeof(float);
1970         float *display_buffer_float = MEM_mallocN(float_buffer_size, "byte_buffer_make_display_space");
1971
1972         memcpy(display_buffer_float, buffer, float_buffer_size);
1973
1974         cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1975
1976         processor_transform_apply_threaded(display_buffer_float, width, height, channels,
1977                                            cm_processor, true);
1978
1979         IMB_buffer_byte_from_float(display_buffer, display_buffer_float,
1980                                    channels, dither, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
1981                                    true, width, height, width, width);
1982
1983         MEM_freeN(display_buffer_float);
1984         IMB_colormanagement_processor_free(cm_processor);
1985 }
1986
1987 /*********************** Public display buffers interfaces *************************/
1988
1989 /* acquire display buffer for given image buffer using specified view and display settings */
1990 unsigned char *IMB_display_buffer_acquire(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
1991                                           const ColorManagedDisplaySettings *display_settings, void **cache_handle)
1992 {
1993         unsigned char *display_buffer;
1994         size_t buffer_size;
1995         ColormanageCacheViewSettings cache_view_settings;
1996         ColormanageCacheDisplaySettings cache_display_settings;
1997         ColorManagedViewSettings default_view_settings;
1998         const ColorManagedViewSettings *applied_view_settings;
1999
2000         *cache_handle = NULL;
2001
2002         if (!ibuf->x || !ibuf->y)
2003                 return NULL;
2004
2005         if (view_settings) {
2006                 applied_view_settings = view_settings;
2007         }
2008         else {
2009                 /* if no view settings were specified, use default display transformation
2010                  * this happens for images which don't want to be displayed with render settings
2011                  */
2012
2013                 init_default_view_settings(display_settings,  &default_view_settings);
2014                 applied_view_settings = &default_view_settings;
2015         }
2016
2017         /* early out: no float buffer and byte buffer is already in display space,
2018          * let's just use if
2019          */
2020         if (ibuf->rect_float == NULL && ibuf->rect_colorspace && ibuf->channels == 4) {
2021                 if (is_ibuf_rect_in_display_space(ibuf, applied_view_settings, display_settings))
2022                         return (unsigned char *) ibuf->rect;
2023         }
2024
2025         colormanage_view_settings_to_cache(ibuf, &cache_view_settings, applied_view_settings);
2026         colormanage_display_settings_to_cache(&cache_display_settings, display_settings);
2027
2028         if (ibuf->invalid_rect.xmin != ibuf->invalid_rect.xmax) {
2029                 if ((ibuf->userflags & IB_DISPLAY_BUFFER_INVALID) == 0) {
2030                         IMB_partial_display_buffer_update(ibuf, ibuf->rect_float, (unsigned char *) ibuf->rect,
2031                                                           ibuf->x, 0, 0, applied_view_settings, display_settings,
2032                                                           ibuf->invalid_rect.xmin, ibuf->invalid_rect.ymin,
2033                                                           ibuf->invalid_rect.xmax, ibuf->invalid_rect.ymax,
2034                                                           false);
2035                 }
2036
2037                 BLI_rcti_init(&ibuf->invalid_rect, 0, 0, 0, 0);
2038         }
2039
2040         BLI_lock_thread(LOCK_COLORMANAGE);
2041
2042         /* ensure color management bit fields exists */
2043         if (!ibuf->display_buffer_flags) {
2044                 ibuf->display_buffer_flags = MEM_callocN(sizeof(unsigned int) * global_tot_display, "imbuf display_buffer_flags");
2045         }
2046         else if (ibuf->userflags & IB_DISPLAY_BUFFER_INVALID) {
2047                 /* all display buffers were marked as invalid from other areas,
2048                  * now propagate this flag to internal color management routines
2049                  */
2050                 memset(ibuf->display_buffer_flags, 0, global_tot_display * sizeof(unsigned int));
2051
2052                 ibuf->userflags &= ~IB_DISPLAY_BUFFER_INVALID;
2053         }
2054
2055         display_buffer = colormanage_cache_get(ibuf, &cache_view_settings, &cache_display_settings, cache_handle);
2056
2057         if (display_buffer) {
2058                 BLI_unlock_thread(LOCK_COLORMANAGE);
2059                 return display_buffer;
2060         }
2061
2062         buffer_size = DISPLAY_BUFFER_CHANNELS * ((size_t)ibuf->x) * ibuf->y * sizeof(char);
2063         display_buffer = MEM_callocN(buffer_size, "imbuf display buffer");
2064
2065         colormanage_display_buffer_process(ibuf, display_buffer, applied_view_settings, display_settings);
2066
2067         colormanage_cache_put(ibuf, &cache_view_settings, &cache_display_settings, display_buffer, cache_handle);
2068
2069         BLI_unlock_thread(LOCK_COLORMANAGE);
2070
2071         return display_buffer;
2072 }
2073
2074 /* same as IMB_display_buffer_acquire but gets view and display settings from context */
2075 unsigned char *IMB_display_buffer_acquire_ctx(const bContext *C, ImBuf *ibuf, void **cache_handle)
2076 {
2077         ColorManagedViewSettings *view_settings;
2078         ColorManagedDisplaySettings *display_settings;
2079
2080         IMB_colormanagement_display_settings_from_ctx(C, &view_settings, &display_settings);
2081
2082         return IMB_display_buffer_acquire(ibuf, view_settings, display_settings, cache_handle);
2083 }
2084
2085 void IMB_display_buffer_transform_apply(unsigned char *display_buffer, float *linear_buffer, int width, int height,
2086                                         int channels, const ColorManagedViewSettings *view_settings,
2087                                         const ColorManagedDisplaySettings *display_settings, bool predivide)
2088 {
2089         float *buffer;
2090         ColormanageProcessor *cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
2091
2092         buffer = MEM_mallocN((size_t)channels * width * height * sizeof(float), "display transform temp buffer");
2093         memcpy(buffer, linear_buffer, (size_t)channels * width * height * sizeof(float));
2094
2095         IMB_colormanagement_processor_apply(cm_processor, buffer, width, height, channels, predivide);
2096
2097         IMB_colormanagement_processor_free(cm_processor);
2098
2099         IMB_buffer_byte_from_float(display_buffer, buffer, channels, 0.0f, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
2100                                    false, width, height, width, width);
2101
2102         MEM_freeN(buffer);
2103 }
2104
2105 void IMB_display_buffer_release(void *cache_handle)
2106 {
2107         if (cache_handle) {
2108                 BLI_lock_thread(LOCK_COLORMANAGE);
2109
2110                 colormanage_cache_handle_release(cache_handle);
2111
2112                 BLI_unlock_thread(LOCK_COLORMANAGE);
2113         }
2114 }
2115
2116 /*********************** Display functions *************************/
2117
2118 const char *colormanage_display_get_default_name(void)
2119 {
2120         OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
2121         const char *display_name;
2122
2123         display_name = OCIO_configGetDefaultDisplay(config);
2124
2125         OCIO_configRelease(config);
2126
2127         return display_name;
2128 }
2129
2130 ColorManagedDisplay *colormanage_display_get_default(void)
2131 {
2132         const char *display_name = colormanage_display_get_default_name();
2133
2134         if (display_name[0] == '\0')
2135                 return NULL;
2136
2137         return colormanage_display_get_named(display_name);
2138 }
2139
2140 ColorManagedDisplay *colormanage_display_add(const char *name)
2141 {
2142         ColorManagedDisplay *display;
2143         int index = 0;
2144
2145         if (global_displays.last) {
2146                 ColorManagedDisplay *last_display = global_displays.last;
2147
2148                 index = last_display->index;
2149         }
2150
2151         display = MEM_callocN(sizeof(ColorManagedDisplay), "ColorManagedDisplay");
2152
2153         display->index = index + 1;
2154
2155         BLI_strncpy(display->name, name, sizeof(display->name));
2156
2157         BLI_addtail(&global_displays, display);
2158
2159         return display;
2160 }
2161
2162 ColorManagedDisplay *colormanage_display_get_named(const char *name)
2163 {
2164         ColorManagedDisplay *display;
2165
2166         for (display = global_displays.first; display; display = display->next) {
2167                 if (STREQ(display->name, name))
2168                         return display;
2169         }
2170
2171         return NULL;
2172 }
2173
2174 ColorManagedDisplay *colormanage_display_get_indexed(int index)
2175 {
2176         /* display indices are 1-based */
2177         return BLI_findlink(&global_displays, index - 1);
2178 }
2179
2180 int IMB_colormanagement_display_get_named_index(const char *name)
2181 {
2182         ColorManagedDisplay *display;
2183
2184         display = colormanage_display_get_named(name);
2185
2186         if (display) {
2187                 return display->index;
2188         }
2189
2190         return 0;
2191 }
2192
2193 const char *IMB_colormanagement_display_get_indexed_name(int index)
2194 {
2195         ColorManagedDisplay *display;
2196
2197         display = colormanage_display_get_indexed(index);
2198
2199         if (display) {
2200                 return display->name;
2201         }
2202
2203         return NULL;
2204 }
2205
2206 const char *IMB_colormanagement_display_get_default_name(void)
2207 {
2208         ColorManagedDisplay *display = colormanage_display_get_default();
2209
2210         return display->name;
2211 }
2212
2213 /* used by performance-critical pixel processing areas, such as color widgets */
2214 ColorManagedDisplay *IMB_colormanagement_display_get_named(const char *name)
2215 {
2216         return colormanage_display_get_named(name);
2217 }
2218
2219 const char *IMB_colormanagement_display_get_none_name(void)
2220 {
2221         if (colormanage_display_get_named("None") != NULL)
2222                 return "None";
2223
2224         return colormanage_display_get_default_name();
2225 }
2226
2227 /*********************** View functions *************************/
2228
2229 const char *colormanage_view_get_default_name(const ColorManagedDisplay *display)
2230 {
2231         OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
2232         const char *name;
2233
2234         name = OCIO_configGetDefaultView(config, display->name);
2235
2236         OCIO_configRelease(config);
2237
2238         return name;
2239 }
2240
2241 ColorManagedView *colormanage_view_get_default(const ColorManagedDisplay *display)
2242 {
2243         const char *name = colormanage_view_get_default_name(display);
2244
2245         if (!name || name[0] == '\0')
2246                 return NULL;
2247
2248         return colormanage_view_get_named(name);
2249 }
2250
2251 ColorManagedView *colormanage_view_add(const char *name)
2252 {
2253         ColorManagedView *view;
2254         int index = global_tot_view;
2255
2256         view = MEM_callocN(sizeof(ColorManagedView), "ColorManagedView");
2257         view->index = index + 1;
2258         BLI_strncpy(view->name, name, sizeof(view->name));
2259
2260         BLI_addtail(&global_views, view);
2261
2262         global_tot_view++;
2263
2264         return view;
2265 }
2266
2267 ColorManagedView *colormanage_view_get_named(const char *name)
2268 {
2269         ColorManagedView *view;
2270
2271         for (view = global_views.first; view; view = view->next) {
2272                 if (STREQ(view->name, name))
2273                         return view;
2274         }
2275
2276         return NULL;
2277 }
2278
2279 ColorManagedView *colormanage_view_get_indexed(int index)
2280 {
2281         /* view transform indices are 1-based */
2282         return BLI_findlink(&global_views, index - 1);
2283 }
2284
2285 int IMB_colormanagement_view_get_named_index(const char *name)
2286 {
2287         ColorManagedView *view = colormanage_view_get_named(name);
2288
2289         if (view) {
2290                 return view->index;
2291         }
2292
2293         return 0;
2294 }
2295
2296 const char *IMB_colormanagement_view_get_indexed_name(int index)
2297 {
2298         ColorManagedView *view = colormanage_view_get_indexed(index);
2299
2300         if (view) {
2301                 return view->name;
2302         }
2303
2304         return NULL;
2305 }
2306
2307 const char *IMB_colormanagement_view_get_default_name(const char *display_name)
2308 {
2309         ColorManagedDisplay *display = colormanage_display_get_named(display_name);
2310         ColorManagedView *view = NULL;
2311         
2312         if (display)
2313                 view = colormanage_view_get_default(display);
2314
2315         if (view)
2316                 return view->name;
2317
2318         return NULL;
2319 }
2320
2321 /*********************** Color space functions *************************/
2322
2323 static void colormanage_description_strip(char *description)
2324 {
2325         int i, n;
2326
2327         for (i = (int)strlen(description) - 1; i >= 0; i--) {
2328                 if (ELEM(description[i], '\r', '\n')) {
2329                         description[i] = '\0';
2330                 }
2331                 else {
2332                         break;
2333                 }
2334         }
2335
2336         for (i = 0, n = strlen(description); i < n; i++) {
2337                 if (ELEM(description[i], '\r', '\n')) {
2338                         description[i] = ' ';
2339                 }
2340         }
2341 }
2342
2343 ColorSpace *colormanage_colorspace_add(const char *name, const char *description, bool is_invertible, bool is_data)
2344 {
2345         ColorSpace *colorspace, *prev_space;
2346         int counter = 1;
2347
2348         colorspace = MEM_callocN(sizeof(ColorSpace), "ColorSpace");
2349
2350         BLI_strncpy(colorspace->name, name, sizeof(colorspace->name));
2351
2352         if (description) {
2353                 BLI_strncpy(colorspace->description, description, sizeof(colorspace->description));
2354
2355                 colormanage_description_strip(colorspace->description);
2356         }
2357
2358         colorspace->is_invertible = is_invertible;
2359         colorspace->is_data = is_data;
2360
2361         for (prev_space = global_colorspaces.first; prev_space; prev_space = prev_space->next) {
2362                 if (BLI_strcasecmp(prev_space->name, colorspace->name) > 0)
2363                         break;
2364
2365                 prev_space->index = counter++;
2366         }
2367
2368         if (!prev_space)
2369                 BLI_addtail(&global_colorspaces, colorspace);
2370         else
2371                 BLI_insertlinkbefore(&global_colorspaces, prev_space, colorspace);
2372
2373         colorspace->index = counter++;
2374         for (; prev_space; prev_space = prev_space->next) {
2375                 prev_space->index = counter++;
2376         }
2377
2378         global_tot_colorspace++;
2379
2380         return colorspace;
2381 }
2382
2383 ColorSpace *colormanage_colorspace_get_named(const char *name)
2384 {
2385         ColorSpace *colorspace;
2386
2387         for (colorspace = global_colorspaces.first; colorspace; colorspace = colorspace->next) {
2388                 if (STREQ(colorspace->name, name))
2389                         return colorspace;
2390         }
2391
2392         return NULL;
2393 }
2394
2395 ColorSpace *colormanage_colorspace_get_roled(int role)
2396 {
2397         const char *role_colorspace = IMB_colormanagement_role_colorspace_name_get(role);
2398
2399         return colormanage_colorspace_get_named(role_colorspace);
2400 }
2401
2402 ColorSpace *colormanage_colorspace_get_indexed(int index)
2403 {
2404         /* color space indices are 1-based */
2405         return BLI_findlink(&global_colorspaces, index - 1);
2406 }
2407
2408 int IMB_colormanagement_colorspace_get_named_index(const char *name)
2409 {
2410         ColorSpace *colorspace;
2411
2412         colorspace = colormanage_colorspace_get_named(name);
2413
2414         if (colorspace) {
2415                 return colorspace->index;
2416         }
2417
2418         return 0;
2419 }
2420
2421 const char *IMB_colormanagement_colorspace_get_indexed_name(int index)
2422 {
2423         ColorSpace *colorspace;
2424
2425         colorspace = colormanage_colorspace_get_indexed(index);
2426
2427         if (colorspace) {
2428                 return colorspace->name;
2429         }
2430
2431         return "";
2432 }
2433
2434 void IMB_colormanagment_colorspace_from_ibuf_ftype(ColorManagedColorspaceSettings *colorspace_settings, ImBuf *ibuf)
2435 {
2436         const ImFileType *type;
2437
2438         for (type = IMB_FILE_TYPES; type < IMB_FILE_TYPES_LAST; type++) {
2439                 if (type->save && type->ftype(type, ibuf)) {
2440                         const char *role_colorspace;
2441
2442                         role_colorspace = IMB_colormanagement_role_colorspace_name_get(type->default_save_role);
2443
2444                         BLI_strncpy(colorspace_settings->name, role_colorspace, sizeof(colorspace_settings->name));
2445                 }
2446         }
2447 }
2448
2449 /*********************** Looks functions *************************/
2450
2451 ColorManagedLook *colormanage_look_add(const char *name, const char *process_space, bool is_noop)
2452 {
2453         ColorManagedLook *look;
2454         int index = global_tot_looks;
2455
2456         look = MEM_callocN(sizeof(ColorManagedLook), "ColorManagedLook");
2457         look->index = index + 1;
2458         BLI_strncpy(look->name, name, sizeof(look->name));
2459         BLI_strncpy(look->process_space, process_space, sizeof(look->process_space));
2460         look->is_noop = is_noop;
2461
2462         BLI_addtail(&global_looks, look);
2463
2464         global_tot_looks++;
2465
2466         return look;
2467 }
2468
2469 ColorManagedLook *colormanage_look_get_named(const char *name)
2470 {
2471         ColorManagedLook *look;
2472
2473         for (look = global_looks.first; look; look = look->next) {
2474                 if (STREQ(look->name, name)) {
2475                         return look;
2476                 }
2477         }
2478
2479         return NULL;
2480 }
2481
2482 ColorManagedLook *colormanage_look_get_indexed(int index)
2483 {
2484         /* look indices are 1-based */
2485         return BLI_findlink(&global_looks, index - 1);
2486 }
2487
2488 int IMB_colormanagement_look_get_named_index(const char *name)
2489 {
2490         ColorManagedLook *look;
2491
2492         look = colormanage_look_get_named(name);
2493
2494         if (look) {
2495                 return look->index;
2496         }
2497
2498         return 0;
2499 }
2500
2501 const char *IMB_colormanagement_look_get_indexed_name(int index)
2502 {
2503         ColorManagedLook *look;
2504
2505         look = colormanage_look_get_indexed(index);
2506
2507         if (look) {
2508                 return look->name;
2509         }
2510
2511         return NULL;
2512 }
2513
2514 /*********************** RNA helper functions *************************/
2515
2516 void IMB_colormanagement_display_items_add(EnumPropertyItem **items, int *totitem)
2517 {
2518         ColorManagedDisplay *display;
2519
2520         for (display = global_displays.first; display; display = display->next) {
2521                 EnumPropertyItem item;
2522
2523                 item.value = display->index;
2524                 item.name = display->name;
2525                 item.identifier = display->name;
2526                 item.icon = 0;
2527                 item.description = "";
2528
2529                 RNA_enum_item_add(items, totitem, &item);
2530         }
2531 }
2532
2533 static void colormanagement_view_item_add(EnumPropertyItem **items, int *totitem, ColorManagedView *view)
2534 {
2535         EnumPropertyItem item;
2536
2537         item.value = view->index;
2538         item.name = view->name;
2539         item.identifier = view->name;
2540         item.icon = 0;
2541         item.description = "";
2542
2543         RNA_enum_item_add(items, totitem, &item);
2544 }
2545
2546 void IMB_colormanagement_view_items_add(EnumPropertyItem **items, int *totitem, const char *display_name)
2547 {
2548         ColorManagedDisplay *display = colormanage_display_get_named(display_name);
2549         ColorManagedView *view;
2550
2551         if (display) {
2552                 LinkData *display_view;
2553
2554                 for (display_view = display->views.first; display_view; display_view = display_view->next) {
2555                         view = display_view->data;
2556
2557                         colormanagement_view_item_add(items, totitem, view);
2558                 }
2559         }
2560 }
2561
2562 void IMB_colormanagement_look_items_add(struct EnumPropertyItem **items, int *totitem)
2563 {
2564         ColorManagedLook *look;
2565
2566         for (look = global_looks.first; look; look = look->next) {
2567                 EnumPropertyItem item;
2568
2569                 item.value = look->index;
2570                 item.name = look->name;
2571                 item.identifier = look->name;
2572                 item.icon = 0;
2573                 item.description = "";
2574
2575                 RNA_enum_item_add(items, totitem, &item);
2576         }
2577 }
2578
2579 void IMB_colormanagement_colorspace_items_add(EnumPropertyItem **items, int *totitem)
2580 {
2581         ColorSpace *colorspace;
2582
2583         for (colorspace = global_colorspaces.first; colorspace; colorspace = colorspace->next) {
2584                 EnumPropertyItem item;
2585
2586                 if (!colorspace->is_invertible)
2587                         continue;
2588
2589                 item.value = colorspace->index;
2590                 item.name = colorspace->name;
2591                 item.identifier = colorspace->name;
2592                 item.icon = 0;
2593                 item.description = colorspace->description;
2594
2595                 RNA_enum_item_add(items, totitem, &item);
2596         }
2597 }
2598
2599 /*********************** Partial display buffer update  *************************/
2600
2601 /*
2602  * Partial display update is supposed to be used by such areas as
2603  * compositor and renderer, This areas are calculating tiles of the
2604  * images and because of performance reasons only this tiles should
2605  * be color managed.
2606  * This gives nice visual feedback without slowing things down.
2607  *
2608  * Updating happens for active display transformation only, all
2609  * the rest buffers would be marked as dirty
2610  */
2611
2612 static void partial_buffer_update_rect(ImBuf *ibuf, unsigned char *display_buffer, const float *linear_buffer,
2613                                        const unsigned char *byte_buffer, int display_stride, int linear_stride,
2614                                        int linear_offset_x, int linear_offset_y, ColormanageProcessor *cm_processor,
2615                                        const int xmin, const int ymin, const int xmax, const int ymax)
2616 {
2617         int x, y;
2618         int channels = ibuf->channels;
2619         float dither = ibuf->dither;
2620         ColorSpace *rect_colorspace = ibuf->rect_colorspace;
2621         float *display_buffer_float = NULL;
2622         const int width = xmax - xmin;
2623         const int height = ymax - ymin;
2624         bool is_data = (ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA) != 0;
2625
2626         if (dither != 0.0f) {
2627                 /* cm_processor is NULL in cases byte_buffer's space matches display
2628                  * buffer's space
2629                  * in this case we could skip extra transform and only apply dither
2630                  * use 4 channels for easier byte->float->byte conversion here so
2631                  * (this is only needed to apply dither, in other cases we'll convert
2632                  * byte buffer to display directly)
2633                  */
2634                 if (!cm_processor)
2635                         channels = 4;
2636
2637                 display_buffer_float = MEM_callocN((size_t)channels * width * height * sizeof(float), "display buffer for dither");
2638         }
2639
2640         if (cm_processor) {
2641                 for (y = ymin; y < ymax; y++) {
2642                         for (x = xmin; x < xmax; x++) {
2643                                 size_t display_index = ((size_t)y * display_stride + x) * 4;
2644                                 size_t linear_index = ((size_t)(y - linear_offset_y) * linear_stride + (x - linear_offset_x)) * channels;
2645                                 float pixel[4];
2646
2647                                 if (linear_buffer) {
2648                                         if (channels == 4) {
2649                                                 copy_v4_v4(pixel, (float *) linear_buffer + linear_index);
2650                                         }
2651                                         else if (channels == 3) {
2652                                                 copy_v3_v3(pixel, (float *) linear_buffer + linear_index);
2653                                                 pixel[3] = 1.0f;
2654                                         }
2655                                         else if (channels == 1) {
2656                                                 pixel[0] = linear_buffer[linear_index];
2657                                         }
2658                                         else {
2659                                                 BLI_assert(!"Unsupported number of channels in partial buffer update");
2660                                         }
2661                                 }
2662                                 else if (byte_buffer) {
2663                                         rgba_uchar_to_float(pixel, byte_buffer + linear_index);
2664                                         IMB_colormanagement_colorspace_to_scene_linear_v3(pixel, rect_colorspace);
2665                                         straight_to_premul_v4(pixel);
2666                                 }
2667
2668                                 if (!is_data) {
2669                                         IMB_colormanagement_processor_apply_pixel(cm_processor, pixel, channels);
2670                                 }
2671
2672                                 if (display_buffer_float) {
2673                                         size_t index = ((size_t)(y - ymin) * width + (x - xmin)) * channels;
2674
2675                                         if (channels == 4) {
2676                                                 copy_v4_v4(display_buffer_float + index, pixel);
2677                                         }
2678                                         else if (channels == 3) {
2679                                                 copy_v3_v3(display_buffer_float + index, pixel);
2680                                         }
2681                                         else /* if (channels == 1) */ {
2682                                                 display_buffer_float[index] = pixel[0];
2683                                         }
2684                                 }
2685                                 else {
2686                                         if (channels == 4) {
2687                                                 float pixel_straight[4];
2688                                                 premul_to_straight_v4_v4(pixel_straight, pixel);
2689                                                 rgba_float_to_uchar(display_buffer + display_index, pixel_straight);
2690                                         }
2691                                         else if (channels == 3) {
2692                                                 rgb_float_to_uchar(display_buffer + display_index, pixel);
2693                                                 display_buffer[display_index + 3] = 255;
2694                                         }
2695                                         else /* if (channels == 1) */ {
2696                                                 display_buffer[display_index] =
2697                                                         display_buffer[display_index + 1] =
2698                                                         display_buffer[display_index + 2] =
2699                                                         display_buffer[display_index + 3] = FTOCHAR(pixel[0]);
2700                                         }
2701                                 }
2702                         }
2703                 }
2704         }
2705         else {
2706                 if (display_buffer_float) {
2707                         /* huh, for dither we need float buffer first, no cheaper way. currently */
2708                         IMB_buffer_float_from_byte(display_buffer_float, byte_buffer,
2709                                                    IB_PROFILE_SRGB, IB_PROFILE_SRGB, true,
2710                                                    width, height, width, display_stride);
2711                 }
2712                 else {
2713                         int i;
2714
2715                         for (i = ymin; i < ymax; i++) {
2716                                 size_t byte_offset = ((size_t)linear_stride * i + xmin) * 4;
2717                                 size_t display_offset = ((size_t)display_stride * i + xmin) * 4;
2718
2719                                 memcpy(display_buffer + display_offset, byte_buffer + byte_offset, 4 * sizeof(char) * width);
2720                         }
2721                 }
2722         }
2723
2724         if (display_buffer_float) {
2725                 size_t display_index = ((size_t)ymin * display_stride + xmin) * channels;
2726
2727                 IMB_buffer_byte_from_float(display_buffer + display_index, display_buffer_float, channels, dither,
2728                                            IB_PROFILE_SRGB, IB_PROFILE_SRGB, true, width, height, display_stride, width);
2729
2730                 MEM_freeN(display_buffer_float);
2731         }
2732 }
2733
2734 void IMB_partial_display_buffer_update(ImBuf *ibuf, const float *linear_buffer, const unsigned char *byte_buffer,
2735                                        int stride, int offset_x, int offset_y,
2736                                        const ColorManagedViewSettings *view_settings,
2737                                        const ColorManagedDisplaySettings *display_settings,
2738                                        int xmin, int ymin, int xmax, int ymax,
2739                                        bool copy_display_to_byte_buffer)
2740 {
2741         ColormanageCacheViewSettings cache_view_settings;
2742         ColormanageCacheDisplaySettings cache_display_settings;
2743         void *cache_handle = NULL;
2744         unsigned char *display_buffer = NULL;
2745         int buffer_width = ibuf->x;
2746
2747         if (ibuf->display_buffer_flags) {
2748                 int view_flag, display_index;
2749
2750                 colormanage_view_settings_to_cache(ibuf, &cache_view_settings, view_settings);
2751                 colormanage_display_settings_to_cache(&cache_display_settings, display_settings);
2752
2753                 view_flag = 1 << (cache_view_settings.view - 1);
2754                 display_index = cache_display_settings.display - 1;
2755
2756                 BLI_lock_thread(LOCK_COLORMANAGE);
2757
2758                 if ((ibuf->userflags & IB_DISPLAY_BUFFER_INVALID) == 0)
2759                         display_buffer = colormanage_cache_get(ibuf, &cache_view_settings, &cache_display_settings, &cache_handle);
2760
2761                 /* in some rare cases buffer's dimension could be changing directly from
2762                  * different thread
2763                  * this i.e. happens when image editor acquires render result
2764                  */
2765                 buffer_width = ibuf->x;
2766
2767                 /* mark all other buffers as invalid */
2768                 memset(ibuf->display_buffer_flags, 0, global_tot_display * sizeof(unsigned int));
2769                 ibuf->display_buffer_flags[display_index] |= view_flag;
2770
2771                 BLI_unlock_thread(LOCK_COLORMANAGE);
2772         }
2773
2774         if (display_buffer == NULL) {
2775                 if (copy_display_to_byte_buffer) {
2776                         display_buffer = (unsigned char *) ibuf->rect;
2777                 }
2778         }
2779
2780         if (display_buffer) {
2781                 ColormanageProcessor *cm_processor = NULL;
2782                 bool skip_transform = false;
2783
2784                 /* Byte buffer is assumed to be in imbuf's rect space, so if byte buffer
2785                  * is known we could skip display->linear->display conversion in case
2786                  * display color space matches imbuf's rect space.
2787                  *
2788                  * But if there's a float buffer it's likely operation was performed on
2789                  * it first and byte buffer is likely to be out of date here.
2790                  */
2791                 if (linear_buffer == NULL && byte_buffer != NULL) {
2792                         skip_transform = is_ibuf_rect_in_display_space(ibuf, view_settings, display_settings);
2793                 }
2794
2795                 if (!skip_transform) {
2796                         cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
2797                 }
2798
2799                 partial_buffer_update_rect(ibuf, display_buffer, linear_buffer, byte_buffer, buffer_width, stride,
2800                                            offset_x, offset_y, cm_processor, xmin, ymin, xmax, ymax);
2801
2802                 if (cm_processor) {
2803                         IMB_colormanagement_processor_free(cm_processor);
2804                 }
2805
2806                 IMB_display_buffer_release(cache_handle);
2807         }
2808
2809         if (copy_display_to_byte_buffer && (unsigned char *) ibuf->rect != display_buffer) {
2810                 int y;
2811                 for (y = ymin; y < ymax; y++) {
2812                         size_t index = (size_t)y * buffer_width * 4;
2813                         memcpy((unsigned char *)ibuf->rect + index, display_buffer + index, (size_t)(xmax - xmin) * 4);
2814                 }
2815         }
2816 }
2817
2818 void IMB_partial_display_buffer_update_delayed(ImBuf *ibuf, int xmin, int ymin, int xmax, int ymax)
2819 {
2820         if (ibuf->invalid_rect.xmin == ibuf->invalid_rect.xmax) {
2821                 BLI_rcti_init(&ibuf->invalid_rect, xmin, xmax, ymin, ymax);
2822         }
2823         else {
2824                 rcti rect;
2825                 BLI_rcti_init(&rect, xmin, xmax, ymin, ymax);
2826                 BLI_rcti_union(&ibuf->invalid_rect, &rect);
2827         }
2828 }
2829
2830 /*********************** Pixel processor functions *************************/
2831
2832 ColormanageProcessor *IMB_colormanagement_display_processor_new(const ColorManagedViewSettings *view_settings,
2833                                                                 const ColorManagedDisplaySettings *display_settings)
2834 {
2835         ColormanageProcessor *cm_processor;
2836         ColorManagedViewSettings default_view_settings;
2837         const ColorManagedViewSettings *applied_view_settings;
2838         ColorSpace *display_space;
2839
2840         cm_processor = MEM_callocN(sizeof(ColormanageProcessor), "colormanagement processor");
2841
2842         if (view_settings) {
2843                 applied_view_settings = view_settings;
2844         }
2845         else {
2846                 init_default_view_settings(display_settings,  &default_view_settings);
2847                 applied_view_settings = &default_view_settings;
2848         }
2849
2850         display_space =  display_transform_get_colorspace(applied_view_settings, display_settings);
2851         if (display_space)
2852                 cm_processor->is_data_result = display_space->is_data;
2853
2854         cm_processor->processor = create_display_buffer_processor(applied_view_settings->look,
2855                                                                   applied_view_settings->view_transform,
2856                                                                   display_settings->display_device,
2857                                                                   applied_view_settings->exposure,
2858                                                                   applied_view_settings->gamma,
2859                                                                   global_role_scene_linear);
2860
2861         if (applied_view_settings->flag & COLORMANAGE_VIEW_USE_CURVES) {
2862                 cm_processor->curve_mapping = curvemapping_copy(applied_view_settings->curve_mapping);
2863                 curvemapping_premultiply(cm_processor->curve_mapping, false);
2864         }
2865
2866         return cm_processor;
2867 }
2868
2869 ColormanageProcessor *IMB_colormanagement_colorspace_processor_new(const char *from_colorspace, const char *to_colorspace)
2870 {
2871         ColormanageProcessor *cm_processor;
2872         ColorSpace *color_space;
2873
2874         cm_processor = MEM_callocN(sizeof(ColormanageProcessor), "colormanagement processor");
2875
2876         color_space = colormanage_colorspace_get_named(to_colorspace);
2877         cm_processor->is_data_result = color_space->is_data;
2878
2879         cm_processor->processor = create_colorspace_transform_processor(from_colorspace, to_colorspace);
2880
2881         return cm_processor;
2882 }
2883
2884 void IMB_colormanagement_processor_apply_v4(ColormanageProcessor *cm_processor, float pixel[4])
2885 {
2886         if (cm_processor->curve_mapping)
2887                 curvemapping_evaluate_premulRGBF(cm_processor->curve_mapping, pixel, pixel);
2888
2889         if (cm_processor->processor)
2890                 OCIO_processorApplyRGBA(cm_processor->processor, pixel);
2891 }
2892
2893 void IMB_colormanagement_processor_apply_v4_predivide(ColormanageProcessor *cm_processor, float pixel[4])
2894 {
2895         if (cm_processor->curve_mapping)
2896                 curvemapping_evaluate_premulRGBF(cm_processor->curve_mapping, pixel, pixel);
2897
2898         if (cm_processor->processor)
2899                 OCIO_processorApplyRGBA_predivide(cm_processor->processor, pixel);
2900 }
2901
2902 void IMB_colormanagement_processor_apply_v3(ColormanageProcessor *cm_processor, float pixel[3])
2903 {
2904         if (cm_processor->curve_mapping)
2905                 curvemapping_evaluate_premulRGBF(cm_processor->curve_mapping, pixel, pixel);
2906
2907         if (cm_processor->processor)
2908                 OCIO_processorApplyRGB(cm_processor->processor, pixel);
2909 }
2910
2911 void IMB_colormanagement_processor_apply_pixel(struct ColormanageProcessor *cm_processor, float *pixel, int channels)
2912 {
2913         if (channels == 4) {
2914                 IMB_colormanagement_processor_apply_v4_predivide(cm_processor, pixel);
2915         }
2916         else if (channels == 3) {
2917                 IMB_colormanagement_processor_apply_v3(cm_processor, pixel);
2918         }
2919         else if (channels == 1) {
2920                 if (cm_processor->curve_mapping) {
2921                         curve_mapping_apply_pixel(cm_processor->curve_mapping, pixel, 1);
2922                 }
2923         }
2924         else {
2925                 BLI_assert(!"Incorrect number of channels passed to IMB_colormanagement_processor_apply_pixel");
2926         }
2927 }
2928
2929 void IMB_colormanagement_processor_apply(ColormanageProcessor *cm_processor, float *buffer, int width, int height,
2930                                          int channels, bool predivide)
2931 {
2932         /* apply curve mapping */
2933         if (cm_processor->curve_mapping) {
2934                 int x, y;
2935
2936                 for (y = 0; y < height; y++) {
2937                         for (x = 0; x < width; x++) {
2938                                 float *pixel = buffer + channels * (((size_t)y) * width + x);
2939
2940                                 curve_mapping_apply_pixel(cm_processor->curve_mapping, pixel, channels);
2941                         }
2942                 }
2943         }
2944
2945         if (cm_processor->processor && channels >= 3) {
2946                 OCIO_PackedImageDesc *img;
2947
2948                 /* apply OCIO processor */
2949                 img = OCIO_createOCIO_PackedImageDesc(
2950                         buffer, width, height, channels, sizeof(float),
2951                         (size_t)channels * sizeof(float),
2952                         (size_t)channels * sizeof(float) * width);
2953
2954                 if (predivide)
2955                         OCIO_processorApply_predivide(cm_processor->processor, img);
2956                 else
2957                         OCIO_processorApply(cm_processor->processor, img);
2958
2959                 OCIO_PackedImageDescRelease(img);
2960         }
2961 }
2962
2963 void IMB_colormanagement_processor_free(ColormanageProcessor *cm_processor)
2964 {
2965         if (cm_processor->curve_mapping)
2966                 curvemapping_free(cm_processor->curve_mapping);
2967         if (cm_processor->processor)
2968                 OCIO_processorRelease(cm_processor->processor);
2969
2970         MEM_freeN(cm_processor);
2971 }
2972
2973 /* **** OpenGL drawing routines using GLSL for color space transform ***** */
2974
2975 static bool check_glsl_display_processor_changed(const ColorManagedViewSettings *view_settings,
2976                                                  const ColorManagedDisplaySettings *display_settings,
2977                                                  const char *from_colorspace)
2978 {
2979         return !(global_glsl_state.exposure == view_settings->exposure &&
2980                  global_glsl_state.gamma == view_settings->gamma &&
2981                  STREQ(global_glsl_state.look, view_settings->look) &&
2982                  STREQ(global_glsl_state.view, view_settings->view_transform) &&
2983                  STREQ(global_glsl_state.display, display_settings->display_device) &&
2984                  STREQ(global_glsl_state.input, from_colorspace));
2985 }
2986
2987 static void curve_mapping_to_ocio_settings(CurveMapping *curve_mapping,
2988                                            OCIO_CurveMappingSettings *curve_mapping_settings)
2989 {
2990         int i;
2991
2992         curvemapping_initialize(curve_mapping);
2993         curvemapping_premultiply(curve_mapping, false);
2994         curvemapping_table_RGBA(curve_mapping,
2995                                 &curve_mapping_settings->lut,
2996                                 &curve_mapping_settings->lut_size);
2997
2998         for (i = 0; i < 4; i++) {
2999                 CurveMap *cuma = curve_mapping->cm + i;
3000                 curve_mapping_settings->use_extend_extrapolate[i] = (cuma->flag & CUMA_EXTEND_EXTRAPOLATE) != 0;
3001                 curve_mapping_settings->range[i] = cuma->range;
3002                 curve_mapping_settings->mintable[i] = cuma->mintable;
3003                 curve_mapping_settings->ext_in_x[i] = cuma->ext_in[0];
3004                 curve_mapping_settings->ext_in_y[i] = cuma->ext_in[1];
3005                 curve_mapping_settings->ext_out_x[i] = cuma->ext_out[0];
3006                 curve_mapping_settings->ext_out_y[i] = cuma->ext_out[1];
3007                 curve_mapping_settings->first_x[i] = cuma->table[0].x;
3008                 curve_mapping_settings->first_y[i] = cuma->table[0].y;
3009                 curve_mapping_settings->last_x[i] = cuma->table[CM_TABLE].x;
3010                 curve_mapping_settings->last_y[i] = cuma->table[CM_TABLE].y;
3011         }
3012
3013         copy_v3_v3(curve_mapping_settings->black, curve_mapping->black);
3014         copy_v3_v3(curve_mapping_settings->bwmul, curve_mapping->bwmul);
3015
3016         curve_mapping_settings->cache_id = (size_t) curve_mapping;
3017 }
3018
3019 static void update_glsl_display_processor(const ColorManagedViewSettings *view_settings,
3020                                           const ColorManagedDisplaySettings *display_settings,
3021                                           const char *from_colorspace)
3022 {
3023         bool use_curve_mapping = (view_settings->flag & COLORMANAGE_VIEW_USE_CURVES) != 0;
3024         bool need_update = false;
3025
3026         need_update = global_glsl_state.processor == NULL ||
3027                       check_glsl_display_processor_changed(view_settings, display_settings, from_colorspace) ||
3028                       use_curve_mapping != global_glsl_state.use_curve_mapping;
3029
3030         if (use_curve_mapping && need_update == false) {
3031                 need_update |= view_settings->curve_mapping->changed_timestamp != global_glsl_state.curve_mapping_timestamp ||
3032                                view_settings->curve_mapping != global_glsl_state.orig_curve_mapping;
3033         }
3034
3035         /* Update state if there's no processor yet or
3036          * processor settings has been changed.
3037          */
3038         if (need_update) {
3039                 OCIO_CurveMappingSettings *curve_mapping_settings = &global_glsl_state.curve_mapping_settings;
3040                 CurveMapping *new_curve_mapping = NULL;
3041
3042                 /* Store settings of processor for further comparison. */
3043                 BLI_strncpy(global_glsl_state.look, view_settings->look, MAX_COLORSPACE_NAME);
3044                 BLI_strncpy(global_glsl_state.view, view_settings->view_transform, MAX_COLORSPACE_NAME);
3045                 BLI_strncpy(global_glsl_state.display, display_settings->display_device, MAX_COLORSPACE_NAME);
3046                 BLI_strncpy(global_glsl_state.input, from_colorspace, MAX_COLORSPACE_NAME);
3047                 global_glsl_state.exposure = view_settings->exposure;
3048                 global_glsl_state.gamma = view_settings->gamma;
3049
3050                 /* We're using curve mapping's address as a cache ID,
3051                  * so we need to make sure re-allocation gives new address here.
3052                  * We do this by allocating new curve mapping before freeing ol one.
3053                  */
3054                 if (use_curve_mapping) {
3055                         new_curve_mapping = curvemapping_copy(view_settings->curve_mapping);
3056                 }
3057
3058                 if (global_glsl_state.curve_mapping) {
3059                         curvemapping_free(global_glsl_state.curve_mapping);
3060                         MEM_freeN(curve_mapping_settings->lut);
3061                         global_glsl_state.curve_mapping = NULL;
3062                         curve_mapping_settings->lut = NULL;
3063                 }
3064
3065                 /* Fill in OCIO's curve mapping settings. */
3066                 if (use_curve_mapping) {
3067                         curve_mapping_to_ocio_settings(new_curve_mapping, &global_glsl_state.curve_mapping_settings);
3068
3069                         global_glsl_state.curve_mapping = new_curve_mapping;
3070                         global_glsl_state.curve_mapping_timestamp = view_settings->curve_mapping->changed_timestamp;
3071                         global_glsl_state.orig_curve_mapping = view_settings->curve_mapping;
3072                         global_glsl_state.use_curve_mapping = true;
3073                 }
3074                 else {
3075                         global_glsl_state.orig_curve_mapping = NULL;
3076                         global_glsl_state.use_curve_mapping = false;
3077                 }
3078
3079                 /* Free old processor, if any. */
3080                 if (global_glsl_state.processor)
3081                         OCIO_processorRelease(global_glsl_state.processor);
3082
3083                 /* We're using display OCIO processor, no RGB curves yet. */
3084                 global_glsl_state.processor =
3085                         create_display_buffer_processor(global_glsl_state.look,
3086                                                         global_glsl_state.view,
3087                                                         global_glsl_state.display,
3088                                                         global_glsl_state.exposure,
3089                                                         global_glsl_state.gamma,
3090                                                         global_glsl_state.input);
3091         }
3092 }
3093
3094 bool IMB_colormanagement_support_glsl_draw(const ColorManagedViewSettings *UNUSED(view_settings))
3095 {
3096         return OCIO_supportGLSLDraw();
3097 }
3098
3099 /**
3100  * Configures GLSL shader for conversion from specified to
3101  * display color space
3102  *
3103  * Will create appropriate OCIO processor and setup GLSL shader,
3104  * so further 2D texture usage will use this conversion.
3105  *
3106  * When there's no need to apply transform on 2D textures, use
3107  * IMB_colormanagement_finish_glsl_draw().
3108  *
3109  * This is low-level function, use glaDrawImBuf_glsl_ctx if you
3110  * only need to display given image buffer
3111  */
3112 bool IMB_colormanagement_setup_glsl_draw_from_space(const ColorManagedViewSettings *view_settings,
3113                                                     const ColorManagedDisplaySettings *display_settings,
3114                                                     struct ColorSpace *from_colorspace,
3115                                                     float dither, bool predivide)
3116 {
3117         ColorManagedViewSettings default_view_settings;
3118         const ColorManagedViewSettings *applied_view_settings;
3119
3120         if (view_settings) {
3121                 applied_view_settings = view_settings;
3122         }
3123         else {
3124                 /* if no view settings were specified, use default display transformation
3125                  * this happens for images which don't want to be displayed with render settings
3126                  */
3127
3128                 init_default_view_settings(display_settings,  &default_view_settings);
3129                 applied_view_settings = &default_view_settings;
3130         }
3131
3132         /* Make sure OCIO processor is up-to-date. */
3133         update_glsl_display_processor(applied_view_settings, display_settings,
3134                                       from_colorspace ? from_colorspace->name : global_role_scene_linear);
3135
3136         return OCIO_setupGLSLDraw(&global_glsl_state.ocio_glsl_state, global_glsl_state.processor,
3137                                   global_glsl_state.use_curve_mapping ? &global_glsl_state.curve_mapping_settings : NULL,
3138                                   dither, predivide);
3139 }
3140
3141 /* Configures GLSL shader for conversion from scene linear to display space */
3142 bool IMB_colormanagement_setup_glsl_draw(const ColorManagedViewSettings *view_settings,
3143                                          const ColorManagedDisplaySettings *display_settings,
3144                                          float dither, bool predivide)
3145 {
3146         return IMB_colormanagement_setup_glsl_draw_from_space(view_settings, display_settings,
3147                                                               NULL, dither, predivide);
3148 }
3149
3150 /* Same as setup_glsl_draw_from_space, but color management settings are guessing from a given context */
3151 bool IMB_colormanagement_setup_glsl_draw_from_space_ctx(const bContext *C, struct ColorSpace *from_colorspace,
3152                                                         float dither, bool predivide)
3153 {
3154         ColorManagedViewSettings *view_settings;
3155         ColorManagedDisplaySettings *display_settings;
3156
3157         IMB_colormanagement_display_settings_from_ctx(C, &view_settings, &display_settings);
3158
3159         return IMB_colormanagement_setup_glsl_draw_from_space(view_settings, display_settings, from_colorspace,
3160                                                               dither, predivide);
3161 }
3162
3163 /* Same as setup_glsl_draw, but color management settings are guessing from a given context */
3164 bool IMB_colormanagement_setup_glsl_draw_ctx(const bContext *C, float dither, bool predivide)
3165 {
3166         return IMB_colormanagement_setup_glsl_draw_from_space_ctx(C, NULL, dither, predivide);
3167 }
3168
3169 /* Finish GLSL-based display space conversion */
3170 void IMB_colormanagement_finish_glsl_draw(void)
3171 {
3172         OCIO_finishGLSLDraw(global_glsl_state.ocio_glsl_state);
3173 }