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