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