Port fix from gooseberry that doesn't load the full res file if a proxy
[blender.git] / source / blender / blenkernel / intern / image.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) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, 2006, full recode
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/image.c
27  *  \ingroup bke
28  */
29
30
31 #include <stdio.h>
32 #include <string.h>
33 #include <fcntl.h>
34 #include <math.h>
35 #ifndef WIN32
36 #  include <unistd.h>
37 #else
38 #  include <io.h>
39 #endif
40
41 #include <time.h>
42
43 #include "MEM_guardedalloc.h"
44
45 #include "IMB_colormanagement.h"
46 #include "IMB_imbuf_types.h"
47 #include "IMB_imbuf.h"
48 #include "IMB_moviecache.h"
49
50 #ifdef WITH_OPENEXR
51 #  include "intern/openexr/openexr_multi.h"
52 #endif
53
54 #include "DNA_packedFile_types.h"
55 #include "DNA_scene_types.h"
56 #include "DNA_object_types.h"
57 #include "DNA_camera_types.h"
58 #include "DNA_sequence_types.h"
59 #include "DNA_userdef_types.h"
60 #include "DNA_brush_types.h"
61 #include "DNA_mesh_types.h"
62 #include "DNA_meshdata_types.h"
63
64 #include "BLI_blenlib.h"
65 #include "BLI_math_vector.h"
66 #include "BLI_threads.h"
67 #include "BLI_timecode.h"  /* for stamp timecode format */
68 #include "BLI_utildefines.h"
69
70 #include "BKE_bmfont.h"
71 #include "BKE_colortools.h"
72 #include "BKE_global.h"
73 #include "BKE_icons.h"
74 #include "BKE_image.h"
75 #include "BKE_library.h"
76 #include "BKE_main.h"
77 #include "BKE_packedFile.h"
78 #include "BKE_scene.h"
79 #include "BKE_node.h"
80 #include "BKE_sequencer.h" /* seq_foreground_frame_get() */
81
82 #include "BLF_api.h"
83
84 #include "PIL_time.h"
85
86 #include "RE_pipeline.h"
87
88 #include "GPU_draw.h"
89
90 #include "BLI_sys_types.h" // for intptr_t support
91
92 /* for image user iteration */
93 #include "DNA_node_types.h"
94 #include "DNA_space_types.h"
95 #include "DNA_screen_types.h"
96 #include "DNA_view3d_types.h"
97
98 #include "WM_api.h"
99
100 static SpinLock image_spin;
101
102 /* max int, to indicate we don't store sequences in ibuf */
103 #define IMA_NO_INDEX    0x7FEFEFEF
104
105 /* quick lookup: supports 1 million frames, thousand passes */
106 #define IMA_MAKE_INDEX(frame, index)    ((frame) << 10) + index
107 #define IMA_INDEX_FRAME(index)          (index >> 10)
108 /*
109 #define IMA_INDEX_PASS(index)           (index & ~1023)
110 */
111
112 /* ******** IMAGE CACHE ************* */
113
114 typedef struct ImageCacheKey {
115         int index;
116 } ImageCacheKey;
117
118 static unsigned int imagecache_hashhash(const void *key_v)
119 {
120         const ImageCacheKey *key = key_v;
121         return key->index;
122 }
123
124 static bool imagecache_hashcmp(const void *a_v, const void *b_v)
125 {
126         const ImageCacheKey *a = a_v;
127         const ImageCacheKey *b = b_v;
128
129         return (a->index != b->index);
130 }
131
132 static void imagecache_keydata(void *userkey, int *framenr, int *proxy, int *render_flags)
133 {
134         ImageCacheKey *key = userkey;
135
136         *framenr = IMA_INDEX_FRAME(key->index);
137         *proxy = IMB_PROXY_NONE;
138         *render_flags = 0;
139 }
140
141 static void imagecache_put(Image *image, int index, ImBuf *ibuf)
142 {
143         ImageCacheKey key;
144
145         if (image->cache == NULL) {
146                 // char cache_name[64];
147                 // BLI_snprintf(cache_name, sizeof(cache_name), "Image Datablock %s", image->id.name);
148
149                 image->cache = IMB_moviecache_create("Image Datablock Cache", sizeof(ImageCacheKey),
150                                                      imagecache_hashhash, imagecache_hashcmp);
151                 IMB_moviecache_set_getdata_callback(image->cache, imagecache_keydata);
152         }
153
154         key.index = index;
155
156         IMB_moviecache_put(image->cache, &key, ibuf);
157 }
158
159 static struct ImBuf *imagecache_get(Image *image, int index)
160 {
161         if (image->cache) {
162                 ImageCacheKey key;
163                 key.index = index;
164                 return IMB_moviecache_get(image->cache, &key);
165         }
166
167         return NULL;
168 }
169
170 void BKE_images_init(void)
171 {
172         BLI_spin_init(&image_spin);
173 }
174
175 void BKE_images_exit(void)
176 {
177         BLI_spin_end(&image_spin);
178 }
179
180 /* ******** IMAGE PROCESSING ************* */
181
182 static void de_interlace_ng(struct ImBuf *ibuf) /* neogeo fields */
183 {
184         struct ImBuf *tbuf1, *tbuf2;
185
186         if (ibuf == NULL) return;
187         if (ibuf->flags & IB_fields) return;
188         ibuf->flags |= IB_fields;
189
190         if (ibuf->rect) {
191                 /* make copies */
192                 tbuf1 = IMB_allocImBuf(ibuf->x, (ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
193                 tbuf2 = IMB_allocImBuf(ibuf->x, (ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
194
195                 ibuf->x *= 2;
196
197                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
198                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
199
200                 ibuf->x /= 2;
201                 IMB_rectcpy(ibuf, tbuf1, 0, 0, 0, 0, tbuf1->x, tbuf1->y);
202                 IMB_rectcpy(ibuf, tbuf2, 0, tbuf2->y, 0, 0, tbuf2->x, tbuf2->y);
203
204                 IMB_freeImBuf(tbuf1);
205                 IMB_freeImBuf(tbuf2);
206         }
207         ibuf->y /= 2;
208 }
209
210 static void de_interlace_st(struct ImBuf *ibuf) /* standard fields */
211 {
212         struct ImBuf *tbuf1, *tbuf2;
213
214         if (ibuf == NULL) return;
215         if (ibuf->flags & IB_fields) return;
216         ibuf->flags |= IB_fields;
217
218         if (ibuf->rect) {
219                 /* make copies */
220                 tbuf1 = IMB_allocImBuf(ibuf->x, (ibuf->y >> 1), (unsigned char)32, IB_rect);
221                 tbuf2 = IMB_allocImBuf(ibuf->x, (ibuf->y >> 1), (unsigned char)32, IB_rect);
222
223                 ibuf->x *= 2;
224
225                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
226                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
227
228                 ibuf->x /= 2;
229                 IMB_rectcpy(ibuf, tbuf2, 0, 0, 0, 0, tbuf2->x, tbuf2->y);
230                 IMB_rectcpy(ibuf, tbuf1, 0, tbuf2->y, 0, 0, tbuf1->x, tbuf1->y);
231
232                 IMB_freeImBuf(tbuf1);
233                 IMB_freeImBuf(tbuf2);
234         }
235         ibuf->y /= 2;
236 }
237
238 void BKE_image_de_interlace(Image *ima, int odd)
239 {
240         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
241         if (ibuf) {
242                 if (odd)
243                         de_interlace_st(ibuf);
244                 else
245                         de_interlace_ng(ibuf);
246         }
247         BKE_image_release_ibuf(ima, ibuf, NULL);
248 }
249
250 /* ***************** ALLOC & FREE, DATA MANAGING *************** */
251
252 static void image_free_cached_frames(Image *image)
253 {
254         if (image->cache) {
255                 IMB_moviecache_free(image->cache);
256                 image->cache = NULL;
257         }
258 }
259
260 /**
261  * Simply free the image data from memory,
262  * on display the image can load again (except for render buffers).
263  */
264 void BKE_image_free_buffers(Image *ima)
265 {
266         image_free_cached_frames(ima);
267
268         if (ima->anim) IMB_free_anim(ima->anim);
269         ima->anim = NULL;
270
271         if (ima->rr) {
272                 RE_FreeRenderResult(ima->rr);
273                 ima->rr = NULL;
274         }
275
276         if (!G.background) {
277                 /* Background mode doesn't use opnegl,
278                  * so we can avoid freeing GPU images and save some
279                  * time by skipping mutex lock.
280                  */
281                 GPU_free_image(ima);
282         }
283
284         ima->ok = IMA_OK;
285 }
286
287 /* called by library too, do not free ima itself */
288 void BKE_image_free(Image *ima)
289 {
290         int a;
291
292         BKE_image_free_buffers(ima);
293         if (ima->packedfile) {
294                 freePackedFile(ima->packedfile);
295                 ima->packedfile = NULL;
296         }
297         BKE_icon_delete(&ima->id);
298         ima->id.icon_id = 0;
299
300         BKE_previewimg_free(&ima->preview);
301
302         for (a = 0; a < IMA_MAX_RENDER_SLOT; a++) {
303                 if (ima->renders[a]) {
304                         RE_FreeRenderResult(ima->renders[a]);
305                         ima->renders[a] = NULL;
306                 }
307         }
308 }
309
310 /* only image block itself */
311 static Image *image_alloc(Main *bmain, const char *name, short source, short type)
312 {
313         Image *ima;
314
315         ima = BKE_libblock_alloc(bmain, ID_IM, name);
316         if (ima) {
317                 ima->ok = IMA_OK;
318
319                 ima->xrep = ima->yrep = 1;
320                 ima->aspx = ima->aspy = 1.0;
321                 ima->gen_x = 1024; ima->gen_y = 1024;
322                 ima->gen_type = 1;   /* no defines yet? */
323
324                 ima->source = source;
325                 ima->type = type;
326
327                 if (source == IMA_SRC_VIEWER)
328                         ima->flag |= IMA_VIEW_AS_RENDER;
329
330                 BKE_color_managed_colorspace_settings_init(&ima->colorspace_settings);
331         }
332         return ima;
333 }
334
335 /* Get the ibuf from an image cache by it's index and frame.
336  * Local use here only.
337  *
338  * Returns referenced image buffer if it exists, callee is to
339  * call IMB_freeImBuf to de-reference the image buffer after
340  * it's done handling it.
341  */
342 static ImBuf *image_get_cached_ibuf_for_index_frame(Image *ima, int index, int frame)
343 {
344         if (index != IMA_NO_INDEX) {
345                 index = IMA_MAKE_INDEX(frame, index);
346         }
347
348         return imagecache_get(ima, index);
349 }
350
351 /* no ima->ibuf anymore, but listbase */
352 static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int frame)
353 {
354         if (ibuf) {
355                 if (index != IMA_NO_INDEX)
356                         index = IMA_MAKE_INDEX(frame, index);
357
358                 imagecache_put(ima, index, ibuf);
359         }
360 }
361
362 /* empty image block, of similar type and filename */
363 Image *BKE_image_copy(Main *bmain, Image *ima)
364 {
365         Image *nima = image_alloc(bmain, ima->id.name + 2, ima->source, ima->type);
366
367         BLI_strncpy(nima->name, ima->name, sizeof(ima->name));
368
369         nima->flag = ima->flag;
370         nima->tpageflag = ima->tpageflag;
371
372         nima->gen_x = ima->gen_x;
373         nima->gen_y = ima->gen_y;
374         nima->gen_type = ima->gen_type;
375         copy_v4_v4(nima->gen_color, ima->gen_color);
376
377         nima->animspeed = ima->animspeed;
378
379         nima->aspx = ima->aspx;
380         nima->aspy = ima->aspy;
381
382         BKE_color_managed_colorspace_settings_copy(&nima->colorspace_settings, &ima->colorspace_settings);
383
384         if (ima->packedfile)
385                 nima->packedfile = dupPackedFile(ima->packedfile);
386
387         if (ima->id.lib) {
388                 BKE_id_lib_local_paths(bmain, ima->id.lib, &nima->id);
389         }
390
391         return nima;
392 }
393
394 static void extern_local_image(Image *UNUSED(ima))
395 {
396         /* Nothing to do: images don't link to other IDs. This function exists to
397          * match id_make_local pattern. */
398 }
399
400 void BKE_image_make_local(struct Image *ima)
401 {
402         Main *bmain = G.main;
403         Tex *tex;
404         Brush *brush;
405         Mesh *me;
406         bool is_local = false, is_lib = false;
407
408         /* - only lib users: do nothing
409          * - only local users: set flag
410          * - mixed: make copy
411          */
412
413         if (ima->id.lib == NULL) return;
414
415         /* Can't take short cut here: must check meshes at least because of bogus
416          * texface ID refs. - z0r */
417 #if 0
418         if (ima->id.us == 1) {
419                 id_clear_lib_data(bmain, &ima->id);
420                 extern_local_image(ima);
421                 return;
422         }
423 #endif
424
425         for (tex = bmain->tex.first; tex; tex = tex->id.next) {
426                 if (tex->ima == ima) {
427                         if (tex->id.lib) is_lib = true;
428                         else is_local = true;
429                 }
430         }
431         for (brush = bmain->brush.first; brush; brush = brush->id.next) {
432                 if (brush->clone.image == ima) {
433                         if (brush->id.lib) is_lib = true;
434                         else is_local = true;
435                 }
436         }
437         for (me = bmain->mesh.first; me; me = me->id.next) {
438                 if (me->mtface) {
439                         MTFace *tface;
440                         int a, i;
441
442                         for (i = 0; i < me->fdata.totlayer; i++) {
443                                 if (me->fdata.layers[i].type == CD_MTFACE) {
444                                         tface = (MTFace *)me->fdata.layers[i].data;
445
446                                         for (a = 0; a < me->totface; a++, tface++) {
447                                                 if (tface->tpage == ima) {
448                                                         if (me->id.lib) is_lib = true;
449                                                         else is_local = true;
450                                                 }
451                                         }
452                                 }
453                         }
454                 }
455
456                 if (me->mtpoly) {
457                         MTexPoly *mtpoly;
458                         int a, i;
459
460                         for (i = 0; i < me->pdata.totlayer; i++) {
461                                 if (me->pdata.layers[i].type == CD_MTEXPOLY) {
462                                         mtpoly = (MTexPoly *)me->pdata.layers[i].data;
463
464                                         for (a = 0; a < me->totpoly; a++, mtpoly++) {
465                                                 if (mtpoly->tpage == ima) {
466                                                         if (me->id.lib) is_lib = true;
467                                                         else is_local = true;
468                                                 }
469                                         }
470                                 }
471                         }
472                 }
473
474         }
475
476         if (is_local && is_lib == false) {
477                 id_clear_lib_data(bmain, &ima->id);
478                 extern_local_image(ima);
479         }
480         else if (is_local && is_lib) {
481                 Image *ima_new = BKE_image_copy(bmain, ima);
482
483                 ima_new->id.us = 0;
484
485                 /* Remap paths of new ID using old library as base. */
486                 BKE_id_lib_local_paths(bmain, ima->id.lib, &ima_new->id);
487
488                 tex = bmain->tex.first;
489                 while (tex) {
490                         if (tex->id.lib == NULL) {
491                                 if (tex->ima == ima) {
492                                         tex->ima = ima_new;
493                                         ima_new->id.us++;
494                                         ima->id.us--;
495                                 }
496                         }
497                         tex = tex->id.next;
498                 }
499                 brush = bmain->brush.first;
500                 while (brush) {
501                         if (brush->id.lib == NULL) {
502                                 if (brush->clone.image == ima) {
503                                         brush->clone.image = ima_new;
504                                         ima_new->id.us++;
505                                         ima->id.us--;
506                                 }
507                         }
508                         brush = brush->id.next;
509                 }
510                 /* Transfer references in texfaces. Texfaces don't add to image ID
511                  * user count *unless* there are no other users. See
512                  * readfile.c:lib_link_mtface. */
513                 me = bmain->mesh.first;
514                 while (me) {
515                         if (me->mtface) {
516                                 MTFace *tface;
517                                 int a, i;
518
519                                 for (i = 0; i < me->fdata.totlayer; i++) {
520                                         if (me->fdata.layers[i].type == CD_MTFACE) {
521                                                 tface = (MTFace *)me->fdata.layers[i].data;
522
523                                                 for (a = 0; a < me->totface; a++, tface++) {
524                                                         if (tface->tpage == ima) {
525                                                                 tface->tpage = ima_new;
526                                                                 if (ima_new->id.us == 0) {
527                                                                         tface->tpage->id.us = 1;
528                                                                 }
529                                                                 id_lib_extern((ID *)ima_new);
530                                                         }
531                                                 }
532                                         }
533                                 }
534                         }
535
536                         if (me->mtpoly) {
537                                 MTexPoly *mtpoly;
538                                 int a, i;
539
540                                 for (i = 0; i < me->pdata.totlayer; i++) {
541                                         if (me->pdata.layers[i].type == CD_MTEXPOLY) {
542                                                 mtpoly = (MTexPoly *)me->pdata.layers[i].data;
543
544                                                 for (a = 0; a < me->totpoly; a++, mtpoly++) {
545                                                         if (mtpoly->tpage == ima) {
546                                                                 mtpoly->tpage = ima_new;
547                                                                 if (ima_new->id.us == 0) {
548                                                                         mtpoly->tpage->id.us = 1;
549                                                                 }
550                                                                 id_lib_extern((ID *)ima_new);
551                                                         }
552                                                 }
553                                         }
554                                 }
555                         }
556
557                         me = me->id.next;
558                 }
559         }
560 }
561
562 void BKE_image_merge(Image *dest, Image *source)
563 {
564         /* sanity check */
565         if (dest && source && dest != source) {
566                 BLI_spin_lock(&image_spin);
567                 if (source->cache != NULL) {
568                         struct MovieCacheIter *iter;
569                         iter = IMB_moviecacheIter_new(source->cache);
570                         while (!IMB_moviecacheIter_done(iter)) {
571                                 ImBuf *ibuf = IMB_moviecacheIter_getImBuf(iter);
572                                 ImageCacheKey *key = IMB_moviecacheIter_getUserKey(iter);
573                                 imagecache_put(dest, key->index, ibuf);
574                                 IMB_moviecacheIter_step(iter);
575                         }
576                         IMB_moviecacheIter_free(iter);
577                 }
578                 BLI_spin_unlock(&image_spin);
579
580                 BKE_libblock_free(G.main, source);
581         }
582 }
583
584 /* note, we could be clever and scale all imbuf's but since some are mipmaps its not so simple */
585 bool BKE_image_scale(Image *image, int width, int height)
586 {
587         ImBuf *ibuf;
588         void *lock;
589
590         ibuf = BKE_image_acquire_ibuf(image, NULL, &lock);
591
592         if (ibuf) {
593                 IMB_scaleImBuf(ibuf, width, height);
594                 ibuf->userflags |= IB_BITMAPDIRTY;
595         }
596
597         BKE_image_release_ibuf(image, ibuf, lock);
598
599         return (ibuf != NULL);
600 }
601
602 static void image_init_color_management(Image *ima)
603 {
604         ImBuf *ibuf;
605         char name[FILE_MAX];
606
607         BKE_image_user_file_path(NULL, ima, name);
608
609         /* will set input color space to image format default's */
610         ibuf = IMB_loadiffname(name, IB_test | IB_alphamode_detect, ima->colorspace_settings.name);
611
612         if (ibuf) {
613                 if (ibuf->flags & IB_alphamode_premul)
614                         ima->alpha_mode = IMA_ALPHA_PREMUL;
615                 else
616                         ima->alpha_mode = IMA_ALPHA_STRAIGHT;
617
618                 IMB_freeImBuf(ibuf);
619         }
620 }
621
622 char BKE_image_alpha_mode_from_extension_ex(const char *filepath)
623 {
624         if (BLI_testextensie_n(filepath, ".exr", ".cin", ".dpx", ".hdr", NULL)) {
625                 return IMA_ALPHA_PREMUL;
626         }
627         else {
628                 return IMA_ALPHA_STRAIGHT;
629         }
630 }
631
632 void BKE_image_alpha_mode_from_extension(Image *image)
633 {
634         image->alpha_mode = BKE_image_alpha_mode_from_extension_ex(image->name);
635 }
636
637 Image *BKE_image_load(Main *bmain, const char *filepath)
638 {
639         Image *ima;
640         int file, len;
641         const char *libname;
642         char str[FILE_MAX];
643
644         BLI_strncpy(str, filepath, sizeof(str));
645         BLI_path_abs(str, bmain->name);
646
647         /* exists? */
648         file = BLI_open(str, O_BINARY | O_RDONLY, 0);
649         if (file == -1)
650                 return NULL;
651         close(file);
652
653         /* create a short library name */
654         len = strlen(filepath);
655
656         while (len > 0 && filepath[len - 1] != '/' && filepath[len - 1] != '\\') len--;
657         libname = filepath + len;
658
659         ima = image_alloc(bmain, libname, IMA_SRC_FILE, IMA_TYPE_IMAGE);
660         BLI_strncpy(ima->name, filepath, sizeof(ima->name));
661
662         if (BLI_testextensie_array(filepath, imb_ext_movie))
663                 ima->source = IMA_SRC_MOVIE;
664
665         image_init_color_management(ima);
666
667         return ima;
668 }
669
670 /* checks if image was already loaded, then returns same image */
671 /* otherwise creates new. */
672 /* does not load ibuf itself */
673 /* pass on optional frame for #name images */
674 Image *BKE_image_load_exists_ex(const char *filepath, bool *r_exists)
675 {
676         Image *ima;
677         char str[FILE_MAX], strtest[FILE_MAX];
678
679         BLI_strncpy(str, filepath, sizeof(str));
680         BLI_path_abs(str, G.main->name);
681
682         /* first search an identical image */
683         for (ima = G.main->image.first; ima; ima = ima->id.next) {
684                 if (ima->source != IMA_SRC_VIEWER && ima->source != IMA_SRC_GENERATED) {
685                         BLI_strncpy(strtest, ima->name, sizeof(ima->name));
686                         BLI_path_abs(strtest, ID_BLEND_PATH(G.main, &ima->id));
687
688                         if (BLI_path_cmp(strtest, str) == 0) {
689                                 if (ima->anim == NULL || ima->id.us == 0) {
690                                         BLI_strncpy(ima->name, filepath, sizeof(ima->name));    /* for stringcode */
691                                         ima->id.us++;                                       /* officially should not, it doesn't link here! */
692                                         if (ima->ok == 0)
693                                                 ima->ok = IMA_OK;
694                                         if (r_exists)
695                                                 *r_exists = true;
696                                         return ima;
697                                 }
698                         }
699                 }
700         }
701
702         if (r_exists)
703                 *r_exists = false;
704         return BKE_image_load(G.main, filepath);
705 }
706
707 Image *BKE_image_load_exists(const char *filepath)
708 {
709         return BKE_image_load_exists_ex(filepath, NULL);
710 }
711
712 static ImBuf *add_ibuf_size(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short gen_type,
713                             const float color[4], ColorManagedColorspaceSettings *colorspace_settings)
714 {
715         ImBuf *ibuf;
716         unsigned char *rect = NULL;
717         float *rect_float = NULL;
718
719         if (floatbuf) {
720                 ibuf = IMB_allocImBuf(width, height, depth, IB_rectfloat);
721
722                 if (colorspace_settings->name[0] == '\0') {
723                         const char *colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_FLOAT);
724
725                         BLI_strncpy(colorspace_settings->name, colorspace, sizeof(colorspace_settings->name));
726                 }
727
728                 if (ibuf != NULL) {
729                         rect_float = ibuf->rect_float;
730                         IMB_colormanagement_check_is_data(ibuf, colorspace_settings->name);
731                 }
732         }
733         else {
734                 ibuf = IMB_allocImBuf(width, height, depth, IB_rect);
735
736                 if (colorspace_settings->name[0] == '\0') {
737                         const char *colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_BYTE);
738
739                         BLI_strncpy(colorspace_settings->name, colorspace, sizeof(colorspace_settings->name));
740                 }
741
742                 if (ibuf != NULL) {
743                         rect = (unsigned char *)ibuf->rect;
744                         IMB_colormanagement_assign_rect_colorspace(ibuf, colorspace_settings->name);
745                 }
746         }
747
748         if (!ibuf) {
749                 return NULL;
750         }
751
752         BLI_strncpy(ibuf->name, name, sizeof(ibuf->name));
753         ibuf->userflags |= IB_BITMAPDIRTY;
754
755         switch (gen_type) {
756                 case IMA_GENTYPE_GRID:
757                         BKE_image_buf_fill_checker(rect, rect_float, width, height);
758                         break;
759                 case IMA_GENTYPE_GRID_COLOR:
760                         BKE_image_buf_fill_checker_color(rect, rect_float, width, height);
761                         break;
762                 default:
763                         BKE_image_buf_fill_color(rect, rect_float, width, height, color);
764                         break;
765         }
766
767         if (rect_float) {
768                 /* both byte and float buffers are filling in sRGB space, need to linearize float buffer after BKE_image_buf_fill* functions */
769
770                 IMB_buffer_float_from_float(rect_float, rect_float, ibuf->channels, IB_PROFILE_LINEAR_RGB, IB_PROFILE_SRGB,
771                                             true, ibuf->x, ibuf->y, ibuf->x, ibuf->x);
772         }
773
774         return ibuf;
775 }
776
777 /* adds new image block, creates ImBuf and initializes color */
778 Image *BKE_image_add_generated(Main *bmain, unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short gen_type, const float color[4])
779 {
780         /* on save, type is changed to FILE in editsima.c */
781         Image *ima = image_alloc(bmain, name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
782
783         if (ima) {
784                 ImBuf *ibuf;
785
786                 /* BLI_strncpy(ima->name, name, FILE_MAX); */ /* don't do this, this writes in ain invalid filepath! */
787                 ima->gen_x = width;
788                 ima->gen_y = height;
789                 ima->gen_type = gen_type;
790                 ima->gen_flag |= (floatbuf ? IMA_GEN_FLOAT : 0);
791                 ima->gen_depth = depth;
792                 copy_v4_v4(ima->gen_color, color);
793
794                 ibuf = add_ibuf_size(width, height, ima->name, depth, floatbuf, gen_type, color, &ima->colorspace_settings);
795                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
796
797                 /* image_assign_ibuf puts buffer to the cache, which increments user counter. */
798                 IMB_freeImBuf(ibuf);
799
800                 ima->ok = IMA_OK_LOADED;
801         }
802
803         return ima;
804 }
805
806 /* creates an image image owns the imbuf passed */
807 Image *BKE_image_add_from_imbuf(ImBuf *ibuf)
808 {
809         /* on save, type is changed to FILE in editsima.c */
810         Image *ima;
811
812         ima = image_alloc(G.main, BLI_path_basename(ibuf->name), IMA_SRC_FILE, IMA_TYPE_IMAGE);
813
814         if (ima) {
815                 BLI_strncpy(ima->name, ibuf->name, FILE_MAX);
816                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
817                 ima->ok = IMA_OK_LOADED;
818         }
819
820         return ima;
821 }
822
823 /* packs rect from memory as PNG */
824 void BKE_image_memorypack(Image *ima)
825 {
826         ImBuf *ibuf = image_get_cached_ibuf_for_index_frame(ima, IMA_NO_INDEX, 0);
827
828         if (ibuf == NULL)
829                 return;
830         if (ima->packedfile) {
831                 freePackedFile(ima->packedfile);
832                 ima->packedfile = NULL;
833         }
834
835         ibuf->ftype = PNG;
836         ibuf->planes = R_IMF_PLANES_RGBA;
837
838         IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem);
839         if (ibuf->encodedbuffer == NULL) {
840                 printf("memory save for pack error\n");
841         }
842         else {
843                 PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
844
845                 pf->data = ibuf->encodedbuffer;
846                 pf->size = ibuf->encodedsize;
847                 ima->packedfile = pf;
848                 ibuf->encodedbuffer = NULL;
849                 ibuf->encodedsize = 0;
850                 ibuf->userflags &= ~IB_BITMAPDIRTY;
851
852                 if (ima->source == IMA_SRC_GENERATED) {
853                         ima->source = IMA_SRC_FILE;
854                         ima->type = IMA_TYPE_IMAGE;
855                 }
856         }
857
858         IMB_freeImBuf(ibuf);
859 }
860
861 void BKE_image_tag_time(Image *ima)
862 {
863         ima->lastused = PIL_check_seconds_timer_i();
864 }
865
866 #if 0
867 static void tag_all_images_time()
868 {
869         Image *ima;
870         int ctime = PIL_check_seconds_timer_i();
871
872         ima = G.main->image.first;
873         while (ima) {
874                 if (ima->bindcode || ima->repbind || ima->ibufs.first) {
875                         ima->lastused = ctime;
876                 }
877         }
878 }
879 #endif
880
881 static uintptr_t image_mem_size(Image *image)
882 {
883         uintptr_t size = 0;
884
885         /* viewers have memory depending on other rules, has no valid rect pointer */
886         if (image->source == IMA_SRC_VIEWER)
887                 return 0;
888
889         BLI_spin_lock(&image_spin);
890         if (image->cache != NULL) {
891                 struct MovieCacheIter *iter = IMB_moviecacheIter_new(image->cache);
892
893                 while (!IMB_moviecacheIter_done(iter)) {
894                         ImBuf *ibuf = IMB_moviecacheIter_getImBuf(iter);
895                         ImBuf *ibufm;
896                         int level;
897
898                         if (ibuf->rect) {
899                                 size += MEM_allocN_len(ibuf->rect);
900                         }
901                         if (ibuf->rect_float) {
902                                 size += MEM_allocN_len(ibuf->rect_float);
903                         }
904
905                         for (level = 0; level < IB_MIPMAP_LEVELS; level++) {
906                                 ibufm = ibuf->mipmap[level];
907                                 if (ibufm) {
908                                         if (ibufm->rect) {
909                                                 size += MEM_allocN_len(ibufm->rect);
910                                         }
911                                         if (ibufm->rect_float) {
912                                                 size += MEM_allocN_len(ibufm->rect_float);
913                                         }
914                                 }
915                         }
916
917                         IMB_moviecacheIter_step(iter);
918                 }
919                 IMB_moviecacheIter_free(iter);
920         }
921         BLI_spin_unlock(&image_spin);
922
923         return size;
924 }
925
926 void BKE_image_print_memlist(void)
927 {
928         Image *ima;
929         uintptr_t size, totsize = 0;
930
931         for (ima = G.main->image.first; ima; ima = ima->id.next)
932                 totsize += image_mem_size(ima);
933
934         printf("\ntotal image memory len: %.3f MB\n", (double)totsize / (double)(1024 * 1024));
935
936         for (ima = G.main->image.first; ima; ima = ima->id.next) {
937                 size = image_mem_size(ima);
938
939                 if (size)
940                         printf("%s len: %.3f MB\n", ima->id.name + 2, (double)size / (double)(1024 * 1024));
941         }
942 }
943
944 static bool imagecache_check_dirty(ImBuf *ibuf, void *UNUSED(userkey), void *UNUSED(userdata))
945 {
946         return (ibuf->userflags & IB_BITMAPDIRTY) == 0;
947 }
948
949 void BKE_image_free_all_textures(void)
950 {
951 #undef CHECK_FREED_SIZE
952
953         Tex *tex;
954         Image *ima;
955 #ifdef CHECK_FREED_SIZE
956         uintptr_t tot_freed_size = 0;
957 #endif
958
959         for (ima = G.main->image.first; ima; ima = ima->id.next)
960                 ima->id.flag &= ~LIB_DOIT;
961
962         for (tex = G.main->tex.first; tex; tex = tex->id.next)
963                 if (tex->ima)
964                         tex->ima->id.flag |= LIB_DOIT;
965
966         for (ima = G.main->image.first; ima; ima = ima->id.next) {
967                 if (ima->cache && (ima->id.flag & LIB_DOIT)) {
968 #ifdef CHECK_FREED_SIZE
969                         uintptr_t old_size = image_mem_size(ima);
970 #endif
971
972                         IMB_moviecache_cleanup(ima->cache, imagecache_check_dirty, NULL);
973
974 #ifdef CHECK_FREED_SIZE
975                         tot_freed_size += old_size - image_mem_size(ima);
976 #endif
977                 }
978         }
979 #ifdef CHECK_FREED_SIZE
980         printf("%s: freed total %lu MB\n", __func__, tot_freed_size / (1024 * 1024));
981 #endif
982 }
983
984 static bool imagecache_check_free_anim(ImBuf *ibuf, void *UNUSED(userkey), void *userdata)
985 {
986         int except_frame = *(int *)userdata;
987         return (ibuf->userflags & IB_BITMAPDIRTY) == 0 &&
988                (ibuf->index != IMA_NO_INDEX) &&
989                (except_frame != IMA_INDEX_FRAME(ibuf->index));
990 }
991
992 /* except_frame is weak, only works for seqs without offset... */
993 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
994 {
995         BLI_spin_lock(&image_spin);
996         if (ima->cache != NULL) {
997                 IMB_moviecache_cleanup(ima->cache, imagecache_check_free_anim, &except_frame);
998         }
999         BLI_spin_unlock(&image_spin);
1000 }
1001
1002 void BKE_image_all_free_anim_ibufs(int cfra)
1003 {
1004         Image *ima;
1005
1006         for (ima = G.main->image.first; ima; ima = ima->id.next)
1007                 if (BKE_image_is_animated(ima))
1008                         BKE_image_free_anim_ibufs(ima, cfra);
1009 }
1010
1011
1012 /* *********** READ AND WRITE ************** */
1013
1014 int BKE_image_imtype_to_ftype(const char imtype)
1015 {
1016         if (imtype == R_IMF_IMTYPE_TARGA)
1017                 return TGA;
1018         else if (imtype == R_IMF_IMTYPE_RAWTGA)
1019                 return RAWTGA;
1020         else if (imtype == R_IMF_IMTYPE_IRIS)
1021                 return IMAGIC;
1022 #ifdef WITH_HDR
1023         else if (imtype == R_IMF_IMTYPE_RADHDR)
1024                 return RADHDR;
1025 #endif
1026         else if (imtype == R_IMF_IMTYPE_PNG)
1027                 return PNG | 15;
1028 #ifdef WITH_DDS
1029         else if (imtype == R_IMF_IMTYPE_DDS)
1030                 return DDS;
1031 #endif
1032         else if (imtype == R_IMF_IMTYPE_BMP)
1033                 return BMP;
1034 #ifdef WITH_TIFF
1035         else if (imtype == R_IMF_IMTYPE_TIFF)
1036                 return TIF;
1037 #endif
1038         else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER)
1039                 return OPENEXR;
1040 #ifdef WITH_CINEON
1041         else if (imtype == R_IMF_IMTYPE_CINEON)
1042                 return CINEON;
1043         else if (imtype == R_IMF_IMTYPE_DPX)
1044                 return DPX;
1045 #endif
1046 #ifdef WITH_OPENJPEG
1047         else if (imtype == R_IMF_IMTYPE_JP2)
1048                 return JP2;
1049 #endif
1050         else
1051                 return JPG | 90;
1052 }
1053
1054 char BKE_image_ftype_to_imtype(const int ftype)
1055 {
1056         if (ftype == 0)
1057                 return R_IMF_IMTYPE_TARGA;
1058         else if (ftype == IMAGIC)
1059                 return R_IMF_IMTYPE_IRIS;
1060 #ifdef WITH_HDR
1061         else if (ftype & RADHDR)
1062                 return R_IMF_IMTYPE_RADHDR;
1063 #endif
1064         else if (ftype & PNG)
1065                 return R_IMF_IMTYPE_PNG;
1066 #ifdef WITH_DDS
1067         else if (ftype & DDS)
1068                 return R_IMF_IMTYPE_DDS;
1069 #endif
1070         else if (ftype & BMP)
1071                 return R_IMF_IMTYPE_BMP;
1072 #ifdef WITH_TIFF
1073         else if (ftype & TIF)
1074                 return R_IMF_IMTYPE_TIFF;
1075 #endif
1076         else if (ftype & OPENEXR)
1077                 return R_IMF_IMTYPE_OPENEXR;
1078 #ifdef WITH_CINEON
1079         else if (ftype & CINEON)
1080                 return R_IMF_IMTYPE_CINEON;
1081         else if (ftype & DPX)
1082                 return R_IMF_IMTYPE_DPX;
1083 #endif
1084         else if (ftype & TGA)
1085                 return R_IMF_IMTYPE_TARGA;
1086         else if (ftype & RAWTGA)
1087                 return R_IMF_IMTYPE_RAWTGA;
1088 #ifdef WITH_OPENJPEG
1089         else if (ftype & JP2)
1090                 return R_IMF_IMTYPE_JP2;
1091 #endif
1092         else
1093                 return R_IMF_IMTYPE_JPEG90;
1094 }
1095
1096
1097 bool BKE_imtype_is_movie(const char imtype)
1098 {
1099         switch (imtype) {
1100                 case R_IMF_IMTYPE_AVIRAW:
1101                 case R_IMF_IMTYPE_AVIJPEG:
1102                 case R_IMF_IMTYPE_QUICKTIME:
1103                 case R_IMF_IMTYPE_FFMPEG:
1104                 case R_IMF_IMTYPE_H264:
1105                 case R_IMF_IMTYPE_THEORA:
1106                 case R_IMF_IMTYPE_XVID:
1107                 case R_IMF_IMTYPE_FRAMESERVER:
1108                         return true;
1109         }
1110         return false;
1111 }
1112
1113 int BKE_imtype_supports_zbuf(const char imtype)
1114 {
1115         switch (imtype) {
1116                 case R_IMF_IMTYPE_IRIZ:
1117                 case R_IMF_IMTYPE_OPENEXR: /* but not R_IMF_IMTYPE_MULTILAYER */
1118                         return 1;
1119         }
1120         return 0;
1121 }
1122
1123 int BKE_imtype_supports_compress(const char imtype)
1124 {
1125         switch (imtype) {
1126                 case R_IMF_IMTYPE_PNG:
1127                         return 1;
1128         }
1129         return 0;
1130 }
1131
1132 int BKE_imtype_supports_quality(const char imtype)
1133 {
1134         switch (imtype) {
1135                 case R_IMF_IMTYPE_JPEG90:
1136                 case R_IMF_IMTYPE_JP2:
1137                 case R_IMF_IMTYPE_AVIJPEG:
1138                         return 1;
1139         }
1140         return 0;
1141 }
1142
1143 int BKE_imtype_requires_linear_float(const char imtype)
1144 {
1145         switch (imtype) {
1146                 case R_IMF_IMTYPE_CINEON:
1147                 case R_IMF_IMTYPE_DPX:
1148                 case R_IMF_IMTYPE_RADHDR:
1149                 case R_IMF_IMTYPE_OPENEXR:
1150                 case R_IMF_IMTYPE_MULTILAYER:
1151                         return true;
1152         }
1153         return 0;
1154 }
1155
1156 char BKE_imtype_valid_channels(const char imtype, bool write_file)
1157 {
1158         char chan_flag = IMA_CHAN_FLAG_RGB; /* assume all support rgb */
1159
1160         /* alpha */
1161         switch (imtype) {
1162                 case R_IMF_IMTYPE_BMP:
1163                         if (write_file) break;
1164                         /* fall-through */
1165                 case R_IMF_IMTYPE_TARGA:
1166                 case R_IMF_IMTYPE_IRIS:
1167                 case R_IMF_IMTYPE_PNG:
1168                 case R_IMF_IMTYPE_RADHDR:
1169                 case R_IMF_IMTYPE_TIFF:
1170                 case R_IMF_IMTYPE_OPENEXR:
1171                 case R_IMF_IMTYPE_MULTILAYER:
1172                 case R_IMF_IMTYPE_DDS:
1173                 case R_IMF_IMTYPE_JP2:
1174                 case R_IMF_IMTYPE_QUICKTIME:
1175                 case R_IMF_IMTYPE_DPX:
1176                         chan_flag |= IMA_CHAN_FLAG_ALPHA;
1177                         break;
1178         }
1179
1180         /* bw */
1181         switch (imtype) {
1182                 case R_IMF_IMTYPE_PNG:
1183                 case R_IMF_IMTYPE_JPEG90:
1184                 case R_IMF_IMTYPE_TARGA:
1185                 case R_IMF_IMTYPE_RAWTGA:
1186                 case R_IMF_IMTYPE_TIFF:
1187                 case R_IMF_IMTYPE_IRIS:
1188                         chan_flag |= IMA_CHAN_FLAG_BW;
1189                         break;
1190         }
1191
1192         return chan_flag;
1193 }
1194
1195 char BKE_imtype_valid_depths(const char imtype)
1196 {
1197         switch (imtype) {
1198                 case R_IMF_IMTYPE_RADHDR:
1199                         return R_IMF_CHAN_DEPTH_32;
1200                 case R_IMF_IMTYPE_TIFF:
1201                         return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_16;
1202                 case R_IMF_IMTYPE_OPENEXR:
1203                         return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32;
1204                 case R_IMF_IMTYPE_MULTILAYER:
1205                         return R_IMF_CHAN_DEPTH_32;
1206                 /* eeh, cineon does some strange 10bits per channel */
1207                 case R_IMF_IMTYPE_DPX:
1208                         return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_10 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
1209                 case R_IMF_IMTYPE_CINEON:
1210                         return R_IMF_CHAN_DEPTH_10;
1211                 case R_IMF_IMTYPE_JP2:
1212                         return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
1213                 case R_IMF_IMTYPE_PNG:
1214                         return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_16;
1215                 /* most formats are 8bit only */
1216                 default:
1217                         return R_IMF_CHAN_DEPTH_8;
1218         }
1219 }
1220
1221
1222 /* string is from command line --render-format arg, keep in sync with
1223  * creator.c help info */
1224 char BKE_imtype_from_arg(const char *imtype_arg)
1225 {
1226         if      (STREQ(imtype_arg, "TGA")) return R_IMF_IMTYPE_TARGA;
1227         else if (STREQ(imtype_arg, "IRIS")) return R_IMF_IMTYPE_IRIS;
1228 #ifdef WITH_DDS
1229         else if (STREQ(imtype_arg, "DDS")) return R_IMF_IMTYPE_DDS;
1230 #endif
1231         else if (STREQ(imtype_arg, "JPEG")) return R_IMF_IMTYPE_JPEG90;
1232         else if (STREQ(imtype_arg, "IRIZ")) return R_IMF_IMTYPE_IRIZ;
1233         else if (STREQ(imtype_arg, "RAWTGA")) return R_IMF_IMTYPE_RAWTGA;
1234         else if (STREQ(imtype_arg, "AVIRAW")) return R_IMF_IMTYPE_AVIRAW;
1235         else if (STREQ(imtype_arg, "AVIJPEG")) return R_IMF_IMTYPE_AVIJPEG;
1236         else if (STREQ(imtype_arg, "PNG")) return R_IMF_IMTYPE_PNG;
1237         else if (STREQ(imtype_arg, "QUICKTIME")) return R_IMF_IMTYPE_QUICKTIME;
1238         else if (STREQ(imtype_arg, "BMP")) return R_IMF_IMTYPE_BMP;
1239 #ifdef WITH_HDR
1240         else if (STREQ(imtype_arg, "HDR")) return R_IMF_IMTYPE_RADHDR;
1241 #endif
1242 #ifdef WITH_TIFF
1243         else if (STREQ(imtype_arg, "TIFF")) return R_IMF_IMTYPE_TIFF;
1244 #endif
1245 #ifdef WITH_OPENEXR
1246         else if (STREQ(imtype_arg, "EXR")) return R_IMF_IMTYPE_OPENEXR;
1247         else if (STREQ(imtype_arg, "MULTILAYER")) return R_IMF_IMTYPE_MULTILAYER;
1248 #endif
1249         else if (STREQ(imtype_arg, "MPEG")) return R_IMF_IMTYPE_FFMPEG;
1250         else if (STREQ(imtype_arg, "FRAMESERVER")) return R_IMF_IMTYPE_FRAMESERVER;
1251 #ifdef WITH_CINEON
1252         else if (STREQ(imtype_arg, "CINEON")) return R_IMF_IMTYPE_CINEON;
1253         else if (STREQ(imtype_arg, "DPX")) return R_IMF_IMTYPE_DPX;
1254 #endif
1255 #ifdef WITH_OPENJPEG
1256         else if (STREQ(imtype_arg, "JP2")) return R_IMF_IMTYPE_JP2;
1257 #endif
1258         else return R_IMF_IMTYPE_INVALID;
1259 }
1260
1261 static bool image_path_ensure_ext(char *string, const char imtype, const ImageFormatData *im_format)
1262 {
1263         const char *extension = NULL;
1264         const char *extension_test;
1265         (void)im_format;  /* may be unused, depends on build options */
1266
1267         if (imtype == R_IMF_IMTYPE_IRIS) {
1268                 if (!BLI_testextensie(string, extension_test = ".rgb"))
1269                         extension = extension_test;
1270         }
1271         else if (imtype == R_IMF_IMTYPE_IRIZ) {
1272                 if (!BLI_testextensie(string, extension_test = ".rgb"))
1273                         extension = extension_test;
1274         }
1275 #ifdef WITH_HDR
1276         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1277                 if (!BLI_testextensie(string, extension_test = ".hdr"))
1278                         extension = extension_test;
1279         }
1280 #endif
1281         else if (ELEM(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1282                 if (!BLI_testextensie(string, extension_test = ".png"))
1283                         extension = extension_test;
1284         }
1285 #ifdef WITH_DDS
1286         else if (imtype == R_IMF_IMTYPE_DDS) {
1287                 if (!BLI_testextensie(string, extension_test = ".dds"))
1288                         extension = extension_test;
1289         }
1290 #endif
1291         else if (ELEM(imtype, R_IMF_IMTYPE_TARGA, R_IMF_IMTYPE_RAWTGA)) {
1292                 if (!BLI_testextensie(string, extension_test = ".tga"))
1293                         extension = extension_test;
1294         }
1295         else if (imtype == R_IMF_IMTYPE_BMP) {
1296                 if (!BLI_testextensie(string, extension_test = ".bmp"))
1297                         extension = extension_test;
1298         }
1299 #ifdef WITH_TIFF
1300         else if (imtype == R_IMF_IMTYPE_TIFF) {
1301                 if (!BLI_testextensie_n(string, extension_test = ".tif", ".tiff", NULL)) {
1302                         extension = extension_test;
1303                 }
1304         }
1305 #endif
1306 #ifdef WITH_OPENIMAGEIO
1307         else if (imtype == R_IMF_IMTYPE_PSD) {
1308                 if (!BLI_testextensie(string, extension_test = ".psd"))
1309                         extension = extension_test;
1310         }
1311 #endif
1312 #ifdef WITH_OPENEXR
1313         else if (ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
1314                 if (!BLI_testextensie(string, extension_test = ".exr"))
1315                         extension = extension_test;
1316         }
1317 #endif
1318 #ifdef WITH_CINEON
1319         else if (imtype == R_IMF_IMTYPE_CINEON) {
1320                 if (!BLI_testextensie(string, extension_test = ".cin"))
1321                         extension = extension_test;
1322         }
1323         else if (imtype == R_IMF_IMTYPE_DPX) {
1324                 if (!BLI_testextensie(string, extension_test = ".dpx"))
1325                         extension = extension_test;
1326         }
1327 #endif
1328 #ifdef WITH_OPENJPEG
1329         else if (imtype == R_IMF_IMTYPE_JP2) {
1330                 if (im_format) {
1331                         if (im_format->jp2_codec == R_IMF_JP2_CODEC_JP2) {
1332                                 if (!BLI_testextensie(string, extension_test = ".jp2"))
1333                                         extension = extension_test;
1334                         }
1335                         else if (im_format->jp2_codec == R_IMF_JP2_CODEC_J2K) {
1336                                 if (!BLI_testextensie(string, extension_test = ".j2c"))
1337                                         extension = extension_test;
1338                         }
1339                         else
1340                                 BLI_assert(!"Unsupported jp2 codec was specified in im_format->jp2_codec");
1341                 }
1342                 else {
1343                         if (!BLI_testextensie(string, extension_test = ".jp2"))
1344                                 extension = extension_test;
1345                 }
1346         }
1347 #endif
1348         else { //   R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90, R_IMF_IMTYPE_QUICKTIME etc
1349                 if (!(BLI_testextensie_n(string, extension_test = ".jpg", ".jpeg", NULL)))
1350                         extension = extension_test;
1351         }
1352
1353         if (extension) {
1354                 /* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */
1355                 /* remove any other known image extension */
1356                 if (BLI_testextensie_array(string, imb_ext_image) ||
1357                     (G.have_quicktime && BLI_testextensie_array(string, imb_ext_image_qt)))
1358                 {
1359                         return BLI_replace_extension(string, FILE_MAX, extension);
1360                 }
1361                 else {
1362                         return BLI_ensure_extension(string, FILE_MAX, extension);
1363                 }
1364
1365         }
1366         else {
1367                 return false;
1368         }
1369 }
1370
1371 bool BKE_image_path_ensure_ext_from_imformat(char *string, const ImageFormatData *im_format)
1372 {
1373         return image_path_ensure_ext(string, im_format->imtype, im_format);
1374 }
1375
1376 bool BKE_image_path_ensure_ext_from_imtype(char *string, const char imtype)
1377 {
1378         return image_path_ensure_ext(string, imtype, NULL);
1379 }
1380
1381 void BKE_imformat_defaults(ImageFormatData *im_format)
1382 {
1383         memset(im_format, 0, sizeof(*im_format));
1384         im_format->planes = R_IMF_PLANES_RGBA;
1385         im_format->imtype = R_IMF_IMTYPE_PNG;
1386         im_format->depth = R_IMF_CHAN_DEPTH_8;
1387         im_format->quality = 90;
1388         im_format->compress = 15;
1389
1390         BKE_color_managed_display_settings_init(&im_format->display_settings);
1391         BKE_color_managed_view_settings_init(&im_format->view_settings);
1392 }
1393
1394 void BKE_imbuf_to_image_format(struct ImageFormatData *im_format, const ImBuf *imbuf)
1395 {
1396         int ftype        = imbuf->ftype & ~IB_CUSTOM_FLAGS_MASK;
1397         int custom_flags = imbuf->ftype & IB_CUSTOM_FLAGS_MASK;
1398
1399         BKE_imformat_defaults(im_format);
1400
1401         /* file type */
1402
1403         if (ftype == IMAGIC)
1404                 im_format->imtype = R_IMF_IMTYPE_IRIS;
1405
1406 #ifdef WITH_HDR
1407         else if (ftype == RADHDR)
1408                 im_format->imtype = R_IMF_IMTYPE_RADHDR;
1409 #endif
1410
1411         else if (ftype == PNG) {
1412                 im_format->imtype = R_IMF_IMTYPE_PNG;
1413
1414                 if (custom_flags & PNG_16BIT)
1415                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1416         }
1417
1418 #ifdef WITH_DDS
1419         else if (ftype == DDS)
1420                 im_format->imtype = R_IMF_IMTYPE_DDS;
1421 #endif
1422
1423         else if (ftype == BMP)
1424                 im_format->imtype = R_IMF_IMTYPE_BMP;
1425
1426 #ifdef WITH_TIFF
1427         else if (ftype == TIF) {
1428                 im_format->imtype = R_IMF_IMTYPE_TIFF;
1429                 if (custom_flags & TIF_16BIT)
1430                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1431         }
1432 #endif
1433
1434 #ifdef WITH_OPENEXR
1435         else if (ftype == OPENEXR) {
1436                 im_format->imtype = R_IMF_IMTYPE_OPENEXR;
1437                 if (custom_flags & OPENEXR_HALF)
1438                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1439                 if (custom_flags & OPENEXR_COMPRESS)
1440                         im_format->exr_codec = R_IMF_EXR_CODEC_ZIP;  // Can't determine compression
1441                 if (imbuf->zbuf_float)
1442                         im_format->flag |= R_IMF_FLAG_ZBUF;
1443         }
1444 #endif
1445
1446 #ifdef WITH_CINEON
1447         else if (ftype == CINEON)
1448                 im_format->imtype = R_IMF_IMTYPE_CINEON;
1449         else if (ftype == DPX)
1450                 im_format->imtype = R_IMF_IMTYPE_DPX;
1451 #endif
1452
1453         else if (ftype == TGA) {
1454                 im_format->imtype = R_IMF_IMTYPE_TARGA;
1455         }
1456         else if (ftype == RAWTGA) {
1457                 im_format->imtype = R_IMF_IMTYPE_RAWTGA;
1458         }
1459
1460 #ifdef WITH_OPENJPEG
1461         else if (ftype & JP2) {
1462                 im_format->imtype = R_IMF_IMTYPE_JP2;
1463                 im_format->quality = custom_flags & ~JPG_MSK;
1464
1465                 if (ftype & JP2_16BIT)
1466                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1467                 else if (ftype & JP2_12BIT)
1468                         im_format->depth = R_IMF_CHAN_DEPTH_12;
1469
1470                 if (ftype & JP2_YCC)
1471                         im_format->jp2_flag |= R_IMF_JP2_FLAG_YCC;
1472
1473                 if (ftype & JP2_CINE) {
1474                         im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_PRESET;
1475                         if (ftype & JP2_CINE_48FPS)
1476                                 im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_48;
1477                 }
1478
1479                 if (ftype & JP2_JP2)
1480                         im_format->jp2_codec = R_IMF_JP2_CODEC_JP2;
1481                 else if (ftype & JP2_J2K)
1482                         im_format->jp2_codec = R_IMF_JP2_CODEC_J2K;
1483                 else
1484                         BLI_assert(!"Unsupported jp2 codec was specified in file type");
1485         }
1486 #endif
1487
1488         else {
1489                 im_format->imtype = R_IMF_IMTYPE_JPEG90;
1490                 im_format->quality = custom_flags & ~JPG_MSK;
1491         }
1492
1493         /* planes */
1494         /* TODO(sergey): Channels doesn't correspond actual planes used for image buffer
1495          *               For example byte buffer will have 4 channels but it might easily
1496          *               be BW or RGB image.
1497          *
1498          *               Need to use im_format->planes = imbuf->planes instead?
1499          */
1500         switch (imbuf->channels) {
1501                 case 0:
1502                 case 4: im_format->planes = R_IMF_PLANES_RGBA;
1503                         break;
1504                 case 3: im_format->planes = R_IMF_PLANES_RGB;
1505                         break;
1506                 case 1: im_format->planes = R_IMF_PLANES_BW;
1507                         break;
1508                 default: im_format->planes = R_IMF_PLANES_RGB;
1509                         break;
1510         }
1511
1512 }
1513
1514
1515 #define STAMP_NAME_SIZE ((MAX_ID_NAME - 2) + 16)
1516 /* could allow access externally - 512 is for long names,
1517  * STAMP_NAME_SIZE is for id names, allowing them some room for description */
1518 typedef struct StampData {
1519         char file[512];
1520         char note[512];
1521         char date[512];
1522         char marker[512];
1523         char time[512];
1524         char frame[512];
1525         char camera[STAMP_NAME_SIZE];
1526         char cameralens[STAMP_NAME_SIZE];
1527         char scene[STAMP_NAME_SIZE];
1528         char strip[STAMP_NAME_SIZE];
1529         char rendertime[STAMP_NAME_SIZE];
1530 } StampData;
1531 #undef STAMP_NAME_SIZE
1532
1533 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix)
1534 {
1535         char text[256];
1536         struct tm *tl;
1537         time_t t;
1538
1539         if (scene->r.stamp & R_STAMP_FILENAME) {
1540                 BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), do_prefix ? "File %s" : "%s", G.relbase_valid ? G.main->name : "<untitled>");
1541         }
1542         else {
1543                 stamp_data->file[0] = '\0';
1544         }
1545
1546         if (scene->r.stamp & R_STAMP_NOTE) {
1547                 /* Never do prefix for Note */
1548                 BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", scene->r.stamp_udata);
1549         }
1550         else {
1551                 stamp_data->note[0] = '\0';
1552         }
1553
1554         if (scene->r.stamp & R_STAMP_DATE) {
1555                 t = time(NULL);
1556                 tl = localtime(&t);
1557                 BLI_snprintf(text, sizeof(text), "%04d/%02d/%02d %02d:%02d:%02d", tl->tm_year + 1900, tl->tm_mon + 1, tl->tm_mday, tl->tm_hour, tl->tm_min, tl->tm_sec);
1558                 BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), do_prefix ? "Date %s" : "%s", text);
1559         }
1560         else {
1561                 stamp_data->date[0] = '\0';
1562         }
1563
1564         if (scene->r.stamp & R_STAMP_MARKER) {
1565                 const char *name = BKE_scene_find_last_marker_name(scene, CFRA);
1566
1567                 if (name) BLI_strncpy(text, name, sizeof(text));
1568                 else BLI_strncpy(text, "<none>", sizeof(text));
1569
1570                 BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), do_prefix ? "Marker %s" : "%s", text);
1571         }
1572         else {
1573                 stamp_data->marker[0] = '\0';
1574         }
1575
1576         if (scene->r.stamp & R_STAMP_TIME) {
1577                 const short timecode_style = USER_TIMECODE_SMPTE_FULL;
1578                 BLI_timecode_string_from_time(text, sizeof(text), 0, FRA2TIME(scene->r.cfra), FPS, timecode_style);
1579                 BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), do_prefix ? "Timecode %s" : "%s", text);
1580         }
1581         else {
1582                 stamp_data->time[0] = '\0';
1583         }
1584
1585         if (scene->r.stamp & R_STAMP_FRAME) {
1586                 char fmtstr[32];
1587                 int digits = 1;
1588
1589                 if (scene->r.efra > 9)
1590                         digits = 1 + (int) log10(scene->r.efra);
1591
1592                 BLI_snprintf(fmtstr, sizeof(fmtstr), do_prefix ? "Frame %%0%di" : "%%0%di", digits);
1593                 BLI_snprintf(stamp_data->frame, sizeof(stamp_data->frame), fmtstr, scene->r.cfra);
1594         }
1595         else {
1596                 stamp_data->frame[0] = '\0';
1597         }
1598
1599         if (scene->r.stamp & R_STAMP_CAMERA) {
1600                 BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), do_prefix ? "Camera %s" : "%s", camera ? camera->id.name + 2 : "<none>");
1601         }
1602         else {
1603                 stamp_data->camera[0] = '\0';
1604         }
1605
1606         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1607                 if (camera && camera->type == OB_CAMERA) {
1608                         BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)camera->data)->lens);
1609                 }
1610                 else {
1611                         BLI_strncpy(text, "<none>", sizeof(text));
1612                 }
1613
1614                 BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), do_prefix ? "Lens %s" : "%s", text);
1615         }
1616         else {
1617                 stamp_data->cameralens[0] = '\0';
1618         }
1619
1620         if (scene->r.stamp & R_STAMP_SCENE) {
1621                 BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), do_prefix ? "Scene %s" : "%s", scene->id.name + 2);
1622         }
1623         else {
1624                 stamp_data->scene[0] = '\0';
1625         }
1626
1627         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1628                 Sequence *seq = BKE_sequencer_foreground_frame_get(scene, scene->r.cfra);
1629
1630                 if (seq) BLI_strncpy(text, seq->name + 2, sizeof(text));
1631                 else BLI_strncpy(text, "<none>", sizeof(text));
1632
1633                 BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), do_prefix ? "Strip %s" : "%s", text);
1634         }
1635         else {
1636                 stamp_data->strip[0] = '\0';
1637         }
1638
1639         {
1640                 Render *re = RE_GetRender(scene->id.name);
1641                 RenderStats *stats = re ? RE_GetStats(re) : NULL;
1642
1643                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1644                         BLI_timestr(stats->lastframetime, text, sizeof(text));
1645
1646                         BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), do_prefix ? "RenderTime %s" : "%s", text);
1647                 }
1648                 else {
1649                         stamp_data->rendertime[0] = '\0';
1650                 }
1651         }
1652 }
1653
1654 void BKE_image_stamp_buf(
1655         Scene *scene, Object *camera,
1656         unsigned char *rect, float *rectf, int width, int height, int channels)
1657 {
1658         struct StampData stamp_data;
1659         float w, h, pad;
1660         int x, y, y_ofs;
1661         float h_fixed;
1662         const int mono = blf_mono_font_render; // XXX
1663         struct ColorManagedDisplay *display;
1664         const char *display_device;
1665
1666         /* this could be an argument if we want to operate on non linear float imbuf's
1667          * for now though this is only used for renders which use scene settings */
1668
1669 #define TEXT_SIZE_CHECK(str, w, h) \
1670         ((str[0]) && ((void)(h = h_fixed), (w = BLF_width(mono, str, sizeof(str)))))
1671
1672 #define BUFF_MARGIN_X 2
1673 #define BUFF_MARGIN_Y 1
1674
1675         if (!rect && !rectf)
1676                 return;
1677
1678         display_device = scene->display_settings.display_device;
1679         display = IMB_colormanagement_display_get_named(display_device);
1680
1681         stampdata(scene, camera, &stamp_data, 1);
1682
1683         /* TODO, do_versions */
1684         if (scene->r.stamp_font_id < 8)
1685                 scene->r.stamp_font_id = 12;
1686
1687         /* set before return */
1688         BLF_size(mono, scene->r.stamp_font_id, 72);
1689
1690         BLF_buffer(mono, rectf, rect, width, height, channels, display);
1691         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1692         pad = BLF_width_max(mono);
1693
1694         /* use 'h_fixed' rather than 'h', aligns better */
1695         h_fixed = BLF_height_max(mono);
1696         y_ofs = -BLF_descender(mono);
1697
1698         x = 0;
1699         y = height;
1700
1701         if (TEXT_SIZE_CHECK(stamp_data.file, w, h)) {
1702                 /* Top left corner */
1703                 y -= h;
1704
1705                 /* also a little of space to the background. */
1706                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1707                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1708
1709                 /* and draw the text. */
1710                 BLF_position(mono, x, y + y_ofs, 0.0);
1711                 BLF_draw_buffer(mono, stamp_data.file);
1712
1713                 /* the extra pixel for background. */
1714                 y -= BUFF_MARGIN_Y * 2;
1715         }
1716
1717         /* Top left corner, below File */
1718         if (TEXT_SIZE_CHECK(stamp_data.note, w, h)) {
1719                 y -= h;
1720
1721                 /* and space for background. */
1722                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1723                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1724
1725                 BLF_position(mono, x, y + y_ofs, 0.0);
1726                 BLF_draw_buffer(mono, stamp_data.note);
1727
1728                 /* the extra pixel for background. */
1729                 y -= BUFF_MARGIN_Y * 2;
1730         }
1731
1732         /* Top left corner, below File (or Note) */
1733         if (TEXT_SIZE_CHECK(stamp_data.date, w, h)) {
1734                 y -= h;
1735
1736                 /* and space for background. */
1737                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1738                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1739
1740                 BLF_position(mono, x, y + y_ofs, 0.0);
1741                 BLF_draw_buffer(mono, stamp_data.date);
1742
1743                 /* the extra pixel for background. */
1744                 y -= BUFF_MARGIN_Y * 2;
1745         }
1746
1747         /* Top left corner, below File, Date or Note */
1748         if (TEXT_SIZE_CHECK(stamp_data.rendertime, w, h)) {
1749                 y -= h;
1750
1751                 /* and space for background. */
1752                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1753                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1754
1755                 BLF_position(mono, x, y + y_ofs, 0.0);
1756                 BLF_draw_buffer(mono, stamp_data.rendertime);
1757         }
1758
1759         x = 0;
1760         y = 0;
1761
1762         /* Bottom left corner, leaving space for timing */
1763         if (TEXT_SIZE_CHECK(stamp_data.marker, w, h)) {
1764
1765                 /* extra space for background. */
1766                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp,  display,
1767                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1768
1769                 /* and pad the text. */
1770                 BLF_position(mono, x, y + y_ofs, 0.0);
1771                 BLF_draw_buffer(mono, stamp_data.marker);
1772
1773                 /* space width. */
1774                 x += w + pad;
1775         }
1776
1777         /* Left bottom corner */
1778         if (TEXT_SIZE_CHECK(stamp_data.time, w, h)) {
1779
1780                 /* extra space for background */
1781                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1782                                   x - BUFF_MARGIN_X, y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1783
1784                 /* and pad the text. */
1785                 BLF_position(mono, x, y + y_ofs, 0.0);
1786                 BLF_draw_buffer(mono, stamp_data.time);
1787
1788                 /* space width. */
1789                 x += w + pad;
1790         }
1791
1792         if (TEXT_SIZE_CHECK(stamp_data.frame, w, h)) {
1793
1794                 /* extra space for background. */
1795                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1796                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1797
1798                 /* and pad the text. */
1799                 BLF_position(mono, x, y + y_ofs, 0.0);
1800                 BLF_draw_buffer(mono, stamp_data.frame);
1801
1802                 /* space width. */
1803                 x += w + pad;
1804         }
1805
1806         if (TEXT_SIZE_CHECK(stamp_data.camera, w, h)) {
1807
1808                 /* extra space for background. */
1809                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1810                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1811                 BLF_position(mono, x, y + y_ofs, 0.0);
1812                 BLF_draw_buffer(mono, stamp_data.camera);
1813
1814                 /* space width. */
1815                 x += w + pad;
1816         }
1817
1818         if (TEXT_SIZE_CHECK(stamp_data.cameralens, w, h)) {
1819
1820                 /* extra space for background. */
1821                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1822                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1823                 BLF_position(mono, x, y + y_ofs, 0.0);
1824                 BLF_draw_buffer(mono, stamp_data.cameralens);
1825         }
1826
1827         if (TEXT_SIZE_CHECK(stamp_data.scene, w, h)) {
1828
1829                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1830                 x = width - w - 2;
1831
1832                 /* extra space for background. */
1833                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1834                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1835
1836                 /* and pad the text. */
1837                 BLF_position(mono, x, y + y_ofs, 0.0);
1838                 BLF_draw_buffer(mono, stamp_data.scene);
1839         }
1840
1841         if (TEXT_SIZE_CHECK(stamp_data.strip, w, h)) {
1842
1843                 /* Top right corner, with an extra space because blenfont is too strict! */
1844                 x = width - w - pad;
1845                 y = height - h;
1846
1847                 /* extra space for background. */
1848                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1849                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1850
1851                 BLF_position(mono, x, y + y_ofs, 0.0);
1852                 BLF_draw_buffer(mono, stamp_data.strip);
1853         }
1854
1855         /* cleanup the buffer. */
1856         BLF_buffer(mono, NULL, NULL, 0, 0, 0, NULL);
1857
1858 #undef TEXT_SIZE_CHECK
1859 #undef BUFF_MARGIN_X
1860 #undef BUFF_MARGIN_Y
1861 }
1862
1863 void BKE_imbuf_stamp_info(Scene *scene, Object *camera, struct ImBuf *ibuf)
1864 {
1865         struct StampData stamp_data;
1866
1867         if (!ibuf) return;
1868
1869         /* fill all the data values, no prefix */
1870         stampdata(scene, camera, &stamp_data, 0);
1871
1872         if (stamp_data.file[0]) IMB_metadata_change_field(ibuf, "File",        stamp_data.file);
1873         if (stamp_data.note[0]) IMB_metadata_change_field(ibuf, "Note",        stamp_data.note);
1874         if (stamp_data.date[0]) IMB_metadata_change_field(ibuf, "Date",        stamp_data.date);
1875         if (stamp_data.marker[0]) IMB_metadata_change_field(ibuf, "Marker",    stamp_data.marker);
1876         if (stamp_data.time[0]) IMB_metadata_change_field(ibuf, "Time",        stamp_data.time);
1877         if (stamp_data.frame[0]) IMB_metadata_change_field(ibuf, "Frame",      stamp_data.frame);
1878         if (stamp_data.camera[0]) IMB_metadata_change_field(ibuf, "Camera",    stamp_data.camera);
1879         if (stamp_data.cameralens[0]) IMB_metadata_change_field(ibuf, "Lens",  stamp_data.cameralens);
1880         if (stamp_data.scene[0]) IMB_metadata_change_field(ibuf, "Scene",      stamp_data.scene);
1881         if (stamp_data.strip[0]) IMB_metadata_change_field(ibuf, "Strip",      stamp_data.strip);
1882         if (stamp_data.rendertime[0]) IMB_metadata_change_field(ibuf, "RenderTime", stamp_data.rendertime);
1883 }
1884
1885 bool BKE_imbuf_alpha_test(ImBuf *ibuf)
1886 {
1887         int tot;
1888         if (ibuf->rect_float) {
1889                 const float *buf = ibuf->rect_float;
1890                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1891                         if (buf[3] < 1.0f) {
1892                                 return true;
1893                         }
1894                 }
1895         }
1896         else if (ibuf->rect) {
1897                 unsigned char *buf = (unsigned char *)ibuf->rect;
1898                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1899                         if (buf[3] != 255) {
1900                                 return true;
1901                         }
1902                 }
1903         }
1904
1905         return false;
1906 }
1907
1908 /* note: imf->planes is ignored here, its assumed the image channels
1909  * are already set */
1910 int BKE_imbuf_write(ImBuf *ibuf, const char *name, ImageFormatData *imf)
1911 {
1912         char imtype = imf->imtype;
1913         char compress = imf->compress;
1914         char quality = imf->quality;
1915
1916         int ok;
1917
1918         if (imtype == R_IMF_IMTYPE_IRIS) {
1919                 ibuf->ftype = IMAGIC;
1920         }
1921 #ifdef WITH_HDR
1922         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1923                 ibuf->ftype = RADHDR;
1924         }
1925 #endif
1926         else if (ELEM(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1927                 ibuf->ftype = PNG;
1928
1929                 if (imtype == R_IMF_IMTYPE_PNG) {
1930                         if (imf->depth == R_IMF_CHAN_DEPTH_16)
1931                                 ibuf->ftype |= PNG_16BIT;
1932
1933                         ibuf->ftype |= compress;
1934                 }
1935
1936         }
1937 #ifdef WITH_DDS
1938         else if (imtype == R_IMF_IMTYPE_DDS) {
1939                 ibuf->ftype = DDS;
1940         }
1941 #endif
1942         else if (imtype == R_IMF_IMTYPE_BMP) {
1943                 ibuf->ftype = BMP;
1944         }
1945 #ifdef WITH_TIFF
1946         else if (imtype == R_IMF_IMTYPE_TIFF) {
1947                 ibuf->ftype = TIF;
1948
1949                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1950                         ibuf->ftype |= TIF_16BIT;
1951         }
1952 #endif
1953 #ifdef WITH_OPENEXR
1954         else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER) {
1955                 ibuf->ftype = OPENEXR;
1956                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1957                         ibuf->ftype |= OPENEXR_HALF;
1958                 ibuf->ftype |= (imf->exr_codec & OPENEXR_COMPRESS);
1959
1960                 if (!(imf->flag & R_IMF_FLAG_ZBUF))
1961                         ibuf->zbuf_float = NULL;    /* signal for exr saving */
1962
1963         }
1964 #endif
1965 #ifdef WITH_CINEON
1966         else if (imtype == R_IMF_IMTYPE_CINEON) {
1967                 ibuf->ftype = CINEON;
1968                 if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
1969                         ibuf->ftype |= CINEON_LOG;
1970                 }
1971                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1972                         ibuf->ftype |= CINEON_16BIT;
1973                 }
1974                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1975                         ibuf->ftype |= CINEON_12BIT;
1976                 }
1977                 else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
1978                         ibuf->ftype |= CINEON_10BIT;
1979                 }
1980         }
1981         else if (imtype == R_IMF_IMTYPE_DPX) {
1982                 ibuf->ftype = DPX;
1983                 if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
1984                         ibuf->ftype |= CINEON_LOG;
1985                 }
1986                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1987                         ibuf->ftype |= CINEON_16BIT;
1988                 }
1989                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1990                         ibuf->ftype |= CINEON_12BIT;
1991                 }
1992                 else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
1993                         ibuf->ftype |= CINEON_10BIT;
1994                 }
1995         }
1996 #endif
1997         else if (imtype == R_IMF_IMTYPE_TARGA) {
1998                 ibuf->ftype = TGA;
1999         }
2000         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
2001                 ibuf->ftype = RAWTGA;
2002         }
2003 #ifdef WITH_OPENJPEG
2004         else if (imtype == R_IMF_IMTYPE_JP2) {
2005                 if (quality < 10) quality = 90;
2006                 ibuf->ftype = JP2 | quality;
2007
2008                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2009                         ibuf->ftype |= JP2_16BIT;
2010                 }
2011                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
2012                         ibuf->ftype |= JP2_12BIT;
2013                 }
2014
2015                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
2016                         ibuf->ftype |= JP2_YCC;
2017                 }
2018
2019                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
2020                         ibuf->ftype |= JP2_CINE;
2021                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
2022                                 ibuf->ftype |= JP2_CINE_48FPS;
2023                 }
2024
2025                 if (imf->jp2_codec == R_IMF_JP2_CODEC_JP2)
2026                         ibuf->ftype |= JP2_JP2;
2027                 else if (imf->jp2_codec == R_IMF_JP2_CODEC_J2K)
2028                         ibuf->ftype |= JP2_J2K;
2029                 else
2030                         BLI_assert(!"Unsupported jp2 codec was specified in im_format->jp2_codec");
2031         }
2032 #endif
2033         else {
2034                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
2035                 if (quality < 10) quality = 90;
2036                 ibuf->ftype = JPG | quality;
2037         }
2038
2039         BLI_make_existing_file(name);
2040
2041         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
2042         if (ok == 0) {
2043                 perror(name);
2044         }
2045
2046         return(ok);
2047 }
2048
2049 /* same as BKE_imbuf_write() but crappy workaround not to permanently modify
2050  * _some_, values in the imbuf */
2051 int BKE_imbuf_write_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
2052                        const bool save_copy)
2053 {
2054         ImBuf ibuf_back = *ibuf;
2055         int ok;
2056
2057         /* all data is rgba anyway,
2058          * this just controls how to save for some formats */
2059         ibuf->planes = imf->planes;
2060
2061         ok = BKE_imbuf_write(ibuf, name, imf);
2062
2063         if (save_copy) {
2064                 /* note that we are not restoring _all_ settings */
2065                 ibuf->planes = ibuf_back.planes;
2066                 ibuf->ftype =  ibuf_back.ftype;
2067         }
2068
2069         return ok;
2070 }
2071
2072 int BKE_imbuf_write_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, struct ImageFormatData *imf)
2073 {
2074         if (scene && scene->r.stamp & R_STAMP_ALL)
2075                 BKE_imbuf_stamp_info(scene, camera, ibuf);
2076
2077         return BKE_imbuf_write(ibuf, name, imf);
2078 }
2079
2080
2081 static void image_path_makepicstring(
2082         char *string, const char *base, const char *relbase, int frame, const char imtype,
2083         const ImageFormatData *im_format, const short use_ext, const short use_frames)
2084 {
2085         if (string == NULL) return;
2086         BLI_strncpy(string, base, FILE_MAX - 10);   /* weak assumption */
2087         BLI_path_abs(string, relbase);
2088
2089         if (use_frames)
2090                 BLI_path_frame(string, frame, 4);
2091
2092         if (use_ext)
2093                 image_path_ensure_ext(string, imtype, im_format);
2094 }
2095
2096 void BKE_image_path_from_imformat(
2097         char *string, const char *base, const char *relbase, int frame,
2098         const ImageFormatData *im_format, const bool use_ext, const bool use_frames)
2099 {
2100         image_path_makepicstring(string, base, relbase, frame, im_format->imtype, im_format, use_ext, use_frames);
2101 }
2102
2103 void BKE_image_path_from_imtype(
2104         char *string, const char *base, const char *relbase, int frame,
2105         const char imtype, const bool use_ext, const bool use_frames)
2106 {
2107         image_path_makepicstring(string, base, relbase, frame, imtype, NULL, use_ext, use_frames);
2108 }
2109
2110 struct anim *openanim_noload(const char *name, int flags, int streamindex, char colorspace[IMA_MAX_SPACE])
2111 {
2112         struct anim *anim;
2113
2114         anim = IMB_open_anim(name, flags, streamindex, colorspace);
2115         return anim;
2116 }
2117
2118 /* used by sequencer too */
2119 struct anim *openanim(const char *name, int flags, int streamindex, char colorspace[IMA_MAX_SPACE])
2120 {
2121         struct anim *anim;
2122         struct ImBuf *ibuf;
2123
2124         anim = IMB_open_anim(name, flags, streamindex, colorspace);
2125         if (anim == NULL) return NULL;
2126
2127         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
2128         if (ibuf == NULL) {
2129                 if (BLI_exists(name))
2130                         printf("not an anim: %s\n", name);
2131                 else
2132                         printf("anim file doesn't exist: %s\n", name);
2133                 IMB_free_anim(anim);
2134                 return NULL;
2135         }
2136         IMB_freeImBuf(ibuf);
2137
2138         return(anim);
2139 }
2140
2141 /* ************************* New Image API *************** */
2142
2143
2144 /* Notes about Image storage
2145  * - packedfile
2146  *   -> written in .blend
2147  * - filename
2148  *   -> written in .blend
2149  * - movie
2150  *   -> comes from packedfile or filename
2151  * - renderresult
2152  *   -> comes from packedfile or filename
2153  * - listbase
2154  *   -> ibufs from exrhandle
2155  * - flipbook array
2156  *   -> ibufs come from movie, temporary renderresult or sequence
2157  * - ibuf
2158  *   -> comes from packedfile or filename or generated
2159  */
2160
2161
2162 /* forces existence of 1 Image for renderout or nodes, returns Image */
2163 /* name is only for default, when making new one */
2164 Image *BKE_image_verify_viewer(int type, const char *name)
2165 {
2166         Image *ima;
2167
2168         for (ima = G.main->image.first; ima; ima = ima->id.next)
2169                 if (ima->source == IMA_SRC_VIEWER)
2170                         if (ima->type == type)
2171                                 break;
2172
2173         if (ima == NULL)
2174                 ima = image_alloc(G.main, name, IMA_SRC_VIEWER, type);
2175
2176         /* happens on reload, imagewindow cannot be image user when hidden*/
2177         if (ima->id.us == 0)
2178                 id_us_plus(&ima->id);
2179
2180         return ima;
2181 }
2182
2183 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
2184 {
2185         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2186 }
2187
2188 void BKE_image_walk_all_users(const Main *mainp, void *customdata,
2189                               void callback(Image *ima, ImageUser *iuser, void *customdata))
2190 {
2191         wmWindowManager *wm;
2192         wmWindow *win;
2193         Tex *tex;
2194
2195         /* texture users */
2196         for (tex = mainp->tex.first; tex; tex = tex->id.next) {
2197                 if (tex->type == TEX_IMAGE && tex->ima) {
2198                         callback(tex->ima, &tex->iuser, customdata);
2199                 }
2200         }
2201
2202         /* image window, compo node users */
2203         for (wm = mainp->wm.first; wm; wm = wm->id.next) { /* only 1 wm */
2204                 for (win = wm->windows.first; win; win = win->next) {
2205                         ScrArea *sa;
2206                         for (sa = win->screen->areabase.first; sa; sa = sa->next) {
2207                                 if (sa->spacetype == SPACE_VIEW3D) {
2208                                         View3D *v3d = sa->spacedata.first;
2209                                         BGpic *bgpic;
2210                                         for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
2211                                                 callback(bgpic->ima, &bgpic->iuser, customdata);
2212                                         }
2213                                 }
2214                                 else if (sa->spacetype == SPACE_IMAGE) {
2215                                         SpaceImage *sima = sa->spacedata.first;
2216                                         callback(sima->image, &sima->iuser, customdata);
2217                                 }
2218                                 else if (sa->spacetype == SPACE_NODE) {
2219                                         SpaceNode *snode = sa->spacedata.first;
2220                                         if (snode->nodetree && snode->nodetree->type == NTREE_COMPOSIT) {
2221                                                 bNode *node;
2222                                                 for (node = snode->nodetree->nodes.first; node; node = node->next) {
2223                                                         if (node->id && node->type == CMP_NODE_IMAGE) {
2224                                                                 Image *ima = (Image *)node->id;
2225                                                                 ImageUser *iuser = node->storage;
2226                                                                 callback(ima, iuser, customdata);
2227                                                         }
2228                                                 }
2229                                         }
2230                                 }
2231                         }
2232                 }
2233         }
2234 }
2235
2236 static void image_tag_frame_recalc(Image *ima, ImageUser *iuser, void *customdata)
2237 {
2238         Image *changed_image = customdata;
2239
2240         if (ima == changed_image && BKE_image_is_animated(ima)) {
2241                 iuser->flag |= IMA_NEED_FRAME_RECALC;
2242         }
2243 }
2244
2245 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
2246 {
2247         if (ima == NULL)
2248                 return;
2249
2250         BLI_spin_lock(&image_spin);
2251
2252         switch (signal) {
2253                 case IMA_SIGNAL_FREE:
2254                         BKE_image_free_buffers(ima);
2255                         if (iuser)
2256                                 iuser->ok = 1;
2257                         break;
2258                 case IMA_SIGNAL_SRC_CHANGE:
2259                         if (ima->type == IMA_TYPE_UV_TEST)
2260                                 if (ima->source != IMA_SRC_GENERATED)
2261                                         ima->type = IMA_TYPE_IMAGE;
2262
2263                         if (ima->source == IMA_SRC_GENERATED) {
2264                                 if (ima->gen_x == 0 || ima->gen_y == 0) {
2265                                         ImBuf *ibuf = image_get_cached_ibuf_for_index_frame(ima, IMA_NO_INDEX, 0);
2266                                         if (ibuf) {
2267                                                 ima->gen_x = ibuf->x;
2268                                                 ima->gen_y = ibuf->y;
2269                                                 IMB_freeImBuf(ibuf);
2270                                         }
2271                                 }
2272
2273                                 /* Changing source type to generated will likely change file format
2274                                  * used by generated image buffer. Saving different file format to
2275                                  * the old name might confuse other applications.
2276                                  *
2277                                  * Here we ensure original image path wouldn't be used when saving
2278                                  * generated image.
2279                                  */
2280                                 ima->name[0] = '\0';
2281                         }
2282
2283 #if 0
2284                         /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
2285                         if (ima->type != IMA_TYPE_MULTILAYER)
2286                                 BKE_image_free_buffers(ima);
2287 #else
2288                         /* image buffers for non-sequence multilayer will share buffers with RenderResult,
2289                          * however sequence multilayer will own buffers. Such logic makes switching from
2290                          * single multilayer file to sequence completely unstable
2291                          * since changes in nodes seems this workaround isn't needed anymore, all sockets
2292                          * are nicely detecting anyway, but freeing buffers always here makes multilayer
2293                          * sequences behave stable
2294                          */
2295                         BKE_image_free_buffers(ima);
2296 #endif
2297
2298                         ima->ok = 1;
2299                         if (iuser)
2300                                 iuser->ok = 1;
2301
2302                         BKE_image_walk_all_users(G.main, ima, image_tag_frame_recalc);
2303
2304                         break;
2305
2306                 case IMA_SIGNAL_RELOAD:
2307                         /* try to repack file */
2308                         if (ima->packedfile) {
2309                                 PackedFile *pf;
2310                                 pf = newPackedFile(NULL, ima->name, ID_BLEND_PATH(G.main, &ima->id));
2311                                 if (pf) {
2312                                         freePackedFile(ima->packedfile);
2313                                         ima->packedfile = pf;
2314                                         BKE_image_free_buffers(ima);
2315                                 }
2316                                 else {
2317                                         printf("ERROR: Image not available. Keeping packed image\n");
2318                                 }
2319                         }
2320                         else
2321                                 BKE_image_free_buffers(ima);
2322
2323                         if (iuser)
2324                                 iuser->ok = 1;
2325
2326                         break;
2327                 case IMA_SIGNAL_USER_NEW_IMAGE:
2328                         if (iuser) {
2329                                 iuser->ok = 1;
2330                                 if (ima->source == IMA_SRC_FILE || ima->source == IMA_SRC_SEQUENCE) {
2331                                         if (ima->type == IMA_TYPE_MULTILAYER) {
2332                                                 iuser->multi_index = 0;
2333                                                 iuser->layer = iuser->pass = 0;
2334                                         }
2335                                 }
2336                         }
2337                         break;
2338                 case IMA_SIGNAL_COLORMANAGE:
2339                         BKE_image_free_buffers(ima);
2340
2341                         ima->ok = 1;
2342
2343                         if (iuser)
2344                                 iuser->ok = 1;
2345
2346                         break;
2347         }
2348
2349         BLI_spin_unlock(&image_spin);
2350
2351         /* don't use notifiers because they are not 100% sure to succeeded
2352          * this also makes sure all scenes are accounted for. */
2353         {
2354                 Scene *scene;
2355                 for (scene = G.main->scene.first; scene; scene = scene->id.next) {
2356                         if (scene->nodetree) {
2357                                 nodeUpdateID(scene->nodetree, &ima->id);
2358                         }
2359                 }
2360         }
2361 }
2362
2363 /* if layer or pass changes, we need an index for the imbufs list */
2364 /* note it is called for rendered results, but it doesnt use the index! */
2365 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
2366 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
2367 {
2368         RenderLayer *rl;
2369         RenderPass *rpass = NULL;
2370
2371         if (rr == NULL)
2372                 return NULL;
2373
2374         if (iuser) {
2375                 short index = 0, rl_index = 0, rp_index;
2376
2377                 for (rl = rr->layers.first; rl; rl = rl->next, rl_index++) {
2378                         rp_index = 0;
2379                         for (rpass = rl->passes.first; rpass; rpass = rpass->next, index++, rp_index++)
2380                                 if (iuser->layer == rl_index && iuser->pass == rp_index)
2381                                         break;
2382                         if (rpass)
2383                                 break;
2384                 }
2385
2386                 if (rpass)
2387                         iuser->multi_index = index;
2388                 else
2389                         iuser->multi_index = 0;
2390         }
2391         if (rpass == NULL) {
2392                 rl = rr->layers.first;
2393                 if (rl)
2394                         rpass = rl->passes.first;
2395         }
2396
2397         return rpass;
2398 }
2399
2400 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
2401 {
2402         if (ima->rr) {
2403                 return ima->rr;
2404         }
2405         else if (ima->type == IMA_TYPE_R_RESULT) {
2406                 if (ima->render_slot == ima->last_render_slot)
2407                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
2408                 else
2409                         return ima->renders[ima->render_slot];
2410         }
2411         else
2412                 return NULL;
2413 }
2414
2415 void BKE_image_release_renderresult(Scene *scene, Image *ima)
2416 {
2417         if (ima->rr) {
2418                 /* pass */
2419         }
2420         else if (ima->type == IMA_TYPE_R_RESULT) {
2421                 if (ima->render_slot == ima->last_render_slot)
2422                         RE_ReleaseResult(RE_GetRender(scene->id.name));
2423         }
2424 }
2425
2426 void BKE_image_backup_render(Scene *scene, Image *ima)
2427 {
2428         /* called right before rendering, ima->renders contains render
2429          * result pointers for everything but the current render */
2430         Render *re = RE_GetRender(scene->id.name);
2431         int slot = ima->render_slot, last = ima->last_render_slot;
2432
2433         if (slot != last) {
2434                 if (ima->renders[slot]) {
2435                         RE_FreeRenderResult(ima->renders[slot]);
2436                         ima->renders[slot] = NULL;
2437                 }
2438
2439                 ima->renders[last] = NULL;
2440                 RE_SwapResult(re, &ima->renders[last]);
2441         }
2442
2443         ima->last_render_slot = slot;
2444 }
2445
2446 /* after imbuf load, openexr type can return with a exrhandle open */
2447 /* in that case we have to build a render-result */
2448 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
2449 {
2450         const char *colorspace = ima->colorspace_settings.name;
2451         bool predivide = (ima->alpha_mode == IMA_ALPHA_PREMUL);
2452
2453         ima->rr = RE_MultilayerConvert(ibuf->userdata, colorspace, predivide, ibuf->x, ibuf->y);
2454
2455 #ifdef WITH_OPENEXR
2456         IMB_exr_close(ibuf->userdata);
2457 #endif
2458
2459         ibuf->userdata = NULL;
2460         if (ima->rr)
2461                 ima->rr->framenr = framenr;
2462 }
2463
2464 /* common stuff to do with images after loading */
2465 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
2466 {
2467         /* preview is NULL when it has never been used as an icon before */
2468         if (G.background == 0 && ima->preview == NULL)
2469                 BKE_icon_changed(BKE_icon_getid(&ima->id));
2470
2471         /* fields */
2472         if (ima->flag & IMA_FIELDS) {
2473                 if (ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
2474                 else de_interlace_ng(ibuf);
2475         }
2476         /* timer */
2477         BKE_image_tag_time(ima);
2478
2479         ima->ok = IMA_OK_LOADED;
2480
2481 }
2482
2483 static int imbuf_alpha_flags_for_image(Image *ima)
2484 {
2485         int flag = 0;
2486
2487         if (ima->flag & IMA_IGNORE_ALPHA)
2488                 flag |= IB_ignore_alpha;
2489         else if (ima->alpha_mode == IMA_ALPHA_PREMUL)
2490                 flag |= IB_alphamode_premul;
2491
2492         return flag;
2493 }
2494
2495 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
2496 {
2497         struct ImBuf *ibuf;
2498         char name[FILE_MAX];
2499         int flag;
2500
2501         /* XXX temp stuff? */
2502         if (ima->lastframe != frame)
2503                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2504
2505         ima->lastframe = frame;
2506         BKE_image_user_file_path(iuser, ima, name);
2507
2508         flag = IB_rect | IB_multilayer;
2509         flag |= imbuf_alpha_flags_for_image(ima);
2510
2511         /* read ibuf */
2512         ibuf = IMB_loadiffname(name, flag, ima->colorspace_settings.name);
2513
2514 #if 0
2515         if (ibuf) {
2516                 printf(AT " loaded %s\n", name);
2517         }
2518         else {
2519                 printf(AT " missed %s\n", name);
2520         }
2521 #endif
2522
2523         if (ibuf) {
2524 #ifdef WITH_OPENEXR
2525                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_acquire_ibuf */
2526                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2527                         image_create_multilayer(ima, ibuf, frame);
2528                         ima->type = IMA_TYPE_MULTILAYER;
2529                         IMB_freeImBuf(ibuf);
2530                         ibuf = NULL;
2531                 }
2532                 else {
2533                         image_initialize_after_load(ima, ibuf);
2534                         image_assign_ibuf(ima, ibuf, 0, frame);
2535                 }
2536 #else
2537                 image_initialize_after_load(ima, ibuf);
2538                 image_assign_ibuf(ima, ibuf, 0, frame);
2539 #endif
2540         }
2541         else
2542                 ima->ok = 0;
2543
2544         if (iuser)
2545                 iuser->ok = ima->ok;
2546
2547         return ibuf;
2548 }
2549
2550 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
2551 {
2552         struct ImBuf *ibuf = NULL;
2553
2554         /* either we load from RenderResult, or we have to load a new one */
2555
2556         /* check for new RenderResult */
2557         if (ima->rr == NULL || frame != ima->rr->framenr) {
2558                 if (ima->rr) {
2559                         /* Cached image buffers shares pointers with render result,
2560                          * need to ensure there's no image buffers are hanging around
2561                          * with dead links after freeing the render result.
2562                          */
2563                         image_free_cached_frames(ima);
2564                         RE_FreeRenderResult(ima->rr);
2565                         ima->rr = NULL;
2566                 }
2567
2568                 ibuf = image_load_sequence_file(ima, iuser, frame);
2569
2570                 if (ibuf) { /* actually an error */
2571                         ima->type = IMA_TYPE_IMAGE;
2572                         printf("error, multi is normal image\n");
2573                 }
2574         }
2575         if (ima->rr) {
2576                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2577
2578                 if (rpass) {
2579                         // printf("load from pass %s\n", rpass->name);
2580                         /* since we free  render results, we copy the rect */
2581                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2582                         ibuf->rect_float = MEM_dupallocN(rpass->rect);
2583                         ibuf->flags |= IB_rectfloat;
2584                         ibuf->mall = IB_rectfloat;
2585                         ibuf->channels = rpass->channels;
2586
2587                         image_initialize_after_load(ima, ibuf);
2588                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : 0, frame);
2589
2590                 }
2591                 // else printf("pass not found\n");
2592         }
2593         else
2594                 ima->ok = 0;
2595
2596         if (iuser)
2597                 iuser->ok = ima->ok;
2598
2599         return ibuf;
2600 }
2601
2602
2603 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
2604 {
2605         struct ImBuf *ibuf = NULL;
2606
2607         ima->lastframe = frame;
2608
2609         if (ima->anim == NULL) {
2610                 char str[FILE_MAX];
2611                 int flags = IB_rect;
2612                 if (ima->flag & IMA_DEINTERLACE) {
2613                         flags |= IB_animdeinterlace;
2614                 }
2615
2616                 BKE_image_user_file_path(iuser, ima, str);
2617
2618                 /* FIXME: make several stream accessible in image editor, too*/
2619                 ima->anim = openanim(str, flags, 0, ima->colorspace_settings.name);
2620
2621                 /* let's initialize this user */
2622                 if (ima->anim && iuser && iuser->frames == 0)
2623                         iuser->frames = IMB_anim_get_duration(ima->anim,
2624                                                               IMB_TC_RECORD_RUN);
2625         }
2626
2627         if (ima->anim) {
2628                 int dur = IMB_anim_get_duration(ima->anim,
2629                                                 IMB_TC_RECORD_RUN);
2630                 int fra = frame - 1;
2631
2632                 if (fra < 0) fra = 0;
2633                 if (fra > (dur - 1)) fra = dur - 1;
2634                 ibuf = IMB_makeSingleUser(
2635                     IMB_anim_absolute(ima->anim, fra,
2636                                       IMB_TC_RECORD_RUN,
2637                                       IMB_PROXY_NONE));
2638
2639                 if (ibuf) {
2640                         image_initialize_after_load(ima, ibuf);
2641                         image_assign_ibuf(ima, ibuf, 0, frame);
2642                 }
2643                 else
2644                         ima->ok = 0;
2645         }
2646         else
2647                 ima->ok = 0;
2648
2649         if (iuser)
2650                 iuser->ok = ima->ok;
2651
2652         return ibuf;
2653 }
2654
2655 /* warning, 'iuser' can be NULL */
2656 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
2657 {
2658         struct ImBuf *ibuf;
2659         char str[FILE_MAX];
2660         int assign = 0, flag;
2661
2662         /* always ensure clean ima */
2663         BKE_image_free_buffers(ima);
2664
2665         /* is there a PackedFile with this image ? */
2666         if (ima->packedfile) {
2667                 flag = IB_rect | IB_multilayer;
2668                 flag |= imbuf_alpha_flags_for_image(ima);
2669
2670                 ibuf = IMB_ibImageFromMemory((unsigned char *)ima->packedfile->data, ima->packedfile->size, flag,
2671                                              ima->colorspace_settings.name, "<packed data>");
2672         }
2673         else {
2674                 flag = IB_rect | IB_multilayer | IB_metadata;
2675                 flag |= imbuf_alpha_flags_for_image(ima);
2676
2677                 /* get the right string */
2678                 BKE_image_user_frame_calc(iuser, cfra, 0);
2679                 BKE_image_user_file_path(iuser, ima, str);
2680
2681                 /* read ibuf */
2682                 ibuf = IMB_loadiffname(str, flag, ima->colorspace_settings.name);
2683         }
2684
2685         if (ibuf) {
2686                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_acquire_ibuf */
2687                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2688                         image_create_multilayer(ima, ibuf, cfra);
2689                         ima->type = IMA_TYPE_MULTILAYER;
2690                         IMB_freeImBuf(ibuf);
2691                         ibuf = NULL;
2692                 }
2693                 else {
2694                         image_initialize_after_load(ima, ibuf);
2695                         assign = 1;
2696
2697                         /* check if the image is a font image... */
2698                         detectBitmapFont(ibuf);
2699
2700                         /* make packed file for autopack */
2701                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
2702                                 ima->packedfile = newPackedFile(NULL, str, ID_BLEND_PATH(G.main, &ima->id));
2703                 }
2704         }
2705         else
2706                 ima->ok = 0;
2707
2708         if (assign)
2709                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2710
2711         if (iuser)
2712                 iuser->ok = ima->ok;
2713
2714         return ibuf;
2715 }
2716
2717 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
2718 {
2719         ImBuf *ibuf = NULL;
2720
2721         if (ima->rr == NULL) {
2722                 ibuf = image_load_image_file(ima, iuser, 0);
2723                 if (ibuf) { /* actually an error */
2724                         ima->type = IMA_TYPE_IMAGE;
2725                         return ibuf;
2726                 }
2727         }
2728         if (ima->rr) {
2729                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2730
2731                 if (rpass) {
2732                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2733
2734                         image_initialize_after_load(ima, ibuf);
2735
2736                         ibuf->rect_float = rpass->rect;
2737                         ibuf->flags |= IB_rectfloat;
2738                         ibuf->channels = rpass->channels;
2739
2740                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2741                 }
2742         }
2743
2744         if (ibuf == NULL)
2745                 ima->ok = 0;
2746         if (iuser)
2747                 iuser->ok = ima->ok;
2748
2749         return ibuf;
2750 }
2751
2752
2753 /* showing RGBA result itself (from compo/sequence) or
2754  * like exr, using layers etc */
2755 /* always returns a single ibuf, also during render progress */
2756 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
2757 {
2758         Render *re;
2759         RenderResult rres;
2760         float *rectf, *rectz;
2761         unsigned int *rect;
2762         float dither;
2763         int channels, layer, pass;
2764         ImBuf *ibuf;
2765         int from_render = (ima->render_slot == ima->last_render_slot);
2766         bool byte_buffer_in_display_space = false;
2767
2768         if (!(iuser && iuser->scene))
2769                 return NULL;
2770
2771         /* if we the caller is not going to release the lock, don't give the image */
2772         if (!lock_r)
2773                 return NULL;
2774
2775         re = RE_GetRender(iuser->scene->id.name);
2776
2777         channels = 4;
2778         layer = iuser->layer;
2779         pass = iuser->pass;
2780
2781         if (from_render) {
2782                 RE_AcquireResultImage(re, &rres);
2783         }
2784         else if (ima->renders[ima->render_slot]) {
2785                 rres = *(ima->renders[ima->render_slot]);
2786                 rres.have_combined = rres.rectf != NULL;
2787         }
2788         else
2789                 memset(&rres, 0, sizeof(RenderResult));
2790
2791         if (!(rres.rectx > 0 && rres.recty > 0)) {
2792                 if (from_render)
2793                         RE_ReleaseResultImage(re);
2794                 return NULL;
2795         }
2796
2797         /* release is done in BKE_image_release_ibuf using lock_r */
2798         if (from_render) {
2799                 BLI_lock_thread(LOCK_VIEWER);
2800                 *lock_r = re;
2801         }
2802
2803         /* this gives active layer, composite or sequence result */
2804         rect = (unsigned int *)rres.rect32;
2805         rectf = rres.rectf;
2806         rectz = rres.rectz;
2807         dither = iuser->scene->r.dither_intensity;
2808
2809         /* combined layer gets added as first layer */
2810         if (rres.have_combined && layer == 0) {
2811                 /* pass */
2812         }
2813         else if (rect && layer == 0) {
2814                 /* rect32 is set when there's a Sequence pass, this pass seems
2815                  * to have layer=0 (this is from image_buttons.c)
2816                  * in this case we ignore float buffer, because it could have
2817                  * hung from previous pass which was float
2818                  */
2819                 rectf = NULL;
2820         }
2821         else if (rres.layers.first) {
2822                 RenderLayer *rl = BLI_findlink(&rres.layers, layer - (rres.have_combined ? 1 : 0));
2823                 if (rl) {
2824                         RenderPass *rpass;
2825
2826                         /* there's no combined pass, is in renderlayer itself */
2827                         if (pass == 0) {
2828                                 rectf = rl->rectf;
2829                                 if (rectf == NULL) {
2830                                         /* Happens when Save Buffers is enabled.
2831                                          * Use display buffer stored in the render layer.
2832                                          */
2833                                         rect = (unsigned int *) rl->display_buffer;
2834                                         byte_buffer_in_display_space = true;
2835                                 }
2836                         }
2837                         else {
2838                                 rpass = BLI_findlink(&rl->passes, pass - 1);
2839                                 if (rpass) {
2840                                         channels = rpass->channels;
2841                                         rectf = rpass->rect;
2842                                         dither = 0.0f; /* don't dither passes */
2843                                 }
2844                         }
2845
2846                         for (rpass = rl->passes.first; rpass; rpass = rpass->next)
2847                                 if (rpass->passtype == SCE_PASS_Z)
2848                                         rectz = rpass->rect;
2849                 }
2850         }
2851
2852         ibuf = image_get_cached_ibuf_for_index_frame(ima, IMA_NO_INDEX, 0);
2853
2854         /* make ibuf if needed, and initialize it */
2855         if (ibuf == NULL) {
2856                 ibuf = IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
2857                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2858         }
2859
2860         /* Set color space settings for a byte buffer.
2861          *
2862          * This is mainly to make it so color management treats byte buffer
2863          * from render result with Save Buffers enabled as final display buffer
2864          * and doesnt' apply any color management on it.
2865          *
2866          * For other cases we need to be sure it stays to default byte buffer space.
2867          */
2868         if (ibuf->rect != rect) {
2869                 if (byte_buffer_in_display_space) {
2870                         const char *colorspace =
2871                                 IMB_colormanagement_get_display_colorspace_name(&iuser->scene->view_settings,
2872                                                                             &iuser->scene->display_settings);
2873                         IMB_colormanagement_assign_rect_colorspace(ibuf, colorspace);
2874                 }
2875                 else {
2876                         const char *colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_BYTE);
2877                         IMB_colormanagement_assign_rect_colorspace(ibuf, colorspace);
2878                 }
2879         }
2880
2881         /* invalidate color managed buffers if render result changed */
2882         BLI_lock_thread(LOCK_COLORMANAGE);
2883         if (ibuf->x != rres.rectx || ibuf->y != rres.recty || ibuf->rect_float != rectf) {
2884                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
2885         }
2886
2887         ibuf->x = rres.rectx;
2888         ibuf->y = rres.recty;
2889
2890         if (rect) {
2891                 imb_freerectImBuf(ibuf);
2892                 ibuf->rect = rect;
2893         }
2894         else {
2895                 /* byte buffer of render result has been freed, make sure image buffers
2896                  * does not reference to this buffer anymore
2897                  * need check for whether byte buffer was allocated and owned by image itself
2898                  * or if it's reusing buffer from render result
2899                  */
2900                 if ((ibuf->mall & IB_rect) == 0)
2901                         ibuf->rect = NULL;
2902         }
2903
2904         if (rectf) {
2905                 ibuf->rect_float = rectf;
2906                 ibuf->flags |= IB_rectfloat;
2907                 ibuf->channels = channels;
2908         }
2909         else {
2910                 ibuf->rect_float = NULL;
2911                 ibuf->flags &= ~IB_rectfloat;
2912         }
2913
2914         if (rectz) {
2915                 ibuf->zbuf_float = rectz;
2916                 ibuf->flags |= IB_zbuffloat;
2917         }
2918         else {
2919                 ibuf->zbuf_float = NULL;
2920                 ibuf->flags &= ~IB_zbuffloat;
2921         }
2922
2923         BLI_unlock_thread(LOCK_COLORMANAGE);
2924
2925         ibuf->dither = dither;
2926
2927         ima->ok = IMA_OK_LOADED;
2928
2929         return ibuf;
2930 }
2931
2932 static void image_get_frame_and_index(Image *ima, ImageUser *iuser, int *r_frame, int *r_index)
2933 {
2934         int frame = 0, index = 0;
2935
2936         /* see if we already have an appropriate ibuf, with image source and type */
2937         if (ima->source == IMA_SRC_MOVIE) {
2938                 frame = iuser ? iuser->framenr : ima->lastframe;
2939         }
2940         else if (ima->source == IMA_SRC_SEQUENCE) {
2941                 if (ima->type == IMA_TYPE_IMAGE) {
2942                         frame = iuser ? iuser->framenr : ima->lastframe;
2943                 }
2944                 else if (ima->type == IMA_TYPE_MULTILAYER) {
2945                         frame = iuser ? iuser->framenr : ima->lastframe;
2946                         index = iuser ? iuser->multi_index : IMA_NO_INDEX;
2947                 }
2948         }
2949
2950         *r_frame = frame;
2951         *r_index = index;
2952 }
2953
2954 /* Get the ibuf from an image cache for a given image user.
2955  *
2956  * Returns referenced image buffer if it exists, callee is to
2957  * call IMB_freeImBuf to de-reference the image buffer after
2958  * it's done handling it.
2959  */
2960 static ImBuf *image_get_cached_ibuf(Image *ima, ImageUser *iuser, int *r_frame, int *r_index)
2961 {
2962         ImBuf *ibuf = NULL;
2963         int frame = 0, index = 0;
2964
2965         /* see if we already have an appropriate ibuf, with image source and type */
2966         if (ima->source == IMA_SRC_MOVIE) {
2967                 frame = iuser ? iuser->framenr : ima->lastframe;
2968                 ibuf = image_get_cached_ibuf_for_index_frame(ima, 0, frame);
2969                 /* XXX temp stuff? */
2970                 if (ima->lastframe != frame)
2971                         ima->tpageflag |= IMA_TPAGE_REFRESH;
2972                 ima->lastframe = frame;
2973         }
2974         else if (ima->source == IMA_SRC_SEQUENCE) {
2975                 if (ima->type == IMA_TYPE_IMAGE) {
2976                         frame = iuser ? iuser->framenr : ima->lastframe;
2977                         ibuf = image_get_cached_ibuf_for_index_frame(ima, 0, frame);
2978
2979                         /* XXX temp stuff? */
2980                         if (ima->lastframe != frame) {
2981                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2982                         }
2983                         ima->lastframe = frame;
2984                 }
2985                 else if (ima->type == IMA_TYPE_MULTILAYER) {
2986                         frame = iuser ? iuser->framenr : ima->lastframe;
2987                         index = iuser ? iuser->multi_index : IMA_NO_INDEX;
2988                         ibuf = image_get_cached_ibuf_for_index_frame(ima, index, frame);
2989                 }
2990         }
2991         else if (ima->source == IMA_SRC_FILE) {
2992                 if (ima->type == IMA_TYPE_IMAGE)
2993                         ibuf = image_get_cached_ibuf_for_index_frame(ima, IMA_NO_INDEX, 0);
2994                 else if (ima->type == IMA_TYPE_MULTILAYER)
2995                         ibuf = image_get_cached_ibuf_for_index_frame(ima, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2996         }
2997         else if (ima->source == IMA_SRC_GENERATED) {
2998                 ibuf = image_get_cached_ibuf_for_index_frame(ima, IMA_NO_INDEX, 0);
2999         }
3000         else if (ima->source == IMA_SRC_VIEWER) {
3001                 /* always verify entirely, not that this shouldn't happen
3002                  * as part of texture sampling in rendering anyway, so not
3003                  * a big bottleneck */
3004         }
3005
3006         if (r_frame)
3007                 *r_frame = frame;
3008
3009         if (r_index)
3010                 *r_index = index;
3011
3012         return ibuf;
3013 }
3014
3015 BLI_INLINE bool image_quick_test(Image *ima, ImageUser *iuser)
3016 {
3017         if (ima == NULL)
3018                 return false;
3019
3020         if (iuser) {
3021                 if (iuser->ok == 0)
3022                         return false;
3023         }
3024         else if (ima->ok == 0)
3025                 return false;
3026
3027         return true;
3028 }
3029
3030 /* Checks optional ImageUser and verifies/creates ImBuf.
3031  *
3032  * not thread-safe, so callee should worry about thread locks
3033  */
3034 static ImBuf *image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
3035 {
3036         ImBuf *ibuf = NULL;
3037         int frame = 0, index = 0;
3038
3039         if (lock_r)
3040                 *lock_r = NULL;
3041
3042         /* quick reject tests */
3043         if (!image_quick_test(ima, iuser))
3044                 return NULL;
3045
3046         ibuf = image_get_cached_ibuf(ima, iuser, &frame, &index);
3047
3048         if (ibuf == NULL) {
3049                 /* we are sure we have to load the ibuf, using source and type */
3050                 if (ima->source == IMA_SRC_MOVIE) {
3051                         /* source is from single file, use flipbook to store ibuf */
3052                         ibuf = image_load_movie_file(ima, iuser, frame);
3053                 }
3054                 else if (ima->source == IMA_SRC_SEQUENCE) {
3055                         if (ima->type == IMA_TYPE_IMAGE) {
3056                                 /* regular files, ibufs in flipbook, allows saving */
3057                                 ibuf = image_load_sequence_file(ima, iuser, frame);
3058                         }
3059                         /* no else; on load the ima type can change */
3060                         if (ima->type == IMA_TYPE_MULTILAYER) {
3061                                 /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
3062                                 ibuf = image_load_sequence_multilayer(ima, iuser, frame);
3063                         }
3064                 }
3065                 else if (ima->source == IMA_SRC_FILE) {
3066
3067                         if (ima->type == IMA_TYPE_IMAGE)
3068                                 ibuf = image_load_image_file(ima, iuser, frame);  /* cfra only for '#', this global is OK */
3069                         /* no else; on load the ima type can change */
3070                         if (ima->type == IMA_TYPE_MULTILAYER)
3071                                 /* keeps render result, stores ibufs in listbase, allows saving */
3072                                 ibuf = image_get_ibuf_multilayer(ima, iuser);
3073                 }
3074                 else if (ima->source == IMA_SRC_GENERATED) {
3075                         /* generated is: ibuf is allocated dynamically */
3076                         /* UV testgrid or black or solid etc */
3077                         if (ima->gen_x == 0) ima->gen_x = 1024;
3078                         if (ima->gen_y == 0) ima->gen_y = 1024;
3079                         if (ima->gen_depth == 0) ima->gen_depth = 24;
3080                         ibuf = add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, ima->gen_depth, (ima->gen_flag & IMA_GEN_FLOAT) != 0, ima->gen_type,
3081                                              ima->gen_color, &ima->colorspace_settings);
3082                         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
3083                         ima->ok = IMA_OK_LOADED;
3084                 }
3085                 else if (ima->source == IMA_SRC_VIEWER) {
3086                         if (ima->type == IMA_TYPE_R_RESULT) {
3087                                 /* always verify entirely, and potentially
3088                                  * returns pointer to release later */
3089                                 ibuf = image_get_render_result(ima, iuser, lock_r);
3090                         }
3091                         else if (ima->type == IMA_TYPE_COMPOSITE) {
3092                                 /* requires lock/unlock, otherwise don't return image */
3093                                 if (lock_r) {
3094                                         /* unlock in BKE_image_release_ibuf */
3095                                         BLI_lock_thread(LOCK_VIEWER);
3096                                         *lock_r = ima;
3097
3098                                         /* XXX anim play for viewer nodes not yet supported */
3099                                         frame = 0; // XXX iuser ? iuser->framenr : 0;
3100                                         ibuf = image_get_cached_ibuf_for_index_frame(ima, 0, frame);
3101
3102                                         if (!ibuf) {
3103                                                 /* Composite Viewer, all handled in compositor */
3104                                                 /* fake ibuf, will be filled in compositor */
3105                                                 ibuf = IMB_allocImBuf(256, 256, 32, IB_rect);
3106                                                 image_assign_ibuf(ima, ibuf, 0, frame);
3107                                         }
3108                                 }
3109                         }
3110                 }
3111
3112                 /* We only want movies and sequences to be memory limited. */
3113                 if (ibuf != NULL && !ELEM(ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
3114                         ibuf->userflags |= IB_PERSISTENT;
3115                 }
3116         }
3117
3118         BKE_image_tag_time(ima);
3119
3120         return ibuf;
3121 }
3122
3123 /* return image buffer for given image and user
3124  *
3125  * - will lock render result if image type is render result and lock is not NULL
3126  * - will return NULL if image type if render or composite result and lock is NULL
3127  *
3128  * references the result, BKE_image_release_ibuf should be used to de-reference
3129  */
3130 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
3131 {
3132         ImBuf *ibuf;
3133
3134         BLI_spin_lock(&image_spin);
3135
3136         ibuf = image_acquire_ibuf(ima, iuser, lock_r);
3137
3138         BLI_spin_unlock(&image_spin);
3139
3140         return ibuf;
3141 }
3142
3143 void BKE_image_release_ibuf(Image *ima, ImBuf *ibuf, void *lock)
3144 {
3145         if (lock) {
3146                 /* for getting image during threaded render / compositing, need to release */
3147                 if (lock == ima) {
3148                         BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
3149                 }
3150                 else if (lock) {
3151                         RE_ReleaseResultImage(lock); /* render result */
3152                         BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
3153                 }
3154         }
3155
3156         if (ibuf) {
3157                 BLI_spin_lock(&image_spin);
3158                 IMB_freeImBuf(ibuf);
3159                 BLI_spin_unlock(&image_spin);
3160         }
3161 }
3162
3163 /* checks whether there's an image buffer for given image and user */
3164 bool BKE_image_has_ibuf(Image *ima, ImageUser *iuser)
3165 {
3166         ImBuf *ibuf;
3167
3168         /* quick reject tests */
3169         if (!image_quick_test(ima, iuser))
3170                 return false;
3171
3172         BLI_spin_lock(&image_spin);
3173
3174         ibuf = image_get_cached_ibuf(ima, iuser, NULL, NULL);
3175
3176         if (!ibuf)
3177                 ibuf = image_acquire_ibuf(ima, iuser, NULL);
3178
3179         BLI_spin_unlock(&image_spin);
3180
3181         IMB_freeImBuf(ibuf);
3182
3183         return ibuf != NULL;
3184 }
3185
3186 /* ******** Pool for image buffers ********  */
3187
3188 typedef struct ImagePoolEntry {
3189         struct ImagePoolEntry *next, *prev;
3190         Image *image;
3191         ImBuf *ibuf;
3192         int index;
3193         int frame;
3194 } ImagePoolEntry;
3195
3196 typedef struct ImagePool {
3197         ListBase image_buffers;
3198 } ImagePool;
3199
3200 ImagePool *BKE_image_pool_new(void)
3201 {
3202         ImagePool *pool = MEM_callocN(sizeof(ImagePool), "Image Pool");
3203
3204         return pool;
3205 }
3206
3207 void BKE_image_pool_free(ImagePool *pool)
3208 {
3209         ImagePoolEntry *entry, *next_entry;
3210
3211         /* use single lock to dereference all the image buffers */
3212         BLI_spin_lock(&image_spin);
3213
3214         for (entry = pool->image_buffers.first; entry; entry = next_entry) {
3215                 next_entry = entry->next;
3216
3217                 if (entry->ibuf)
3218                         IMB_freeImBuf(entry->ibuf);
3219
3220                 MEM_freeN(entry);
3221         }
3222
3223         BLI_spin_unlock(&image_spin);
3224
3225         MEM_freeN(pool);
3226 }
3227
3228 BLI_INLINE ImBuf *image_pool_find_entry(ImagePool *pool, Image *image, int frame, int index, bool *found)
3229 {
3230         ImagePoolEntry *entry;
3231
3232         *found = false;
3233
3234         for (entry = pool->image_buffers.first; entry; entry = entry->next) {
3235                 if (entry->image == image && entry->frame == frame && entry->index == index) {
3236                         *found = true;
3237                         return entry->ibuf;
3238                 }
3239         }
3240
3241         return NULL;
3242 }
3243
3244 ImBuf *BKE_image_pool_acquire_ibuf(Image *ima, ImageUser *iuser, ImagePool *pool)
3245 {
3246         ImBuf *ibuf;
3247         int index, frame;
3248         bool found;
3249
3250         if (!image_quick_test(ima, iuser))
3251                 return NULL;
3252
3253         if (pool == NULL) {
3254                 /* pool could be NULL, in this case use general acquire function */
3255                 return BKE_image_acquire_ibuf(ima, iuser, NULL);
3256         }
3257
3258         image_get_frame_and_index(ima, iuser, &frame, &index);
3259
3260         ibuf = image_pool_find_entry(pool, ima, frame, index, &found);
3261         if (found)
3262                 return ibuf;
3263
3264         BLI_spin_lock(&image_spin);
3265
3266         ibuf = image_pool_find_entry(pool, ima, frame, index, &found);
3267
3268         /* will also create entry even in cases image buffer failed to load,
3269          * prevents trying to load the same buggy file multiple times
3270          */
3271         if (!found) {
3272                 ImagePoolEntry *entry;
3273
3274                 ibuf = image_acquire_ibuf(ima, iuser, NULL);
3275
3276                 entry = MEM_callocN(sizeof(ImagePoolEntry), "Image Pool Entry");
3277                 entry->image = ima;
3278                 entry->frame = frame;