Implement threaded partial display buffer update
[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_threaded(ibuf,
2031                                                                    ibuf->rect_float,
2032                                                                    (unsigned char *) ibuf->rect,
2033                                                                    ibuf->x,
2034                                                                    0, 0,
2035                                                                    applied_view_settings,
2036                                                                    display_settings,
2037                                                                    ibuf->invalid_rect.xmin,
2038                                                                    ibuf->invalid_rect.ymin,
2039                                                                    ibuf->invalid_rect.xmax,
2040                                                                    ibuf->invalid_rect.ymax,
2041                                                                    false);
2042                 }
2043
2044                 BLI_rcti_init(&ibuf->invalid_rect, 0, 0, 0, 0);
2045         }
2046
2047         BLI_lock_thread(LOCK_COLORMANAGE);
2048
2049         /* ensure color management bit fields exists */
2050         if (!ibuf->display_buffer_flags) {
2051                 ibuf->display_buffer_flags = MEM_callocN(sizeof(unsigned int) * global_tot_display, "imbuf display_buffer_flags");
2052         }
2053         else if (ibuf->userflags & IB_DISPLAY_BUFFER_INVALID) {
2054                 /* all display buffers were marked as invalid from other areas,
2055                  * now propagate this flag to internal color management routines
2056                  */
2057                 memset(ibuf->display_buffer_flags, 0, global_tot_display * sizeof(unsigned int));
2058
2059                 ibuf->userflags &= ~IB_DISPLAY_BUFFER_INVALID;
2060         }
2061
2062         display_buffer = colormanage_cache_get(ibuf, &cache_view_settings, &cache_display_settings, cache_handle);
2063
2064         if (display_buffer) {
2065                 BLI_unlock_thread(LOCK_COLORMANAGE);
2066                 return display_buffer;
2067         }
2068
2069         buffer_size = DISPLAY_BUFFER_CHANNELS * ((size_t)ibuf->x) * ibuf->y * sizeof(char);
2070         display_buffer = MEM_callocN(buffer_size, "imbuf display buffer");
2071
2072         colormanage_display_buffer_process(ibuf, display_buffer, applied_view_settings, display_settings);
2073
2074         colormanage_cache_put(ibuf, &cache_view_settings, &cache_display_settings, display_buffer, cache_handle);
2075
2076         BLI_unlock_thread(LOCK_COLORMANAGE);
2077
2078         return display_buffer;
2079 }
2080
2081 /* same as IMB_display_buffer_acquire but gets view and display settings from context */
2082 unsigned char *IMB_display_buffer_acquire_ctx(const bContext *C, ImBuf *ibuf, void **cache_handle)
2083 {
2084         ColorManagedViewSettings *view_settings;
2085         ColorManagedDisplaySettings *display_settings;
2086
2087         IMB_colormanagement_display_settings_from_ctx(C, &view_settings, &display_settings);
2088
2089         return IMB_display_buffer_acquire(ibuf, view_settings, display_settings, cache_handle);
2090 }
2091
2092 void IMB_display_buffer_transform_apply(unsigned char *display_buffer, float *linear_buffer, int width, int height,
2093                                         int channels, const ColorManagedViewSettings *view_settings,
2094                                         const ColorManagedDisplaySettings *display_settings, bool predivide)
2095 {
2096         float *buffer;
2097         ColormanageProcessor *cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
2098
2099         buffer = MEM_mallocN((size_t)channels * width * height * sizeof(float), "display transform temp buffer");
2100         memcpy(buffer, linear_buffer, (size_t)channels * width * height * sizeof(float));
2101
2102         IMB_colormanagement_processor_apply(cm_processor, buffer, width, height, channels, predivide);
2103
2104         IMB_colormanagement_processor_free(cm_processor);
2105
2106         IMB_buffer_byte_from_float(display_buffer, buffer, channels, 0.0f, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
2107                                    false, width, height, width, width);
2108
2109         MEM_freeN(buffer);
2110 }
2111
2112 void IMB_display_buffer_release(void *cache_handle)
2113 {
2114         if (cache_handle) {
2115                 BLI_lock_thread(LOCK_COLORMANAGE);
2116
2117                 colormanage_cache_handle_release(cache_handle);
2118
2119                 BLI_unlock_thread(LOCK_COLORMANAGE);
2120         }
2121 }
2122
2123 /*********************** Display functions *************************/
2124
2125 const char *colormanage_display_get_default_name(void)
2126 {
2127         OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
2128         const char *display_name;
2129
2130         display_name = OCIO_configGetDefaultDisplay(config);
2131
2132         OCIO_configRelease(config);
2133
2134         return display_name;
2135 }
2136
2137 ColorManagedDisplay *colormanage_display_get_default(void)
2138 {
2139         const char *display_name = colormanage_display_get_default_name();
2140
2141         if (display_name[0] == '\0')
2142                 return NULL;
2143
2144         return colormanage_display_get_named(display_name);
2145 }
2146
2147 ColorManagedDisplay *colormanage_display_add(const char *name)
2148 {
2149         ColorManagedDisplay *display;
2150         int index = 0;
2151
2152         if (global_displays.last) {
2153                 ColorManagedDisplay *last_display = global_displays.last;
2154
2155                 index = last_display->index;
2156         }
2157
2158         display = MEM_callocN(sizeof(ColorManagedDisplay), "ColorManagedDisplay");
2159
2160         display->index = index + 1;
2161
2162         BLI_strncpy(display->name, name, sizeof(display->name));
2163
2164         BLI_addtail(&global_displays, display);
2165
2166         return display;
2167 }
2168
2169 ColorManagedDisplay *colormanage_display_get_named(const char *name)
2170 {
2171         ColorManagedDisplay *display;
2172
2173         for (display = global_displays.first; display; display = display->next) {
2174                 if (STREQ(display->name, name))
2175                         return display;
2176         }
2177
2178         return NULL;
2179 }
2180
2181 ColorManagedDisplay *colormanage_display_get_indexed(int index)
2182 {
2183         /* display indices are 1-based */
2184         return BLI_findlink(&global_displays, index - 1);
2185 }
2186
2187 int IMB_colormanagement_display_get_named_index(const char *name)
2188 {
2189         ColorManagedDisplay *display;
2190
2191         display = colormanage_display_get_named(name);
2192
2193         if (display) {
2194                 return display->index;
2195         }
2196
2197         return 0;
2198 }
2199
2200 const char *IMB_colormanagement_display_get_indexed_name(int index)
2201 {
2202         ColorManagedDisplay *display;
2203
2204         display = colormanage_display_get_indexed(index);
2205
2206         if (display) {
2207                 return display->name;
2208         }
2209
2210         return NULL;
2211 }
2212
2213 const char *IMB_colormanagement_display_get_default_name(void)
2214 {
2215         ColorManagedDisplay *display = colormanage_display_get_default();
2216
2217         return display->name;
2218 }
2219
2220 /* used by performance-critical pixel processing areas, such as color widgets */
2221 ColorManagedDisplay *IMB_colormanagement_display_get_named(const char *name)
2222 {
2223         return colormanage_display_get_named(name);
2224 }
2225
2226 const char *IMB_colormanagement_display_get_none_name(void)
2227 {
2228         if (colormanage_display_get_named("None") != NULL)
2229                 return "None";
2230
2231         return colormanage_display_get_default_name();
2232 }
2233
2234 /*********************** View functions *************************/
2235
2236 const char *colormanage_view_get_default_name(const ColorManagedDisplay *display)
2237 {
2238         OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
2239         const char *name;
2240
2241         name = OCIO_configGetDefaultView(config, display->name);
2242
2243         OCIO_configRelease(config);
2244
2245         return name;
2246 }
2247
2248 ColorManagedView *colormanage_view_get_default(const ColorManagedDisplay *display)
2249 {
2250         const char *name = colormanage_view_get_default_name(display);
2251
2252         if (!name || name[0] == '\0')
2253                 return NULL;
2254
2255         return colormanage_view_get_named(name);
2256 }
2257
2258 ColorManagedView *colormanage_view_add(const char *name)
2259 {
2260         ColorManagedView *view;
2261         int index = global_tot_view;
2262
2263         view = MEM_callocN(sizeof(ColorManagedView), "ColorManagedView");
2264         view->index = index + 1;
2265         BLI_strncpy(view->name, name, sizeof(view->name));
2266
2267         BLI_addtail(&global_views, view);
2268
2269         global_tot_view++;
2270
2271         return view;
2272 }
2273
2274 ColorManagedView *colormanage_view_get_named(const char *name)
2275 {
2276         ColorManagedView *view;
2277
2278         for (view = global_views.first; view; view = view->next) {
2279                 if (STREQ(view->name, name))
2280                         return view;
2281         }
2282
2283         return NULL;
2284 }
2285
2286 ColorManagedView *colormanage_view_get_indexed(int index)
2287 {
2288         /* view transform indices are 1-based */
2289         return BLI_findlink(&global_views, index - 1);
2290 }
2291
2292 int IMB_colormanagement_view_get_named_index(const char *name)
2293 {
2294         ColorManagedView *view = colormanage_view_get_named(name);
2295
2296         if (view) {
2297                 return view->index;
2298         }
2299
2300         return 0;
2301 }
2302
2303 const char *IMB_colormanagement_view_get_indexed_name(int index)
2304 {
2305         ColorManagedView *view = colormanage_view_get_indexed(index);
2306
2307         if (view) {
2308                 return view->name;
2309         }
2310
2311         return NULL;
2312 }
2313
2314 const char *IMB_colormanagement_view_get_default_name(const char *display_name)
2315 {
2316         ColorManagedDisplay *display = colormanage_display_get_named(display_name);
2317         ColorManagedView *view = NULL;
2318         
2319         if (display)
2320                 view = colormanage_view_get_default(display);
2321
2322         if (view)
2323                 return view->name;
2324
2325         return NULL;
2326 }
2327
2328 /*********************** Color space functions *************************/
2329
2330 static void colormanage_description_strip(char *description)
2331 {
2332         int i, n;
2333
2334         for (i = (int)strlen(description) - 1; i >= 0; i--) {
2335                 if (ELEM(description[i], '\r', '\n')) {
2336                         description[i] = '\0';
2337                 }
2338                 else {
2339                         break;
2340                 }
2341         }
2342
2343         for (i = 0, n = strlen(description); i < n; i++) {
2344                 if (ELEM(description[i], '\r', '\n')) {
2345                         description[i] = ' ';
2346                 }
2347         }
2348 }
2349
2350 ColorSpace *colormanage_colorspace_add(const char *name, const char *description, bool is_invertible, bool is_data)
2351 {
2352         ColorSpace *colorspace, *prev_space;
2353         int counter = 1;
2354
2355         colorspace = MEM_callocN(sizeof(ColorSpace), "ColorSpace");
2356
2357         BLI_strncpy(colorspace->name, name, sizeof(colorspace->name));
2358
2359         if (description) {
2360                 BLI_strncpy(colorspace->description, description, sizeof(colorspace->description));
2361
2362                 colormanage_description_strip(colorspace->description);
2363         }
2364
2365         colorspace->is_invertible = is_invertible;
2366         colorspace->is_data = is_data;
2367
2368         for (prev_space = global_colorspaces.first; prev_space; prev_space = prev_space->next) {
2369                 if (BLI_strcasecmp(prev_space->name, colorspace->name) > 0)
2370                         break;
2371
2372                 prev_space->index = counter++;
2373         }
2374
2375         if (!prev_space)
2376                 BLI_addtail(&global_colorspaces, colorspace);
2377         else
2378                 BLI_insertlinkbefore(&global_colorspaces, prev_space, colorspace);
2379
2380         colorspace->index = counter++;
2381         for (; prev_space; prev_space = prev_space->next) {
2382                 prev_space->index = counter++;
2383         }
2384
2385         global_tot_colorspace++;
2386
2387         return colorspace;
2388 }
2389
2390 ColorSpace *colormanage_colorspace_get_named(const char *name)
2391 {
2392         ColorSpace *colorspace;
2393
2394         for (colorspace = global_colorspaces.first; colorspace; colorspace = colorspace->next) {
2395                 if (STREQ(colorspace->name, name))
2396                         return colorspace;
2397         }
2398
2399         return NULL;
2400 }
2401
2402 ColorSpace *colormanage_colorspace_get_roled(int role)
2403 {
2404         const char *role_colorspace = IMB_colormanagement_role_colorspace_name_get(role);
2405
2406         return colormanage_colorspace_get_named(role_colorspace);
2407 }
2408
2409 ColorSpace *colormanage_colorspace_get_indexed(int index)
2410 {
2411         /* color space indices are 1-based */
2412         return BLI_findlink(&global_colorspaces, index - 1);
2413 }
2414
2415 int IMB_colormanagement_colorspace_get_named_index(const char *name)
2416 {
2417         ColorSpace *colorspace;
2418
2419         colorspace = colormanage_colorspace_get_named(name);
2420
2421         if (colorspace) {
2422                 return colorspace->index;
2423         }
2424
2425         return 0;
2426 }
2427
2428 const char *IMB_colormanagement_colorspace_get_indexed_name(int index)
2429 {
2430         ColorSpace *colorspace;
2431
2432         colorspace = colormanage_colorspace_get_indexed(index);
2433
2434         if (colorspace) {
2435                 return colorspace->name;
2436         }
2437
2438         return "";
2439 }
2440
2441 void IMB_colormanagment_colorspace_from_ibuf_ftype(ColorManagedColorspaceSettings *colorspace_settings, ImBuf *ibuf)
2442 {
2443         const ImFileType *type;
2444
2445         for (type = IMB_FILE_TYPES; type < IMB_FILE_TYPES_LAST; type++) {
2446                 if (type->save && type->ftype(type, ibuf)) {
2447                         const char *role_colorspace;
2448
2449                         role_colorspace = IMB_colormanagement_role_colorspace_name_get(type->default_save_role);
2450
2451                         BLI_strncpy(colorspace_settings->name, role_colorspace, sizeof(colorspace_settings->name));
2452                 }
2453         }
2454 }
2455
2456 /*********************** Looks functions *************************/
2457
2458 ColorManagedLook *colormanage_look_add(const char *name, const char *process_space, bool is_noop)
2459 {
2460         ColorManagedLook *look;
2461         int index = global_tot_looks;
2462
2463         look = MEM_callocN(sizeof(ColorManagedLook), "ColorManagedLook");
2464         look->index = index + 1;
2465         BLI_strncpy(look->name, name, sizeof(look->name));
2466         BLI_strncpy(look->process_space, process_space, sizeof(look->process_space));
2467         look->is_noop = is_noop;
2468
2469         BLI_addtail(&global_looks, look);
2470
2471         global_tot_looks++;
2472
2473         return look;
2474 }
2475
2476 ColorManagedLook *colormanage_look_get_named(const char *name)
2477 {
2478         ColorManagedLook *look;
2479
2480         for (look = global_looks.first; look; look = look->next) {
2481                 if (STREQ(look->name, name)) {
2482                         return look;
2483                 }
2484         }
2485
2486         return NULL;
2487 }
2488
2489 ColorManagedLook *colormanage_look_get_indexed(int index)
2490 {
2491         /* look indices are 1-based */
2492         return BLI_findlink(&global_looks, index - 1);
2493 }
2494
2495 int IMB_colormanagement_look_get_named_index(const char *name)
2496 {
2497         ColorManagedLook *look;
2498
2499         look = colormanage_look_get_named(name);
2500
2501         if (look) {
2502                 return look->index;
2503         }
2504
2505         return 0;
2506 }
2507
2508 const char *IMB_colormanagement_look_get_indexed_name(int index)
2509 {
2510         ColorManagedLook *look;
2511
2512         look = colormanage_look_get_indexed(index);
2513
2514         if (look) {
2515                 return look->name;
2516         }
2517
2518         return NULL;
2519 }
2520
2521 /*********************** RNA helper functions *************************/
2522
2523 void IMB_colormanagement_display_items_add(EnumPropertyItem **items, int *totitem)
2524 {
2525         ColorManagedDisplay *display;
2526
2527         for (display = global_displays.first; display; display = display->next) {
2528                 EnumPropertyItem item;
2529
2530                 item.value = display->index;
2531                 item.name = display->name;
2532                 item.identifier = display->name;
2533                 item.icon = 0;
2534                 item.description = "";
2535
2536                 RNA_enum_item_add(items, totitem, &item);
2537         }
2538 }
2539
2540 static void colormanagement_view_item_add(EnumPropertyItem **items, int *totitem, ColorManagedView *view)
2541 {
2542         EnumPropertyItem item;
2543
2544         item.value = view->index;
2545         item.name = view->name;
2546         item.identifier = view->name;
2547         item.icon = 0;
2548         item.description = "";
2549
2550         RNA_enum_item_add(items, totitem, &item);
2551 }
2552
2553 void IMB_colormanagement_view_items_add(EnumPropertyItem **items, int *totitem, const char *display_name)
2554 {
2555         ColorManagedDisplay *display = colormanage_display_get_named(display_name);
2556         ColorManagedView *view;
2557
2558         if (display) {
2559                 LinkData *display_view;
2560
2561                 for (display_view = display->views.first; display_view; display_view = display_view->next) {
2562                         view = display_view->data;
2563
2564                         colormanagement_view_item_add(items, totitem, view);
2565                 }
2566         }
2567 }
2568
2569 void IMB_colormanagement_look_items_add(struct EnumPropertyItem **items, int *totitem)
2570 {
2571         ColorManagedLook *look;
2572
2573         for (look = global_looks.first; look; look = look->next) {
2574                 EnumPropertyItem item;
2575
2576                 item.value = look->index;
2577                 item.name = look->name;
2578                 item.identifier = look->name;
2579                 item.icon = 0;
2580                 item.description = "";
2581
2582                 RNA_enum_item_add(items, totitem, &item);
2583         }
2584 }
2585
2586 void IMB_colormanagement_colorspace_items_add(EnumPropertyItem **items, int *totitem)
2587 {
2588         ColorSpace *colorspace;
2589
2590         for (colorspace = global_colorspaces.first; colorspace; colorspace = colorspace->next) {
2591                 EnumPropertyItem item;
2592
2593                 if (!colorspace->is_invertible)
2594                         continue;
2595
2596                 item.value = colorspace->index;
2597                 item.name = colorspace->name;
2598                 item.identifier = colorspace->name;
2599                 item.icon = 0;
2600                 item.description = colorspace->description;
2601
2602                 RNA_enum_item_add(items, totitem, &item);
2603         }
2604 }
2605
2606 /*********************** Partial display buffer update  *************************/
2607
2608 /*
2609  * Partial display update is supposed to be used by such areas as
2610  * compositor and renderer, This areas are calculating tiles of the
2611  * images and because of performance reasons only this tiles should
2612  * be color managed.
2613  * This gives nice visual feedback without slowing things down.
2614  *
2615  * Updating happens for active display transformation only, all
2616  * the rest buffers would be marked as dirty
2617  */
2618
2619 static void partial_buffer_update_rect(ImBuf *ibuf,
2620                                        unsigned char *display_buffer,
2621                                        const float *linear_buffer,
2622                                        const unsigned char *byte_buffer,
2623                                        int display_stride,
2624                                        int linear_stride,
2625                                        int linear_offset_x, int linear_offset_y,
2626                                        ColormanageProcessor *cm_processor,
2627                                        const int xmin, const int ymin,
2628                                        const int xmax, const int ymax)
2629 {
2630         int x, y;
2631         int channels = ibuf->channels;
2632         float dither = ibuf->dither;
2633         ColorSpace *rect_colorspace = ibuf->rect_colorspace;
2634         float *display_buffer_float = NULL;
2635         const int width = xmax - xmin;
2636         const int height = ymax - ymin;
2637         bool is_data = (ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA) != 0;
2638
2639         if (dither != 0.0f) {
2640                 /* cm_processor is NULL in cases byte_buffer's space matches display
2641                  * buffer's space
2642                  * in this case we could skip extra transform and only apply dither
2643                  * use 4 channels for easier byte->float->byte conversion here so
2644                  * (this is only needed to apply dither, in other cases we'll convert
2645                  * byte buffer to display directly)
2646                  */
2647                 if (!cm_processor)
2648                         channels = 4;
2649
2650                 display_buffer_float = MEM_callocN((size_t)channels * width * height * sizeof(float), "display buffer for dither");
2651         }
2652
2653         if (cm_processor) {
2654                 for (y = ymin; y < ymax; y++) {
2655                         for (x = xmin; x < xmax; x++) {
2656                                 size_t display_index = ((size_t)y * display_stride + x) * 4;
2657                                 size_t linear_index = ((size_t)(y - linear_offset_y) * linear_stride + (x - linear_offset_x)) * channels;
2658                                 float pixel[4];
2659
2660                                 if (linear_buffer) {
2661                                         if (channels == 4) {
2662                                                 copy_v4_v4(pixel, (float *) linear_buffer + linear_index);
2663                                         }
2664                                         else if (channels == 3) {
2665                                                 copy_v3_v3(pixel, (float *) linear_buffer + linear_index);
2666                                                 pixel[3] = 1.0f;
2667                                         }
2668                                         else if (channels == 1) {
2669                                                 pixel[0] = linear_buffer[linear_index];
2670                                         }
2671                                         else {
2672                                                 BLI_assert(!"Unsupported number of channels in partial buffer update");
2673                                         }
2674                                 }
2675                                 else if (byte_buffer) {
2676                                         rgba_uchar_to_float(pixel, byte_buffer + linear_index);
2677                                         IMB_colormanagement_colorspace_to_scene_linear_v3(pixel, rect_colorspace);
2678                                         straight_to_premul_v4(pixel);
2679                                 }
2680
2681                                 if (!is_data) {
2682                                         IMB_colormanagement_processor_apply_pixel(cm_processor, pixel, channels);
2683                                 }
2684
2685                                 if (display_buffer_float) {
2686                                         size_t index = ((size_t)(y - ymin) * width + (x - xmin)) * channels;
2687
2688                                         if (channels == 4) {
2689                                                 copy_v4_v4(display_buffer_float + index, pixel);
2690                                         }
2691                                         else if (channels == 3) {
2692                                                 copy_v3_v3(display_buffer_float + index, pixel);
2693                                         }
2694                                         else /* if (channels == 1) */ {
2695                                                 display_buffer_float[index] = pixel[0];
2696                                         }
2697                                 }
2698                                 else {
2699                                         if (channels == 4) {
2700                                                 float pixel_straight[4];
2701                                                 premul_to_straight_v4_v4(pixel_straight, pixel);
2702                                                 rgba_float_to_uchar(display_buffer + display_index, pixel_straight);
2703                                         }
2704                                         else if (channels == 3) {
2705                                                 rgb_float_to_uchar(display_buffer + display_index, pixel);
2706                                                 display_buffer[display_index + 3] = 255;
2707                                         }
2708                                         else /* if (channels == 1) */ {
2709                                                 display_buffer[display_index] =
2710                                                         display_buffer[display_index + 1] =
2711                                                         display_buffer[display_index + 2] =
2712                                                         display_buffer[display_index + 3] = FTOCHAR(pixel[0]);
2713                                         }
2714                                 }
2715                         }
2716                 }
2717         }
2718         else {
2719                 if (display_buffer_float) {
2720                         /* huh, for dither we need float buffer first, no cheaper way. currently */
2721                         IMB_buffer_float_from_byte(display_buffer_float, byte_buffer,
2722                                                    IB_PROFILE_SRGB, IB_PROFILE_SRGB, true,
2723                                                    width, height, width, display_stride);
2724                 }
2725                 else {
2726                         int i;
2727
2728                         for (i = ymin; i < ymax; i++) {
2729                                 size_t byte_offset = ((size_t)linear_stride * i + xmin) * 4;
2730                                 size_t display_offset = ((size_t)display_stride * i + xmin) * 4;
2731
2732                                 memcpy(display_buffer + display_offset, byte_buffer + byte_offset, 4 * sizeof(char) * width);
2733                         }
2734                 }
2735         }
2736
2737         if (display_buffer_float) {
2738                 size_t display_index = ((size_t)ymin * display_stride + xmin) * channels;
2739
2740                 IMB_buffer_byte_from_float(display_buffer + display_index, display_buffer_float, channels, dither,
2741                                            IB_PROFILE_SRGB, IB_PROFILE_SRGB, true, width, height, display_stride, width);
2742
2743                 MEM_freeN(display_buffer_float);
2744         }
2745 }
2746
2747 typedef struct PartialThreadData {
2748         ImBuf *ibuf;
2749         unsigned char *display_buffer;
2750         const float *linear_buffer;
2751         const unsigned char *byte_buffer;
2752         int display_stride;
2753         int linear_stride;
2754         int linear_offset_x, linear_offset_y;
2755         ColormanageProcessor *cm_processor;
2756         int xmin, ymin, xmax;
2757 } PartialThreadData;
2758
2759 static void partial_buffer_update_rect_thread_do(void *data_v,
2760                                                  int start_scanline,
2761                                                  int num_scanlines)
2762 {
2763         PartialThreadData *data = (PartialThreadData *)data_v;
2764         int ymin = data->ymin + start_scanline;
2765         partial_buffer_update_rect(data->ibuf,
2766                                    data->display_buffer,
2767                                    data->linear_buffer,
2768                                    data->byte_buffer,
2769                                    data->display_stride,
2770                                    data->linear_stride,
2771                                    data->linear_offset_x,
2772                                    data->linear_offset_y,
2773                                    data->cm_processor,
2774                                    data->xmin,
2775                                    ymin,
2776                                    data->xmax,
2777                                    ymin + num_scanlines);
2778 }
2779
2780 static void imb_partial_display_buffer_update_ex(ImBuf *ibuf,
2781                                                  const float *linear_buffer,
2782                                                  const unsigned char *byte_buffer,
2783                                                  int stride,
2784                                                  int offset_x, int offset_y,
2785                                                  const ColorManagedViewSettings *view_settings,
2786                                                  const ColorManagedDisplaySettings *display_settings,
2787                                                  int xmin, int ymin,
2788                                                  int xmax, int ymax,
2789                                                  bool copy_display_to_byte_buffer,
2790                                                  bool do_threads)
2791 {
2792         ColormanageCacheViewSettings cache_view_settings;
2793         ColormanageCacheDisplaySettings cache_display_settings;
2794         void *cache_handle = NULL;
2795         unsigned char *display_buffer = NULL;
2796         int buffer_width = ibuf->x;
2797
2798         if (ibuf->display_buffer_flags) {
2799                 int view_flag, display_index;
2800
2801                 colormanage_view_settings_to_cache(ibuf, &cache_view_settings, view_settings);
2802                 colormanage_display_settings_to_cache(&cache_display_settings, display_settings);
2803
2804                 view_flag = 1 << (cache_view_settings.view - 1);
2805                 display_index = cache_display_settings.display - 1;
2806
2807                 BLI_lock_thread(LOCK_COLORMANAGE);
2808
2809                 if ((ibuf->userflags & IB_DISPLAY_BUFFER_INVALID) == 0) {
2810                         display_buffer = colormanage_cache_get(ibuf,
2811                                                                &cache_view_settings,
2812                                                                &cache_display_settings,
2813                                                                &cache_handle);
2814                 }
2815
2816                 /* In some rare cases buffer's dimension could be changing directly from
2817                  * different thread
2818                  * this i.e. happens when image editor acquires render result
2819                  */
2820                 buffer_width = ibuf->x;
2821
2822                 /* Mark all other buffers as invalid. */
2823                 memset(ibuf->display_buffer_flags, 0, global_tot_display * sizeof(unsigned int));
2824                 ibuf->display_buffer_flags[display_index] |= view_flag;
2825
2826                 BLI_unlock_thread(LOCK_COLORMANAGE);
2827         }
2828
2829         if (display_buffer == NULL) {
2830                 if (copy_display_to_byte_buffer) {
2831                         display_buffer = (unsigned char *) ibuf->rect;
2832                 }
2833         }
2834
2835         if (display_buffer) {
2836                 ColormanageProcessor *cm_processor = NULL;
2837                 bool skip_transform = false;
2838
2839                 /* Byte buffer is assumed to be in imbuf's rect space, so if byte buffer
2840                  * is known we could skip display->linear->display conversion in case
2841                  * display color space matches imbuf's rect space.
2842                  *
2843                  * But if there's a float buffer it's likely operation was performed on
2844                  * it first and byte buffer is likely to be out of date here.
2845                  */
2846                 if (linear_buffer == NULL && byte_buffer != NULL) {
2847                         skip_transform = is_ibuf_rect_in_display_space(ibuf,
2848                                                                        view_settings,
2849                                                                        display_settings);
2850                 }
2851
2852                 if (!skip_transform) {
2853                         cm_processor = IMB_colormanagement_display_processor_new(
2854                                 view_settings, display_settings);
2855                 }
2856
2857                 if (do_threads) {
2858                         PartialThreadData data;
2859                         data.ibuf = ibuf;
2860                         data.display_buffer = display_buffer;
2861                         data.linear_buffer = linear_buffer;
2862                         data.byte_buffer = byte_buffer;
2863                         data.display_stride = buffer_width;
2864                         data.linear_stride = stride;
2865                         data.linear_offset_x = offset_x;
2866                         data.linear_offset_y = offset_y;
2867                         data.cm_processor = cm_processor;
2868                         data.xmin = xmin;
2869                         data.ymin = ymin;
2870                         data.xmax = xmax;
2871                         IMB_processor_apply_threaded_scanlines(
2872                             ymax - ymin, partial_buffer_update_rect_thread_do, &data);
2873                 }
2874                 else {
2875                         partial_buffer_update_rect(ibuf,
2876                                                    display_buffer, linear_buffer, byte_buffer,
2877                                                    buffer_width,
2878                                                    stride,
2879                                                    offset_x, offset_y,
2880                                                    cm_processor,
2881                                                    xmin, ymin, xmax, ymax);
2882                 }
2883
2884                 if (cm_processor) {
2885                         IMB_colormanagement_processor_free(cm_processor);
2886                 }
2887
2888                 IMB_display_buffer_release(cache_handle);
2889         }
2890
2891         if (copy_display_to_byte_buffer && (unsigned char *) ibuf->rect != display_buffer) {
2892                 int y;
2893                 for (y = ymin; y < ymax; y++) {
2894                         size_t index = (size_t)y * buffer_width * 4;
2895                         memcpy((unsigned char *)ibuf->rect + index,
2896                                display_buffer + index,
2897                                (size_t)(xmax - xmin) * 4);
2898                 }
2899         }
2900 }
2901
2902 void IMB_partial_display_buffer_update(ImBuf *ibuf,
2903                                        const float *linear_buffer,
2904                                        const unsigned char *byte_buffer,
2905                                        int stride,
2906                                        int offset_x, int offset_y,
2907                                        const ColorManagedViewSettings *view_settings,
2908                                        const ColorManagedDisplaySettings *display_settings,
2909                                        int xmin, int ymin,
2910                                        int xmax, int ymax,
2911                                        bool copy_display_to_byte_buffer)
2912 {
2913         imb_partial_display_buffer_update_ex(ibuf,
2914                                              linear_buffer,
2915                                              byte_buffer,
2916                                              stride,
2917                                              offset_x, offset_y,
2918                                              view_settings,
2919                                              display_settings,
2920                                              xmin, ymin,
2921                                              xmax, ymax,
2922                                              copy_display_to_byte_buffer,
2923                                              false);
2924
2925 }
2926
2927 void IMB_partial_display_buffer_update_threaded(struct ImBuf *ibuf,
2928                                                 const float *linear_buffer,
2929                                                 const unsigned char *byte_buffer,
2930                                                 int stride,
2931                                                 int offset_x, int offset_y,
2932                                                 const struct ColorManagedViewSettings *view_settings,
2933                                                 const struct ColorManagedDisplaySettings *display_settings,
2934                                                 int xmin, int ymin, int xmax, int ymax,
2935                                                 bool copy_display_to_byte_buffer)
2936 {
2937         int width = xmax - xmin;
2938         int height = ymax - ymin;
2939         bool do_threads = (((size_t)width) * height >= 64 * 64);
2940         imb_partial_display_buffer_update_ex(ibuf,
2941                                              linear_buffer,
2942                                              byte_buffer,
2943                                              stride,
2944                                              offset_x, offset_y,
2945                                              view_settings,
2946                                              display_settings,
2947                                              xmin, ymin,
2948                                              xmax, ymax,
2949                                              copy_display_to_byte_buffer,
2950                                              do_threads);
2951 }
2952
2953 void IMB_partial_display_buffer_update_delayed(ImBuf *ibuf, int xmin, int ymin, int xmax, int ymax)
2954 {
2955         if (ibuf->invalid_rect.xmin == ibuf->invalid_rect.xmax) {
2956                 BLI_rcti_init(&ibuf->invalid_rect, xmin, xmax, ymin, ymax);
2957         }
2958         else {
2959                 rcti rect;
2960                 BLI_rcti_init(&rect, xmin, xmax, ymin, ymax);
2961                 BLI_rcti_union(&ibuf->invalid_rect, &rect);
2962         }
2963 }
2964
2965 /*********************** Pixel processor functions *************************/
2966
2967 ColormanageProcessor *IMB_colormanagement_display_processor_new(const ColorManagedViewSettings *view_settings,
2968                                                                 const ColorManagedDisplaySettings *display_settings)
2969 {
2970         ColormanageProcessor *cm_processor;
2971         ColorManagedViewSettings default_view_settings;
2972         const ColorManagedViewSettings *applied_view_settings;
2973         ColorSpace *display_space;
2974
2975         cm_processor = MEM_callocN(sizeof(ColormanageProcessor), "colormanagement processor");
2976
2977         if (view_settings) {
2978                 applied_view_settings = view_settings;
2979         }
2980         else {
2981                 init_default_view_settings(display_settings,  &default_view_settings);
2982                 applied_view_settings = &default_view_settings;
2983         }
2984
2985         display_space =  display_transform_get_colorspace(applied_view_settings, display_settings);
2986         if (display_space)
2987                 cm_processor->is_data_result = display_space->is_data;
2988
2989         cm_processor->processor = create_display_buffer_processor(applied_view_settings->look,
2990                                                                   applied_view_settings->view_transform,
2991                                                                   display_settings->display_device,
2992                                                                   applied_view_settings->exposure,
2993                                                                   applied_view_settings->gamma,
2994                                                                   global_role_scene_linear);
2995
2996         if (applied_view_settings->flag & COLORMANAGE_VIEW_USE_CURVES) {
2997                 cm_processor->curve_mapping = curvemapping_copy(applied_view_settings->curve_mapping);
2998                 curvemapping_premultiply(cm_processor->curve_mapping, false);
2999         }
3000
3001         return cm_processor;
3002 }
3003
3004 ColormanageProcessor *IMB_colormanagement_colorspace_processor_new(const char *from_colorspace, const char *to_colorspace)
3005 {
3006         ColormanageProcessor *cm_processor;
3007         ColorSpace *color_space;
3008
3009         cm_processor = MEM_callocN(sizeof(ColormanageProcessor), "colormanagement processor");
3010
3011         color_space = colormanage_colorspace_get_named(to_colorspace);
3012         cm_processor->is_data_result = color_space->is_data;
3013
3014         cm_processor->processor = create_colorspace_transform_processor(from_colorspace, to_colorspace);
3015
3016         return cm_processor;
3017 }
3018
3019 void IMB_colormanagement_processor_apply_v4(ColormanageProcessor *cm_processor, float pixel[4])
3020 {
3021         if (cm_processor->curve_mapping)
3022                 curvemapping_evaluate_premulRGBF(cm_processor->curve_mapping, pixel, pixel);
3023
3024         if (cm_processor->processor)
3025                 OCIO_processorApplyRGBA(cm_processor->processor, pixel);
3026 }
3027
3028 void IMB_colormanagement_processor_apply_v4_predivide(ColormanageProcessor *cm_processor, float pixel[4])
3029 {
3030         if (cm_processor->curve_mapping)
3031                 curvemapping_evaluate_premulRGBF(cm_processor->curve_mapping, pixel, pixel);
3032
3033         if (cm_processor->processor)
3034                 OCIO_processorApplyRGBA_predivide(cm_processor->processor, pixel);
3035 }
3036
3037 void IMB_colormanagement_processor_apply_v3(ColormanageProcessor *cm_processor, float pixel[3])
3038 {
3039         if (cm_processor->curve_mapping)
3040                 curvemapping_evaluate_premulRGBF(cm_processor->curve_mapping, pixel, pixel);
3041
3042         if (cm_processor->processor)
3043                 OCIO_processorApplyRGB(cm_processor->processor, pixel);
3044 }
3045
3046 void IMB_colormanagement_processor_apply_pixel(struct ColormanageProcessor *cm_processor, float *pixel, int channels)
3047 {
3048         if (channels == 4) {
3049                 IMB_colormanagement_processor_apply_v4_predivide(cm_processor, pixel);
3050         }
3051         else if (channels == 3) {
3052                 IMB_colormanagement_processor_apply_v3(cm_processor, pixel);
3053         }
3054         else if (channels == 1) {
3055                 if (cm_processor->curve_mapping) {
3056                         curve_mapping_apply_pixel(cm_processor->curve_mapping, pixel, 1);
3057                 }
3058         }
3059         else {
3060                 BLI_assert(!"Incorrect number of channels passed to IMB_colormanagement_processor_apply_pixel");
3061         }
3062 }
3063
3064 void IMB_colormanagement_processor_apply(ColormanageProcessor *cm_processor, float *buffer, int width, int height,
3065                                          int channels, bool predivide)
3066 {
3067         /* apply curve mapping */
3068         if (cm_processor->curve_mapping) {
3069                 int x, y;
3070
3071                 for (y = 0; y < height; y++) {
3072                         for (x = 0; x < width; x++) {
3073                                 float *pixel = buffer + channels * (((size_t)y) * width + x);
3074
3075                                 curve_mapping_apply_pixel(cm_processor->curve_mapping, pixel, channels);
3076                         }
3077                 }
3078         }
3079
3080         if (cm_processor->processor && channels >= 3) {
3081                 OCIO_PackedImageDesc *img;
3082
3083                 /* apply OCIO processor */
3084                 img = OCIO_createOCIO_PackedImageDesc(
3085                         buffer, width, height, channels, sizeof(float),
3086                         (size_t)channels * sizeof(float),
3087                         (size_t)channels * sizeof(float) * width);
3088
3089                 if (predivide)
3090                         OCIO_processorApply_predivide(cm_processor->processor, img);
3091                 else
3092                         OCIO_processorApply(cm_processor->processor, img);
3093
3094                 OCIO_PackedImageDescRelease(img);
3095         }
3096 }
3097
3098 void IMB_colormanagement_processor_free(ColormanageProcessor *cm_processor)
3099 {
3100         if (cm_processor->curve_mapping)
3101                 curvemapping_free(cm_processor->curve_mapping);
3102         if (cm_processor->processor)
3103                 OCIO_processorRelease(cm_processor->processor);
3104
3105         MEM_freeN(cm_processor);
3106 }
3107
3108 /* **** OpenGL drawing routines using GLSL for color space transform ***** */
3109
3110 static bool check_glsl_display_processor_changed(const ColorManagedViewSettings *view_settings,
3111                                                  const ColorManagedDisplaySettings *display_settings,
3112                                                  const char *from_colorspace)
3113 {
3114         return !(global_glsl_state.exposure == view_settings->exposure &&
3115                  global_glsl_state.gamma == view_settings->gamma &&
3116                  STREQ(global_glsl_state.look, view_settings->look) &&
3117                  STREQ(global_glsl_state.view, view_settings->view_transform) &&
3118                  STREQ(global_glsl_state.display, display_settings->display_device) &&
3119                  STREQ(global_glsl_state.input, from_colorspace));
3120 }
3121
3122 static void curve_mapping_to_ocio_settings(CurveMapping *curve_mapping,
3123                                            OCIO_CurveMappingSettings *curve_mapping_settings)
3124 {
3125         int i;
3126
3127         curvemapping_initialize(curve_mapping);
3128         curvemapping_premultiply(curve_mapping, false);
3129         curvemapping_table_RGBA(curve_mapping,
3130                                 &curve_mapping_settings->lut,
3131                                 &curve_mapping_settings->lut_size);
3132
3133         for (i = 0; i < 4; i++) {
3134                 CurveMap *cuma = curve_mapping->cm + i;
3135                 curve_mapping_settings->use_extend_extrapolate[i] = (cuma->flag & CUMA_EXTEND_EXTRAPOLATE) != 0;
3136                 curve_mapping_settings->range[i] = cuma->range;
3137                 curve_mapping_settings->mintable[i] = cuma->mintable;
3138                 curve_mapping_settings->ext_in_x[i] = cuma->ext_in[0];
3139                 curve_mapping_settings->ext_in_y[i] = cuma->ext_in[1];
3140                 curve_mapping_settings->ext_out_x[i] = cuma->ext_out[0];
3141                 curve_mapping_settings->ext_out_y[i] = cuma->ext_out[1];
3142                 curve_mapping_settings->first_x[i] = cuma->table[0].x;
3143                 curve_mapping_settings->first_y[i] = cuma->table[0].y;
3144                 curve_mapping_settings->last_x[i] = cuma->table[CM_TABLE].x;
3145                 curve_mapping_settings->last_y[i] = cuma->table[CM_TABLE].y;
3146         }
3147
3148         copy_v3_v3(curve_mapping_settings->black, curve_mapping->black);
3149         copy_v3_v3(curve_mapping_settings->bwmul, curve_mapping->bwmul);
3150
3151         curve_mapping_settings->cache_id = (size_t) curve_mapping;
3152 }
3153
3154 static void update_glsl_display_processor(const ColorManagedViewSettings *view_settings,
3155                                           const ColorManagedDisplaySettings *display_settings,
3156                                           const char *from_colorspace)
3157 {
3158         bool use_curve_mapping = (view_settings->flag & COLORMANAGE_VIEW_USE_CURVES) != 0;
3159         bool need_update = false;
3160
3161         need_update = global_glsl_state.processor == NULL ||
3162                       check_glsl_display_processor_changed(view_settings, display_settings, from_colorspace) ||
3163                       use_curve_mapping != global_glsl_state.use_curve_mapping;
3164
3165         if (use_curve_mapping && need_update == false) {
3166                 need_update |= view_settings->curve_mapping->changed_timestamp != global_glsl_state.curve_mapping_timestamp ||
3167                                view_settings->curve_mapping != global_glsl_state.orig_curve_mapping;
3168         }
3169
3170         /* Update state if there's no processor yet or
3171          * processor settings has been changed.
3172          */
3173         if (need_update) {
3174                 OCIO_CurveMappingSettings *curve_mapping_settings = &global_glsl_state.curve_mapping_settings;
3175                 CurveMapping *new_curve_mapping = NULL;
3176
3177                 /* Store settings of processor for further comparison. */
3178                 BLI_strncpy(global_glsl_state.look, view_settings->look, MAX_COLORSPACE_NAME);
3179                 BLI_strncpy(global_glsl_state.view, view_settings->view_transform, MAX_COLORSPACE_NAME);
3180                 BLI_strncpy(global_glsl_state.display, display_settings->display_device, MAX_COLORSPACE_NAME);
3181                 BLI_strncpy(global_glsl_state.input, from_colorspace, MAX_COLORSPACE_NAME);
3182                 global_glsl_state.exposure = view_settings->exposure;
3183                 global_glsl_state.gamma = view_settings->gamma;
3184
3185                 /* We're using curve mapping's address as a cache ID,
3186                  * so we need to make sure re-allocation gives new address here.
3187                  * We do this by allocating new curve mapping before freeing ol one.
3188                  */
3189                 if (use_curve_mapping) {
3190                         new_curve_mapping = curvemapping_copy(view_settings->curve_mapping);
3191                 }
3192
3193                 if (global_glsl_state.curve_mapping) {
3194                         curvemapping_free(global_glsl_state.curve_mapping);
3195                         MEM_freeN(curve_mapping_settings->lut);
3196                         global_glsl_state.curve_mapping = NULL;
3197                         curve_mapping_settings->lut = NULL;
3198                 }
3199
3200                 /* Fill in OCIO's curve mapping settings. */
3201                 if (use_curve_mapping) {
3202                         curve_mapping_to_ocio_settings(new_curve_mapping, &global_glsl_state.curve_mapping_settings);
3203
3204                         global_glsl_state.curve_mapping = new_curve_mapping;
3205                         global_glsl_state.curve_mapping_timestamp = view_settings->curve_mapping->changed_timestamp;
3206                         global_glsl_state.orig_curve_mapping = view_settings->curve_mapping;
3207                         global_glsl_state.use_curve_mapping = true;
3208                 }
3209                 else {
3210                         global_glsl_state.orig_curve_mapping = NULL;
3211                         global_glsl_state.use_curve_mapping = false;
3212                 }
3213
3214                 /* Free old processor, if any. */
3215                 if (global_glsl_state.processor)
3216                         OCIO_processorRelease(global_glsl_state.processor);
3217
3218                 /* We're using display OCIO processor, no RGB curves yet. */
3219                 global_glsl_state.processor =
3220                         create_display_buffer_processor(global_glsl_state.look,
3221                                                         global_glsl_state.view,
3222                                                         global_glsl_state.display,
3223                                                         global_glsl_state.exposure,
3224                                                         global_glsl_state.gamma,
3225                                                         global_glsl_state.input);