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