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