Merging r45810 through r45876 from trunk into soc-2011-tomato
[blender.git] / source / blender / blenkernel / intern / image.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, 2006, full recode
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/image.c
27  *  \ingroup bke
28  */
29
30
31 #include <stdio.h>
32 #include <string.h>
33 #include <fcntl.h>
34 #include <math.h>
35 #ifndef WIN32 
36 #include <unistd.h>
37 #else
38 #include <io.h>
39 #endif
40
41 #include <time.h>
42
43 #ifdef _WIN32
44 #define open _open
45 #define close _close
46 #endif
47
48 #include "MEM_guardedalloc.h"
49
50 #include "IMB_imbuf_types.h"
51 #include "IMB_imbuf.h"
52
53 #ifdef WITH_OPENEXR
54 #include "intern/openexr/openexr_multi.h"
55 #endif
56
57 #include "DNA_packedFile_types.h"
58 #include "DNA_scene_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_camera_types.h"
61 #include "DNA_sequence_types.h"
62 #include "DNA_userdef_types.h"
63 #include "DNA_brush_types.h"
64 #include "DNA_mesh_types.h"
65 #include "DNA_meshdata_types.h"
66
67 #include "BLI_blenlib.h"
68 #include "BLI_threads.h"
69 #include "BLI_utildefines.h"
70 #include "BLI_bpath.h"
71
72 #include "BKE_bmfont.h"
73 #include "BKE_global.h"
74 #include "BKE_icons.h"
75 #include "BKE_image.h"
76 #include "BKE_library.h"
77 #include "BKE_main.h"
78 #include "BKE_packedFile.h"
79 #include "BKE_scene.h"
80 #include "BKE_node.h"
81 #include "BKE_sequencer.h" /* seq_foreground_frame_get() */
82 #include "BKE_utildefines.h"
83
84 #include "BLF_api.h"
85
86 #include "PIL_time.h"
87
88 #include "RE_pipeline.h"
89
90 #include "GPU_draw.h"
91
92 #include "BLO_sys_types.h" // for intptr_t support
93
94 /* max int, to indicate we don't store sequences in ibuf */
95 #define IMA_NO_INDEX    0x7FEFEFEF
96
97 /* quick lookup: supports 1 million frames, thousand passes */
98 #define IMA_MAKE_INDEX(frame, index)    ((frame)<<10)+index
99 #define IMA_INDEX_FRAME(index)                  (index>>10)
100 #define IMA_INDEX_PASS(index)                   (index & ~1023)
101
102 /* ******** IMAGE PROCESSING ************* */
103
104 static void de_interlace_ng(struct ImBuf *ibuf) /* neogeo fields */
105 {
106         struct ImBuf * tbuf1, * tbuf2;
107         
108         if (ibuf == NULL) return;
109         if (ibuf->flags & IB_fields) return;
110         ibuf->flags |= IB_fields;
111         
112         if (ibuf->rect) {
113                 /* make copies */
114                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
115                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
116                 
117                 ibuf->x *= 2;
118                 
119                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
120                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
121                 
122                 ibuf->x /= 2;
123                 IMB_rectcpy(ibuf, tbuf1, 0, 0, 0, 0, tbuf1->x, tbuf1->y);
124                 IMB_rectcpy(ibuf, tbuf2, 0, tbuf2->y, 0, 0, tbuf2->x, tbuf2->y);
125                 
126                 IMB_freeImBuf(tbuf1);
127                 IMB_freeImBuf(tbuf2);
128         }
129         ibuf->y /= 2;
130 }
131
132 static void de_interlace_st(struct ImBuf *ibuf) /* standard fields */
133 {
134         struct ImBuf * tbuf1, * tbuf2;
135         
136         if (ibuf == NULL) return;
137         if (ibuf->flags & IB_fields) return;
138         ibuf->flags |= IB_fields;
139         
140         if (ibuf->rect) {
141                 /* make copies */
142                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect);
143                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect);
144                 
145                 ibuf->x *= 2;
146                 
147                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
148                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
149                 
150                 ibuf->x /= 2;
151                 IMB_rectcpy(ibuf, tbuf2, 0, 0, 0, 0, tbuf2->x, tbuf2->y);
152                 IMB_rectcpy(ibuf, tbuf1, 0, tbuf2->y, 0, 0, tbuf1->x, tbuf1->y);
153                 
154                 IMB_freeImBuf(tbuf1);
155                 IMB_freeImBuf(tbuf2);
156         }
157         ibuf->y /= 2;
158 }
159
160 void 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                 {
1154                         return BLI_replace_extension(string, FILE_MAX, extension);
1155                 }
1156                 else {
1157                         return BLI_ensure_extension(string, FILE_MAX, extension);
1158                 }
1159                 
1160         }
1161         else {
1162                 return FALSE;
1163         }
1164 }
1165
1166 /* could allow access externally - 512 is for long names, 64 is for id names */
1167 typedef struct StampData {
1168         char    file[512];
1169         char    note[512];
1170         char    date[512];
1171         char    marker[512];
1172         char    time[512];
1173         char    frame[512];
1174         char    camera[64];
1175         char    cameralens[64];
1176         char    scene[64];
1177         char    strip[64];
1178         char    rendertime[64];
1179 } StampData;
1180
1181 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix)
1182 {
1183         char text[256];
1184         struct tm *tl;
1185         time_t t;
1186
1187         if (scene->r.stamp & R_STAMP_FILENAME) {
1188                 BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), do_prefix ? "File %s":"%s", G.relbase_valid ? G.main->name:"<untitled>");
1189         }
1190         else {
1191                 stamp_data->file[0] = '\0';
1192         }
1193         
1194         if (scene->r.stamp & R_STAMP_NOTE) {
1195                 /* Never do prefix for Note */
1196                 BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", scene->r.stamp_udata);
1197         }
1198         else {
1199                 stamp_data->note[0] = '\0';
1200         }
1201         
1202         if (scene->r.stamp & R_STAMP_DATE) {
1203                 t = time(NULL);
1204                 tl = localtime(&t);
1205                 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);
1206                 BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), do_prefix ? "Date %s":"%s", text);
1207         }
1208         else {
1209                 stamp_data->date[0] = '\0';
1210         }
1211         
1212         if (scene->r.stamp & R_STAMP_MARKER) {
1213                 char *name = scene_find_last_marker_name(scene, CFRA);
1214
1215                 if (name)       BLI_strncpy(text, name, sizeof(text));
1216                 else            BLI_strncpy(text, "<none>", sizeof(text));
1217
1218                 BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), do_prefix ? "Marker %s":"%s", text);
1219         }
1220         else {
1221                 stamp_data->marker[0] = '\0';
1222         }
1223         
1224         if (scene->r.stamp & R_STAMP_TIME) {
1225                 int f = (int)(scene->r.cfra % scene->r.frs_sec);
1226                 int s = (int)(scene->r.cfra / scene->r.frs_sec);
1227                 int h= 0;
1228                 int m= 0;
1229
1230                 if (s) {
1231                         m = (int)(s / 60);
1232                         s %= 60;
1233
1234                         if (m) {
1235                                 h = (int)(m / 60);
1236                                 m %= 60;
1237                         }
1238                 }
1239
1240                 if (scene->r.frs_sec < 100)
1241                         BLI_snprintf(text, sizeof(text), "%02d:%02d:%02d.%02d", h, m, s, f);
1242                 else
1243                         BLI_snprintf(text, sizeof(text), "%02d:%02d:%02d.%03d", h, m, s, f);
1244
1245                 BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), do_prefix ? "Time %s":"%s", text);
1246         }
1247         else {
1248                 stamp_data->time[0] = '\0';
1249         }
1250         
1251         if (scene->r.stamp & R_STAMP_FRAME) {
1252                 char fmtstr[32];
1253                 int digits= 1;
1254                 
1255                 if (scene->r.efra>9)
1256                         digits= 1 + (int) log10(scene->r.efra);
1257
1258                 BLI_snprintf(fmtstr, sizeof(fmtstr), do_prefix ? "Frame %%0%di":"%%0%di", digits);
1259                 BLI_snprintf (stamp_data->frame, sizeof(stamp_data->frame), fmtstr, scene->r.cfra);
1260         }
1261         else {
1262                 stamp_data->frame[0] = '\0';
1263         }
1264
1265         if (scene->r.stamp & R_STAMP_CAMERA) {
1266                 BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), do_prefix ? "Camera %s":"%s", camera ? camera->id.name+2 : "<none>");
1267         }
1268         else {
1269                 stamp_data->camera[0] = '\0';
1270         }
1271
1272         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1273                 if (camera && camera->type == OB_CAMERA) {
1274                         BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)camera->data)->lens);
1275                 }
1276                 else            BLI_strncpy(text, "<none>", sizeof(text));
1277
1278                 BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), do_prefix ? "Lens %s":"%s", text);
1279         }
1280         else {
1281                 stamp_data->cameralens[0] = '\0';
1282         }
1283
1284         if (scene->r.stamp & R_STAMP_SCENE) {
1285                 BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), do_prefix ? "Scene %s":"%s", scene->id.name+2);
1286         }
1287         else {
1288                 stamp_data->scene[0] = '\0';
1289         }
1290         
1291         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1292                 Sequence *seq= seq_foreground_frame_get(scene, scene->r.cfra);
1293         
1294                 if (seq)        BLI_strncpy(text, seq->name+2, sizeof(text));
1295                 else            BLI_strncpy(text, "<none>", sizeof(text));
1296
1297                 BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), do_prefix ? "Strip %s":"%s", text);
1298         }
1299         else {
1300                 stamp_data->strip[0] = '\0';
1301         }
1302
1303         {
1304                 Render *re= RE_GetRender(scene->id.name);
1305                 RenderStats *stats= re ? RE_GetStats(re):NULL;
1306
1307                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1308                         BLI_timestr(stats->lastframetime, text);
1309
1310                         BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), do_prefix ? "RenderTime %s":"%s", text);
1311                 }
1312                 else {
1313                         stamp_data->rendertime[0] = '\0';
1314                 }
1315         }
1316 }
1317
1318 void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rectf, int width, int height, int channels)
1319 {
1320         struct StampData stamp_data;
1321         float w, h, pad;
1322         int x, y, y_ofs;
1323         float h_fixed;
1324         const int mono= blf_mono_font_render; // XXX
1325
1326 #define BUFF_MARGIN_X 2
1327 #define BUFF_MARGIN_Y 1
1328
1329         if (!rect && !rectf)
1330                 return;
1331         
1332         stampdata(scene, camera, &stamp_data, 1);
1333
1334         /* TODO, do_versions */
1335         if (scene->r.stamp_font_id < 8)
1336                 scene->r.stamp_font_id= 12;
1337
1338         /* set before return */
1339         BLF_size(mono, scene->r.stamp_font_id, 72);
1340         
1341         BLF_buffer(mono, rectf, rect, width, height, channels);
1342         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1343         pad= BLF_width_max(mono);
1344
1345         /* use 'h_fixed' rather than 'h', aligns better */
1346         h_fixed= BLF_height_max(mono);
1347         y_ofs = -BLF_descender(mono);
1348
1349         x= 0;
1350         y= height;
1351
1352         if (stamp_data.file[0]) {
1353                 /* Top left corner */
1354                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h= h_fixed;
1355                 y -= h;
1356
1357                 /* also a little of space to the background. */
1358                 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);
1359
1360                 /* and draw the text. */
1361                 BLF_position(mono, x, y + y_ofs, 0.0);
1362                 BLF_draw_buffer(mono, stamp_data.file);
1363
1364                 /* the extra pixel for background. */
1365                 y -= BUFF_MARGIN_Y * 2;
1366         }
1367
1368         /* Top left corner, below File */
1369         if (stamp_data.note[0]) {
1370                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h= h_fixed;
1371                 y -= h;
1372
1373                 /* and space for background. */
1374                 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);
1375
1376                 BLF_position(mono, x, y + y_ofs, 0.0);
1377                 BLF_draw_buffer(mono, stamp_data.note);
1378
1379                 /* the extra pixel for background. */
1380                 y -= BUFF_MARGIN_Y * 2;
1381         }
1382         
1383         /* Top left corner, below File (or Note) */
1384         if (stamp_data.date[0]) {
1385                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h= h_fixed;
1386                 y -= h;
1387
1388                 /* and space for background. */
1389                 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);
1390
1391                 BLF_position(mono, x, y + y_ofs, 0.0);
1392                 BLF_draw_buffer(mono, stamp_data.date);
1393
1394                 /* the extra pixel for background. */
1395                 y -= BUFF_MARGIN_Y * 2;
1396         }
1397
1398         /* Top left corner, below File, Date or Note */
1399         if (stamp_data.rendertime[0]) {
1400                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h= h_fixed;
1401                 y -= h;
1402
1403                 /* and space for background. */
1404                 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);
1405
1406                 BLF_position(mono, x, y + y_ofs, 0.0);
1407                 BLF_draw_buffer(mono, stamp_data.rendertime);
1408         }
1409
1410         x= 0;
1411         y= 0;
1412
1413         /* Bottom left corner, leaving space for timing */
1414         if (stamp_data.marker[0]) {
1415                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h= h_fixed;
1416
1417                 /* extra space for background. */
1418                 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);
1419
1420                 /* and pad the text. */
1421                 BLF_position(mono, x, y + y_ofs, 0.0);
1422                 BLF_draw_buffer(mono, stamp_data.marker);
1423
1424                 /* space width. */
1425                 x += w + pad;
1426         }
1427         
1428         /* Left bottom corner */
1429         if (stamp_data.time[0]) {
1430                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h= h_fixed;
1431
1432                 /* extra space for background */
1433                 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);
1434
1435                 /* and pad the text. */
1436                 BLF_position(mono, x, y + y_ofs, 0.0);
1437                 BLF_draw_buffer(mono, stamp_data.time);
1438
1439                 /* space width. */
1440                 x += w + pad;
1441         }
1442         
1443         if (stamp_data.frame[0]) {
1444                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h= h_fixed;
1445
1446                 /* extra space for background. */
1447                 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);
1448
1449                 /* and pad the text. */
1450                 BLF_position(mono, x, y + y_ofs, 0.0);
1451                 BLF_draw_buffer(mono, stamp_data.frame);
1452
1453                 /* space width. */
1454                 x += w + pad;
1455         }
1456
1457         if (stamp_data.camera[0]) {
1458                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h= h_fixed;
1459
1460                 /* extra space for background. */
1461                 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);
1462                 BLF_position(mono, x, y + y_ofs, 0.0);
1463                 BLF_draw_buffer(mono, stamp_data.camera);
1464
1465                 /* space width. */
1466                 x += w + pad;
1467         }
1468
1469         if (stamp_data.cameralens[0]) {
1470                 BLF_width_and_height(mono, stamp_data.cameralens, &w, &h); h= h_fixed;
1471
1472                 /* extra space for background. */
1473                 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);
1474                 BLF_position(mono, x, y + y_ofs, 0.0);
1475                 BLF_draw_buffer(mono, stamp_data.cameralens);
1476         }
1477         
1478         if (stamp_data.scene[0]) {
1479                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h= h_fixed;
1480
1481                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1482                 x= width - w - 2;
1483
1484                 /* extra space for background. */
1485                 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);
1486
1487                 /* and pad the text. */
1488                 BLF_position(mono, x, y+y_ofs, 0.0);
1489                 BLF_draw_buffer(mono, stamp_data.scene);
1490         }
1491         
1492         if (stamp_data.strip[0]) {
1493                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h= h_fixed;
1494
1495                 /* Top right corner, with an extra space because blenfont is too strict! */
1496                 x= width - w - pad;
1497                 y= height - h;
1498
1499                 /* extra space for background. */
1500                 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);
1501
1502                 BLF_position(mono, x, y + y_ofs, 0.0);
1503                 BLF_draw_buffer(mono, stamp_data.strip);
1504         }
1505
1506         /* cleanup the buffer. */
1507         BLF_buffer(mono, NULL, NULL, 0, 0, 0);
1508
1509 #undef BUFF_MARGIN_X
1510 #undef BUFF_MARGIN_Y
1511 }
1512
1513 void BKE_stamp_info(Scene *scene, Object *camera, struct ImBuf *ibuf)
1514 {
1515         struct StampData stamp_data;
1516
1517         if (!ibuf)      return;
1518         
1519         /* fill all the data values, no prefix */
1520         stampdata(scene, camera, &stamp_data, 0);
1521         
1522         if (stamp_data.file[0])         IMB_metadata_change_field (ibuf, "File",                stamp_data.file);
1523         if (stamp_data.note[0])         IMB_metadata_change_field (ibuf, "Note",                stamp_data.note);
1524         if (stamp_data.date[0])         IMB_metadata_change_field (ibuf, "Date",                stamp_data.date);
1525         if (stamp_data.marker[0])       IMB_metadata_change_field (ibuf, "Marker",      stamp_data.marker);
1526         if (stamp_data.time[0])         IMB_metadata_change_field (ibuf, "Time",                stamp_data.time);
1527         if (stamp_data.frame[0])        IMB_metadata_change_field (ibuf, "Frame",       stamp_data.frame);
1528         if (stamp_data.camera[0])       IMB_metadata_change_field (ibuf, "Camera",      stamp_data.camera);
1529         if (stamp_data.cameralens[0]) IMB_metadata_change_field (ibuf, "Lens",  stamp_data.cameralens);
1530         if (stamp_data.scene[0])        IMB_metadata_change_field (ibuf, "Scene",       stamp_data.scene);
1531         if (stamp_data.strip[0])        IMB_metadata_change_field (ibuf, "Strip",       stamp_data.strip);
1532         if (stamp_data.rendertime[0]) IMB_metadata_change_field (ibuf, "RenderTime", stamp_data.rendertime);
1533 }
1534
1535 int BKE_alphatest_ibuf(ImBuf *ibuf)
1536 {
1537         int tot;
1538         if (ibuf->rect_float) {
1539                 float *buf= ibuf->rect_float;
1540                 for (tot= ibuf->x * ibuf->y; tot--; buf+=4) {
1541                         if (buf[3] < 1.0f) {
1542                                 return TRUE;
1543                         }
1544                 }
1545         }
1546         else if (ibuf->rect) {
1547                 unsigned char *buf= (unsigned char *)ibuf->rect;
1548                 for (tot= ibuf->x * ibuf->y; tot--; buf+=4) {
1549                         if (buf[3] != 255) {
1550                                 return TRUE;
1551                         }
1552                 }
1553         }
1554
1555         return FALSE;
1556 }
1557
1558 /* note: imf->planes is ignored here, its assumed the image channels
1559  * are already set */
1560 int BKE_write_ibuf(ImBuf *ibuf, const char *name, ImageFormatData *imf)
1561 {
1562         char imtype= imf->imtype;
1563         char compress= imf->compress;
1564         char quality= imf->quality;
1565
1566         int ok;
1567
1568         if (imtype== R_IMF_IMTYPE_IRIS) {
1569                 ibuf->ftype= IMAGIC;
1570         }
1571 #ifdef WITH_HDR
1572         else if (imtype==R_IMF_IMTYPE_RADHDR) {
1573                 ibuf->ftype= RADHDR;
1574         }
1575 #endif
1576         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1577                 ibuf->ftype= PNG;
1578
1579                 if (imtype==R_IMF_IMTYPE_PNG)
1580                         ibuf->ftype |= compress;
1581
1582         }
1583 #ifdef WITH_DDS
1584         else if (imtype==R_IMF_IMTYPE_DDS) {
1585                 ibuf->ftype= DDS;
1586         }
1587 #endif
1588         else if (imtype==R_IMF_IMTYPE_BMP) {
1589                 ibuf->ftype= BMP;
1590         }
1591 #ifdef WITH_TIFF
1592         else if (imtype==R_IMF_IMTYPE_TIFF) {
1593                 ibuf->ftype= TIF;
1594
1595                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1596                         ibuf->ftype |= TIF_16BIT;
1597         }
1598 #endif
1599 #ifdef WITH_OPENEXR
1600         else if (imtype==R_IMF_IMTYPE_OPENEXR || imtype==R_IMF_IMTYPE_MULTILAYER) {
1601                 ibuf->ftype= OPENEXR;
1602                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1603                         ibuf->ftype |= OPENEXR_HALF;
1604                 ibuf->ftype |= (imf->exr_codec & OPENEXR_COMPRESS);
1605                 
1606                 if (!(imf->flag & R_IMF_FLAG_ZBUF))
1607                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1608                 
1609         }
1610 #endif
1611 #ifdef WITH_CINEON
1612         else if (imtype==R_IMF_IMTYPE_CINEON) {
1613                 ibuf->ftype = CINEON;
1614         }
1615         else if (imtype==R_IMF_IMTYPE_DPX) {
1616                 ibuf->ftype = DPX;
1617         }
1618 #endif
1619         else if (imtype==R_IMF_IMTYPE_TARGA) {
1620                 ibuf->ftype= TGA;
1621         }
1622         else if (imtype==R_IMF_IMTYPE_RAWTGA) {
1623                 ibuf->ftype= RAWTGA;
1624         }
1625 #ifdef WITH_OPENJPEG
1626         else if (imtype==R_IMF_IMTYPE_JP2) {
1627                 if (quality < 10) quality= 90;
1628                 ibuf->ftype= JP2|quality;
1629                 
1630                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1631                         ibuf->ftype |= JP2_16BIT;
1632                 }
1633                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1634                         ibuf->ftype |= JP2_12BIT;
1635                 }
1636                 
1637                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
1638                         ibuf->ftype |= JP2_YCC;
1639                 }
1640
1641                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
1642                         ibuf->ftype |= JP2_CINE;
1643                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
1644                                 ibuf->ftype |= JP2_CINE_48FPS;
1645                 }
1646         }
1647 #endif
1648         else {
1649                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
1650                 if (quality < 10) quality= 90;
1651                 ibuf->ftype= JPG|quality;
1652         }
1653         
1654         BLI_make_existing_file(name);
1655         
1656         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1657         if (ok == 0) {
1658                 perror(name);
1659         }
1660         
1661         return(ok);
1662 }
1663
1664 /* same as BKE_write_ibuf() but crappy workaround not to perminantly modify
1665  * _some_, values in the imbuf */
1666 int BKE_write_ibuf_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
1667                       const short save_copy)
1668 {
1669         ImBuf ibuf_back= *ibuf;
1670         int ok;
1671
1672         /* all data is rgba anyway,
1673          * this just controls how to save for some formats */
1674         ibuf->planes= imf->planes;
1675
1676         ok= BKE_write_ibuf(ibuf, name, imf);
1677
1678         if (save_copy) {
1679                 /* note that we are not restoring _all_ settings */
1680                 ibuf->planes= ibuf_back.planes;
1681                 ibuf->ftype=  ibuf_back.ftype;
1682         }
1683
1684         return ok;
1685 }
1686
1687 int BKE_write_ibuf_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, struct ImageFormatData *imf)
1688 {
1689         if (scene && scene->r.stamp & R_STAMP_ALL)
1690                 BKE_stamp_info(scene, camera, ibuf);
1691
1692         return BKE_write_ibuf(ibuf, name, imf);
1693 }
1694
1695
1696 void BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, const char imtype, const short use_ext, const short use_frames)
1697 {
1698         if (string==NULL) return;
1699         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1700         BLI_path_abs(string, relbase);
1701
1702         if (use_frames)
1703                 BLI_path_frame(string, frame, 4);
1704
1705         if (use_ext)
1706                 BKE_add_image_extension(string, imtype);
1707                 
1708 }
1709
1710 /* used by sequencer too */
1711 struct anim *openanim(const char *name, int flags, int streamindex)
1712 {
1713         struct anim *anim;
1714         struct ImBuf *ibuf;
1715         
1716         anim = IMB_open_anim(name, flags, streamindex);
1717         if (anim == NULL) return NULL;
1718
1719         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
1720         if (ibuf == NULL) {
1721                 if (BLI_exists(name))
1722                         printf("not an anim: %s\n", name);
1723                 else
1724                         printf("anim file doesn't exist: %s\n", name);
1725                 IMB_free_anim(anim);
1726                 return NULL;
1727         }
1728         IMB_freeImBuf(ibuf);
1729         
1730         return(anim);
1731 }
1732
1733 /* ************************* New Image API *************** */
1734
1735
1736 /* Notes about Image storage 
1737  * - packedfile
1738  *   -> written in .blend
1739  * - filename
1740  *   -> written in .blend
1741  * - movie
1742  *   -> comes from packedfile or filename
1743  * - renderresult
1744  *   -> comes from packedfile or filename
1745  * - listbase
1746  *   -> ibufs from exrhandle
1747  * - flipbook array
1748  *   -> ibufs come from movie, temporary renderresult or sequence
1749  * - ibuf
1750  *   -> comes from packedfile or filename or generated
1751  */
1752
1753
1754 /* forces existence of 1 Image for renderout or nodes, returns Image */
1755 /* name is only for default, when making new one */
1756 Image *BKE_image_verify_viewer(int type, const char *name)
1757 {
1758         Image *ima;
1759         
1760         for (ima=G.main->image.first; ima; ima= ima->id.next)
1761                 if (ima->source==IMA_SRC_VIEWER)
1762                         if (ima->type==type)
1763                                 break;
1764         
1765         if (ima==NULL)
1766                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1767         
1768         /* happens on reload, imagewindow cannot be image user when hidden*/
1769         if (ima->id.us==0)
1770                 id_us_plus(&ima->id);
1771
1772         return ima;
1773 }
1774
1775 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1776 {
1777         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1778 }
1779
1780 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1781 {
1782         if (ima==NULL)
1783                 return;
1784         
1785         switch(signal) {
1786         case IMA_SIGNAL_FREE:
1787                 image_free_buffers(ima);
1788                 if (iuser)
1789                         iuser->ok= 1;
1790                 break;
1791         case IMA_SIGNAL_SRC_CHANGE:
1792                 if (ima->type == IMA_TYPE_UV_TEST)
1793                         if (ima->source != IMA_SRC_GENERATED)
1794                                 ima->type= IMA_TYPE_IMAGE;
1795
1796                 if (ima->source==IMA_SRC_GENERATED) {
1797                         if (ima->gen_x==0 || ima->gen_y==0) {
1798                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1799                                 if (ibuf) {
1800                                         ima->gen_x= ibuf->x;
1801                                         ima->gen_y= ibuf->y;
1802                                 }
1803                         }
1804                 }
1805
1806                 /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
1807                 if (ima->type!=IMA_TYPE_MULTILAYER)
1808                         image_free_buffers(ima);
1809
1810                 ima->ok= 1;
1811                 if (iuser)
1812                         iuser->ok= 1;
1813                 break;
1814                         
1815         case IMA_SIGNAL_RELOAD:
1816                 /* try to repack file */
1817                 if (ima->packedfile) {
1818                         PackedFile *pf;
1819                         pf = newPackedFile(NULL, ima->name, ID_BLEND_PATH(G.main, &ima->id));
1820                         if (pf) {
1821                                 freePackedFile(ima->packedfile);
1822                                 ima->packedfile = pf;
1823                                 image_free_buffers(ima);
1824                         }
1825                         else {
1826                                 printf("ERROR: Image not available. Keeping packed image\n");
1827                         }
1828                 }
1829                 else
1830                         image_free_buffers(ima);
1831                 
1832                 if (iuser)
1833                         iuser->ok= 1;
1834                 
1835                 break;
1836         case IMA_SIGNAL_USER_NEW_IMAGE:
1837                 if (iuser) {
1838                         iuser->ok= 1;
1839                         if (ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1840                                 if (ima->type==IMA_TYPE_MULTILAYER) {
1841                                         iuser->multi_index= 0;
1842                                         iuser->layer= iuser->pass= 0;
1843                                 }
1844                         }
1845                 }
1846                 break;
1847         }
1848         
1849         /* don't use notifiers because they are not 100% sure to succeeded
1850          * this also makes sure all scenes are accounted for. */
1851         {
1852                 Scene *scene;
1853                 for (scene= G.main->scene.first; scene; scene= scene->id.next) {
1854                         if (scene->nodetree) {
1855                                 nodeUpdateID(scene->nodetree, &ima->id);
1856                         }
1857                 }
1858         }
1859 }
1860
1861 /* if layer or pass changes, we need an index for the imbufs list */
1862 /* note it is called for rendered results, but it doesnt use the index! */
1863 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1864 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1865 {
1866         RenderLayer *rl;
1867         RenderPass *rpass= NULL;
1868         
1869         if (rr==NULL) 
1870                 return NULL;
1871         
1872         if (iuser) {
1873                 short index= 0, rl_index= 0, rp_index;
1874                 
1875                 for (rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1876                         rp_index= 0;
1877                         for (rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1878                                 if (iuser->layer==rl_index && iuser->pass==rp_index)
1879                                         break;
1880                         if (rpass)
1881                                 break;
1882                 }
1883                 
1884                 if (rpass)
1885                         iuser->multi_index= index;
1886                 else 
1887                         iuser->multi_index= 0;
1888         }
1889         if (rpass==NULL) {
1890                 rl= rr->layers.first;
1891                 if (rl)
1892                         rpass= rl->passes.first;
1893         }
1894         
1895         return rpass;
1896 }
1897
1898 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
1899 {
1900         if (ima->rr) {
1901                 return ima->rr;
1902         }
1903         else if (ima->type==IMA_TYPE_R_RESULT) {
1904                 if (ima->render_slot == ima->last_render_slot)
1905                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
1906                 else
1907                         return ima->renders[ima->render_slot];
1908         }
1909         else
1910                 return NULL;
1911 }
1912
1913 void BKE_image_release_renderresult(Scene *scene, Image *ima)
1914 {
1915         if (ima->rr);
1916         else if (ima->type==IMA_TYPE_R_RESULT) {
1917                 if (ima->render_slot == ima->last_render_slot)
1918                         RE_ReleaseResult(RE_GetRender(scene->id.name));
1919         }
1920 }
1921
1922 void BKE_image_backup_render(Scene *scene, Image *ima)
1923 {
1924         /* called right before rendering, ima->renders contains render
1925          * result pointers for everything but the current render */
1926         Render *re= RE_GetRender(scene->id.name);
1927         int slot= ima->render_slot, last= ima->last_render_slot;
1928
1929         if (slot != last) {
1930                 if (ima->renders[slot]) {
1931                         RE_FreeRenderResult(ima->renders[slot]);
1932                         ima->renders[slot]= NULL;
1933                 }
1934
1935                 ima->renders[last]= NULL;
1936                 RE_SwapResult(re, &ima->renders[last]);
1937         }
1938
1939         ima->last_render_slot= slot;
1940 }
1941
1942 /* after imbuf load, openexr type can return with a exrhandle open */
1943 /* in that case we have to build a render-result */
1944 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1945 {
1946         
1947         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1948
1949 #ifdef WITH_OPENEXR
1950         IMB_exr_close(ibuf->userdata);
1951 #endif
1952
1953         ibuf->userdata= NULL;
1954         if (ima->rr)
1955                 ima->rr->framenr= framenr;
1956 }
1957
1958 /* common stuff to do with images after loading */
1959 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1960 {
1961         /* preview is NULL when it has never been used as an icon before */
1962         if (G.background==0 && ima->preview==NULL)
1963                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1964
1965         /* fields */
1966         if (ima->flag & IMA_FIELDS) {
1967                 if (ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1968                 else de_interlace_ng(ibuf);
1969         }
1970         /* timer */
1971         ima->lastused = clock() / CLOCKS_PER_SEC;
1972         
1973         ima->ok= IMA_OK_LOADED;
1974         
1975 }
1976
1977 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1978 {
1979         struct ImBuf *ibuf;
1980         unsigned short numlen;
1981         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1982         int flag;
1983         
1984         /* XXX temp stuff? */
1985         if (ima->lastframe != frame)
1986                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1987
1988         ima->lastframe= frame;
1989         BLI_strncpy(name, ima->name, sizeof(name));
1990         BLI_stringdec(name, head, tail, &numlen);
1991         BLI_stringenc(name, head, tail, numlen, frame);
1992
1993         BLI_path_abs(name, ID_BLEND_PATH(G.main, &ima->id));
1994         
1995         flag= IB_rect|IB_multilayer;
1996         if (ima->flag & IMA_DO_PREMUL)
1997                 flag |= IB_premul;
1998
1999         /* read ibuf */
2000         ibuf = IMB_loadiffname(name, flag);
2001
2002 #if 0
2003         if (ibuf) {
2004                 printf(AT" loaded %s\n", name);
2005         }
2006         else {
2007                 printf(AT" missed %s\n", name);
2008         }
2009 #endif
2010
2011         if (ibuf) {
2012 #ifdef WITH_OPENEXR
2013                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2014                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
2015                         image_create_multilayer(ima, ibuf, frame);      
2016                         ima->type= IMA_TYPE_MULTILAYER;
2017                         IMB_freeImBuf(ibuf);
2018                         ibuf= NULL;
2019                 }
2020                 else {
2021                         image_initialize_after_load(ima, ibuf);
2022                         image_assign_ibuf(ima, ibuf, 0, frame);
2023                 }
2024 #else
2025                 image_initialize_after_load(ima, ibuf);
2026                 image_assign_ibuf(ima, ibuf, 0, frame);
2027 #endif
2028         }
2029         else
2030                 ima->ok= 0;
2031         
2032         if (iuser)
2033                 iuser->ok= ima->ok;
2034         
2035         return ibuf;
2036 }
2037
2038 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
2039 {
2040         struct ImBuf *ibuf= NULL;
2041         
2042         /* either we load from RenderResult, or we have to load a new one */
2043         
2044         /* check for new RenderResult */
2045         if (ima->rr==NULL || frame!=ima->rr->framenr) {
2046                 /* copy to survive not found multilayer image */
2047                 RenderResult *oldrr= ima->rr;
2048         
2049                 ima->rr= NULL;
2050                 ibuf = image_load_sequence_file(ima, iuser, frame);
2051                 
2052                 if (ibuf) { /* actually an error */
2053                         ima->type= IMA_TYPE_IMAGE;
2054                         printf("error, multi is normal image\n");
2055                 }
2056                 // printf("loaded new result %p\n", ima->rr);
2057                 /* free result if new one found */
2058                 if (ima->rr) {
2059                         // if (oldrr) printf("freed previous result %p\n", oldrr);
2060                         if (oldrr) RE_FreeRenderResult(oldrr);
2061                 }
2062                 else {
2063                         ima->rr= oldrr;
2064                 }
2065
2066         }
2067         if (ima->rr) {
2068                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
2069                 
2070                 if (rpass) {
2071                         // printf("load from pass %s\n", rpass->name);
2072                         /* since we free  render results, we copy the rect */
2073                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2074                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
2075                         ibuf->flags |= IB_rectfloat;
2076                         ibuf->mall= IB_rectfloat;
2077                         ibuf->channels= rpass->channels;
2078                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2079                         
2080                         image_initialize_after_load(ima, ibuf);
2081                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
2082                         
2083                 }
2084                 // else printf("pass not found\n");
2085         }
2086         else
2087                 ima->ok= 0;
2088         
2089         if (iuser)
2090                 iuser->ok= ima->ok;
2091         
2092         return ibuf;
2093 }
2094
2095
2096 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
2097 {
2098         struct ImBuf *ibuf= NULL;
2099         
2100         ima->lastframe= frame;
2101         
2102         if (ima->anim==NULL) {
2103                 char str[FILE_MAX];
2104                 
2105                 BLI_strncpy(str, ima->name, FILE_MAX);
2106                 BLI_path_abs(str, ID_BLEND_PATH(G.main, &ima->id));
2107
2108                 /* FIXME: make several stream accessible in image editor, too*/
2109                 ima->anim = openanim(str, IB_rect, 0);
2110                 
2111                 /* let's initialize this user */
2112                 if (ima->anim && iuser && iuser->frames==0)
2113                         iuser->frames= IMB_anim_get_duration(ima->anim,
2114                                                              IMB_TC_RECORD_RUN);
2115         }
2116         
2117         if (ima->anim) {
2118                 int dur = IMB_anim_get_duration(ima->anim,
2119                                                 IMB_TC_RECORD_RUN);
2120                 int fra= frame-1;
2121                 
2122                 if (fra<0) fra = 0;
2123                 if (fra>(dur-1)) fra= dur-1;
2124                 ibuf = IMB_makeSingleUser(
2125                         IMB_anim_absolute(ima->anim, fra,
2126                                           IMB_TC_RECORD_RUN,
2127                                           IMB_PROXY_NONE));
2128                 
2129                 if (ibuf) {
2130                         image_initialize_after_load(ima, ibuf);
2131                         image_assign_ibuf(ima, ibuf, 0, frame);
2132                 }
2133                 else
2134                         ima->ok= 0;
2135         }
2136         else
2137                 ima->ok= 0;
2138         
2139         if (iuser)
2140                 iuser->ok= ima->ok;
2141         
2142         return ibuf;
2143 }
2144
2145 /* warning, 'iuser' can be NULL */
2146 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
2147 {
2148         struct ImBuf *ibuf;
2149         char str[FILE_MAX];
2150         int assign = 0, flag;
2151         
2152         /* always ensure clean ima */
2153         image_free_buffers(ima);
2154         
2155         /* is there a PackedFile with this image ? */
2156         if (ima->packedfile) {
2157                 flag = IB_rect|IB_multilayer;
2158                 if (ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
2159                 
2160                 ibuf = IMB_ibImageFromMemory((unsigned char*)ima->packedfile->data, ima->packedfile->size, flag, "<packed data>");
2161         } 
2162         else {
2163                 flag= IB_rect|IB_multilayer|IB_metadata;
2164                 if (ima->flag & IMA_DO_PREMUL)
2165                         flag |= IB_premul;
2166                         
2167                 /* get the right string */
2168                 BLI_strncpy(str, ima->name, sizeof(str));
2169                 BLI_path_abs(str, ID_BLEND_PATH(G.main, &ima->id));
2170                 
2171                 /* read ibuf */
2172                 ibuf = IMB_loadiffname(str, flag);
2173         }
2174         
2175         if (ibuf) {
2176                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2177                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
2178                         image_create_multilayer(ima, ibuf, cfra);       
2179                         ima->type= IMA_TYPE_MULTILAYER;
2180                         IMB_freeImBuf(ibuf);
2181                         ibuf= NULL;
2182                 }
2183                 else {
2184                         image_initialize_after_load(ima, ibuf);
2185                         assign= 1;
2186
2187                         /* check if the image is a font image... */
2188                         detectBitmapFont(ibuf);
2189                         
2190                         /* make packed file for autopack */
2191                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
2192                                 ima->packedfile = newPackedFile(NULL, str, ID_BLEND_PATH(G.main, &ima->id));
2193                 }
2194         }
2195         else
2196                 ima->ok= 0;
2197         
2198         if (assign)
2199                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2200
2201         if (iuser)
2202                 iuser->ok= ima->ok;
2203         
2204         return ibuf;
2205 }
2206
2207 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
2208 {
2209         ImBuf *ibuf= NULL;
2210         
2211         if (ima->rr==NULL) {
2212                 ibuf = image_load_image_file(ima, iuser, 0);
2213                 if (ibuf) { /* actually an error */
2214                         ima->type= IMA_TYPE_IMAGE;
2215                         return ibuf;
2216                 }
2217         }
2218         if (ima->rr) {
2219                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
2220
2221                 if (rpass) {
2222                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2223                         
2224                         image_initialize_after_load(ima, ibuf);
2225                         
2226                         ibuf->rect_float= rpass->rect;
2227                         ibuf->flags |= IB_rectfloat;
2228                         ibuf->channels= rpass->channels;
2229                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2230
2231                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2232                 }
2233         }
2234         
2235         if (ibuf==NULL) 
2236                 ima->ok= 0;
2237         if (iuser)
2238                 iuser->ok= ima->ok;
2239         
2240         return ibuf;
2241 }
2242
2243
2244 /* showing RGBA result itself (from compo/sequence) or
2245  * like exr, using layers etc */
2246 /* always returns a single ibuf, also during render progress */
2247 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
2248 {
2249         Render *re;
2250         RenderResult rres;
2251         float *rectf, *rectz;
2252         unsigned int *rect;
2253         float dither;
2254         int channels, layer, pass;
2255         ImBuf *ibuf;
2256         int from_render= (ima->render_slot == ima->last_render_slot);
2257
2258         if (!(iuser && iuser->scene))
2259                 return NULL;
2260
2261         /* if we the caller is not going to release the lock, don't give the image */
2262         if (!lock_r)
2263                 return NULL;
2264
2265         re= RE_GetRender(iuser->scene->id.name);
2266
2267         channels= 4;
2268         layer= (iuser)? iuser->layer: 0;
2269         pass= (iuser)? iuser->pass: 0;
2270
2271         if (from_render) {
2272                 RE_AcquireResultImage(re, &rres);
2273         }
2274         else if (ima->renders[ima->render_slot]) {
2275                 rres= *(ima->renders[ima->render_slot]);
2276                 rres.have_combined= rres.rectf != NULL;
2277         }
2278         else
2279                 memset(&rres, 0, sizeof(RenderResult));
2280         
2281         if (!(rres.rectx > 0 && rres.recty > 0)) {
2282                 if (from_render)
2283                         RE_ReleaseResultImage(re);
2284                 return NULL;
2285         }
2286
2287         /* release is done in BKE_image_release_ibuf using lock_r */
2288         if (from_render) {
2289                 BLI_lock_thread(LOCK_VIEWER);
2290                 *lock_r= re;
2291         }
2292
2293         /* this gives active layer, composite or seqence result */
2294         rect= (unsigned int *)rres.rect32;
2295         rectf= rres.rectf;
2296         rectz= rres.rectz;
2297         dither= iuser->scene->r.dither_intensity;
2298
2299         /* combined layer gets added as first layer */
2300         if (rres.have_combined && layer==0);
2301         else if (rres.layers.first) {
2302                 RenderLayer *rl= BLI_findlink(&rres.layers, layer-(rres.have_combined?1:0));
2303                 if (rl) {
2304                         RenderPass *rpass;
2305
2306                         /* there's no combined pass, is in renderlayer itself */
2307                         if (pass==0) {
2308                                 rectf= rl->rectf;
2309                         }
2310                         else {
2311                                 rpass= BLI_findlink(&rl->passes, pass-1);
2312                                 if (rpass) {
2313                                         channels= rpass->channels;
2314                                         rectf= rpass->rect;
2315                                         dither= 0.0f; /* don't dither passes */
2316                                 }
2317                         }
2318
2319                         for (rpass= rl->passes.first; rpass; rpass= rpass->next)
2320                                 if (rpass->passtype == SCE_PASS_Z)
2321                                         rectz= rpass->rect;
2322                 }
2323         }
2324
2325         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2326
2327         /* make ibuf if needed, and initialize it */
2328         if (ibuf==NULL) {
2329                 ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
2330                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2331         }
2332
2333         ibuf->x= rres.rectx;
2334         ibuf->y= rres.recty;
2335         
2336         /* free rect buffer if float buffer changes, so it can be recreated with
2337          * the updated result, and also in case we got byte buffer from sequencer,
2338          * so we don't keep reference to freed buffer */
2339         if (ibuf->rect_float!=rectf || rect || !rectf)
2340                 imb_freerectImBuf(ibuf);
2341
2342         if (rect)
2343                 ibuf->rect= rect;
2344         
2345         if (rectf) {
2346                 ibuf->rect_float= rectf;
2347                 ibuf->flags |= IB_rectfloat;
2348                 ibuf->channels= channels;
2349         }
2350         else {
2351                 ibuf->rect_float= NULL;
2352                 ibuf->flags &= ~IB_rectfloat;
2353         }
2354
2355         if (rectz) {
2356                 ibuf->zbuf_float= rectz;
2357                 ibuf->flags |= IB_zbuffloat;
2358         }
2359         else {
2360                 ibuf->zbuf_float= NULL;
2361                 ibuf->flags &= ~IB_zbuffloat;
2362         }
2363
2364         /* since its possible to access the buffer from the image directly, set the profile [#25073] */
2365         ibuf->profile= (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) ? IB_PROFILE_LINEAR_RGB : IB_PROFILE_NONE;
2366         ibuf->dither= dither;
2367
2368         if (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT_PREDIVIDE) {
2369                 ibuf->flags |= IB_cm_predivide;
2370                 ima->flag |= IMA_CM_PREDIVIDE;
2371         }
2372         else {
2373                 ibuf->flags &= ~IB_cm_predivide;
2374                 ima->flag &= ~IMA_CM_PREDIVIDE;
2375         }
2376
2377         ima->ok= IMA_OK_LOADED;
2378
2379         return ibuf;
2380 }
2381
2382 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2383 {
2384         ImBuf *ibuf = NULL;
2385         int frame = 0, index = 0;
2386
2387         /* see if we already have an appropriate ibuf, with image source and type */
2388         if (ima->source==IMA_SRC_MOVIE) {
2389                 frame= iuser?iuser->framenr:ima->lastframe;
2390                 ibuf= image_get_ibuf(ima, 0, frame);
2391                 /* XXX temp stuff? */
2392                 if (ima->lastframe != frame)
2393                         ima->tpageflag |= IMA_TPAGE_REFRESH;
2394                 ima->lastframe = frame;
2395         }
2396         else if (ima->source==IMA_SRC_SEQUENCE) {
2397                 if (ima->type==IMA_TYPE_IMAGE) {
2398                         frame= iuser?iuser->framenr:ima->lastframe;
2399                         ibuf= image_get_ibuf(ima, 0, frame);
2400                         
2401                         /* XXX temp stuff? */
2402                         if (ima->lastframe != frame) {
2403                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2404                         }
2405                         ima->lastframe = frame;
2406                 }       
2407                 else if (ima->type==IMA_TYPE_MULTILAYER) {
2408                         frame= iuser?iuser->framenr:ima->lastframe;
2409                         index= iuser?iuser->multi_index:IMA_NO_INDEX;
2410                         ibuf= image_get_ibuf(ima, index, frame);
2411                 }
2412         }
2413         else if (ima->source==IMA_SRC_FILE) {
2414                 if (ima->type==IMA_TYPE_IMAGE)
2415                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2416                 else if (ima->type==IMA_TYPE_MULTILAYER)
2417                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2418         }
2419         else if (ima->source == IMA_SRC_GENERATED) {
2420                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2421         }
2422         else if (ima->source == IMA_SRC_VIEWER) {
2423                 /* always verify entirely, not that this shouldn't happen
2424                  * as part of texture sampling in rendering anyway, so not
2425                  * a big bottleneck */
2426         }
2427
2428         *frame_r = frame;
2429         *index_r = index;
2430
2431         return ibuf;
2432 }
2433
2434 /* Checks optional ImageUser and verifies/creates ImBuf. */
2435 /* use this one if you want to get a render result in progress,
2436  * if not, use BKE_image_get_ibuf which doesn't require a release */
2437 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2438 {
2439         ImBuf *ibuf= NULL;
2440         float color[] = {0, 0, 0, 1};
2441         int frame= 0, index= 0;
2442
2443         /* This function is intended to be thread-safe. It postpones the mutex lock
2444          * until it needs to load the image, if the image is already there it
2445          * should just get the pointer and return. The reason is that a lot of mutex
2446          * locks appears to be very slow on certain multicore macs, causing a render
2447          * with image textures to actually slow down as more threads are used.
2448          *
2449          * Note that all the image loading functions should also make sure they do
2450          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2451          * That means, the last two steps must be, 1) add the ibuf to the list and
2452          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2453         
2454         if (lock_r)
2455                 *lock_r= NULL;
2456
2457         /* quick reject tests */
2458         if (ima==NULL) 
2459                 return NULL;
2460         if (iuser) {
2461                 if (iuser->ok==0)
2462                         return NULL;
2463         }
2464         else if (ima->ok==0)
2465                 return NULL;
2466         
2467         /* try to get the ibuf without locking */
2468         ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2469
2470         if (ibuf == NULL) {
2471                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2472                  * load the image */
2473                 BLI_lock_thread(LOCK_IMAGE);
2474
2475                 /* need to check ok flag and loading ibuf again, because the situation
2476                  * might have changed in the meantime */
2477                 if (iuser) {
2478                         if (iuser->ok==0) {
2479                                 BLI_unlock_thread(LOCK_IMAGE);
2480                                 return NULL;
2481                         }
2482                 }
2483                 else if (ima->ok==0) {
2484                         BLI_unlock_thread(LOCK_IMAGE);
2485                         return NULL;
2486                 }
2487
2488                 ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2489
2490                 if (ibuf == NULL) {
2491                         /* we are sure we have to load the ibuf, using source and type */
2492                         if (ima->source==IMA_SRC_MOVIE) {
2493                                 /* source is from single file, use flipbook to store ibuf */
2494                                 ibuf= image_load_movie_file(ima, iuser, frame);
2495                         }
2496                         else if (ima->source==IMA_SRC_SEQUENCE) {
2497                                 if (ima->type==IMA_TYPE_IMAGE) {
2498                                         /* regular files, ibufs in flipbook, allows saving */
2499                                         ibuf= image_load_sequence_file(ima, iuser, frame);
2500                                 }
2501                                 /* no else; on load the ima type can change */
2502                                 if (ima->type==IMA_TYPE_MULTILAYER) {
2503                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2504                                         ibuf= image_load_sequence_multilayer(ima, iuser, frame);
2505                                 }
2506                         }
2507                         else if (ima->source==IMA_SRC_FILE) {
2508                                 
2509                                 if (ima->type==IMA_TYPE_IMAGE)
2510                                         ibuf= image_load_image_file(ima, iuser, frame); /* cfra only for '#', this global is OK */
2511                                 /* no else; on load the ima type can change */
2512                                 if (ima->type==IMA_TYPE_MULTILAYER)
2513                                         /* keeps render result, stores ibufs in listbase, allows saving */
2514                                         ibuf= image_get_ibuf_multilayer(ima, iuser);
2515                                         
2516                         }
2517                         else if (ima->source == IMA_SRC_GENERATED) {
2518                                 /* generated is: ibuf is allocated dynamically */
2519                                 /* UV testgrid or black or solid etc */
2520                                 if (ima->gen_x==0) ima->gen_x= 1024;
2521                                 if (ima->gen_y==0) ima->gen_y= 1024;
2522                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, (ima->gen_flag & IMA_GEN_FLOAT) != 0, ima->gen_type, color);
2523                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2524                                 ima->ok= IMA_OK_LOADED;
2525                         }
2526                         else if (ima->source == IMA_SRC_VIEWER) {
2527                                 if (ima->type==IMA_TYPE_R_RESULT) {
2528                                         /* always verify entirely, and potentially
2529                                          * returns pointer to release later */
2530                                         ibuf= image_get_render_result(ima, iuser, lock_r);
2531                                 }
2532                                 else if (ima->type==IMA_TYPE_COMPOSITE) {
2533                                         /* requires lock/unlock, otherwise don't return image */
2534                                         if (lock_r) {
2535                                                 /* unlock in BKE_image_release_ibuf */
2536                                                 BLI_lock_thread(LOCK_VIEWER);
2537                                                 *lock_r= ima;
2538
2539                                                 /* XXX anim play for viewer nodes not yet supported */
2540                                                 frame= 0; // XXX iuser?iuser->framenr:0;
2541                                                 ibuf= image_get_ibuf(ima, 0, frame);
2542
2543                                                 if (!ibuf) {
2544                                                         /* Composite Viewer, all handled in compositor */
2545                                                         /* fake ibuf, will be filled in compositor */
2546                                                         ibuf= IMB_allocImBuf(256, 256, 32, IB_rect);
2547                                                         image_assign_ibuf(ima, ibuf, 0, frame);
2548                                                 }
2549                                         }
2550                                 }
2551                         }
2552                 }
2553
2554                 BLI_unlock_thread(LOCK_IMAGE);
2555         }
2556
2557         tag_image_time(ima);
2558
2559         return ibuf;
2560 }
2561
2562 void BKE_image_release_ibuf(Image *ima, void *lock)
2563 {
2564         /* for getting image during threaded render / compositing, need to release */
2565         if (lock == ima) {
2566                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2567         }
2568         else if (lock) {
2569                 RE_ReleaseResultImage(lock); /* render result */
2570                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2571         }
2572 }
2573
2574 /* warning, this can allocate generated images */
2575 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2576 {
2577         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2578         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2579 }
2580
2581 int BKE_image_user_get_frame(const ImageUser *iuser, int cfra, int fieldnr)
2582 {
2583         const int len= (iuser->fie_ima*iuser->frames)/2;
2584
2585         if (len==0) {
2586                 return 0;
2587         }
2588         else {
2589                 int framenr;
2590                 cfra= cfra - iuser->sfra+1;
2591
2592                 /* cyclic */
2593                 if (iuser->cycl) {
2594                         cfra= ( (cfra) % len );
2595                         if (cfra < 0) cfra+= len;
2596                         if (cfra==0) cfra= len;
2597                 }
2598
2599                 if (cfra<0) cfra= 0;
2600                 else if (cfra>len) cfra= len;
2601
2602                 /* convert current frame to current field */
2603                 cfra= 2*(cfra);
2604                 if (fieldnr) cfra++;
2605
2606                 /* transform to images space */
2607                 framenr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
2608                 if (framenr>iuser->frames) framenr= iuser->frames;
2609                 framenr+= iuser->offset;
2610
2611                 if (iuser->cycl) {
2612                         framenr= ( (framenr) % len );
2613                         while (framenr < 0) framenr+= len;
2614                         if (framenr==0) framenr= len;
2615                 }
2616
2617                 return framenr;
2618         }
2619 }
2620
2621 void BKE_image_user_calc_frame(ImageUser *iuser, int cfra, int fieldnr)
2622 {
2623         const int framenr= BKE_image_user_get_frame(iuser, cfra, fieldnr);
2624
2625         /* allows image users to handle redraws */
2626         if (iuser->flag & IMA_ANIM_ALWAYS)
2627                 if (framenr!=iuser->framenr)
2628                         iuser->flag |= IMA_ANIM_REFRESHED;
2629
2630         iuser->framenr= framenr;
2631         if (iuser->ok==0) iuser->ok= 1;
2632 }
2633
2634 int BKE_image_has_alpha(struct Image *image)
2635 {
2636         ImBuf *ibuf;
2637         void *lock;
2638         int planes;
2639         
2640         ibuf= BKE_image_acquire_ibuf(image, NULL, &lock);
2641         planes = (ibuf?ibuf->planes:0);
2642         BKE_image_release_ibuf(image, lock);
2643
2644         if (planes == 32)
2645                 return 1;
2646         else
2647                 return 0;
2648 }
2649