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