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