Color Management: fix crash when displaying render preview if OCIO was disabled buildtime
[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 #include "IMB_colormanagement.h"
32 #include "IMB_colormanagement_intern.h"
33
34 #include <string.h>
35 #include <math.h>
36
37 #include "DNA_color_types.h"
38 #include "DNA_image_types.h"
39 #include "DNA_movieclip_types.h"
40 #include "DNA_scene_types.h"
41 #include "DNA_screen_types.h"
42 #include "DNA_space_types.h"
43 #include "DNA_windowmanager_types.h"
44
45 #include "IMB_filter.h"
46 #include "IMB_imbuf.h"
47 #include "IMB_imbuf_types.h"
48 #include "IMB_filetype.h"
49 #include "IMB_moviecache.h"
50
51 #include "MEM_guardedalloc.h"
52
53 #include "BLI_blenlib.h"
54 #include "BLI_math.h"
55 #include "BLI_math_color.h"
56 #include "BLI_path_util.h"
57 #include "BLI_string.h"
58 #include "BLI_threads.h"
59
60 #include "BKE_colortools.h"
61 #include "BKE_context.h"
62 #include "BKE_utildefines.h"
63 #include "BKE_main.h"
64
65 #include "RNA_define.h"
66
67 #include <ocio_capi.h>
68
69 /*********************** Global declarations *************************/
70
71 #define MAX_COLORSPACE_NAME 64
72
73 /* ** list of all supported color spaces, displays and views */
74 static char global_role_scene_linear[MAX_COLORSPACE_NAME];
75 static char global_role_color_picking[MAX_COLORSPACE_NAME];
76 static char global_role_texture_painting[MAX_COLORSPACE_NAME];
77 static char global_role_default_byte[MAX_COLORSPACE_NAME];
78 static char global_role_default_float[MAX_COLORSPACE_NAME];
79 static char global_role_default_sequencer[MAX_COLORSPACE_NAME];
80
81 static ListBase global_colorspaces = {NULL};
82 static ListBase global_displays = {NULL};
83 static ListBase global_views = {NULL};
84
85 static int global_tot_colorspace = 0;
86 static int global_tot_display = 0;
87 static int global_tot_view = 0;
88
89 typedef struct ColormanageProcessor {
90         ConstProcessorRcPtr *processor;
91         CurveMapping *curve_mapping;
92 } ColormanageProcessor;
93
94 /*********************** Color managed cache *************************/
95
96 /* Cache Implementation Notes
97  * ==========================
98  *
99  * All color management cache stuff is stored in two properties of
100  * image buffers:
101  *
102  *   1. display_buffer_flags
103  *
104  *      This is a bit field which used to mark calculated transformations
105  *      for particular image buffer. Index inside of this array means index
106  *      of a color managed display. Element with given index matches view
107  *      transformations applied for a given display. So if bit B of array
108  *      element B is set to 1, this means display buffer with display index
109  *      of A and view transform of B was ever calculated for this imbuf.
110  *
111  *      In contrast with indices in global lists of displays and views this
112  *      indices are 0-based, not 1-based. This is needed to save some bytes
113  *      of memory.
114  *
115  *   2. colormanage_cache
116  *
117  *      This is a pointer to a structure which holds all data which is
118  *      needed for color management cache to work.
119  *
120  *      It contains two parts:
121  *        - data
122  *        - moviecache
123  *
124  *      Data field is used to store additional information about cached
125  *      buffers which affects on whether cached buffer could be used.
126  *      This data can't go to cache key because changes in this data
127  *      shouldn't lead extra buffers adding to cache, it shall
128  *      invalidate cached images.
129  *
130  *      Currently such a data contains only exposure and gamma, but
131  *      would likely extended further.
132  *
133  *      data field is not null only for elements of cache, not used for
134  *      original image buffers.
135  *
136  *      Color management cache is using generic MovieCache implementation
137  *      to make it easier to deal with memory limitation.
138  *
139  *      Currently color management is using the same memory limitation
140  *      pool as sequencer and clip editor are using which means color
141  *      managed buffers would be removed from the cache as soon as new
142  *      frames are loading for the movie clip and there's no space in
143  *      cache.
144  *
145  *      Every image buffer has got own movie cache instance, which
146  *      means keys for color managed buffers could be really simple
147  *      and look up in this cache would be fast and independent from
148  *      overall amount of color managed images.
149  */
150
151 /* NOTE: ColormanageCacheViewSettings and ColormanageCacheDisplaySettings are
152  *       quite the same as ColorManagedViewSettings and ColorManageDisplaySettings
153  *       but they holds indexes of all transformations and color spaces, not
154  *       their names.
155  *
156  *       This helps avoid extra colorsmace / display / view lookup without
157  *       requiring to pass all variables which affects on display buffer
158  *       to color management cache system and keeps calls small and nice.
159  */
160 typedef struct ColormanageCacheViewSettings {
161         int flag;
162         int view;
163         float exposure;
164         float gamma;
165         CurveMapping *curve_mapping;
166 } ColormanageCacheViewSettings;
167
168 typedef struct ColormanageCacheDisplaySettings {
169         int display;
170 } ColormanageCacheDisplaySettings;
171
172 typedef struct ColormanageCacheKey {
173         int view;            /* view transformation used for display buffer */
174         int display;         /* display device name */
175 } ColormanageCacheKey;
176
177 typedef struct ColormnaageCacheData {
178         int flag;        /* view flags of cached buffer */
179         float exposure;  /* exposure value cached buffer is calculated with */
180         float gamma;     /* gamma value cached buffer is calculated with */
181         int predivide;   /* predivide flag of cached buffer */
182         CurveMapping *curve_mapping;  /* curve mapping used for cached buffer */
183         int curve_mapping_timestamp;  /* time stamp of curve mapping used for cached buffer */
184 } ColormnaageCacheData;
185
186 typedef struct ColormanageCache {
187         struct MovieCache *moviecache;
188
189         ColormnaageCacheData *data;
190 } ColormanageCache;
191
192 static struct MovieCache *colormanage_moviecache_get(const ImBuf *ibuf)
193 {
194         if (!ibuf->colormanage_cache)
195                 return NULL;
196
197         return ibuf->colormanage_cache->moviecache;
198 }
199
200 static ColormnaageCacheData *colormanage_cachedata_get(const ImBuf *ibuf)
201 {
202         if (!ibuf->colormanage_cache)
203                 return NULL;
204
205         return ibuf->colormanage_cache->data;
206 }
207
208 static unsigned int colormanage_hashhash(const void *key_v)
209 {
210         ColormanageCacheKey *key = (ColormanageCacheKey *)key_v;
211
212         unsigned int rval = (key->display << 16) | (key->view % 0xffff);
213
214         return rval;
215 }
216
217 static int colormanage_hashcmp(const void *av, const void *bv)
218 {
219         const ColormanageCacheKey *a = (ColormanageCacheKey *) av;
220         const ColormanageCacheKey *b = (ColormanageCacheKey *) bv;
221
222         if (a->view < b->view)
223                 return -1;
224         else if (a->view > b->view)
225                 return 1;
226
227         if (a->display < b->display)
228                 return -1;
229         else if (a->display > b->display)
230                 return 1;
231
232         return 0;
233 }
234
235 static struct MovieCache *colormanage_moviecache_ensure(ImBuf *ibuf)
236 {
237         if (!ibuf->colormanage_cache)
238                 ibuf->colormanage_cache = MEM_callocN(sizeof(ColormanageCache), "imbuf colormanage cache");
239
240         if (!ibuf->colormanage_cache->moviecache) {
241                 struct MovieCache *moviecache;
242
243                 moviecache = IMB_moviecache_create("colormanage cache", sizeof(ColormanageCacheKey),
244                                                    colormanage_hashhash, colormanage_hashcmp);
245
246                 ibuf->colormanage_cache->moviecache = moviecache;
247         }
248
249         return ibuf->colormanage_cache->moviecache;
250 }
251
252 static void colormanage_cachedata_set(ImBuf *ibuf, ColormnaageCacheData *data)
253 {
254         if (!ibuf->colormanage_cache)
255                 ibuf->colormanage_cache = MEM_callocN(sizeof(ColormanageCache), "imbuf colormanage cache");
256
257         ibuf->colormanage_cache->data = data;
258 }
259
260 static void colormanage_view_settings_to_cache(ColormanageCacheViewSettings *cache_view_settings,
261                                                const ColorManagedViewSettings *view_settings)
262 {
263         int view = IMB_colormanagement_view_get_named_index(view_settings->view_transform);
264
265         cache_view_settings->view = view;
266         cache_view_settings->exposure = view_settings->exposure;
267         cache_view_settings->gamma = view_settings->gamma;
268         cache_view_settings->flag = view_settings->flag;
269         cache_view_settings->curve_mapping = view_settings->curve_mapping;
270 }
271
272 static void colormanage_display_settings_to_cache(ColormanageCacheDisplaySettings *cache_display_settings,
273                                                   const ColorManagedDisplaySettings *display_settings)
274 {
275         int display = IMB_colormanagement_display_get_named_index(display_settings->display_device);
276
277         cache_display_settings->display = display;
278 }
279
280 static void colormanage_settings_to_key(ColormanageCacheKey *key,
281                                         const ColormanageCacheViewSettings *view_settings,
282                                         const ColormanageCacheDisplaySettings *display_settings)
283 {
284         key->view = view_settings->view;
285         key->display = display_settings->display;
286 }
287
288 static ImBuf *colormanage_cache_get_ibuf(ImBuf *ibuf, ColormanageCacheKey *key, void **cache_handle)
289 {
290         ImBuf *cache_ibuf;
291         struct MovieCache *moviecache = colormanage_moviecache_get(ibuf);
292
293         if (!moviecache) {
294                 /* if there's no moviecache it means no color management was applied on given image buffer before */
295
296                 return NULL;
297         }
298
299         *cache_handle = NULL;
300
301         cache_ibuf = IMB_moviecache_get(moviecache, key);
302
303         *cache_handle = cache_ibuf;
304
305         return cache_ibuf;
306 }
307
308 static unsigned char *colormanage_cache_get(ImBuf *ibuf, const ColormanageCacheViewSettings *view_settings,
309                                             const ColormanageCacheDisplaySettings *display_settings,
310                                             void **cache_handle)
311 {
312         ColormanageCacheKey key;
313         ImBuf *cache_ibuf;
314         int view_flag = 1 << (view_settings->view - 1);
315         int predivide = ibuf->flags & IB_cm_predivide;
316         CurveMapping *curve_mapping = view_settings->curve_mapping;
317         int curve_mapping_timestamp = curve_mapping ? curve_mapping->changed_timestamp : 0;
318
319         colormanage_settings_to_key(&key, view_settings, display_settings);
320
321         /* check whether image was marked as dirty for requested transform */
322         if ((ibuf->display_buffer_flags[display_settings->display - 1] & view_flag) == 0) {
323                 return NULL;
324         }
325
326         cache_ibuf = colormanage_cache_get_ibuf(ibuf, &key, cache_handle);
327
328         if (cache_ibuf) {
329                 ColormnaageCacheData *cache_data;
330
331                 BLI_assert(cache_ibuf->x == ibuf->x &&
332                            cache_ibuf->y == ibuf->y &&
333                            cache_ibuf->channels == ibuf->channels);
334
335                 /* only buffers with different color space conversions are being stored
336                  * in cache separately. buffer which were used only different exposure/gamma
337                  * are re-suing the same cached buffer
338                  *
339                  * check here which exposure/gamma/curve was used for cached buffer and if they're
340                  * different from requested buffer should be re-generated
341                  */
342                 cache_data = colormanage_cachedata_get(cache_ibuf);
343
344                 if (cache_data->exposure != view_settings->exposure ||
345                     cache_data->gamma != view_settings->gamma ||
346                         cache_data->predivide != predivide ||
347                         cache_data->flag != view_settings->flag ||
348                         cache_data->curve_mapping != curve_mapping ||
349                         cache_data->curve_mapping_timestamp != curve_mapping_timestamp)
350                 {
351                         *cache_handle = NULL;
352
353                         IMB_freeImBuf(cache_ibuf);
354
355                         return NULL;
356                 }
357
358                 return (unsigned char *) cache_ibuf->rect;
359         }
360
361         return NULL;
362 }
363
364 static void colormanage_cache_put(ImBuf *ibuf, const ColormanageCacheViewSettings *view_settings,
365                                   const ColormanageCacheDisplaySettings *display_settings,
366                                   unsigned char *display_buffer, void **cache_handle)
367 {
368         ColormanageCacheKey key;
369         ImBuf *cache_ibuf;
370         ColormnaageCacheData *cache_data;
371         int view_flag = 1 << (view_settings->view - 1);
372         int predivide = ibuf->flags & IB_cm_predivide;
373         struct MovieCache *moviecache = colormanage_moviecache_ensure(ibuf);
374         CurveMapping *curve_mapping = view_settings->curve_mapping;
375         int curve_mapping_timestamp = curve_mapping ? curve_mapping->changed_timestamp : 0;
376
377         colormanage_settings_to_key(&key, view_settings, display_settings);
378
379         /* mark display buffer as valid */
380         ibuf->display_buffer_flags[display_settings->display - 1] |= view_flag;
381
382         /* buffer itself */
383         cache_ibuf = IMB_allocImBuf(ibuf->x, ibuf->y, ibuf->planes, 0);
384         cache_ibuf->rect = (unsigned int *) display_buffer;
385
386         cache_ibuf->mall |= IB_rect;
387         cache_ibuf->flags |= IB_rect;
388
389         /* store data which is needed to check whether cached buffer could be used for color managed display settings */
390         cache_data = MEM_callocN(sizeof(ColormnaageCacheData), "color manage cache imbuf data");
391         cache_data->exposure = view_settings->exposure;
392         cache_data->gamma = view_settings->gamma;
393         cache_data->predivide = predivide;
394         cache_data->flag = view_settings->flag;
395         cache_data->curve_mapping = curve_mapping;
396         cache_data->curve_mapping_timestamp = curve_mapping_timestamp;
397
398         colormanage_cachedata_set(cache_ibuf, cache_data);
399
400         *cache_handle = cache_ibuf;
401
402         IMB_moviecache_put(moviecache, &key, cache_ibuf);
403 }
404
405 static void colormanage_cache_handle_release(void *cache_handle)
406 {
407         ImBuf *cache_ibuf = cache_handle;
408
409         IMB_freeImBuf(cache_ibuf);
410 }
411
412 /*********************** Initialization / De-initialization *************************/
413
414 static void colormanage_role_color_space_name_get(ConstConfigRcPtr *config, char *colorspace_name, const char *role)
415 {
416         ConstColorSpaceRcPtr *ociocs;
417
418         ociocs = OCIO_configGetColorSpace(config, role);
419
420         if (ociocs) {
421                 const char *name = OCIO_colorSpaceGetName(ociocs);
422
423                 /* assume function was called with buffer properly allocated to MAX_COLORSPACE_NAME chars */
424                 BLI_strncpy(colorspace_name, name, MAX_COLORSPACE_NAME);
425                 OCIO_colorSpaceRelease(ociocs);
426         }
427         else {
428                 printf("Color management: Error could not find role %s role.\n", role);
429         }
430 }
431
432 static void colormanage_load_config(ConstConfigRcPtr *config)
433 {
434         int tot_colorspace, tot_display, tot_display_view, index, viewindex, viewindex2;
435         const char *name;
436
437         /* get roles */
438         colormanage_role_color_space_name_get(config, global_role_scene_linear, OCIO_ROLE_SCENE_LINEAR);
439         colormanage_role_color_space_name_get(config, global_role_color_picking, OCIO_ROLE_COLOR_PICKING);
440         colormanage_role_color_space_name_get(config, global_role_texture_painting, OCIO_ROLE_TEXTURE_PAINT);
441         colormanage_role_color_space_name_get(config, global_role_default_sequencer, OCIO_ROLE_DEFAULT_SEQUENCER);
442         colormanage_role_color_space_name_get(config, global_role_default_byte, OCIO_ROLE_DEFAULT_BYTE);
443         colormanage_role_color_space_name_get(config, global_role_default_float, OCIO_ROLE_DEFAULT_FLOAT);
444
445         /* load colorspaces */
446         tot_colorspace = OCIO_configGetNumColorSpaces(config);
447         for (index = 0 ; index < tot_colorspace; index++) {
448                 ConstColorSpaceRcPtr *ocio_colorspace;
449                 const char *description;
450                 int is_invertible;
451
452                 name = OCIO_configGetColorSpaceNameByIndex(config, index);
453
454                 ocio_colorspace = OCIO_configGetColorSpace(config, name);
455                 description = OCIO_colorSpaceGetDescription(ocio_colorspace);
456                 is_invertible = OCIO_colorSpaceIsInvertible(ocio_colorspace);
457
458                 colormanage_colorspace_add(name, description, is_invertible);
459
460                 OCIO_colorSpaceRelease(ocio_colorspace);
461         }
462
463         /* load displays */
464         viewindex2 = 0;
465         tot_display = OCIO_configGetNumDisplays(config);
466
467         for (index = 0 ; index < tot_display; index++) {
468                 const char *displayname;
469                 ColorManagedDisplay *display;
470
471                 displayname = OCIO_configGetDisplay(config, index);
472
473                 display = colormanage_display_add(displayname);
474
475                 /* load views */
476                 tot_display_view = OCIO_configGetNumViews(config, displayname);
477                 for (viewindex = 0 ; viewindex < tot_display_view; viewindex++, viewindex2++) {
478                         const char *viewname;
479                         ColorManagedView *view;
480                         LinkData *display_view;
481
482                         viewname = OCIO_configGetView(config, displayname, viewindex);
483
484                         /* first check if view transform with given name was already loaded */
485                         view = colormanage_view_get_named(viewname);
486
487                         if (!view) {
488                                 view = colormanage_view_add(viewname);
489                         }
490
491                         display_view = BLI_genericNodeN(view);
492
493                         BLI_addtail(&display->views, display_view);
494                 }
495         }
496
497         global_tot_display = tot_display;
498 }
499
500 static void colormanage_free_config(void)
501 {
502         ColorSpace *colorspace;
503         ColorManagedDisplay *display;
504
505         /* free color spaces */
506         colorspace = global_colorspaces.first;
507         while (colorspace) {
508                 ColorSpace *colorspace_next = colorspace->next;
509
510                 /* free precomputer processors */
511                 if (colorspace->to_scene_linear)
512                         OCIO_processorRelease((ConstProcessorRcPtr *) colorspace->to_scene_linear);
513
514                 if (colorspace->from_scene_linear)
515                         OCIO_processorRelease((ConstProcessorRcPtr *) colorspace->from_scene_linear);
516
517                 /* free color space itself */
518                 MEM_freeN(colorspace);
519
520                 colorspace = colorspace_next;
521         }
522
523         /* free displays */
524         display = global_displays.first;
525         while (display) {
526                 ColorManagedDisplay *display_next = display->next;
527
528                 /* free precomputer processors */
529                 if (display->to_scene_linear)
530                         OCIO_processorRelease((ConstProcessorRcPtr *) display->to_scene_linear);
531
532                 if (display->from_scene_linear)
533                         OCIO_processorRelease((ConstProcessorRcPtr *) display->from_scene_linear);
534
535                 /* free list of views */
536                 BLI_freelistN(&display->views);
537
538                 MEM_freeN(display);
539                 display = display_next;
540         }
541
542         /* free views */
543         BLI_freelistN(&global_views);
544 }
545
546 void IMB_colormanagement_init(void)
547 {
548         const char *ocio_env;
549         const char *configdir;
550         char configfile[FILE_MAX];
551         ConstConfigRcPtr *config = NULL;
552
553         ocio_env = getenv("OCIO");
554
555         if (ocio_env && ocio_env[0] != '\0')
556                 config = OCIO_configCreateFromEnv();
557
558         if (config == NULL) {
559                 configdir = BLI_get_folder(BLENDER_DATAFILES, "colormanagement");
560
561                 if (configdir)  {
562                         BLI_join_dirfile(configfile, sizeof(configfile), configdir, BCM_CONFIG_FILE);
563
564                         config = OCIO_configCreateFromFile(configfile);
565                 }
566         }
567
568         if (config == NULL) {
569                 config = OCIO_getDefaultConfig();
570         }
571
572         if (config) {
573                 OCIO_setCurrentConfig(config);
574
575                 colormanage_load_config(config);
576
577                 OCIO_configRelease(config);
578         }
579
580         BLI_init_srgb_conversion();
581 }
582
583 void IMB_colormanagement_exit(void)
584 {
585         colormanage_free_config();
586 }
587
588 /*********************** Internal functions *************************/
589
590 void colormanage_cache_free(ImBuf *ibuf)
591 {
592         if (ibuf->display_buffer_flags) {
593                 MEM_freeN(ibuf->display_buffer_flags);
594
595                 ibuf->display_buffer_flags = NULL;
596         }
597
598         if (ibuf->colormanage_cache) {
599                 ColormnaageCacheData *cache_data = colormanage_cachedata_get(ibuf);
600                 struct MovieCache *moviecache = colormanage_moviecache_get(ibuf);
601
602                 if (cache_data) {
603                         MEM_freeN(cache_data);
604                 }
605
606                 if (moviecache) {
607                         IMB_moviecache_free(moviecache);
608                 }
609
610                 MEM_freeN(ibuf->colormanage_cache);
611
612                 ibuf->colormanage_cache = NULL;
613         }
614 }
615
616 static void display_transform_get_from_ctx(const bContext *C, ColorManagedViewSettings **view_settings_r,
617                                            ColorManagedDisplaySettings **display_settings_r)
618 {
619         Scene *scene = CTX_data_scene(C);
620         SpaceImage *sima = CTX_wm_space_image(C);
621
622         *view_settings_r = &scene->view_settings;
623         *display_settings_r = &scene->display_settings;
624
625         if (sima) {
626                 if ((sima->image->flag & IMA_VIEW_AS_RENDER) == 0)
627                         *view_settings_r = NULL;
628         }
629 }
630
631 static ConstProcessorRcPtr *create_display_buffer_processor(const char *view_transform, const char *display,
632                                                             float exposure, float gamma)
633 {
634         ConstConfigRcPtr *config = OCIO_getCurrentConfig();
635         DisplayTransformRcPtr *dt;
636         ConstProcessorRcPtr *processor;
637
638         if (!config) {
639                 /* there's no valid OCIO configuration, can't create processor */
640
641                 return NULL;
642         }
643
644         dt = OCIO_createDisplayTransform();
645
646         /* assuming handling buffer was already converted to scene linear space */
647         OCIO_displayTransformSetInputColorSpaceName(dt, global_role_scene_linear);
648         OCIO_displayTransformSetView(dt, view_transform);
649         OCIO_displayTransformSetDisplay(dt, display);
650
651         /* fstop exposure control */
652         if (exposure != 0.0f) {
653                 MatrixTransformRcPtr *mt;
654                 float gain = powf(2.0f, exposure);
655                 const float scale4f[] = {gain, gain, gain, gain};
656                 float m44[16], offset4[4];
657
658                 OCIO_matrixTransformScale(m44, offset4, scale4f);
659                 mt = OCIO_createMatrixTransform();
660                 OCIO_matrixTransformSetValue(mt, m44, offset4);
661                 OCIO_displayTransformSetLinearCC(dt, (ConstTransformRcPtr *) mt);
662
663                 OCIO_matrixTransformRelease(mt);
664         }
665
666         /* post-display gamma transform */
667         if (gamma != 1.0f) {
668                 ExponentTransformRcPtr *et;
669                 float exponent = 1.0f / MAX2(FLT_EPSILON, gamma);
670                 const float exponent4f[] = {exponent, exponent, exponent, exponent};
671
672                 et = OCIO_createExponentTransform();
673                 OCIO_exponentTransformSetValue(et, exponent4f);
674                 OCIO_displayTransformSetDisplayCC(dt, (ConstTransformRcPtr *) et);
675
676                 OCIO_exponentTransformRelease(et);
677         }
678
679         processor = OCIO_configGetProcessor(config, (ConstTransformRcPtr *) dt);
680
681         OCIO_displayTransformRelease(dt);
682         OCIO_configRelease(config);
683
684         return processor;
685 }
686
687 static ConstProcessorRcPtr *create_colorspace_transform_processor(const char *from_colorspace,
688                                                                   const char *to_colorspace)
689 {
690         ConstConfigRcPtr *config = OCIO_getCurrentConfig();
691         ConstProcessorRcPtr *processor;
692
693         if (!config) {
694                 /* there's no valid OCIO configuration, can't create processor */
695
696                 return NULL;
697         }
698
699         processor = OCIO_configGetProcessorWithNames(config, from_colorspace, to_colorspace);
700
701         OCIO_configRelease(config);
702
703         return processor;
704 }
705
706 static ConstProcessorRcPtr *colorspace_to_scene_linear_processor(ColorSpace *colorspace)
707 {
708         if (colorspace->to_scene_linear == NULL) {
709                 BLI_lock_thread(LOCK_COLORMANAGE);
710
711                 if (colorspace->to_scene_linear == NULL) {
712                         ConstProcessorRcPtr *to_scene_linear;
713                         to_scene_linear = create_colorspace_transform_processor(colorspace->name, global_role_scene_linear);
714                         colorspace->to_scene_linear = (struct ConstProcessorRcPtr *) to_scene_linear;
715                 }
716
717                 BLI_unlock_thread(LOCK_COLORMANAGE);
718         }
719
720         return (ConstProcessorRcPtr *) colorspace->to_scene_linear;
721 }
722
723 static ConstProcessorRcPtr *colorspace_from_scene_linear_processor(ColorSpace *colorspace)
724 {
725         if (colorspace->from_scene_linear == NULL) {
726                 BLI_lock_thread(LOCK_COLORMANAGE);
727
728                 if (colorspace->from_scene_linear == NULL) {
729                         ConstProcessorRcPtr *from_scene_linear;
730                         from_scene_linear = create_colorspace_transform_processor(global_role_scene_linear, colorspace->name);
731                         colorspace->from_scene_linear = (struct ConstProcessorRcPtr *) from_scene_linear;
732                 }
733
734                 BLI_unlock_thread(LOCK_COLORMANAGE);
735         }
736
737         return (ConstProcessorRcPtr *) colorspace->from_scene_linear;
738 }
739
740 static ConstProcessorRcPtr *display_from_scene_linear_processor(ColorManagedDisplay *display)
741 {
742         if (display->from_scene_linear == NULL) {
743                 BLI_lock_thread(LOCK_COLORMANAGE);
744
745                 if (display->from_scene_linear == NULL) {
746                         const char *view_name = colormanage_view_get_default_name(display);
747                         ConstConfigRcPtr *config = OCIO_getCurrentConfig();
748                         ConstProcessorRcPtr *processor = NULL;
749
750                         if (view_name && config) {
751                                 const char *view_colorspace = OCIO_configGetDisplayColorSpaceName(config, display->name, view_name);
752                                 processor = OCIO_configGetProcessorWithNames(config, global_role_scene_linear, view_colorspace);
753
754                                 OCIO_configRelease(config);
755                         }
756
757                         display->from_scene_linear = (struct ConstProcessorRcPtr *) processor;
758                 }
759
760                 BLI_unlock_thread(LOCK_COLORMANAGE);
761         }
762
763         return (ConstProcessorRcPtr *) display->from_scene_linear;
764 }
765
766 static ConstProcessorRcPtr *display_to_scene_linear_processor(ColorManagedDisplay *display)
767 {
768         if (display->to_scene_linear == NULL) {
769                 BLI_lock_thread(LOCK_COLORMANAGE);
770
771                 if (display->to_scene_linear == NULL) {
772                         const char *view_name = colormanage_view_get_default_name(display);
773                         ConstConfigRcPtr *config = OCIO_getCurrentConfig();
774                         ConstProcessorRcPtr *processor = NULL;
775
776                         if (view_name && config) {
777                                 const char *view_colorspace = OCIO_configGetDisplayColorSpaceName(config, display->name, view_name);
778                                 processor = OCIO_configGetProcessorWithNames(config, view_colorspace, global_role_scene_linear);
779
780                                 OCIO_configRelease(config);
781                         }
782
783                         display->to_scene_linear = (struct ConstProcessorRcPtr *) processor;
784                 }
785
786                 BLI_unlock_thread(LOCK_COLORMANAGE);
787         }
788
789         return (ConstProcessorRcPtr *) display->to_scene_linear;
790 }
791
792 static void init_default_view_settings(const ColorManagedDisplaySettings *display_settings,
793                                        ColorManagedViewSettings *view_settings)
794 {
795         ColorManagedDisplay *display;
796         ColorManagedView *default_view;
797
798         display = colormanage_display_get_named(display_settings->display_device);
799         default_view = colormanage_view_get_default(display);
800
801         if (default_view)
802                 BLI_strncpy(view_settings->view_transform, default_view->name, sizeof(view_settings->view_transform));
803         else
804                 view_settings->view_transform[0] = '\0';
805
806         view_settings->flag = 0;
807         view_settings->gamma = 1.0f;
808         view_settings->exposure = 0.0f;
809         view_settings->curve_mapping = NULL;
810 }
811
812 static void curve_mapping_apply_pixel(CurveMapping *curve_mapping, float *pixel, int channels)
813 {
814         if (channels == 1) {
815                 pixel[0] = curvemap_evaluateF(curve_mapping->cm, pixel[0]);
816         }
817         else if (channels == 2) {
818                 pixel[0] = curvemap_evaluateF(curve_mapping->cm, pixel[0]);
819                 pixel[1] = curvemap_evaluateF(curve_mapping->cm, pixel[1]);
820         }
821         else {
822                 curvemapping_evaluate_premulRGBF(curve_mapping, pixel, pixel);
823         }
824 }
825
826 void colorspace_set_default_role(char *colorspace, int size, int role)
827 {
828         if (colorspace && colorspace[0] == '\0') {
829                 const char *role_colorspace;
830
831                 role_colorspace = IMB_colormanagement_role_colorspace_name_get(role);
832
833                 BLI_strncpy(colorspace, role_colorspace, size);
834         }
835 }
836
837 void colormanage_imbuf_set_default_spaces(ImBuf *ibuf)
838 {
839         ibuf->rect_colorspace = colormanage_colorspace_get_named(global_role_default_byte);
840 }
841
842 void colormanage_imbuf_make_linear(ImBuf *ibuf, const char *from_colorspace)
843 {
844         if (ibuf->rect_float) {
845                 const char *to_colorspace = global_role_scene_linear;
846                 int predivide = ibuf->flags & IB_cm_predivide;
847
848                 if (ibuf->rect)
849                         imb_freerectImBuf(ibuf);
850
851                 IMB_colormanagement_transform(ibuf->rect_float, ibuf->x, ibuf->y, ibuf->channels,
852                                               from_colorspace, to_colorspace, predivide);
853         }
854 }
855
856 /*********************** Generic functions *************************/
857
858 static void colormanage_check_display_settings(ColorManagedDisplaySettings *display_settings, const char *what,
859                                                const ColorManagedDisplay *default_display)
860 {
861         if (display_settings->display_device[0] == '\0') {
862                 BLI_strncpy(display_settings->display_device, default_display->name, sizeof(display_settings->display_device));
863         }
864         else {
865                 ColorManagedDisplay *display = colormanage_display_get_named(display_settings->display_device);
866
867                 if (!display) {
868                         printf("Color management: display \"%s\" used by %s not found, setting to default (\"%s\").\n",
869                                display_settings->display_device, what, default_display->name);
870
871                         BLI_strncpy(display_settings->display_device, default_display->name,
872                                     sizeof(display_settings->display_device));
873                 }
874         }
875 }
876
877 static void colormanage_check_view_settings(ColorManagedDisplaySettings *display_settings,
878                                             ColorManagedViewSettings *view_settings, const char *what)
879 {
880         ColorManagedDisplay *display;
881         ColorManagedView *default_view;
882
883         if (view_settings->view_transform[0] == '\0') {
884                 display = colormanage_display_get_named(display_settings->display_device);
885                 default_view = colormanage_view_get_default(display);
886
887                 if (default_view)
888                         BLI_strncpy(view_settings->view_transform, default_view->name, sizeof(view_settings->view_transform));
889         }
890         else {
891                 ColorManagedView *view = colormanage_view_get_named(view_settings->view_transform);
892
893                 if (!view) {
894                         display = colormanage_display_get_named(display_settings->display_device);
895                         default_view = colormanage_view_get_default(display);
896
897                         if (default_view) {
898                                 printf("Color management: %s view \"%s\" not found, setting default \"%s\".\n",
899                                        what, view_settings->view_transform, default_view->name);
900
901                                 BLI_strncpy(view_settings->view_transform, default_view->name, sizeof(view_settings->view_transform));
902                         }
903                 }
904         }
905
906         /* OCIO_TODO: move to do_versions() */
907         if (view_settings->exposure == 0.0f && view_settings->gamma == 0.0f) {
908                 view_settings->exposure = 0.0f;
909                 view_settings->gamma = 1.0f;
910         }
911 }
912
913 static void colormanage_check_colorspace_settings(ColorManagedColorspaceSettings *colorspace_settings, const char *what)
914 {
915         if (colorspace_settings->name[0] == '\0') {
916                 /* pass */
917         }
918         else {
919                 ColorSpace *colorspace = colormanage_colorspace_get_named(colorspace_settings->name);
920
921                 if (!colorspace) {
922                         printf("Color management: %s colorspace \"%s\" not found, will use default instead.\n",
923                                what, colorspace_settings->name);
924
925                         BLI_strncpy(colorspace_settings->name, "", sizeof(colorspace_settings->name));
926                 }
927         }
928
929         (void) what;
930 }
931
932 void IMB_colormanagement_check_file_config(Main *bmain)
933 {
934         Scene *scene;
935         Image *image;
936         MovieClip *clip;
937
938         ColorManagedDisplay *default_display;
939
940         default_display = colormanage_display_get_default();
941
942         if (!default_display) {
943                 /* happens when OCIO configuration is incorrect */
944                 return;
945         }
946
947         for (scene = bmain->scene.first; scene; scene = scene->id.next) {
948                 ColorManagedColorspaceSettings *sequencer_colorspace_settings;
949
950                 colormanage_check_display_settings(&scene->display_settings, "scene", default_display);
951                 colormanage_check_view_settings(&scene->display_settings, &scene->view_settings, "scene");
952
953                 sequencer_colorspace_settings = &scene->sequencer_colorspace_settings;
954
955                 colormanage_check_colorspace_settings(sequencer_colorspace_settings, "sequencer");
956
957                 if (sequencer_colorspace_settings->name[0] == '\0') {
958                         BLI_strncpy(sequencer_colorspace_settings->name, global_role_default_sequencer, MAX_COLORSPACE_NAME);
959                 }
960         }
961
962         /* ** check input color space settings ** */
963
964         for (image = bmain->image.first; image; image = image->id.next) {
965                 colormanage_check_colorspace_settings(&image->colorspace_settings, "image");
966         }
967
968         for (clip = bmain->movieclip.first; clip; clip = clip->id.next) {
969                 colormanage_check_colorspace_settings(&clip->colorspace_settings, "clip");
970         }
971 }
972
973 void IMB_colormanagement_validate_settings(ColorManagedDisplaySettings *display_settings,
974                                            ColorManagedViewSettings *view_settings)
975 {
976         ColorManagedDisplay *display;
977         ColorManagedView *default_view;
978         LinkData *view_link;
979
980         display = colormanage_display_get_named(display_settings->display_device);
981         default_view = colormanage_view_get_default(display);
982
983         for (view_link = display->views.first; view_link; view_link = view_link->next) {
984                 ColorManagedView *view = view_link->data;
985
986                 if (!strcmp(view->name, view_settings->view_transform))
987                         break;
988         }
989
990         if (view_link == NULL)
991                 BLI_strncpy(view_settings->view_transform, default_view->name, sizeof(view_settings->view_transform));
992 }
993
994 const char *IMB_colormanagement_role_colorspace_name_get(int role)
995 {
996         switch (role) {
997                 case COLOR_ROLE_SCENE_LINEAR:
998                         return global_role_scene_linear;
999                         break;
1000                 case COLOR_ROLE_COLOR_PICKING:
1001                         return global_role_color_picking;
1002                         break;
1003                 case COLOR_ROLE_TEXTURE_PAINTING:
1004                         return global_role_texture_painting;
1005                         break;
1006                 case COLOR_ROLE_DEFAULT_SEQUENCER:
1007                         return global_role_default_sequencer;
1008                         break;
1009                 case COLOR_ROLE_DEFAULT_FLOAT:
1010                         return global_role_default_float;
1011                         break;
1012                 case COLOR_ROLE_DEFAULT_BYTE:
1013                         return global_role_default_byte;
1014                         break;
1015                 default:
1016                         printf("Unknown role was passed to %s\n", __func__);
1017                         BLI_assert(0);
1018         }
1019
1020         return NULL;
1021 }
1022
1023 /*********************** Threaded display buffer transform routines *************************/
1024
1025 typedef struct DisplayBufferThread {
1026         ColormanageProcessor *cm_processor;
1027
1028         float *buffer;
1029         unsigned char *byte_buffer;
1030
1031         float *display_buffer;
1032         unsigned char *display_buffer_byte;
1033
1034         int width;
1035         int start_line;
1036         int tot_line;
1037
1038         int channels;
1039         float dither;
1040         int predivide;
1041
1042         const char *byte_colorspace;
1043         const char *float_colorspace;
1044 } DisplayBufferThread;
1045
1046 typedef struct DisplayBufferInitData {
1047         ImBuf *ibuf;
1048         ColormanageProcessor *cm_processor;
1049         float *buffer;
1050         unsigned char *byte_buffer;
1051
1052         float *display_buffer;
1053         unsigned char *display_buffer_byte;
1054
1055         int width;
1056
1057         const char *byte_colorspace;
1058         const char *float_colorspace;
1059 } DisplayBufferInitData;
1060
1061 static void display_buffer_init_handle(void *handle_v, int start_line, int tot_line, void *init_data_v)
1062 {
1063         DisplayBufferThread *handle = (DisplayBufferThread *) handle_v;
1064         DisplayBufferInitData *init_data = (DisplayBufferInitData *) init_data_v;
1065         ImBuf *ibuf = init_data->ibuf;
1066
1067         int predivide = ibuf->flags & IB_cm_predivide;
1068         int channels = ibuf->channels;
1069         float dither = ibuf->dither;
1070
1071         int offset = channels * start_line * ibuf->x;
1072
1073         memset(handle, 0, sizeof(DisplayBufferThread));
1074
1075         handle->cm_processor = init_data->cm_processor;
1076
1077         if (init_data->buffer)
1078                 handle->buffer = init_data->buffer + offset;
1079
1080         if (init_data->byte_buffer)
1081                 handle->byte_buffer = init_data->byte_buffer + offset;
1082
1083         if (init_data->display_buffer)
1084                 handle->display_buffer = init_data->display_buffer + offset;
1085
1086         if (init_data->display_buffer_byte)
1087                 handle->display_buffer_byte = init_data->display_buffer_byte + offset;
1088
1089         handle->width = ibuf->x;
1090
1091         handle->start_line = start_line;
1092         handle->tot_line = tot_line;
1093
1094         handle->channels = channels;
1095         handle->dither = dither;
1096         handle->predivide = predivide;
1097
1098         handle->byte_colorspace = init_data->byte_colorspace;
1099         handle->float_colorspace = init_data->float_colorspace;
1100 }
1101
1102 static void *display_buffer_apply_get_linear_buffer(DisplayBufferThread *handle)
1103 {
1104         float *linear_buffer = NULL;
1105
1106         int channels = handle->channels;
1107         int width = handle->width;
1108         int height = handle->tot_line;
1109
1110         int buffer_size = channels * width * height;
1111
1112         int predivide = handle->predivide;
1113
1114         linear_buffer = MEM_callocN(buffer_size * sizeof(float), "color conversion linear buffer");
1115
1116         if (!handle->buffer) {
1117                 unsigned char *byte_buffer = handle->byte_buffer;
1118
1119                 const char *from_colorspace = handle->byte_colorspace;
1120                 const char *to_colorspace = global_role_scene_linear;
1121
1122                 float *fp;
1123                 unsigned char *cp;
1124                 int i;
1125
1126                 /* first convert byte buffer to float, keep in image space */
1127                 for (i = 0, fp = linear_buffer, cp = byte_buffer;
1128                      i < channels * width * height;
1129                          i++, fp++, cp++)
1130                 {
1131                         *fp = (float)(*cp) / 255.0f;
1132                 }
1133
1134                 /* convert float buffer to scene linear space */
1135                 IMB_colormanagement_transform(linear_buffer, width, height, channels,
1136                                               from_colorspace, to_colorspace, predivide);
1137         }
1138         else if (handle->float_colorspace) {
1139                 /* currently float is non-linear only in sequencer, which is working
1140                  * in it's own color space even to handle float buffers.
1141                  * This color space is the same for byte and float images.
1142                  * Need to convert float buffer to linear space before applying display transform
1143                  */
1144
1145                 const char *from_colorspace = handle->float_colorspace;
1146                 const char *to_colorspace = global_role_scene_linear;
1147
1148                 memcpy(linear_buffer, handle->buffer, buffer_size * sizeof(float));
1149
1150                 IMB_colormanagement_transform(linear_buffer, width, height, channels,
1151                                               from_colorspace, to_colorspace, predivide);
1152         }
1153         else {
1154                 /* some processors would want to modify float original buffer
1155                  * before converting it into display byte buffer, so we need to
1156                  * make sure original's ImBuf buffers wouldn't be modified by
1157                  * using duplicated buffer here
1158                  *
1159                  * NOTE: MEM_dupallocN can't be used because buffer could be
1160                  *       specified as an offset inside allocated buffer
1161                  */
1162
1163                 memcpy(linear_buffer, handle->buffer, buffer_size * sizeof(float));
1164         }
1165
1166         return linear_buffer;
1167 }
1168
1169 static void *do_display_buffer_apply_thread(void *handle_v)
1170 {
1171         DisplayBufferThread *handle = (DisplayBufferThread *) handle_v;
1172         ColormanageProcessor *cm_processor = handle->cm_processor;
1173         float *buffer = handle->buffer;
1174         float *display_buffer = handle->display_buffer;
1175         unsigned char *display_buffer_byte = handle->display_buffer_byte;
1176         int channels = handle->channels;
1177         int width = handle->width;
1178         int height = handle->tot_line;
1179         float dither = handle->dither;
1180         int predivide = handle->predivide;
1181
1182         float *linear_buffer = display_buffer_apply_get_linear_buffer(handle);
1183
1184         /* apply processor */
1185         IMB_colormanagement_processor_apply(cm_processor, linear_buffer, width, height, channels, predivide);
1186
1187         /* copy result to output buffers */
1188         if (display_buffer_byte) {
1189                 /* do conversion */
1190                 IMB_buffer_byte_from_float(display_buffer_byte, linear_buffer,
1191                                            channels, dither, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
1192                                            predivide, width, height, width, width);
1193         }
1194
1195         if (display_buffer)
1196                 memcpy(display_buffer, linear_buffer, width * height * channels * sizeof(float));
1197
1198         if (linear_buffer != buffer)
1199                 MEM_freeN(linear_buffer);
1200
1201         return NULL;
1202 }
1203
1204 static void display_buffer_apply_threaded(ImBuf *ibuf, float *buffer, unsigned char *byte_buffer, float *display_buffer,
1205                                           unsigned char *display_buffer_byte, ColormanageProcessor *cm_processor)
1206 {
1207         DisplayBufferInitData init_data;
1208
1209         init_data.ibuf = ibuf;
1210         init_data.cm_processor = cm_processor;
1211         init_data.buffer = buffer;
1212         init_data.byte_buffer = byte_buffer;
1213         init_data.display_buffer = display_buffer;
1214         init_data.display_buffer_byte = display_buffer_byte;
1215
1216         if (ibuf->rect_colorspace != NULL) {
1217                 init_data.byte_colorspace = ibuf->rect_colorspace->name;
1218         }
1219         else {
1220                 /* happens for viewer images, which are not so simple to determine where to
1221                  * set image buffer's color spaces
1222                  */
1223                 init_data.byte_colorspace = global_role_default_byte;
1224         }
1225
1226         if (ibuf->float_colorspace != NULL) {
1227                 /* sequencer stores float buffers in non-linear space */
1228                 init_data.float_colorspace = ibuf->float_colorspace->name;
1229         }
1230         else {
1231                 init_data.float_colorspace = NULL;
1232         }
1233
1234         IMB_processor_apply_threaded(ibuf->y, sizeof(DisplayBufferThread), &init_data,
1235                                      display_buffer_init_handle, do_display_buffer_apply_thread);
1236 }
1237
1238 static void colormanage_display_buffer_process_ex(ImBuf *ibuf, float *display_buffer, unsigned char *display_buffer_byte,
1239                                                   const ColorManagedViewSettings *view_settings,
1240                                                   const ColorManagedDisplaySettings *display_settings)
1241 {
1242         ColormanageProcessor *cm_processor;
1243
1244         cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1245
1246         display_buffer_apply_threaded(ibuf, ibuf->rect_float, (unsigned char *) ibuf->rect,
1247                                       display_buffer, display_buffer_byte, cm_processor);
1248
1249         IMB_colormanagement_processor_free(cm_processor);
1250 }
1251
1252 static void colormanage_display_buffer_process(ImBuf *ibuf, unsigned char *display_buffer,
1253                                                const ColorManagedViewSettings *view_settings,
1254                                                const ColorManagedDisplaySettings *display_settings)
1255 {
1256         colormanage_display_buffer_process_ex(ibuf, NULL, display_buffer, view_settings, display_settings);
1257 }
1258
1259 /*********************** Threaded processor transform routines *************************/
1260
1261 typedef struct ProcessorTransformThread {
1262         ColormanageProcessor *cm_processor;
1263         float *buffer;
1264         int width;
1265         int start_line;
1266         int tot_line;
1267         int channels;
1268         int predivide;
1269 } ProcessorTransformThread;
1270
1271 typedef struct ProcessorTransformInit {
1272         ColormanageProcessor *cm_processor;
1273         float *buffer;
1274         int width;
1275         int height;
1276         int channels;
1277         int predivide;
1278 } ProcessorTransformInitData;
1279
1280 static void processor_transform_init_handle(void *handle_v, int start_line, int tot_line, void *init_data_v)
1281 {
1282         ProcessorTransformThread *handle = (ProcessorTransformThread *) handle_v;
1283         ProcessorTransformInitData *init_data = (ProcessorTransformInitData *) init_data_v;
1284
1285         int channels = init_data->channels;
1286         int width = init_data->width;
1287         int predivide = init_data->predivide;
1288
1289         int offset = channels * start_line * width;
1290
1291         memset(handle, 0, sizeof(ProcessorTransformThread));
1292
1293         handle->cm_processor = init_data->cm_processor;
1294
1295         handle->buffer = init_data->buffer + offset;
1296
1297         handle->width = width;
1298
1299         handle->start_line = start_line;
1300         handle->tot_line = tot_line;
1301
1302         handle->channels = channels;
1303         handle->predivide = predivide;
1304 }
1305
1306 static void *do_processor_transform_thread(void *handle_v)
1307 {
1308         ProcessorTransformThread *handle = (ProcessorTransformThread *) handle_v;
1309         float *buffer = handle->buffer;
1310         int channels = handle->channels;
1311         int width = handle->width;
1312         int height = handle->tot_line;
1313         int predivide = handle->predivide;
1314
1315         IMB_colormanagement_processor_apply(handle->cm_processor, buffer, width, height, channels, predivide);
1316
1317         return NULL;
1318 }
1319
1320 static void processor_transform_apply_threaded(float *buffer, int width, int height, int channels,
1321                                                ColormanageProcessor *cm_processor, int predivide)
1322 {
1323         ProcessorTransformInitData init_data;
1324
1325         init_data.cm_processor = cm_processor;
1326         init_data.buffer = buffer;
1327         init_data.width = width;
1328         init_data.height = height;
1329         init_data.channels = channels;
1330         init_data.predivide = predivide;
1331
1332         IMB_processor_apply_threaded(height, sizeof(ProcessorTransformThread), &init_data,
1333                                      processor_transform_init_handle, do_processor_transform_thread);
1334 }
1335
1336 /*********************** Color space transformation functions *************************/
1337
1338 /* convert the whole buffer from specified by name color space to another - internal implementation */
1339 static void colormanagement_transform_ex(float *buffer, int width, int height, int channels, const char *from_colorspace,
1340                                          const char *to_colorspace, int predivide, int do_threaded)
1341 {
1342         ColormanageProcessor *cm_processor;
1343
1344         if (from_colorspace[0] == '\0') {
1345                 return;
1346         }
1347
1348         if (!strcmp(from_colorspace, to_colorspace)) {
1349                 /* if source and destination color spaces are identical, skip
1350                  * threading overhead and simply do nothing
1351                  */
1352                 return;
1353         }
1354
1355         cm_processor = IMB_colormanagement_colorspace_processor_new(from_colorspace, to_colorspace);
1356
1357         if (do_threaded)
1358                 processor_transform_apply_threaded(buffer, width, height, channels, cm_processor, predivide);
1359         else
1360                 IMB_colormanagement_processor_apply(cm_processor, buffer, width, height, channels, predivide);
1361
1362         IMB_colormanagement_processor_free(cm_processor);
1363 }
1364
1365 /* convert the whole buffer from specified by name color space to another */
1366 void IMB_colormanagement_transform(float *buffer, int width, int height, int channels,
1367                                    const char *from_colorspace, const char *to_colorspace, int predivide)
1368 {
1369         colormanagement_transform_ex(buffer, width, height, channels, from_colorspace, to_colorspace, predivide, FALSE);
1370 }
1371
1372 /* convert the whole buffer from specified by name color space to another
1373  * will do threaded conversion
1374  */
1375 void IMB_colormanagement_transform_threaded(float *buffer, int width, int height, int channels,
1376                                             const char *from_colorspace, const char *to_colorspace, int predivide)
1377 {
1378         colormanagement_transform_ex(buffer, width, height, channels, from_colorspace, to_colorspace, predivide, TRUE);
1379 }
1380
1381 void IMB_colormanagement_transform_v4(float pixel[4], const char *from_colorspace, const char *to_colorspace)
1382 {
1383         ColormanageProcessor *cm_processor;
1384
1385         if (from_colorspace[0] == '\0') {
1386                 return;
1387         }
1388
1389         if (!strcmp(from_colorspace, to_colorspace)) {
1390                 /* if source and destination color spaces are identical, skip
1391                  * threading overhead and simply do nothing
1392                  */
1393                 return;
1394         }
1395
1396         cm_processor = IMB_colormanagement_colorspace_processor_new(from_colorspace, to_colorspace);
1397
1398         IMB_colormanagement_processor_apply_v4(cm_processor, pixel);
1399
1400         IMB_colormanagement_processor_free(cm_processor);
1401 }
1402
1403 /* convert pixel from specified by descriptor color space to scene linear
1404  * used by performance-critical areas such as renderer and baker
1405  */
1406 void IMB_colormanagement_colorspace_to_scene_linear_v3(float pixel[3], ColorSpace *colorspace)
1407 {
1408         ConstProcessorRcPtr *processor;
1409
1410         if (!colorspace) {
1411                 /* OCIO_TODO: make sure it never happens */
1412
1413                 printf("%s: perform conversion from unknown color space\n", __func__);
1414
1415                 return;
1416         }
1417
1418         processor = colorspace_to_scene_linear_processor(colorspace);
1419
1420         if (processor)
1421                 OCIO_processorApplyRGB(processor, pixel);
1422 }
1423
1424 /* same as above, but converts colors in opposite direction */
1425 void IMB_colormanagement_scene_linear_to_colorspace_v3(float pixel[3], ColorSpace *colorspace)
1426 {
1427         ConstProcessorRcPtr *processor;
1428
1429         if (!colorspace) {
1430                 /* OCIO_TODO: make sure it never happens */
1431
1432                 printf("%s: perform conversion from unknown color space\n", __func__);
1433
1434                 return;
1435         }
1436
1437         processor = colorspace_from_scene_linear_processor(colorspace);
1438
1439         if (processor)
1440                 OCIO_processorApplyRGB(processor, pixel);
1441 }
1442
1443 void IMB_colormanagement_colorspace_to_scene_linear(float *buffer, int width, int height, int channels, struct ColorSpace *colorspace, int predivide)
1444 {
1445         ConstProcessorRcPtr *processor;
1446
1447         if (!colorspace) {
1448                 /* OCIO_TODO: make sure it never happens */
1449
1450                 printf("%s: perform conversion from unknown color space\n", __func__);
1451
1452                 return;
1453         }
1454
1455         processor = colorspace_to_scene_linear_processor(colorspace);
1456
1457         if (processor) {
1458                 PackedImageDesc *img;
1459
1460                 img = OCIO_createPackedImageDesc(buffer, width, height, channels, sizeof(float),
1461                                                  channels * sizeof(float), channels * sizeof(float) * width);
1462
1463                 if (predivide)
1464                         OCIO_processorApply_predivide(processor, img);
1465                 else
1466                         OCIO_processorApply(processor, img);
1467
1468                 OCIO_packedImageDescRelease(img);
1469         }
1470 }
1471
1472 /* convert pixel from scene linear to display space using default view
1473  * used by performance-critical areas such as color-related widgets where we want to reduce
1474  * amount of per-widget allocations
1475  */
1476 void IMB_colormanagement_scene_linear_to_display_v3(float pixel[3], ColorManagedDisplay *display)
1477 {
1478         ConstProcessorRcPtr *processor;
1479
1480         processor = display_from_scene_linear_processor(display);
1481
1482         if (processor)
1483                 OCIO_processorApplyRGB(processor, pixel);
1484 }
1485
1486 /* same as above, but converts color in opposite direction */
1487 void IMB_colormanagement_display_to_scene_linear_v3(float pixel[3], ColorManagedDisplay *display)
1488 {
1489         ConstProcessorRcPtr *processor;
1490
1491         processor = display_to_scene_linear_processor(display);
1492
1493         if (processor)
1494                 OCIO_processorApplyRGB(processor, pixel);
1495 }
1496
1497 void IMB_colormanagement_pixel_to_display_space_v4(float result[4], const float pixel[4],
1498                                                    const ColorManagedViewSettings *view_settings,
1499                                                    const ColorManagedDisplaySettings *display_settings)
1500 {
1501         ColormanageProcessor *cm_processor;
1502
1503         copy_v4_v4(result, pixel);
1504
1505         cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1506         IMB_colormanagement_processor_apply_v4(cm_processor, result);
1507         IMB_colormanagement_processor_free(cm_processor);
1508 }
1509
1510 void IMB_colormanagement_pixel_to_display_space_v3(float result[3], const float pixel[3],
1511                                                    const ColorManagedViewSettings *view_settings,
1512                                                    const ColorManagedDisplaySettings *display_settings)
1513 {
1514         ColormanageProcessor *cm_processor;
1515
1516         copy_v3_v3(result, pixel);
1517
1518         cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1519         IMB_colormanagement_processor_apply_v3(cm_processor, result);
1520         IMB_colormanagement_processor_free(cm_processor);
1521 }
1522
1523 void IMB_colormanagement_imbuf_assign_float_space(ImBuf *ibuf, ColorManagedColorspaceSettings *colorspace_settings)
1524 {
1525         ibuf->float_colorspace = colormanage_colorspace_get_named(colorspace_settings->name);
1526 }
1527
1528 void IMB_colormanagement_imbuf_make_display_space(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
1529                                                   const ColorManagedDisplaySettings *display_settings)
1530 {
1531         /* OCIO_TODO: byte buffer management is not supported here yet */
1532         if (!ibuf->rect_float)
1533                 return;
1534
1535         if (global_tot_display == 0 || global_tot_view == 0) {
1536                 IMB_buffer_float_from_float(ibuf->rect_float, ibuf->rect_float, ibuf->channels, IB_PROFILE_SRGB, IB_PROFILE_LINEAR_RGB,
1537                                             ibuf->flags & IB_cm_predivide, ibuf->x, ibuf->y, ibuf->x, ibuf->x);
1538         }
1539         else {
1540                 colormanage_display_buffer_process_ex(ibuf, ibuf->rect_float, NULL, view_settings, display_settings);
1541         }
1542 }
1543
1544 static void imbuf_verify_float(ImBuf *ibuf)
1545 {
1546         /* multiple threads could request for display buffer at once and in case
1547          * view transform is not used it'll lead to display buffer calculated
1548          * several times
1549          * it is harmless, but would take much more time (assuming thread lock
1550          * happens faster than running float->byte conversion for average image)
1551          */
1552         BLI_lock_thread(LOCK_COLORMANAGE);
1553
1554         if (ibuf->rect_float && (ibuf->rect == NULL || (ibuf->userflags & IB_RECT_INVALID))) {
1555                 IMB_rect_from_float(ibuf);
1556
1557                 ibuf->userflags &= ~IB_RECT_INVALID;
1558         }
1559
1560         BLI_unlock_thread(LOCK_COLORMANAGE);
1561 }
1562
1563 /*********************** Public display buffers interfaces *************************/
1564
1565 /* acquire display buffer for given image buffer using specified view and display settings */
1566 unsigned char *IMB_display_buffer_acquire(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
1567                                           const ColorManagedDisplaySettings *display_settings, void **cache_handle)
1568 {
1569         *cache_handle = NULL;
1570
1571         if (!ibuf->x || !ibuf->y)
1572                 return NULL;
1573
1574         if (global_tot_display == 0 || global_tot_view == 0) {
1575                 /* if there's no view transform or display transforms, fallback to standard sRGB/linear conversion
1576                  * the same logic would be used if OCIO is disabled
1577                  */
1578
1579                 imbuf_verify_float(ibuf);
1580
1581                 return (unsigned char *) ibuf->rect;
1582         }
1583         else {
1584                 unsigned char *display_buffer;
1585                 int buffer_size;
1586                 ColormanageCacheViewSettings cache_view_settings;
1587                 ColormanageCacheDisplaySettings cache_display_settings;
1588                 ColorManagedViewSettings default_view_settings;
1589                 const ColorManagedViewSettings *applied_view_settings;
1590
1591                 if (view_settings) {
1592                         applied_view_settings = view_settings;
1593                 }
1594                 else {
1595                         /* if no view settings were specified, use default display transformation
1596                          * this happens for images which don't want to be displayed with render settings
1597                          */
1598
1599                         init_default_view_settings(display_settings,  &default_view_settings);
1600                         applied_view_settings = &default_view_settings;
1601                 }
1602
1603                 colormanage_view_settings_to_cache(&cache_view_settings, applied_view_settings);
1604                 colormanage_display_settings_to_cache(&cache_display_settings, display_settings);
1605
1606                 BLI_lock_thread(LOCK_COLORMANAGE);
1607
1608                 /* ensure color management bit fields exists */
1609                 if (!ibuf->display_buffer_flags) {
1610                         if (global_tot_display)
1611                                 ibuf->display_buffer_flags = MEM_callocN(sizeof(unsigned int) * global_tot_display, "imbuf display_buffer_flags");
1612                 }
1613                  else if (ibuf->userflags & IB_DISPLAY_BUFFER_INVALID) {
1614                         /* all display buffers were marked as invalid from other areas,
1615                          * now propagate this flag to internal color management routines
1616                          */
1617                         memset(ibuf->display_buffer_flags, 0, global_tot_display * sizeof(unsigned int));
1618
1619                         ibuf->userflags &= ~IB_DISPLAY_BUFFER_INVALID;
1620                 }
1621
1622                 display_buffer = colormanage_cache_get(ibuf, &cache_view_settings, &cache_display_settings, cache_handle);
1623
1624                 if (display_buffer) {
1625                         BLI_unlock_thread(LOCK_COLORMANAGE);
1626                         return display_buffer;
1627                 }
1628
1629                 buffer_size = ibuf->channels * ibuf->x * ibuf->y * sizeof(float);
1630                 display_buffer = MEM_callocN(buffer_size, "imbuf display buffer");
1631
1632                 colormanage_display_buffer_process(ibuf, display_buffer, applied_view_settings, display_settings);
1633
1634                 colormanage_cache_put(ibuf, &cache_view_settings, &cache_display_settings, display_buffer, cache_handle);
1635
1636                 BLI_unlock_thread(LOCK_COLORMANAGE);
1637
1638                 return display_buffer;
1639         }
1640 }
1641
1642 /* same as IMB_display_buffer_acquire but gets view and display settings from context */
1643 unsigned char *IMB_display_buffer_acquire_ctx(const bContext *C, ImBuf *ibuf, void **cache_handle)
1644 {
1645         ColorManagedViewSettings *view_settings;
1646         ColorManagedDisplaySettings *display_settings;
1647
1648         display_transform_get_from_ctx(C, &view_settings, &display_settings);
1649
1650         return IMB_display_buffer_acquire(ibuf, view_settings, display_settings, cache_handle);
1651 }
1652
1653 /* covert float buffer to display space and store it in image buffer's byte array */
1654 void IMB_display_buffer_to_imbuf_rect(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
1655                                       const ColorManagedDisplaySettings *display_settings)
1656 {
1657         if (global_tot_display == 0 || global_tot_view == 0) {
1658                 imbuf_verify_float(ibuf);
1659         }
1660         else {
1661                 if (!ibuf->rect) {
1662                         imb_addrectImBuf(ibuf);
1663                 }
1664
1665                 colormanage_display_buffer_process(ibuf, (unsigned char *) ibuf->rect, view_settings, display_settings);
1666         }
1667 }
1668
1669 void IMB_display_buffer_transform_apply(unsigned char *display_buffer, float *linear_buffer, int width, int height,
1670                                         int channels, const ColorManagedViewSettings *view_settings,
1671                                         const ColorManagedDisplaySettings *display_settings, int predivide)
1672 {
1673         if (global_tot_display == 0 || global_tot_view == 0) {
1674                 IMB_buffer_byte_from_float(display_buffer, linear_buffer, 4, 0.0f, IB_PROFILE_SRGB, IB_PROFILE_LINEAR_RGB, FALSE,
1675                                            width, height, width, width);
1676         }
1677         else {
1678                 float *buffer;
1679                 ColormanageProcessor *cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1680
1681                 buffer = MEM_callocN(channels * width * height * sizeof(float), "display transform temp buffer");
1682                 memcpy(buffer, linear_buffer, channels * width * height * sizeof(float));
1683
1684                 IMB_colormanagement_processor_apply(cm_processor, buffer, width, height, channels, predivide);
1685
1686                 IMB_colormanagement_processor_free(cm_processor);
1687
1688                 IMB_buffer_byte_from_float(display_buffer, buffer, channels, 0.0f, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
1689                                            FALSE, width, height, width, width);
1690
1691                 MEM_freeN(buffer);
1692         }
1693 }
1694
1695 void IMB_display_buffer_release(void *cache_handle)
1696 {
1697         if (cache_handle) {
1698                 BLI_lock_thread(LOCK_COLORMANAGE);
1699
1700                 colormanage_cache_handle_release(cache_handle);
1701
1702                 BLI_unlock_thread(LOCK_COLORMANAGE);
1703         }
1704 }
1705
1706 /*********************** Display functions *************************/
1707
1708 ColorManagedDisplay *colormanage_display_get_default(void)
1709 {
1710         ConstConfigRcPtr *config = OCIO_getCurrentConfig();
1711         const char *display;
1712
1713         if (!config) {
1714                 /* no valid OCIO configuration, can't get default display */
1715
1716                 return NULL;
1717         }
1718
1719         display = OCIO_configGetDefaultDisplay(config);
1720
1721         OCIO_configRelease(config);
1722
1723         if (display[0] == '\0')
1724                 return NULL;
1725
1726         return colormanage_display_get_named(display);
1727 }
1728
1729 ColorManagedDisplay *colormanage_display_add(const char *name)
1730 {
1731         ColorManagedDisplay *display;
1732         int index = 0;
1733
1734         if (global_displays.last) {
1735                 ColorManagedDisplay *last_display = global_displays.last;
1736
1737                 index = last_display->index;
1738         }
1739
1740         display = MEM_callocN(sizeof(ColorManagedDisplay), "ColorManagedDisplay");
1741
1742         display->index = index + 1;
1743
1744         BLI_strncpy(display->name, name, sizeof(display->name));
1745
1746         BLI_addtail(&global_displays, display);
1747
1748         return display;
1749 }
1750
1751 ColorManagedDisplay *colormanage_display_get_named(const char *name)
1752 {
1753         ColorManagedDisplay *display;
1754
1755         for (display = global_displays.first; display; display = display->next) {
1756                 if (!strcmp(display->name, name))
1757                         return display;
1758         }
1759
1760         return NULL;
1761 }
1762
1763 ColorManagedDisplay *colormanage_display_get_indexed(int index)
1764 {
1765         /* display indices are 1-based */
1766         return BLI_findlink(&global_displays, index - 1);
1767 }
1768
1769 int IMB_colormanagement_display_get_named_index(const char *name)
1770 {
1771         ColorManagedDisplay *display;
1772
1773         display = colormanage_display_get_named(name);
1774
1775         if (display) {
1776                 return display->index;
1777         }
1778
1779         return 0;
1780 }
1781
1782 const char *IMB_colormanagement_display_get_indexed_name(int index)
1783 {
1784         ColorManagedDisplay *display;
1785
1786         display = colormanage_display_get_indexed(index);
1787
1788         if (display) {
1789                 return display->name;
1790         }
1791
1792         return NULL;
1793 }
1794
1795 const char *IMB_colormanagement_display_get_default_name(void)
1796 {
1797         ColorManagedDisplay *display = colormanage_display_get_default();
1798
1799         return display->name;
1800 }
1801
1802 /* used by performance-critical pixel processing areas, such as color widgets */
1803 ColorManagedDisplay *IMB_colormanagement_display_get_named(const char *name)
1804 {
1805         return colormanage_display_get_named(name);
1806 }
1807
1808 /*********************** View functions *************************/
1809
1810 const char *colormanage_view_get_default_name(const ColorManagedDisplay *display)
1811 {
1812         ConstConfigRcPtr *config = OCIO_getCurrentConfig();
1813         const char *name;
1814
1815         if (!config) {
1816                 /* no valid OCIO configuration, can't get default view */
1817
1818                 return NULL;
1819         }
1820
1821         name = OCIO_configGetDefaultView(config, display->name);
1822
1823         OCIO_configRelease(config);
1824
1825         return name;
1826 }
1827
1828 ColorManagedView *colormanage_view_get_default(const ColorManagedDisplay *display)
1829 {
1830         const char *name = colormanage_view_get_default_name(display);
1831
1832         if (!name || name[0] == '\0')
1833                 return NULL;
1834
1835         return colormanage_view_get_named(name);
1836 }
1837
1838 ColorManagedView *colormanage_view_add(const char *name)
1839 {
1840         ColorManagedView *view;
1841         int index = global_tot_view;
1842
1843         view = MEM_callocN(sizeof(ColorManagedView), "ColorManagedView");
1844         view->index = index + 1;
1845         BLI_strncpy(view->name, name, sizeof(view->name));
1846
1847         BLI_addtail(&global_views, view);
1848
1849         global_tot_view++;
1850
1851         return view;
1852 }
1853
1854 ColorManagedView *colormanage_view_get_named(const char *name)
1855 {
1856         ColorManagedView *view;
1857
1858         for (view = global_views.first; view; view = view->next) {
1859                 if (!strcmp(view->name, name))
1860                         return view;
1861         }
1862
1863         return NULL;
1864 }
1865
1866 ColorManagedView *colormanage_view_get_indexed(int index)
1867 {
1868         /* view transform indices are 1-based */
1869         return BLI_findlink(&global_views, index - 1);
1870 }
1871
1872 int IMB_colormanagement_view_get_named_index(const char *name)
1873 {
1874         ColorManagedView *view = colormanage_view_get_named(name);
1875
1876         if (view) {
1877                 return view->index;
1878         }
1879
1880         return 0;
1881 }
1882
1883 const char *IMB_colormanagement_view_get_indexed_name(int index)
1884 {
1885         ColorManagedView *view = colormanage_view_get_indexed(index);
1886
1887         if (view) {
1888                 return view->name;
1889         }
1890
1891         return NULL;
1892 }
1893
1894 const char *IMB_colormanagement_view_get_default_name(const char *display_name)
1895 {
1896         ColorManagedDisplay *display = colormanage_display_get_named(display_name);
1897         ColorManagedView *view = colormanage_view_get_default(display);
1898
1899         if (view) {
1900                 return view->name;
1901         }
1902
1903         return NULL;
1904 }
1905
1906 /*********************** Color space functions *************************/
1907
1908 static void colormanage_description_strip(char *description)
1909 {
1910         int i, n;
1911
1912         for (i = strlen(description) - 1; i >= 0; i--) {
1913                 if (ELEM(description[i], '\r', '\n')) {
1914                         description[i] = '\0';
1915                 }
1916                 else {
1917                         break;
1918                 }
1919         }
1920
1921         for (i = 0, n = strlen(description); i < n; i++) {
1922                 if (ELEM(description[i], '\r', '\n')) {
1923                         description[i] = ' ';
1924                 }
1925         }
1926 }
1927
1928 ColorSpace *colormanage_colorspace_add(const char *name, const char *description, int is_invertible)
1929 {
1930         ColorSpace *colorspace, *prev_space;
1931         int counter = 1;
1932
1933         colorspace = MEM_callocN(sizeof(ColorSpace), "ColorSpace");
1934
1935         BLI_strncpy(colorspace->name, name, sizeof(colorspace->name));
1936
1937         if (description) {
1938                 BLI_strncpy(colorspace->description, description, sizeof(colorspace->description));
1939
1940                 colormanage_description_strip(colorspace->description);
1941         }
1942
1943         colorspace->is_invertible = is_invertible;
1944
1945         for (prev_space = global_colorspaces.first; prev_space; prev_space = prev_space->next) {
1946                 if (BLI_strcasecmp(prev_space->name, colorspace->name) > 0)
1947                         break;
1948
1949                 prev_space->index = counter++;
1950         }
1951
1952         if (!prev_space)
1953                 BLI_addtail(&global_colorspaces, colorspace);
1954         else
1955                 BLI_insertlinkbefore(&global_colorspaces, prev_space, colorspace);
1956
1957         colorspace->index = counter++;
1958         for (; prev_space; prev_space = prev_space->next) {
1959                 prev_space->index = counter++;
1960         }
1961
1962         global_tot_colorspace++;
1963
1964         return colorspace;
1965 }
1966
1967 ColorSpace *colormanage_colorspace_get_named(const char *name)
1968 {
1969         ColorSpace *colorspace;
1970
1971         for (colorspace = global_colorspaces.first; colorspace; colorspace = colorspace->next) {
1972                 if (!strcmp(colorspace->name, name))
1973                         return colorspace;
1974         }
1975
1976         return NULL;
1977 }
1978
1979 ColorSpace *colormanage_colorspace_get_roled(int role)
1980 {
1981         const char *role_colorspace = IMB_colormanagement_role_colorspace_name_get(role);
1982
1983         return colormanage_colorspace_get_named(role_colorspace);
1984 }
1985
1986 ColorSpace *colormanage_colorspace_get_indexed(int index)
1987 {
1988         /* display indices are 1-based */
1989         return BLI_findlink(&global_colorspaces, index - 1);
1990 }
1991
1992 int IMB_colormanagement_colorspace_get_named_index(const char *name)
1993 {
1994         ColorSpace *colorspace;
1995
1996         colorspace = colormanage_colorspace_get_named(name);
1997
1998         if (colorspace) {
1999                 return colorspace->index;
2000         }
2001
2002         return 0;
2003 }
2004
2005 const char *IMB_colormanagement_colorspace_get_indexed_name(int index)
2006 {
2007         ColorSpace *colorspace;
2008
2009         colorspace = colormanage_colorspace_get_indexed(index);
2010
2011         if (colorspace) {
2012                 return colorspace->name;
2013         }
2014
2015         return "";
2016 }
2017
2018 void IMB_colormanagment_colorspace_from_ibuf_ftype(ColorManagedColorspaceSettings *colorspace_settings, ImBuf *ibuf)
2019 {
2020         ImFileType *type;
2021
2022         for (type = IMB_FILE_TYPES; type->is_a; type++) {
2023                 if (type->save && type->ftype(type, ibuf)) {
2024                         const char *role_colorspace;
2025
2026                         role_colorspace = IMB_colormanagement_role_colorspace_name_get(type->default_save_role);
2027
2028                         BLI_strncpy(colorspace_settings->name, role_colorspace, sizeof(colorspace_settings->name));
2029                 }
2030         }
2031 }
2032
2033 /*********************** RNA helper functions *************************/
2034
2035 void IMB_colormanagement_display_items_add(EnumPropertyItem **items, int *totitem)
2036 {
2037         ColorManagedDisplay *display;
2038
2039         for (display = global_displays.first; display; display = display->next) {
2040                 EnumPropertyItem item;
2041
2042                 item.value = display->index;
2043                 item.name = display->name;
2044                 item.identifier = display->name;
2045                 item.icon = 0;
2046                 item.description = "";
2047
2048                 RNA_enum_item_add(items, totitem, &item);
2049         }
2050 }
2051
2052 static void colormanagement_view_item_add(EnumPropertyItem **items, int *totitem, ColorManagedView *view)
2053 {
2054         EnumPropertyItem item;
2055
2056         item.value = view->index;
2057         item.name = view->name;
2058         item.identifier = view->name;
2059         item.icon = 0;
2060         item.description = "";
2061
2062         RNA_enum_item_add(items, totitem, &item);
2063 }
2064
2065 void IMB_colormanagement_view_items_add(EnumPropertyItem **items, int *totitem, const char *display_name)
2066 {
2067         ColorManagedDisplay *display = colormanage_display_get_named(display_name);
2068         ColorManagedView *view;
2069
2070         if (display) {
2071                 LinkData *display_view;
2072
2073                 for (display_view = display->views.first; display_view; display_view = display_view->next) {
2074                         view = display_view->data;
2075
2076                         colormanagement_view_item_add(items, totitem, view);
2077                 }
2078         }
2079 }
2080
2081 void IMB_colormanagement_colorspace_items_add(EnumPropertyItem **items, int *totitem)
2082 {
2083         ColorSpace *colorspace;
2084
2085         for (colorspace = global_colorspaces.first; colorspace; colorspace = colorspace->next) {
2086                 EnumPropertyItem item;
2087
2088                 if (!colorspace->is_invertible)
2089                         continue;
2090
2091                 item.value = colorspace->index;
2092                 item.name = colorspace->name;
2093                 item.identifier = colorspace->name;
2094                 item.icon = 0;
2095
2096                 if (colorspace->description)
2097                         item.description = colorspace->description;
2098                 else
2099                         item.description = "";
2100
2101                 RNA_enum_item_add(items, totitem, &item);
2102         }
2103 }
2104
2105 /*********************** Partial display buffer update  *************************/
2106
2107 /*
2108  * Partial display update is supposed to be used by such areas as
2109  * compositor and renderer, This areas are calculating tiles of the
2110  * images and because of performance reasons only this tiles should
2111  * be color managed.
2112  * This gives nice visual feedback without slowing things down.
2113  *
2114  * Updating happens for active display transformation only, all
2115  * the rest buffers would be marked as dirty
2116  */
2117
2118 static void partial_buffer_update_rect(ImBuf *ibuf, unsigned char *display_buffer, const float *linear_buffer,
2119                                        const unsigned char *byte_buffer, int display_stride, int linear_stride,
2120                                        int linear_offset_x, int linear_offset_y, ColormanageProcessor *cm_processor,
2121                                        int xmin, int ymin, int xmax, int ymax)
2122 {
2123         int x, y;
2124         int channels = ibuf->channels;
2125         int predivide = ibuf->flags & IB_cm_predivide;
2126         float dither = ibuf->dither;
2127         ColorSpace *rect_colorspace = ibuf->rect_colorspace;
2128         float *display_buffer_float = NULL;
2129         int width = xmax - xmin;
2130         int height = ymax - ymin;
2131
2132         if (dither != 0.0f) {
2133                 display_buffer_float = MEM_callocN(channels * width * height * sizeof(float), "display buffer for dither");
2134         }
2135
2136         for (y = ymin; y < ymax; y++) {
2137                 for (x = xmin; x < xmax; x++) {
2138                         int display_index = (y * display_stride + x) * channels;
2139                         int linear_index = ((y - linear_offset_y) * linear_stride + (x - linear_offset_x)) * channels;
2140                         float pixel[4];
2141
2142                         if (linear_buffer) {
2143                                 copy_v4_v4(pixel, (float *) linear_buffer + linear_index);
2144                         }
2145                         else if (byte_buffer) {
2146                                 rgba_uchar_to_float(pixel, byte_buffer + linear_index);
2147
2148                                 IMB_colormanagement_colorspace_to_scene_linear_v3(pixel, rect_colorspace);
2149                         }
2150
2151                         if (predivide)
2152                                 IMB_colormanagement_processor_apply_v4(cm_processor, pixel);
2153                         else
2154                                 IMB_colormanagement_processor_apply_v4(cm_processor, pixel);
2155
2156                         if (display_buffer_float) {
2157                                 int index = ((y - ymin) * width + (x - xmin)) * channels;
2158
2159                                 copy_v4_v4(display_buffer_float + index, pixel);
2160                         }
2161                         else {
2162                                 rgba_float_to_uchar(display_buffer + display_index, pixel);
2163                         }
2164                 }
2165         }
2166
2167         if (display_buffer_float) {
2168                 int display_index = (ymin * display_stride + xmin) * channels;
2169
2170                 IMB_buffer_byte_from_float(display_buffer + display_index, display_buffer_float, channels, dither,
2171                                            IB_PROFILE_SRGB, IB_PROFILE_SRGB, FALSE, width, height, display_stride, width);
2172
2173                 MEM_freeN(display_buffer_float);
2174         }
2175 }
2176
2177 void IMB_partial_display_buffer_update(ImBuf *ibuf, const float *linear_buffer, const unsigned char *byte_buffer,
2178                                        int stride, int offset_x, int offset_y, const ColorManagedViewSettings *view_settings,
2179                                        const ColorManagedDisplaySettings *display_settings,
2180                                        int xmin, int ymin, int xmax, int ymax)
2181 {
2182         if (ibuf->rect && ibuf->rect_float) {
2183                 /* update byte buffer created by legacy color management */
2184
2185                 unsigned char *rect = (unsigned char *) ibuf->rect;
2186                 int predivide = ibuf->flags & IB_cm_predivide;
2187                 int channels = ibuf->channels;
2188                 int width = xmax - xmin;
2189                 int height = ymax - ymin;
2190                 int rect_index = (ymin * ibuf->x + xmin) * channels;
2191                 int linear_index = ((ymin - offset_y) * stride + (xmin - offset_x)) * channels;
2192
2193                 IMB_buffer_byte_from_float(rect + rect_index, linear_buffer + linear_index, channels, ibuf->dither,
2194                                            IB_PROFILE_SRGB, IB_PROFILE_LINEAR_RGB, predivide, width, height, ibuf->x, stride);
2195         }
2196
2197         if (ibuf->display_buffer_flags) {
2198                 ColormanageCacheViewSettings cache_view_settings;
2199                 ColormanageCacheDisplaySettings cache_display_settings;
2200                 void *cache_handle = NULL;
2201                 unsigned char *display_buffer = NULL;
2202                 int view_flag, display_index, buffer_width;
2203
2204                 colormanage_view_settings_to_cache(&cache_view_settings, view_settings);
2205                 colormanage_display_settings_to_cache(&cache_display_settings, display_settings);
2206
2207                 view_flag = 1 << (cache_view_settings.view - 1);
2208                 display_index = cache_display_settings.display - 1;
2209
2210                 BLI_lock_thread(LOCK_COLORMANAGE);
2211                 if ((ibuf->userflags & IB_DISPLAY_BUFFER_INVALID) == 0)
2212                         display_buffer = colormanage_cache_get(ibuf, &cache_view_settings, &cache_display_settings, &cache_handle);
2213
2214                 /* in some rare cases buffer's dimension could be changing directly from
2215                  * different thread
2216                  * this i.e. happens when image editor acquires render result
2217                  */
2218                 buffer_width = ibuf->x;
2219
2220                 /* mark all other buffers as invalid */
2221                 memset(ibuf->display_buffer_flags, 0, global_tot_display * sizeof(unsigned int));
2222                 ibuf->display_buffer_flags[display_index] |= view_flag;
2223
2224                 BLI_unlock_thread(LOCK_COLORMANAGE);
2225
2226                 if (display_buffer) {
2227                         ColormanageProcessor *cm_processor;
2228
2229                         cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
2230
2231                         partial_buffer_update_rect(ibuf, display_buffer, linear_buffer, byte_buffer, buffer_width, stride,
2232                                                    offset_x, offset_y, cm_processor, xmin, ymin, xmax, ymax);
2233
2234                         IMB_colormanagement_processor_free(cm_processor);
2235
2236                         IMB_display_buffer_release(cache_handle);
2237                 }
2238         }
2239 }
2240
2241 /*********************** Pixel processor functions *************************/
2242
2243 ColormanageProcessor *IMB_colormanagement_display_processor_new(const ColorManagedViewSettings *view_settings,
2244                                                                 const ColorManagedDisplaySettings *display_settings)
2245 {
2246         ColormanageProcessor *cm_processor;
2247
2248         cm_processor = MEM_callocN(sizeof(ColormanageProcessor), "colormanagement processor");
2249
2250         {
2251                 ColorManagedViewSettings default_view_settings;
2252                 const ColorManagedViewSettings *applied_view_settings;
2253
2254                 if (view_settings) {
2255                         applied_view_settings = view_settings;
2256                 }
2257                 else {
2258                         init_default_view_settings(display_settings,  &default_view_settings);
2259                         applied_view_settings = &default_view_settings;
2260                 }
2261
2262                 cm_processor->processor = create_display_buffer_processor(applied_view_settings->view_transform, display_settings->display_device,
2263                                                                           applied_view_settings->exposure, applied_view_settings->gamma);
2264
2265                 if (applied_view_settings->flag & COLORMANAGE_VIEW_USE_CURVES) {
2266                         cm_processor->curve_mapping = curvemapping_copy(applied_view_settings->curve_mapping);
2267                         curvemapping_premultiply(cm_processor->curve_mapping, FALSE);
2268                 }
2269         }
2270
2271         return cm_processor;
2272 }
2273
2274 ColormanageProcessor *IMB_colormanagement_colorspace_processor_new(const char *from_colorspace, const char *to_colorspace)
2275 {
2276         ColormanageProcessor *cm_processor;
2277
2278         cm_processor = MEM_callocN(sizeof(ColormanageProcessor), "colormanagement processor");
2279
2280         cm_processor->processor = create_colorspace_transform_processor(from_colorspace, to_colorspace);
2281
2282         return cm_processor;
2283 }
2284
2285 void IMB_colormanagement_processor_apply_v4(ColormanageProcessor *cm_processor, float pixel[4])
2286 {
2287         if (cm_processor->curve_mapping)
2288                 curvemapping_evaluate_premulRGBF(cm_processor->curve_mapping, pixel, pixel);
2289
2290         OCIO_processorApplyRGBA(cm_processor->processor, pixel);
2291 }
2292
2293 void IMB_colormanagement_processor_apply_v3(ColormanageProcessor *cm_processor, float pixel[3])
2294 {
2295         if (cm_processor->curve_mapping)
2296                 curvemapping_evaluate_premulRGBF(cm_processor->curve_mapping, pixel, pixel);
2297
2298         OCIO_processorApplyRGB(cm_processor->processor, pixel);
2299 }
2300
2301 void IMB_colormanagement_processor_apply(ColormanageProcessor *cm_processor, float *buffer, int width, int height,
2302                                          int channels, int predivide)
2303 {
2304         /* apply curve mapping */
2305         if (cm_processor->curve_mapping) {
2306                 int x, y;
2307
2308                 for (y = 0; y < height; y++) {
2309                         for (x = 0; x < width; x++) {
2310                                 float *pixel = buffer + channels * (y * width + x);
2311
2312                                 curve_mapping_apply_pixel(cm_processor->curve_mapping, pixel, channels);
2313                         }
2314                 }
2315         }
2316
2317         {
2318                 PackedImageDesc *img;
2319
2320                 /* apply OCIO processor */
2321                 img = OCIO_createPackedImageDesc(buffer, width, height, channels, sizeof(float),
2322                                                  channels * sizeof(float), channels * sizeof(float) * width);
2323
2324                 if (predivide)
2325                         OCIO_processorApply_predivide(cm_processor->processor, img);
2326                 else
2327                         OCIO_processorApply(cm_processor->processor, img);
2328
2329                 OCIO_packedImageDescRelease(img);
2330         }
2331 }
2332
2333 void IMB_colormanagement_processor_free(ColormanageProcessor *cm_processor)
2334 {
2335         if (cm_processor->curve_mapping)
2336                 curvemapping_free(cm_processor->curve_mapping);
2337
2338         OCIO_processorRelease(cm_processor->processor);
2339
2340         MEM_freeN(cm_processor);
2341 }