synched with trunk at revision 34793
[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, (unsigned char)0);
107                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, (int)IB_rect, (unsigned char)0);
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, 0);
135                 tbuf2 = IMB_allocImBuf(ibuf->x, (short)(ibuf->y >> 1), (unsigned char)32, IB_rect, 0);
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, int frame)
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.sce);
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.sce);
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(int width, int height, char *name, int depth, int floatbuf, short uvtestgrid, float color[4])
386 {
387         ImBuf *ibuf;
388         unsigned char *rect= NULL;
389         float *rect_float= NULL;
390         
391         if (floatbuf) {
392                 ibuf= IMB_allocImBuf(width, height, depth, IB_rectfloat, 0);
393                 rect_float= (float*)ibuf->rect_float;
394         }
395         else {
396                 ibuf= IMB_allocImBuf(width, height, depth, IB_rect, 0);
397                 rect= (unsigned char*)ibuf->rect;
398         }
399         
400         strcpy(ibuf->name, "//Untitled");
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(int width, int height, char *name, int depth, int floatbuf, short uvtestgrid, float color[4])
419 {
420         /* on save, type is changed to FILE in editsima.c */
421         Image *ima= image_alloc(name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
422         
423         if (ima) {
424                 ImBuf *ibuf;
425                 
426                 BLI_strncpy(ima->name, name, FILE_MAX);
427                 ima->gen_x= width;
428                 ima->gen_y= height;
429                 ima->gen_type= uvtestgrid;
430                 
431                 ibuf= add_ibuf_size(width, height, name, depth, floatbuf, uvtestgrid, color);
432                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
433                 
434                 ima->ok= IMA_OK_LOADED;
435         }
436
437         return ima;
438 }
439
440 /* creates an image image owns the imbuf passed */
441 Image *BKE_add_image_imbuf(ImBuf *ibuf)
442 {
443         /* on save, type is changed to FILE in editsima.c */
444         Image *ima;
445
446         ima= image_alloc(BLI_path_basename(ibuf->name), IMA_SRC_FILE, IMA_TYPE_IMAGE);
447
448         if (ima) {
449                 BLI_strncpy(ima->name, ibuf->name, FILE_MAX);
450                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
451                 ima->ok= IMA_OK_LOADED;
452         }
453
454         return ima;
455 }
456
457 /* packs rect from memory as PNG */
458 void BKE_image_memorypack(Image *ima)
459 {
460         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
461         
462         if(ibuf==NULL)
463                 return;
464         if (ima->packedfile) {
465                 freePackedFile(ima->packedfile);
466                 ima->packedfile = NULL;
467         }
468         
469         ibuf->ftype= PNG;
470         ibuf->depth= 32;
471         
472         IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem);
473         if(ibuf->encodedbuffer==NULL) {
474                 printf("memory save for pack error\n");
475         }
476         else {
477                 PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
478                 
479                 pf->data = ibuf->encodedbuffer;
480                 pf->size = ibuf->encodedsize;
481                 ima->packedfile= pf;
482                 ibuf->encodedbuffer= NULL;
483                 ibuf->encodedsize= 0;
484                 ibuf->userflags &= ~IB_BITMAPDIRTY;
485                 
486                 if(ima->source==IMA_SRC_GENERATED) {
487                         ima->source= IMA_SRC_FILE;
488                         ima->type= IMA_TYPE_IMAGE;
489                 }
490         }
491 }
492
493 void tag_image_time(Image *ima)
494 {
495         if (ima)
496                 ima->lastused = (int)PIL_check_seconds_timer();
497 }
498
499 #if 0
500 static void tag_all_images_time() 
501 {
502         Image *ima;
503         int ctime = (int)PIL_check_seconds_timer();
504
505         ima= G.main->image.first;
506         while(ima) {
507                 if(ima->bindcode || ima->repbind || ima->ibufs.first) {
508                         ima->lastused = ctime;
509                 }
510         }
511 }
512 #endif
513
514 void free_old_images()
515 {
516         Image *ima;
517         static int lasttime = 0;
518         int ctime = (int)PIL_check_seconds_timer();
519         
520         /* 
521            Run garbage collector once for every collecting period of time 
522            if textimeout is 0, that's the option to NOT run the collector
523         */
524         if (U.textimeout == 0 || ctime % U.texcollectrate || ctime == lasttime)
525                 return;
526
527         lasttime = ctime;
528
529         ima= G.main->image.first;
530         while(ima) {
531                 if((ima->flag & IMA_NOCOLLECT)==0 && ctime - ima->lastused > U.textimeout) {
532                         /*
533                            If it's in GL memory, deallocate and set time tag to current time
534                            This gives textures a "second chance" to be used before dying.
535                         */
536                         if(ima->bindcode || ima->repbind) {
537                                 GPU_free_image(ima);
538                                 ima->lastused = ctime;
539                         }
540                         /* Otherwise, just kill the buffers */
541                         else if (ima->ibufs.first) {
542                                 image_free_buffers(ima);
543                         }
544                 }
545                 ima = ima->id.next;
546         }
547 }
548
549 static uintptr_t image_mem_size(Image *ima)
550 {
551         ImBuf *ibuf, *ibufm;
552         int level;
553         uintptr_t size = 0;
554
555         size= 0;
556         
557         /* viewers have memory depending on other rules, has no valid rect pointer */
558         if(ima->source==IMA_SRC_VIEWER)
559                 return 0;
560         
561         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
562                 if(ibuf->rect) size += MEM_allocN_len(ibuf->rect);
563                 else if(ibuf->rect_float) size += MEM_allocN_len(ibuf->rect_float);
564
565                 for(level=0; level<IB_MIPMAP_LEVELS; level++) {
566                         ibufm= ibuf->mipmap[level];
567                         if(ibufm) {
568                                 if(ibufm->rect) size += MEM_allocN_len(ibufm->rect);
569                                 else if(ibufm->rect_float) size += MEM_allocN_len(ibufm->rect_float);
570                         }
571                 }
572         }
573
574         return size;
575 }
576
577 void BKE_image_print_memlist(void)
578 {
579         Image *ima;
580         uintptr_t size, totsize= 0;
581
582         for(ima= G.main->image.first; ima; ima= ima->id.next)
583                 totsize += image_mem_size(ima);
584
585         printf("\ntotal image memory len: %.3lf MB\n", (double)totsize/(double)(1024*1024));
586
587         for(ima= G.main->image.first; ima; ima= ima->id.next) {
588                 size= image_mem_size(ima);
589
590                 if(size)
591                         printf("%s len: %.3f MB\n", ima->id.name+2, (double)size/(double)(1024*1024));
592         }
593 }
594
595 void BKE_image_free_all_textures(void)
596 {
597         Tex *tex;
598         Image *ima;
599         unsigned int totsize= 0;
600         
601         for(ima= G.main->image.first; ima; ima= ima->id.next)
602                 ima->id.flag &= ~LIB_DOIT;
603         
604         for(tex= G.main->tex.first; tex; tex= tex->id.next)
605                 if(tex->ima)
606                         tex->ima->id.flag |= LIB_DOIT;
607         
608         for(ima= G.main->image.first; ima; ima= ima->id.next) {
609                 if(ima->ibufs.first && (ima->id.flag & LIB_DOIT)) {
610                         ImBuf *ibuf;
611                         for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next) {
612                                 if(ibuf->mipmap[0]) 
613                                         totsize+= 1.33*ibuf->x*ibuf->y*4;
614                                 else
615                                         totsize+= ibuf->x*ibuf->y*4;
616                         }
617                         image_free_buffers(ima);
618                 }
619         }
620         /* printf("freed total %d MB\n", totsize/(1024*1024)); */
621 }
622
623 /* except_frame is weak, only works for seqs without offset... */
624 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
625 {
626         ImBuf *ibuf, *nbuf;
627
628         for(ibuf= ima->ibufs.first; ibuf; ibuf= nbuf) {
629                 nbuf= ibuf->next;
630                 if(ibuf->userflags & IB_BITMAPDIRTY)
631                         continue;
632                 if(ibuf->index==IMA_NO_INDEX)
633                         continue;
634                 if(except_frame!=IMA_INDEX_FRAME(ibuf->index)) {
635                         BLI_remlink(&ima->ibufs, ibuf);
636                         
637                         if (ibuf->userdata) {
638                                 MEM_freeN(ibuf->userdata);
639                                 ibuf->userdata = NULL;
640                         }
641                         IMB_freeImBuf(ibuf);
642                 }                                       
643         }
644 }
645
646 void BKE_image_all_free_anim_ibufs(int cfra)
647 {
648         Image *ima;
649         
650         for(ima= G.main->image.first; ima; ima= ima->id.next)
651                 if(ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE))
652                         BKE_image_free_anim_ibufs(ima, cfra);
653 }
654
655
656 /* *********** READ AND WRITE ************** */
657
658 int BKE_imtype_to_ftype(int imtype)
659 {
660         if(imtype==0)
661                 return TGA;
662         else if(imtype== R_IRIS) 
663                 return IMAGIC;
664 #ifdef WITH_HDR
665         else if (imtype==R_RADHDR)
666                 return RADHDR;
667 #endif
668         else if (imtype==R_PNG)
669                 return PNG;
670 #ifdef WITH_DDS
671         else if (imtype==R_DDS)
672                 return DDS;
673 #endif
674         else if (imtype==R_BMP)
675                 return BMP;
676 #ifdef WITH_TIFF
677         else if (imtype==R_TIFF)
678                 return TIF;
679 #endif
680         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER)
681                 return OPENEXR;
682 #ifdef WITH_CINEON
683         else if (imtype==R_CINEON)
684                 return CINEON;
685         else if (imtype==R_DPX)
686                 return DPX;
687 #endif
688         else if (imtype==R_TARGA)
689                 return TGA;
690         else if(imtype==R_RAWTGA)
691                 return RAWTGA;
692 #ifdef WITH_OPENJPEG
693         else if(imtype==R_JP2)
694                 return JP2;
695 #endif
696         else
697                 return JPG|90;
698 }
699
700 int BKE_ftype_to_imtype(int ftype)
701 {
702         if(ftype==0)
703                 return TGA;
704         else if(ftype == IMAGIC) 
705                 return R_IRIS;
706 #ifdef WITH_HDR
707         else if (ftype & RADHDR)
708                 return R_RADHDR;
709 #endif
710         else if (ftype & PNG)
711                 return R_PNG;
712 #ifdef WITH_DDS
713         else if (ftype & DDS)
714                 return R_DDS;
715 #endif
716         else if (ftype & BMP)
717                 return R_BMP;
718 #ifdef WITH_TIFF
719         else if (ftype & TIF)
720                 return R_TIFF;
721 #endif
722         else if (ftype & OPENEXR)
723                 return R_OPENEXR;
724 #ifdef WITH_CINEON
725         else if (ftype & CINEON)
726                 return R_CINEON;
727         else if (ftype & DPX)
728                 return R_DPX;
729 #endif
730         else if (ftype & TGA)
731                 return R_TARGA;
732         else if(ftype & RAWTGA)
733                 return R_RAWTGA;
734 #ifdef WITH_OPENJPEG
735         else if(ftype & JP2)
736                 return R_JP2;
737 #endif
738         else
739                 return R_JPEG90;
740 }
741
742
743 int BKE_imtype_is_movie(int imtype)
744 {
745         switch(imtype) {
746         case R_AVIRAW:
747         case R_AVIJPEG:
748         case R_AVICODEC:
749         case R_QUICKTIME:
750         case R_FFMPEG:
751         case R_H264:
752         case R_THEORA:
753         case R_XVID:
754         case R_FRAMESERVER:
755                         return 1;
756         }
757         return 0;
758 }
759
760 int BKE_add_image_extension(char *string, int imtype)
761 {
762         char *extension= NULL;
763         
764         if(imtype== R_IRIS) {
765                 if(!BLI_testextensie(string, ".rgb"))
766                         extension= ".rgb";
767         }
768         else if(imtype==R_IRIZ) {
769                 if(!BLI_testextensie(string, ".rgb"))
770                         extension= ".rgb";
771         }
772 #ifdef WITH_HDR
773         else if(imtype==R_RADHDR) {
774                 if(!BLI_testextensie(string, ".hdr"))
775                         extension= ".hdr";
776         }
777 #endif
778         else if (ELEM5(imtype, R_PNG, R_FFMPEG, R_H264, R_THEORA, R_XVID)) {
779                 if(!BLI_testextensie(string, ".png"))
780                         extension= ".png";
781         }
782 #ifdef WITH_DDS
783         else if(imtype==R_DDS) {
784                 if(!BLI_testextensie(string, ".dds"))
785                         extension= ".dds";
786         }
787 #endif
788         else if(imtype==R_RAWTGA) {
789                 if(!BLI_testextensie(string, ".tga"))
790                         extension= ".tga";
791         }
792         else if(imtype==R_BMP) {
793                 if(!BLI_testextensie(string, ".bmp"))
794                         extension= ".bmp";
795         }
796 #ifdef WITH_TIFF
797         else if(imtype==R_TIFF) {
798                 if(!BLI_testextensie(string, ".tif") && 
799                         !BLI_testextensie(string, ".tiff")) extension= ".tif";
800         }
801 #endif
802 #ifdef WITH_OPENEXR
803         else if( ELEM(imtype, R_OPENEXR, R_MULTILAYER)) {
804                 if(!BLI_testextensie(string, ".exr"))
805                         extension= ".exr";
806         }
807 #endif
808 #ifdef WITH_CINEON
809         else if(imtype==R_CINEON){
810                 if (!BLI_testextensie(string, ".cin"))
811                         extension= ".cin";
812         }
813         else if(imtype==R_DPX){
814                 if (!BLI_testextensie(string, ".dpx"))
815                         extension= ".dpx";
816         }
817 #endif
818         else if(imtype==R_TARGA) {
819                 if(!BLI_testextensie(string, ".tga"))
820                         extension= ".tga";
821         }
822 #ifdef WITH_OPENJPEG
823         else if(imtype==R_JP2) {
824                 if(!BLI_testextensie(string, ".jp2"))
825                         extension= ".jp2";
826         }
827 #endif
828         else { //   R_AVICODEC, R_AVIRAW, R_AVIJPEG, R_JPEG90, R_QUICKTIME etc
829                 if(!( BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
830                         extension= ".jpg";
831         }
832
833         if(extension) {
834                 return BLI_replace_extension(string, FILE_MAX, extension);
835         }
836         else {
837                 return FALSE;
838         }
839 }
840
841 /* could allow access externally - 512 is for long names, 64 is for id names */
842 typedef struct StampData {
843         char    file[512];
844         char    note[512];
845         char    date[512];
846         char    marker[512];
847         char    time[512];
848         char    frame[512];
849         char    camera[64];
850         char    scene[64];
851         char    strip[64];
852         char    rendertime[64];
853 } StampData;
854
855 static void stampdata(Scene *scene, StampData *stamp_data, int do_prefix)
856 {
857         char text[256];
858         struct tm *tl;
859         time_t t;
860
861         if (scene->r.stamp & R_STAMP_FILENAME) {
862                 if (G.relbase_valid) {
863                         if (do_prefix)          sprintf(stamp_data->file, "File %s", G.sce);
864                         else                            sprintf(stamp_data->file, "%s", G.sce);
865                 } else {
866                         if (do_prefix)          strcpy(stamp_data->file, "File <untitled>");
867                         else                            strcpy(stamp_data->file, "<untitled>");
868                 }
869         } else {
870                 stamp_data->file[0] = '\0';
871         }
872         
873         if (scene->r.stamp & R_STAMP_NOTE) {
874                 /* Never do prefix for Note */
875                 sprintf(stamp_data->note, "%s", scene->r.stamp_udata);
876         } else {
877                 stamp_data->note[0] = '\0';
878         }
879         
880         if (scene->r.stamp & R_STAMP_DATE) {
881
882                 t = time (NULL);
883                 tl = localtime (&t);
884                 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);
885
886                 if (do_prefix)          sprintf(stamp_data->date, "Date %s", text);
887                 else                            sprintf(stamp_data->date, "%s", text);
888         } else {
889                 stamp_data->date[0] = '\0';
890         }
891         
892         if (scene->r.stamp & R_STAMP_MARKER) {
893                 char *name = scene_find_last_marker_name(scene, CFRA);
894         
895                 if (name)       strcpy(text, name);
896                 else            strcpy(text, "<none>");
897                 
898                 if (do_prefix)          sprintf(stamp_data->marker, "Marker %s", text);
899                 else                            sprintf(stamp_data->marker, "%s", text);
900         } else {
901                 stamp_data->marker[0] = '\0';
902         }
903         
904         if (scene->r.stamp & R_STAMP_TIME) {
905                 int h, m, s, f;
906                 h= m= s= f= 0;
907                 f = (int)(scene->r.cfra % scene->r.frs_sec);
908                 s = (int)(scene->r.cfra / scene->r.frs_sec);
909
910                 if (s) {
911                         m = (int)(s / 60);
912                         s %= 60;
913
914                         if (m) {
915                                 h = (int)(m / 60);
916                                 m %= 60;
917                         }
918                 }
919
920                 if (scene->r.frs_sec < 100)
921                         sprintf (text, "%02d:%02d:%02d.%02d", h, m, s, f);
922                 else
923                         sprintf (text, "%02d:%02d:%02d.%03d", h, m, s, f);
924                 
925                 if (do_prefix)          sprintf(stamp_data->time, "Time %s", text);
926                 else                            sprintf(stamp_data->time, "%s", text);
927         } else {
928                 stamp_data->time[0] = '\0';
929         }
930         
931         if (scene->r.stamp & R_STAMP_FRAME) {
932                 char format[32];
933                 if (do_prefix)          sprintf(format, "Frame %%0%di", 1 + (int) log10(scene->r.efra));
934                 else                            sprintf(format, "%%0%di", 1 + (int) log10(scene->r.efra));
935                 sprintf (stamp_data->frame, format, scene->r.cfra);
936         } else {
937                 stamp_data->frame[0] = '\0';
938         }
939
940         if (scene->r.stamp & R_STAMP_CAMERA) {
941                 if (scene->camera) strcpy(text, ((Camera *) scene->camera)->id.name+2);
942                 else            strcpy(text, "<none>");
943                 
944                 if (do_prefix)          sprintf(stamp_data->camera, "Camera %s", text);
945                 else                            sprintf(stamp_data->camera, "%s", text);
946         } else {
947                 stamp_data->camera[0] = '\0';
948         }
949
950         if (scene->r.stamp & R_STAMP_SCENE) {
951                 if (do_prefix)          sprintf(stamp_data->scene, "Scene %s", scene->id.name+2);
952                 else                            sprintf(stamp_data->scene, "%s", scene->id.name+2);
953         } else {
954                 stamp_data->scene[0] = '\0';
955         }
956         
957         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
958                 Sequence *seq= NULL; //XXX = get_foreground_frame_seq(scene->r.cfra);
959         
960                 if (seq) strcpy(text, seq->name+2);
961                 else            strcpy(text, "<none>");
962                 
963                 if (do_prefix)          sprintf(stamp_data->strip, "Strip %s", text);
964                 else                            sprintf(stamp_data->strip, "%s", text);
965         } else {
966                 stamp_data->strip[0] = '\0';
967         }
968
969         {
970                 Render *re= RE_GetRender(scene->id.name);
971                 RenderStats *stats= re ? RE_GetStats(re):NULL;
972
973                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
974                         BLI_timestr(stats->lastframetime, text);
975
976                         if (do_prefix)          sprintf(stamp_data->rendertime, "RenderTime %s", text);
977                         else                            sprintf(stamp_data->rendertime, "%s", text);
978                 } else {
979                         stamp_data->rendertime[0] = '\0';
980                 }
981         }
982 }
983
984 // XXX - Bad level call.
985 extern int datatoc_bmonofont_ttf_size;
986 extern char datatoc_bmonofont_ttf[];
987
988 // XXX - copied from text_font_begin ! Change all the BLF_* here
989 static int mono= -1;
990
991 int stamp_font_begin(int size)
992 {
993         if (mono == -1)
994                 mono= BLF_load_mem_unique("monospace", (unsigned char *)datatoc_bmonofont_ttf, datatoc_bmonofont_ttf_size);
995
996         BLF_aspect(mono, 1.0);
997         BLF_size(mono, size, 72);
998         return(mono); // XXX This is for image_gen.c!!
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         
1008         if (!rect && !rectf)
1009                 return;
1010         
1011         stampdata(scene, &stamp_data, 1);
1012
1013         /* TODO, do_versions */
1014         if(scene->r.stamp_font_id < 8)
1015                 scene->r.stamp_font_id= 12;
1016
1017         stamp_font_begin(scene->r.stamp_font_id);
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.scene, &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_write_ibuf(Scene *scene, ImBuf *ibuf, char *name, int imtype, int subimtype, int quality)
1202 {
1203         int ok;
1204         
1205         if(imtype==0) {
1206                 /* pass */
1207         }
1208         else if(imtype== R_IRIS) {
1209                 ibuf->ftype= IMAGIC;
1210         }
1211 #ifdef WITH_HDR
1212         else if ((imtype==R_RADHDR)) {
1213                 ibuf->ftype= RADHDR;
1214         }
1215 #endif
1216         else if (ELEM5(imtype, R_PNG, R_FFMPEG, R_H264, R_THEORA, R_XVID)) {
1217                 ibuf->ftype= PNG;
1218
1219                 if(imtype==R_PNG)
1220                         ibuf->ftype |= quality;  /* quality is actually compression 0-100 --> 0-9 */
1221
1222         }
1223 #ifdef WITH_DDS
1224         else if ((imtype==R_DDS)) {
1225                 ibuf->ftype= DDS;
1226         }
1227 #endif
1228         else if ((imtype==R_BMP)) {
1229                 ibuf->ftype= BMP;
1230         }
1231 #ifdef WITH_TIFF
1232         else if (imtype==R_TIFF) {
1233                 ibuf->ftype= TIF;
1234
1235                 if(subimtype & R_TIFF_16BIT)
1236                         ibuf->ftype |= TIF_16BIT;
1237         }
1238 #endif
1239 #ifdef WITH_OPENEXR
1240         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
1241                 ibuf->ftype= OPENEXR;
1242                 if(subimtype & R_OPENEXR_HALF)
1243                         ibuf->ftype |= OPENEXR_HALF;
1244                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
1245                 
1246                 if(!(subimtype & R_OPENEXR_ZBUF))
1247                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1248                 
1249         }
1250 #endif
1251 #ifdef WITH_CINEON
1252         else if (imtype==R_CINEON) {
1253                 ibuf->ftype = CINEON;
1254         }
1255         else if (imtype==R_DPX) {
1256                 ibuf->ftype = DPX;
1257         }
1258 #endif
1259         else if (imtype==R_TARGA) {
1260                 ibuf->ftype= TGA;
1261         }
1262         else if(imtype==R_RAWTGA) {
1263                 ibuf->ftype= RAWTGA;
1264         }
1265 #ifdef WITH_OPENJPEG
1266         else if(imtype==R_JP2) {
1267                 if(quality < 10) quality= 90;
1268                 ibuf->ftype= JP2|quality;
1269                 
1270                 if (subimtype & R_JPEG2K_16BIT) {
1271                         ibuf->ftype |= JP2_16BIT;
1272                 } else if (subimtype & R_JPEG2K_12BIT) {
1273                         ibuf->ftype |= JP2_12BIT;
1274                 }
1275                 
1276                 if (subimtype & R_JPEG2K_YCC) {
1277                         ibuf->ftype |= JP2_YCC;
1278                 }
1279                 
1280                 if (subimtype & R_JPEG2K_CINE_PRESET) {
1281                         ibuf->ftype |= JP2_CINE;
1282                         if (subimtype & R_JPEG2K_CINE_48FPS)
1283                                 ibuf->ftype |= JP2_CINE_48FPS;
1284                 }
1285         }
1286 #endif
1287         else {
1288                 /* R_JPEG90, etc. default we save jpegs */
1289                 if(quality < 10) quality= 90;
1290                 ibuf->ftype= JPG|quality;
1291                 if(ibuf->depth==32) ibuf->depth= 24;    /* unsupported feature only confuses other s/w */
1292         }
1293         
1294         BLI_make_existing_file(name);
1295
1296         if(scene && scene->r.stamp & R_STAMP_ALL)
1297                 BKE_stamp_info(scene, ibuf);
1298         
1299         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1300         if (ok == 0) {
1301                 perror(name);
1302         }
1303         
1304         return(ok);
1305 }
1306
1307
1308 void BKE_makepicstring(char *string, char *base, int frame, int imtype, int use_ext)
1309 {
1310         if (string==NULL) return;
1311         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1312         BLI_path_abs(string, G.sce);
1313         BLI_path_frame(string, frame, 4);
1314
1315         if(use_ext)
1316                 BKE_add_image_extension(string, imtype);
1317                 
1318 }
1319
1320 /* used by sequencer too */
1321 struct anim *openanim(char *name, int flags)
1322 {
1323         struct anim *anim;
1324         struct ImBuf *ibuf;
1325         
1326         anim = IMB_open_anim(name, flags);
1327         if (anim == NULL) return(0);
1328
1329         ibuf = IMB_anim_absolute(anim, 0);
1330         if (ibuf == NULL) {
1331                 if(BLI_exists(name))
1332                         printf("not an anim: %s\n", name);
1333                 else
1334                         printf("anim file doesn't exist: %s\n", name);
1335                 IMB_free_anim(anim);
1336                 return(0);
1337         }
1338         IMB_freeImBuf(ibuf);
1339         
1340         return(anim);
1341 }
1342
1343 /* ************************* New Image API *************** */
1344
1345
1346 /* Notes about Image storage 
1347 - packedfile
1348   -> written in .blend
1349 - filename
1350   -> written in .blend
1351 - movie
1352   -> comes from packedfile or filename
1353 - renderresult
1354   -> comes from packedfile or filename
1355 - listbase
1356   -> ibufs from exrhandle
1357 - flipbook array
1358   -> ibufs come from movie, temporary renderresult or sequence
1359 - ibuf
1360   -> comes from packedfile or filename or generated
1361
1362 */
1363
1364
1365 /* forces existence of 1 Image for renderout or nodes, returns Image */
1366 /* name is only for default, when making new one */
1367 Image *BKE_image_verify_viewer(int type, const char *name)
1368 {
1369         Image *ima;
1370         
1371         for(ima=G.main->image.first; ima; ima= ima->id.next)
1372                 if(ima->source==IMA_SRC_VIEWER)
1373                         if(ima->type==type)
1374                                 break;
1375         
1376         if(ima==NULL)
1377                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1378         
1379         /* happens on reload, imagewindow cannot be image user when hidden*/
1380         if(ima->id.us==0)
1381                 id_us_plus(&ima->id);
1382
1383         return ima;
1384 }
1385
1386 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1387 {
1388         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1389 }
1390
1391 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1392 {
1393         if(ima==NULL)
1394                 return;
1395         
1396         switch(signal) {
1397         case IMA_SIGNAL_FREE:
1398                 image_free_buffers(ima);
1399                 if(iuser)
1400                         iuser->ok= 1;
1401                 break;
1402         case IMA_SIGNAL_SRC_CHANGE:
1403                 if(ima->type == IMA_TYPE_UV_TEST)
1404                         if(ima->source != IMA_SRC_GENERATED)
1405                                 ima->type= IMA_TYPE_IMAGE;
1406
1407                 if(ima->source==IMA_SRC_GENERATED) {
1408                         if(ima->gen_x==0 || ima->gen_y==0) {
1409                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1410                                 if(ibuf) {
1411                                         ima->gen_x= ibuf->x;
1412                                         ima->gen_y= ibuf->y;
1413                                 }
1414                         }
1415                 }
1416
1417                 image_free_buffers(ima);
1418
1419                 ima->ok= 1;
1420                 if(iuser)
1421                         iuser->ok= 1;
1422                 break;
1423                         
1424         case IMA_SIGNAL_RELOAD:
1425                 /* try to repack file */
1426                 if(ima->packedfile) {
1427                         PackedFile *pf;
1428                         pf = newPackedFile(NULL, ima->name);
1429                         if (pf) {
1430                                 freePackedFile(ima->packedfile);
1431                                 ima->packedfile = pf;
1432                                 image_free_buffers(ima);
1433                         } else {
1434                                 printf("ERROR: Image not available. Keeping packed image\n");
1435                         }
1436                 }
1437                 else
1438                         image_free_buffers(ima);
1439                 
1440                 if(iuser)
1441                         iuser->ok= 1;
1442                 
1443                 break;
1444         case IMA_SIGNAL_USER_NEW_IMAGE:
1445                 if(iuser) {
1446                         iuser->ok= 1;
1447                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1448                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1449                                         iuser->multi_index= 0;
1450                                         iuser->layer= iuser->pass= 0;
1451                                 }
1452                         }
1453                 }
1454                 break;
1455         }
1456         
1457         /* dont use notifiers because they are not 100% sure to succseed
1458          * this also makes sure all scenes are accounted for. */
1459         {
1460                 Scene *scene;
1461                 for(scene= G.main->scene.first; scene; scene= scene->id.next) {
1462                         if(scene->nodetree) {
1463                                 NodeTagIDChanged(scene->nodetree, &ima->id);
1464                         }
1465                 }
1466         }
1467 }
1468
1469 /* if layer or pass changes, we need an index for the imbufs list */
1470 /* note it is called for rendered results, but it doesnt use the index! */
1471 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1472 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1473 {
1474         RenderLayer *rl;
1475         RenderPass *rpass= NULL;
1476         
1477         if(rr==NULL) 
1478                 return NULL;
1479         
1480         if(iuser) {
1481                 short index= 0, rl_index= 0, rp_index;
1482                 
1483                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1484                         rp_index= 0;
1485                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1486                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1487                                         break;
1488                         if(rpass)
1489                                 break;
1490                 }
1491                 
1492                 if(rpass)
1493                         iuser->multi_index= index;
1494                 else 
1495                         iuser->multi_index= 0;
1496         }
1497         if(rpass==NULL) {
1498                 rl= rr->layers.first;
1499                 if(rl)
1500                         rpass= rl->passes.first;
1501         }
1502         
1503         return rpass;
1504 }
1505
1506 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
1507 {
1508         if(ima->rr) {
1509                 return ima->rr;
1510         }
1511         else if(ima->type==IMA_TYPE_R_RESULT) {
1512                 if(ima->render_slot == ima->last_render_slot)
1513                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
1514                 else
1515                         return ima->renders[ima->render_slot];
1516         }
1517         else
1518                 return NULL;
1519 }
1520
1521 void BKE_image_release_renderresult(Scene *scene, Image *ima)
1522 {
1523         if(ima->rr);
1524         else if(ima->type==IMA_TYPE_R_RESULT) {
1525                 if(ima->render_slot == ima->last_render_slot)
1526                         RE_ReleaseResult(RE_GetRender(scene->id.name));
1527         }
1528 }
1529
1530 void BKE_image_backup_render(Scene *scene, Image *ima)
1531 {
1532         /* called right before rendering, ima->renders contains render
1533            result pointers for everything but the current render */
1534         Render *re= RE_GetRender(scene->id.name);
1535         int slot= ima->render_slot, last= ima->last_render_slot;
1536
1537         if(slot != last) {
1538                 if(ima->renders[slot]) {
1539                         RE_FreeRenderResult(ima->renders[slot]);
1540                         ima->renders[slot]= NULL;
1541                 }
1542
1543                 ima->renders[last]= NULL;
1544                 RE_SwapResult(re, &ima->renders[last]);
1545         }
1546
1547         ima->last_render_slot= slot;
1548 }
1549
1550 /* after imbuf load, openexr type can return with a exrhandle open */
1551 /* in that case we have to build a render-result */
1552 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1553 {
1554         
1555         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1556
1557 #ifdef WITH_OPENEXR
1558         IMB_exr_close(ibuf->userdata);
1559 #endif
1560
1561         ibuf->userdata= NULL;
1562         if(ima->rr)
1563                 ima->rr->framenr= framenr;
1564 }
1565
1566 /* common stuff to do with images after loading */
1567 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1568 {
1569         
1570         
1571         /* preview is NULL when it has never been used as an icon before */
1572         if(G.background==0 && ima->preview==NULL)
1573                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1574         
1575         /* stringcodes also in ibuf, ibuf->name is used to retrieve original (buttons) */
1576         BLI_strncpy(ibuf->name, ima->name, FILE_MAX);
1577         
1578         /* fields */
1579         if (ima->flag & IMA_FIELDS) {
1580                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1581                 else de_interlace_ng(ibuf);
1582         }
1583         /* timer */
1584         ima->lastused = clock() / CLOCKS_PER_SEC;
1585         
1586         ima->ok= IMA_OK_LOADED;
1587         
1588 }
1589
1590 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1591 {
1592         struct ImBuf *ibuf;
1593         unsigned short numlen;
1594         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1595         int flag;
1596         
1597         /* XXX temp stuff? */
1598         if(ima->lastframe != frame)
1599                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1600
1601         ima->lastframe= frame;
1602
1603         BLI_stringdec(ima->name, head, tail, &numlen);
1604         BLI_stringenc(ima->name, head, tail, numlen, frame);
1605         BLI_strncpy(name, ima->name, sizeof(name));
1606         
1607         if(ima->id.lib)
1608                 BLI_path_abs(name, ima->id.lib->filepath);
1609         else
1610                 BLI_path_abs(name, G.sce);
1611         
1612         flag= IB_rect|IB_multilayer;
1613         if(ima->flag & IMA_DO_PREMUL)
1614                 flag |= IB_premul;
1615
1616         /* read ibuf */
1617         ibuf = IMB_loadiffname(name, flag);
1618         if(G.f & G_DEBUG) printf("loaded %s\n", name);
1619         
1620         if (ibuf) {
1621 #ifdef WITH_OPENEXR
1622                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1623                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1624                         image_create_multilayer(ima, ibuf, frame);      
1625                         ima->type= IMA_TYPE_MULTILAYER;
1626                         IMB_freeImBuf(ibuf);
1627                         ibuf= NULL;
1628                 }
1629                 else {
1630                         image_initialize_after_load(ima, ibuf);
1631                         image_assign_ibuf(ima, ibuf, 0, frame);
1632                 }
1633 #else
1634                 image_initialize_after_load(ima, ibuf);
1635                 image_assign_ibuf(ima, ibuf, 0, frame);
1636 #endif
1637         }
1638         else
1639                 ima->ok= 0;
1640         
1641         if(iuser)
1642                 iuser->ok= ima->ok;
1643         
1644         return ibuf;
1645 }
1646
1647 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1648 {
1649         struct ImBuf *ibuf= NULL;
1650         
1651         /* either we load from RenderResult, or we have to load a new one */
1652         
1653         /* check for new RenderResult */
1654         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1655                 /* copy to survive not found multilayer image */
1656                 RenderResult *oldrr= ima->rr;
1657         
1658                 ima->rr= NULL;
1659                 ibuf = image_load_sequence_file(ima, iuser, frame);
1660                 
1661                 if(ibuf) { /* actually an error */
1662                         ima->type= IMA_TYPE_IMAGE;
1663                         printf("error, multi is normal image\n");
1664                 }
1665                 // printf("loaded new result %p\n", ima->rr);
1666                 /* free result if new one found */
1667                 if(ima->rr) {
1668                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1669                         if(oldrr) RE_FreeRenderResult(oldrr);
1670                 }
1671                 else {
1672                         ima->rr= oldrr;
1673                 }
1674
1675         }
1676         if(ima->rr) {
1677                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1678                 
1679                 if(rpass) {
1680                         // printf("load from pass %s\n", rpass->name);
1681                         /* since we free  render results, we copy the rect */
1682                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1683                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1684                         ibuf->flags |= IB_rectfloat;
1685                         ibuf->mall= IB_rectfloat;
1686                         ibuf->channels= rpass->channels;
1687                         
1688                         image_initialize_after_load(ima, ibuf);
1689                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
1690                         
1691                 }
1692                 // else printf("pass not found\n");
1693         }
1694         else
1695                 ima->ok= 0;
1696         
1697         if(iuser)
1698                 iuser->ok= ima->ok;
1699         
1700         return ibuf;
1701 }
1702
1703
1704 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
1705 {
1706         struct ImBuf *ibuf= NULL;
1707         
1708         ima->lastframe= frame;
1709         
1710         if(ima->anim==NULL) {
1711                 char str[FILE_MAX];
1712                 
1713                 BLI_strncpy(str, ima->name, FILE_MAX);
1714                 if(ima->id.lib)
1715                         BLI_path_abs(str, ima->id.lib->filepath);
1716                 else
1717                         BLI_path_abs(str, G.sce);
1718                 
1719                 ima->anim = openanim(str, IB_rect);
1720                 
1721                 /* let's initialize this user */
1722                 if(ima->anim && iuser && iuser->frames==0)
1723                         iuser->frames= IMB_anim_get_duration(ima->anim);
1724         }
1725         
1726         if(ima->anim) {
1727                 int dur = IMB_anim_get_duration(ima->anim);
1728                 int fra= frame-1;
1729                 
1730                 if(fra<0) fra = 0;
1731                 if(fra>(dur-1)) fra= dur-1;
1732                 ibuf = IMB_anim_absolute(ima->anim, fra);
1733                 
1734                 if(ibuf) {
1735                         image_initialize_after_load(ima, ibuf);
1736                         image_assign_ibuf(ima, ibuf, 0, frame);
1737                 }
1738                 else
1739                         ima->ok= 0;
1740         }
1741         else
1742                 ima->ok= 0;
1743         
1744         if(iuser)
1745                 iuser->ok= ima->ok;
1746         
1747         return ibuf;
1748 }
1749
1750 /* cfra used for # code, Image can only have this # for all its users
1751  * warning, 'iuser' can be NULL */
1752 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
1753 {
1754         struct ImBuf *ibuf;
1755         char str[FILE_MAX];
1756         int assign = 0, flag;
1757         
1758         /* always ensure clean ima */
1759         image_free_buffers(ima);
1760         
1761         /* is there a PackedFile with this image ? */
1762         if (ima->packedfile) {
1763                 flag = IB_rect|IB_multilayer;
1764                 if(ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
1765                 
1766                 ibuf = IMB_ibImageFromMemory((unsigned char*)ima->packedfile->data, ima->packedfile->size, flag);
1767         } 
1768         else {
1769                 flag= IB_rect|IB_multilayer|IB_metadata;
1770                 if(ima->flag & IMA_DO_PREMUL)
1771                         flag |= IB_premul;
1772                         
1773                 /* get the right string */
1774                 BLI_strncpy(str, ima->name, sizeof(str));
1775                 if(ima->id.lib)
1776                         BLI_path_abs(str, ima->id.lib->filepath);
1777                 else
1778                         BLI_path_abs(str, G.sce);
1779                 
1780                 /* read ibuf */
1781                 ibuf = IMB_loadiffname(str, flag);
1782         }
1783         
1784         if (ibuf) {
1785                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1786                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1787                         image_create_multilayer(ima, ibuf, cfra);       
1788                         ima->type= IMA_TYPE_MULTILAYER;
1789                         IMB_freeImBuf(ibuf);
1790                         ibuf= NULL;
1791                 }
1792                 else {
1793                         image_initialize_after_load(ima, ibuf);
1794                         assign= 1;
1795
1796                         /* check if the image is a font image... */
1797                         detectBitmapFont(ibuf);
1798                         
1799                         /* make packed file for autopack */
1800                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
1801                                 ima->packedfile = newPackedFile(NULL, str);
1802                 }
1803         }
1804         else
1805                 ima->ok= 0;
1806         
1807         if(assign)
1808                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1809
1810         if(iuser)
1811                 iuser->ok= ima->ok;
1812         
1813         return ibuf;
1814 }
1815
1816 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
1817 {
1818         ImBuf *ibuf= NULL;
1819         
1820         if(ima->rr==NULL) {
1821                 ibuf = image_load_image_file(ima, iuser, 0);
1822                 if(ibuf) { /* actually an error */
1823                         ima->type= IMA_TYPE_IMAGE;
1824                         return ibuf;
1825                 }
1826         }
1827         if(ima->rr) {
1828                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1829
1830                 if(rpass) {
1831                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1832                         
1833                         image_initialize_after_load(ima, ibuf);
1834                         
1835                         ibuf->rect_float= rpass->rect;
1836                         ibuf->flags |= IB_rectfloat;
1837                         ibuf->channels= rpass->channels;
1838                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1839
1840                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1841                 }
1842         }
1843         
1844         if(ibuf==NULL) 
1845                 ima->ok= 0;
1846         if(iuser)
1847                 iuser->ok= ima->ok;
1848         
1849         return ibuf;
1850 }
1851
1852
1853 /* showing RGBA result itself (from compo/sequence) or
1854    like exr, using layers etc */
1855 /* always returns a single ibuf, also during render progress */
1856 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
1857 {
1858         Render *re;
1859         RenderResult rres;
1860         float *rectf, *rectz;
1861         unsigned int *rect;
1862         float dither;
1863         int channels, layer, pass;
1864         ImBuf *ibuf;
1865         int from_render= (ima->render_slot == ima->last_render_slot);
1866
1867         if(!(iuser && iuser->scene))
1868                 return NULL;
1869
1870         /* if we the caller is not going to release the lock, don't give the image */
1871         if(!lock_r)
1872                 return NULL;
1873
1874         re= RE_GetRender(iuser->scene->id.name);
1875
1876         channels= 4;
1877         layer= (iuser)? iuser->layer: 0;
1878         pass= (iuser)? iuser->pass: 0;
1879
1880         if(from_render) {
1881                 RE_AcquireResultImage(re, &rres);
1882         }
1883         else if(ima->renders[ima->render_slot]) {
1884                 rres= *(ima->renders[ima->render_slot]);
1885                 rres.have_combined= rres.rectf != NULL;
1886         }
1887         else
1888                 memset(&rres, 0, sizeof(RenderResult));
1889         
1890         if(!(rres.rectx > 0 && rres.recty > 0)) {
1891                 if(from_render)
1892                         RE_ReleaseResultImage(re);
1893                 return NULL;
1894         }
1895
1896         /* release is done in BKE_image_release_ibuf using lock_r */
1897         if(from_render) {
1898                 BLI_lock_thread(LOCK_VIEWER);
1899                 *lock_r= re;
1900         }
1901
1902         /* this gives active layer, composite or seqence result */
1903         rect= (unsigned int *)rres.rect32;
1904         rectf= rres.rectf;
1905         rectz= rres.rectz;
1906         dither= iuser->scene->r.dither_intensity;
1907
1908         /* combined layer gets added as first layer */
1909         if(rres.have_combined && layer==0);
1910         else if(rres.layers.first) {
1911                 RenderLayer *rl= BLI_findlink(&rres.layers, layer-(rres.have_combined?1:0));
1912                 if(rl) {
1913                         RenderPass *rpass;
1914
1915                         /* there's no combined pass, is in renderlayer itself */
1916                         if(pass==0) {
1917                                 rectf= rl->rectf;
1918                         }
1919                         else {
1920                                 rpass= BLI_findlink(&rl->passes, pass-1);
1921                                 if(rpass) {
1922                                         channels= rpass->channels;
1923                                         rectf= rpass->rect;
1924                                         dither= 0.0f; /* don't dither passes */
1925                                 }
1926                         }
1927
1928                         for(rpass= rl->passes.first; rpass; rpass= rpass->next)
1929                                 if(rpass->passtype == SCE_PASS_Z)
1930                                         rectz= rpass->rect;
1931                 }
1932         }
1933
1934         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1935
1936         /* make ibuf if needed, and initialize it */
1937         if(ibuf==NULL) {
1938                 ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, 0, 0);
1939                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1940         }
1941
1942         ibuf->x= rres.rectx;
1943         ibuf->y= rres.recty;
1944         
1945         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
1946                 imb_freerectImBuf(ibuf);
1947
1948         if(rect)
1949                 ibuf->rect= rect;
1950         
1951         if(rectf) {
1952                 ibuf->rect_float= rectf;
1953                 ibuf->flags |= IB_rectfloat;
1954                 ibuf->channels= channels;
1955         }
1956         else {
1957                 ibuf->rect_float= NULL;
1958                 ibuf->flags &= ~IB_rectfloat;
1959         }
1960
1961         if(rectz) {
1962                 ibuf->zbuf_float= rectz;
1963                 ibuf->flags |= IB_zbuffloat;
1964         }
1965         else {
1966                 ibuf->zbuf_float= NULL;
1967                 ibuf->flags &= ~IB_zbuffloat;
1968         }
1969
1970         ibuf->dither= dither;
1971
1972         ima->ok= IMA_OK_LOADED;
1973
1974         return ibuf;
1975 }
1976
1977 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
1978 {
1979         ImBuf *ibuf = NULL;
1980         int frame = 0, index = 0;
1981
1982         /* see if we already have an appropriate ibuf, with image source and type */
1983         if(ima->source==IMA_SRC_MOVIE) {
1984                 frame= iuser?iuser->framenr:ima->lastframe;
1985                 ibuf= image_get_ibuf(ima, 0, frame);
1986                 /* XXX temp stuff? */
1987                 if(ima->lastframe != frame)
1988                         ima->tpageflag |= IMA_TPAGE_REFRESH;
1989                 ima->lastframe = frame;
1990         }
1991         else if(ima->source==IMA_SRC_SEQUENCE) {
1992                 if(ima->type==IMA_TYPE_IMAGE) {
1993                         frame= iuser?iuser->framenr:ima->lastframe;
1994                         ibuf= image_get_ibuf(ima, 0, frame);
1995                         
1996                         /* XXX temp stuff? */
1997                         if(ima->lastframe != frame) {
1998                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1999                                 if(ibuf) {
2000                                         /* without this the image name only updates
2001                                          * on first load which is quite confusing */
2002                                         BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
2003                                 }
2004                         }
2005                         ima->lastframe = frame;
2006                 }       
2007                 else if(ima->type==IMA_TYPE_MULTILAYER) {
2008                         frame= iuser?iuser->framenr:ima->lastframe;
2009                         index= iuser?iuser->multi_index:IMA_NO_INDEX;
2010                         ibuf= image_get_ibuf(ima, index, frame);
2011                 }
2012         }
2013         else if(ima->source==IMA_SRC_FILE) {
2014                 if(ima->type==IMA_TYPE_IMAGE)
2015                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2016                 else if(ima->type==IMA_TYPE_MULTILAYER)
2017                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2018         }
2019         else if(ima->source == IMA_SRC_GENERATED) {
2020                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2021         }
2022         else if(ima->source == IMA_SRC_VIEWER) {
2023                 /* always verify entirely, not that this shouldn't happen
2024                  * as part of texture sampling in rendering anyway, so not
2025                  * a big bottleneck */
2026         }
2027
2028         *frame_r = frame;
2029         *index_r = index;
2030
2031         return ibuf;
2032 }
2033
2034 /* Checks optional ImageUser and verifies/creates ImBuf. */
2035 /* use this one if you want to get a render result in progress,
2036  * if not, use BKE_image_get_ibuf which doesn't require a release */
2037 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2038 {
2039         ImBuf *ibuf= NULL;
2040         float color[] = {0, 0, 0, 1};
2041         int frame= 0, index= 0;
2042
2043         /* This function is intended to be thread-safe. It postpones the mutex lock
2044          * until it needs to load the image, if the image is already there it
2045          * should just get the pointer and return. The reason is that a lot of mutex
2046          * locks appears to be very slow on certain multicore macs, causing a render
2047          * with image textures to actually slow down as more threads are used.
2048          *
2049          * Note that all the image loading functions should also make sure they do
2050          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2051          * That means, the last two steps must be, 1) add the ibuf to the list and
2052          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2053         
2054         if(lock_r)
2055                 *lock_r= NULL;
2056
2057         /* quick reject tests */
2058         if(ima==NULL) 
2059                 return NULL;
2060         if(iuser) {
2061                 if(iuser->ok==0)
2062                         return NULL;
2063         }
2064         else if(ima->ok==0)
2065                 return NULL;
2066         
2067         /* try to get the ibuf without locking */
2068         ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2069
2070         if(ibuf == NULL) {
2071                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2072                  * load the image */
2073                 BLI_lock_thread(LOCK_IMAGE);
2074
2075                 /* need to check ok flag and loading ibuf again, because the situation
2076                  * might have changed in the meantime */
2077                 if(iuser) {
2078                         if(iuser->ok==0) {
2079                                 BLI_unlock_thread(LOCK_IMAGE);
2080                                 return NULL;
2081                         }
2082                 }
2083                 else if(ima->ok==0) {
2084                         BLI_unlock_thread(LOCK_IMAGE);
2085                         return NULL;
2086                 }
2087
2088                 ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2089
2090                 if(ibuf == NULL) {
2091                         /* we are sure we have to load the ibuf, using source and type */
2092                         if(ima->source==IMA_SRC_MOVIE) {
2093                                 /* source is from single file, use flipbook to store ibuf */
2094                                 ibuf= image_load_movie_file(ima, iuser, frame);
2095                         }
2096                         else if(ima->source==IMA_SRC_SEQUENCE) {
2097                                 if(ima->type==IMA_TYPE_IMAGE) {
2098                                         /* regular files, ibufs in flipbook, allows saving */
2099                                         ibuf= image_load_sequence_file(ima, iuser, frame);
2100                                 }
2101                                 /* no else; on load the ima type can change */
2102                                 if(ima->type==IMA_TYPE_MULTILAYER) {
2103                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2104                                         ibuf= image_load_sequence_multilayer(ima, iuser, frame);
2105                                 }
2106
2107                                 if(ibuf)
2108                                         BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
2109                         }
2110                         else if(ima->source==IMA_SRC_FILE) {
2111                                 
2112                                 if(ima->type==IMA_TYPE_IMAGE)
2113                                         ibuf= image_load_image_file(ima, iuser, frame); /* cfra only for '#', this global is OK */
2114                                 /* no else; on load the ima type can change */
2115                                 if(ima->type==IMA_TYPE_MULTILAYER)
2116                                         /* keeps render result, stores ibufs in listbase, allows saving */
2117                                         ibuf= image_get_ibuf_multilayer(ima, iuser);
2118                                         
2119                         }
2120                         else if(ima->source == IMA_SRC_GENERATED) {
2121                                 /* generated is: ibuf is allocated dynamically */
2122                                 /* UV testgrid or black or solid etc */
2123                                 if(ima->gen_x==0) ima->gen_x= 1024;
2124                                 if(ima->gen_y==0) ima->gen_y= 1024;
2125                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, 0, ima->gen_type, color);
2126                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2127                                 ima->ok= IMA_OK_LOADED;
2128                         }
2129                         else if(ima->source == IMA_SRC_VIEWER) {
2130                                 if(ima->type==IMA_TYPE_R_RESULT) {
2131                                         /* always verify entirely, and potentially
2132                                            returns pointer to release later */
2133                                         ibuf= image_get_render_result(ima, iuser, lock_r);
2134                                 }
2135                                 else if(ima->type==IMA_TYPE_COMPOSITE) {
2136                                         /* requires lock/unlock, otherwise don't return image */
2137                                         if(lock_r) {
2138                                                 /* unlock in BKE_image_release_ibuf */
2139                                                 BLI_lock_thread(LOCK_VIEWER);
2140                                                 *lock_r= ima;
2141
2142                                                 frame= iuser?iuser->framenr:0;
2143                                                 ibuf= image_get_ibuf(ima, 0, frame);
2144
2145                                                 if(!ibuf) {
2146                                                         /* Composite Viewer, all handled in compositor */
2147                                                         /* fake ibuf, will be filled in compositor */
2148                                                         ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
2149                                                         image_assign_ibuf(ima, ibuf, 0, frame);
2150                                                 }
2151                                         }
2152                                 }
2153                         }
2154                 }
2155
2156                 BLI_unlock_thread(LOCK_IMAGE);
2157         }
2158
2159         /* we assuming that if it is not rendering, it's also not multithreaded
2160          * (a somewhat weak assumption) */
2161         if(G.rendering==0)
2162                 tag_image_time(ima);
2163
2164         return ibuf;
2165 }
2166
2167 void BKE_image_release_ibuf(Image *ima, void *lock)
2168 {
2169         /* for getting image during threaded render / compositing, need to release */
2170         if(lock == ima) {
2171                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2172         }
2173         else if(lock) {
2174                 RE_ReleaseResultImage(lock); /* render result */
2175                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2176         }
2177 }
2178
2179 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2180 {
2181         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2182 }
2183
2184 void BKE_image_user_calc_frame(ImageUser *iuser, int cfra, int fieldnr)
2185 {
2186         int imanr, len;
2187         
2188         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2189         len= (iuser->fie_ima*iuser->frames)/2;
2190         
2191         if(len==0) {
2192                 iuser->framenr= 0;
2193         }
2194         else {
2195                 cfra= cfra - iuser->sfra+1;
2196                 
2197                 /* cyclic */
2198                 if(iuser->cycl) {
2199                         cfra= ( (cfra) % len );
2200                         if(cfra < 0) cfra+= len;
2201                         if(cfra==0) cfra= len;
2202                 }
2203                 
2204                 if(cfra<1) cfra= 1;
2205                 else if(cfra>len) cfra= len;
2206                 
2207                 /* convert current frame to current field */
2208                 cfra= 2*(cfra);
2209                 if(fieldnr) cfra++;
2210                 
2211                 /* transform to images space */
2212                 imanr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
2213                 if(imanr>iuser->frames) imanr= iuser->frames;
2214                 imanr+= iuser->offset;
2215                 
2216                 if(iuser->cycl) {
2217                         imanr= ( (imanr) % len );
2218                         while(imanr < 0) imanr+= len;
2219                         if(imanr==0) imanr= len;
2220                 }
2221         
2222                 /* allows image users to handle redraws */
2223                 if(iuser->flag & IMA_ANIM_ALWAYS)
2224                         if(imanr!=iuser->framenr)
2225                                 iuser->flag |= IMA_ANIM_REFRESHED;
2226                 
2227                 iuser->framenr= imanr;
2228                 if(iuser->ok==0) iuser->ok= 1;
2229         }
2230 }