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