Color Management, Stage 2: Switch color pipeline to use OpenColorIO
[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) {
569                 OCIO_setCurrentConfig(config);
570
571                 colormanage_load_config(config);
572
573                 OCIO_configRelease(config);
574         }
575
576         BLI_init_srgb_conversion();
577 }
578
579 void IMB_colormanagement_exit(void)
580 {
581         colormanage_free_config();
582 }
583
584 /*********************** Internal functions *************************/
585
586 void colormanage_cache_free(ImBuf *ibuf)
587 {
588         if (ibuf->display_buffer_flags) {
589                 MEM_freeN(ibuf->display_buffer_flags);
590
591                 ibuf->display_buffer_flags = NULL;
592         }
593
594         if (ibuf->colormanage_cache) {
595                 ColormnaageCacheData *cache_data = colormanage_cachedata_get(ibuf);
596                 struct MovieCache *moviecache = colormanage_moviecache_get(ibuf);
597
598                 if (cache_data) {
599                         MEM_freeN(cache_data);
600                 }
601
602                 if (moviecache) {
603                         IMB_moviecache_free(moviecache);
604                 }
605
606                 MEM_freeN(ibuf->colormanage_cache);
607
608                 ibuf->colormanage_cache = NULL;
609         }
610 }
611
612 static void display_transform_get_from_ctx(const bContext *C, ColorManagedViewSettings **view_settings_r,
613                                            ColorManagedDisplaySettings **display_settings_r)
614 {
615         Scene *scene = CTX_data_scene(C);
616         SpaceImage *sima = CTX_wm_space_image(C);
617
618         *view_settings_r = &scene->view_settings;
619         *display_settings_r = &scene->display_settings;
620
621         if (sima) {
622                 if ((sima->image->flag & IMA_VIEW_AS_RENDER) == 0)
623                         *view_settings_r = NULL;
624         }
625 }
626
627 static ConstProcessorRcPtr *create_display_buffer_processor(const char *view_transform, const char *display,
628                                                             float exposure, float gamma)
629 {
630         ConstConfigRcPtr *config = OCIO_getCurrentConfig();
631         DisplayTransformRcPtr *dt;
632         ConstProcessorRcPtr *processor;
633
634         if (!config) {
635                 /* there's no valid OCIO configuration, can't create processor */
636
637                 return NULL;
638         }
639
640         dt = OCIO_createDisplayTransform();
641
642         /* assuming handling buffer was already converted to scene linear space */
643         OCIO_displayTransformSetInputColorSpaceName(dt, global_role_scene_linear);
644         OCIO_displayTransformSetView(dt, view_transform);
645         OCIO_displayTransformSetDisplay(dt, display);
646
647         /* fstop exposure control */
648         if (exposure != 0.0f) {
649                 MatrixTransformRcPtr *mt;
650                 float gain = powf(2.0f, exposure);
651                 const float scale4f[] = {gain, gain, gain, gain};
652                 float m44[16], offset4[4];
653
654                 OCIO_matrixTransformScale(m44, offset4, scale4f);
655                 mt = OCIO_createMatrixTransform();
656                 OCIO_matrixTransformSetValue(mt, m44, offset4);
657                 OCIO_displayTransformSetLinearCC(dt, (ConstTransformRcPtr *) mt);
658
659                 OCIO_matrixTransformRelease(mt);
660         }
661
662         /* post-display gamma transform */
663         if (gamma != 1.0f) {
664                 ExponentTransformRcPtr *et;
665                 float exponent = 1.0f / MAX2(FLT_EPSILON, gamma);
666                 const float exponent4f[] = {exponent, exponent, exponent, exponent};
667
668                 et = OCIO_createExponentTransform();
669                 OCIO_exponentTransformSetValue(et, exponent4f);
670                 OCIO_displayTransformSetDisplayCC(dt, (ConstTransformRcPtr *) et);
671
672                 OCIO_exponentTransformRelease(et);
673         }
674
675         processor = OCIO_configGetProcessor(config, (ConstTransformRcPtr *) dt);
676
677         OCIO_displayTransformRelease(dt);
678         OCIO_configRelease(config);
679
680         return processor;
681 }
682
683 static ConstProcessorRcPtr *create_colorspace_transform_processor(const char *from_colorspace,
684                                                                   const char *to_colorspace)
685 {
686         ConstConfigRcPtr *config = OCIO_getCurrentConfig();
687         ConstProcessorRcPtr *processor;
688
689         if (!config) {
690                 /* there's no valid OCIO configuration, can't create processor */
691
692                 return NULL;
693         }
694
695         processor = OCIO_configGetProcessorWithNames(config, from_colorspace, to_colorspace);
696
697         OCIO_configRelease(config);
698
699         return processor;
700 }
701
702 static ConstProcessorRcPtr *colorspace_to_scene_linear_processor(ColorSpace *colorspace)
703 {
704         if (colorspace->to_scene_linear == NULL) {
705                 BLI_lock_thread(LOCK_COLORMANAGE);
706
707                 if (colorspace->to_scene_linear == NULL) {
708                         ConstProcessorRcPtr *to_scene_linear;
709                         to_scene_linear = create_colorspace_transform_processor(colorspace->name, global_role_scene_linear);
710                         colorspace->to_scene_linear = (struct ConstProcessorRcPtr *) to_scene_linear;
711                 }
712
713                 BLI_unlock_thread(LOCK_COLORMANAGE);
714         }
715
716         return (ConstProcessorRcPtr *) colorspace->to_scene_linear;
717 }
718
719 static ConstProcessorRcPtr *colorspace_from_scene_linear_processor(ColorSpace *colorspace)
720 {
721         if (colorspace->from_scene_linear == NULL) {
722                 BLI_lock_thread(LOCK_COLORMANAGE);
723
724                 if (colorspace->from_scene_linear == NULL) {
725                         ConstProcessorRcPtr *from_scene_linear;
726                         from_scene_linear = create_colorspace_transform_processor(global_role_scene_linear, colorspace->name);
727                         colorspace->from_scene_linear = (struct ConstProcessorRcPtr *) from_scene_linear;
728                 }
729
730                 BLI_unlock_thread(LOCK_COLORMANAGE);
731         }
732
733         return (ConstProcessorRcPtr *) colorspace->from_scene_linear;
734 }
735
736 static ConstProcessorRcPtr *display_from_scene_linear_processor(ColorManagedDisplay *display)
737 {
738         if (display->from_scene_linear == NULL) {
739                 BLI_lock_thread(LOCK_COLORMANAGE);
740
741                 if (display->from_scene_linear == NULL) {
742                         const char *view_name = colormanage_view_get_default_name(display);
743                         ConstConfigRcPtr *config = OCIO_getCurrentConfig();
744                         ConstProcessorRcPtr *processor = NULL;
745
746                         if (view_name && config) {
747                                 const char *view_colorspace = OCIO_configGetDisplayColorSpaceName(config, display->name, view_name);
748                                 processor = OCIO_configGetProcessorWithNames(config, global_role_scene_linear, view_colorspace);
749
750                                 OCIO_configRelease(config);
751                         }
752
753                         display->from_scene_linear = (struct ConstProcessorRcPtr *) processor;
754                 }
755
756                 BLI_unlock_thread(LOCK_COLORMANAGE);
757         }
758
759         return (ConstProcessorRcPtr *) display->from_scene_linear;
760 }
761
762 static ConstProcessorRcPtr *display_to_scene_linear_processor(ColorManagedDisplay *display)
763 {
764         if (display->to_scene_linear == NULL) {
765                 BLI_lock_thread(LOCK_COLORMANAGE);
766
767                 if (display->to_scene_linear == NULL) {
768                         const char *view_name = colormanage_view_get_default_name(display);
769                         ConstConfigRcPtr *config = OCIO_getCurrentConfig();
770                         ConstProcessorRcPtr *processor = NULL;
771
772                         if (view_name && config) {
773                                 const char *view_colorspace = OCIO_configGetDisplayColorSpaceName(config, display->name, view_name);
774                                 processor = OCIO_configGetProcessorWithNames(config, view_colorspace, global_role_scene_linear);
775
776                                 OCIO_configRelease(config);
777                         }
778
779                         display->to_scene_linear = (struct ConstProcessorRcPtr *) processor;
780                 }
781
782                 BLI_unlock_thread(LOCK_COLORMANAGE);
783         }
784
785         return (ConstProcessorRcPtr *) display->to_scene_linear;
786 }
787
788 static void init_default_view_settings(const ColorManagedDisplaySettings *display_settings,
789                                        ColorManagedViewSettings *view_settings)
790 {
791         ColorManagedDisplay *display;
792         ColorManagedView *default_view;
793
794         display = colormanage_display_get_named(display_settings->display_device);
795         default_view = colormanage_view_get_default(display);
796
797         if (default_view)
798                 BLI_strncpy(view_settings->view_transform, default_view->name, sizeof(view_settings->view_transform));
799         else
800                 view_settings->view_transform[0] = '\0';
801
802         view_settings->flag = 0;
803         view_settings->gamma = 1.0f;
804         view_settings->exposure = 0.0f;
805         view_settings->curve_mapping = NULL;
806 }
807
808 static void curve_mapping_apply_pixel(CurveMapping *curve_mapping, float *pixel, int channels)
809 {
810         if (channels == 1) {
811                 pixel[0] = curvemap_evaluateF(curve_mapping->cm, pixel[0]);
812         }
813         else if (channels == 2) {
814                 pixel[0] = curvemap_evaluateF(curve_mapping->cm, pixel[0]);
815                 pixel[1] = curvemap_evaluateF(curve_mapping->cm, pixel[1]);
816         }
817         else {
818                 curvemapping_evaluate_premulRGBF(curve_mapping, pixel, pixel);
819         }
820 }
821
822 void colorspace_set_default_role(char *colorspace, int size, int role)
823 {
824         if (colorspace && colorspace[0] == '\0') {
825                 const char *role_colorspace;
826
827                 role_colorspace = IMB_colormanagement_role_colorspace_name_get(role);
828
829                 BLI_strncpy(colorspace, role_colorspace, size);
830         }
831 }
832
833 void colormanage_imbuf_set_default_spaces(ImBuf *ibuf)
834 {
835         ibuf->rect_colorspace = colormanage_colorspace_get_named(global_role_default_byte);
836 }
837
838 void colormanage_imbuf_make_linear(ImBuf *ibuf, const char *from_colorspace)
839 {
840         if (ibuf->rect_float) {
841                 const char *to_colorspace = global_role_scene_linear;
842                 int predivide = ibuf->flags & IB_cm_predivide;
843
844                 if (ibuf->rect)
845                         imb_freerectImBuf(ibuf);
846
847                 IMB_colormanagement_transform(ibuf->rect_float, ibuf->x, ibuf->y, ibuf->channels,
848                                               from_colorspace, to_colorspace, predivide);
849         }
850 }
851
852 /*********************** Generic functions *************************/
853
854 static void colormanage_check_display_settings(ColorManagedDisplaySettings *display_settings, const char *what,
855                                                const ColorManagedDisplay *default_display)
856 {
857         if (display_settings->display_device[0] == '\0') {
858                 BLI_strncpy(display_settings->display_device, default_display->name, sizeof(display_settings->display_device));
859         }
860         else {
861                 ColorManagedDisplay *display = colormanage_display_get_named(display_settings->display_device);
862
863                 if (!display) {
864                         printf("Color management: display \"%s\" used by %s not found, setting to default (\"%s\").\n",
865                                display_settings->display_device, what, default_display->name);
866
867                         BLI_strncpy(display_settings->display_device, default_display->name,
868                                     sizeof(display_settings->display_device));
869                 }
870         }
871 }
872
873 static void colormanage_check_view_settings(ColorManagedDisplaySettings *display_settings,
874                                             ColorManagedViewSettings *view_settings, const char *what)
875 {
876         ColorManagedDisplay *display;
877         ColorManagedView *default_view;
878
879         if (view_settings->view_transform[0] == '\0') {
880                 display = colormanage_display_get_named(display_settings->display_device);
881                 default_view = colormanage_view_get_default(display);
882
883                 if (default_view)
884                         BLI_strncpy(view_settings->view_transform, default_view->name, sizeof(view_settings->view_transform));
885         }
886         else {
887                 ColorManagedView *view = colormanage_view_get_named(view_settings->view_transform);
888
889                 if (!view) {
890                         display = colormanage_display_get_named(display_settings->display_device);
891                         default_view = colormanage_view_get_default(display);
892
893                         if (default_view) {
894                                 printf("Color management: %s view \"%s\" not found, setting default \"%s\".\n",
895                                        what, view_settings->view_transform, default_view->name);
896
897                                 BLI_strncpy(view_settings->view_transform, default_view->name, sizeof(view_settings->view_transform));
898                         }
899                 }
900         }
901
902         /* OCIO_TODO: move to do_versions() */
903         if (view_settings->exposure == 0.0f && view_settings->gamma == 0.0f) {
904                 view_settings->exposure = 0.0f;
905                 view_settings->gamma = 1.0f;
906         }
907 }
908
909 static void colormanage_check_colorspace_settings(ColorManagedColorspaceSettings *colorspace_settings, const char *what)
910 {
911         if (colorspace_settings->name[0] == '\0') {
912                 /* pass */
913         }
914         else {
915                 ColorSpace *colorspace = colormanage_colorspace_get_named(colorspace_settings->name);
916
917                 if (!colorspace) {
918                         printf("Color management: %s colorspace \"%s\" not found, will use default instead.\n",
919                                what, colorspace_settings->name);
920
921                         BLI_strncpy(colorspace_settings->name, "", sizeof(colorspace_settings->name));
922                 }
923         }
924
925         (void) what;
926 }
927
928 void IMB_colormanagement_check_file_config(Main *bmain)
929 {
930         Scene *scene;
931         Image *image;
932         MovieClip *clip;
933
934         ColorManagedDisplay *default_display;
935
936         default_display = colormanage_display_get_default();
937
938         if (!default_display) {
939                 /* happens when OCIO configuration is incorrect */
940                 return;
941         }
942
943         for (scene = bmain->scene.first; scene; scene = scene->id.next) {
944                 ColorManagedColorspaceSettings *sequencer_colorspace_settings;
945
946                 colormanage_check_display_settings(&scene->display_settings, "scene", default_display);
947                 colormanage_check_view_settings(&scene->display_settings, &scene->view_settings, "scene");
948
949                 sequencer_colorspace_settings = &scene->sequencer_colorspace_settings;
950
951                 colormanage_check_colorspace_settings(sequencer_colorspace_settings, "sequencer");
952
953                 if (sequencer_colorspace_settings->name[0] == '\0') {
954                         BLI_strncpy(sequencer_colorspace_settings->name, global_role_default_sequencer, MAX_COLORSPACE_NAME);
955                 }
956         }
957
958         /* ** check input color space settings ** */
959
960         for (image = bmain->image.first; image; image = image->id.next) {
961                 colormanage_check_colorspace_settings(&image->colorspace_settings, "image");
962         }
963
964         for (clip = bmain->movieclip.first; clip; clip = clip->id.next) {
965                 colormanage_check_colorspace_settings(&clip->colorspace_settings, "clip");
966         }
967 }
968
969 void IMB_colormanagement_validate_settings(ColorManagedDisplaySettings *display_settings,
970                                            ColorManagedViewSettings *view_settings)
971 {
972         ColorManagedDisplay *display;
973         ColorManagedView *default_view;
974         LinkData *view_link;
975
976         display = colormanage_display_get_named(display_settings->display_device);
977         default_view = colormanage_view_get_default(display);
978
979         for (view_link = display->views.first; view_link; view_link = view_link->next) {
980                 ColorManagedView *view = view_link->data;
981
982                 if (!strcmp(view->name, view_settings->view_transform))
983                         break;
984         }
985
986         if (view_link == NULL)
987                 BLI_strncpy(view_settings->view_transform, default_view->name, sizeof(view_settings->view_transform));
988 }
989
990 const char *IMB_colormanagement_role_colorspace_name_get(int role)
991 {
992         switch (role) {
993                 case COLOR_ROLE_SCENE_LINEAR:
994                         return global_role_scene_linear;
995                         break;
996                 case COLOR_ROLE_COLOR_PICKING:
997                         return global_role_color_picking;
998                         break;
999                 case COLOR_ROLE_TEXTURE_PAINTING:
1000                         return global_role_texture_painting;
1001                         break;
1002                 case COLOR_ROLE_DEFAULT_SEQUENCER:
1003                         return global_role_default_sequencer;
1004                         break;
1005                 case COLOR_ROLE_DEFAULT_FLOAT:
1006                         return global_role_default_float;
1007                         break;
1008                 case COLOR_ROLE_DEFAULT_BYTE:
1009                         return global_role_default_byte;
1010                         break;
1011                 default:
1012                         printf("Unknown role was passed to %s\n", __func__);
1013                         BLI_assert(0);
1014         }
1015
1016         return NULL;
1017 }
1018
1019 /*********************** Threaded display buffer transform routines *************************/
1020
1021 typedef struct DisplayBufferThread {
1022         ColormanageProcessor *cm_processor;
1023
1024         float *buffer;
1025         unsigned char *byte_buffer;
1026
1027         float *display_buffer;
1028         unsigned char *display_buffer_byte;
1029
1030         int width;
1031         int start_line;
1032         int tot_line;
1033
1034         int channels;
1035         float dither;
1036         int predivide;
1037
1038         const char *byte_colorspace;
1039         const char *float_colorspace;
1040 } DisplayBufferThread;
1041
1042 typedef struct DisplayBufferInitData {
1043         ImBuf *ibuf;
1044         ColormanageProcessor *cm_processor;
1045         float *buffer;
1046         unsigned char *byte_buffer;
1047
1048         float *display_buffer;
1049         unsigned char *display_buffer_byte;
1050
1051         int width;
1052
1053         const char *byte_colorspace;
1054         const char *float_colorspace;
1055 } DisplayBufferInitData;
1056
1057 static void display_buffer_init_handle(void *handle_v, int start_line, int tot_line, void *init_data_v)
1058 {
1059         DisplayBufferThread *handle = (DisplayBufferThread *) handle_v;
1060         DisplayBufferInitData *init_data = (DisplayBufferInitData *) init_data_v;
1061         ImBuf *ibuf = init_data->ibuf;
1062
1063         int predivide = ibuf->flags & IB_cm_predivide;
1064         int channels = ibuf->channels;
1065         float dither = ibuf->dither;
1066
1067         int offset = channels * start_line * ibuf->x;
1068
1069         memset(handle, 0, sizeof(DisplayBufferThread));
1070
1071         handle->cm_processor = init_data->cm_processor;
1072
1073         if (init_data->buffer)
1074                 handle->buffer = init_data->buffer + offset;
1075
1076         if (init_data->byte_buffer)
1077                 handle->byte_buffer = init_data->byte_buffer + offset;
1078
1079         if (init_data->display_buffer)
1080                 handle->display_buffer = init_data->display_buffer + offset;
1081
1082         if (init_data->display_buffer_byte)
1083                 handle->display_buffer_byte = init_data->display_buffer_byte + offset;
1084
1085         handle->width = ibuf->x;
1086
1087         handle->start_line = start_line;
1088         handle->tot_line = tot_line;
1089
1090         handle->channels = channels;
1091         handle->dither = dither;
1092         handle->predivide = predivide;
1093
1094         handle->byte_colorspace = init_data->byte_colorspace;
1095         handle->float_colorspace = init_data->float_colorspace;
1096 }
1097
1098 static void *display_buffer_apply_get_linear_buffer(DisplayBufferThread *handle)
1099 {
1100         float *linear_buffer = NULL;
1101
1102         int channels = handle->channels;
1103         int width = handle->width;
1104         int height = handle->tot_line;
1105
1106         int buffer_size = channels * width * height;
1107
1108         int predivide = handle->predivide;
1109
1110         linear_buffer = MEM_callocN(buffer_size * sizeof(float), "color conversion linear buffer");
1111
1112         if (!handle->buffer) {
1113                 unsigned char *byte_buffer = handle->byte_buffer;
1114
1115                 const char *from_colorspace = handle->byte_colorspace;
1116                 const char *to_colorspace = global_role_scene_linear;
1117
1118                 float *fp;
1119                 unsigned char *cp;
1120                 int i;
1121
1122                 /* first convert byte buffer to float, keep in image space */
1123                 for (i = 0, fp = linear_buffer, cp = byte_buffer;
1124                      i < channels * width * height;
1125                          i++, fp++, cp++)
1126                 {
1127                         *fp = (float)(*cp) / 255.0f;
1128                 }
1129
1130                 /* convert float buffer to scene linear space */
1131                 IMB_colormanagement_transform(linear_buffer, width, height, channels,
1132                                               from_colorspace, to_colorspace, predivide);
1133         }
1134         else if (handle->float_colorspace) {
1135                 /* currently float is non-linear only in sequencer, which is working
1136                  * in it's own color space even to handle float buffers.
1137                  * This color space is the same for byte and float images.
1138                  * Need to convert float buffer to linear space before applying display transform
1139                  */
1140
1141                 const char *from_colorspace = handle->float_colorspace;
1142                 const char *to_colorspace = global_role_scene_linear;
1143
1144                 memcpy(linear_buffer, handle->buffer, buffer_size * sizeof(float));
1145
1146                 IMB_colormanagement_transform(linear_buffer, width, height, channels,
1147                                               from_colorspace, to_colorspace, predivide);
1148         }
1149         else {
1150                 /* some processors would want to modify float original buffer
1151                  * before converting it into display byte buffer, so we need to
1152                  * make sure original's ImBuf buffers wouldn't be modified by
1153                  * using duplicated buffer here
1154                  *
1155                  * NOTE: MEM_dupallocN can't be used because buffer could be
1156                  *       specified as an offset inside allocated buffer
1157                  */
1158
1159                 memcpy(linear_buffer, handle->buffer, buffer_size * sizeof(float));
1160         }
1161
1162         return linear_buffer;
1163 }
1164
1165 static void *do_display_buffer_apply_thread(void *handle_v)
1166 {
1167         DisplayBufferThread *handle = (DisplayBufferThread *) handle_v;
1168         ColormanageProcessor *cm_processor = handle->cm_processor;
1169         float *buffer = handle->buffer;
1170         float *display_buffer = handle->display_buffer;
1171         unsigned char *display_buffer_byte = handle->display_buffer_byte;
1172         int channels = handle->channels;
1173         int width = handle->width;
1174         int height = handle->tot_line;
1175         float dither = handle->dither;
1176         int predivide = handle->predivide;
1177
1178         float *linear_buffer = display_buffer_apply_get_linear_buffer(handle);
1179
1180         /* apply processor */
1181         IMB_colormanagement_processor_apply(cm_processor, linear_buffer, width, height, channels, predivide);
1182
1183         /* copy result to output buffers */
1184         if (display_buffer_byte) {
1185                 /* do conversion */
1186                 IMB_buffer_byte_from_float(display_buffer_byte, linear_buffer,
1187                                            channels, dither, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
1188                                            predivide, width, height, width, width);
1189         }
1190
1191         if (display_buffer)
1192                 memcpy(display_buffer, linear_buffer, width * height * channels * sizeof(float));
1193
1194         if (linear_buffer != buffer)
1195                 MEM_freeN(linear_buffer);
1196
1197         return NULL;
1198 }
1199
1200 static void display_buffer_apply_threaded(ImBuf *ibuf, float *buffer, unsigned char *byte_buffer, float *display_buffer,
1201                                           unsigned char *display_buffer_byte, ColormanageProcessor *cm_processor)
1202 {
1203         DisplayBufferInitData init_data;
1204
1205         init_data.ibuf = ibuf;
1206         init_data.cm_processor = cm_processor;
1207         init_data.buffer = buffer;
1208         init_data.byte_buffer = byte_buffer;
1209         init_data.display_buffer = display_buffer;
1210         init_data.display_buffer_byte = display_buffer_byte;
1211
1212         if (ibuf->rect_colorspace != NULL) {
1213                 init_data.byte_colorspace = ibuf->rect_colorspace->name;
1214         }
1215         else {
1216                 /* happens for viewer images, which are not so simple to determine where to
1217                  * set image buffer's color spaces
1218                  */
1219                 init_data.byte_colorspace = global_role_default_byte;
1220         }
1221
1222         if (ibuf->float_colorspace != NULL) {
1223                 /* sequencer stores float buffers in non-linear space */
1224                 init_data.float_colorspace = ibuf->float_colorspace->name;
1225         }
1226         else {
1227                 init_data.float_colorspace = NULL;
1228         }
1229
1230         IMB_processor_apply_threaded(ibuf->y, sizeof(DisplayBufferThread), &init_data,
1231                                      display_buffer_init_handle, do_display_buffer_apply_thread);
1232 }
1233
1234 static void colormanage_display_buffer_process_ex(ImBuf *ibuf, float *display_buffer, unsigned char *display_buffer_byte,
1235                                                   const ColorManagedViewSettings *view_settings,
1236                                                   const ColorManagedDisplaySettings *display_settings)
1237 {
1238         ColormanageProcessor *cm_processor;
1239
1240         cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1241
1242         display_buffer_apply_threaded(ibuf, ibuf->rect_float, (unsigned char *) ibuf->rect,
1243                                       display_buffer, display_buffer_byte, cm_processor);
1244
1245         IMB_colormanagement_processor_free(cm_processor);
1246 }
1247
1248 static void colormanage_display_buffer_process(ImBuf *ibuf, unsigned char *display_buffer,
1249                                                const ColorManagedViewSettings *view_settings,
1250                                                const ColorManagedDisplaySettings *display_settings)
1251 {
1252         colormanage_display_buffer_process_ex(ibuf, NULL, display_buffer, view_settings, display_settings);
1253 }
1254
1255 /*********************** Threaded processor transform routines *************************/
1256
1257 typedef struct ProcessorTransformThread {
1258         ColormanageProcessor *cm_processor;
1259         float *buffer;
1260         int width;
1261         int start_line;
1262         int tot_line;
1263         int channels;
1264         int predivide;
1265 } ProcessorTransformThread;
1266
1267 typedef struct ProcessorTransformInit {
1268         ColormanageProcessor *cm_processor;
1269         float *buffer;
1270         int width;
1271         int height;
1272         int channels;
1273         int predivide;
1274 } ProcessorTransformInitData;
1275
1276 static void processor_transform_init_handle(void *handle_v, int start_line, int tot_line, void *init_data_v)
1277 {
1278         ProcessorTransformThread *handle = (ProcessorTransformThread *) handle_v;
1279         ProcessorTransformInitData *init_data = (ProcessorTransformInitData *) init_data_v;
1280
1281         int channels = init_data->channels;
1282         int width = init_data->width;
1283         int predivide = init_data->predivide;
1284
1285         int offset = channels * start_line * width;
1286
1287         memset(handle, 0, sizeof(ProcessorTransformThread));
1288
1289         handle->cm_processor = init_data->cm_processor;
1290
1291         handle->buffer = init_data->buffer + offset;
1292
1293         handle->width = width;
1294
1295         handle->start_line = start_line;
1296         handle->tot_line = tot_line;
1297
1298         handle->channels = channels;
1299         handle->predivide = predivide;
1300 }
1301
1302 static void *do_processor_transform_thread(void *handle_v)
1303 {
1304         ProcessorTransformThread *handle = (ProcessorTransformThread *) handle_v;
1305         float *buffer = handle->buffer;
1306         int channels = handle->channels;
1307         int width = handle->width;
1308         int height = handle->tot_line;
1309         int predivide = handle->predivide;
1310
1311         IMB_colormanagement_processor_apply(handle->cm_processor, buffer, width, height, channels, predivide);
1312
1313         return NULL;
1314 }
1315
1316 static void processor_transform_apply_threaded(float *buffer, int width, int height, int channels,
1317                                                ColormanageProcessor *cm_processor, int predivide)
1318 {
1319         ProcessorTransformInitData init_data;
1320
1321         init_data.cm_processor = cm_processor;
1322         init_data.buffer = buffer;
1323         init_data.width = width;
1324         init_data.height = height;
1325         init_data.channels = channels;
1326         init_data.predivide = predivide;
1327
1328         IMB_processor_apply_threaded(height, sizeof(ProcessorTransformThread), &init_data,
1329                                      processor_transform_init_handle, do_processor_transform_thread);
1330 }
1331
1332 /*********************** Color space transformation functions *************************/
1333
1334 /* convert the whole buffer from specified by name color space to another - internal implementation */
1335 static void colormanagement_transform_ex(float *buffer, int width, int height, int channels, const char *from_colorspace,
1336                                          const char *to_colorspace, int predivide, int do_threaded)
1337 {
1338         ColormanageProcessor *cm_processor;
1339
1340         if (from_colorspace[0] == '\0') {
1341                 return;
1342         }
1343
1344         if (!strcmp(from_colorspace, to_colorspace)) {
1345                 /* if source and destination color spaces are identical, skip
1346                  * threading overhead and simply do nothing
1347                  */
1348                 return;
1349         }
1350
1351         cm_processor = IMB_colormanagement_colorspace_processor_new(from_colorspace, to_colorspace);
1352
1353         if (do_threaded)
1354                 processor_transform_apply_threaded(buffer, width, height, channels, cm_processor, predivide);
1355         else
1356                 IMB_colormanagement_processor_apply(cm_processor, buffer, width, height, channels, predivide);
1357
1358         IMB_colormanagement_processor_free(cm_processor);
1359 }
1360
1361 /* convert the whole buffer from specified by name color space to another */
1362 void IMB_colormanagement_transform(float *buffer, int width, int height, int channels,
1363                                    const char *from_colorspace, const char *to_colorspace, int predivide)
1364 {
1365         colormanagement_transform_ex(buffer, width, height, channels, from_colorspace, to_colorspace, predivide, FALSE);
1366 }
1367
1368 /* convert the whole buffer from specified by name color space to another
1369  * will do threaded conversion
1370  */
1371 void IMB_colormanagement_transform_threaded(float *buffer, int width, int height, int channels,
1372                                             const char *from_colorspace, const char *to_colorspace, int predivide)
1373 {
1374         colormanagement_transform_ex(buffer, width, height, channels, from_colorspace, to_colorspace, predivide, TRUE);
1375 }
1376
1377 void IMB_colormanagement_transform_v4(float pixel[4], const char *from_colorspace, const char *to_colorspace)
1378 {
1379         ColormanageProcessor *cm_processor;
1380
1381         if (from_colorspace[0] == '\0') {
1382                 return;
1383         }
1384
1385         if (!strcmp(from_colorspace, to_colorspace)) {
1386                 /* if source and destination color spaces are identical, skip
1387                  * threading overhead and simply do nothing
1388                  */
1389                 return;
1390         }
1391
1392         cm_processor = IMB_colormanagement_colorspace_processor_new(from_colorspace, to_colorspace);
1393
1394         IMB_colormanagement_processor_apply_v4(cm_processor, pixel);
1395
1396         IMB_colormanagement_processor_free(cm_processor);
1397 }
1398
1399 /* convert pixel from specified by descriptor color space to scene linear
1400  * used by performance-critical areas such as renderer and baker
1401  */
1402 void IMB_colormanagement_colorspace_to_scene_linear_v3(float pixel[3], ColorSpace *colorspace)
1403 {
1404         ConstProcessorRcPtr *processor;
1405
1406         if (!colorspace) {
1407                 /* OCIO_TODO: make sure it never happens */
1408
1409                 printf("%s: perform conversion from unknown color space\n", __func__);
1410
1411                 return;
1412         }
1413
1414         processor = colorspace_to_scene_linear_processor(colorspace);
1415
1416         if (processor)
1417                 OCIO_processorApplyRGB(processor, pixel);
1418 }
1419
1420 /* same as above, but converts colors in opposite direction */
1421 void IMB_colormanagement_scene_linear_to_colorspace_v3(float pixel[3], ColorSpace *colorspace)
1422 {
1423         ConstProcessorRcPtr *processor;
1424
1425         if (!colorspace) {
1426                 /* OCIO_TODO: make sure it never happens */
1427
1428                 printf("%s: perform conversion from unknown color space\n", __func__);
1429
1430                 return;
1431         }
1432
1433         processor = colorspace_from_scene_linear_processor(colorspace);
1434
1435         if (processor)
1436                 OCIO_processorApplyRGB(processor, pixel);
1437 }
1438
1439 void IMB_colormanagement_colorspace_to_scene_linear(float *buffer, int width, int height, int channels, struct ColorSpace *colorspace, int predivide)
1440 {
1441         ConstProcessorRcPtr *processor;
1442
1443         if (!colorspace) {
1444                 /* OCIO_TODO: make sure it never happens */
1445
1446                 printf("%s: perform conversion from unknown color space\n", __func__);
1447
1448                 return;
1449         }
1450
1451         processor = colorspace_to_scene_linear_processor(colorspace);
1452
1453         if (processor) {
1454                 PackedImageDesc *img;
1455
1456                 img = OCIO_createPackedImageDesc(buffer, width, height, channels, sizeof(float),
1457                                                  channels * sizeof(float), channels * sizeof(float) * width);
1458
1459                 if (predivide)
1460                         OCIO_processorApply_predivide(processor, img);
1461                 else
1462                         OCIO_processorApply(processor, img);
1463
1464                 OCIO_packedImageDescRelease(img);
1465         }
1466 }
1467
1468 /* convert pixel from scene linear to display space using default view
1469  * used by performance-critical areas such as color-related widgets where we want to reduce
1470  * amount of per-widget allocations
1471  */
1472 void IMB_colormanagement_scene_linear_to_display_v3(float pixel[3], ColorManagedDisplay *display)
1473 {
1474         ConstProcessorRcPtr *processor;
1475
1476         processor = display_from_scene_linear_processor(display);
1477
1478         if (processor)
1479                 OCIO_processorApplyRGB(processor, pixel);
1480 }
1481
1482 /* same as above, but converts color in opposite direction */
1483 void IMB_colormanagement_display_to_scene_linear_v3(float pixel[3], ColorManagedDisplay *display)
1484 {
1485         ConstProcessorRcPtr *processor;
1486
1487         processor = display_to_scene_linear_processor(display);
1488
1489         if (processor)
1490                 OCIO_processorApplyRGB(processor, pixel);
1491 }
1492
1493 void IMB_colormanagement_pixel_to_display_space_v4(float result[4], const float pixel[4],
1494                                                    const ColorManagedViewSettings *view_settings,
1495                                                    const ColorManagedDisplaySettings *display_settings)
1496 {
1497         ColormanageProcessor *cm_processor;
1498
1499         copy_v4_v4(result, pixel);
1500
1501         cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1502         IMB_colormanagement_processor_apply_v4(cm_processor, result);
1503         IMB_colormanagement_processor_free(cm_processor);
1504 }
1505
1506 void IMB_colormanagement_pixel_to_display_space_v3(float result[3], const float pixel[3],
1507                                                    const ColorManagedViewSettings *view_settings,
1508                                                    const ColorManagedDisplaySettings *display_settings)
1509 {
1510         ColormanageProcessor *cm_processor;
1511
1512         copy_v3_v3(result, pixel);
1513
1514         cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1515         IMB_colormanagement_processor_apply_v3(cm_processor, result);
1516         IMB_colormanagement_processor_free(cm_processor);
1517 }
1518
1519 void IMB_colormanagement_imbuf_assign_float_space(ImBuf *ibuf, ColorManagedColorspaceSettings *colorspace_settings)
1520 {
1521         ibuf->float_colorspace = colormanage_colorspace_get_named(colorspace_settings->name);
1522 }
1523
1524 void IMB_colormanagement_imbuf_make_display_space(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
1525                                                   const ColorManagedDisplaySettings *display_settings)
1526 {
1527         /* OCIO_TODO: byte buffer management is not supported here yet */
1528         if (!ibuf->rect_float)
1529                 return;
1530
1531         if (global_tot_display == 0 || global_tot_view == 0) {
1532                 IMB_buffer_float_from_float(ibuf->rect_float, ibuf->rect_float, ibuf->channels, IB_PROFILE_SRGB, IB_PROFILE_LINEAR_RGB,
1533                                             ibuf->flags & IB_cm_predivide, ibuf->x, ibuf->y, ibuf->x, ibuf->x);
1534         }
1535         else {
1536                 colormanage_display_buffer_process_ex(ibuf, ibuf->rect_float, NULL, view_settings, display_settings);
1537         }
1538 }
1539
1540 static void imbuf_verify_float(ImBuf *ibuf)
1541 {
1542         /* multiple threads could request for display buffer at once and in case
1543          * view transform is not used it'll lead to display buffer calculated
1544          * several times
1545          * it is harmless, but would take much more time (assuming thread lock
1546          * happens faster than running float->byte conversion for average image)
1547          */
1548         BLI_lock_thread(LOCK_COLORMANAGE);
1549
1550         if (ibuf->rect_float && (ibuf->rect == NULL || (ibuf->userflags & IB_RECT_INVALID))) {
1551                 IMB_rect_from_float(ibuf);
1552
1553                 ibuf->userflags &= ~IB_RECT_INVALID;
1554         }
1555
1556         BLI_unlock_thread(LOCK_COLORMANAGE);
1557 }
1558
1559 /*********************** Public display buffers interfaces *************************/
1560
1561 /* acquire display buffer for given image buffer using specified view and display settings */
1562 unsigned char *IMB_display_buffer_acquire(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
1563                                           const ColorManagedDisplaySettings *display_settings, void **cache_handle)
1564 {
1565         *cache_handle = NULL;
1566
1567         if (!ibuf->x || !ibuf->y)
1568                 return NULL;
1569
1570         if (global_tot_display == 0 || global_tot_view == 0) {
1571                 /* if there's no view transform or display transforms, fallback to standard sRGB/linear conversion
1572                  * the same logic would be used if OCIO is disabled
1573                  */
1574
1575                 imbuf_verify_float(ibuf);
1576
1577                 return (unsigned char *) ibuf->rect;
1578         }
1579         else {
1580                 unsigned char *display_buffer;
1581                 int buffer_size;
1582                 ColormanageCacheViewSettings cache_view_settings;
1583                 ColormanageCacheDisplaySettings cache_display_settings;
1584                 ColorManagedViewSettings default_view_settings;
1585                 const ColorManagedViewSettings *applied_view_settings;
1586
1587                 if (view_settings) {
1588                         applied_view_settings = view_settings;
1589                 }
1590                 else {
1591                         /* if no view settings were specified, use default display transformation
1592                          * this happens for images which don't want to be displayed with render settings
1593                          */
1594
1595                         init_default_view_settings(display_settings,  &default_view_settings);
1596                         applied_view_settings = &default_view_settings;
1597                 }
1598
1599                 colormanage_view_settings_to_cache(&cache_view_settings, applied_view_settings);
1600                 colormanage_display_settings_to_cache(&cache_display_settings, display_settings);
1601
1602                 BLI_lock_thread(LOCK_COLORMANAGE);
1603
1604                 /* ensure color management bit fields exists */
1605                 if (!ibuf->display_buffer_flags) {
1606                         if (global_tot_display)
1607                                 ibuf->display_buffer_flags = MEM_callocN(sizeof(unsigned int) * global_tot_display, "imbuf display_buffer_flags");
1608                 }
1609                  else if (ibuf->userflags & IB_DISPLAY_BUFFER_INVALID) {
1610                         /* all display buffers were marked as invalid from other areas,
1611                          * now propagate this flag to internal color management routines
1612                          */
1613                         memset(ibuf->display_buffer_flags, 0, global_tot_display * sizeof(unsigned int));
1614
1615                         ibuf->userflags &= ~IB_DISPLAY_BUFFER_INVALID;
1616                 }
1617
1618                 display_buffer = colormanage_cache_get(ibuf, &cache_view_settings, &cache_display_settings, cache_handle);
1619
1620                 if (display_buffer) {
1621                         BLI_unlock_thread(LOCK_COLORMANAGE);
1622                         return display_buffer;
1623                 }
1624
1625                 buffer_size = ibuf->channels * ibuf->x * ibuf->y * sizeof(float);
1626                 display_buffer = MEM_callocN(buffer_size, "imbuf display buffer");
1627
1628                 colormanage_display_buffer_process(ibuf, display_buffer, applied_view_settings, display_settings);
1629
1630                 colormanage_cache_put(ibuf, &cache_view_settings, &cache_display_settings, display_buffer, cache_handle);
1631
1632                 BLI_unlock_thread(LOCK_COLORMANAGE);
1633
1634                 return display_buffer;
1635         }
1636 }
1637
1638 /* same as IMB_display_buffer_acquire but gets view and display settings from context */
1639 unsigned char *IMB_display_buffer_acquire_ctx(const bContext *C, ImBuf *ibuf, void **cache_handle)
1640 {
1641         ColorManagedViewSettings *view_settings;
1642         ColorManagedDisplaySettings *display_settings;
1643
1644         display_transform_get_from_ctx(C, &view_settings, &display_settings);
1645
1646         return IMB_display_buffer_acquire(ibuf, view_settings, display_settings, cache_handle);
1647 }
1648
1649 /* covert float buffer to display space and store it in image buffer's byte array */
1650 void IMB_display_buffer_to_imbuf_rect(ImBuf *ibuf, const ColorManagedViewSettings *view_settings,
1651                                       const ColorManagedDisplaySettings *display_settings)
1652 {
1653         if (global_tot_display == 0 || global_tot_view == 0) {
1654                 imbuf_verify_float(ibuf);
1655         }
1656         else {
1657                 if (!ibuf->rect) {
1658                         imb_addrectImBuf(ibuf);
1659                 }
1660
1661                 colormanage_display_buffer_process(ibuf, (unsigned char *) ibuf->rect, view_settings, display_settings);
1662         }
1663 }
1664
1665 void IMB_display_buffer_transform_apply(unsigned char *display_buffer, float *linear_buffer, int width, int height,
1666                                         int channels, const ColorManagedViewSettings *view_settings,
1667                                         const ColorManagedDisplaySettings *display_settings, int predivide)
1668 {
1669         if (global_tot_display == 0 || global_tot_view == 0) {
1670                 IMB_buffer_byte_from_float(display_buffer, linear_buffer, 4, 0.0f, IB_PROFILE_SRGB, IB_PROFILE_LINEAR_RGB, FALSE,
1671                                            width, height, width, width);
1672         }
1673         else {
1674                 float *buffer;
1675                 ColormanageProcessor *cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
1676
1677                 buffer = MEM_callocN(channels * width * height * sizeof(float), "display transform temp buffer");
1678                 memcpy(buffer, linear_buffer, channels * width * height * sizeof(float));
1679
1680                 IMB_colormanagement_processor_apply(cm_processor, buffer, width, height, channels, predivide);
1681
1682                 IMB_colormanagement_processor_free(cm_processor);
1683
1684                 IMB_buffer_byte_from_float(display_buffer, buffer, channels, 0.0f, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
1685                                            FALSE, width, height, width, width);
1686
1687                 MEM_freeN(buffer);
1688         }
1689 }
1690
1691 void IMB_display_buffer_release(void *cache_handle)
1692 {
1693         if (cache_handle) {
1694                 BLI_lock_thread(LOCK_COLORMANAGE);
1695
1696                 colormanage_cache_handle_release(cache_handle);
1697
1698                 BLI_unlock_thread(LOCK_COLORMANAGE);
1699         }
1700 }
1701
1702 /*********************** Display functions *************************/
1703
1704 ColorManagedDisplay *colormanage_display_get_default(void)
1705 {
1706         ConstConfigRcPtr *config = OCIO_getCurrentConfig();
1707         const char *display;
1708
1709         if (!config) {
1710                 /* no valid OCIO configuration, can't get default display */
1711
1712                 return NULL;
1713         }
1714
1715         display = OCIO_configGetDefaultDisplay(config);
1716
1717         OCIO_configRelease(config);
1718
1719         if (display[0] == '\0')
1720                 return NULL;
1721
1722         return colormanage_display_get_named(display);
1723 }
1724
1725 ColorManagedDisplay *colormanage_display_add(const char *name)
1726 {
1727         ColorManagedDisplay *display;
1728         int index = 0;
1729
1730         if (global_displays.last) {
1731                 ColorManagedDisplay *last_display = global_displays.last;
1732
1733                 index = last_display->index;
1734         }
1735
1736         display = MEM_callocN(sizeof(ColorManagedDisplay), "ColorManagedDisplay");
1737
1738         display->index = index + 1;
1739
1740         BLI_strncpy(display->name, name, sizeof(display->name));
1741
1742         BLI_addtail(&global_displays, display);
1743
1744         return display;
1745 }
1746
1747 ColorManagedDisplay *colormanage_display_get_named(const char *name)
1748 {
1749         ColorManagedDisplay *display;
1750
1751         for (display = global_displays.first; display; display = display->next) {
1752                 if (!strcmp(display->name, name))
1753                         return display;
1754         }
1755
1756         return NULL;
1757 }
1758
1759 ColorManagedDisplay *colormanage_display_get_indexed(int index)
1760 {
1761         /* display indices are 1-based */
1762         return BLI_findlink(&global_displays, index - 1);
1763 }
1764
1765 int IMB_colormanagement_display_get_named_index(const char *name)
1766 {
1767         ColorManagedDisplay *display;
1768
1769         display = colormanage_display_get_named(name);
1770
1771         if (display) {
1772                 return display->index;
1773         }
1774
1775         return 0;
1776 }
1777
1778 const char *IMB_colormanagement_display_get_indexed_name(int index)
1779 {
1780         ColorManagedDisplay *display;
1781
1782         display = colormanage_display_get_indexed(index);
1783
1784         if (display) {
1785                 return display->name;
1786         }
1787
1788         return NULL;
1789 }
1790
1791 const char *IMB_colormanagement_display_get_default_name(void)
1792 {
1793         ColorManagedDisplay *display = colormanage_display_get_default();
1794
1795         return display->name;
1796 }
1797
1798 /* used by performance-critical pixel processing areas, such as color widgets */
1799 ColorManagedDisplay *IMB_colormanagement_display_get_named(const char *name)
1800 {
1801         return colormanage_display_get_named(name);
1802 }
1803
1804 /*********************** View functions *************************/
1805
1806 const char *colormanage_view_get_default_name(const ColorManagedDisplay *display)
1807 {
1808         ConstConfigRcPtr *config = OCIO_getCurrentConfig();
1809         const char *name;
1810
1811         if (!config) {
1812                 /* no valid OCIO configuration, can't get default view */
1813
1814                 return NULL;
1815         }
1816
1817         name = OCIO_configGetDefaultView(config, display->name);
1818
1819         OCIO_configRelease(config);
1820
1821         return name;
1822 }
1823
1824 ColorManagedView *colormanage_view_get_default(const ColorManagedDisplay *display)
1825 {
1826         const char *name = colormanage_view_get_default_name(display);
1827
1828         if (!name || name[0] == '\0')
1829                 return NULL;
1830
1831         return colormanage_view_get_named(name);
1832 }
1833
1834 ColorManagedView *colormanage_view_add(const char *name)
1835 {
1836         ColorManagedView *view;
1837         int index = global_tot_view;
1838
1839         view = MEM_callocN(sizeof(ColorManagedView), "ColorManagedView");
1840         view->index = index + 1;
1841         BLI_strncpy(view->name, name, sizeof(view->name));
1842
1843         BLI_addtail(&global_views, view);
1844
1845         global_tot_view++;
1846
1847         return view;
1848 }
1849
1850 ColorManagedView *colormanage_view_get_named(const char *name)
1851 {
1852         ColorManagedView *view;
1853
1854         for (view = global_views.first; view; view = view->next) {
1855                 if (!strcmp(view->name, name))
1856                         return view;
1857         }
1858
1859         return NULL;
1860 }
1861
1862 ColorManagedView *colormanage_view_get_indexed(int index)
1863 {
1864         /* view transform indices are 1-based */
1865         return BLI_findlink(&global_views, index - 1);
1866 }
1867
1868 int IMB_colormanagement_view_get_named_index(const char *name)
1869 {
1870         ColorManagedView *view = colormanage_view_get_named(name);
1871
1872         if (view) {
1873                 return view->index;
1874         }
1875
1876         return 0;
1877 }
1878
1879 const char *IMB_colormanagement_view_get_indexed_name(int index)
1880 {
1881         ColorManagedView *view = colormanage_view_get_indexed(index);
1882
1883         if (view) {
1884                 return view->name;
1885         }
1886
1887         return NULL;
1888 }
1889
1890 const char *IMB_colormanagement_view_get_default_name(const char *display_name)
1891 {
1892         ColorManagedDisplay *display = colormanage_display_get_named(display_name);
1893         ColorManagedView *view = colormanage_view_get_default(display);
1894
1895         if (view) {
1896                 return view->name;
1897         }
1898
1899         return NULL;
1900 }
1901
1902 /*********************** Color space functions *************************/
1903
1904 static void colormanage_description_strip(char *description)
1905 {
1906         int i, n;
1907
1908         for (i = strlen(description) - 1; i >= 0; i--) {
1909                 if (ELEM(description[i], '\r', '\n')) {
1910                         description[i] = '\0';
1911                 }
1912                 else {
1913                         break;
1914                 }
1915         }
1916
1917         for (i = 0, n = strlen(description); i < n; i++) {
1918                 if (ELEM(description[i], '\r', '\n')) {
1919                         description[i] = ' ';
1920                 }
1921         }
1922 }
1923
1924 ColorSpace *colormanage_colorspace_add(const char *name, const char *description, int is_invertible)
1925 {
1926         ColorSpace *colorspace, *prev_space;
1927         int counter = 1;
1928
1929         colorspace = MEM_callocN(sizeof(ColorSpace), "ColorSpace");
1930
1931         BLI_strncpy(colorspace->name, name, sizeof(colorspace->name));
1932
1933         if (description) {
1934                 BLI_strncpy(colorspace->description, description, sizeof(colorspace->description));
1935
1936                 colormanage_description_strip(colorspace->description);
1937         }
1938
1939         colorspace->is_invertible = is_invertible;
1940
1941         for (prev_space = global_colorspaces.first; prev_space; prev_space = prev_space->next) {
1942                 if (BLI_strcasecmp(prev_space->name, colorspace->name) > 0)
1943                         break;
1944
1945                 prev_space->index = counter++;
1946         }
1947
1948         if (!prev_space)
1949                 BLI_addtail(&global_colorspaces, colorspace);
1950         else
1951                 BLI_insertlinkbefore(&global_colorspaces, prev_space, colorspace);
1952
1953         colorspace->index = counter++;
1954         for (; prev_space; prev_space = prev_space->next) {
1955                 prev_space->index = counter++;
1956         }
1957
1958         global_tot_colorspace++;
1959
1960         return colorspace;
1961 }
1962
1963 ColorSpace *colormanage_colorspace_get_named(const char *name)
1964 {
1965         ColorSpace *colorspace;
1966
1967         for (colorspace = global_colorspaces.first; colorspace; colorspace = colorspace->next) {
1968                 if (!strcmp(colorspace->name, name))
1969                         return colorspace;
1970         }
1971
1972         return NULL;
1973 }
1974
1975 ColorSpace *colormanage_colorspace_get_roled(int role)
1976 {
1977         const char *role_colorspace = IMB_colormanagement_role_colorspace_name_get(role);
1978
1979         return colormanage_colorspace_get_named(role_colorspace);
1980 }
1981
1982 ColorSpace *colormanage_colorspace_get_indexed(int index)
1983 {
1984         /* display indices are 1-based */
1985         return BLI_findlink(&global_colorspaces, index - 1);
1986 }
1987
1988 int IMB_colormanagement_colorspace_get_named_index(const char *name)
1989 {
1990         ColorSpace *colorspace;
1991
1992         colorspace = colormanage_colorspace_get_named(name);
1993
1994         if (colorspace) {
1995                 return colorspace->index;
1996         }
1997
1998         return 0;
1999 }
2000
2001 const char *IMB_colormanagement_colorspace_get_indexed_name(int index)
2002 {
2003         ColorSpace *colorspace;
2004
2005         colorspace = colormanage_colorspace_get_indexed(index);
2006
2007         if (colorspace) {
2008                 return colorspace->name;
2009         }
2010
2011         return "";
2012 }
2013
2014 void IMB_colormanagment_colorspace_from_ibuf_ftype(ColorManagedColorspaceSettings *colorspace_settings, ImBuf *ibuf)
2015 {
2016         ImFileType *type;
2017
2018         for (type = IMB_FILE_TYPES; type->is_a; type++) {
2019                 if (type->save && type->ftype(type, ibuf)) {
2020                         const char *role_colorspace;
2021
2022                         role_colorspace = IMB_colormanagement_role_colorspace_name_get(type->default_save_role);
2023
2024                         BLI_strncpy(colorspace_settings->name, role_colorspace, sizeof(colorspace_settings->name));
2025                 }
2026         }
2027 }
2028
2029 /*********************** RNA helper functions *************************/
2030
2031 void IMB_colormanagement_display_items_add(EnumPropertyItem **items, int *totitem)
2032 {
2033         ColorManagedDisplay *display;
2034
2035         for (display = global_displays.first; display; display = display->next) {
2036                 EnumPropertyItem item;
2037
2038                 item.value = display->index;
2039                 item.name = display->name;
2040                 item.identifier = display->name;
2041                 item.icon = 0;
2042                 item.description = "";
2043
2044                 RNA_enum_item_add(items, totitem, &item);
2045         }
2046 }
2047
2048 static void colormanagement_view_item_add(EnumPropertyItem **items, int *totitem, ColorManagedView *view)
2049 {
2050         EnumPropertyItem item;
2051
2052         item.value = view->index;
2053         item.name = view->name;
2054         item.identifier = view->name;
2055         item.icon = 0;
2056         item.description = "";
2057
2058         RNA_enum_item_add(items, totitem, &item);
2059 }
2060
2061 void IMB_colormanagement_view_items_add(EnumPropertyItem **items, int *totitem, const char *display_name)
2062 {
2063         ColorManagedDisplay *display = colormanage_display_get_named(display_name);
2064         ColorManagedView *view;
2065
2066         if (display) {
2067                 LinkData *display_view;
2068
2069                 for (display_view = display->views.first; display_view; display_view = display_view->next) {
2070                         view = display_view->data;
2071
2072                         colormanagement_view_item_add(items, totitem, view);
2073                 }
2074         }
2075 }
2076
2077 void IMB_colormanagement_colorspace_items_add(EnumPropertyItem **items, int *totitem)
2078 {
2079         ColorSpace *colorspace;
2080
2081         for (colorspace = global_colorspaces.first; colorspace; colorspace = colorspace->next) {
2082                 EnumPropertyItem item;
2083
2084                 if (!colorspace->is_invertible)
2085                         continue;
2086
2087                 item.value = colorspace->index;
2088                 item.name = colorspace->name;
2089                 item.identifier = colorspace->name;
2090                 item.icon = 0;
2091
2092                 if (colorspace->description)
2093                         item.description = colorspace->description;
2094                 else
2095                         item.description = "";
2096
2097                 RNA_enum_item_add(items, totitem, &item);
2098         }
2099 }
2100
2101 /*********************** Partial display buffer update  *************************/
2102
2103 /*
2104  * Partial display update is supposed to be used by such areas as
2105  * compositor and renderer, This areas are calculating tiles of the
2106  * images and because of performance reasons only this tiles should
2107  * be color managed.
2108  * This gives nice visual feedback without slowing things down.
2109  *
2110  * Updating happens for active display transformation only, all
2111  * the rest buffers would be marked as dirty
2112  */
2113
2114 static void partial_buffer_update_rect(ImBuf *ibuf, unsigned char *display_buffer, const float *linear_buffer,
2115                                        const unsigned char *byte_buffer, int display_stride, int linear_stride,
2116                                        int linear_offset_x, int linear_offset_y, ColormanageProcessor *cm_processor,
2117                                        int xmin, int ymin, int xmax, int ymax)
2118 {
2119         int x, y;
2120         int channels = ibuf->channels;
2121         int predivide = ibuf->flags & IB_cm_predivide;
2122         float dither = ibuf->dither;
2123         ColorSpace *rect_colorspace = ibuf->rect_colorspace;
2124         float *display_buffer_float = NULL;
2125         int width = xmax - xmin;
2126         int height = ymax - ymin;
2127
2128         if (dither != 0.0f) {
2129                 display_buffer_float = MEM_callocN(channels * width * height * sizeof(float), "display buffer for dither");
2130         }
2131
2132         for (y = ymin; y < ymax; y++) {
2133                 for (x = xmin; x < xmax; x++) {
2134                         int display_index = (y * display_stride + x) * channels;
2135                         int linear_index = ((y - linear_offset_y) * linear_stride + (x - linear_offset_x)) * channels;
2136                         float pixel[4];
2137
2138                         if (linear_buffer) {
2139                                 copy_v4_v4(pixel, (float *) linear_buffer + linear_index);
2140                         }
2141                         else if (byte_buffer) {
2142                                 rgba_uchar_to_float(pixel, byte_buffer + linear_index);
2143
2144                                 IMB_colormanagement_colorspace_to_scene_linear_v3(pixel, rect_colorspace);
2145                         }
2146
2147                         if (predivide)
2148                                 IMB_colormanagement_processor_apply_v4(cm_processor, pixel);
2149                         else
2150                                 IMB_colormanagement_processor_apply_v4(cm_processor, pixel);
2151
2152                         if (display_buffer_float) {
2153                                 int index = ((y - ymin) * width + (x - xmin)) * channels;
2154
2155                                 copy_v4_v4(display_buffer_float + index, pixel);
2156                         }
2157                         else {
2158                                 rgba_float_to_uchar(display_buffer + display_index, pixel);
2159                         }
2160                 }
2161         }
2162
2163         if (display_buffer_float) {
2164                 int display_index = (ymin * display_stride + xmin) * channels;
2165
2166                 IMB_buffer_byte_from_float(display_buffer + display_index, display_buffer_float, channels, dither,
2167                                            IB_PROFILE_SRGB, IB_PROFILE_SRGB, FALSE, width, height, display_stride, width);
2168
2169                 MEM_freeN(display_buffer_float);
2170         }
2171 }
2172
2173 void IMB_partial_display_buffer_update(ImBuf *ibuf, const float *linear_buffer, const unsigned char *byte_buffer,
2174                                        int stride, int offset_x, int offset_y, const ColorManagedViewSettings *view_settings,
2175                                        const ColorManagedDisplaySettings *display_settings,
2176                                        int xmin, int ymin, int xmax, int ymax)
2177 {
2178         if (ibuf->rect && ibuf->rect_float) {
2179                 /* update byte buffer created by legacy color management */
2180
2181                 unsigned char *rect = (unsigned char *) ibuf->rect;
2182                 int predivide = ibuf->flags & IB_cm_predivide;
2183                 int channels = ibuf->channels;
2184                 int width = xmax - xmin;
2185                 int height = ymax - ymin;
2186                 int rect_index = (ymin * ibuf->x + xmin) * channels;
2187                 int linear_index = ((ymin - offset_y) * stride + (xmin - offset_x)) * channels;
2188
2189                 IMB_buffer_byte_from_float(rect + rect_index, linear_buffer + linear_index, channels, ibuf->dither,
2190                                            IB_PROFILE_SRGB, IB_PROFILE_LINEAR_RGB, predivide, width, height, ibuf->x, stride);
2191         }
2192
2193         if (ibuf->display_buffer_flags) {
2194                 ColormanageCacheViewSettings cache_view_settings;
2195                 ColormanageCacheDisplaySettings cache_display_settings;
2196                 void *cache_handle = NULL;
2197                 unsigned char *display_buffer = NULL;
2198                 int view_flag, display_index, buffer_width;
2199
2200                 colormanage_view_settings_to_cache(&cache_view_settings, view_settings);
2201                 colormanage_display_settings_to_cache(&cache_display_settings, display_settings);
2202
2203                 view_flag = 1 << (cache_view_settings.view - 1);
2204                 display_index = cache_display_settings.display - 1;
2205
2206                 BLI_lock_thread(LOCK_COLORMANAGE);
2207                 if ((ibuf->userflags & IB_DISPLAY_BUFFER_INVALID) == 0)
2208                         display_buffer = colormanage_cache_get(ibuf, &cache_view_settings, &cache_display_settings, &cache_handle);
2209
2210                 /* in some rare cases buffer's dimension could be changing directly from
2211                  * different thread
2212                  * this i.e. happens when image editor acquires render result
2213                  */
2214                 buffer_width = ibuf->x;
2215
2216                 /* mark all other buffers as invalid */
2217                 memset(ibuf->display_buffer_flags, 0, global_tot_display * sizeof(unsigned int));
2218                 ibuf->display_buffer_flags[display_index] |= view_flag;
2219
2220                 BLI_unlock_thread(LOCK_COLORMANAGE);
2221
2222                 if (display_buffer) {
2223                         ColormanageProcessor *cm_processor;
2224
2225                         cm_processor = IMB_colormanagement_display_processor_new(view_settings, display_settings);
2226
2227                         partial_buffer_update_rect(ibuf, display_buffer, linear_buffer, byte_buffer, buffer_width, stride,
2228                                                    offset_x, offset_y, cm_processor, xmin, ymin, xmax, ymax);
2229
2230                         IMB_colormanagement_processor_free(cm_processor);
2231
2232                         IMB_display_buffer_release(cache_handle);
2233                 }
2234         }
2235 }
2236
2237 /*********************** Pixel processor functions *************************/
2238
2239 ColormanageProcessor *IMB_colormanagement_display_processor_new(const ColorManagedViewSettings *view_settings,
2240                                                                 const ColorManagedDisplaySettings *display_settings)
2241 {
2242         ColormanageProcessor *cm_processor;
2243
2244         cm_processor = MEM_callocN(sizeof(ColormanageProcessor), "colormanagement processor");
2245
2246         {
2247                 ColorManagedViewSettings default_view_settings;
2248                 const ColorManagedViewSettings *applied_view_settings;
2249
2250                 if (view_settings) {
2251                         applied_view_settings = view_settings;
2252                 }
2253                 else {
2254                         init_default_view_settings(display_settings,  &default_view_settings);
2255                         applied_view_settings = &default_view_settings;
2256                 }
2257
2258                 cm_processor->processor = create_display_buffer_processor(applied_view_settings->view_transform, display_settings->display_device,
2259                                                                           applied_view_settings->exposure, applied_view_settings->gamma);
2260
2261                 if (applied_view_settings->flag & COLORMANAGE_VIEW_USE_CURVES) {
2262                         cm_processor->curve_mapping = curvemapping_copy(applied_view_settings->curve_mapping);
2263                         curvemapping_premultiply(cm_processor->curve_mapping, FALSE);
2264                 }
2265         }
2266
2267         return cm_processor;
2268 }
2269
2270 ColormanageProcessor *IMB_colormanagement_colorspace_processor_new(const char *from_colorspace, const char *to_colorspace)
2271 {
2272         ColormanageProcessor *cm_processor;
2273
2274         cm_processor = MEM_callocN(sizeof(ColormanageProcessor), "colormanagement processor");
2275
2276         cm_processor->processor = create_colorspace_transform_processor(from_colorspace, to_colorspace);
2277
2278         return cm_processor;
2279 }
2280
2281 void IMB_colormanagement_processor_apply_v4(ColormanageProcessor *cm_processor, float pixel[4])
2282 {
2283         if (cm_processor->curve_mapping)
2284                 curvemapping_evaluate_premulRGBF(cm_processor->curve_mapping, pixel, pixel);
2285
2286         OCIO_processorApplyRGBA(cm_processor->processor, pixel);
2287 }
2288
2289 void IMB_colormanagement_processor_apply_v3(ColormanageProcessor *cm_processor, float pixel[3])
2290 {
2291         if (cm_processor->curve_mapping)
2292                 curvemapping_evaluate_premulRGBF(cm_processor->curve_mapping, pixel, pixel);
2293
2294         OCIO_processorApplyRGB(cm_processor->processor, pixel);
2295 }
2296
2297 void IMB_colormanagement_processor_apply(ColormanageProcessor *cm_processor, float *buffer, int width, int height,
2298                                          int channels, int predivide)
2299 {
2300         /* apply curve mapping */
2301         if (cm_processor->curve_mapping) {
2302                 int x, y;
2303
2304                 for (y = 0; y < height; y++) {
2305                         for (x = 0; x < width; x++) {
2306                                 float *pixel = buffer + channels * (y * width + x);
2307
2308                                 curve_mapping_apply_pixel(cm_processor->curve_mapping, pixel, channels);
2309                         }
2310                 }
2311         }
2312
2313         {
2314                 PackedImageDesc *img;
2315
2316                 /* apply OCIO processor */
2317                 img = OCIO_createPackedImageDesc(buffer, width, height, channels, sizeof(float),
2318                                                  channels * sizeof(float), channels * sizeof(float) * width);
2319
2320                 if (predivide)
2321                         OCIO_processorApply_predivide(cm_processor->processor, img);
2322                 else
2323                         OCIO_processorApply(cm_processor->processor, img);
2324
2325                 OCIO_packedImageDescRelease(img);
2326         }
2327 }
2328
2329 void IMB_colormanagement_processor_free(ColormanageProcessor *cm_processor)
2330 {
2331         if (cm_processor->curve_mapping)
2332                 curvemapping_free(cm_processor->curve_mapping);
2333
2334         OCIO_processorRelease(cm_processor->processor);
2335
2336         MEM_freeN(cm_processor);
2337 }