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