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