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