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