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