Draw Engine: remove hard coded limit on array sizes
[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         if (ibuf->rect_colorspace) {
1231                 return ibuf->rect_colorspace->name;
1232         }
1233         else {
1234                 return IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_BYTE);
1235         }
1236 }
1237
1238 /*********************** Threaded display buffer transform routines *************************/
1239
1240 typedef struct DisplayBufferThread {
1241         ColormanageProcessor *cm_processor;
1242
1243         const float *buffer;
1244         unsigned char *byte_buffer;
1245
1246         float *display_buffer;
1247         unsigned char *display_buffer_byte;
1248
1249         int width;
1250         int start_line;
1251         int tot_line;
1252
1253         int channels;
1254         float dither;
1255         bool is_data;
1256
1257         const char *byte_colorspace;
1258         const char *float_colorspace;
1259 } DisplayBufferThread;
1260
1261 typedef struct DisplayBufferInitData {
1262         ImBuf *ibuf;
1263         ColormanageProcessor *cm_processor;
1264         const float *buffer;
1265         unsigned char *byte_buffer;
1266
1267         float *display_buffer;
1268         unsigned char *display_buffer_byte;
1269
1270         int width;
1271
1272         const char *byte_colorspace;
1273         const char *float_colorspace;
1274 } DisplayBufferInitData;
1275
1276 static void display_buffer_init_handle(void *handle_v, int start_line, int tot_line, void *init_data_v)
1277 {
1278         DisplayBufferThread *handle = (DisplayBufferThread *) handle_v;
1279         DisplayBufferInitData *init_data = (DisplayBufferInitData *) init_data_v;
1280         ImBuf *ibuf = init_data->ibuf;
1281
1282         int channels = ibuf->channels;
1283         float dither = ibuf->dither;
1284         bool is_data = (ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA) != 0;
1285
1286         size_t offset = ((size_t)channels) * start_line * ibuf->x;
1287         size_t display_buffer_byte_offset = ((size_t)DISPLAY_BUFFER_CHANNELS) * start_line * ibuf->x;
1288
1289         memset(handle, 0, sizeof(DisplayBufferThread));
1290
1291         handle->cm_processor = init_data->cm_processor;
1292
1293         if (init_data->buffer)
1294                 handle->buffer = init_data->buffer + offset;
1295
1296         if (init_data->byte_buffer)
1297                 handle->byte_buffer = init_data->byte_buffer + offset;
1298
1299         if (init_data->display_buffer)
1300                 handle->display_buffer = init_data->display_buffer + offset;
1301
1302         if (init_data->display_buffer_byte)
1303                 handle->display_buffer_byte = init_data->display_buffer_byte + display_buffer_byte_offset;
1304
1305         handle->width = ibuf->x;
1306
1307         handle->start_line = start_line;
1308         handle->tot_line = tot_line;
1309
1310         handle->channels = channels;
1311         handle->dither = dither;
1312         handle->is_data = is_data;
1313
1314         handle->byte_colorspace = init_data->byte_colorspace;
1315         handle->float_colorspace = init_data->float_colorspace;
1316 }
1317
1318 static void display_buffer_apply_get_linear_buffer(DisplayBufferThread *handle, int height,
1319                                                    float *linear_buffer, bool *is_straight_alpha)
1320 {
1321         int channels = handle->channels;
1322         int width = handle->width;
1323
1324         size_t buffer_size = ((size_t)channels) * width * height;
1325
1326         bool is_data = handle->is_data;
1327         bool is_data_display = handle->cm_processor->is_data_result;
1328
1329         if (!handle->buffer) {
1330                 unsigned char *byte_buffer = handle->byte_buffer;
1331
1332                 const char *from_colorspace = handle->byte_colorspace;
1333                 const char *to_colorspace = global_role_scene_linear;
1334
1335                 float *fp;
1336                 unsigned char *cp;
1337                 const size_t i_last = ((size_t)width) * height;
1338                 size_t i;
1339
1340                 /* first convert byte buffer to float, keep in image space */
1341                 for (i = 0, fp = linear_buffer, cp = byte_buffer;
1342                      i != i_last;
1343                      i++, fp += channels, cp += channels)
1344                 {
1345                         if (channels == 3) {
1346                                 rgb_uchar_to_float(fp, cp);
1347                         }
1348                         else if (channels == 4) {
1349                                 rgba_uchar_to_float(fp, cp);
1350                         }
1351                         else {
1352                                 BLI_assert(!"Buffers of 3 or 4 channels are only supported here");
1353                         }
1354                 }
1355
1356                 if (!is_data && !is_data_display) {
1357                         /* convert float buffer to scene linear space */
1358                         IMB_colormanagement_transform(linear_buffer, width, height, channels,
1359                                                       from_colorspace, to_colorspace, false);
1360                 }
1361
1362                 *is_straight_alpha = true;
1363         }
1364         else if (handle->float_colorspace) {
1365                 /* currently float is non-linear only in sequencer, which is working
1366                  * in it's own color space even to handle float buffers.
1367                  * This color space is the same for byte and float images.
1368                  * Need to convert float buffer to linear space before applying display transform
1369                  */
1370
1371                 const char *from_colorspace = handle->float_colorspace;
1372                 const char *to_colorspace = global_role_scene_linear;
1373
1374                 memcpy(linear_buffer, handle->buffer, buffer_size * sizeof(float));
1375
1376                 if (!is_data && !is_data_display) {
1377                         IMB_colormanagement_transform(linear_buffer, width, height, channels,
1378                                                       from_colorspace, to_colorspace, true);
1379                 }
1380
1381                 *is_straight_alpha = false;
1382         }
1383         else {
1384                 /* some processors would want to modify float original buffer
1385                  * before converting it into display byte buffer, so we need to
1386                  * make sure original's ImBuf buffers wouldn't be modified by
1387                  * using duplicated buffer here
1388                  */
1389
1390                 memcpy(linear_buffer, handle->buffer, buffer_size * sizeof(float));
1391
1392                 *is_straight_alpha = false;
1393         }
1394 }
1395
1396 static void *do_display_buffer_apply_thread(void *handle_v)
1397 {
1398         DisplayBufferThread *handle = (DisplayBufferThread *) handle_v;
1399         ColormanageProcessor *cm_processor = handle->cm_processor;
1400         float *display_buffer = handle->display_buffer;
1401         unsigned char *display_buffer_byte = handle->display_buffer_byte;
1402         int channels = handle->channels;
1403         int width = handle->width;
1404         int height = handle->tot_line;
1405         float dither = handle->dither;
1406         bool is_data = handle->is_data;
1407
1408         if (cm_processor == NULL) {
1409                 if (display_buffer_byte) {
1410                         IMB_buffer_byte_from_byte(display_buffer_byte, handle->byte_buffer, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
1411                                                   false, width, height, width, width);
1412                 }
1413
1414                 if (display_buffer) {
1415                         IMB_buffer_float_from_byte(display_buffer, handle->byte_buffer, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
1416                                                    false, width, height, width, width);
1417                 }
1418         }
1419         else {
1420                 bool is_straight_alpha, predivide;
1421                 float *linear_buffer = MEM_mallocN(((size_t)channels) * width * height * sizeof(float),
1422                                                    "color conversion linear buffer");
1423
1424                 display_buffer_apply_get_linear_buffer(handle, height, linear_buffer, &is_straight_alpha);
1425
1426                 predivide = is_straight_alpha == false;
1427
1428                 if (is_data) {
1429                         /* special case for data buffers - no color space conversions,
1430                          * only generate byte buffers
1431                          */
1432                 }
1433                 else {
1434                         /* apply processor */
1435                         IMB_colormanagement_processor_apply(cm_processor, linear_buffer, width, height, channels,
1436                                                             predivide);
1437                 }
1438
1439                 /* copy result to output buffers */
1440                 if (display_buffer_byte) {
1441                         /* do conversion */
1442                         IMB_buffer_byte_from_float(display_buffer_byte, linear_buffer,
1443                                                    channels, dither, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
1444                                                    predivide, width, height, width, width);
1445                 }
1446
1447                 if (display_buffer) {
1448                         memcpy(display_buffer, linear_buffer, ((size_t)width) * height * channels * sizeof(float));
1449
1450                         if (is_straight_alpha && channels == 4) {
1451                                 const size_t i_last = ((size_t)width) * height;
1452                                 size_t i;
1453                                 float *fp;
1454
1455                                 for (i = 0, fp = display_buffer;
1456                                      i != i_last;
1457                                      i++, fp += channels)
1458                                 {
1459                                         straight_to_premul_v4(fp);
1460                                 }
1461                         }
1462                 }
1463
1464                 MEM_freeN(linear_buffer);
1465         }
1466
1467         return NULL;
1468 }
1469
1470 static void display_buffer_apply_threaded(ImBuf *ibuf, float *buffer, unsigned char *byte_buffer, float *display_buffer,
1471                                           unsigned char *display_buffer_byte, ColormanageProcessor *cm_processor)
1472 {
1473         DisplayBufferInitData init_data;
1474
1475         init_data.ibuf = ibuf;
1476         init_data.cm_processor = cm_processor;
1477         init_data.buffer = buffer;
1478         init_data.byte_buffer = byte_buffer;
1479         init_data.display_buffer = display_buffer;
1480         init_data.display_buffer_byte = display_buffer_byte;
1481
1482         if (ibuf->rect_colorspace != NULL) {
1483                 init_data.byte_colorspace = ibuf->rect_colorspace->name;
1484         }
1485         else {
1486                 /* happens for viewer images, which are not so simple to determine where to
1487                  * set image buffer's color spaces
1488                  */
1489                 init_data.byte_colorspace = global_role_default_byte;
1490         }
1491
1492         if (ibuf->float_colorspace != NULL) {
1493                 /* sequencer stores float buffers in non-linear space */
1494                 init_data.float_colorspace = ibuf->float_colorspace->name;
1495         }
1496         else {
1497                 init_data.float_colorspace = NULL;
1498         }
1499
1500         IMB_processor_apply_threaded(ibuf->y, sizeof(DisplayBufferThread), &init_data,
1501                                      display_buffer_init_handle, do_display_buffer_apply_thread);
1502 }
1503
1504 static bool is_ibuf_rect_in_display_space(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
1505                                           const ColorManagedDisplaySettings *display_settings)
1506 {
1507         if ((view_settings->flag & COLORMANAGE_VIEW_USE_CURVES) == 0 &&
1508             view_settings->exposure == 0.0f &&
1509             view_settings->gamma == 1.0f)
1510         {
1511                 const char *from_colorspace = ibuf->rect_colorspace->name;
1512                 const char *to_colorspace = IMB_colormanagement_get_display_colorspace_name(view_settings, display_settings);
1513
1514                 if (to_colorspace && STREQ(from_colorspace, to_colorspace))
1515                         return true;
1516         }
1517
1518         return false;
1519 }
1520
1521 static void colormanage_display_buffer_process_ex(ImBuf *ibuf, float *display_buffer, unsigned char *display_buffer_byte,
1522                                                   const ColorManagedViewSettings *view_settings,
1523                                                   const ColorManagedDisplaySettings *display_settings)
1524 {
1525         ColormanageProcessor *cm_processor = NULL;
1526         bool skip_transform = false;
1527
1528         /* if we're going to transform byte buffer, check whether transformation would
1529          * happen to the same color space as byte buffer itself is
1530          * this would save byte -> float -> byte conversions making display buffer
1531          * computation noticeable faster
1532          */
1533         if (ibuf->rect_float == NULL && ibuf->rect_colorspace) {
1534                 skip_transform = is_ibuf_rect_in_display_space(ibuf, view_settings, display_settings);
1535         }
1536
1537         if (skip_transform == false)
1538                 cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1539
1540         display_buffer_apply_threaded(ibuf, ibuf->rect_float, (unsigned char *) ibuf->rect,
1541                                       display_buffer, display_buffer_byte, cm_processor);
1542
1543         if (cm_processor)
1544                 IMB_colormanagement_processor_free(cm_processor);
1545 }
1546
1547 static void colormanage_display_buffer_process(ImBuf *ibuf, unsigned char *display_buffer,
1548                                                const ColorManagedViewSettings *view_settings,
1549                                                const ColorManagedDisplaySettings *display_settings)
1550 {
1551         colormanage_display_buffer_process_ex(ibuf, NULL, display_buffer, view_settings, display_settings);
1552 }
1553
1554 /*********************** Threaded processor transform routines *************************/
1555
1556 typedef struct ProcessorTransformThread {
1557         ColormanageProcessor *cm_processor;
1558         unsigned char *byte_buffer;
1559         float *float_buffer;
1560         int width;
1561         int start_line;
1562         int tot_line;
1563         int channels;
1564         bool predivide;
1565         bool float_from_byte;
1566 } ProcessorTransformThread;
1567
1568 typedef struct ProcessorTransformInit {
1569         ColormanageProcessor *cm_processor;
1570         unsigned char *byte_buffer;
1571         float *float_buffer;
1572         int width;
1573         int height;
1574         int channels;
1575         bool predivide;
1576         bool float_from_byte;
1577 } ProcessorTransformInitData;
1578
1579 static void processor_transform_init_handle(void *handle_v, int start_line, int tot_line, void *init_data_v)
1580 {
1581         ProcessorTransformThread *handle = (ProcessorTransformThread *) handle_v;
1582         ProcessorTransformInitData *init_data = (ProcessorTransformInitData *) init_data_v;
1583
1584         const int channels = init_data->channels;
1585         const int width = init_data->width;
1586         const bool predivide = init_data->predivide;
1587         const bool float_from_byte = init_data->float_from_byte;
1588
1589         const size_t offset = ((size_t)channels) * start_line * width;
1590
1591         memset(handle, 0, sizeof(ProcessorTransformThread));
1592
1593         handle->cm_processor = init_data->cm_processor;
1594
1595         if (init_data->byte_buffer != NULL) {
1596                 /* TODO(serge): Offset might be different for byte and float buffers. */
1597                 handle->byte_buffer = init_data->byte_buffer + offset;
1598         }
1599         if (init_data->float_buffer != NULL) {
1600                 handle->float_buffer = init_data->float_buffer + offset;
1601         }
1602
1603         handle->width = width;
1604
1605         handle->start_line = start_line;
1606         handle->tot_line = tot_line;
1607
1608         handle->channels = channels;
1609         handle->predivide = predivide;
1610         handle->float_from_byte = float_from_byte;
1611 }
1612
1613 static void *do_processor_transform_thread(void *handle_v)
1614 {
1615         ProcessorTransformThread *handle = (ProcessorTransformThread *) handle_v;
1616         unsigned char *byte_buffer = handle->byte_buffer;
1617         float *float_buffer = handle->float_buffer;
1618         const int channels = handle->channels;
1619         const int width = handle->width;
1620         const int height = handle->tot_line;
1621         const bool predivide = handle->predivide;
1622         const bool float_from_byte = handle->float_from_byte;
1623
1624         if (float_from_byte) {
1625                 IMB_buffer_float_from_byte(float_buffer, byte_buffer,
1626                                            IB_PROFILE_SRGB, IB_PROFILE_SRGB,
1627                                            true,
1628                                            width, height, width, width);
1629                         IMB_colormanagement_processor_apply(handle->cm_processor,
1630                                                             float_buffer,
1631                                                             width, height, channels,
1632                                                             predivide);
1633         }
1634         else {
1635                 if (byte_buffer != NULL) {
1636                         IMB_colormanagement_processor_apply_byte(handle->cm_processor,
1637                                                                  byte_buffer,
1638                                                                  width, height, channels);
1639                 }
1640                 if (float_buffer != NULL) {
1641                         IMB_colormanagement_processor_apply(handle->cm_processor,
1642                                                             float_buffer,
1643                                                             width, height, channels,
1644                                                             predivide);
1645                 }
1646         }
1647
1648         return NULL;
1649 }
1650
1651 static void processor_transform_apply_threaded(unsigned char *byte_buffer, float *float_buffer,
1652                                                const int width, const int height, const int channels,
1653                                                ColormanageProcessor *cm_processor,
1654                                                const bool predivide, const bool float_from_byte)
1655 {
1656         ProcessorTransformInitData init_data;
1657
1658         init_data.cm_processor = cm_processor;
1659         init_data.byte_buffer = byte_buffer;
1660         init_data.float_buffer = float_buffer;
1661         init_data.width = width;
1662         init_data.height = height;
1663         init_data.channels = channels;
1664         init_data.predivide = predivide;
1665         init_data.float_from_byte = float_from_byte;
1666
1667         IMB_processor_apply_threaded(height, sizeof(ProcessorTransformThread), &init_data,
1668                                      processor_transform_init_handle, do_processor_transform_thread);
1669 }
1670
1671 /*********************** Color space transformation functions *************************/
1672
1673 /* convert the whole buffer from specified by name color space to another - internal implementation */
1674 static void colormanagement_transform_ex(unsigned char *byte_buffer, float *float_buffer,
1675                                          int width, int height, int channels,
1676                                          const char *from_colorspace, const char *to_colorspace,
1677                                          bool predivide, bool do_threaded)
1678 {
1679         ColormanageProcessor *cm_processor;
1680
1681         if (from_colorspace[0] == '\0') {
1682                 return;
1683         }
1684
1685         if (STREQ(from_colorspace, to_colorspace)) {
1686                 /* if source and destination color spaces are identical, skip
1687                  * threading overhead and simply do nothing
1688                  */
1689                 return;
1690         }
1691
1692         cm_processor = IMB_colormanagement_colorspace_processor_new(from_colorspace, to_colorspace);
1693
1694         if (do_threaded) {
1695                 processor_transform_apply_threaded(byte_buffer, float_buffer,
1696                                                    width, height, channels,
1697                                                    cm_processor, predivide, false);
1698         }
1699         else {
1700                 if (byte_buffer != NULL) {
1701                         IMB_colormanagement_processor_apply_byte(cm_processor, byte_buffer, width, height, channels);
1702                 }
1703                 if (float_buffer != NULL) {
1704                         IMB_colormanagement_processor_apply(cm_processor, float_buffer, width, height, channels, predivide);
1705                 }
1706         }
1707
1708         IMB_colormanagement_processor_free(cm_processor);
1709 }
1710
1711 /* convert the whole buffer from specified by name color space to another */
1712 void IMB_colormanagement_transform(float *buffer, int width, int height, int channels,
1713                                    const char *from_colorspace, const char *to_colorspace, bool predivide)
1714 {
1715         colormanagement_transform_ex(NULL, buffer, width, height, channels, from_colorspace, to_colorspace, predivide, false);
1716 }
1717
1718 /* convert the whole buffer from specified by name color space to another
1719  * will do threaded conversion
1720  */
1721 void IMB_colormanagement_transform_threaded(float *buffer, int width, int height, int channels,
1722                                             const char *from_colorspace, const char *to_colorspace, bool predivide)
1723 {
1724         colormanagement_transform_ex(NULL, buffer, width, height, channels, from_colorspace, to_colorspace, predivide, true);
1725 }
1726
1727 /* Similar to functions above, but operates on byte buffer. */
1728 void IMB_colormanagement_transform_byte(unsigned char *buffer, int width, int height, int channels,
1729                                         const char *from_colorspace, const char *to_colorspace)
1730 {
1731         colormanagement_transform_ex(buffer, NULL, width, height, channels, from_colorspace, to_colorspace, false, false);
1732 }
1733 void IMB_colormanagement_transform_byte_threaded(unsigned char *buffer, int width, int height, int channels,
1734                                                  const char *from_colorspace, const char *to_colorspace)
1735 {
1736         colormanagement_transform_ex(buffer, NULL, width, height, channels, from_colorspace, to_colorspace, false, true);
1737 }
1738
1739 /* Similar to above, but gets float buffer from display one. */
1740 void IMB_colormanagement_transform_from_byte(float *float_buffer, unsigned char *byte_buffer,
1741                                              int width, int height, int channels,
1742                                              const char *from_colorspace, const char *to_colorspace)
1743 {
1744         IMB_buffer_float_from_byte(float_buffer, byte_buffer,
1745                                    IB_PROFILE_SRGB, IB_PROFILE_SRGB,
1746                                    true,
1747                                    width, height, width, width);
1748         IMB_colormanagement_transform(float_buffer,
1749                                       width, height, channels,
1750                                       from_colorspace, to_colorspace,
1751                                       true);
1752 }
1753 void IMB_colormanagement_transform_from_byte_threaded(float *float_buffer, unsigned char *byte_buffer,
1754                                                       int width, int height, int channels,
1755                                                       const char *from_colorspace, const char *to_colorspace)
1756 {
1757         ColormanageProcessor *cm_processor;
1758         if (from_colorspace == NULL || from_colorspace[0] == '\0') {
1759                 return;
1760         }
1761         if (STREQ(from_colorspace, to_colorspace)) {
1762                 /* If source and destination color spaces are identical, skip
1763                  * threading overhead and simply do nothing
1764                  */
1765                 return;
1766         }
1767         cm_processor = IMB_colormanagement_colorspace_processor_new(from_colorspace, to_colorspace);
1768         processor_transform_apply_threaded(byte_buffer, float_buffer,
1769                                            width, height, channels,
1770                                            cm_processor, true, true);
1771         IMB_colormanagement_processor_free(cm_processor);
1772 }
1773
1774 void IMB_colormanagement_transform_v4(float pixel[4], const char *from_colorspace, const char *to_colorspace)
1775 {
1776         ColormanageProcessor *cm_processor;
1777
1778         if (from_colorspace[0] == '\0') {
1779                 return;
1780         }
1781
1782         if (STREQ(from_colorspace, to_colorspace)) {
1783                 /* if source and destination color spaces are identical, skip
1784                  * threading overhead and simply do nothing
1785                  */
1786                 return;
1787         }
1788
1789         cm_processor = IMB_colormanagement_colorspace_processor_new(from_colorspace, to_colorspace);
1790
1791         IMB_colormanagement_processor_apply_v4(cm_processor, pixel);
1792
1793         IMB_colormanagement_processor_free(cm_processor);
1794 }
1795
1796 /* convert pixel from specified by descriptor color space to scene linear
1797  * used by performance-critical areas such as renderer and baker
1798  */
1799 void IMB_colormanagement_colorspace_to_scene_linear_v3(float pixel[3], ColorSpace *colorspace)
1800 {
1801         OCIO_ConstProcessorRcPtr *processor;
1802
1803         if (!colorspace) {
1804                 /* should never happen */
1805                 printf("%s: perform conversion from unknown color space\n", __func__);
1806                 return;
1807         }
1808
1809         processor = colorspace_to_scene_linear_processor(colorspace);
1810
1811         if (processor)
1812                 OCIO_processorApplyRGB(processor, pixel);
1813 }
1814
1815 /* same as above, but converts colors in opposite direction */
1816 void IMB_colormanagement_scene_linear_to_colorspace_v3(float pixel[3], ColorSpace *colorspace)
1817 {
1818         OCIO_ConstProcessorRcPtr *processor;
1819
1820         if (!colorspace) {
1821                 /* should never happen */
1822                 printf("%s: perform conversion from unknown color space\n", __func__);
1823                 return;
1824         }
1825
1826         processor = colorspace_from_scene_linear_processor(colorspace);
1827
1828         if (processor)
1829                 OCIO_processorApplyRGB(processor, pixel);
1830 }
1831
1832 void IMB_colormanagement_colorspace_to_scene_linear_v4(float pixel[4], bool predivide, ColorSpace *colorspace)
1833 {
1834         OCIO_ConstProcessorRcPtr *processor;
1835
1836         if (!colorspace) {
1837                 /* should never happen */
1838                 printf("%s: perform conversion from unknown color space\n", __func__);
1839                 return;
1840         }
1841
1842         processor = colorspace_to_scene_linear_processor(colorspace);
1843
1844         if (processor) {
1845                 if (predivide)
1846                         OCIO_processorApplyRGBA_predivide(processor, pixel);
1847                 else
1848                         OCIO_processorApplyRGBA(processor, pixel);
1849         }
1850 }
1851
1852 void IMB_colormanagement_colorspace_to_scene_linear(float *buffer, int width, int height, int channels, struct ColorSpace *colorspace, bool predivide)
1853 {
1854         OCIO_ConstProcessorRcPtr *processor;
1855
1856         if (!colorspace) {
1857                 /* should never happen */
1858                 printf("%s: perform conversion from unknown color space\n", __func__);
1859                 return;
1860         }
1861
1862         processor = colorspace_to_scene_linear_processor(colorspace);
1863
1864         if (processor) {
1865                 OCIO_PackedImageDesc *img;
1866
1867                 img = OCIO_createOCIO_PackedImageDesc(
1868                         buffer, width, height, channels, sizeof(float),
1869                         (size_t)channels * sizeof(float),
1870                         (size_t)channels * sizeof(float) * width);
1871
1872                 if (predivide)
1873                         OCIO_processorApply_predivide(processor, img);
1874                 else
1875                         OCIO_processorApply(processor, img);
1876
1877                 OCIO_PackedImageDescRelease(img);
1878         }
1879 }
1880
1881 /* convert pixel from scene linear to display space using default view
1882  * used by performance-critical areas such as color-related widgets where we want to reduce
1883  * amount of per-widget allocations
1884  */
1885 void IMB_colormanagement_scene_linear_to_display_v3(float pixel[3], ColorManagedDisplay *display)
1886 {
1887         OCIO_ConstProcessorRcPtr *processor;
1888
1889         processor = display_from_scene_linear_processor(display);
1890
1891         if (processor)
1892                 OCIO_processorApplyRGB(processor, pixel);
1893 }
1894
1895 /* same as above, but converts color in opposite direction */
1896 void IMB_colormanagement_display_to_scene_linear_v3(float pixel[3], ColorManagedDisplay *display)
1897 {
1898         OCIO_ConstProcessorRcPtr *processor;
1899
1900         processor = display_to_scene_linear_processor(display);
1901
1902         if (processor)
1903                 OCIO_processorApplyRGB(processor, pixel);
1904 }
1905
1906 void IMB_colormanagement_pixel_to_display_space_v4(float result[4], const float pixel[4],
1907                                                    const ColorManagedViewSettings *view_settings,
1908                                                    const ColorManagedDisplaySettings *display_settings)
1909 {
1910         ColormanageProcessor *cm_processor;
1911
1912         copy_v4_v4(result, pixel);
1913
1914         cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1915         IMB_colormanagement_processor_apply_v4(cm_processor, result);
1916         IMB_colormanagement_processor_free(cm_processor);
1917 }
1918
1919 void IMB_colormanagement_pixel_to_display_space_v3(float result[3], const float pixel[3],
1920                                                    const ColorManagedViewSettings *view_settings,
1921                                                    const ColorManagedDisplaySettings *display_settings)
1922 {
1923         ColormanageProcessor *cm_processor;
1924
1925         copy_v3_v3(result, pixel);
1926
1927         cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1928         IMB_colormanagement_processor_apply_v3(cm_processor, result);
1929         IMB_colormanagement_processor_free(cm_processor);
1930 }
1931
1932 static void colormanagement_imbuf_make_display_space(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
1933                                                      const ColorManagedDisplaySettings *display_settings, bool make_byte)
1934 {
1935         if (!ibuf->rect && make_byte)
1936                 imb_addrectImBuf(ibuf);
1937
1938         colormanage_display_buffer_process_ex(ibuf, ibuf->rect_float, (unsigned char *)ibuf->rect,
1939                                               view_settings, display_settings);
1940 }
1941
1942 void IMB_colormanagement_imbuf_make_display_space(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
1943                                                   const ColorManagedDisplaySettings *display_settings)
1944 {
1945         colormanagement_imbuf_make_display_space(ibuf, view_settings, display_settings, false);
1946 }
1947
1948 /* prepare image buffer to be saved on disk, applying color management if needed
1949  * color management would be applied if image is saving as render result and if
1950  * file format is not expecting float buffer to be in linear space (currently
1951  * JPEG2000 and TIFF are such formats -- they're storing image as float but
1952  * file itself stores applied color space).
1953  *
1954  * Both byte and float buffers would contain applied color space, and result's
1955  * float_colorspace would be set to display color space. This should be checked
1956  * in image format write callback and if float_colorspace is not NULL, no color
1957  * space transformation should be applied on this buffer.
1958  */
1959 ImBuf *IMB_colormanagement_imbuf_for_write(ImBuf *ibuf, bool save_as_render, bool allocate_result, const ColorManagedViewSettings *view_settings,
1960                                            const ColorManagedDisplaySettings *display_settings, ImageFormatData *image_format_data)
1961 {
1962         ImBuf *colormanaged_ibuf = ibuf;
1963         bool do_colormanagement;
1964         bool is_movie = BKE_imtype_is_movie(image_format_data->imtype);
1965         bool requires_linear_float = BKE_imtype_requires_linear_float(image_format_data->imtype);
1966         bool do_alpha_under = image_format_data->planes != R_IMF_PLANES_RGBA;
1967
1968         if (ibuf->rect_float && ibuf->rect &&
1969             (ibuf->userflags & (IB_DISPLAY_BUFFER_INVALID | IB_RECT_INVALID)) != 0)
1970         {
1971                 IMB_rect_from_float(ibuf);
1972                 ibuf->userflags &= ~(IB_RECT_INVALID | IB_DISPLAY_BUFFER_INVALID);
1973         }
1974
1975         do_colormanagement = save_as_render && (is_movie || !requires_linear_float);
1976
1977         if (do_colormanagement || do_alpha_under) {
1978                 if (allocate_result) {
1979                         colormanaged_ibuf = IMB_dupImBuf(ibuf);
1980                 }
1981                 else {
1982                         /* render pipeline is constructing image buffer itself, but it's re-using byte and float buffers from render result
1983                          * make copy of this buffers here sine this buffers would be transformed to other color space here
1984                          */
1985
1986                         if (ibuf->rect && (ibuf->mall & IB_rect) == 0) {
1987                                 ibuf->rect = MEM_dupallocN(ibuf->rect);
1988                                 ibuf->mall |= IB_rect;
1989                         }
1990
1991                         if (ibuf->rect_float && (ibuf->mall & IB_rectfloat) == 0) {
1992                                 ibuf->rect_float = MEM_dupallocN(ibuf->rect_float);
1993                                 ibuf->mall |= IB_rectfloat;
1994                         }
1995                 }
1996         }
1997
1998         /* If we're saving from RGBA to RGB buffer then it's not
1999          * so much useful to just ignore alpha -- it leads to bad
2000          * artifacts especially when saving byte images.
2001          *
2002          * What we do here is we're overlaying our image on top of
2003          * background color (which is currently black).
2004          *
2005          * This is quite much the same as what Gimp does and it
2006          * seems to be what artists expects from saving.
2007          *
2008          * Do a conversion here, so image format writers could
2009          * happily assume all the alpha tricks were made already.
2010          * helps keep things locally here, not spreading it to
2011          * all possible image writers we've got.
2012          */
2013         if (do_alpha_under) {
2014                 float color[3] = {0, 0, 0};
2015
2016                 if (colormanaged_ibuf->rect_float && colormanaged_ibuf->channels == 4) {
2017                         IMB_alpha_under_color_float(colormanaged_ibuf->rect_float, colormanaged_ibuf->x,
2018                                                     colormanaged_ibuf->y, color);
2019                 }
2020
2021                 if (colormanaged_ibuf->rect) {
2022                         IMB_alpha_under_color_byte((unsigned char *)colormanaged_ibuf->rect,
2023                                                    colormanaged_ibuf->x, colormanaged_ibuf->y,
2024                                                    color);
2025                 }
2026         }
2027
2028         if (do_colormanagement) {
2029                 bool make_byte = false;
2030                 const ImFileType *type;
2031
2032                 /* for proper check whether byte buffer is required by a format or not
2033                  * should be pretty safe since this image buffer is supposed to be used for
2034                  * saving only and ftype would be overwritten a bit later by BKE_imbuf_write
2035                  */
2036                 colormanaged_ibuf->ftype = BKE_image_imtype_to_ftype(image_format_data->imtype, &colormanaged_ibuf->foptions);
2037
2038                 /* if file format isn't able to handle float buffer itself,
2039                  * we need to allocate byte buffer and store color managed
2040                  * image there
2041                  */
2042                 for (type = IMB_FILE_TYPES; type < IMB_FILE_TYPES_LAST; type++) {
2043                         if (type->save && type->ftype(type, colormanaged_ibuf)) {
2044                                 if ((type->flag & IM_FTYPE_FLOAT) == 0)
2045                                         make_byte = true;
2046
2047                                 break;
2048                         }
2049                 }
2050
2051                 /* perform color space conversions */
2052                 colormanagement_imbuf_make_display_space(colormanaged_ibuf, view_settings, display_settings, make_byte);
2053
2054                 if (colormanaged_ibuf->rect_float) {
2055                         /* float buffer isn't linear anymore,
2056                          * image format write callback should check for this flag and assume
2057                          * no space conversion should happen if ibuf->float_colorspace != NULL
2058                          */
2059                         colormanaged_ibuf->float_colorspace = display_transform_get_colorspace(view_settings, display_settings);
2060                 }
2061         }
2062
2063         return colormanaged_ibuf;
2064 }
2065
2066 void IMB_colormanagement_buffer_make_display_space(float *buffer, unsigned char *display_buffer,
2067                                                    int width, int height, int channels, float dither,
2068                                                    const ColorManagedViewSettings *view_settings,
2069                                                    const ColorManagedDisplaySettings *display_settings)
2070 {
2071         ColormanageProcessor *cm_processor;
2072         size_t float_buffer_size = ((size_t)width) * height * channels * sizeof(float);
2073         float *display_buffer_float = MEM_mallocN(float_buffer_size, "byte_buffer_make_display_space");
2074
2075         /* TODO(sergey): Convert float directly to byte buffer. */
2076
2077         memcpy(display_buffer_float, buffer, float_buffer_size);
2078
2079         cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
2080
2081         processor_transform_apply_threaded(NULL, display_buffer_float, width, height, channels,
2082                                            cm_processor, true, false);
2083
2084         IMB_buffer_byte_from_float(display_buffer, display_buffer_float,
2085                                    channels, dither, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
2086                                    true, width, height, width, width);
2087
2088         MEM_freeN(display_buffer_float);
2089         IMB_colormanagement_processor_free(cm_processor);
2090 }
2091
2092 /*********************** Public display buffers interfaces *************************/
2093
2094 /* acquire display buffer for given image buffer using specified view and display settings */
2095 unsigned char *IMB_display_buffer_acquire(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
2096                                           const ColorManagedDisplaySettings *display_settings, void **cache_handle)
2097 {
2098         unsigned char *display_buffer;
2099         size_t buffer_size;
2100         ColormanageCacheViewSettings cache_view_settings;
2101         ColormanageCacheDisplaySettings cache_display_settings;
2102         ColorManagedViewSettings default_view_settings;
2103         const ColorManagedViewSettings *applied_view_settings;
2104
2105         *cache_handle = NULL;
2106
2107         if (!ibuf->x || !ibuf->y)
2108                 return NULL;
2109
2110         if (view_settings) {
2111                 applied_view_settings = view_settings;
2112         }
2113         else {
2114                 /* if no view settings were specified, use default display transformation
2115                  * this happens for images which don't want to be displayed with render settings
2116                  */
2117
2118                 init_default_view_settings(display_settings,  &default_view_settings);
2119                 applied_view_settings = &default_view_settings;
2120         }
2121
2122         /* early out: no float buffer and byte buffer is already in display space,
2123          * let's just use if
2124          */
2125         if (ibuf->rect_float == NULL && ibuf->rect_colorspace && ibuf->channels == 4) {
2126                 if (is_ibuf_rect_in_display_space(ibuf, applied_view_settings, display_settings))
2127                         return (unsigned char *) ibuf->rect;
2128         }
2129
2130         colormanage_view_settings_to_cache(ibuf, &cache_view_settings, applied_view_settings);
2131         colormanage_display_settings_to_cache(&cache_display_settings, display_settings);
2132
2133         if (ibuf->invalid_rect.xmin != ibuf->invalid_rect.xmax) {
2134                 if ((ibuf->userflags & IB_DISPLAY_BUFFER_INVALID) == 0) {
2135                         IMB_partial_display_buffer_update_threaded(ibuf,
2136                                                                    ibuf->rect_float,
2137                                                                    (unsigned char *) ibuf->rect,
2138                                                                    ibuf->x,
2139                                                                    0, 0,
2140                                                                    applied_view_settings,
2141                                                                    display_settings,
2142                                                                    ibuf->invalid_rect.xmin,
2143                                                                    ibuf->invalid_rect.ymin,
2144                                                                    ibuf->invalid_rect.xmax,
2145                                                                    ibuf->invalid_rect.ymax,
2146                                                                    false);
2147                 }
2148
2149                 BLI_rcti_init(&ibuf->invalid_rect, 0, 0, 0, 0);
2150         }
2151
2152         BLI_lock_thread(LOCK_COLORMANAGE);
2153
2154         /* ensure color management bit fields exists */
2155         if (!ibuf->display_buffer_flags) {
2156                 ibuf->display_buffer_flags = MEM_callocN(sizeof(unsigned int) * global_tot_display, "imbuf display_buffer_flags");
2157         }
2158         else if (ibuf->userflags & IB_DISPLAY_BUFFER_INVALID) {
2159                 /* all display buffers were marked as invalid from other areas,
2160                  * now propagate this flag to internal color management routines
2161                  */
2162                 memset(ibuf->display_buffer_flags, 0, global_tot_display * sizeof(unsigned int));
2163
2164                 ibuf->userflags &= ~IB_DISPLAY_BUFFER_INVALID;
2165         }
2166
2167         display_buffer = colormanage_cache_get(ibuf, &cache_view_settings, &cache_display_settings, cache_handle);
2168
2169         if (display_buffer) {
2170                 BLI_unlock_thread(LOCK_COLORMANAGE);
2171                 return display_buffer;
2172         }
2173
2174         buffer_size = DISPLAY_BUFFER_CHANNELS * ((size_t)ibuf->x) * ibuf->y * sizeof(char);
2175         display_buffer = MEM_callocN(buffer_size, "imbuf display buffer");
2176
2177         colormanage_display_buffer_process(ibuf, display_buffer, applied_view_settings, display_settings);
2178
2179         colormanage_cache_put(ibuf, &cache_view_settings, &cache_display_settings, display_buffer, cache_handle);
2180
2181         BLI_unlock_thread(LOCK_COLORMANAGE);
2182
2183         return display_buffer;
2184 }
2185
2186 /* same as IMB_display_buffer_acquire but gets view and display settings from context */
2187 unsigned char *IMB_display_buffer_acquire_ctx(const bContext *C, ImBuf *ibuf, void **cache_handle)
2188 {
2189         ColorManagedViewSettings *view_settings;
2190         ColorManagedDisplaySettings *display_settings;
2191
2192         IMB_colormanagement_display_settings_from_ctx(C, &view_settings, &display_settings);
2193
2194         return IMB_display_buffer_acquire(ibuf, view_settings, display_settings, cache_handle);
2195 }
2196
2197 void IMB_display_buffer_transform_apply(unsigned char *display_buffer, float *linear_buffer, int width, int height,
2198                                         int channels, const ColorManagedViewSettings *view_settings,
2199                                         const ColorManagedDisplaySettings *display_settings, bool predivide)
2200 {
2201         float *buffer;
2202         ColormanageProcessor *cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
2203
2204         buffer = MEM_mallocN((size_t)channels * width * height * sizeof(float), "display transform temp buffer");
2205         memcpy(buffer, linear_buffer, (size_t)channels * width * height * sizeof(float));
2206
2207         IMB_colormanagement_processor_apply(cm_processor, buffer, width, height, channels, predivide);
2208
2209         IMB_colormanagement_processor_free(cm_processor);
2210
2211         IMB_buffer_byte_from_float(display_buffer, buffer, channels, 0.0f, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
2212                                    false, width, height, width, width);
2213
2214         MEM_freeN(buffer);
2215 }
2216
2217 void IMB_display_buffer_release(void *cache_handle)
2218 {
2219         if (cache_handle) {
2220                 BLI_lock_thread(LOCK_COLORMANAGE);
2221
2222                 colormanage_cache_handle_release(cache_handle);
2223
2224                 BLI_unlock_thread(LOCK_COLORMANAGE);
2225         }
2226 }
2227
2228 /*********************** Display functions *************************/
2229
2230 const char *colormanage_display_get_default_name(void)
2231 {
2232         OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
2233         const char *display_name;
2234
2235         display_name = OCIO_configGetDefaultDisplay(config);
2236
2237         OCIO_configRelease(config);
2238
2239         return display_name;
2240 }
2241
2242 ColorManagedDisplay *colormanage_display_get_default(void)
2243 {
2244         const char *display_name = colormanage_display_get_default_name();
2245
2246         if (display_name[0] == '\0')
2247                 return NULL;
2248
2249         return colormanage_display_get_named(display_name);
2250 }
2251
2252 ColorManagedDisplay *colormanage_display_add(const char *name)
2253 {
2254         ColorManagedDisplay *display;
2255         int index = 0;
2256
2257         if (global_displays.last) {
2258                 ColorManagedDisplay *last_display = global_displays.last;
2259
2260                 index = last_display->index;
2261         }
2262
2263         display = MEM_callocN(sizeof(ColorManagedDisplay), "ColorManagedDisplay");
2264
2265         display->index = index + 1;
2266
2267         BLI_strncpy(display->name, name, sizeof(display->name));
2268
2269         BLI_addtail(&global_displays, display);
2270
2271         return display;
2272 }
2273
2274 ColorManagedDisplay *colormanage_display_get_named(const char *name)
2275 {
2276         ColorManagedDisplay *display;
2277
2278         for (display = global_displays.first; display; display = display->next) {
2279                 if (STREQ(display->name, name))
2280                         return display;
2281         }
2282
2283         return NULL;
2284 }
2285
2286 ColorManagedDisplay *colormanage_display_get_indexed(int index)
2287 {
2288         /* display indices are 1-based */
2289         return BLI_findlink(&global_displays, index - 1);
2290 }
2291
2292 int IMB_colormanagement_display_get_named_index(const char *name)
2293 {
2294         ColorManagedDisplay *display;
2295
2296         display = colormanage_display_get_named(name);
2297
2298         if (display) {
2299                 return display->index;
2300         }
2301
2302         return 0;
2303 }
2304
2305 const char *IMB_colormanagement_display_get_indexed_name(int index)
2306 {
2307         ColorManagedDisplay *display;
2308
2309         display = colormanage_display_get_indexed(index);
2310
2311         if (display) {
2312                 return display->name;
2313         }
2314
2315         return NULL;
2316 }
2317
2318 const char *IMB_colormanagement_display_get_default_name(void)
2319 {
2320         ColorManagedDisplay *display = colormanage_display_get_default();
2321
2322         return display->name;
2323 }
2324
2325 /* used by performance-critical pixel processing areas, such as color widgets */
2326 ColorManagedDisplay *IMB_colormanagement_display_get_named(const char *name)
2327 {
2328         return colormanage_display_get_named(name);
2329 }
2330
2331 const char *IMB_colormanagement_display_get_none_name(void)
2332 {
2333         if (colormanage_display_get_named("None") != NULL)
2334                 return "None";
2335
2336         return colormanage_display_get_default_name();
2337 }
2338
2339 /*********************** View functions *************************/
2340
2341 const char *colormanage_view_get_default_name(const ColorManagedDisplay *display)
2342 {
2343         OCIO_ConstConfigRcPtr *config = OCIO_getCurrentConfig();
2344         const char *name;
2345
2346         name = OCIO_configGetDefaultView(config, display->name);
2347
2348         OCIO_configRelease(config);
2349
2350         return name;
2351 }
2352
2353 ColorManagedView *colormanage_view_get_default(const ColorManagedDisplay *display)
2354 {
2355         const char *name = colormanage_view_get_default_name(display);
2356
2357         if (!name || name[0] == '\0')
2358                 return NULL;
2359
2360         return colormanage_view_get_named(name);
2361 }
2362
2363 ColorManagedView *colormanage_view_add(const char *name)
2364 {
2365         ColorManagedView *view;
2366         int index = global_tot_view;
2367
2368         view = MEM_callocN(sizeof(ColorManagedView), "ColorManagedView");
2369         view->index = index + 1;
2370         BLI_strncpy(view->name, name, sizeof(view->name));
2371
2372         BLI_addtail(&global_views, view);
2373
2374         global_tot_view++;
2375
2376         return view;
2377 }
2378
2379 ColorManagedView *colormanage_view_get_named(const char *name)
2380 {
2381         ColorManagedView *view;
2382
2383         for (view = global_views.first; view; view = view->next) {
2384                 if (STREQ(view->name, name))
2385                         return view;
2386         }
2387
2388         return NULL;
2389 }
2390
2391 ColorManagedView *colormanage_view_get_indexed(int index)
2392 {
2393         /* view transform indices are 1-based */
2394         return BLI_findlink(&global_views, index - 1);
2395 }
2396
2397 int IMB_colormanagement_view_get_named_index(const char *name)
2398 {
2399         ColorManagedView *view = colormanage_view_get_named(name);
2400
2401         if (view) {
2402                 return view->index;
2403         }
2404
2405         return 0;
2406 }
2407
2408 const char *IMB_colormanagement_view_get_indexed_name(int index)
2409 {
2410         ColorManagedView *view = colormanage_view_get_indexed(index);
2411
2412         if (view) {
2413                 return view->name;
2414         }
2415
2416         return NULL;
2417 }
2418
2419 const char *IMB_colormanagement_view_get_default_name(const char *display_name)
2420 {
2421         ColorManagedDisplay *display = colormanage_display_get_named(display_name);
2422         ColorManagedView *view = NULL;
2423         
2424         if (display)
2425                 view = colormanage_view_get_default(display);
2426
2427         if (view)
2428                 return view->name;
2429
2430         return NULL;
2431 }
2432
2433 /*********************** Color space functions *************************/
2434
2435 static void colormanage_description_strip(char *description)
2436 {
2437         int i, n;
2438
2439         for (i = (int)strlen(description) - 1; i >= 0; i--) {
2440                 if (ELEM(description[i], '\r', '\n')) {
2441                         description[i] = '\0';
2442                 }
2443                 else {
2444                         break;
2445                 }
2446         }
2447
2448         for (i = 0, n = strlen(description); i < n; i++) {
2449                 if (ELEM(description[i], '\r', '\n')) {
2450                         description[i] = ' ';
2451                 }
2452         }
2453 }
2454
2455 ColorSpace *colormanage_colorspace_add(const char *name, const char *description, bool is_invertible, bool is_data)
2456 {
2457         ColorSpace *colorspace, *prev_space;
2458         int counter = 1;
2459
2460         colorspace = MEM_callocN(sizeof(ColorSpace), "ColorSpace");
2461
2462         BLI_strncpy(colorspace->name, name, sizeof(colorspace->name));
2463
2464         if (description) {
2465                 BLI_strncpy(colorspace->description, description, sizeof(colorspace->description));
2466
2467                 colormanage_description_strip(colorspace->description);
2468         }
2469
2470         colorspace->is_invertible = is_invertible;
2471         colorspace->is_data = is_data;
2472
2473         for (prev_space = global_colorspaces.first; prev_space; prev_space = prev_space->next) {
2474                 if (BLI_strcasecmp(prev_space->name, colorspace->name) > 0)
2475                         break;
2476
2477                 prev_space->index = counter++;
2478         }
2479
2480         if (!prev_space)
2481                 BLI_addtail(&global_colorspaces, colorspace);
2482         else
2483                 BLI_insertlinkbefore(&global_colorspaces, prev_space, colorspace);
2484
2485         colorspace->index = counter++;
2486         for (; prev_space; prev_space = prev_space->next) {
2487                 prev_space->index = counter++;
2488         }
2489
2490         global_tot_colorspace++;
2491
2492         return colorspace;
2493 }
2494
2495 ColorSpace *colormanage_colorspace_get_named(const char *name)
2496 {
2497         ColorSpace *colorspace;
2498
2499         for (colorspace = global_colorspaces.first; colorspace; colorspace = colorspace->next) {
2500                 if (STREQ(colorspace->name, name))
2501                         return colorspace;
2502         }
2503
2504         return NULL;
2505 }
2506
2507 ColorSpace *colormanage_colorspace_get_roled(int role)
2508 {
2509         const char *role_colorspace = IMB_colormanagement_role_colorspace_name_get(role);
2510
2511         return colormanage_colorspace_get_named(role_colorspace);
2512 }
2513
2514 ColorSpace *colormanage_colorspace_get_indexed(int index)
2515 {
2516         /* color space indices are 1-based */
2517         return BLI_findlink(&global_colorspaces, index - 1);
2518 }
2519
2520 int IMB_colormanagement_colorspace_get_named_index(const char *name)
2521 {
2522         ColorSpace *colorspace;
2523
2524         colorspace = colormanage_colorspace_get_named(name);
2525
2526         if (colorspace) {
2527                 return colorspace->index;
2528         }
2529
2530         return 0;
2531 }
2532
2533 const char *IMB_colormanagement_colorspace_get_indexed_name(int index)
2534 {
2535         ColorSpace *colorspace;
2536
2537         colorspace = colormanage_colorspace_get_indexed(index);
2538
2539         if (colorspace) {
2540                 return colorspace->name;
2541         }
2542
2543         return "";
2544 }
2545
2546 void IMB_colormanagment_colorspace_from_ibuf_ftype(ColorManagedColorspaceSettings *colorspace_settings, ImBuf *ibuf)
2547 {
2548         const ImFileType *type;
2549
2550         for (type = IMB_FILE_TYPES; type < IMB_FILE_TYPES_LAST; type++) {
2551                 if (type->save && type->ftype(type, ibuf)) {
2552                         const char *role_colorspace;
2553
2554                         role_colorspace = IMB_colormanagement_role_colorspace_name_get(type->default_save_role);
2555
2556                         BLI_strncpy(colorspace_settings->name, role_colorspace, sizeof(colorspace_settings->name));
2557                 }
2558         }
2559 }
2560
2561 /*********************** Looks functions *************************/
2562
2563 ColorManagedLook *colormanage_look_add(const char *name, const char *process_space, bool is_noop)
2564 {
2565         ColorManagedLook *look;
2566         int index = global_tot_looks;
2567
2568         look = MEM_callocN(sizeof(ColorManagedLook), "ColorManagedLook");
2569         look->index = index + 1;
2570         BLI_strncpy(look->name, name, sizeof(look->name));
2571         BLI_strncpy(look->process_space, process_space, sizeof(look->process_space));
2572         look->is_noop = is_noop;
2573
2574         BLI_addtail(&global_looks, look);
2575
2576         global_tot_looks++;
2577
2578         return look;
2579 }
2580
2581 ColorManagedLook *colormanage_look_get_named(const char *name)
2582 {
2583         ColorManagedLook *look;
2584
2585         for (look = global_looks.first; look; look = look->next) {
2586                 if (STREQ(look->name, name)) {
2587                         return look;
2588                 }
2589         }
2590
2591         return NULL;
2592 }
2593
2594 ColorManagedLook *colormanage_look_get_indexed(int index)
2595 {
2596         /* look indices are 1-based */
2597         return BLI_findlink(&global_looks, index - 1);
2598 }
2599
2600 int IMB_colormanagement_look_get_named_index(const char *name)
2601 {
2602         ColorManagedLook *look;
2603
2604         look = colormanage_look_get_named(name);
2605
2606         if (look) {
2607                 return look->index;
2608         }
2609
2610         return 0;
2611 }
2612
2613 const char *IMB_colormanagement_look_get_indexed_name(int index)
2614 {
2615         ColorManagedLook *look;
2616
2617         look = colormanage_look_get_indexed(index);
2618
2619         if (look) {
2620                 return look->name;
2621         }
2622
2623         return NULL;
2624 }
2625
2626 /*********************** RNA helper functions *************************/
2627
2628 void IMB_colormanagement_display_items_add(EnumPropertyItem **items, int *totitem)
2629 {
2630         ColorManagedDisplay *display;
2631
2632         for (display = global_displays.first; display; display = display->next) {
2633                 EnumPropertyItem item;
2634
2635                 item.value = display->index;
2636                 item.name = display->name;
2637                 item.identifier = display->name;
2638                 item.icon = 0;
2639                 item.description = "";
2640
2641                 RNA_enum_item_add(items, totitem, &item);
2642         }
2643 }
2644
2645 static void colormanagement_view_item_add(EnumPropertyItem **items, int *totitem, ColorManagedView *view)
2646 {
2647         EnumPropertyItem item;
2648
2649         item.value = view->index;
2650         item.name = view->name;
2651         item.identifier = view->name;
2652         item.icon = 0;
2653         item.description = "";
2654
2655         RNA_enum_item_add(items, totitem, &item);
2656 }
2657
2658 void IMB_colormanagement_view_items_add(EnumPropertyItem **items, int *totitem, const char *display_name)
2659 {
2660         ColorManagedDisplay *display = colormanage_display_get_named(display_name);
2661         ColorManagedView *view;
2662
2663         if (display) {
2664                 LinkData *display_view;
2665
2666                 for (display_view = display->views.first; display_view; display_view = display_view->next) {
2667                         view = display_view->data;
2668
2669                         colormanagement_view_item_add(items, totitem, view);
2670                 }
2671         }
2672 }
2673
2674 void IMB_colormanagement_look_items_add(struct EnumPropertyItem **items, int *totitem)
2675 {
2676         ColorManagedLook *look;
2677
2678         for (look = global_looks.first; look; look = look->next) {
2679                 EnumPropertyItem item;
2680
2681                 item.value = look->index;
2682                 item.name = look->name;
2683                 item.identifier = look->name;
2684                 item.icon = 0;
2685                 item.description = "";
2686
2687                 RNA_enum_item_add(items, totitem, &item);
2688         }
2689 }
2690
2691 void IMB_colormanagement_colorspace_items_add(EnumPropertyItem **items, int *totitem)
2692 {
2693         ColorSpace *colorspace;
2694
2695         for (colorspace = global_colorspaces.first; colorspace; colorspace = colorspace->next) {
2696                 EnumPropertyItem item;
2697
2698                 if (!colorspace->is_invertible)
2699                         continue;
2700
2701                 item.value = colorspace->index;
2702                 item.name = colorspace->name;
2703                 item.identifier = colorspace->name;
2704                 item.icon = 0;
2705                 item.description = colorspace->description;
2706
2707                 RNA_enum_item_add(items, totitem, &item);
2708         }
2709 }
2710
2711 /*********************** Partial display buffer update  *************************/
2712
2713 /*
2714  * Partial display update is supposed to be used by such areas as
2715  * compositor and renderer, This areas are calculating tiles of the
2716  * images and because of performance reasons only this tiles should
2717  * be color managed.
2718  * This gives nice visual feedback without slowing things down.
2719  *
2720  * Updating happens for active display transformation only, all
2721  * the rest buffers would be marked as dirty
2722  */
2723
2724 static void partial_buffer_update_rect(ImBuf *ibuf,
2725                                        unsigned char *display_buffer,
2726                                        const float *linear_buffer,
2727                                        const unsigned char *byte_buffer,
2728                                        int display_stride,
2729                                        int linear_stride,
2730                                        int linear_offset_x, int linear_offset_y,
2731                                        ColormanageProcessor *cm_processor,
2732                                        const int xmin, const int ymin,
2733                                        const int xmax, const int ymax)
2734 {
2735         int x, y;
2736         int channels = ibuf->channels;
2737         float dither = ibuf->dither;
2738         ColorSpace *rect_colorspace = ibuf->rect_colorspace;
2739         float *display_buffer_float = NULL;
2740         const int width = xmax - xmin;
2741         const int height = ymax - ymin;
2742         bool is_data = (ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA) != 0;
2743
2744         if (dither != 0.0f) {
2745                 /* cm_processor is NULL in cases byte_buffer's space matches display
2746                  * buffer's space
2747                  * in this case we could skip extra transform and only apply dither
2748                  * use 4 channels for easier byte->float->byte conversion here so
2749                  * (this is only needed to apply dither, in other cases we'll convert
2750                  * byte buffer to display directly)
2751                  */
2752                 if (!cm_processor)
2753                         channels = 4;
2754
2755                 display_buffer_float = MEM_callocN((size_t)channels * width * height * sizeof(float), "display buffer for dither");
2756         }
2757
2758         if (cm_processor) {
2759                 for (y = ymin; y < ymax; y++) {
2760                         for (x = xmin; x < xmax; x++) {
2761                                 size_t display_index = ((size_t)y * display_stride + x) * 4;
2762                                 size_t linear_index = ((size_t)(y - linear_offset_y) * linear_stride + (x - linear_offset_x)) * channels;
2763                                 float pixel[4];
2764
2765                                 if (linear_buffer) {
2766                                         if (channels == 4) {
2767                                                 copy_v4_v4(pixel, (float *) linear_buffer + linear_index);
2768                                         }
2769                                         else if (channels == 3) {
2770                                                 copy_v3_v3(pixel, (float *) linear_buffer + linear_index);
2771                                                 pixel[3] = 1.0f;
2772                                         }
2773                                         else if (channels == 1) {
2774                                                 pixel[0] = linear_buffer[linear_index];
2775                                         }
2776                                         else {
2777                                                 BLI_assert(!"Unsupported number of channels in partial buffer update");
2778                                         }
2779                                 }
2780                                 else if (byte_buffer) {
2781                                         rgba_uchar_to_float(pixel, byte_buffer + linear_index);
2782                                         IMB_colormanagement_colorspace_to_scene_linear_v3(pixel, rect_colorspace);
2783                                         straight_to_premul_v4(pixel);
2784                                 }
2785
2786                                 if (!is_data) {
2787                                         IMB_colormanagement_processor_apply_pixel(cm_processor, pixel, channels);
2788                                 }
2789
2790                                 if (display_buffer_float) {
2791                                         size_t index = ((size_t)(y - ymin) * width + (x - xmin)) * channels;
2792
2793                                         if (channels == 4) {
2794                                                 copy_v4_v4(display_buffer_float + index, pixel);
2795                                         }
2796                                         else if (channels == 3) {
2797                                                 copy_v3_v3(display_buffer_float + index, pixel);
2798                                         }
2799                                         else /* if (channels == 1) */ {
2800                                                 display_buffer_float[index] = pixel[0];
2801                                         }
2802                                 }
2803                                 else {
2804                                         if (channels == 4) {
2805                                                 float pixel_straight[4];
2806                                                 premul_to_straight_v4_v4(pixel_straight, pixel);
2807                                                 rgba_float_to_uchar(display_buffer + display_index, pixel_straight);
2808                                         }
2809                                         else if (channels == 3) {
2810                                                 rgb_float_to_uchar(display_buffer + display_index, pixel);
2811                                                 display_buffer[display_index + 3] = 255;
2812                                         }
2813                                         else /* if (channels == 1) */ {
2814                                                 display_buffer[display_index] =
2815                                                         display_buffer[display_index + 1] =
2816                                                         display_buffer[display_index + 2] =
2817                                                         display_buffer[display_index + 3] = FTOCHAR(pixel[0]);
2818                                         }
2819                                 }
2820                         }
2821                 }
2822         }
2823         else {
2824                 if (display_buffer_float) {
2825                         /* huh, for dither we need float buffer first, no cheaper way. currently */
2826                         IMB_buffer_float_from_byte(display_buffer_float, byte_buffer,
2827                                                    IB_PROFILE_SRGB, IB_PROFILE_SRGB, true,
2828                                                    width, height, width, display_stride);
2829                 }
2830                 else {
2831                         int i;
2832
2833                         for (i = ymin; i < ymax; i++) {
2834                                 size_t byte_offset = ((size_t)linear_stride * i + xmin) * 4;
2835                                 size_t display_offset = ((size_t)display_stride * i + xmin) * 4;
2836
2837                                 memcpy(display_buffer + display_offset, byte_buffer + byte_offset, 4 * sizeof(char) * width);
2838                         }
2839                 }
2840         }
2841
2842         if (display_buffer_float) {
2843                 size_t display_index = ((size_t)ymin * display_stride + xmin) * channels;
2844
2845                 IMB_buffer_byte_from_float(display_buffer + display_index, display_buffer_float, channels, dither,
2846                                            IB_PROFILE_SRGB, IB_PROFILE_SRGB, true, width, height, display_stride, width);
2847
2848                 MEM_freeN(display_buffer_float);
2849         }
2850 }
2851
2852 typedef struct PartialThreadData {
2853         ImBuf *ibuf;
2854         unsigned char *display_buffer;
2855         const float *linear_buffer;
2856         const unsigned char *byte_buffer;
2857         int display_stride;
2858         int linear_stride;
2859         int linear_offset_x, linear_offset_y;
2860         ColormanageProcessor *cm_processor;
2861         int xmin, ymin, xmax;
2862 } PartialThreadData;
2863
2864 static void partial_buffer_update_rect_thread_do(void *data_v,
2865                                                  int start_scanline,
2866                                                  int num_scanlines)
2867 {
2868         PartialThreadData *data = (PartialThreadData *)data_v;
2869         int ymin = data->ymin + start_scanline;
2870         partial_buffer_update_rect(data->ibuf,
2871                                    data->display_buffer,
2872                                    data->linear_buffer,
2873                                    data->byte_buffer,
2874                                    data->display_stride,
2875                                    data->linear_stride,
2876                                    data->linear_offset_x,
2877                                    data->linear_offset_y,
2878                                    data->cm_processor,
2879                                    data->xmin,
2880                                    ymin,
2881                                    data->xmax,
2882                                    ymin + num_scanlines);
2883 }
2884
2885 static void imb_partial_display_buffer_update_ex(ImBuf *ibuf,
2886                                                  const float *linear_buffer,
2887                                                  const unsigned char *byte_buffer,
2888                                                  int stride,
2889                                                  int offset_x, int offset_y,
2890                                                  const ColorManagedViewSettings *view_settings,
2891                                                  const ColorManagedDisplaySettings *display_settings,
2892                                                  int xmin, int ymin,
2893                                                  int xmax, int ymax,
2894                                                  bool copy_display_to_byte_buffer,
2895                                                  bool do_threads)
2896 {
2897         ColormanageCacheViewSettings cache_view_settings;
2898         ColormanageCacheDisplaySettings cache_display_settings;
2899         void *cache_handle = NULL;
2900         unsigned char *display_buffer = NULL;
2901         int buffer_width = ibuf->x;
2902
2903         if (ibuf->display_buffer_flags) {
2904                 int view_flag, display_index;
2905
2906                 colormanage_view_settings_to_cache(ibuf, &cache_view_settings, view_settings);
2907                 colormanage_display_settings_to_cache(&cache_display_settings, display_settings);
2908
2909                 view_flag = 1 << (cache_view_settings.view - 1);
2910                 display_index = cache_display_settings.display - 1;
2911
2912                 BLI_lock_thread(LOCK_COLORMANAGE);
2913
2914                 if ((ibuf->userflags & IB_DISPLAY_BUFFER_INVALID) == 0) {
2915                         display_buffer = colormanage_cache_get(ibuf,
2916                                                                &cache_view_settings,
2917                                                                &cache_display_settings,
2918                                                                &cache_handle);
2919                 }
2920
2921                 /* In some rare cases buffer's dimension could be changing directly from
2922                  * different thread
2923                  * this i.e. happens when image editor acquires render result
2924                  */
2925                 buffer_width = ibuf->x;
2926
2927                 /* Mark all other buffers as invalid. */
2928                 memset(ibuf->display_buffer_flags, 0, global_tot_display * sizeof(unsigned int));
2929                 ibuf->display_buffer_flags[display_index] |= view_flag;
2930
2931                 BLI_unlock_thread(LOCK_COLORMANAGE);
2932         }
2933
2934         if (display_buffer == NULL) {
2935                 if (copy_display_to_byte_buffer) {
2936                         display_buffer = (unsigned char *) ibuf->rect;
2937                 }
2938         }
2939
2940         if (display_buffer) {
2941                 ColormanageProcessor *cm_processor = NULL;
2942                 bool skip_transform = false;
2943
2944                 /* Byte buffer is assumed to be in imbuf's rect space, so if byte buffer
2945                  * is known we could skip display->linear->display conversion in case
2946                  * display color space matches imbuf's rect space.
2947                  *
2948                  * But if there's a float buffer it's likely operation was performed on
2949                  * it first and byte buffer is likely to be out of date here.
2950                  */
2951                 if (linear_buffer == NULL && byte_buffer != NULL) {
2952                         skip_transform = is_ibuf_rect_in_display_space(ibuf,
2953                                                                        view_settings,
2954                                                                        display_settings);
2955                 }
2956
2957                 if (!skip_transform) {
2958                         cm_processor = IMB_colormanagement_display_processor_new(
2959                                 view_settings, display_settings);
2960                 }
2961
2962                 if (do_threads) {
2963                         PartialThreadData data;
2964                         data.ibuf = ibuf;
2965                         data.display_buffer = display_buffer;
2966                         data.linear_buffer = linear_buffer;
2967                         data.byte_buffer = byte_buffer;
2968                         data.display_stride = buffer_width;
2969                         data.linear_stride = stride;
2970                         data.linear_offset_x = offset_x;
2971                         data.linear_offset_y = offset_y;
2972                         data.cm_processor = cm_processor;
2973                         data.xmin = xmin;
2974                         data.ymin = ymin;
2975                         data.xmax = xmax;
2976                         IMB_processor_apply_threaded_scanlines(
2977                             ymax - ymin, partial_buffer_update_rect_thread_do, &data);
2978                 }
2979                 else {
2980                         partial_buffer_update_rect(ibuf,
2981                                                    display_buffer, linear_buffer, byte_buffer,
2982                                                    buffer_width,
2983                                                    stride,
2984                                                    offset_x, offset_y,
2985                                                    cm_processor,
2986                                                    xmin, ymin, xmax, ymax);
2987                 }
2988
2989                 if (cm_processor) {
2990                         IMB_colormanagement_processor_free(cm_processor);
2991                 }
2992
2993                 IMB_display_buffer_release(cache_handle);
2994         }
2995
2996         if (copy_display_to_byte_buffer && (unsigned char *) ibuf->rect != display_buffer) {
2997                 int y;
2998                 for (y = ymin; y < ymax; y++) {
2999                         size_t index = (size_t)y * buffer_width * 4;
3000                         memcpy((unsigned char *)ibuf->rect + index,
3001                                display_buffer + index,
3002                                (size_t)(xmax - xmin) * 4);
3003                 }
3004         }
3005 }
3006
3007 void IMB_partial_display_buffer_update(ImBuf *ibuf,
3008                                        const float *linear_buffer,
3009                                        const unsigned char *byte_buffer,
3010                                        int stride,
3011                                        int offset_x, int offset_y,
3012                                        const ColorManagedViewSettings *view_settings,
3013                                        const ColorManagedDisplaySettings *display_settings,
3014                                        int xmin, int ymin,
3015                                        int xmax, int ymax,
3016                                        bool copy_display_to_byte_buffer)
3017 {
3018         imb_partial_display_buffer_update_ex(ibuf,
3019                                              linear_buffer,
3020                                              byte_buffer,
3021                                              stride,
3022                                              offset_x, offset_y,
3023                                              view_settings,
3024                                              display_settings,
3025                                              xmin, ymin,
3026                                              xmax, ymax,
3027                                              copy_display_to_byte_buffer,
3028                                              false);
3029
3030 }
3031
3032 void IMB_partial_display_buffer_update_threaded(struct ImBuf *ibuf,
3033                                                 const float *linear_buffer,
3034                                                 const unsigned char *byte_buffer,
3035                                                 int stride,
3036                                                 int offset_x, int offset_y,
3037                                                 const struct ColorManagedViewSettings *view_settings,
3038                                                 const struct ColorManagedDisplaySettings *display_settings,
3039                                                 int xmin, int ymin, int xmax, int ymax,
3040                                                 bool copy_display_to_byte_buffer)
3041 {
3042         int width = xmax - xmin;
3043         int height = ymax - ymin;
3044         bool do_threads = (((size_t)width) * height >= 64 * 64);
3045         imb_partial_display_buffer_update_ex(ibuf,
3046                                              linear_buffer,
3047                                              byte_buffer,
3048                                              stride,
3049                                              offset_x, offset_y,
3050                                              view_settings,
3051                                              display_settings,
3052                                              xmin, ymin,
3053                                              xmax, ymax,
3054                                              copy_display_to_byte_buffer,
3055                                              do_threads);
3056 }
3057
3058 void IMB_partial_display_buffer_update_delayed(ImBuf *ibuf, int xmin, int ymin, int xmax, int ymax)
3059 {
3060         if (ibuf->invalid_rect.xmin == ibuf->invalid_rect.xmax) {
3061                 BLI_rcti_init(&ibuf->invalid_rect, xmin, xmax, ymin, ymax);
3062         }
3063         else {
3064                 rcti rect;
3065                 BLI_rcti_init(&rect, xmin, xmax, ymin, ymax);
3066                 BLI_rcti_union(&ibuf->invalid_rect, &rect);
3067         }
3068 }
3069
3070 /*********************** Pixel processor functions *************************/
3071
3072 ColormanageProcessor *IMB_colormanagement_display_processor_new(const ColorManagedViewSettings *view_settings,
3073                                                                 const ColorManagedDisplaySettings *display_settings)
3074 {
3075         ColormanageProcessor *cm_processor;
3076         ColorManagedViewSettings default_view_settings;
3077         const ColorManagedViewSettings *applied_view_settings;
3078         ColorSpace *display_space;
3079
3080         cm_processor = MEM_callocN(sizeof(ColormanageProcessor), "colormanagement processor");
3081
3082         if (view_settings) {
3083                 applied_view_settings = view_settings;
3084         }
3085         else {
3086                 init_default_view_settings(display_settings,  &default_view_settings);
3087                 applied_view_settings = &default_view_settings;
3088         }
3089
3090         display_space =  display_transform_get_colorspace(applied_view_settings, display_settings);
3091         if (display_space)
3092                 cm_processor->is_data_result = display_space->is_data;
3093
3094         cm_processor->processor = create_display_buffer_processor(applied_view_settings->look,
3095                                                                   applied_view_settings->view_transform,
3096                                                                   display_settings->display_device,
3097                                                                   applied_view_settings->exposure,
3098                                                                   applied_view_settings->gamma,
3099                                                                   global_role_scene_linear);
3100
3101         if (applied_view_settings->flag & COLORMANAGE_VIEW_USE_CURVES) {
3102                 cm_processor->curve_mapping = curvemapping_copy(applied_view_settings->curve_mapping);
3103                 curvemapping_premultiply(cm_processor->curve_mapping, false);
3104         }
3105
3106         return cm_processor;
3107 }
3108
3109 ColormanageProcessor *IMB_colormanagement_colorspace_processor_new(const char *from_colorspace, const char *to_colorspace)
3110 {
3111         ColormanageProcessor *cm_processor;
3112         ColorSpace *color_space;
3113
3114         cm_processor = MEM_callocN(sizeof(ColormanageProcessor), "colormanagement processor");
3115
3116         color_space = colormanage_colorspace_get_named(to_colorspace);
3117         cm_processor->is_data_result = color_space->is_data;
3118
3119         cm_processor->processor = create_colorspace_transform_processor(from_colorspace, to_colorspace);
3120
3121         return cm_processor;
3122 }
3123
3124 void IMB_colormanagement_processor_apply_v4(ColormanageProcessor *cm_processor, float pixel[4])
3125 {
3126         if (cm_processor->curve_mapping)
3127                 curvemapping_evaluate_premulRGBF(cm_processor->curve_mapping, pixel, pixel);
3128
3129         if (cm_processor->processor)
3130                 OCIO_processorApplyRGBA(cm_processor->processor, pixel);
3131 }
3132
3133 void IMB_colormanagement_processor_apply_v4_predivide(ColormanageProcessor *cm_processor, float pixel[4])
3134 {
3135         if (cm_processor->curve_mapping)
3136                 curvemapping_evaluate_premulRGBF(cm_processor->curve_mapping, pixel, pixel);
3137
3138         if (cm_processor->processor)
3139                 OCIO_processorApplyRGBA_predivide(cm_processor->processor, pixel);
3140 }
3141
3142 void IMB_colormanagement_processor_apply_v3(ColormanageProcessor *cm_processor, float pixel[3])
3143 {
3144         if (cm_processor->curve_mapping)
3145                 curvemapping_evaluate_premulRGBF(cm_processor->curve_mapping, pixel, pixel);
3146
3147         if (cm_processor->processor)
3148                 OCIO_processorApplyRGB(cm_processor->processor, pixel);
3149 }
3150
3151 void IMB_colormanagement_processor_apply_pixel(struct ColormanageProcessor *cm_processor, float *pixel, int channels)
3152 {
3153         if (channels == 4) {
3154                 IMB_colormanagement_processor_apply_v4_predivide(cm_processor, pixel);
3155         }
3156         else if (channels == 3) {
3157                 IMB_colormanagement_processor_apply_v3(cm_processor, pixel);
3158         }
3159         else if (channels == 1) {
3160                 if (cm_processor->curve_mapping) {
3161                         curve_mapping_apply_pixel(cm_processor->curve_mapping, pixel, 1);
3162                 }
3163         }
3164         else {
3165                 BLI_assert(!"Incorrect number of channels passed to IMB_colormanagement_processor_apply_pixel");
3166         }
3167 }
3168
3169 void IMB_colormanagement_processor_apply(ColormanageProcessor *cm_processor, float *buffer, int width, int height,
3170                                          int channels, bool predivide)
3171 {
3172         /* apply curve mapping */
3173         if (cm_processor->curve_mapping) {
3174                 int x, y;
3175
3176                 for (y = 0; y < height; y++) {
3177                         for (x = 0; x < width; x++) {
3178                                 float *pixel = buffer + channels * (((size_t)y) * width + x);
3179
3180                                 curve_mapping_apply_pixel(cm_processor->curve_mapping, pixel, channels);
3181                         }
3182                 }
3183         }
3184
3185         if (cm_processor->processor && channels >= 3) {
3186                 OCIO_PackedImageDesc *img;
3187
3188                 /* apply OCIO processor */
3189                 img = OCIO_createOCIO_PackedImageDesc(
3190                         buffer, width, height, channels, sizeof(float),
3191                         (size_t)channels * sizeof(float),
3192                         (size_t)channels * sizeof(float) * width);
3193
3194                 if (predivide)
3195                         OCIO_processorApply_predivide(cm_processor->processor, img);
3196                 else
3197                         OCIO_processorApply(cm_processor->processor, img);
3198
3199                 OCIO_PackedImageDescRelease(img);
3200         }
3201 }
3202
3203 void IMB_colormanagement_processor_apply_byte(ColormanageProcessor *cm_processor,
3204                                               unsigned char *buffer,
3205                                               int width, int height, int channels)
3206 {
3207         /* TODO(sergey): Would be nice to support arbitrary channels configurations,
3208          * but for now it's not so important.
3209          */
3210         BLI_assert(channels == 4);
3211         float pixel[4];
3212         for (int y = 0; y < height; y++) {
3213                 for (int x = 0; x < width; x++) {
3214                         size_t offset = channels * (((size_t)y) * width + x);
3215                         rgba_uchar_to_float(pixel, buffer + offset);
3216                         IMB_colormanagement_processor_apply_v4(cm_processor, pixel);