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