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