fix for crash canceling fly mode.
[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 // XXX - Bad level call.
989 extern int datatoc_bmonofont_ttf_size;
990 extern char datatoc_bmonofont_ttf[];
991
992 // XXX - copied from text_font_begin ! Change all the BLF_* here
993 static int mono= -1;
994
995 int stamp_font_begin(int size)
996 {
997         if (mono == -1)
998                 mono= BLF_load_mem_unique("monospace", (unsigned char *)datatoc_bmonofont_ttf, datatoc_bmonofont_ttf_size);
999
1000         BLF_aspect(mono, 1.0);
1001         BLF_size(mono, size, 72);
1002         return(mono); // XXX This is for image_gen.c!!
1003 }
1004
1005 void BKE_stamp_buf(Scene *scene, unsigned char *rect, float *rectf, int width, int height, int channels)
1006 {
1007         struct StampData stamp_data;
1008         float w, h, pad;
1009         int x, y;
1010         float h_fixed;
1011         
1012         if (!rect && !rectf)
1013                 return;
1014         
1015         stampdata(scene, &stamp_data, 1);
1016
1017         /* TODO, do_versions */
1018         if(scene->r.stamp_font_id < 8)
1019                 scene->r.stamp_font_id= 12;
1020
1021         stamp_font_begin(scene->r.stamp_font_id);
1022
1023         BLF_buffer(mono, rectf, rect, width, height, channels);
1024         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1025         pad= BLF_width(mono, "--");
1026
1027         /* use 'h_fixed' rather then 'h', aligns better */
1028         // BLF_width_and_height(mono, "^|/_AgPpJjlYy", &w, &h_fixed);
1029         {
1030                 rctf box;
1031                 BLF_boundbox(mono, "^|/_AgPpJjlYy", &box);
1032                 h_fixed= box.ymax - box.ymin;
1033         }
1034
1035         x= 0;
1036         y= height;
1037
1038         if (stamp_data.file[0]) {
1039                 /* Top left corner */
1040                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h= h_fixed;
1041                 y -= h;
1042
1043                 /* also a little of space to the background. */
1044                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y-3, w+3, y+h+2);
1045
1046                 /* and draw the text. */
1047                 BLF_position(mono, x, y, 0.0);
1048                 BLF_draw_buffer(mono, stamp_data.file);
1049
1050                 /* the extra pixel for background. */
1051                 y -= 4;
1052         }
1053
1054         /* Top left corner, below File */
1055         if (stamp_data.note[0]) {
1056                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h= h_fixed;
1057                 y -= h;
1058
1059                 /* and space for background. */
1060                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-3, w+3, y+h+2);
1061
1062                 BLF_position(mono, x, y+1, 0.0);
1063                 BLF_draw_buffer(mono, stamp_data.note);
1064
1065                 /* the extra pixel for background. */
1066                 y -= 4;
1067         }
1068         
1069         /* Top left corner, below File (or Note) */
1070         if (stamp_data.date[0]) {
1071                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h= h_fixed;
1072                 y -= h;
1073
1074                 /* and space for background. */
1075                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-3, w+3, y+h+2);
1076
1077                 BLF_position(mono, x, y, 0.0);
1078                 BLF_draw_buffer(mono, stamp_data.date);
1079
1080                 /* the extra pixel for background. */
1081                 y -= 4;
1082         }
1083
1084         /* Top left corner, below File, Date or Note */
1085         if (stamp_data.rendertime[0]) {
1086                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h= h_fixed;
1087                 y -= h;
1088
1089                 /* and space for background. */
1090                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-3, w+3, y+h+2);
1091
1092                 BLF_position(mono, x, y, 0.0);
1093                 BLF_draw_buffer(mono, stamp_data.rendertime);
1094         }
1095
1096         x= 0;
1097         y= 0;
1098
1099         /* Bottom left corner, leaving space for timing */
1100         if (stamp_data.marker[0]) {
1101                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h= h_fixed;
1102
1103                 /* extra space for background. */
1104                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, w+2, y+h+2);
1105
1106                 /* and pad the text. */
1107                 BLF_position(mono, x, y+3, 0.0);
1108                 BLF_draw_buffer(mono, stamp_data.marker);
1109
1110                 /* space width. */
1111                 x += w + pad;
1112         }
1113         
1114         /* Left bottom corner */
1115         if (stamp_data.time[0]) {
1116                 BLF_width_and_height(mono, stamp_data.time, &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.time);
1124
1125                 /* space width. */
1126                 x += w + pad;
1127         }
1128         
1129         if (stamp_data.frame[0]) {
1130                 BLF_width_and_height(mono, stamp_data.frame, &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
1135                 /* and pad the text. */
1136                 BLF_position(mono, x, y+3, 0.0);
1137                 BLF_draw_buffer(mono, stamp_data.frame);
1138
1139                 /* space width. */
1140                 x += w + pad;
1141         }
1142
1143         if (stamp_data.camera[0]) {
1144                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h= h_fixed;
1145
1146                 /* extra space for background. */
1147                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+2);
1148                 BLF_position(mono, x, y+3, 0.0);
1149                 BLF_draw_buffer(mono, stamp_data.camera);
1150         }
1151         
1152         if (stamp_data.scene[0]) {
1153                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h= h_fixed;
1154
1155                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1156                 x= width - w - 2;
1157
1158                 /* extra space for background. */
1159                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+3, y+h+2);
1160
1161                 /* and pad the text. */
1162                 BLF_position(mono, x, y+3, 0.0);
1163                 BLF_draw_buffer(mono, stamp_data.scene);
1164         }
1165         
1166         if (stamp_data.strip[0]) {
1167                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h= h_fixed;
1168
1169                 /* Top right corner, with an extra space because blenfont is too strict! */
1170                 x= width - w - pad;
1171                 y= height - h;
1172
1173                 /* extra space for background. */
1174                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y-3, x+w+pad, y+h+2);
1175
1176                 BLF_position(mono, x, y, 0.0);
1177                 BLF_draw_buffer(mono, stamp_data.strip);
1178         }
1179
1180         /* cleanup the buffer. */
1181         BLF_buffer(mono, NULL, NULL, 0, 0, 0);
1182 }
1183
1184 void BKE_stamp_info(Scene *scene, struct ImBuf *ibuf)
1185 {
1186         struct StampData stamp_data;
1187
1188         if (!ibuf)      return;
1189         
1190         /* fill all the data values, no prefix */
1191         stampdata(scene, &stamp_data, 0);
1192         
1193         if (stamp_data.file[0])         IMB_metadata_change_field (ibuf, "File",                stamp_data.file);
1194         if (stamp_data.note[0])         IMB_metadata_change_field (ibuf, "Note",                stamp_data.note);
1195         if (stamp_data.date[0])         IMB_metadata_change_field (ibuf, "Date",                stamp_data.date);
1196         if (stamp_data.marker[0])       IMB_metadata_change_field (ibuf, "Marker",      stamp_data.marker);
1197         if (stamp_data.time[0])         IMB_metadata_change_field (ibuf, "Time",                stamp_data.time);
1198         if (stamp_data.frame[0])        IMB_metadata_change_field (ibuf, "Frame",       stamp_data.frame);
1199         if (stamp_data.camera[0])       IMB_metadata_change_field (ibuf, "Camera",      stamp_data.camera);
1200         if (stamp_data.scene[0])        IMB_metadata_change_field (ibuf, "Scene",       stamp_data.scene);
1201         if (stamp_data.strip[0])        IMB_metadata_change_field (ibuf, "Strip",       stamp_data.strip);
1202         if (stamp_data.rendertime[0]) IMB_metadata_change_field (ibuf, "RenderTime", stamp_data.rendertime);
1203 }
1204
1205 int BKE_write_ibuf(Scene *scene, ImBuf *ibuf, const char *name, int imtype, int subimtype, int quality)
1206 {
1207         int ok;
1208         (void)subimtype; /* quies unused warnings */
1209
1210         if(imtype==0) {
1211                 /* pass */
1212         }
1213         else if(imtype== R_IRIS) {
1214                 ibuf->ftype= IMAGIC;
1215         }
1216 #ifdef WITH_HDR
1217         else if ((imtype==R_RADHDR)) {
1218                 ibuf->ftype= RADHDR;
1219         }
1220 #endif
1221         else if (ELEM5(imtype, R_PNG, R_FFMPEG, R_H264, R_THEORA, R_XVID)) {
1222                 ibuf->ftype= PNG;
1223
1224                 if(imtype==R_PNG)
1225                         ibuf->ftype |= quality;  /* quality is actually compression 0-100 --> 0-9 */
1226
1227         }
1228 #ifdef WITH_DDS
1229         else if ((imtype==R_DDS)) {
1230                 ibuf->ftype= DDS;
1231         }
1232 #endif
1233         else if ((imtype==R_BMP)) {
1234                 ibuf->ftype= BMP;
1235         }
1236 #ifdef WITH_TIFF
1237         else if (imtype==R_TIFF) {
1238                 ibuf->ftype= TIF;
1239
1240                 if(subimtype & R_TIFF_16BIT)
1241                         ibuf->ftype |= TIF_16BIT;
1242         }
1243 #endif
1244 #ifdef WITH_OPENEXR
1245         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
1246                 ibuf->ftype= OPENEXR;
1247                 if(subimtype & R_OPENEXR_HALF)
1248                         ibuf->ftype |= OPENEXR_HALF;
1249                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
1250                 
1251                 if(!(subimtype & R_OPENEXR_ZBUF))
1252                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1253                 
1254         }
1255 #endif
1256 #ifdef WITH_CINEON
1257         else if (imtype==R_CINEON) {
1258                 ibuf->ftype = CINEON;
1259         }
1260         else if (imtype==R_DPX) {
1261                 ibuf->ftype = DPX;
1262         }
1263 #endif
1264         else if (imtype==R_TARGA) {
1265                 ibuf->ftype= TGA;
1266         }
1267         else if(imtype==R_RAWTGA) {
1268                 ibuf->ftype= RAWTGA;
1269         }
1270 #ifdef WITH_OPENJPEG
1271         else if(imtype==R_JP2) {
1272                 if(quality < 10) quality= 90;
1273                 ibuf->ftype= JP2|quality;
1274                 
1275                 if (subimtype & R_JPEG2K_16BIT) {
1276                         ibuf->ftype |= JP2_16BIT;
1277                 } else if (subimtype & R_JPEG2K_12BIT) {
1278                         ibuf->ftype |= JP2_12BIT;
1279                 }
1280                 
1281                 if (subimtype & R_JPEG2K_YCC) {
1282                         ibuf->ftype |= JP2_YCC;
1283                 }
1284                 
1285                 if (subimtype & R_JPEG2K_CINE_PRESET) {
1286                         ibuf->ftype |= JP2_CINE;
1287                         if (subimtype & R_JPEG2K_CINE_48FPS)
1288                                 ibuf->ftype |= JP2_CINE_48FPS;
1289                 }
1290         }
1291 #endif
1292         else {
1293                 /* R_JPEG90, etc. default we save jpegs */
1294                 if(quality < 10) quality= 90;
1295                 ibuf->ftype= JPG|quality;
1296                 if(ibuf->depth==32) ibuf->depth= 24;    /* unsupported feature only confuses other s/w */
1297         }
1298         
1299         BLI_make_existing_file(name);
1300
1301         if(scene && scene->r.stamp & R_STAMP_ALL)
1302                 BKE_stamp_info(scene, ibuf);
1303         
1304         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1305         if (ok == 0) {
1306                 perror(name);
1307         }
1308         
1309         return(ok);
1310 }
1311
1312
1313 void BKE_makepicstring(char *string, const char *base, int frame, int imtype, const short use_ext, const short use_frames)
1314 {
1315         if (string==NULL) return;
1316         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1317         BLI_path_abs(string, G.main->name);
1318
1319         if(use_frames)
1320                 BLI_path_frame(string, frame, 4);
1321
1322         if(use_ext)
1323                 BKE_add_image_extension(string, imtype);
1324                 
1325 }
1326
1327 /* used by sequencer too */
1328 struct anim *openanim(char *name, int flags)
1329 {
1330         struct anim *anim;
1331         struct ImBuf *ibuf;
1332         
1333         anim = IMB_open_anim(name, flags);
1334         if (anim == NULL) return(0);
1335
1336         ibuf = IMB_anim_absolute(anim, 0);
1337         if (ibuf == NULL) {
1338                 if(BLI_exists(name))
1339                         printf("not an anim: %s\n", name);
1340                 else
1341                         printf("anim file doesn't exist: %s\n", name);
1342                 IMB_free_anim(anim);
1343                 return(0);
1344         }
1345         IMB_freeImBuf(ibuf);
1346         
1347         return(anim);
1348 }
1349
1350 /* ************************* New Image API *************** */
1351
1352
1353 /* Notes about Image storage 
1354 - packedfile
1355   -> written in .blend
1356 - filename
1357   -> written in .blend
1358 - movie
1359   -> comes from packedfile or filename
1360 - renderresult
1361   -> comes from packedfile or filename
1362 - listbase
1363   -> ibufs from exrhandle
1364 - flipbook array
1365   -> ibufs come from movie, temporary renderresult or sequence
1366 - ibuf
1367   -> comes from packedfile or filename or generated
1368
1369 */
1370
1371
1372 /* forces existence of 1 Image for renderout or nodes, returns Image */
1373 /* name is only for default, when making new one */
1374 Image *BKE_image_verify_viewer(int type, const char *name)
1375 {
1376         Image *ima;
1377         
1378         for(ima=G.main->image.first; ima; ima= ima->id.next)
1379                 if(ima->source==IMA_SRC_VIEWER)
1380                         if(ima->type==type)
1381                                 break;
1382         
1383         if(ima==NULL)
1384                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1385         
1386         /* happens on reload, imagewindow cannot be image user when hidden*/
1387         if(ima->id.us==0)
1388                 id_us_plus(&ima->id);
1389
1390         return ima;
1391 }
1392
1393 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1394 {
1395         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1396 }
1397
1398 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1399 {
1400         if(ima==NULL)
1401                 return;
1402         
1403         switch(signal) {
1404         case IMA_SIGNAL_FREE:
1405                 image_free_buffers(ima);
1406                 if(iuser)
1407                         iuser->ok= 1;
1408                 break;
1409         case IMA_SIGNAL_SRC_CHANGE:
1410                 if(ima->type == IMA_TYPE_UV_TEST)
1411                         if(ima->source != IMA_SRC_GENERATED)
1412                                 ima->type= IMA_TYPE_IMAGE;
1413
1414                 if(ima->source==IMA_SRC_GENERATED) {
1415                         if(ima->gen_x==0 || ima->gen_y==0) {
1416                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1417                                 if(ibuf) {
1418                                         ima->gen_x= ibuf->x;
1419                                         ima->gen_y= ibuf->y;
1420                                 }
1421                         }
1422                 }
1423
1424                 image_free_buffers(ima);
1425
1426                 ima->ok= 1;
1427                 if(iuser)
1428                         iuser->ok= 1;
1429                 break;
1430                         
1431         case IMA_SIGNAL_RELOAD:
1432                 /* try to repack file */
1433                 if(ima->packedfile) {
1434                         PackedFile *pf;
1435                         pf = newPackedFile(NULL, ima->name);
1436                         if (pf) {
1437                                 freePackedFile(ima->packedfile);
1438                                 ima->packedfile = pf;
1439                                 image_free_buffers(ima);
1440                         } else {
1441                                 printf("ERROR: Image not available. Keeping packed image\n");
1442                         }
1443                 }
1444                 else
1445                         image_free_buffers(ima);
1446                 
1447                 if(iuser)
1448                         iuser->ok= 1;
1449                 
1450                 break;
1451         case IMA_SIGNAL_USER_NEW_IMAGE:
1452                 if(iuser) {
1453                         iuser->ok= 1;
1454                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1455                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1456                                         iuser->multi_index= 0;
1457                                         iuser->layer= iuser->pass= 0;
1458                                 }
1459                         }
1460                 }
1461                 break;
1462         }
1463         
1464         /* dont use notifiers because they are not 100% sure to succseed
1465          * this also makes sure all scenes are accounted for. */
1466         {
1467                 Scene *scene;
1468                 for(scene= G.main->scene.first; scene; scene= scene->id.next) {
1469                         if(scene->nodetree) {
1470                                 NodeTagIDChanged(scene->nodetree, &ima->id);
1471                         }
1472                 }
1473         }
1474 }
1475
1476 /* if layer or pass changes, we need an index for the imbufs list */
1477 /* note it is called for rendered results, but it doesnt use the index! */
1478 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1479 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1480 {
1481         RenderLayer *rl;
1482         RenderPass *rpass= NULL;
1483         
1484         if(rr==NULL) 
1485                 return NULL;
1486         
1487         if(iuser) {
1488                 short index= 0, rl_index= 0, rp_index;
1489                 
1490                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1491                         rp_index= 0;
1492                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1493                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1494                                         break;
1495                         if(rpass)
1496                                 break;
1497                 }
1498                 
1499                 if(rpass)
1500                         iuser->multi_index= index;
1501                 else 
1502                         iuser->multi_index= 0;
1503         }
1504         if(rpass==NULL) {
1505                 rl= rr->layers.first;
1506                 if(rl)
1507                         rpass= rl->passes.first;
1508         }
1509         
1510         return rpass;
1511 }
1512
1513 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
1514 {
1515         if(ima->rr) {
1516                 return ima->rr;
1517         }
1518         else if(ima->type==IMA_TYPE_R_RESULT) {
1519                 if(ima->render_slot == ima->last_render_slot)
1520                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
1521                 else
1522                         return ima->renders[ima->render_slot];
1523         }
1524         else
1525                 return NULL;
1526 }
1527
1528 void BKE_image_release_renderresult(Scene *scene, Image *ima)
1529 {
1530         if(ima->rr);
1531         else if(ima->type==IMA_TYPE_R_RESULT) {
1532                 if(ima->render_slot == ima->last_render_slot)
1533                         RE_ReleaseResult(RE_GetRender(scene->id.name));
1534         }
1535 }
1536
1537 void BKE_image_backup_render(Scene *scene, Image *ima)
1538 {
1539         /* called right before rendering, ima->renders contains render
1540            result pointers for everything but the current render */
1541         Render *re= RE_GetRender(scene->id.name);
1542         int slot= ima->render_slot, last= ima->last_render_slot;
1543
1544         if(slot != last) {
1545                 if(ima->renders[slot]) {
1546                         RE_FreeRenderResult(ima->renders[slot]);
1547                         ima->renders[slot]= NULL;
1548                 }
1549
1550                 ima->renders[last]= NULL;
1551                 RE_SwapResult(re, &ima->renders[last]);
1552         }
1553
1554         ima->last_render_slot= slot;
1555 }
1556
1557 /* after imbuf load, openexr type can return with a exrhandle open */
1558 /* in that case we have to build a render-result */
1559 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1560 {
1561         
1562         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1563
1564 #ifdef WITH_OPENEXR
1565         IMB_exr_close(ibuf->userdata);
1566 #endif
1567
1568         ibuf->userdata= NULL;
1569         if(ima->rr)
1570                 ima->rr->framenr= framenr;
1571 }
1572
1573 /* common stuff to do with images after loading */
1574 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1575 {
1576         /* preview is NULL when it has never been used as an icon before */
1577         if(G.background==0 && ima->preview==NULL)
1578                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1579
1580         /* fields */
1581         if (ima->flag & IMA_FIELDS) {
1582                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1583                 else de_interlace_ng(ibuf);
1584         }
1585         /* timer */
1586         ima->lastused = clock() / CLOCKS_PER_SEC;
1587         
1588         ima->ok= IMA_OK_LOADED;
1589         
1590 }
1591
1592 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1593 {
1594         struct ImBuf *ibuf;
1595         unsigned short numlen;
1596         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1597         int flag;
1598         
1599         /* XXX temp stuff? */
1600         if(ima->lastframe != frame)
1601                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1602
1603         ima->lastframe= frame;
1604         BLI_strncpy(name, ima->name, sizeof(name));
1605         BLI_stringdec(name, head, tail, &numlen);
1606         BLI_stringenc(name, head, tail, numlen, frame);
1607
1608         if(ima->id.lib)
1609                 BLI_path_abs(name, ima->id.lib->filepath);
1610         else
1611                 BLI_path_abs(name, G.main->name);
1612         
1613         flag= IB_rect|IB_multilayer;
1614         if(ima->flag & IMA_DO_PREMUL)
1615                 flag |= IB_premul;
1616
1617         /* read ibuf */
1618         ibuf = IMB_loadiffname(name, flag);
1619         if(G.f & G_DEBUG) printf("loaded %s\n", name);
1620         
1621         if (ibuf) {
1622 #ifdef WITH_OPENEXR
1623                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1624                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1625                         image_create_multilayer(ima, ibuf, frame);      
1626                         ima->type= IMA_TYPE_MULTILAYER;
1627                         IMB_freeImBuf(ibuf);
1628                         ibuf= NULL;
1629                 }
1630                 else {
1631                         image_initialize_after_load(ima, ibuf);
1632                         image_assign_ibuf(ima, ibuf, 0, frame);
1633                 }
1634 #else
1635                 image_initialize_after_load(ima, ibuf);
1636                 image_assign_ibuf(ima, ibuf, 0, frame);
1637 #endif
1638         }
1639         else
1640                 ima->ok= 0;
1641         
1642         if(iuser)
1643                 iuser->ok= ima->ok;
1644         
1645         return ibuf;
1646 }
1647
1648 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1649 {
1650         struct ImBuf *ibuf= NULL;
1651         
1652         /* either we load from RenderResult, or we have to load a new one */
1653         
1654         /* check for new RenderResult */
1655         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1656                 /* copy to survive not found multilayer image */
1657                 RenderResult *oldrr= ima->rr;
1658         
1659                 ima->rr= NULL;
1660                 ibuf = image_load_sequence_file(ima, iuser, frame);
1661                 
1662                 if(ibuf) { /* actually an error */
1663                         ima->type= IMA_TYPE_IMAGE;
1664                         printf("error, multi is normal image\n");
1665                 }
1666                 // printf("loaded new result %p\n", ima->rr);
1667                 /* free result if new one found */
1668                 if(ima->rr) {
1669                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1670                         if(oldrr) RE_FreeRenderResult(oldrr);
1671                 }
1672                 else {
1673                         ima->rr= oldrr;
1674                 }
1675
1676         }
1677         if(ima->rr) {
1678                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1679                 
1680                 if(rpass) {
1681                         // printf("load from pass %s\n", rpass->name);
1682                         /* since we free  render results, we copy the rect */
1683                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
1684                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1685                         ibuf->flags |= IB_rectfloat;
1686                         ibuf->mall= IB_rectfloat;
1687                         ibuf->channels= rpass->channels;
1688                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1689                         
1690                         image_initialize_after_load(ima, ibuf);
1691                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
1692                         
1693                 }
1694                 // else printf("pass not found\n");
1695         }
1696         else
1697                 ima->ok= 0;
1698         
1699         if(iuser)
1700                 iuser->ok= ima->ok;
1701         
1702         return ibuf;
1703 }
1704
1705
1706 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
1707 {
1708         struct ImBuf *ibuf= NULL;
1709         
1710         ima->lastframe= frame;
1711         
1712         if(ima->anim==NULL) {
1713                 char str[FILE_MAX];
1714                 
1715                 BLI_strncpy(str, ima->name, FILE_MAX);
1716                 if(ima->id.lib)
1717                         BLI_path_abs(str, ima->id.lib->filepath);
1718                 else
1719                         BLI_path_abs(str, G.main->name);
1720                 
1721                 ima->anim = openanim(str, IB_rect);
1722                 
1723                 /* let's initialize this user */
1724                 if(ima->anim && iuser && iuser->frames==0)
1725                         iuser->frames= IMB_anim_get_duration(ima->anim);
1726         }
1727         
1728         if(ima->anim) {
1729                 int dur = IMB_anim_get_duration(ima->anim);
1730                 int fra= frame-1;
1731                 
1732                 if(fra<0) fra = 0;
1733                 if(fra>(dur-1)) fra= dur-1;
1734                 ibuf = IMB_anim_absolute(ima->anim, fra);
1735                 
1736                 if(ibuf) {
1737                         image_initialize_after_load(ima, ibuf);
1738                         image_assign_ibuf(ima, ibuf, 0, frame);
1739                 }
1740                 else
1741                         ima->ok= 0;
1742         }
1743         else
1744                 ima->ok= 0;
1745         
1746         if(iuser)
1747                 iuser->ok= ima->ok;
1748         
1749         return ibuf;
1750 }
1751
1752 /* warning, 'iuser' can be NULL */
1753 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
1754 {
1755         struct ImBuf *ibuf;
1756         char str[FILE_MAX];
1757         int assign = 0, flag;
1758         
1759         /* always ensure clean ima */
1760         image_free_buffers(ima);
1761         
1762         /* is there a PackedFile with this image ? */
1763         if (ima->packedfile) {
1764                 flag = IB_rect|IB_multilayer;
1765                 if(ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
1766                 
1767                 ibuf = IMB_ibImageFromMemory((unsigned char*)ima->packedfile->data, ima->packedfile->size, flag);
1768         } 
1769         else {
1770                 flag= IB_rect|IB_multilayer|IB_metadata;
1771                 if(ima->flag & IMA_DO_PREMUL)
1772                         flag |= IB_premul;
1773                         
1774                 /* get the right string */
1775                 BLI_strncpy(str, ima->name, sizeof(str));
1776                 if(ima->id.lib)
1777                         BLI_path_abs(str, ima->id.lib->filepath);
1778                 else
1779                         BLI_path_abs(str, G.main->name);
1780                 
1781                 /* read ibuf */
1782                 ibuf = IMB_loadiffname(str, flag);
1783         }
1784         
1785         if (ibuf) {
1786                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1787                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1788                         image_create_multilayer(ima, ibuf, cfra);       
1789                         ima->type= IMA_TYPE_MULTILAYER;
1790                         IMB_freeImBuf(ibuf);
1791                         ibuf= NULL;
1792                 }
1793                 else {
1794                         image_initialize_after_load(ima, ibuf);
1795                         assign= 1;
1796
1797                         /* check if the image is a font image... */
1798                         detectBitmapFont(ibuf);
1799                         
1800                         /* make packed file for autopack */
1801                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
1802                                 ima->packedfile = newPackedFile(NULL, str);
1803                 }
1804         }
1805         else
1806                 ima->ok= 0;
1807         
1808         if(assign)
1809                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1810
1811         if(iuser)
1812                 iuser->ok= ima->ok;
1813         
1814         return ibuf;
1815 }
1816
1817 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
1818 {
1819         ImBuf *ibuf= NULL;
1820         
1821         if(ima->rr==NULL) {
1822                 ibuf = image_load_image_file(ima, iuser, 0);
1823                 if(ibuf) { /* actually an error */
1824                         ima->type= IMA_TYPE_IMAGE;
1825                         return ibuf;
1826                 }
1827         }
1828         if(ima->rr) {
1829                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1830
1831                 if(rpass) {
1832                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
1833                         
1834                         image_initialize_after_load(ima, ibuf);
1835                         
1836                         ibuf->rect_float= rpass->rect;
1837                         ibuf->flags |= IB_rectfloat;
1838                         ibuf->channels= rpass->channels;
1839                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1840
1841                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1842                 }
1843         }
1844         
1845         if(ibuf==NULL) 
1846                 ima->ok= 0;
1847         if(iuser)
1848                 iuser->ok= ima->ok;
1849         
1850         return ibuf;
1851 }
1852
1853
1854 /* showing RGBA result itself (from compo/sequence) or
1855    like exr, using layers etc */
1856 /* always returns a single ibuf, also during render progress */
1857 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
1858 {
1859         Render *re;
1860         RenderResult rres;
1861         float *rectf, *rectz;
1862         unsigned int *rect;
1863         float dither;
1864         int channels, layer, pass;
1865         ImBuf *ibuf;
1866         int from_render= (ima->render_slot == ima->last_render_slot);
1867
1868         if(!(iuser && iuser->scene))
1869                 return NULL;
1870
1871         /* if we the caller is not going to release the lock, don't give the image */
1872         if(!lock_r)
1873                 return NULL;
1874
1875         re= RE_GetRender(iuser->scene->id.name);
1876
1877         channels= 4;
1878         layer= (iuser)? iuser->layer: 0;
1879         pass= (iuser)? iuser->pass: 0;
1880
1881         if(from_render) {
1882                 RE_AcquireResultImage(re, &rres);
1883         }
1884         else if(ima->renders[ima->render_slot]) {
1885                 rres= *(ima->renders[ima->render_slot]);
1886                 rres.have_combined= rres.rectf != NULL;
1887         }
1888         else
1889                 memset(&rres, 0, sizeof(RenderResult));
1890         
1891         if(!(rres.rectx > 0 && rres.recty > 0)) {
1892                 if(from_render)
1893                         RE_ReleaseResultImage(re);
1894                 return NULL;
1895         }
1896
1897         /* release is done in BKE_image_release_ibuf using lock_r */
1898         if(from_render) {
1899                 BLI_lock_thread(LOCK_VIEWER);
1900                 *lock_r= re;
1901         }
1902
1903         /* this gives active layer, composite or seqence result */
1904         rect= (unsigned int *)rres.rect32;
1905         rectf= rres.rectf;
1906         rectz= rres.rectz;
1907         dither= iuser->scene->r.dither_intensity;
1908
1909         /* combined layer gets added as first layer */
1910         if(rres.have_combined && layer==0);
1911         else if(rres.layers.first) {
1912                 RenderLayer *rl= BLI_findlink(&rres.layers, layer-(rres.have_combined?1:0));
1913                 if(rl) {
1914                         RenderPass *rpass;
1915
1916                         /* there's no combined pass, is in renderlayer itself */
1917                         if(pass==0) {
1918                                 rectf= rl->rectf;
1919                         }
1920                         else {
1921                                 rpass= BLI_findlink(&rl->passes, pass-1);
1922                                 if(rpass) {
1923                                         channels= rpass->channels;
1924                                         rectf= rpass->rect;
1925                                         dither= 0.0f; /* don't dither passes */
1926                                 }
1927                         }
1928
1929                         for(rpass= rl->passes.first; rpass; rpass= rpass->next)
1930                                 if(rpass->passtype == SCE_PASS_Z)
1931                                         rectz= rpass->rect;
1932                 }
1933         }
1934
1935         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1936
1937         /* make ibuf if needed, and initialize it */
1938         if(ibuf==NULL) {
1939                 ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
1940                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1941         }
1942
1943         ibuf->x= rres.rectx;
1944         ibuf->y= rres.recty;
1945         
1946         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
1947                 imb_freerectImBuf(ibuf);
1948
1949         if(rect)
1950                 ibuf->rect= rect;
1951         
1952         if(rectf) {
1953                 ibuf->rect_float= rectf;
1954                 ibuf->flags |= IB_rectfloat;
1955                 ibuf->channels= channels;
1956         }
1957         else {
1958                 ibuf->rect_float= NULL;
1959                 ibuf->flags &= ~IB_rectfloat;
1960         }
1961
1962         if(rectz) {
1963                 ibuf->zbuf_float= rectz;
1964                 ibuf->flags |= IB_zbuffloat;
1965         }
1966         else {
1967                 ibuf->zbuf_float= NULL;
1968                 ibuf->flags &= ~IB_zbuffloat;
1969         }
1970
1971         ibuf->dither= dither;
1972
1973         ima->ok= IMA_OK_LOADED;
1974
1975         return ibuf;
1976 }
1977
1978 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
1979 {
1980         ImBuf *ibuf = NULL;
1981         int frame = 0, index = 0;
1982
1983         /* see if we already have an appropriate ibuf, with image source and type */
1984         if(ima->source==IMA_SRC_MOVIE) {
1985                 frame= iuser?iuser->framenr:ima->lastframe;
1986                 ibuf= image_get_ibuf(ima, 0, frame);
1987                 /* XXX temp stuff? */
1988                 if(ima->lastframe != frame)
1989                         ima->tpageflag |= IMA_TPAGE_REFRESH;
1990                 ima->lastframe = frame;
1991         }
1992         else if(ima->source==IMA_SRC_SEQUENCE) {
1993                 if(ima->type==IMA_TYPE_IMAGE) {
1994                         frame= iuser?iuser->framenr:ima->lastframe;
1995                         ibuf= image_get_ibuf(ima, 0, frame);
1996                         
1997                         /* XXX temp stuff? */
1998                         if(ima->lastframe != frame) {
1999                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2000                         }
2001                         ima->lastframe = frame;
2002                 }       
2003                 else if(ima->type==IMA_TYPE_MULTILAYER) {
2004                         frame= iuser?iuser->framenr:ima->lastframe;
2005                         index= iuser?iuser->multi_index:IMA_NO_INDEX;
2006                         ibuf= image_get_ibuf(ima, index, frame);
2007                 }
2008         }
2009         else if(ima->source==IMA_SRC_FILE) {
2010                 if(ima->type==IMA_TYPE_IMAGE)
2011                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2012                 else if(ima->type==IMA_TYPE_MULTILAYER)
2013                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2014         }
2015         else if(ima->source == IMA_SRC_GENERATED) {
2016                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2017         }
2018         else if(ima->source == IMA_SRC_VIEWER) {
2019                 /* always verify entirely, not that this shouldn't happen
2020                  * as part of texture sampling in rendering anyway, so not
2021                  * a big bottleneck */
2022         }
2023
2024         *frame_r = frame;
2025         *index_r = index;
2026
2027         return ibuf;
2028 }
2029
2030 /* Checks optional ImageUser and verifies/creates ImBuf. */
2031 /* use this one if you want to get a render result in progress,
2032  * if not, use BKE_image_get_ibuf which doesn't require a release */
2033 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2034 {
2035         ImBuf *ibuf= NULL;
2036         float color[] = {0, 0, 0, 1};
2037         int frame= 0, index= 0;
2038
2039         /* This function is intended to be thread-safe. It postpones the mutex lock
2040          * until it needs to load the image, if the image is already there it
2041          * should just get the pointer and return. The reason is that a lot of mutex
2042          * locks appears to be very slow on certain multicore macs, causing a render
2043          * with image textures to actually slow down as more threads are used.
2044          *
2045          * Note that all the image loading functions should also make sure they do
2046          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2047          * That means, the last two steps must be, 1) add the ibuf to the list and
2048          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2049         
2050         if(lock_r)
2051                 *lock_r= NULL;
2052
2053         /* quick reject tests */
2054         if(ima==NULL) 
2055                 return NULL;
2056         if(iuser) {
2057                 if(iuser->ok==0)
2058                         return NULL;
2059         }
2060         else if(ima->ok==0)
2061                 return NULL;
2062         
2063         /* try to get the ibuf without locking */
2064         ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2065
2066         if(ibuf == NULL) {
2067                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2068                  * load the image */
2069                 BLI_lock_thread(LOCK_IMAGE);
2070
2071                 /* need to check ok flag and loading ibuf again, because the situation
2072                  * might have changed in the meantime */
2073                 if(iuser) {
2074                         if(iuser->ok==0) {
2075                                 BLI_unlock_thread(LOCK_IMAGE);
2076                                 return NULL;
2077                         }
2078                 }
2079                 else if(ima->ok==0) {
2080                         BLI_unlock_thread(LOCK_IMAGE);
2081                         return NULL;
2082                 }
2083
2084                 ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2085
2086                 if(ibuf == NULL) {
2087                         /* we are sure we have to load the ibuf, using source and type */
2088                         if(ima->source==IMA_SRC_MOVIE) {
2089                                 /* source is from single file, use flipbook to store ibuf */
2090                                 ibuf= image_load_movie_file(ima, iuser, frame);
2091                         }
2092                         else if(ima->source==IMA_SRC_SEQUENCE) {
2093                                 if(ima->type==IMA_TYPE_IMAGE) {
2094                                         /* regular files, ibufs in flipbook, allows saving */
2095                                         ibuf= image_load_sequence_file(ima, iuser, frame);
2096                                 }
2097                                 /* no else; on load the ima type can change */
2098                                 if(ima->type==IMA_TYPE_MULTILAYER) {
2099                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2100                                         ibuf= image_load_sequence_multilayer(ima, iuser, frame);
2101                                 }
2102                         }
2103                         else if(ima->source==IMA_SRC_FILE) {
2104                                 
2105                                 if(ima->type==IMA_TYPE_IMAGE)
2106                                         ibuf= image_load_image_file(ima, iuser, frame); /* cfra only for '#', this global is OK */
2107                                 /* no else; on load the ima type can change */
2108                                 if(ima->type==IMA_TYPE_MULTILAYER)
2109                                         /* keeps render result, stores ibufs in listbase, allows saving */
2110                                         ibuf= image_get_ibuf_multilayer(ima, iuser);
2111                                         
2112                         }
2113                         else if(ima->source == IMA_SRC_GENERATED) {
2114                                 /* generated is: ibuf is allocated dynamically */
2115                                 /* UV testgrid or black or solid etc */
2116                                 if(ima->gen_x==0) ima->gen_x= 1024;
2117                                 if(ima->gen_y==0) ima->gen_y= 1024;
2118                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, 0, ima->gen_type, color);
2119                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2120                                 ima->ok= IMA_OK_LOADED;
2121                         }
2122                         else if(ima->source == IMA_SRC_VIEWER) {
2123                                 if(ima->type==IMA_TYPE_R_RESULT) {
2124                                         /* always verify entirely, and potentially
2125                                            returns pointer to release later */
2126                                         ibuf= image_get_render_result(ima, iuser, lock_r);
2127                                 }
2128                                 else if(ima->type==IMA_TYPE_COMPOSITE) {
2129                                         /* requires lock/unlock, otherwise don't return image */
2130                                         if(lock_r) {
2131                                                 /* unlock in BKE_image_release_ibuf */
2132                                                 BLI_lock_thread(LOCK_VIEWER);
2133                                                 *lock_r= ima;
2134
2135                                                 frame= iuser?iuser->framenr:0;
2136                                                 ibuf= image_get_ibuf(ima, 0, frame);
2137
2138                                                 if(!ibuf) {
2139                                                         /* Composite Viewer, all handled in compositor */
2140                                                         /* fake ibuf, will be filled in compositor */
2141                                                         ibuf= IMB_allocImBuf(256, 256, 32, IB_rect);
2142                                                         image_assign_ibuf(ima, ibuf, 0, frame);
2143                                                 }
2144                                         }
2145                                 }
2146                         }
2147                 }
2148
2149                 BLI_unlock_thread(LOCK_IMAGE);
2150         }
2151
2152         /* we assuming that if it is not rendering, it's also not multithreaded
2153          * (a somewhat weak assumption) */
2154         if(G.rendering==0)
2155                 tag_image_time(ima);
2156
2157         return ibuf;
2158 }
2159
2160 void BKE_image_release_ibuf(Image *ima, void *lock)
2161 {
2162         /* for getting image during threaded render / compositing, need to release */
2163         if(lock == ima) {
2164                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2165         }
2166         else if(lock) {
2167                 RE_ReleaseResultImage(lock); /* render result */
2168                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2169         }
2170 }
2171
2172 /* warning, this can allocate generated images */
2173 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2174 {
2175         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2176 }
2177
2178 void BKE_image_user_calc_frame(ImageUser *iuser, int cfra, int fieldnr)
2179 {
2180         int len;
2181         
2182         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2183         len= (iuser->fie_ima*iuser->frames)/2;
2184         
2185         if(len==0) {
2186                 iuser->framenr= 0;
2187         }
2188         else {
2189                 int imanr;
2190                 cfra= cfra - iuser->sfra+1;
2191
2192                 /* cyclic */
2193                 if(iuser->cycl) {
2194                         cfra= ( (cfra) % len );
2195                         if(cfra < 0) cfra+= len;
2196                         if(cfra==0) cfra= len;
2197                 }
2198                 
2199                 if(cfra<1) cfra= 1;
2200                 else if(cfra>len) cfra= len;
2201                 
2202                 /* convert current frame to current field */
2203                 cfra= 2*(cfra);
2204                 if(fieldnr) cfra++;
2205                 
2206                 /* transform to images space */
2207                 imanr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
2208                 if(imanr>iuser->frames) imanr= iuser->frames;
2209                 imanr+= iuser->offset;
2210                 
2211                 if(iuser->cycl) {
2212                         imanr= ( (imanr) % len );
2213                         while(imanr < 0) imanr+= len;
2214                         if(imanr==0) imanr= len;
2215                 }
2216         
2217                 /* allows image users to handle redraws */
2218                 if(iuser->flag & IMA_ANIM_ALWAYS)
2219                         if(imanr!=iuser->framenr)
2220                                 iuser->flag |= IMA_ANIM_REFRESHED;
2221                 
2222                 iuser->framenr= imanr;
2223                 if(iuser->ok==0) iuser->ok= 1;
2224         }
2225 }