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