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