BugFix:
[blender-staging.git] / source / blender / blenkernel / intern / image.c
1 /*  image.c
2  * 
3  * $Id$
4  *
5  * ***** BEGIN GPL LICENSE BLOCK *****
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20  *
21  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
22  * All rights reserved.
23  *
24  * Contributor(s): Blender Foundation, 2006, full recode
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #include <stdio.h>
30 #include <string.h>
31 #include <fcntl.h>
32 #include <math.h>
33 #ifndef WIN32 
34 #include <unistd.h>
35 #else
36 #include <io.h>
37 #endif
38
39 #include <time.h>
40
41 #ifdef _WIN32
42 #define open _open
43 #define close _close
44 #endif
45
46 #include "MEM_guardedalloc.h"
47
48 #include "IMB_imbuf_types.h"
49 #include "IMB_imbuf.h"
50
51 #ifdef WITH_OPENEXR
52 #include "intern/openexr/openexr_multi.h"
53 #endif
54
55 #include "DNA_packedFile_types.h"
56 #include "DNA_scene_types.h"
57 #include "DNA_camera_types.h"
58 #include "DNA_sequence_types.h"
59 #include "DNA_userdef_types.h"
60
61 #include "BLI_blenlib.h"
62 #include "BLI_threads.h"
63
64 #include "BKE_bmfont.h"
65 #include "BKE_global.h"
66 #include "BKE_icons.h"
67 #include "BKE_image.h"
68 #include "BKE_library.h"
69 #include "BKE_main.h"
70 #include "BKE_packedFile.h"
71 #include "BKE_scene.h"
72
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         struct tm *tl;
893         time_t t;
894
895         if (scene->r.stamp & R_STAMP_FILENAME) {
896                 if (G.relbase_valid) {
897                         if (do_prefix)          sprintf(stamp_data->file, "File %s", G.sce);
898                         else                            sprintf(stamp_data->file, "%s", G.sce);
899                 } else {
900                         if (do_prefix)          strcpy(stamp_data->file, "File <untitled>");
901                         else                            strcpy(stamp_data->file, "<untitled>");
902                 }
903         } else {
904                 stamp_data->file[0] = '\0';
905         }
906         
907         if (scene->r.stamp & R_STAMP_NOTE) {
908                 /* Never do prefix for Note */
909                 sprintf(stamp_data->note, "%s", scene->r.stamp_udata);
910         } else {
911                 stamp_data->note[0] = '\0';
912         }
913         
914         if (scene->r.stamp & R_STAMP_DATE) {
915
916                 t = time (NULL);
917                 tl = localtime (&t);
918                 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);
919
920                 if (do_prefix)          sprintf(stamp_data->date, "Date %s", text);
921                 else                            sprintf(stamp_data->date, "%s", text);
922         } else {
923                 stamp_data->date[0] = '\0';
924         }
925         
926         if (scene->r.stamp & R_STAMP_MARKER) {
927                 char *name = scene_find_last_marker_name(scene, CFRA);
928         
929                 if (name)       strcpy(text, name);
930                 else            strcpy(text, "<none>");
931                 
932                 if (do_prefix)          sprintf(stamp_data->marker, "Marker %s", text);
933                 else                            sprintf(stamp_data->marker, "%s", text);
934         } else {
935                 stamp_data->marker[0] = '\0';
936         }
937         
938         if (scene->r.stamp & R_STAMP_TIME) {
939                 int h, m, s, f;
940                 h= m= s= f= 0;
941                 f = (int)(scene->r.cfra % scene->r.frs_sec);
942                 s = (int)(scene->r.cfra / scene->r.frs_sec);
943
944                 if (s) {
945                         m = (int)(s / 60);
946                         s %= 60;
947
948                         if (m) {
949                                 h = (int)(m / 60);
950                                 m %= 60;
951                         }
952                 }
953
954                 if (scene->r.frs_sec < 100)
955                         sprintf (text, "%02d:%02d:%02d.%02d", h, m, s, f);
956                 else
957                         sprintf (text, "%02d:%02d:%02d.%03d", h, m, s, f);
958                 
959                 if (do_prefix)          sprintf(stamp_data->time, "Time %s", text);
960                 else                            sprintf(stamp_data->time, "%s", text);
961         } else {
962                 stamp_data->time[0] = '\0';
963         }
964         
965         if (scene->r.stamp & R_STAMP_FRAME) {
966                 char format[32];
967                 if (do_prefix)          sprintf(format, "Frame %%0%di", 1 + (int) log10(scene->r.efra));
968                 else                            sprintf(format, "%%0%di", 1 + (int) log10(scene->r.efra));
969                 sprintf (stamp_data->frame, format, scene->r.cfra);
970         } else {
971                 stamp_data->frame[0] = '\0';
972         }
973
974         if (scene->r.stamp & R_STAMP_CAMERA) {
975                 if (scene->camera) strcpy(text, ((Camera *) scene->camera)->id.name+2);
976                 else            strcpy(text, "<none>");
977                 
978                 if (do_prefix)          sprintf(stamp_data->camera, "Camera %s", text);
979                 else                            sprintf(stamp_data->camera, "%s", text);
980         } else {
981                 stamp_data->camera[0] = '\0';
982         }
983
984         if (scene->r.stamp & R_STAMP_SCENE) {
985                 if (do_prefix)          sprintf(stamp_data->scene, "Scene %s", scene->id.name+2);
986                 else                            sprintf(stamp_data->scene, "%s", scene->id.name+2);
987         } else {
988                 stamp_data->scene[0] = '\0';
989         }
990         
991         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
992                 Sequence *seq= NULL; //XXX = get_foreground_frame_seq(scene->r.cfra);
993         
994                 if (seq) strcpy(text, seq->name+2);
995                 else            strcpy(text, "<none>");
996                 
997                 if (do_prefix)          sprintf(stamp_data->strip, "Strip %s", text);
998                 else                            sprintf(stamp_data->strip, "%s", text);
999         } else {
1000                 stamp_data->strip[0] = '\0';
1001         }
1002
1003         {
1004                 Render *re= RE_GetRender(scene->id.name);
1005                 RenderStats *stats= re ? RE_GetStats(re):NULL;
1006
1007                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1008                         BLI_timestr(stats->lastframetime, text);
1009
1010                         if (do_prefix)          sprintf(stamp_data->rendertime, "RenderTime %s", text);
1011                         else                            sprintf(stamp_data->rendertime, "%s", text);
1012                 } else {
1013                         stamp_data->rendertime[0] = '\0';
1014                 }
1015         }
1016 }
1017
1018 // XXX - Bad level call.
1019 extern int datatoc_bmonofont_ttf_size;
1020 extern char datatoc_bmonofont_ttf[];
1021
1022 // XXX - copied from text_font_begin ! Change all the BLF_* here
1023 static int mono= -1;
1024
1025 int stamp_font_begin(int size)
1026 {
1027         if (mono == -1)
1028                 mono= BLF_load_mem_unique("monospace", (unsigned char *)datatoc_bmonofont_ttf, datatoc_bmonofont_ttf_size);
1029
1030         BLF_aspect(mono, 1.0);
1031         BLF_size(mono, size, 72);
1032         return(mono); // XXX This is for image_gen.c!!
1033 }
1034
1035 void BKE_stamp_buf(Scene *scene, unsigned char *rect, float *rectf, int width, int height, int channels)
1036 {
1037         struct StampData stamp_data;
1038         float w, h, pad;
1039         int x, y;
1040         
1041         if (!rect && !rectf)
1042                 return;
1043         
1044         stampdata(scene, &stamp_data, 1);
1045
1046         /* TODO, do_versions */
1047         if(scene->r.stamp_font_id < 8)
1048                 scene->r.stamp_font_id= 12;
1049
1050         stamp_font_begin(scene->r.stamp_font_id);
1051
1052         BLF_buffer(mono, rectf, rect, width, height, channels);
1053         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1054         pad= BLF_width(mono, "--");
1055
1056         x= 0;
1057         y= height;
1058
1059         if (stamp_data.file[0]) {
1060                 /* Top left corner */
1061                 BLF_width_and_height(mono, stamp_data.file, &w, &h);
1062                 y -= h;
1063
1064                 /* also a little of space to the background. */
1065                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y-3, w+3, y+h+3);
1066
1067                 /* and draw the text. */
1068                 BLF_position(mono, x, y, 0.0);
1069                 BLF_draw_buffer(mono, stamp_data.file);
1070
1071                 /* the extra pixel for background. */
1072                 y -= 4;
1073         }
1074
1075         /* Top left corner, below File */
1076         if (stamp_data.note[0]) {
1077                 BLF_width_and_height(mono, stamp_data.note, &w, &h);
1078                 y -= h;
1079
1080                 /* and space for background. */
1081                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-2, w+3, y+h+2);
1082
1083                 BLF_position(mono, x, y+1, 0.0);
1084                 BLF_draw_buffer(mono, stamp_data.note);
1085
1086                 /* the extra pixel for background. */
1087                 y -= 4;
1088         }
1089         
1090         /* Top left corner, below File (or Note) */
1091         if (stamp_data.date[0]) {
1092                 BLF_width_and_height(mono, stamp_data.date, &w, &h);
1093                 y -= h;
1094
1095                 /* and space for background. */
1096                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-3, w+3, y+h+3);
1097
1098                 BLF_position(mono, x, y, 0.0);
1099                 BLF_draw_buffer(mono, stamp_data.date);
1100
1101                 /* the extra pixel for background. */
1102                 y -= 4;
1103         }
1104
1105         /* Top left corner, below File, Date or Note */
1106         if (stamp_data.rendertime[0]) {
1107                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h);
1108                 y -= h;
1109
1110                 /* and space for background. */
1111                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-3, w+3, y+h+3);
1112
1113                 BLF_position(mono, x, y, 0.0);
1114                 BLF_draw_buffer(mono, stamp_data.rendertime);
1115         }
1116
1117         x= 0;
1118         y= 0;
1119
1120         /* Bottom left corner, leaving space for timing */
1121         if (stamp_data.marker[0]) {
1122                 BLF_width_and_height(mono, stamp_data.marker, &w, &h);
1123
1124                 /* extra space for background. */
1125                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, w+2, y+h+3);
1126
1127                 /* and pad the text. */
1128                 BLF_position(mono, x, y+3, 0.0);
1129                 BLF_draw_buffer(mono, stamp_data.marker);
1130
1131                 /* space width. */
1132                 x += w + pad;
1133         }
1134         
1135         /* Left bottom corner */
1136         if (stamp_data.time[0]) {
1137                 BLF_width_and_height(mono, stamp_data.time, &w, &h);
1138
1139                 /* extra space for background */
1140                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+3);
1141
1142                 /* and pad the text. */
1143                 BLF_position(mono, x, y+3, 0.0);
1144                 BLF_draw_buffer(mono, stamp_data.time);
1145
1146                 /* space width. */
1147                 x += w + pad;
1148         }
1149         
1150         if (stamp_data.frame[0]) {
1151                 BLF_width_and_height(mono, stamp_data.frame, &w, &h);
1152
1153                 /* extra space for background. */
1154                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+3);
1155
1156                 /* and pad the text. */
1157                 BLF_position(mono, x, y+3, 0.0);
1158                 BLF_draw_buffer(mono, stamp_data.frame);
1159
1160                 /* space width. */
1161                 x += w + pad;
1162         }
1163
1164         if (stamp_data.camera[0]) {
1165                 BLF_width_and_height(mono, stamp_data.camera, &w, &h);
1166
1167                 /* extra space for background. */
1168                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+3);
1169                 BLF_position(mono, x, y+3, 0.0);
1170                 BLF_draw_buffer(mono, stamp_data.camera);
1171         }
1172         
1173         if (stamp_data.scene[0]) {
1174                 BLF_width_and_height(mono, stamp_data.scene, &w, &h);
1175
1176                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1177                 x= width - w - 2;
1178
1179                 /* extra space for background. */
1180                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+3, y+h+3);
1181
1182                 /* and pad the text. */
1183                 BLF_position(mono, x, y+3, 0.0);
1184                 BLF_draw_buffer(mono, stamp_data.scene);
1185         }
1186         
1187         if (stamp_data.strip[0]) {
1188                 BLF_width_and_height(mono, stamp_data.scene, &w, &h);
1189
1190                 /* Top right corner, with an extra space because blenfont is too strict! */
1191                 x= width - w - pad;
1192                 y= height - h;
1193
1194                 /* extra space for background. */
1195                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y-3, x+w+pad, y+h+3);
1196
1197                 BLF_position(mono, x, y, 0.0);
1198                 BLF_draw_buffer(mono, stamp_data.strip);
1199         }
1200
1201         /* cleanup the buffer. */
1202         BLF_buffer(mono, NULL, NULL, 0, 0, 0);
1203 }
1204
1205 void BKE_stamp_info(Scene *scene, struct ImBuf *ibuf)
1206 {
1207         struct StampData stamp_data;
1208
1209         if (!ibuf)      return;
1210         
1211         /* fill all the data values, no prefix */
1212         stampdata(scene, &stamp_data, 0);
1213         
1214         if (stamp_data.file[0])         IMB_imginfo_change_field (ibuf, "File",         stamp_data.file);
1215         if (stamp_data.note[0])         IMB_imginfo_change_field (ibuf, "Note",         stamp_data.note);
1216         if (stamp_data.date[0])         IMB_imginfo_change_field (ibuf, "Date",         stamp_data.date);
1217         if (stamp_data.marker[0])       IMB_imginfo_change_field (ibuf, "Marker",       stamp_data.marker);
1218         if (stamp_data.time[0])         IMB_imginfo_change_field (ibuf, "Time",         stamp_data.time);
1219         if (stamp_data.frame[0])        IMB_imginfo_change_field (ibuf, "Frame",        stamp_data.frame);
1220         if (stamp_data.camera[0])       IMB_imginfo_change_field (ibuf, "Camera",       stamp_data.camera);
1221         if (stamp_data.scene[0])        IMB_imginfo_change_field (ibuf, "Scene",        stamp_data.scene);
1222         if (stamp_data.strip[0])        IMB_imginfo_change_field (ibuf, "Strip",        stamp_data.strip);
1223 }
1224
1225 int BKE_write_ibuf(Scene *scene, ImBuf *ibuf, char *name, int imtype, int subimtype, int quality)
1226 {
1227         int ok;
1228         
1229         if(imtype==0);
1230         else if(imtype== R_IRIS) 
1231                 ibuf->ftype= IMAGIC;
1232         else if ((imtype==R_RADHDR)) {
1233                 ibuf->ftype= RADHDR;
1234         }
1235         else if (ELEM5(imtype, R_PNG, R_FFMPEG, R_H264, R_THEORA, R_XVID)) {
1236                 ibuf->ftype= PNG;
1237         }
1238 #ifdef WITH_DDS
1239         else if ((imtype==R_DDS)) {
1240                 ibuf->ftype= DDS;
1241         }
1242 #endif
1243         else if ((imtype==R_BMP)) {
1244                 ibuf->ftype= BMP;
1245         }
1246         else if ((G.have_libtiff) && (imtype==R_TIFF)) {
1247                 ibuf->ftype= TIF;
1248
1249                 if(subimtype & R_TIFF_16BIT)
1250                         ibuf->ftype |= TIF_16BIT;
1251         }
1252 #ifdef WITH_OPENEXR
1253         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
1254                 ibuf->ftype= OPENEXR;
1255                 if(subimtype & R_OPENEXR_HALF)
1256                         ibuf->ftype |= OPENEXR_HALF;
1257                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
1258                 
1259                 if(!(subimtype & R_OPENEXR_ZBUF))
1260                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1261                 
1262         }
1263 #endif
1264         else if (imtype==R_CINEON) {
1265                 ibuf->ftype = CINEON;
1266         }
1267         else if (imtype==R_DPX) {
1268                 ibuf->ftype = DPX;
1269         }
1270         else if (imtype==R_TARGA) {
1271                 ibuf->ftype= TGA;
1272         }
1273         else if(imtype==R_RAWTGA) {
1274                 ibuf->ftype= RAWTGA;
1275         }
1276         else if(imtype==R_HAMX) {
1277                 ibuf->ftype= AN_hamx;
1278         }
1279 #ifdef WITH_OPENJPEG
1280         else if(imtype==R_JP2) {
1281                 if(quality < 10) quality= 90;
1282                 ibuf->ftype= JP2|quality;
1283                 
1284                 if (subimtype & R_JPEG2K_16BIT) {
1285                         ibuf->ftype |= JP2_16BIT;
1286                 } else if (subimtype & R_JPEG2K_12BIT) {
1287                         ibuf->ftype |= JP2_12BIT;
1288                 }
1289                 
1290                 if (subimtype & R_JPEG2K_YCC) {
1291                         ibuf->ftype |= JP2_YCC;
1292                 }
1293                 
1294                 if (subimtype & R_JPEG2K_CINE_PRESET) {
1295                         ibuf->ftype |= JP2_CINE;
1296                         if (subimtype & R_JPEG2K_CINE_48FPS)
1297                                 ibuf->ftype |= JP2_CINE_48FPS;
1298                 }
1299         }
1300 #endif
1301         else {
1302                 /* R_JPEG90, R_MOVIE, etc. default we save jpegs */
1303                 if(quality < 10) quality= 90;
1304                 ibuf->ftype= JPG|quality;
1305                 if(ibuf->depth==32) ibuf->depth= 24;    /* unsupported feature only confuses other s/w */
1306         }
1307         
1308         BLI_make_existing_file(name);
1309
1310         if(scene && scene->r.stamp & R_STAMP_ALL)
1311                 BKE_stamp_info(scene, ibuf);
1312         
1313         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1314         if (ok == 0) {
1315                 perror(name);
1316         }
1317         
1318         return(ok);
1319 }
1320
1321
1322 void BKE_makepicstring(char *string, char *base, int frame, int imtype, int use_ext)
1323 {
1324         if (string==NULL) return;
1325         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1326         BLI_path_abs(string, G.sce);
1327         BLI_path_frame(string, frame, 4);
1328
1329         if(use_ext)
1330                 BKE_add_image_extension(string, imtype);
1331                 
1332 }
1333
1334 /* used by sequencer too */
1335 struct anim *openanim(char *name, int flags)
1336 {
1337         struct anim *anim;
1338         struct ImBuf *ibuf;
1339         
1340         anim = IMB_open_anim(name, flags);
1341         if (anim == NULL) return(0);
1342
1343         ibuf = IMB_anim_absolute(anim, 0);
1344         if (ibuf == NULL) {
1345                 if(BLI_exists(name))
1346                         printf("not an anim: %s\n", name);
1347                 else
1348                         printf("anim file doesn't exist: %s\n", name);
1349                 IMB_free_anim(anim);
1350                 return(0);
1351         }
1352         IMB_freeImBuf(ibuf);
1353         
1354         return(anim);
1355 }
1356
1357 /* ************************* New Image API *************** */
1358
1359
1360 /* Notes about Image storage 
1361 - packedfile
1362   -> written in .blend
1363 - filename
1364   -> written in .blend
1365 - movie
1366   -> comes from packedfile or filename
1367 - renderresult
1368   -> comes from packedfile or filename
1369 - listbase
1370   -> ibufs from exrhandle
1371 - flipbook array
1372   -> ibufs come from movie, temporary renderresult or sequence
1373 - ibuf
1374   -> comes from packedfile or filename or generated
1375
1376 */
1377
1378
1379 /* forces existence of 1 Image for renderout or nodes, returns Image */
1380 /* name is only for default, when making new one */
1381 Image *BKE_image_verify_viewer(int type, const char *name)
1382 {
1383         Image *ima;
1384         
1385         for(ima=G.main->image.first; ima; ima= ima->id.next)
1386                 if(ima->source==IMA_SRC_VIEWER)
1387                         if(ima->type==type)
1388                                 break;
1389         
1390         if(ima==NULL)
1391                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1392         
1393         /* happens on reload, imagewindow cannot be image user when hidden*/
1394         if(ima->id.us==0)
1395                 id_us_plus(&ima->id);
1396
1397         return ima;
1398 }
1399
1400 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1401 {
1402         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1403 }
1404
1405 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1406 {
1407         if(ima==NULL)
1408                 return;
1409         
1410         switch(signal) {
1411         case IMA_SIGNAL_FREE:
1412                 image_free_buffers(ima);
1413                 if(iuser)
1414                         iuser->ok= 1;
1415                 break;
1416         case IMA_SIGNAL_SRC_CHANGE:
1417                 if(ima->type == IMA_TYPE_UV_TEST)
1418                         if(ima->source != IMA_SRC_GENERATED)
1419                                 ima->type= IMA_TYPE_IMAGE;
1420
1421                 if(ima->source==IMA_SRC_GENERATED) {
1422                         if(ima->gen_x==0 || ima->gen_y==0) {
1423                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1424                                 if(ibuf) {
1425                                         ima->gen_x= ibuf->x;
1426                                         ima->gen_y= ibuf->y;
1427                                 }
1428                         }
1429                 }
1430
1431                 image_free_buffers(ima);
1432
1433                 ima->ok= 1;
1434                 if(iuser)
1435                         iuser->ok= 1;
1436                 break;
1437                         
1438         case IMA_SIGNAL_RELOAD:
1439                 /* try to repack file */
1440                 if(ima->packedfile) {
1441                         PackedFile *pf;
1442                         pf = newPackedFile(NULL, ima->name);
1443                         if (pf) {
1444                                 freePackedFile(ima->packedfile);
1445                                 ima->packedfile = pf;
1446                                 image_free_buffers(ima);
1447                         } else {
1448                                 printf("ERROR: Image not available. Keeping packed image\n");
1449                         }
1450                 }
1451                 else
1452                         image_free_buffers(ima);
1453                 
1454                 if(iuser)
1455                         iuser->ok= 1;
1456                 
1457                 break;
1458         case IMA_SIGNAL_USER_NEW_IMAGE:
1459                 if(iuser) {
1460                         iuser->ok= 1;
1461                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1462                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1463                                         iuser->multi_index= 0;
1464                                         iuser->layer= iuser->pass= 0;
1465                                 }
1466                         }
1467                 }
1468                 break;
1469         }
1470 }
1471
1472 /* if layer or pass changes, we need an index for the imbufs list */
1473 /* note it is called for rendered results, but it doesnt use the index! */
1474 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1475 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1476 {
1477         RenderLayer *rl;
1478         RenderPass *rpass= NULL;
1479         
1480         if(rr==NULL) 
1481                 return NULL;
1482         
1483         if(iuser) {
1484                 short index= 0, rl_index= 0, rp_index;
1485                 
1486                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1487                         rp_index= 0;
1488                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1489                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1490                                         break;
1491                         if(rpass)
1492                                 break;
1493                 }
1494                 
1495                 if(rpass)
1496                         iuser->multi_index= index;
1497                 else 
1498                         iuser->multi_index= 0;
1499         }
1500         if(rpass==NULL) {
1501                 rl= rr->layers.first;
1502                 if(rl)
1503                         rpass= rl->passes.first;
1504         }
1505         
1506         return rpass;
1507 }
1508
1509 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
1510 {
1511         if(ima->rr) {
1512                 return ima->rr;
1513         }
1514         else if(ima->type==IMA_TYPE_R_RESULT) {
1515                 if(ima->render_slot == ima->last_render_slot)
1516                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
1517                 else
1518                         return ima->renders[ima->render_slot];
1519         }
1520         else
1521                 return NULL;
1522 }
1523
1524 void BKE_image_release_renderresult(Scene *scene, Image *ima)
1525 {
1526         if(ima->rr);
1527         else if(ima->type==IMA_TYPE_R_RESULT) {
1528                 if(ima->render_slot == ima->last_render_slot)
1529                         RE_ReleaseResult(RE_GetRender(scene->id.name));
1530         }
1531 }
1532
1533 void BKE_image_backup_render(Scene *scene, Image *ima)
1534 {
1535         /* called right before rendering, ima->renders contains render
1536            result pointers for everything but the current render */
1537         Render *re= RE_GetRender(scene->id.name);
1538         int slot= ima->render_slot, last= ima->last_render_slot;
1539
1540         if(slot != last) {
1541                 if(ima->renders[slot]) {
1542                         RE_FreeRenderResult(ima->renders[slot]);
1543                         ima->renders[slot]= NULL;
1544                 }
1545
1546                 ima->renders[last]= NULL;
1547                 RE_SwapResult(re, &ima->renders[last]);
1548         }
1549
1550         ima->last_render_slot= slot;
1551 }
1552
1553 /* after imbuf load, openexr type can return with a exrhandle open */
1554 /* in that case we have to build a render-result */
1555 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1556 {
1557         
1558         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1559
1560 #ifdef WITH_OPENEXR
1561         IMB_exr_close(ibuf->userdata);
1562 #endif
1563
1564         ibuf->userdata= NULL;
1565         if(ima->rr)
1566                 ima->rr->framenr= framenr;
1567 }
1568
1569 /* common stuff to do with images after loading */
1570 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1571 {
1572         
1573         
1574         /* preview is NULL when it has never been used as an icon before */
1575         if(G.background==0 && ima->preview==NULL)
1576                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1577         
1578         /* stringcodes also in ibuf, ibuf->name is used to retrieve original (buttons) */
1579         BLI_strncpy(ibuf->name, ima->name, FILE_MAX);
1580         
1581         /* fields */
1582         if (ima->flag & IMA_FIELDS) {
1583                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1584                 else de_interlace_ng(ibuf);
1585         }
1586         /* timer */
1587         ima->lastused = clock() / CLOCKS_PER_SEC;
1588         
1589         ima->ok= IMA_OK_LOADED;
1590         
1591 }
1592
1593 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1594 {
1595         struct ImBuf *ibuf;
1596         unsigned short numlen;
1597         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1598         
1599         /* XXX temp stuff? */
1600         if(ima->lastframe != frame)
1601                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1602
1603         ima->lastframe= frame;
1604
1605         BLI_stringdec(ima->name, head, tail, &numlen);
1606         BLI_stringenc(ima->name, head, tail, numlen, frame);
1607         BLI_strncpy(name, ima->name, sizeof(name));
1608         
1609         if(ima->id.lib)
1610                 BLI_path_abs(name, ima->id.lib->filename);
1611         else
1612                 BLI_path_abs(name, G.sce);
1613         
1614         /* read ibuf */
1615         ibuf = IMB_loadiffname(name, IB_rect|IB_multilayer);
1616         if(G.f & G_DEBUG) printf("loaded %s\n", name);
1617         
1618         if (ibuf) {
1619 #ifdef WITH_OPENEXR
1620                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1621                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1622                         image_create_multilayer(ima, ibuf, frame);      
1623                         ima->type= IMA_TYPE_MULTILAYER;
1624                         IMB_freeImBuf(ibuf);
1625                         ibuf= NULL;
1626                 }
1627                 else {
1628                         image_initialize_after_load(ima, ibuf);
1629                         image_assign_ibuf(ima, ibuf, 0, frame);
1630                 }
1631 #else
1632                 image_initialize_after_load(ima, ibuf);
1633                 image_assign_ibuf(ima, ibuf, 0, frame);
1634 #endif
1635                 
1636                 if(ima->flag & IMA_DO_PREMUL)
1637                         converttopremul(ibuf);
1638                 
1639         }
1640         else
1641                 ima->ok= 0;
1642         
1643         if(iuser)
1644                 iuser->ok= ima->ok;
1645         
1646         return ibuf;
1647 }
1648
1649 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1650 {
1651         struct ImBuf *ibuf= NULL;
1652         
1653         /* either we load from RenderResult, or we have to load a new one */
1654         
1655         /* check for new RenderResult */
1656         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1657                 /* copy to survive not found multilayer image */
1658                 RenderResult *oldrr= ima->rr;
1659         
1660                 ima->rr= NULL;
1661                 ibuf = image_load_sequence_file(ima, iuser, frame);
1662                 
1663                 if(ibuf) { /* actually an error */
1664                         ima->type= IMA_TYPE_IMAGE;
1665                         printf("error, multi is normal image\n");
1666                 }
1667                 // printf("loaded new result %p\n", ima->rr);
1668                 /* free result if new one found */
1669                 if(ima->rr) {
1670                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1671                         if(oldrr) RE_FreeRenderResult(oldrr);
1672                 }
1673                 else {
1674                         ima->rr= oldrr;
1675                 }
1676
1677         }
1678         if(ima->rr) {
1679                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1680                 
1681                 if(rpass) {
1682                         // printf("load from pass %s\n", rpass->name);
1683                         /* since we free  render results, we copy the rect */
1684                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1685                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1686                         ibuf->flags |= IB_rectfloat;
1687                         ibuf->mall= IB_rectfloat;
1688                         ibuf->channels= rpass->channels;
1689                         
1690                         image_initialize_after_load(ima, ibuf);
1691                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
1692                         
1693                 }
1694                 // else printf("pass not found\n");
1695         }
1696         else
1697                 ima->ok= 0;
1698         
1699         if(iuser)
1700                 iuser->ok= ima->ok;
1701         
1702         return ibuf;
1703 }
1704
1705
1706 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
1707 {
1708         struct ImBuf *ibuf= NULL;
1709         
1710         ima->lastframe= frame;
1711         
1712         if(ima->anim==NULL) {
1713                 char str[FILE_MAX];
1714                 
1715                 BLI_strncpy(str, ima->name, FILE_MAX);
1716                 if(ima->id.lib)
1717                         BLI_path_abs(str, ima->id.lib->filename);
1718                 else
1719                         BLI_path_abs(str, G.sce);
1720                 
1721                 ima->anim = openanim(str, IB_cmap | IB_rect);
1722                 
1723                 /* let's initialize this user */
1724                 if(ima->anim && iuser && iuser->frames==0)
1725                         iuser->frames= IMB_anim_get_duration(ima->anim);
1726         }
1727         
1728         if(ima->anim) {
1729                 int dur = IMB_anim_get_duration(ima->anim);
1730                 int fra= frame-1;
1731                 
1732                 if(fra<0) fra = 0;
1733                 if(fra>(dur-1)) fra= dur-1;
1734                 ibuf = IMB_anim_absolute(ima->anim, fra);
1735                 
1736                 if(ibuf) {
1737                         image_initialize_after_load(ima, ibuf);
1738                         image_assign_ibuf(ima, ibuf, 0, frame);
1739                 }
1740                 else
1741                         ima->ok= 0;
1742         }
1743         else
1744                 ima->ok= 0;
1745         
1746         if(iuser)
1747                 iuser->ok= ima->ok;
1748         
1749         return ibuf;
1750 }
1751
1752 /* cfra used for # code, Image can only have this # for all its users */
1753 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
1754 {
1755         struct ImBuf *ibuf;
1756         char str[FILE_MAX];
1757         int assign = 0;
1758         
1759         /* always ensure clean ima */
1760         image_free_buffers(ima);
1761         
1762         /* is there a PackedFile with this image ? */
1763         if (ima->packedfile) {
1764                 ibuf = IMB_ibImageFromMemory((int *) ima->packedfile->data, ima->packedfile->size, IB_rect|IB_multilayer);
1765         } 
1766         else {
1767                         
1768                 /* get the right string */
1769                 BLI_strncpy(str, ima->name, sizeof(str));
1770                 if(ima->id.lib)
1771                         BLI_path_abs(str, ima->id.lib->filename);
1772                 else
1773                         BLI_path_abs(str, G.sce);
1774                 
1775                 BLI_path_frame(str, cfra, 0);
1776                 
1777                 /* read ibuf */
1778                 ibuf = IMB_loadiffname(str, IB_rect|IB_multilayer|IB_imginfo);
1779         }
1780         
1781         if (ibuf) {
1782                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1783                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1784                         image_create_multilayer(ima, ibuf, cfra);       
1785                         ima->type= IMA_TYPE_MULTILAYER;
1786                         IMB_freeImBuf(ibuf);
1787                         ibuf= NULL;
1788                 }
1789                 else {
1790                         image_initialize_after_load(ima, ibuf);
1791                         assign= 1;
1792
1793                         /* check if the image is a font image... */
1794                         detectBitmapFont(ibuf);
1795                         
1796                         /* make packed file for autopack */
1797                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
1798                                 ima->packedfile = newPackedFile(NULL, str);
1799                 }
1800                 
1801                 if(ima->flag & IMA_DO_PREMUL)
1802                         converttopremul(ibuf);
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         else if(ima->renders[ima->render_slot])
1883                 rres= *(ima->renders[ima->render_slot]);
1884         else
1885                 memset(&rres, 0, sizeof(RenderResult));
1886         
1887         if(!(rres.rectx > 0 && rres.recty > 0)) {
1888                 if(from_render)
1889                         RE_ReleaseResultImage(re);
1890                 return NULL;
1891         }
1892
1893         /* release is done in BKE_image_release_ibuf using lock_r */
1894         if(from_render) {
1895                 BLI_lock_thread(LOCK_VIEWER);
1896                 *lock_r= re;
1897         }
1898
1899         /* this gives active layer, composite or seqence result */
1900         rect= (unsigned int *)rres.rect32;
1901         rectf= rres.rectf;
1902         rectz= rres.rectz;
1903         dither= iuser->scene->r.dither_intensity;
1904
1905         /* get compo/seq result by default */
1906         if(rres.compo_seq && layer==0);
1907         else if(rres.layers.first) {
1908                 RenderLayer *rl= BLI_findlink(&rres.layers, layer-(rres.compo_seq?1:0));
1909                 if(rl) {
1910                         RenderPass *rpass;
1911
1912                         /* there's no combined pass, is in renderlayer itself */
1913                         if(pass==0) {
1914                                 rectf= rl->rectf;
1915                         }
1916                         else {
1917                                 rpass= BLI_findlink(&rl->passes, pass-1);
1918                                 if(rpass) {
1919                                         channels= rpass->channels;
1920                                         rectf= rpass->rect;
1921                                         dither= 0.0f; /* don't dither passes */
1922                                 }
1923                         }
1924
1925                         for(rpass= rl->passes.first; rpass; rpass= rpass->next)
1926                                 if(rpass->passtype == SCE_PASS_Z)
1927                                         rectz= rpass->rect;
1928                 }
1929         }
1930
1931         if(!(rectf || rect))
1932                 return NULL;
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         ibuf->rect_float= rectf;
1952         ibuf->flags |= IB_rectfloat;
1953         ibuf->channels= channels;
1954         ibuf->zbuf_float= rectz;
1955         ibuf->flags |= IB_zbuffloat;
1956         ibuf->dither= dither;
1957
1958         ima->ok= IMA_OK_LOADED;
1959
1960         return ibuf;
1961 }
1962
1963 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
1964 {
1965         ImBuf *ibuf = NULL;
1966         int frame = 0, index = 0;
1967
1968         /* see if we already have an appropriate ibuf, with image source and type */
1969         if(ima->source==IMA_SRC_MOVIE) {
1970                 frame= iuser?iuser->framenr:ima->lastframe;
1971                 ibuf= image_get_ibuf(ima, 0, frame);
1972                 /* XXX temp stuff? */
1973                 if(ima->lastframe != frame)
1974                         ima->tpageflag |= IMA_TPAGE_REFRESH;
1975                 ima->lastframe = frame;
1976         }
1977         else if(ima->source==IMA_SRC_SEQUENCE) {
1978                 if(ima->type==IMA_TYPE_IMAGE) {
1979                         frame= iuser?iuser->framenr:ima->lastframe;
1980                         ibuf= image_get_ibuf(ima, 0, frame);
1981                         
1982                         /* XXX temp stuff? */
1983                         if(ima->lastframe != frame)
1984                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1985                         ima->lastframe = frame;
1986                 }       
1987                 else if(ima->type==IMA_TYPE_MULTILAYER) {
1988                         frame= iuser?iuser->framenr:ima->lastframe;
1989                         index= iuser?iuser->multi_index:IMA_NO_INDEX;
1990                         ibuf= image_get_ibuf(ima, index, frame);
1991                 }
1992         }
1993         else if(ima->source==IMA_SRC_FILE) {
1994                 if(ima->type==IMA_TYPE_IMAGE)
1995                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1996                 else if(ima->type==IMA_TYPE_MULTILAYER)
1997                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1998         }
1999         else if(ima->source == IMA_SRC_GENERATED) {
2000                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2001         }
2002         else if(ima->source == IMA_SRC_VIEWER) {
2003                 if(ima->type==IMA_TYPE_R_RESULT) {
2004                         /* always verify entirely, not that this shouldn't happen
2005                          * during render anyway */
2006                 }
2007                 else if(ima->type==IMA_TYPE_COMPOSITE) {
2008                         frame= iuser?iuser->framenr:0;
2009                         ibuf= image_get_ibuf(ima, 0, frame);
2010                 }
2011         }
2012
2013         *frame_r = frame;
2014         *index_r = index;
2015
2016         return ibuf;
2017 }
2018
2019 /* Checks optional ImageUser and verifies/creates ImBuf. */
2020 /* use this one if you want to get a render result in progress,
2021  * if not, use BKE_image_get_ibuf which doesn't require a release */
2022 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2023 {
2024         ImBuf *ibuf= NULL;
2025         float color[] = {0, 0, 0, 1};
2026         int frame= 0, index= 0;
2027
2028         /* This function is intended to be thread-safe. It postpones the mutex lock
2029          * until it needs to load the image, if the image is already there it
2030          * should just get the pointer and return. The reason is that a lot of mutex
2031          * locks appears to be very slow on certain multicore macs, causing a render
2032          * with image textures to actually slow down as more threads are used.
2033          *
2034          * Note that all the image loading functions should also make sure they do
2035          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2036          * That means, the last two steps must be, 1) add the ibuf to the list and
2037          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2038         
2039         if(lock_r)
2040                 *lock_r= NULL;
2041
2042         /* quick reject tests */
2043         if(ima==NULL) 
2044                 return NULL;
2045         if(iuser) {
2046                 if(iuser->ok==0)
2047                         return NULL;
2048         }
2049         else if(ima->ok==0)
2050                 return NULL;
2051         
2052         /* try to get the ibuf without locking */
2053         ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2054
2055         if(ibuf == NULL) {
2056                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2057                  * load the image */
2058                 BLI_lock_thread(LOCK_IMAGE);
2059
2060                 /* need to check ok flag and loading ibuf again, because the situation
2061                  * might have changed in the meantime */
2062                 if(iuser) {
2063                         if(iuser->ok==0) {
2064                                 BLI_unlock_thread(LOCK_IMAGE);
2065                                 return NULL;
2066                         }
2067                 }
2068                 else if(ima->ok==0) {
2069                         BLI_unlock_thread(LOCK_IMAGE);
2070                         return NULL;
2071                 }
2072
2073                 ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2074
2075                 if(ibuf == NULL) {
2076                         /* we are sure we have to load the ibuf, using source and type */
2077                         if(ima->source==IMA_SRC_MOVIE) {
2078                                 /* source is from single file, use flipbook to store ibuf */
2079                                 ibuf= image_load_movie_file(ima, iuser, frame);
2080                         }
2081                         else if(ima->source==IMA_SRC_SEQUENCE) {
2082                                 if(ima->type==IMA_TYPE_IMAGE) {
2083                                         /* regular files, ibufs in flipbook, allows saving */
2084                                         ibuf= image_load_sequence_file(ima, iuser, frame);
2085                                 }
2086                                 /* no else; on load the ima type can change */
2087                                 if(ima->type==IMA_TYPE_MULTILAYER) {
2088                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2089                                         ibuf= image_load_sequence_multilayer(ima, iuser, frame);
2090                                 }
2091
2092                                 if(ibuf)
2093                                         BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
2094                         }
2095                         else if(ima->source==IMA_SRC_FILE) {
2096                                 
2097                                 if(ima->type==IMA_TYPE_IMAGE)
2098                                         ibuf= image_load_image_file(ima, iuser, frame); /* cfra only for '#', this global is OK */
2099                                 /* no else; on load the ima type can change */
2100                                 if(ima->type==IMA_TYPE_MULTILAYER)
2101                                         /* keeps render result, stores ibufs in listbase, allows saving */
2102                                         ibuf= image_get_ibuf_multilayer(ima, iuser);
2103                                         
2104                         }
2105                         else if(ima->source == IMA_SRC_GENERATED) {
2106                                 /* generated is: ibuf is allocated dynamically */
2107                                 /* UV testgrid or black or solid etc */
2108                                 if(ima->gen_x==0) ima->gen_x= 1024;
2109                                 if(ima->gen_y==0) ima->gen_y= 1024;
2110                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 0, ima->gen_type, color);
2111                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2112                                 ima->ok= IMA_OK_LOADED;
2113                         }
2114                         else if(ima->source == IMA_SRC_VIEWER) {
2115                                 if(ima->type==IMA_TYPE_R_RESULT) {
2116                                         /* always verify entirely, and potentially
2117                                            returns pointer to release later */
2118                                         ibuf= image_get_render_result(ima, iuser, lock_r);
2119                                 }
2120                                 else if(ima->type==IMA_TYPE_COMPOSITE) {
2121                                         /* requires lock/unlock, otherwise don't return image */
2122                                         if(lock_r) {
2123                                                 /* unlock in BKE_image_release_ibuf */
2124                                                 BLI_lock_thread(LOCK_VIEWER);
2125                                                 *lock_r= ima;
2126
2127                                                 /* Composite Viewer, all handled in compositor */
2128                                                 /* fake ibuf, will be filled in compositor */
2129                                                 ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
2130                                                 image_assign_ibuf(ima, ibuf, 0, frame);
2131                                         }
2132                                 }
2133                         }
2134                 }
2135
2136                 BLI_unlock_thread(LOCK_IMAGE);
2137         }
2138
2139         /* we assuming that if it is not rendering, it's also not multithreaded
2140          * (a somewhat weak assumption) */
2141         if(G.rendering==0)
2142                 tag_image_time(ima);
2143
2144         return ibuf;
2145 }
2146
2147 void BKE_image_release_ibuf(Image *ima, void *lock)
2148 {
2149         /* for getting image during threaded render / compositing, need to release */
2150         if(lock == ima) {
2151                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2152         }
2153         else if(lock) {
2154                 RE_ReleaseResultImage(lock); /* render result */
2155                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2156         }
2157 }
2158
2159 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2160 {
2161         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2162 }
2163
2164 void BKE_image_user_calc_frame(ImageUser *iuser, int cfra, int fieldnr)
2165 {
2166         int imanr, len;
2167         
2168         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2169         len= (iuser->fie_ima*iuser->frames)/2;
2170         
2171         if(len==0) {
2172                 iuser->framenr= 0;
2173         }
2174         else {
2175                 cfra= cfra - iuser->sfra+1;
2176                 
2177                 /* cyclic */
2178                 if(iuser->cycl) {
2179                         cfra= ( (cfra) % len );
2180                         if(cfra < 0) cfra+= len;
2181                         if(cfra==0) cfra= len;
2182                 }
2183                 
2184                 if(cfra<1) cfra= 1;
2185                 else if(cfra>len) cfra= len;
2186                 
2187                 /* convert current frame to current field */
2188                 cfra= 2*(cfra);
2189                 if(fieldnr) cfra++;
2190                 
2191                 /* transform to images space */
2192                 imanr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
2193                 if(imanr>iuser->frames) imanr= iuser->frames;
2194                 imanr+= iuser->offset;
2195                 
2196                 if(iuser->cycl) {
2197                         imanr= ( (imanr) % len );
2198                         while(imanr < 0) imanr+= len;
2199                         if(imanr==0) imanr= len;
2200                 }
2201         
2202                 /* allows image users to handle redraws */
2203                 if(iuser->flag & IMA_ANIM_ALWAYS)
2204                         if(imanr!=iuser->framenr)
2205                                 iuser->flag |= IMA_ANIM_REFRESHED;
2206                 
2207                 iuser->framenr= imanr;
2208                 if(iuser->ok==0) iuser->ok= 1;
2209         }
2210 }