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