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