bugfix [#22638] Alpha channel not saved when using texture paint
[blender.git] / source / blender / blenkernel / intern / image.c
1 /*  image.c
2  * 
3  * $Id$
4  *
5  * ***** BEGIN GPL LICENSE BLOCK *****
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20  *
21  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
22  * All rights reserved.
23  *
24  * Contributor(s): Blender Foundation, 2006, full recode
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #include <stdio.h>
30 #include <string.h>
31 #include <fcntl.h>
32 #include <math.h>
33 #ifndef WIN32 
34 #include <unistd.h>
35 #else
36 #include <io.h>
37 #endif
38
39 #include <time.h>
40
41 #ifdef _WIN32
42 #define open _open
43 #define close _close
44 #endif
45
46 #include "MEM_guardedalloc.h"
47
48 #include "IMB_imbuf_types.h"
49 #include "IMB_imbuf.h"
50
51 #ifdef WITH_OPENEXR
52 #include "intern/openexr/openexr_multi.h"
53 #endif
54
55 #include "DNA_packedFile_types.h"
56 #include "DNA_scene_types.h"
57 #include "DNA_camera_types.h"
58 #include "DNA_sequence_types.h"
59 #include "DNA_userdef_types.h"
60
61 #include "BLI_blenlib.h"
62 #include "BLI_threads.h"
63
64 #include "BKE_bmfont.h"
65 #include "BKE_global.h"
66 #include "BKE_icons.h"
67 #include "BKE_image.h"
68 #include "BKE_library.h"
69 #include "BKE_main.h"
70 #include "BKE_packedFile.h"
71 #include "BKE_scene.h"
72 #include "BKE_node.h"
73
74 //XXX #include "BIF_editseq.h"
75
76 #include "BLF_api.h"
77
78 #include "PIL_time.h"
79
80 #include "RE_pipeline.h"
81
82 #include "GPU_draw.h"
83
84 #include "BLO_sys_types.h" // for intptr_t support
85
86 /* max int, to indicate we don't store sequences in ibuf */
87 #define IMA_NO_INDEX    0x7FEFEFEF
88
89 /* quick lookup: supports 1 million frames, thousand passes */
90 #define IMA_MAKE_INDEX(frame, index)    ((frame)<<10)+index
91 #define IMA_INDEX_FRAME(index)                  (index>>10)
92 #define IMA_INDEX_PASS(index)                   (index & ~1023)
93
94 /* ******** IMAGE PROCESSING ************* */
95
96 static void de_interlace_ng(struct ImBuf *ibuf) /* neogeo fields */
97 {
98         struct ImBuf * tbuf1, * tbuf2;
99         
100         if (ibuf == 0) return;
101         if (ibuf->flags & IB_fields) return;
102         ibuf->flags |= IB_fields;
103         
104         if (ibuf->rect) {
105                 /* make copies */
106                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
107                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
108                 
109                 ibuf->x *= 2;
110                 
111                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
112                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
113                 
114                 ibuf->x /= 2;
115                 IMB_rectcpy(ibuf, tbuf1, 0, 0, 0, 0, tbuf1->x, tbuf1->y);
116                 IMB_rectcpy(ibuf, tbuf2, 0, tbuf2->y, 0, 0, tbuf2->x, tbuf2->y);
117                 
118                 IMB_freeImBuf(tbuf1);
119                 IMB_freeImBuf(tbuf2);
120         }
121         ibuf->y /= 2;
122 }
123
124 static void de_interlace_st(struct ImBuf *ibuf) /* standard fields */
125 {
126         struct ImBuf * tbuf1, * tbuf2;
127         
128         if (ibuf == 0) return;
129         if (ibuf->flags & IB_fields) return;
130         ibuf->flags |= IB_fields;
131         
132         if (ibuf->rect) {
133                 /* make copies */
134                 tbuf1 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect);
135                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect);
136                 
137                 ibuf->x *= 2;
138                 
139                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
140                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
141                 
142                 ibuf->x /= 2;
143                 IMB_rectcpy(ibuf, tbuf2, 0, 0, 0, 0, tbuf2->x, tbuf2->y);
144                 IMB_rectcpy(ibuf, tbuf1, 0, tbuf2->y, 0, 0, tbuf1->x, tbuf1->y);
145                 
146                 IMB_freeImBuf(tbuf1);
147                 IMB_freeImBuf(tbuf2);
148         }
149         ibuf->y /= 2;
150 }
151
152 void image_de_interlace(Image *ima, int odd)
153 {
154         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
155         if(ibuf) {
156                 if(odd)
157                         de_interlace_st(ibuf);
158                 else
159                         de_interlace_ng(ibuf);
160         }
161 }
162
163 /* ***************** ALLOC & FREE, DATA MANAGING *************** */
164
165 static void image_free_buffers(Image *ima)
166 {
167         ImBuf *ibuf;
168         
169         while((ibuf = ima->ibufs.first)) {
170                 BLI_remlink(&ima->ibufs, ibuf);
171                 
172                 if (ibuf->userdata) {
173                         MEM_freeN(ibuf->userdata);
174                         ibuf->userdata = NULL;
175                 }
176                 IMB_freeImBuf(ibuf);
177         }
178         
179         if(ima->anim) IMB_free_anim(ima->anim);
180         ima->anim= NULL;
181
182         if(ima->rr) {
183                 RE_FreeRenderResult(ima->rr);
184                 ima->rr= NULL;
185         }       
186         
187         GPU_free_image(ima);
188         
189         ima->ok= IMA_OK;
190 }
191
192 /* called by library too, do not free ima itself */
193 void free_image(Image *ima)
194 {
195         int a;
196
197         image_free_buffers(ima);
198         if (ima->packedfile) {
199                 freePackedFile(ima->packedfile);
200                 ima->packedfile = NULL;
201         }
202         BKE_icon_delete(&ima->id);
203         ima->id.icon_id = 0;
204
205         BKE_previewimg_free(&ima->preview);
206
207         for(a=0; a<IMA_MAX_RENDER_SLOT; a++) {
208                 if(ima->renders[a]) {
209                         RE_FreeRenderResult(ima->renders[a]);
210                         ima->renders[a]= NULL;
211                 }
212         }
213 }
214
215 /* only image block itself */
216 static Image *image_alloc(const char *name, short source, short type)
217 {
218         Image *ima;
219         
220         ima= alloc_libblock(&G.main->image, ID_IM, name);
221         if(ima) {
222                 ima->ok= IMA_OK;
223                 
224                 ima->xrep= ima->yrep= 1;
225                 ima->aspx= ima->aspy= 1.0;
226                 ima->gen_x= 1024; ima->gen_y= 1024;
227                 ima->gen_type= 1;       /* no defines yet? */
228                 
229                 ima->source= source;
230                 ima->type= type;
231         }
232         return ima;
233 }
234
235 /* get the ibuf from an image cache, local use here only */
236 static ImBuf *image_get_ibuf(Image *ima, int index, int frame)
237 {
238         /* this function is intended to be thread safe. with IMA_NO_INDEX this
239          * should be OK, but when iterating over the list this is more tricky
240          * */
241         if(index==IMA_NO_INDEX)
242                 return ima->ibufs.first;
243         else {
244                 ImBuf *ibuf;
245
246                 index= IMA_MAKE_INDEX(frame, index);
247                 for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next)
248                         if(ibuf->index==index)
249                                 return ibuf;
250
251                 return NULL;
252         }
253 }
254
255 /* no ima->ibuf anymore, but listbase */
256 static void image_remove_ibuf(Image *ima, ImBuf *ibuf)
257 {
258         if(ibuf) {
259                 BLI_remlink(&ima->ibufs, ibuf);
260                 IMB_freeImBuf(ibuf);
261         }
262 }
263
264
265 /* no ima->ibuf anymore, but listbase */
266 static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int frame)
267 {
268         if(ibuf) {
269                 ImBuf *link;
270                 
271                 if(index!=IMA_NO_INDEX)
272                         index= IMA_MAKE_INDEX(frame, index);
273                 
274                 /* insert based on index */
275                 for(link= ima->ibufs.first; link; link= link->next)
276                         if(link->index>=index)
277                                 break;
278
279                 ibuf->index= index;
280
281                 /* this function accepts link==NULL */
282                 BLI_insertlinkbefore(&ima->ibufs, link, ibuf);
283
284                 /* now we don't want copies? */
285                 if(link && ibuf->index==link->index)
286                         image_remove_ibuf(ima, link);
287         }
288 }
289
290 /* empty image block, of similar type and filename */
291 Image *copy_image(Image *ima)
292 {
293         Image *nima= image_alloc(ima->id.name+2, ima->source, ima->type);
294
295         BLI_strncpy(nima->name, ima->name, sizeof(ima->name));
296
297         nima->flag= ima->flag;
298         nima->tpageflag= ima->tpageflag;
299         
300         nima->gen_x= ima->gen_x;
301         nima->gen_y= ima->gen_y;
302         nima->gen_type= ima->gen_type;
303
304         nima->animspeed= ima->animspeed;
305
306         nima->aspx= ima->aspx;
307         nima->aspy= ima->aspy;
308
309         return nima;
310 }
311
312 void BKE_image_merge(Image *dest, Image *source)
313 {
314         ImBuf *ibuf;
315         
316         /* sanity check */
317         if(dest && source && dest!=source) {
318         
319                 while((ibuf= source->ibufs.first)) {
320                         BLI_remlink(&source->ibufs, ibuf);
321                         image_assign_ibuf(dest, ibuf, IMA_INDEX_PASS(ibuf->index), IMA_INDEX_FRAME(ibuf->index));
322                 }
323                 
324                 free_libblock(&G.main->image, source);
325         }
326 }
327
328
329 /* checks if image was already loaded, then returns same image */
330 /* otherwise creates new. */
331 /* does not load ibuf itself */
332 /* pass on optional frame for #name images */
333 Image *BKE_add_image_file(const char *name)
334 {
335         Image *ima;
336         int file, len;
337         const char *libname;
338         char str[FILE_MAX], strtest[FILE_MAX];
339         
340         BLI_strncpy(str, name, sizeof(str));
341         BLI_path_abs(str, G.main->name);
342         
343         /* exists? */
344         file= open(str, O_BINARY|O_RDONLY);
345         if(file== -1) return NULL;
346         close(file);
347         
348         /* first search an identical image */
349         for(ima= G.main->image.first; ima; ima= ima->id.next) {
350                 if(ima->source!=IMA_SRC_VIEWER && ima->source!=IMA_SRC_GENERATED) {
351                         BLI_strncpy(strtest, ima->name, sizeof(ima->name));
352                         BLI_path_abs(strtest, G.main->name);
353                         
354                         if( strcmp(strtest, str)==0 ) {
355                                 if(ima->anim==NULL || ima->id.us==0) {
356                                         BLI_strncpy(ima->name, name, sizeof(ima->name));        /* for stringcode */
357                                         ima->id.us++;                                                                           /* officially should not, it doesn't link here! */
358                                         if(ima->ok==0)
359                                                 ima->ok= IMA_OK;
360                         /* RETURN! */
361                                         return ima;
362                                 }
363                         }
364                 }
365         }
366         /* add new image */
367         
368         /* create a short library name */
369         len= strlen(name);
370         
371         while (len > 0 && name[len - 1] != '/' && name[len - 1] != '\\') len--;
372         libname= name+len;
373         
374         ima= image_alloc(libname, IMA_SRC_FILE, IMA_TYPE_IMAGE);
375         BLI_strncpy(ima->name, name, sizeof(ima->name));
376         
377         /* do a wild guess! */
378         if(BLI_testextensie(name, ".avi") || BLI_testextensie(name, ".mov")
379                         || BLI_testextensie(name, ".mpg")  || BLI_testextensie(name, ".mp4"))
380                 ima->source= IMA_SRC_MOVIE;
381         
382         return ima;
383 }
384
385 static ImBuf *add_ibuf_size(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short uvtestgrid, float color[4])
386 {
387         ImBuf *ibuf;
388         unsigned char *rect= NULL;
389         float *rect_float= NULL;
390         
391         if (floatbuf) {
392                 ibuf= IMB_allocImBuf(width, height, depth, IB_rectfloat);
393                 rect_float= (float*)ibuf->rect_float;
394         }
395         else {
396                 ibuf= IMB_allocImBuf(width, height, depth, IB_rect);
397                 rect= (unsigned char*)ibuf->rect;
398         }
399         
400         BLI_strncpy(ibuf->name, name, sizeof(ibuf->name));
401         ibuf->userflags |= IB_BITMAPDIRTY;
402         
403         switch(uvtestgrid) {
404         case 1:
405                 BKE_image_buf_fill_checker(rect, rect_float, width, height);
406                 break;
407         case 2:
408                 BKE_image_buf_fill_checker_color(rect, rect_float, width, height);
409                 break;
410         default:
411                 BKE_image_buf_fill_color(rect, rect_float, width, height, color);
412         }
413
414         return ibuf;
415 }
416
417 /* adds new image block, creates ImBuf and initializes color */
418 Image *BKE_add_image_size(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short uvtestgrid, float color[4])
419 {
420         /* on save, type is changed to FILE in editsima.c */
421         Image *ima= image_alloc(name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
422         
423         if (ima) {
424                 ImBuf *ibuf;
425                 
426                 BLI_strncpy(ima->name, name, FILE_MAX);
427                 ima->gen_x= width;
428                 ima->gen_y= height;
429                 ima->gen_type= uvtestgrid;
430                 
431                 ibuf= add_ibuf_size(width, height, name, depth, floatbuf, uvtestgrid, color);
432                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
433                 
434                 ima->ok= IMA_OK_LOADED;
435         }
436
437         return ima;
438 }
439
440 /* creates an image image owns the imbuf passed */
441 Image *BKE_add_image_imbuf(ImBuf *ibuf)
442 {
443         /* on save, type is changed to FILE in editsima.c */
444         Image *ima;
445
446         ima= image_alloc(BLI_path_basename(ibuf->name), IMA_SRC_FILE, IMA_TYPE_IMAGE);
447
448         if (ima) {
449                 BLI_strncpy(ima->name, ibuf->name, FILE_MAX);
450                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
451                 ima->ok= IMA_OK_LOADED;
452         }
453
454         return ima;
455 }
456
457 /* packs rect from memory as PNG */
458 void BKE_image_memorypack(Image *ima)
459 {
460         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
461         
462         if(ibuf==NULL)
463                 return;
464         if (ima->packedfile) {
465                 freePackedFile(ima->packedfile);
466                 ima->packedfile = NULL;
467         }
468         
469         ibuf->ftype= PNG;
470         ibuf->depth= 32;
471         
472         IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem);
473         if(ibuf->encodedbuffer==NULL) {
474                 printf("memory save for pack error\n");
475         }
476         else {
477                 PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
478                 
479                 pf->data = ibuf->encodedbuffer;
480                 pf->size = ibuf->encodedsize;
481                 ima->packedfile= pf;
482                 ibuf->encodedbuffer= NULL;
483                 ibuf->encodedsize= 0;
484                 ibuf->userflags &= ~IB_BITMAPDIRTY;
485                 
486                 if(ima->source==IMA_SRC_GENERATED) {
487                         ima->source= IMA_SRC_FILE;
488                         ima->type= IMA_TYPE_IMAGE;
489                 }
490         }
491 }
492
493 void tag_image_time(Image *ima)
494 {
495         if (ima)
496                 ima->lastused = (int)PIL_check_seconds_timer();
497 }
498
499 #if 0
500 static void tag_all_images_time() 
501 {
502         Image *ima;
503         int ctime = (int)PIL_check_seconds_timer();
504
505         ima= G.main->image.first;
506         while(ima) {
507                 if(ima->bindcode || ima->repbind || ima->ibufs.first) {
508                         ima->lastused = ctime;
509                 }
510         }
511 }
512 #endif
513
514 void free_old_images()
515 {
516         Image *ima;
517         static int lasttime = 0;
518         int ctime = (int)PIL_check_seconds_timer();
519         
520         /* 
521            Run garbage collector once for every collecting period of time 
522            if textimeout is 0, that's the option to NOT run the collector
523         */
524         if (U.textimeout == 0 || ctime % U.texcollectrate || ctime == lasttime)
525                 return;
526
527         lasttime = ctime;
528
529         ima= G.main->image.first;
530         while(ima) {
531                 if((ima->flag & IMA_NOCOLLECT)==0 && ctime - ima->lastused > U.textimeout) {
532                         /*
533                            If it's in GL memory, deallocate and set time tag to current time
534                            This gives textures a "second chance" to be used before dying.
535                         */
536                         if(ima->bindcode || ima->repbind) {
537                                 GPU_free_image(ima);
538                                 ima->lastused = ctime;
539                         }
540                         /* Otherwise, just kill the buffers */
541                         else if (ima->ibufs.first) {
542                                 image_free_buffers(ima);
543                         }
544                 }
545                 ima = ima->id.next;
546         }
547 }
548
549 static uintptr_t image_mem_size(Image *ima)
550 {
551         ImBuf *ibuf, *ibufm;
552         int level;
553         uintptr_t size = 0;
554
555         size= 0;
556         
557         /* viewers have memory depending on other rules, has no valid rect pointer */
558         if(ima->source==IMA_SRC_VIEWER)
559                 return 0;
560         
561         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
562                 if(ibuf->rect) size += MEM_allocN_len(ibuf->rect);
563                 else if(ibuf->rect_float) size += MEM_allocN_len(ibuf->rect_float);
564
565                 for(level=0; level<IB_MIPMAP_LEVELS; level++) {
566                         ibufm= ibuf->mipmap[level];
567                         if(ibufm) {
568                                 if(ibufm->rect) size += MEM_allocN_len(ibufm->rect);
569                                 else if(ibufm->rect_float) size += MEM_allocN_len(ibufm->rect_float);
570                         }
571                 }
572         }
573
574         return size;
575 }
576
577 void BKE_image_print_memlist(void)
578 {
579         Image *ima;
580         uintptr_t size, totsize= 0;
581
582         for(ima= G.main->image.first; ima; ima= ima->id.next)
583                 totsize += image_mem_size(ima);
584
585         printf("\ntotal image memory len: %.3lf MB\n", (double)totsize/(double)(1024*1024));
586
587         for(ima= G.main->image.first; ima; ima= ima->id.next) {
588                 size= image_mem_size(ima);
589
590                 if(size)
591                         printf("%s len: %.3f MB\n", ima->id.name+2, (double)size/(double)(1024*1024));
592         }
593 }
594
595 void BKE_image_free_all_textures(void)
596 {
597         Tex *tex;
598         Image *ima;
599         /* unsigned int totsize= 0; */
600         
601         for(ima= G.main->image.first; ima; ima= ima->id.next)
602                 ima->id.flag &= ~LIB_DOIT;
603         
604         for(tex= G.main->tex.first; tex; tex= tex->id.next)
605                 if(tex->ima)
606                         tex->ima->id.flag |= LIB_DOIT;
607         
608         for(ima= G.main->image.first; ima; ima= ima->id.next) {
609                 if(ima->ibufs.first && (ima->id.flag & LIB_DOIT)) {
610                         /*
611                         ImBuf *ibuf;
612                         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
613                                 if(ibuf->mipmap[0]) 
614                                         totsize+= 1.33*ibuf->x*ibuf->y*4;
615                                 else
616                                         totsize+= ibuf->x*ibuf->y*4;
617                         } */
618                         image_free_buffers(ima);
619                 }
620         }
621         /* printf("freed total %d MB\n", totsize/(1024*1024)); */
622 }
623
624 /* except_frame is weak, only works for seqs without offset... */
625 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
626 {
627         ImBuf *ibuf, *nbuf;
628
629         for(ibuf= ima->ibufs.first; ibuf; ibuf= nbuf) {
630                 nbuf= ibuf->next;
631                 if(ibuf->userflags & IB_BITMAPDIRTY)
632                         continue;
633                 if(ibuf->index==IMA_NO_INDEX)
634                         continue;
635                 if(except_frame!=IMA_INDEX_FRAME(ibuf->index)) {
636                         BLI_remlink(&ima->ibufs, ibuf);
637                         
638                         if (ibuf->userdata) {
639                                 MEM_freeN(ibuf->userdata);
640                                 ibuf->userdata = NULL;
641                         }
642                         IMB_freeImBuf(ibuf);
643                 }                                       
644         }
645 }
646
647 void BKE_image_all_free_anim_ibufs(int cfra)
648 {
649         Image *ima;
650         
651         for(ima= G.main->image.first; ima; ima= ima->id.next)
652                 if(ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE))
653                         BKE_image_free_anim_ibufs(ima, cfra);
654 }
655
656
657 /* *********** READ AND WRITE ************** */
658
659 int BKE_imtype_to_ftype(int imtype)
660 {
661         if(imtype==0)
662                 return TGA;
663         else if(imtype== R_IRIS) 
664                 return IMAGIC;
665 #ifdef WITH_HDR
666         else if (imtype==R_RADHDR)
667                 return RADHDR;
668 #endif
669         else if (imtype==R_PNG)
670                 return PNG;
671 #ifdef WITH_DDS
672         else if (imtype==R_DDS)
673                 return DDS;
674 #endif
675         else if (imtype==R_BMP)
676                 return BMP;
677 #ifdef WITH_TIFF
678         else if (imtype==R_TIFF)
679                 return TIF;
680 #endif
681         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER)
682                 return OPENEXR;
683 #ifdef WITH_CINEON
684         else if (imtype==R_CINEON)
685                 return CINEON;
686         else if (imtype==R_DPX)
687                 return DPX;
688 #endif
689         else if (imtype==R_TARGA)
690                 return TGA;
691         else if(imtype==R_RAWTGA)
692                 return RAWTGA;
693 #ifdef WITH_OPENJPEG
694         else if(imtype==R_JP2)
695                 return JP2;
696 #endif
697         else
698                 return JPG|90;
699 }
700
701 int BKE_ftype_to_imtype(int ftype)
702 {
703         if(ftype==0)
704                 return TGA;
705         else if(ftype == IMAGIC) 
706                 return R_IRIS;
707 #ifdef WITH_HDR
708         else if (ftype & RADHDR)
709                 return R_RADHDR;
710 #endif
711         else if (ftype & PNG)
712                 return R_PNG;
713 #ifdef WITH_DDS
714         else if (ftype & DDS)
715                 return R_DDS;
716 #endif
717         else if (ftype & BMP)
718                 return R_BMP;
719 #ifdef WITH_TIFF
720         else if (ftype & TIF)
721                 return R_TIFF;
722 #endif
723         else if (ftype & OPENEXR)
724                 return R_OPENEXR;
725 #ifdef WITH_CINEON
726         else if (ftype & CINEON)
727                 return R_CINEON;
728         else if (ftype & DPX)
729                 return R_DPX;
730 #endif
731         else if (ftype & TGA)
732                 return R_TARGA;
733         else if(ftype & RAWTGA)
734                 return R_RAWTGA;
735 #ifdef WITH_OPENJPEG
736         else if(ftype & JP2)
737                 return R_JP2;
738 #endif
739         else
740                 return R_JPEG90;
741 }
742
743
744 int BKE_imtype_is_movie(int imtype)
745 {
746         switch(imtype) {
747         case R_AVIRAW:
748         case R_AVIJPEG:
749         case R_AVICODEC:
750         case R_QUICKTIME:
751         case R_FFMPEG:
752         case R_H264:
753         case R_THEORA:
754         case R_XVID:
755         case R_FRAMESERVER:
756                         return 1;
757         }
758         return 0;
759 }
760
761 int BKE_add_image_extension(char *string, int imtype)
762 {
763         char *extension= NULL;
764         
765         if(imtype== R_IRIS) {
766                 if(!BLI_testextensie(string, ".rgb"))
767                         extension= ".rgb";
768         }
769         else if(imtype==R_IRIZ) {
770                 if(!BLI_testextensie(string, ".rgb"))
771                         extension= ".rgb";
772         }
773 #ifdef WITH_HDR
774         else if(imtype==R_RADHDR) {
775                 if(!BLI_testextensie(string, ".hdr"))
776                         extension= ".hdr";
777         }
778 #endif
779         else if (ELEM5(imtype, R_PNG, R_FFMPEG, R_H264, R_THEORA, R_XVID)) {
780                 if(!BLI_testextensie(string, ".png"))
781                         extension= ".png";
782         }
783 #ifdef WITH_DDS
784         else if(imtype==R_DDS) {
785                 if(!BLI_testextensie(string, ".dds"))
786                         extension= ".dds";
787         }
788 #endif
789         else if(imtype==R_RAWTGA) {
790                 if(!BLI_testextensie(string, ".tga"))
791                         extension= ".tga";
792         }
793         else if(imtype==R_BMP) {
794                 if(!BLI_testextensie(string, ".bmp"))
795                         extension= ".bmp";
796         }
797 #ifdef WITH_TIFF
798         else if(imtype==R_TIFF) {
799                 if(!BLI_testextensie(string, ".tif") && 
800                         !BLI_testextensie(string, ".tiff")) extension= ".tif";
801         }
802 #endif
803 #ifdef WITH_OPENEXR
804         else if( ELEM(imtype, R_OPENEXR, R_MULTILAYER)) {
805                 if(!BLI_testextensie(string, ".exr"))
806                         extension= ".exr";
807         }
808 #endif
809 #ifdef WITH_CINEON
810         else if(imtype==R_CINEON){
811                 if (!BLI_testextensie(string, ".cin"))
812                         extension= ".cin";
813         }
814         else if(imtype==R_DPX){
815                 if (!BLI_testextensie(string, ".dpx"))
816                         extension= ".dpx";
817         }
818 #endif
819         else if(imtype==R_TARGA) {
820                 if(!BLI_testextensie(string, ".tga"))
821                         extension= ".tga";
822         }
823 #ifdef WITH_OPENJPEG
824         else if(imtype==R_JP2) {
825                 if(!BLI_testextensie(string, ".jp2"))
826                         extension= ".jp2";
827         }
828 #endif
829         else { //   R_AVICODEC, R_AVIRAW, R_AVIJPEG, R_JPEG90, R_QUICKTIME etc
830                 if(!( BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
831                         extension= ".jpg";
832         }
833
834         if(extension) {
835                 /* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */
836                 /* return BLI_replace_extension(string, FILE_MAX, extension); */
837                 strcat(string, extension);
838                 return TRUE;
839         }
840         else {
841                 return FALSE;
842         }
843 }
844
845 /* could allow access externally - 512 is for long names, 64 is for id names */
846 typedef struct StampData {
847         char    file[512];
848         char    note[512];
849         char    date[512];
850         char    marker[512];
851         char    time[512];
852         char    frame[512];
853         char    camera[64];
854         char    scene[64];
855         char    strip[64];
856         char    rendertime[64];
857 } StampData;
858
859 static void stampdata(Scene *scene, StampData *stamp_data, int do_prefix)
860 {
861         char text[256];
862         struct tm *tl;
863         time_t t;
864
865         if (scene->r.stamp & R_STAMP_FILENAME) {
866                 if (G.relbase_valid) {
867                         if (do_prefix)          sprintf(stamp_data->file, "File %s", G.main->name);
868                         else                            sprintf(stamp_data->file, "%s", G.main->name);
869                 } else {
870                         if (do_prefix)          strcpy(stamp_data->file, "File <untitled>");
871                         else                            strcpy(stamp_data->file, "<untitled>");
872                 }
873         } else {
874                 stamp_data->file[0] = '\0';
875         }
876         
877         if (scene->r.stamp & R_STAMP_NOTE) {
878                 /* Never do prefix for Note */
879                 sprintf(stamp_data->note, "%s", scene->r.stamp_udata);
880         } else {
881                 stamp_data->note[0] = '\0';
882         }
883         
884         if (scene->r.stamp & R_STAMP_DATE) {
885
886                 t = time (NULL);
887                 tl = localtime (&t);
888                 sprintf (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);
889
890                 if (do_prefix)          sprintf(stamp_data->date, "Date %s", text);
891                 else                            sprintf(stamp_data->date, "%s", text);
892         } else {
893                 stamp_data->date[0] = '\0';
894         }
895         
896         if (scene->r.stamp & R_STAMP_MARKER) {
897                 char *name = scene_find_last_marker_name(scene, CFRA);
898         
899                 if (name)       strcpy(text, name);
900                 else            strcpy(text, "<none>");
901                 
902                 if (do_prefix)          sprintf(stamp_data->marker, "Marker %s", text);
903                 else                            sprintf(stamp_data->marker, "%s", text);
904         } else {
905                 stamp_data->marker[0] = '\0';
906         }
907         
908         if (scene->r.stamp & R_STAMP_TIME) {
909                 int h, m, s, f;
910                 h= m= s= f= 0;
911                 f = (int)(scene->r.cfra % scene->r.frs_sec);
912                 s = (int)(scene->r.cfra / scene->r.frs_sec);
913
914                 if (s) {
915                         m = (int)(s / 60);
916                         s %= 60;
917
918                         if (m) {
919                                 h = (int)(m / 60);
920                                 m %= 60;
921                         }
922                 }
923
924                 if (scene->r.frs_sec < 100)
925                         sprintf (text, "%02d:%02d:%02d.%02d", h, m, s, f);
926                 else
927                         sprintf (text, "%02d:%02d:%02d.%03d", h, m, s, f);
928                 
929                 if (do_prefix)          sprintf(stamp_data->time, "Time %s", text);
930                 else                            sprintf(stamp_data->time, "%s", text);
931         } else {
932                 stamp_data->time[0] = '\0';
933         }
934         
935         if (scene->r.stamp & R_STAMP_FRAME) {
936                 char format[32];
937                 if (do_prefix)          sprintf(format, "Frame %%0%di", 1 + (int) log10(scene->r.efra));
938                 else                            sprintf(format, "%%0%di", 1 + (int) log10(scene->r.efra));
939                 sprintf (stamp_data->frame, format, scene->r.cfra);
940         } else {
941                 stamp_data->frame[0] = '\0';
942         }
943
944         if (scene->r.stamp & R_STAMP_CAMERA) {
945                 if (scene->camera) strcpy(text, ((Camera *) scene->camera)->id.name+2);
946                 else            strcpy(text, "<none>");
947                 
948                 if (do_prefix)          sprintf(stamp_data->camera, "Camera %s", text);
949                 else                            sprintf(stamp_data->camera, "%s", text);
950         } else {
951                 stamp_data->camera[0] = '\0';
952         }
953
954         if (scene->r.stamp & R_STAMP_SCENE) {
955                 if (do_prefix)          sprintf(stamp_data->scene, "Scene %s", scene->id.name+2);
956                 else                            sprintf(stamp_data->scene, "%s", scene->id.name+2);
957         } else {
958                 stamp_data->scene[0] = '\0';
959         }
960         
961         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
962                 Sequence *seq= NULL; //XXX = get_foreground_frame_seq(scene->r.cfra);
963         
964                 if (seq) strcpy(text, seq->name+2);
965                 else            strcpy(text, "<none>");
966                 
967                 if (do_prefix)          sprintf(stamp_data->strip, "Strip %s", text);
968                 else                            sprintf(stamp_data->strip, "%s", text);
969         } else {
970                 stamp_data->strip[0] = '\0';
971         }
972
973         {
974                 Render *re= RE_GetRender(scene->id.name);
975                 RenderStats *stats= re ? RE_GetStats(re):NULL;
976
977                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
978                         BLI_timestr(stats->lastframetime, text);
979
980                         if (do_prefix)          sprintf(stamp_data->rendertime, "RenderTime %s", text);
981                         else                            sprintf(stamp_data->rendertime, "%s", text);
982                 } else {
983                         stamp_data->rendertime[0] = '\0';
984                 }
985         }
986 }
987
988 void BKE_stamp_buf(Scene *scene, unsigned char *rect, float *rectf, int width, int height, int channels)
989 {
990         struct StampData stamp_data;
991         float w, h, pad;
992         int x, y;
993         float h_fixed;
994         const int mono= blf_mono_font_render; // XXX
995         
996         if (!rect && !rectf)
997                 return;
998         
999         stampdata(scene, &stamp_data, 1);
1000
1001         /* TODO, do_versions */
1002         if(scene->r.stamp_font_id < 8)
1003                 scene->r.stamp_font_id= 12;
1004
1005         /* set before return */
1006         BLF_aspect(mono, 1.0);
1007         BLF_size(mono, scene->r.stamp_font_id, 72);
1008         
1009         BLF_buffer(mono, rectf, rect, width, height, channels);
1010         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1011         pad= BLF_width(mono, "--");
1012
1013         /* use 'h_fixed' rather then 'h', aligns better */
1014         // BLF_width_and_height(mono, "^|/_AgPpJjlYy", &w, &h_fixed);
1015         {
1016                 rctf box;
1017                 BLF_boundbox(mono, "^|/_AgPpJjlYy", &box);
1018                 h_fixed= box.ymax - box.ymin;
1019         }
1020
1021         x= 0;
1022         y= height;
1023
1024         if (stamp_data.file[0]) {
1025                 /* Top left corner */
1026                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h= h_fixed;
1027                 y -= h;
1028
1029                 /* also a little of space to the background. */
1030                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y-3, w+3, y+h+2);
1031
1032                 /* and draw the text. */
1033                 BLF_position(mono, x, y, 0.0);
1034                 BLF_draw_buffer(mono, stamp_data.file);
1035
1036                 /* the extra pixel for background. */
1037                 y -= 4;
1038         }
1039
1040         /* Top left corner, below File */
1041         if (stamp_data.note[0]) {
1042                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h= h_fixed;
1043                 y -= h;
1044
1045                 /* and space for background. */
1046                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-3, w+3, y+h+2);
1047
1048                 BLF_position(mono, x, y+1, 0.0);
1049                 BLF_draw_buffer(mono, stamp_data.note);
1050
1051                 /* the extra pixel for background. */
1052                 y -= 4;
1053         }
1054         
1055         /* Top left corner, below File (or Note) */
1056         if (stamp_data.date[0]) {
1057                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h= h_fixed;
1058                 y -= h;
1059
1060                 /* and space for background. */
1061                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-3, w+3, y+h+2);
1062
1063                 BLF_position(mono, x, y, 0.0);
1064                 BLF_draw_buffer(mono, stamp_data.date);
1065
1066                 /* the extra pixel for background. */
1067                 y -= 4;
1068         }
1069
1070         /* Top left corner, below File, Date or Note */
1071         if (stamp_data.rendertime[0]) {
1072                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h= h_fixed;
1073                 y -= h;
1074
1075                 /* and space for background. */
1076                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-3, w+3, y+h+2);
1077
1078                 BLF_position(mono, x, y, 0.0);
1079                 BLF_draw_buffer(mono, stamp_data.rendertime);
1080         }
1081
1082         x= 0;
1083         y= 0;
1084
1085         /* Bottom left corner, leaving space for timing */
1086         if (stamp_data.marker[0]) {
1087                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h= h_fixed;
1088
1089                 /* extra space for background. */
1090                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, w+2, y+h+2);
1091
1092                 /* and pad the text. */
1093                 BLF_position(mono, x, y+3, 0.0);
1094                 BLF_draw_buffer(mono, stamp_data.marker);
1095
1096                 /* space width. */
1097                 x += w + pad;
1098         }
1099         
1100         /* Left bottom corner */
1101         if (stamp_data.time[0]) {
1102                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h= h_fixed;
1103
1104                 /* extra space for background */
1105                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+2);
1106
1107                 /* and pad the text. */
1108                 BLF_position(mono, x, y+3, 0.0);
1109                 BLF_draw_buffer(mono, stamp_data.time);
1110
1111                 /* space width. */
1112                 x += w + pad;
1113         }
1114         
1115         if (stamp_data.frame[0]) {
1116                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h= h_fixed;
1117
1118                 /* extra space for background. */
1119                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+2);
1120
1121                 /* and pad the text. */
1122                 BLF_position(mono, x, y+3, 0.0);
1123                 BLF_draw_buffer(mono, stamp_data.frame);
1124
1125                 /* space width. */
1126                 x += w + pad;
1127         }
1128
1129         if (stamp_data.camera[0]) {
1130                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h= h_fixed;
1131
1132                 /* extra space for background. */
1133                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+2);
1134                 BLF_position(mono, x, y+3, 0.0);
1135                 BLF_draw_buffer(mono, stamp_data.camera);
1136         }
1137         
1138         if (stamp_data.scene[0]) {
1139                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h= h_fixed;
1140
1141                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1142                 x= width - w - 2;
1143
1144                 /* extra space for background. */
1145                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+3, y+h+2);
1146
1147                 /* and pad the text. */
1148                 BLF_position(mono, x, y+3, 0.0);
1149                 BLF_draw_buffer(mono, stamp_data.scene);
1150         }
1151         
1152         if (stamp_data.strip[0]) {
1153                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h= h_fixed;
1154
1155                 /* Top right corner, with an extra space because blenfont is too strict! */
1156                 x= width - w - pad;
1157                 y= height - h;
1158
1159                 /* extra space for background. */
1160                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y-3, x+w+pad, y+h+2);
1161
1162                 BLF_position(mono, x, y, 0.0);
1163                 BLF_draw_buffer(mono, stamp_data.strip);
1164         }
1165
1166         /* cleanup the buffer. */
1167         BLF_buffer(mono, NULL, NULL, 0, 0, 0);
1168 }
1169
1170 void BKE_stamp_info(Scene *scene, struct ImBuf *ibuf)
1171 {
1172         struct StampData stamp_data;
1173
1174         if (!ibuf)      return;
1175         
1176         /* fill all the data values, no prefix */
1177         stampdata(scene, &stamp_data, 0);
1178         
1179         if (stamp_data.file[0])         IMB_metadata_change_field (ibuf, "File",                stamp_data.file);
1180         if (stamp_data.note[0])         IMB_metadata_change_field (ibuf, "Note",                stamp_data.note);
1181         if (stamp_data.date[0])         IMB_metadata_change_field (ibuf, "Date",                stamp_data.date);
1182         if (stamp_data.marker[0])       IMB_metadata_change_field (ibuf, "Marker",      stamp_data.marker);
1183         if (stamp_data.time[0])         IMB_metadata_change_field (ibuf, "Time",                stamp_data.time);
1184         if (stamp_data.frame[0])        IMB_metadata_change_field (ibuf, "Frame",       stamp_data.frame);
1185         if (stamp_data.camera[0])       IMB_metadata_change_field (ibuf, "Camera",      stamp_data.camera);
1186         if (stamp_data.scene[0])        IMB_metadata_change_field (ibuf, "Scene",       stamp_data.scene);
1187         if (stamp_data.strip[0])        IMB_metadata_change_field (ibuf, "Strip",       stamp_data.strip);
1188         if (stamp_data.rendertime[0]) IMB_metadata_change_field (ibuf, "RenderTime", stamp_data.rendertime);
1189 }
1190
1191 int BKE_alphatest_ibuf(ImBuf *ibuf)
1192 {
1193         int tot;
1194         if(ibuf->rect_float) {
1195                 float *buf= ibuf->rect_float;
1196                 for(tot= ibuf->x * ibuf->y; tot--; buf+=4) {
1197                         if(buf[3] < 1.0f) {
1198                                 return TRUE;
1199                         }
1200                 }
1201         }
1202         else if (ibuf->rect) {
1203                 unsigned char *buf= (unsigned char *)ibuf->rect;
1204                 for(tot= ibuf->x * ibuf->y; tot--; buf+=4) {
1205                         if(buf[3] != 255) {
1206                                 return TRUE;
1207                         }
1208                 }
1209         }
1210
1211         return FALSE;
1212 }
1213
1214 int BKE_write_ibuf(Scene *scene, ImBuf *ibuf, const char *name, int imtype, int subimtype, int quality)
1215 {
1216         int ok;
1217         (void)subimtype; /* quies unused warnings */
1218
1219         if(imtype==0) {
1220                 /* pass */
1221         }
1222         else if(imtype== R_IRIS) {
1223                 ibuf->ftype= IMAGIC;
1224         }
1225 #ifdef WITH_HDR
1226         else if ((imtype==R_RADHDR)) {
1227                 ibuf->ftype= RADHDR;
1228         }
1229 #endif
1230         else if (ELEM5(imtype, R_PNG, R_FFMPEG, R_H264, R_THEORA, R_XVID)) {
1231                 ibuf->ftype= PNG;
1232
1233                 if(imtype==R_PNG)
1234                         ibuf->ftype |= quality;  /* quality is actually compression 0-100 --> 0-9 */
1235
1236         }
1237 #ifdef WITH_DDS
1238         else if ((imtype==R_DDS)) {
1239                 ibuf->ftype= DDS;
1240         }
1241 #endif
1242         else if ((imtype==R_BMP)) {
1243                 ibuf->ftype= BMP;
1244         }
1245 #ifdef WITH_TIFF
1246         else if (imtype==R_TIFF) {
1247                 ibuf->ftype= TIF;
1248
1249                 if(subimtype & R_TIFF_16BIT)
1250                         ibuf->ftype |= TIF_16BIT;
1251         }
1252 #endif
1253 #ifdef WITH_OPENEXR
1254         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
1255                 ibuf->ftype= OPENEXR;
1256                 if(subimtype & R_OPENEXR_HALF)
1257                         ibuf->ftype |= OPENEXR_HALF;
1258                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
1259                 
1260                 if(!(subimtype & R_OPENEXR_ZBUF))
1261                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1262                 
1263         }
1264 #endif
1265 #ifdef WITH_CINEON
1266         else if (imtype==R_CINEON) {
1267                 ibuf->ftype = CINEON;
1268         }
1269         else if (imtype==R_DPX) {
1270                 ibuf->ftype = DPX;
1271         }
1272 #endif
1273         else if (imtype==R_TARGA) {
1274                 ibuf->ftype= TGA;
1275         }
1276         else if(imtype==R_RAWTGA) {
1277                 ibuf->ftype= RAWTGA;
1278         }
1279 #ifdef WITH_OPENJPEG
1280         else if(imtype==R_JP2) {
1281                 if(quality < 10) quality= 90;
1282                 ibuf->ftype= JP2|quality;
1283                 
1284                 if (subimtype & R_JPEG2K_16BIT) {
1285                         ibuf->ftype |= JP2_16BIT;
1286                 } else if (subimtype & R_JPEG2K_12BIT) {
1287                         ibuf->ftype |= JP2_12BIT;
1288                 }
1289                 
1290                 if (subimtype & R_JPEG2K_YCC) {
1291                         ibuf->ftype |= JP2_YCC;
1292                 }
1293                 
1294                 if (subimtype & R_JPEG2K_CINE_PRESET) {
1295                         ibuf->ftype |= JP2_CINE;
1296                         if (subimtype & R_JPEG2K_CINE_48FPS)
1297                                 ibuf->ftype |= JP2_CINE_48FPS;
1298                 }
1299         }
1300 #endif
1301         else {
1302                 /* R_JPEG90, etc. default we save jpegs */
1303                 if(quality < 10) quality= 90;
1304                 ibuf->ftype= JPG|quality;
1305                 if(ibuf->depth==32) ibuf->depth= 24;    /* unsupported feature only confuses other s/w */
1306         }
1307         
1308         BLI_make_existing_file(name);
1309
1310         if(scene && scene->r.stamp & R_STAMP_ALL)
1311                 BKE_stamp_info(scene, ibuf);
1312         
1313         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1314         if (ok == 0) {
1315                 perror(name);
1316         }
1317         
1318         return(ok);
1319 }
1320
1321
1322 void BKE_makepicstring(char *string, const char *base, int frame, int imtype, const short use_ext, const short use_frames)
1323 {
1324         if (string==NULL) return;
1325         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1326         BLI_path_abs(string, G.main->name);
1327
1328         if(use_frames)
1329                 BLI_path_frame(string, frame, 4);
1330
1331         if(use_ext)
1332                 BKE_add_image_extension(string, imtype);
1333                 
1334 }
1335
1336 /* used by sequencer too */
1337 struct anim *openanim(char *name, int flags)
1338 {
1339         struct anim *anim;
1340         struct ImBuf *ibuf;
1341         
1342         anim = IMB_open_anim(name, flags);
1343         if (anim == NULL) return(0);
1344
1345         ibuf = IMB_anim_absolute(anim, 0);
1346         if (ibuf == NULL) {
1347                 if(BLI_exists(name))
1348                         printf("not an anim: %s\n", name);
1349                 else
1350                         printf("anim file doesn't exist: %s\n", name);
1351                 IMB_free_anim(anim);
1352                 return(0);
1353         }
1354         IMB_freeImBuf(ibuf);
1355         
1356         return(anim);
1357 }
1358
1359 /* ************************* New Image API *************** */
1360
1361
1362 /* Notes about Image storage 
1363 - packedfile
1364   -> written in .blend
1365 - filename
1366   -> written in .blend
1367 - movie
1368   -> comes from packedfile or filename
1369 - renderresult
1370   -> comes from packedfile or filename
1371 - listbase
1372   -> ibufs from exrhandle
1373 - flipbook array
1374   -> ibufs come from movie, temporary renderresult or sequence
1375 - ibuf
1376   -> comes from packedfile or filename or generated
1377
1378 */
1379
1380
1381 /* forces existence of 1 Image for renderout or nodes, returns Image */
1382 /* name is only for default, when making new one */
1383 Image *BKE_image_verify_viewer(int type, const char *name)
1384 {
1385         Image *ima;
1386         
1387         for(ima=G.main->image.first; ima; ima= ima->id.next)
1388                 if(ima->source==IMA_SRC_VIEWER)
1389                         if(ima->type==type)
1390                                 break;
1391         
1392         if(ima==NULL)
1393                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1394         
1395         /* happens on reload, imagewindow cannot be image user when hidden*/
1396         if(ima->id.us==0)
1397                 id_us_plus(&ima->id);
1398
1399         return ima;
1400 }
1401
1402 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1403 {
1404         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1405 }
1406
1407 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1408 {
1409         if(ima==NULL)
1410                 return;
1411         
1412         switch(signal) {
1413         case IMA_SIGNAL_FREE:
1414                 image_free_buffers(ima);
1415                 if(iuser)
1416                         iuser->ok= 1;
1417                 break;
1418         case IMA_SIGNAL_SRC_CHANGE:
1419                 if(ima->type == IMA_TYPE_UV_TEST)
1420                         if(ima->source != IMA_SRC_GENERATED)
1421                                 ima->type= IMA_TYPE_IMAGE;
1422
1423                 if(ima->source==IMA_SRC_GENERATED) {
1424                         if(ima->gen_x==0 || ima->gen_y==0) {
1425                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1426                                 if(ibuf) {
1427                                         ima->gen_x= ibuf->x;
1428                                         ima->gen_y= ibuf->y;
1429                                 }
1430                         }
1431                 }
1432
1433                 image_free_buffers(ima);
1434
1435                 ima->ok= 1;
1436                 if(iuser)
1437                         iuser->ok= 1;
1438                 break;
1439                         
1440         case IMA_SIGNAL_RELOAD:
1441                 /* try to repack file */
1442                 if(ima->packedfile) {
1443                         PackedFile *pf;
1444                         pf = newPackedFile(NULL, ima->name);
1445                         if (pf) {
1446                                 freePackedFile(ima->packedfile);
1447                                 ima->packedfile = pf;
1448                                 image_free_buffers(ima);
1449                         } else {
1450                                 printf("ERROR: Image not available. Keeping packed image\n");
1451                         }
1452                 }
1453                 else
1454                         image_free_buffers(ima);
1455                 
1456                 if(iuser)
1457                         iuser->ok= 1;
1458                 
1459                 break;
1460         case IMA_SIGNAL_USER_NEW_IMAGE:
1461                 if(iuser) {
1462                         iuser->ok= 1;
1463                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1464                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1465                                         iuser->multi_index= 0;
1466                                         iuser->layer= iuser->pass= 0;
1467                                 }
1468                         }
1469                 }
1470                 break;
1471         }
1472         
1473         /* dont use notifiers because they are not 100% sure to succseed
1474          * this also makes sure all scenes are accounted for. */
1475         {
1476                 Scene *scene;
1477                 for(scene= G.main->scene.first; scene; scene= scene->id.next) {
1478                         if(scene->nodetree) {
1479                                 NodeTagIDChanged(scene->nodetree, &ima->id);
1480                         }
1481                 }
1482         }
1483 }
1484
1485 /* if layer or pass changes, we need an index for the imbufs list */
1486 /* note it is called for rendered results, but it doesnt use the index! */
1487 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1488 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1489 {
1490         RenderLayer *rl;
1491         RenderPass *rpass= NULL;
1492         
1493         if(rr==NULL) 
1494                 return NULL;
1495         
1496         if(iuser) {
1497                 short index= 0, rl_index= 0, rp_index;
1498                 
1499                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1500                         rp_index= 0;
1501                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1502                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1503                                         break;
1504                         if(rpass)
1505                                 break;
1506                 }
1507                 
1508                 if(rpass)
1509                         iuser->multi_index= index;
1510                 else 
1511                         iuser->multi_index= 0;
1512         }
1513         if(rpass==NULL) {
1514                 rl= rr->layers.first;
1515                 if(rl)
1516                         rpass= rl->passes.first;
1517         }
1518         
1519         return rpass;
1520 }
1521
1522 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
1523 {
1524         if(ima->rr) {
1525                 return ima->rr;
1526         }
1527         else if(ima->type==IMA_TYPE_R_RESULT) {
1528                 if(ima->render_slot == ima->last_render_slot)
1529                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
1530                 else
1531                         return ima->renders[ima->render_slot];
1532         }
1533         else
1534                 return NULL;
1535 }
1536
1537 void BKE_image_release_renderresult(Scene *scene, Image *ima)
1538 {
1539         if(ima->rr);
1540         else if(ima->type==IMA_TYPE_R_RESULT) {
1541                 if(ima->render_slot == ima->last_render_slot)
1542                         RE_ReleaseResult(RE_GetRender(scene->id.name));
1543         }
1544 }
1545
1546 void BKE_image_backup_render(Scene *scene, Image *ima)
1547 {
1548         /* called right before rendering, ima->renders contains render
1549            result pointers for everything but the current render */
1550         Render *re= RE_GetRender(scene->id.name);
1551         int slot= ima->render_slot, last= ima->last_render_slot;
1552
1553         if(slot != last) {
1554                 if(ima->renders[slot]) {
1555                         RE_FreeRenderResult(ima->renders[slot]);
1556                         ima->renders[slot]= NULL;
1557                 }
1558
1559                 ima->renders[last]= NULL;
1560                 RE_SwapResult(re, &ima->renders[last]);
1561         }
1562
1563         ima->last_render_slot= slot;
1564 }
1565
1566 /* after imbuf load, openexr type can return with a exrhandle open */
1567 /* in that case we have to build a render-result */
1568 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1569 {
1570         
1571         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1572
1573 #ifdef WITH_OPENEXR
1574         IMB_exr_close(ibuf->userdata);
1575 #endif
1576
1577         ibuf->userdata= NULL;
1578         if(ima->rr)
1579                 ima->rr->framenr= framenr;
1580 }
1581
1582 /* common stuff to do with images after loading */
1583 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1584 {
1585         /* preview is NULL when it has never been used as an icon before */
1586         if(G.background==0 && ima->preview==NULL)
1587                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1588
1589         /* fields */
1590         if (ima->flag & IMA_FIELDS) {
1591                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1592                 else de_interlace_ng(ibuf);
1593         }
1594         /* timer */
1595         ima->lastused = clock() / CLOCKS_PER_SEC;
1596         
1597         ima->ok= IMA_OK_LOADED;
1598         
1599 }
1600
1601 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1602 {
1603         struct ImBuf *ibuf;
1604         unsigned short numlen;
1605         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1606         int flag;
1607         
1608         /* XXX temp stuff? */
1609         if(ima->lastframe != frame)
1610                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1611
1612         ima->lastframe= frame;
1613         BLI_strncpy(name, ima->name, sizeof(name));
1614         BLI_stringdec(name, head, tail, &numlen);
1615         BLI_stringenc(name, head, tail, numlen, frame);
1616
1617         if(ima->id.lib)
1618                 BLI_path_abs(name, ima->id.lib->filepath);
1619         else
1620                 BLI_path_abs(name, G.main->name);
1621         
1622         flag= IB_rect|IB_multilayer;
1623         if(ima->flag & IMA_DO_PREMUL)
1624                 flag |= IB_premul;
1625
1626         /* read ibuf */
1627         ibuf = IMB_loadiffname(name, flag);
1628         if(G.f & G_DEBUG) printf("loaded %s\n", name);
1629         
1630         if (ibuf) {
1631 #ifdef WITH_OPENEXR
1632                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1633                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1634                         image_create_multilayer(ima, ibuf, frame);      
1635                         ima->type= IMA_TYPE_MULTILAYER;
1636                         IMB_freeImBuf(ibuf);
1637                         ibuf= NULL;
1638                 }
1639                 else {
1640                         image_initialize_after_load(ima, ibuf);
1641                         image_assign_ibuf(ima, ibuf, 0, frame);
1642                 }
1643 #else
1644                 image_initialize_after_load(ima, ibuf);
1645                 image_assign_ibuf(ima, ibuf, 0, frame);
1646 #endif
1647         }
1648         else
1649                 ima->ok= 0;
1650         
1651         if(iuser)
1652                 iuser->ok= ima->ok;
1653         
1654         return ibuf;
1655 }
1656
1657 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1658 {
1659         struct ImBuf *ibuf= NULL;
1660         
1661         /* either we load from RenderResult, or we have to load a new one */
1662         
1663         /* check for new RenderResult */
1664         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1665                 /* copy to survive not found multilayer image */
1666                 RenderResult *oldrr= ima->rr;
1667         
1668                 ima->rr= NULL;
1669                 ibuf = image_load_sequence_file(ima, iuser, frame);
1670                 
1671                 if(ibuf) { /* actually an error */
1672                         ima->type= IMA_TYPE_IMAGE;
1673                         printf("error, multi is normal image\n");
1674                 }
1675                 // printf("loaded new result %p\n", ima->rr);
1676                 /* free result if new one found */
1677                 if(ima->rr) {
1678                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1679                         if(oldrr) RE_FreeRenderResult(oldrr);
1680                 }
1681                 else {
1682                         ima->rr= oldrr;
1683                 }
1684
1685         }
1686         if(ima->rr) {
1687                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1688                 
1689                 if(rpass) {
1690                         // printf("load from pass %s\n", rpass->name);
1691                         /* since we free  render results, we copy the rect */
1692                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
1693                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1694                         ibuf->flags |= IB_rectfloat;
1695                         ibuf->mall= IB_rectfloat;
1696                         ibuf->channels= rpass->channels;
1697                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1698                         
1699                         image_initialize_after_load(ima, ibuf);
1700                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
1701                         
1702                 }
1703                 // else printf("pass not found\n");
1704         }
1705         else
1706                 ima->ok= 0;
1707         
1708         if(iuser)
1709                 iuser->ok= ima->ok;
1710         
1711         return ibuf;
1712 }
1713
1714
1715 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
1716 {
1717         struct ImBuf *ibuf= NULL;
1718         
1719         ima->lastframe= frame;
1720         
1721         if(ima->anim==NULL) {
1722                 char str[FILE_MAX];
1723                 
1724                 BLI_strncpy(str, ima->name, FILE_MAX);
1725                 if(ima->id.lib)
1726                         BLI_path_abs(str, ima->id.lib->filepath);
1727                 else
1728                         BLI_path_abs(str, G.main->name);
1729                 
1730                 ima->anim = openanim(str, IB_rect);
1731                 
1732                 /* let's initialize this user */
1733                 if(ima->anim && iuser && iuser->frames==0)
1734                         iuser->frames= IMB_anim_get_duration(ima->anim);
1735         }
1736         
1737         if(ima->anim) {
1738                 int dur = IMB_anim_get_duration(ima->anim);
1739                 int fra= frame-1;
1740                 
1741                 if(fra<0) fra = 0;
1742                 if(fra>(dur-1)) fra= dur-1;
1743                 ibuf = IMB_anim_absolute(ima->anim, fra);
1744                 
1745                 if(ibuf) {
1746                         image_initialize_after_load(ima, ibuf);
1747                         image_assign_ibuf(ima, ibuf, 0, frame);
1748                 }
1749                 else
1750                         ima->ok= 0;
1751         }
1752         else
1753                 ima->ok= 0;
1754         
1755         if(iuser)
1756                 iuser->ok= ima->ok;
1757         
1758         return ibuf;
1759 }
1760
1761 /* warning, 'iuser' can be NULL */
1762 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
1763 {
1764         struct ImBuf *ibuf;
1765         char str[FILE_MAX];
1766         int assign = 0, flag;
1767         
1768         /* always ensure clean ima */
1769         image_free_buffers(ima);
1770         
1771         /* is there a PackedFile with this image ? */
1772         if (ima->packedfile) {
1773                 flag = IB_rect|IB_multilayer;
1774                 if(ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
1775                 
1776                 ibuf = IMB_ibImageFromMemory((unsigned char*)ima->packedfile->data, ima->packedfile->size, flag);
1777         } 
1778         else {
1779                 flag= IB_rect|IB_multilayer|IB_metadata;
1780                 if(ima->flag & IMA_DO_PREMUL)
1781                         flag |= IB_premul;
1782                         
1783                 /* get the right string */
1784                 BLI_strncpy(str, ima->name, sizeof(str));
1785                 if(ima->id.lib)
1786                         BLI_path_abs(str, ima->id.lib->filepath);
1787                 else
1788                         BLI_path_abs(str, G.main->name);
1789                 
1790                 /* read ibuf */
1791                 ibuf = IMB_loadiffname(str, flag);
1792         }
1793         
1794         if (ibuf) {
1795                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1796                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1797                         image_create_multilayer(ima, ibuf, cfra);       
1798                         ima->type= IMA_TYPE_MULTILAYER;
1799                         IMB_freeImBuf(ibuf);
1800                         ibuf= NULL;
1801                 }
1802                 else {
1803                         image_initialize_after_load(ima, ibuf);
1804                         assign= 1;
1805
1806                         /* check if the image is a font image... */
1807                         detectBitmapFont(ibuf);
1808                         
1809                         /* make packed file for autopack */
1810                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
1811                                 ima->packedfile = newPackedFile(NULL, str);
1812                 }
1813         }
1814         else
1815                 ima->ok= 0;
1816         
1817         if(assign)
1818                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1819
1820         if(iuser)
1821                 iuser->ok= ima->ok;
1822         
1823         return ibuf;
1824 }
1825
1826 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
1827 {
1828         ImBuf *ibuf= NULL;
1829         
1830         if(ima->rr==NULL) {
1831                 ibuf = image_load_image_file(ima, iuser, 0);
1832                 if(ibuf) { /* actually an error */
1833                         ima->type= IMA_TYPE_IMAGE;
1834                         return ibuf;
1835                 }
1836         }
1837         if(ima->rr) {
1838                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1839
1840                 if(rpass) {
1841                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
1842                         
1843                         image_initialize_after_load(ima, ibuf);
1844                         
1845                         ibuf->rect_float= rpass->rect;
1846                         ibuf->flags |= IB_rectfloat;
1847                         ibuf->channels= rpass->channels;
1848                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1849
1850                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1851                 }
1852         }
1853         
1854         if(ibuf==NULL) 
1855                 ima->ok= 0;
1856         if(iuser)
1857                 iuser->ok= ima->ok;
1858         
1859         return ibuf;
1860 }
1861
1862
1863 /* showing RGBA result itself (from compo/sequence) or
1864    like exr, using layers etc */
1865 /* always returns a single ibuf, also during render progress */
1866 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
1867 {
1868         Render *re;
1869         RenderResult rres;
1870         float *rectf, *rectz;
1871         unsigned int *rect;
1872         float dither;
1873         int channels, layer, pass;
1874         ImBuf *ibuf;
1875         int from_render= (ima->render_slot == ima->last_render_slot);
1876
1877         if(!(iuser && iuser->scene))
1878                 return NULL;
1879
1880         /* if we the caller is not going to release the lock, don't give the image */
1881         if(!lock_r)
1882                 return NULL;
1883
1884         re= RE_GetRender(iuser->scene->id.name);
1885
1886         channels= 4;
1887         layer= (iuser)? iuser->layer: 0;
1888         pass= (iuser)? iuser->pass: 0;
1889
1890         if(from_render) {
1891                 RE_AcquireResultImage(re, &rres);
1892         }
1893         else if(ima->renders[ima->render_slot]) {
1894                 rres= *(ima->renders[ima->render_slot]);
1895                 rres.have_combined= rres.rectf != NULL;
1896         }
1897         else
1898                 memset(&rres, 0, sizeof(RenderResult));
1899         
1900         if(!(rres.rectx > 0 && rres.recty > 0)) {
1901                 if(from_render)
1902                         RE_ReleaseResultImage(re);
1903                 return NULL;
1904         }
1905
1906         /* release is done in BKE_image_release_ibuf using lock_r */
1907         if(from_render) {
1908                 BLI_lock_thread(LOCK_VIEWER);
1909                 *lock_r= re;
1910         }
1911
1912         /* this gives active layer, composite or seqence result */
1913         rect= (unsigned int *)rres.rect32;
1914         rectf= rres.rectf;
1915         rectz= rres.rectz;
1916         dither= iuser->scene->r.dither_intensity;
1917
1918         /* combined layer gets added as first layer */
1919         if(rres.have_combined && layer==0);
1920         else if(rres.layers.first) {
1921                 RenderLayer *rl= BLI_findlink(&rres.layers, layer-(rres.have_combined?1:0));
1922                 if(rl) {
1923                         RenderPass *rpass;
1924
1925                         /* there's no combined pass, is in renderlayer itself */
1926                         if(pass==0) {
1927                                 rectf= rl->rectf;
1928                         }
1929                         else {
1930                                 rpass= BLI_findlink(&rl->passes, pass-1);
1931                                 if(rpass) {
1932                                         channels= rpass->channels;
1933                                         rectf= rpass->rect;
1934                                         dither= 0.0f; /* don't dither passes */
1935                                 }
1936                         }
1937
1938                         for(rpass= rl->passes.first; rpass; rpass= rpass->next)
1939                                 if(rpass->passtype == SCE_PASS_Z)
1940                                         rectz= rpass->rect;
1941                 }
1942         }
1943
1944         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1945
1946         /* make ibuf if needed, and initialize it */
1947         if(ibuf==NULL) {
1948                 ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
1949                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1950         }
1951
1952         ibuf->x= rres.rectx;
1953         ibuf->y= rres.recty;
1954         
1955         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
1956                 imb_freerectImBuf(ibuf);
1957
1958         if(rect)
1959                 ibuf->rect= rect;
1960         
1961         if(rectf) {
1962                 ibuf->rect_float= rectf;
1963                 ibuf->flags |= IB_rectfloat;
1964                 ibuf->channels= channels;
1965         }
1966         else {
1967                 ibuf->rect_float= NULL;
1968                 ibuf->flags &= ~IB_rectfloat;
1969         }
1970
1971         if(rectz) {
1972                 ibuf->zbuf_float= rectz;
1973                 ibuf->flags |= IB_zbuffloat;
1974         }
1975         else {
1976                 ibuf->zbuf_float= NULL;
1977                 ibuf->flags &= ~IB_zbuffloat;
1978         }
1979
1980         ibuf->dither= dither;
1981
1982         ima->ok= IMA_OK_LOADED;
1983
1984         return ibuf;
1985 }
1986
1987 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
1988 {
1989         ImBuf *ibuf = NULL;
1990         int frame = 0, index = 0;
1991
1992         /* see if we already have an appropriate ibuf, with image source and type */
1993         if(ima->source==IMA_SRC_MOVIE) {
1994                 frame= iuser?iuser->framenr:ima->lastframe;
1995                 ibuf= image_get_ibuf(ima, 0, frame);
1996                 /* XXX temp stuff? */
1997                 if(ima->lastframe != frame)
1998                         ima->tpageflag |= IMA_TPAGE_REFRESH;
1999                 ima->lastframe = frame;
2000         }
2001         else if(ima->source==IMA_SRC_SEQUENCE) {
2002                 if(ima->type==IMA_TYPE_IMAGE) {
2003                         frame= iuser?iuser->framenr:ima->lastframe;
2004                         ibuf= image_get_ibuf(ima, 0, frame);
2005                         
2006                         /* XXX temp stuff? */
2007                         if(ima->lastframe != frame) {
2008                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2009                         }
2010                         ima->lastframe = frame;
2011                 }       
2012                 else if(ima->type==IMA_TYPE_MULTILAYER) {
2013                         frame= iuser?iuser->framenr:ima->lastframe;
2014                         index= iuser?iuser->multi_index:IMA_NO_INDEX;
2015                         ibuf= image_get_ibuf(ima, index, frame);
2016                 }
2017         }
2018         else if(ima->source==IMA_SRC_FILE) {
2019                 if(ima->type==IMA_TYPE_IMAGE)
2020                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2021                 else if(ima->type==IMA_TYPE_MULTILAYER)
2022                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2023         }
2024         else if(ima->source == IMA_SRC_GENERATED) {
2025                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2026         }
2027         else if(ima->source == IMA_SRC_VIEWER) {
2028                 /* always verify entirely, not that this shouldn't happen
2029                  * as part of texture sampling in rendering anyway, so not
2030                  * a big bottleneck */
2031         }
2032
2033         *frame_r = frame;
2034         *index_r = index;
2035
2036         return ibuf;
2037 }
2038
2039 /* Checks optional ImageUser and verifies/creates ImBuf. */
2040 /* use this one if you want to get a render result in progress,
2041  * if not, use BKE_image_get_ibuf which doesn't require a release */
2042 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2043 {
2044         ImBuf *ibuf= NULL;
2045         float color[] = {0, 0, 0, 1};
2046         int frame= 0, index= 0;
2047
2048         /* This function is intended to be thread-safe. It postpones the mutex lock
2049          * until it needs to load the image, if the image is already there it
2050          * should just get the pointer and return. The reason is that a lot of mutex
2051          * locks appears to be very slow on certain multicore macs, causing a render
2052          * with image textures to actually slow down as more threads are used.
2053          *
2054          * Note that all the image loading functions should also make sure they do
2055          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2056          * That means, the last two steps must be, 1) add the ibuf to the list and
2057          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2058         
2059         if(lock_r)
2060                 *lock_r= NULL;
2061
2062         /* quick reject tests */
2063         if(ima==NULL) 
2064                 return NULL;
2065         if(iuser) {
2066                 if(iuser->ok==0)
2067                         return NULL;
2068         }
2069         else if(ima->ok==0)
2070                 return NULL;
2071         
2072         /* try to get the ibuf without locking */
2073         ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2074
2075         if(ibuf == NULL) {
2076                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2077                  * load the image */
2078                 BLI_lock_thread(LOCK_IMAGE);
2079
2080                 /* need to check ok flag and loading ibuf again, because the situation
2081                  * might have changed in the meantime */
2082                 if(iuser) {
2083                         if(iuser->ok==0) {
2084                                 BLI_unlock_thread(LOCK_IMAGE);
2085                                 return NULL;
2086                         }
2087                 }
2088                 else if(ima->ok==0) {
2089                         BLI_unlock_thread(LOCK_IMAGE);
2090                         return NULL;
2091                 }
2092
2093                 ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2094
2095                 if(ibuf == NULL) {
2096                         /* we are sure we have to load the ibuf, using source and type */
2097                         if(ima->source==IMA_SRC_MOVIE) {
2098                                 /* source is from single file, use flipbook to store ibuf */
2099                                 ibuf= image_load_movie_file(ima, iuser, frame);
2100                         }
2101                         else if(ima->source==IMA_SRC_SEQUENCE) {
2102                                 if(ima->type==IMA_TYPE_IMAGE) {
2103                                         /* regular files, ibufs in flipbook, allows saving */
2104                                         ibuf= image_load_sequence_file(ima, iuser, frame);
2105                                 }
2106                                 /* no else; on load the ima type can change */
2107                                 if(ima->type==IMA_TYPE_MULTILAYER) {
2108                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2109                                         ibuf= image_load_sequence_multilayer(ima, iuser, frame);
2110                                 }
2111                         }
2112                         else if(ima->source==IMA_SRC_FILE) {
2113                                 
2114                                 if(ima->type==IMA_TYPE_IMAGE)
2115                                         ibuf= image_load_image_file(ima, iuser, frame); /* cfra only for '#', this global is OK */
2116                                 /* no else; on load the ima type can change */
2117                                 if(ima->type==IMA_TYPE_MULTILAYER)
2118                                         /* keeps render result, stores ibufs in listbase, allows saving */
2119                                         ibuf= image_get_ibuf_multilayer(ima, iuser);
2120                                         
2121                         }
2122                         else if(ima->source == IMA_SRC_GENERATED) {
2123                                 /* generated is: ibuf is allocated dynamically */
2124                                 /* UV testgrid or black or solid etc */
2125                                 if(ima->gen_x==0) ima->gen_x= 1024;
2126                                 if(ima->gen_y==0) ima->gen_y= 1024;
2127                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, 0, ima->gen_type, color);
2128                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2129                                 ima->ok= IMA_OK_LOADED;
2130                         }
2131                         else if(ima->source == IMA_SRC_VIEWER) {
2132                                 if(ima->type==IMA_TYPE_R_RESULT) {
2133                                         /* always verify entirely, and potentially
2134                                            returns pointer to release later */
2135                                         ibuf= image_get_render_result(ima, iuser, lock_r);
2136                                 }
2137                                 else if(ima->type==IMA_TYPE_COMPOSITE) {
2138                                         /* requires lock/unlock, otherwise don't return image */
2139                                         if(lock_r) {
2140                                                 /* unlock in BKE_image_release_ibuf */
2141                                                 BLI_lock_thread(LOCK_VIEWER);
2142                                                 *lock_r= ima;
2143
2144                                                 frame= iuser?iuser->framenr:0;
2145                                                 ibuf= image_get_ibuf(ima, 0, frame);
2146
2147                                                 if(!ibuf) {
2148                                                         /* Composite Viewer, all handled in compositor */
2149                                                         /* fake ibuf, will be filled in compositor */
2150                                                         ibuf= IMB_allocImBuf(256, 256, 32, IB_rect);
2151                                                         image_assign_ibuf(ima, ibuf, 0, frame);
2152                                                 }
2153                                         }
2154                                 }
2155                         }
2156                 }
2157
2158                 BLI_unlock_thread(LOCK_IMAGE);
2159         }
2160
2161         /* we assuming that if it is not rendering, it's also not multithreaded
2162          * (a somewhat weak assumption) */
2163         if(G.rendering==0)
2164                 tag_image_time(ima);
2165
2166         return ibuf;
2167 }
2168
2169 void BKE_image_release_ibuf(Image *ima, void *lock)
2170 {
2171         /* for getting image during threaded render / compositing, need to release */
2172         if(lock == ima) {
2173                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2174         }
2175         else if(lock) {
2176                 RE_ReleaseResultImage(lock); /* render result */
2177                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2178         }
2179 }
2180
2181 /* warning, this can allocate generated images */
2182 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2183 {
2184         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2185 }
2186
2187 void BKE_image_user_calc_frame(ImageUser *iuser, int cfra, int fieldnr)
2188 {
2189         int len;
2190         
2191         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2192         len= (iuser->fie_ima*iuser->frames)/2;
2193         
2194         if(len==0) {
2195                 iuser->framenr= 0;
2196         }
2197         else {
2198                 int imanr;
2199                 cfra= cfra - iuser->sfra+1;
2200
2201                 /* cyclic */
2202                 if(iuser->cycl) {
2203                         cfra= ( (cfra) % len );
2204                         if(cfra < 0) cfra+= len;
2205                         if(cfra==0) cfra= len;
2206                 }
2207                 
2208                 if(cfra<1) cfra= 1;
2209                 else if(cfra>len) cfra= len;
2210                 
2211                 /* convert current frame to current field */
2212                 cfra= 2*(cfra);
2213                 if(fieldnr) cfra++;
2214                 
2215                 /* transform to images space */
2216                 imanr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
2217                 if(imanr>iuser->frames) imanr= iuser->frames;
2218                 imanr+= iuser->offset;
2219                 
2220                 if(iuser->cycl) {
2221                         imanr= ( (imanr) % len );
2222                         while(imanr < 0) imanr+= len;
2223                         if(imanr==0) imanr= len;
2224                 }
2225         
2226                 /* allows image users to handle redraws */
2227                 if(iuser->flag & IMA_ANIM_ALWAYS)
2228                         if(imanr!=iuser->framenr)
2229                                 iuser->flag |= IMA_ANIM_REFRESHED;
2230                 
2231                 iuser->framenr= imanr;
2232                 if(iuser->ok==0) iuser->ok= 1;
2233         }
2234 }