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