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