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