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