7d194461c7823d975abf260c2d1619393834cccd
[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
1023 void stamp_font_begin(int size)
1024 {
1025         static int mono= -1;
1026
1027         if (mono == -1)
1028                 mono= BLF_load_mem("monospace", (unsigned char *)datatoc_bmonofont_ttf, datatoc_bmonofont_ttf_size);
1029
1030         BLF_set(mono);
1031         BLF_aspect(1.0);
1032         BLF_size(size, 72);
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(rectf, rect, width, height, channels);
1053         BLF_buffer_col(scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1054         pad= BLF_width("--");
1055
1056         x= 0;
1057         y= height;
1058
1059         if (stamp_data.file[0]) {
1060                 /* Top left corner */
1061                 BLF_width_and_height(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(x, y, 0.0);
1069                 BLF_draw_buffer(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(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(x, y+1, 0.0);
1084                 BLF_draw_buffer(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(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(x, y, 0.0);
1099                 BLF_draw_buffer(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(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(x, y, 0.0);
1114                 BLF_draw_buffer(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(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(x, y+3, 0.0);
1129                 BLF_draw_buffer(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(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(x, y+3, 0.0);
1144                 BLF_draw_buffer(stamp_data.time);
1145
1146                 /* space width. */
1147                 x += w + pad;
1148         }
1149         
1150         if (stamp_data.frame[0]) {
1151                 BLF_width_and_height(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(x, y+3, 0.0);
1158
1159                 BLF_draw_buffer(stamp_data.frame);
1160
1161                 /* space width. */
1162                 x += w + pad;
1163         }
1164
1165         if (stamp_data.camera[0]) {
1166                 BLF_width_and_height(stamp_data.camera, &w, &h);
1167
1168                 /* extra space for background. */
1169                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+3);
1170                 BLF_position(x, y+3, 0.0);
1171                 BLF_draw_buffer(stamp_data.camera);
1172         }
1173         
1174         if (stamp_data.scene[0]) {
1175                 BLF_width_and_height(stamp_data.scene, &w, &h);
1176
1177                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1178                 x= width - w - 2;
1179
1180                 /* extra space for background. */
1181                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+3, y+h+3);
1182
1183                 /* and pad the text. */
1184                 BLF_position(x, y+3, 0.0);
1185                 BLF_draw_buffer(stamp_data.scene);
1186         }
1187         
1188         if (stamp_data.strip[0]) {
1189                 BLF_width_and_height(stamp_data.scene, &w, &h);
1190
1191                 /* Top right corner, with an extra space because blenfont is too strict! */
1192                 x= width - w - pad;
1193                 y= height - h;
1194
1195                 /* extra space for background. */
1196                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y-3, x+w+pad, y+h+3);
1197
1198                 BLF_position(x, y, 0.0);
1199                 BLF_draw_buffer(stamp_data.strip);
1200         }
1201
1202         /* cleanup the buffer. */
1203         BLF_buffer(NULL, NULL, 0, 0, 0);
1204 }
1205
1206 void BKE_stamp_info(Scene *scene, struct ImBuf *ibuf)
1207 {
1208         struct StampData stamp_data;
1209
1210         if (!ibuf)      return;
1211         
1212         /* fill all the data values, no prefix */
1213         stampdata(scene, &stamp_data, 0);
1214         
1215         if (stamp_data.file[0])         IMB_imginfo_change_field (ibuf, "File",         stamp_data.file);
1216         if (stamp_data.note[0])         IMB_imginfo_change_field (ibuf, "Note",         stamp_data.note);
1217         if (stamp_data.date[0])         IMB_imginfo_change_field (ibuf, "Date",         stamp_data.date);
1218         if (stamp_data.marker[0])       IMB_imginfo_change_field (ibuf, "Marker",       stamp_data.marker);
1219         if (stamp_data.time[0])         IMB_imginfo_change_field (ibuf, "Time",         stamp_data.time);
1220         if (stamp_data.frame[0])        IMB_imginfo_change_field (ibuf, "Frame",        stamp_data.frame);
1221         if (stamp_data.camera[0])       IMB_imginfo_change_field (ibuf, "Camera",       stamp_data.camera);
1222         if (stamp_data.scene[0])        IMB_imginfo_change_field (ibuf, "Scene",        stamp_data.scene);
1223         if (stamp_data.strip[0])        IMB_imginfo_change_field (ibuf, "Strip",        stamp_data.strip);
1224 }
1225
1226 int BKE_write_ibuf(Scene *scene, ImBuf *ibuf, char *name, int imtype, int subimtype, int quality)
1227 {
1228         int ok;
1229         
1230         if(imtype==0);
1231         else if(imtype== R_IRIS) 
1232                 ibuf->ftype= IMAGIC;
1233         else if ((imtype==R_RADHDR)) {
1234                 ibuf->ftype= RADHDR;
1235         }
1236         else if (ELEM5(imtype, R_PNG, R_FFMPEG, R_H264, R_THEORA, R_XVID)) {
1237                 ibuf->ftype= PNG;
1238         }
1239 #ifdef WITH_DDS
1240         else if ((imtype==R_DDS)) {
1241                 ibuf->ftype= DDS;
1242         }
1243 #endif
1244         else if ((imtype==R_BMP)) {
1245                 ibuf->ftype= BMP;
1246         }
1247         else if ((G.have_libtiff) && (imtype==R_TIFF)) {
1248                 ibuf->ftype= TIF;
1249
1250                 if(subimtype & R_TIFF_16BIT)
1251                         ibuf->ftype |= TIF_16BIT;
1252         }
1253 #ifdef WITH_OPENEXR
1254         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
1255                 ibuf->ftype= OPENEXR;
1256                 if(subimtype & R_OPENEXR_HALF)
1257                         ibuf->ftype |= OPENEXR_HALF;
1258                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
1259                 
1260                 if(!(subimtype & R_OPENEXR_ZBUF))
1261                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1262                 
1263         }
1264 #endif
1265         else if (imtype==R_CINEON) {
1266                 ibuf->ftype = CINEON;
1267         }
1268         else if (imtype==R_DPX) {
1269                 ibuf->ftype = DPX;
1270         }
1271         else if (imtype==R_TARGA) {
1272                 ibuf->ftype= TGA;
1273         }
1274         else if(imtype==R_RAWTGA) {
1275                 ibuf->ftype= RAWTGA;
1276         }
1277         else if(imtype==R_HAMX) {
1278                 ibuf->ftype= AN_hamx;
1279         }
1280 #ifdef WITH_OPENJPEG
1281         else if(imtype==R_JP2) {
1282                 if(quality < 10) quality= 90;
1283                 ibuf->ftype= JP2|quality;
1284                 
1285                 if (subimtype & R_JPEG2K_16BIT) {
1286                         ibuf->ftype |= JP2_16BIT;
1287                 } else if (subimtype & R_JPEG2K_12BIT) {
1288                         ibuf->ftype |= JP2_12BIT;
1289                 }
1290                 
1291                 if (subimtype & R_JPEG2K_YCC) {
1292                         ibuf->ftype |= JP2_YCC;
1293                 }
1294                 
1295                 if (subimtype & R_JPEG2K_CINE_PRESET) {
1296                         ibuf->ftype |= JP2_CINE;
1297                         if (subimtype & R_JPEG2K_CINE_48FPS)
1298                                 ibuf->ftype |= JP2_CINE_48FPS;
1299                 }
1300         }
1301 #endif
1302         else {
1303                 /* R_JPEG90, R_MOVIE, etc. default we save jpegs */
1304                 if(quality < 10) quality= 90;
1305                 ibuf->ftype= JPG|quality;
1306                 if(ibuf->depth==32) ibuf->depth= 24;    /* unsupported feature only confuses other s/w */
1307         }
1308         
1309         BLI_make_existing_file(name);
1310
1311         if(scene && scene->r.stamp & R_STAMP_ALL)
1312                 BKE_stamp_info(scene, ibuf);
1313         
1314         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1315         if (ok == 0) {
1316                 perror(name);
1317         }
1318         
1319         return(ok);
1320 }
1321
1322
1323 void BKE_makepicstring(char *string, char *base, int frame, int imtype, int use_ext)
1324 {
1325         if (string==NULL) return;
1326         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1327         BLI_path_abs(string, G.sce);
1328         BLI_path_frame(string, frame, 4);
1329
1330         if(use_ext)
1331                 BKE_add_image_extension(string, imtype);
1332                 
1333 }
1334
1335 /* used by sequencer too */
1336 struct anim *openanim(char *name, int flags)
1337 {
1338         struct anim *anim;
1339         struct ImBuf *ibuf;
1340         
1341         anim = IMB_open_anim(name, flags);
1342         if (anim == NULL) return(0);
1343
1344         ibuf = IMB_anim_absolute(anim, 0);
1345         if (ibuf == NULL) {
1346                 if(BLI_exists(name))
1347                         printf("not an anim: %s\n", name);
1348                 else
1349                         printf("anim file doesn't exist: %s\n", name);
1350                 IMB_free_anim(anim);
1351                 return(0);
1352         }
1353         IMB_freeImBuf(ibuf);
1354         
1355         return(anim);
1356 }
1357
1358 /* ************************* New Image API *************** */
1359
1360
1361 /* Notes about Image storage 
1362 - packedfile
1363   -> written in .blend
1364 - filename
1365   -> written in .blend
1366 - movie
1367   -> comes from packedfile or filename
1368 - renderresult
1369   -> comes from packedfile or filename
1370 - listbase
1371   -> ibufs from exrhandle
1372 - flipbook array
1373   -> ibufs come from movie, temporary renderresult or sequence
1374 - ibuf
1375   -> comes from packedfile or filename or generated
1376
1377 */
1378
1379
1380 /* forces existence of 1 Image for renderout or nodes, returns Image */
1381 /* name is only for default, when making new one */
1382 Image *BKE_image_verify_viewer(int type, const char *name)
1383 {
1384         Image *ima;
1385         
1386         for(ima=G.main->image.first; ima; ima= ima->id.next)
1387                 if(ima->source==IMA_SRC_VIEWER)
1388                         if(ima->type==type)
1389                                 break;
1390         
1391         if(ima==NULL)
1392                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1393         
1394         /* happens on reload, imagewindow cannot be image user when hidden*/
1395         if(ima->id.us==0)
1396                 id_us_plus(&ima->id);
1397
1398         return ima;
1399 }
1400
1401 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1402 {
1403         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1404 }
1405
1406 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1407 {
1408         if(ima==NULL)
1409                 return;
1410         
1411         switch(signal) {
1412         case IMA_SIGNAL_FREE:
1413                 image_free_buffers(ima);
1414                 if(iuser)
1415                         iuser->ok= 1;
1416                 break;
1417         case IMA_SIGNAL_SRC_CHANGE:
1418                 if(ima->type == IMA_TYPE_UV_TEST)
1419                         if(ima->source != IMA_SRC_GENERATED)
1420                                 ima->type= IMA_TYPE_IMAGE;
1421
1422                 if(ima->source==IMA_SRC_GENERATED) {
1423                         if(ima->gen_x==0 || ima->gen_y==0) {
1424                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1425                                 if(ibuf) {
1426                                         ima->gen_x= ibuf->x;
1427                                         ima->gen_y= ibuf->y;
1428                                 }
1429                         }
1430                 }
1431
1432                 image_free_buffers(ima);
1433
1434                 ima->ok= 1;
1435                 if(iuser)
1436                         iuser->ok= 1;
1437                 break;
1438                         
1439         case IMA_SIGNAL_RELOAD:
1440                 /* try to repack file */
1441                 if(ima->packedfile) {
1442                         PackedFile *pf;
1443                         pf = newPackedFile(NULL, ima->name);
1444                         if (pf) {
1445                                 freePackedFile(ima->packedfile);
1446                                 ima->packedfile = pf;
1447                                 image_free_buffers(ima);
1448                         } else {
1449                                 printf("ERROR: Image not available. Keeping packed image\n");
1450                         }
1451                 }
1452                 else
1453                         image_free_buffers(ima);
1454                 
1455                 if(iuser)
1456                         iuser->ok= 1;
1457                 
1458                 break;
1459         case IMA_SIGNAL_USER_NEW_IMAGE:
1460                 if(iuser) {
1461                         iuser->ok= 1;
1462                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1463                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1464                                         iuser->multi_index= 0;
1465                                         iuser->layer= iuser->pass= 0;
1466                                 }
1467                         }
1468                 }
1469                 break;
1470         }
1471 }
1472
1473 /* if layer or pass changes, we need an index for the imbufs list */
1474 /* note it is called for rendered results, but it doesnt use the index! */
1475 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1476 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1477 {
1478         RenderLayer *rl;
1479         RenderPass *rpass= NULL;
1480         
1481         if(rr==NULL) 
1482                 return NULL;
1483         
1484         if(iuser) {
1485                 short index= 0, rl_index= 0, rp_index;
1486                 
1487                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1488                         rp_index= 0;
1489                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1490                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1491                                         break;
1492                         if(rpass)
1493                                 break;
1494                 }
1495                 
1496                 if(rpass)
1497                         iuser->multi_index= index;
1498                 else 
1499                         iuser->multi_index= 0;
1500         }
1501         if(rpass==NULL) {
1502                 rl= rr->layers.first;
1503                 if(rl)
1504                         rpass= rl->passes.first;
1505         }
1506         
1507         return rpass;
1508 }
1509
1510 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
1511 {
1512         if(ima->rr) {
1513                 return ima->rr;
1514         }
1515         else if(ima->type==IMA_TYPE_R_RESULT) {
1516                 if(ima->render_slot == ima->last_render_slot)
1517                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
1518                 else
1519                         return ima->renders[ima->render_slot];
1520         }
1521         else
1522                 return NULL;
1523 }
1524
1525 void BKE_image_release_renderresult(Scene *scene, Image *ima)
1526 {
1527         if(ima->rr);
1528         else if(ima->type==IMA_TYPE_R_RESULT) {
1529                 if(ima->render_slot == ima->last_render_slot)
1530                         RE_ReleaseResult(RE_GetRender(scene->id.name));
1531         }
1532 }
1533
1534 void BKE_image_backup_render(Scene *scene, Image *ima)
1535 {
1536         /* called right before rendering, ima->renders contains render
1537            result pointers for everything but the current render */
1538         Render *re= RE_GetRender(scene->id.name);
1539         int slot= ima->render_slot, last= ima->last_render_slot;
1540
1541         if(slot != last) {
1542                 if(ima->renders[slot]) {
1543                         RE_FreeRenderResult(ima->renders[slot]);
1544                         ima->renders[slot]= NULL;
1545                 }
1546
1547                 ima->renders[last]= NULL;
1548                 RE_SwapResult(re, &ima->renders[last]);
1549         }
1550
1551         ima->last_render_slot= slot;
1552 }
1553
1554 /* after imbuf load, openexr type can return with a exrhandle open */
1555 /* in that case we have to build a render-result */
1556 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1557 {
1558         
1559         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1560
1561 #ifdef WITH_OPENEXR
1562         IMB_exr_close(ibuf->userdata);
1563 #endif
1564
1565         ibuf->userdata= NULL;
1566         if(ima->rr)
1567                 ima->rr->framenr= framenr;
1568 }
1569
1570 /* common stuff to do with images after loading */
1571 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1572 {
1573         
1574         
1575         /* preview is NULL when it has never been used as an icon before */
1576         if(G.background==0 && ima->preview==NULL)
1577                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1578         
1579         /* stringcodes also in ibuf, ibuf->name is used to retrieve original (buttons) */
1580         BLI_strncpy(ibuf->name, ima->name, FILE_MAX);
1581         
1582         /* fields */
1583         if (ima->flag & IMA_FIELDS) {
1584                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1585                 else de_interlace_ng(ibuf);
1586         }
1587         /* timer */
1588         ima->lastused = clock() / CLOCKS_PER_SEC;
1589         
1590         ima->ok= IMA_OK_LOADED;
1591         
1592 }
1593
1594 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1595 {
1596         struct ImBuf *ibuf;
1597         unsigned short numlen;
1598         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1599         
1600         /* XXX temp stuff? */
1601         if(ima->lastframe != frame)
1602                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1603
1604         ima->lastframe= frame;
1605
1606         BLI_stringdec(ima->name, head, tail, &numlen);
1607         BLI_stringenc(ima->name, head, tail, numlen, frame);
1608         BLI_strncpy(name, ima->name, sizeof(name));
1609         
1610         if(ima->id.lib)
1611                 BLI_path_abs(name, ima->id.lib->filename);
1612         else
1613                 BLI_path_abs(name, G.sce);
1614         
1615         /* read ibuf */
1616         ibuf = IMB_loadiffname(name, IB_rect|IB_multilayer);
1617         if(G.f & G_DEBUG) printf("loaded %s\n", name);
1618         
1619         if (ibuf) {
1620 #ifdef WITH_OPENEXR
1621                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1622                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1623                         image_create_multilayer(ima, ibuf, frame);      
1624                         ima->type= IMA_TYPE_MULTILAYER;
1625                         IMB_freeImBuf(ibuf);
1626                         ibuf= NULL;
1627                 }
1628                 else {
1629                         image_initialize_after_load(ima, ibuf);
1630                         image_assign_ibuf(ima, ibuf, 0, frame);
1631                 }
1632 #else
1633                 image_initialize_after_load(ima, ibuf);
1634                 image_assign_ibuf(ima, ibuf, 0, frame);
1635 #endif
1636                 
1637                 if(ima->flag & IMA_DO_PREMUL)
1638                         converttopremul(ibuf);
1639                 
1640         }
1641         else
1642                 ima->ok= 0;
1643         
1644         if(iuser)
1645                 iuser->ok= ima->ok;
1646         
1647         return ibuf;
1648 }
1649
1650 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1651 {
1652         struct ImBuf *ibuf= NULL;
1653         
1654         /* either we load from RenderResult, or we have to load a new one */
1655         
1656         /* check for new RenderResult */
1657         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1658                 /* copy to survive not found multilayer image */
1659                 RenderResult *oldrr= ima->rr;
1660         
1661                 ima->rr= NULL;
1662                 ibuf = image_load_sequence_file(ima, iuser, frame);
1663                 
1664                 if(ibuf) { /* actually an error */
1665                         ima->type= IMA_TYPE_IMAGE;
1666                         printf("error, multi is normal image\n");
1667                 }
1668                 // printf("loaded new result %p\n", ima->rr);
1669                 /* free result if new one found */
1670                 if(ima->rr) {
1671                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1672                         if(oldrr) RE_FreeRenderResult(oldrr);
1673                 }
1674                 else {
1675                         ima->rr= oldrr;
1676                 }
1677
1678         }
1679         if(ima->rr) {
1680                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1681                 
1682                 if(rpass) {
1683                         // printf("load from pass %s\n", rpass->name);
1684                         /* since we free  render results, we copy the rect */
1685                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1686                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1687                         ibuf->flags |= IB_rectfloat;
1688                         ibuf->mall= IB_rectfloat;
1689                         ibuf->channels= rpass->channels;
1690                         
1691                         image_initialize_after_load(ima, ibuf);
1692                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
1693                         
1694                 }
1695                 // else printf("pass not found\n");
1696         }
1697         else
1698                 ima->ok= 0;
1699         
1700         if(iuser)
1701                 iuser->ok= ima->ok;
1702         
1703         return ibuf;
1704 }
1705
1706
1707 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
1708 {
1709         struct ImBuf *ibuf= NULL;
1710         
1711         ima->lastframe= frame;
1712         
1713         if(ima->anim==NULL) {
1714                 char str[FILE_MAX];
1715                 
1716                 BLI_strncpy(str, ima->name, FILE_MAX);
1717                 if(ima->id.lib)
1718                         BLI_path_abs(str, ima->id.lib->filename);
1719                 else
1720                         BLI_path_abs(str, G.sce);
1721                 
1722                 ima->anim = openanim(str, IB_cmap | IB_rect);
1723                 
1724                 /* let's initialize this user */
1725                 if(ima->anim && iuser && iuser->frames==0)
1726                         iuser->frames= IMB_anim_get_duration(ima->anim);
1727         }
1728         
1729         if(ima->anim) {
1730                 int dur = IMB_anim_get_duration(ima->anim);
1731                 int fra= frame-1;
1732                 
1733                 if(fra<0) fra = 0;
1734                 if(fra>(dur-1)) fra= dur-1;
1735                 ibuf = IMB_anim_absolute(ima->anim, fra);
1736                 
1737                 if(ibuf) {
1738                         image_initialize_after_load(ima, ibuf);
1739                         image_assign_ibuf(ima, ibuf, 0, frame);
1740                 }
1741                 else
1742                         ima->ok= 0;
1743         }
1744         else
1745                 ima->ok= 0;
1746         
1747         if(iuser)
1748                 iuser->ok= ima->ok;
1749         
1750         return ibuf;
1751 }
1752
1753 /* cfra used for # code, Image can only have this # for all its users */
1754 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
1755 {
1756         struct ImBuf *ibuf;
1757         char str[FILE_MAX];
1758         int assign = 0;
1759         
1760         /* always ensure clean ima */
1761         image_free_buffers(ima);
1762         
1763         /* is there a PackedFile with this image ? */
1764         if (ima->packedfile) {
1765                 ibuf = IMB_ibImageFromMemory((int *) ima->packedfile->data, ima->packedfile->size, IB_rect|IB_multilayer);
1766         } 
1767         else {
1768                         
1769                 /* get the right string */
1770                 BLI_strncpy(str, ima->name, sizeof(str));
1771                 if(ima->id.lib)
1772                         BLI_path_abs(str, ima->id.lib->filename);
1773                 else
1774                         BLI_path_abs(str, G.sce);
1775                 
1776                 BLI_path_frame(str, cfra, 0);
1777                 
1778                 /* read ibuf */
1779                 ibuf = IMB_loadiffname(str, IB_rect|IB_multilayer|IB_imginfo);
1780         }
1781         
1782         if (ibuf) {
1783                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1784                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1785                         image_create_multilayer(ima, ibuf, cfra);       
1786                         ima->type= IMA_TYPE_MULTILAYER;
1787                         IMB_freeImBuf(ibuf);
1788                         ibuf= NULL;
1789                 }
1790                 else {
1791                         image_initialize_after_load(ima, ibuf);
1792                         assign= 1;
1793
1794                         /* check if the image is a font image... */
1795                         detectBitmapFont(ibuf);
1796                         
1797                         /* make packed file for autopack */
1798                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
1799                                 ima->packedfile = newPackedFile(NULL, str);
1800                 }
1801                 
1802                 if(ima->flag & IMA_DO_PREMUL)
1803                         converttopremul(ibuf);
1804         }
1805         else
1806                 ima->ok= 0;
1807         
1808         if(assign)
1809                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1810
1811         if(iuser)
1812                 iuser->ok= ima->ok;
1813         
1814         return ibuf;
1815 }
1816
1817 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
1818 {
1819         ImBuf *ibuf= NULL;
1820         
1821         if(ima->rr==NULL) {
1822                 ibuf = image_load_image_file(ima, iuser, 0);
1823                 if(ibuf) { /* actually an error */
1824                         ima->type= IMA_TYPE_IMAGE;
1825                         return ibuf;
1826                 }
1827         }
1828         if(ima->rr) {
1829                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1830
1831                 if(rpass) {
1832                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1833                         
1834                         image_initialize_after_load(ima, ibuf);
1835                         
1836                         ibuf->rect_float= rpass->rect;
1837                         ibuf->flags |= IB_rectfloat;
1838                         ibuf->channels= rpass->channels;
1839                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1840
1841                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1842                 }
1843         }
1844         
1845         if(ibuf==NULL) 
1846                 ima->ok= 0;
1847         if(iuser)
1848                 iuser->ok= ima->ok;
1849         
1850         return ibuf;
1851 }
1852
1853
1854 /* showing RGBA result itself (from compo/sequence) or
1855    like exr, using layers etc */
1856 /* always returns a single ibuf, also during render progress */
1857 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
1858 {
1859         Render *re;
1860         RenderResult rres;
1861         float *rectf, *rectz;
1862         unsigned int *rect;
1863         float dither;
1864         int channels, layer, pass;
1865         ImBuf *ibuf;
1866         int from_render= (ima->render_slot == ima->last_render_slot);
1867
1868         if(!(iuser && iuser->scene))
1869                 return NULL;
1870
1871         /* if we the caller is not going to release the lock, don't give the image */
1872         if(!lock_r)
1873                 return NULL;
1874
1875         re= RE_GetRender(iuser->scene->id.name);
1876
1877         channels= 4;
1878         layer= (iuser)? iuser->layer: 0;
1879         pass= (iuser)? iuser->pass: 0;
1880
1881         if(from_render)
1882                 RE_AcquireResultImage(re, &rres);
1883         else if(ima->renders[ima->render_slot])
1884                 rres= *(ima->renders[ima->render_slot]);
1885         else
1886                 memset(&rres, 0, sizeof(RenderResult));
1887         
1888         if(!(rres.rectx > 0 && rres.recty > 0)) {
1889                 if(from_render)
1890                         RE_ReleaseResultImage(re);
1891                 return NULL;
1892         }
1893
1894         /* release is done in BKE_image_release_ibuf using lock_r */
1895         if(from_render) {
1896                 BLI_lock_thread(LOCK_VIEWER);
1897                 *lock_r= re;
1898         }
1899
1900         /* this gives active layer, composite or seqence result */
1901         rect= (unsigned int *)rres.rect32;
1902         rectf= rres.rectf;
1903         rectz= rres.rectz;
1904         dither= iuser->scene->r.dither_intensity;
1905
1906         /* get compo/seq result by default */
1907         if(rres.compo_seq && layer==0);
1908         else if(rres.layers.first) {
1909                 RenderLayer *rl= BLI_findlink(&rres.layers, layer-(rres.compo_seq?1:0));
1910                 if(rl) {
1911                         RenderPass *rpass;
1912
1913                         /* there's no combined pass, is in renderlayer itself */
1914                         if(pass==0) {
1915                                 rectf= rl->rectf;
1916                         }
1917                         else {
1918                                 rpass= BLI_findlink(&rl->passes, pass-1);
1919                                 if(rpass) {
1920                                         channels= rpass->channels;
1921                                         rectf= rpass->rect;
1922                                         dither= 0.0f; /* don't dither passes */
1923                                 }
1924                         }
1925
1926                         for(rpass= rl->passes.first; rpass; rpass= rpass->next)
1927                                 if(rpass->passtype == SCE_PASS_Z)
1928                                         rectz= rpass->rect;
1929                 }
1930         }
1931
1932         if(!(rectf || rect))
1933                 return NULL;
1934
1935         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1936
1937         /* make ibuf if needed, and initialize it */
1938         if(ibuf==NULL) {
1939                 ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, 0, 0);
1940                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1941         }
1942
1943         ibuf->x= rres.rectx;
1944         ibuf->y= rres.recty;
1945         
1946         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
1947                 imb_freerectImBuf(ibuf);
1948
1949         if(rect)
1950                 ibuf->rect= rect;
1951         
1952         ibuf->rect_float= rectf;
1953         ibuf->flags |= IB_rectfloat;
1954         ibuf->channels= channels;
1955         ibuf->zbuf_float= rectz;
1956         ibuf->flags |= IB_zbuffloat;
1957         ibuf->dither= dither;
1958
1959         ima->ok= IMA_OK_LOADED;
1960
1961         return ibuf;
1962 }
1963
1964 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
1965 {
1966         ImBuf *ibuf = NULL;
1967         int frame = 0, index = 0;
1968
1969         /* see if we already have an appropriate ibuf, with image source and type */
1970         if(ima->source==IMA_SRC_MOVIE) {
1971                 frame= iuser?iuser->framenr:ima->lastframe;
1972                 ibuf= image_get_ibuf(ima, 0, frame);
1973                 /* XXX temp stuff? */
1974                 if(ima->lastframe != frame)
1975                         ima->tpageflag |= IMA_TPAGE_REFRESH;
1976                 ima->lastframe = frame;
1977         }
1978         else if(ima->source==IMA_SRC_SEQUENCE) {
1979                 if(ima->type==IMA_TYPE_IMAGE) {
1980                         frame= iuser?iuser->framenr:ima->lastframe;
1981                         ibuf= image_get_ibuf(ima, 0, frame);
1982                         
1983                         /* XXX temp stuff? */
1984                         if(ima->lastframe != frame)
1985                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1986                         ima->lastframe = frame;
1987                 }       
1988                 else if(ima->type==IMA_TYPE_MULTILAYER) {
1989                         frame= iuser?iuser->framenr:ima->lastframe;
1990                         index= iuser?iuser->multi_index:IMA_NO_INDEX;
1991                         ibuf= image_get_ibuf(ima, index, frame);
1992                 }
1993         }
1994         else if(ima->source==IMA_SRC_FILE) {
1995                 if(ima->type==IMA_TYPE_IMAGE)
1996                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1997                 else if(ima->type==IMA_TYPE_MULTILAYER)
1998                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1999         }
2000         else if(ima->source == IMA_SRC_GENERATED) {
2001                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2002         }
2003         else if(ima->source == IMA_SRC_VIEWER) {
2004                 if(ima->type==IMA_TYPE_R_RESULT) {
2005                         /* always verify entirely, not that this shouldn't happen
2006                          * during render anyway */
2007                 }
2008                 else if(ima->type==IMA_TYPE_COMPOSITE) {
2009                         frame= iuser?iuser->framenr:0;
2010                         ibuf= image_get_ibuf(ima, 0, frame);
2011                 }
2012         }
2013
2014         *frame_r = frame;
2015         *index_r = index;
2016
2017         return ibuf;
2018 }
2019
2020 /* Checks optional ImageUser and verifies/creates ImBuf. */
2021 /* use this one if you want to get a render result in progress,
2022  * if not, use BKE_image_get_ibuf which doesn't require a release */
2023 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2024 {
2025         ImBuf *ibuf= NULL;
2026         float color[] = {0, 0, 0, 1};
2027         int frame= 0, index= 0;
2028
2029         /* This function is intended to be thread-safe. It postpones the mutex lock
2030          * until it needs to load the image, if the image is already there it
2031          * should just get the pointer and return. The reason is that a lot of mutex
2032          * locks appears to be very slow on certain multicore macs, causing a render
2033          * with image textures to actually slow down as more threads are used.
2034          *
2035          * Note that all the image loading functions should also make sure they do
2036          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2037          * That means, the last two steps must be, 1) add the ibuf to the list and
2038          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2039         
2040         if(lock_r)
2041                 *lock_r= NULL;
2042
2043         /* quick reject tests */
2044         if(ima==NULL) 
2045                 return NULL;
2046         if(iuser) {
2047                 if(iuser->ok==0)
2048                         return NULL;
2049         }
2050         else if(ima->ok==0)
2051                 return NULL;
2052         
2053         /* try to get the ibuf without locking */
2054         ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2055
2056         if(ibuf == NULL) {
2057                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2058                  * load the image */
2059                 BLI_lock_thread(LOCK_IMAGE);
2060
2061                 /* need to check ok flag and loading ibuf again, because the situation
2062                  * might have changed in the meantime */
2063                 if(iuser) {
2064                         if(iuser->ok==0) {
2065                                 BLI_unlock_thread(LOCK_IMAGE);
2066                                 return NULL;
2067                         }
2068                 }
2069                 else if(ima->ok==0) {
2070                         BLI_unlock_thread(LOCK_IMAGE);
2071                         return NULL;
2072                 }
2073
2074                 ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2075
2076                 if(ibuf == NULL) {
2077                         /* we are sure we have to load the ibuf, using source and type */
2078                         if(ima->source==IMA_SRC_MOVIE) {
2079                                 /* source is from single file, use flipbook to store ibuf */
2080                                 ibuf= image_load_movie_file(ima, iuser, frame);
2081                         }
2082                         else if(ima->source==IMA_SRC_SEQUENCE) {
2083                                 if(ima->type==IMA_TYPE_IMAGE) {
2084                                         /* regular files, ibufs in flipbook, allows saving */
2085                                         ibuf= image_load_sequence_file(ima, iuser, frame);
2086                                 }
2087                                 /* no else; on load the ima type can change */
2088                                 if(ima->type==IMA_TYPE_MULTILAYER) {
2089                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2090                                         ibuf= image_load_sequence_multilayer(ima, iuser, frame);
2091                                 }
2092
2093                                 if(ibuf)
2094                                         BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
2095                         }
2096                         else if(ima->source==IMA_SRC_FILE) {
2097                                 
2098                                 if(ima->type==IMA_TYPE_IMAGE)
2099                                         ibuf= image_load_image_file(ima, iuser, frame); /* cfra only for '#', this global is OK */
2100                                 /* no else; on load the ima type can change */
2101                                 if(ima->type==IMA_TYPE_MULTILAYER)
2102                                         /* keeps render result, stores ibufs in listbase, allows saving */
2103                                         ibuf= image_get_ibuf_multilayer(ima, iuser);
2104                                         
2105                         }
2106                         else if(ima->source == IMA_SRC_GENERATED) {
2107                                 /* generated is: ibuf is allocated dynamically */
2108                                 /* UV testgrid or black or solid etc */
2109                                 if(ima->gen_x==0) ima->gen_x= 1024;
2110                                 if(ima->gen_y==0) ima->gen_y= 1024;
2111                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 0, ima->gen_type, color);
2112                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2113                                 ima->ok= IMA_OK_LOADED;
2114                         }
2115                         else if(ima->source == IMA_SRC_VIEWER) {
2116                                 if(ima->type==IMA_TYPE_R_RESULT) {
2117                                         /* always verify entirely, and potentially
2118                                            returns pointer to release later */
2119                                         ibuf= image_get_render_result(ima, iuser, lock_r);
2120                                 }
2121                                 else if(ima->type==IMA_TYPE_COMPOSITE) {
2122                                         /* requires lock/unlock, otherwise don't return image */
2123                                         if(lock_r) {
2124                                                 /* unlock in BKE_image_release_ibuf */
2125                                                 BLI_lock_thread(LOCK_VIEWER);
2126                                                 *lock_r= ima;
2127
2128                                                 /* Composite Viewer, all handled in compositor */
2129                                                 /* fake ibuf, will be filled in compositor */
2130                                                 ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
2131                                                 image_assign_ibuf(ima, ibuf, 0, frame);
2132                                         }
2133                                 }
2134                         }
2135                 }
2136
2137                 BLI_unlock_thread(LOCK_IMAGE);
2138         }
2139
2140         /* we assuming that if it is not rendering, it's also not multithreaded
2141          * (a somewhat weak assumption) */
2142         if(G.rendering==0)
2143                 tag_image_time(ima);
2144
2145         return ibuf;
2146 }
2147
2148 void BKE_image_release_ibuf(Image *ima, void *lock)
2149 {
2150         /* for getting image during threaded render / compositing, need to release */
2151         if(lock == ima) {
2152                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2153         }
2154         else if(lock) {
2155                 RE_ReleaseResultImage(lock); /* render result */
2156                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2157         }
2158 }
2159
2160 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2161 {
2162         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2163 }
2164
2165 void BKE_image_user_calc_frame(ImageUser *iuser, int cfra, int fieldnr)
2166 {
2167         int imanr, len;
2168         
2169         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2170         len= (iuser->fie_ima*iuser->frames)/2;
2171         
2172         if(len==0) {
2173                 iuser->framenr= 0;
2174         }
2175         else {
2176                 cfra= cfra - iuser->sfra+1;
2177                 
2178                 /* cyclic */
2179                 if(iuser->cycl) {
2180                         cfra= ( (cfra) % len );
2181                         if(cfra < 0) cfra+= len;
2182                         if(cfra==0) cfra= len;
2183                 }
2184                 
2185                 if(cfra<1) cfra= 1;
2186                 else if(cfra>len) cfra= len;
2187                 
2188                 /* convert current frame to current field */
2189                 cfra= 2*(cfra);
2190                 if(fieldnr) cfra++;
2191                 
2192                 /* transform to images space */
2193                 imanr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
2194                 if(imanr>iuser->frames) imanr= iuser->frames;
2195                 imanr+= iuser->offset;
2196                 
2197                 if(iuser->cycl) {
2198                         imanr= ( (imanr) % len );
2199                         while(imanr < 0) imanr+= len;
2200                         if(imanr==0) imanr= len;
2201                 }
2202         
2203                 /* allows image users to handle redraws */
2204                 if(iuser->flag & IMA_ANIM_ALWAYS)
2205                         if(imanr!=iuser->framenr)
2206                                 iuser->flag |= IMA_ANIM_REFRESHED;
2207                 
2208                 iuser->framenr= imanr;
2209                 if(iuser->ok==0) iuser->ok= 1;
2210         }
2211 }