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