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