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