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