28559812f4d8f068fc52e8936138ddc8c5de9523
[blender-staging.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, Object *camera, 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", camera ? 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 (camera && camera->type == OB_CAMERA) {
969                         BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)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, Object *camera, 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, y_ofs;
1014         float h_fixed;
1015         const int mono= blf_mono_font_render; // XXX
1016         
1017         if (!rect && !rectf)
1018                 return;
1019         
1020         stampdata(scene, camera, &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                 float baseline;
1038                 BLF_boundbox(mono, "^|/_AgPpJjlYy", &box);
1039                 h_fixed= box.ymax - box.ymin;
1040                 
1041                 /* crude way to get the decent line from A->j*/
1042                 BLF_boundbox(mono, "A", &box);
1043                 baseline= box.ymin;
1044                 BLF_boundbox(mono, "j", &box);
1045                 y_ofs = (int)(baseline - box.ymin);
1046                 if(y_ofs < 0) y_ofs= 0; /* should never happen */
1047                 y_ofs++;
1048         }
1049
1050         x= 0;
1051         y= height;
1052
1053         if (stamp_data.file[0]) {
1054                 /* Top left corner */
1055                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h= h_fixed;
1056                 y -= h;
1057
1058                 /* also a little of space to the background. */
1059                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y-3, w+3, y+h+2);
1060
1061                 /* and draw the text. */
1062                 BLF_position(mono, x, y + y_ofs, 0.0);
1063                 BLF_draw_buffer(mono, stamp_data.file);
1064
1065                 /* the extra pixel for background. */
1066                 y -= 4;
1067         }
1068
1069         /* Top left corner, below File */
1070         if (stamp_data.note[0]) {
1071                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h= h_fixed;
1072                 y -= h;
1073
1074                 /* and space for background. */
1075                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-3, w+3, y+h+2);
1076
1077                 BLF_position(mono, x, y + y_ofs, 0.0);
1078                 BLF_draw_buffer(mono, stamp_data.note);
1079
1080                 /* the extra pixel for background. */
1081                 y -= 4;
1082         }
1083         
1084         /* Top left corner, below File (or Note) */
1085         if (stamp_data.date[0]) {
1086                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h= h_fixed;
1087                 y -= h;
1088
1089                 /* and space for background. */
1090                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-3, w+3, y+h+2);
1091
1092                 BLF_position(mono, x, y + y_ofs, 0.0);
1093                 BLF_draw_buffer(mono, stamp_data.date);
1094
1095                 /* the extra pixel for background. */
1096                 y -= 4;
1097         }
1098
1099         /* Top left corner, below File, Date or Note */
1100         if (stamp_data.rendertime[0]) {
1101                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h= h_fixed;
1102                 y -= h;
1103
1104                 /* and space for background. */
1105                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-3, w+3, y+h+2);
1106
1107                 BLF_position(mono, x, y + y_ofs, 0.0);
1108                 BLF_draw_buffer(mono, stamp_data.rendertime);
1109         }
1110
1111         x= 0;
1112         y= 0;
1113
1114         /* Bottom left corner, leaving space for timing */
1115         if (stamp_data.marker[0]) {
1116                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h= h_fixed;
1117
1118                 /* extra space for background. */
1119                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, w+2, y+h+2);
1120
1121                 /* and pad the text. */
1122                 BLF_position(mono, x, y + y_ofs, 0.0);
1123                 BLF_draw_buffer(mono, stamp_data.marker);
1124
1125                 /* space width. */
1126                 x += w + pad;
1127         }
1128         
1129         /* Left bottom corner */
1130         if (stamp_data.time[0]) {
1131                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h= h_fixed;
1132
1133                 /* extra space for background */
1134                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+2);
1135
1136                 /* and pad the text. */
1137                 BLF_position(mono, x, y + y_ofs, 0.0);
1138                 BLF_draw_buffer(mono, stamp_data.time);
1139
1140                 /* space width. */
1141                 x += w + pad;
1142         }
1143         
1144         if (stamp_data.frame[0]) {
1145                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h= h_fixed;
1146
1147                 /* extra space for background. */
1148                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+2);
1149
1150                 /* and pad the text. */
1151                 BLF_position(mono, x, y + y_ofs, 0.0);
1152                 BLF_draw_buffer(mono, stamp_data.frame);
1153
1154                 /* space width. */
1155                 x += w + pad;
1156         }
1157
1158         if (stamp_data.camera[0]) {
1159                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h= h_fixed;
1160
1161                 /* extra space for background. */
1162                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+2);
1163                 BLF_position(mono, x, y + y_ofs, 0.0);
1164                 BLF_draw_buffer(mono, stamp_data.camera);
1165
1166                 /* space width. */
1167                 x += w + pad;
1168         }
1169
1170         if (stamp_data.cameralens[0]) {
1171                 BLF_width_and_height(mono, stamp_data.cameralens, &w, &h); h= h_fixed;
1172
1173                 /* extra space for background. */
1174                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+2);
1175                 BLF_position(mono, x, y + y_ofs, 0.0);
1176                 BLF_draw_buffer(mono, stamp_data.cameralens);
1177         }
1178         
1179         if (stamp_data.scene[0]) {
1180                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h= h_fixed;
1181
1182                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1183                 x= width - w - 2;
1184
1185                 /* extra space for background. */
1186                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+3, y+h+2);
1187
1188                 /* and pad the text. */
1189                 BLF_position(mono, x, y+y_ofs, 0.0);
1190                 BLF_draw_buffer(mono, stamp_data.scene);
1191         }
1192         
1193         if (stamp_data.strip[0]) {
1194                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h= h_fixed;
1195
1196                 /* Top right corner, with an extra space because blenfont is too strict! */
1197                 x= width - w - pad;
1198                 y= height - h;
1199
1200                 /* extra space for background. */
1201                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y-3, x+w+pad, y+h+2);
1202
1203                 BLF_position(mono, x, y + y_ofs, 0.0);
1204                 BLF_draw_buffer(mono, stamp_data.strip);
1205         }
1206
1207         /* cleanup the buffer. */
1208         BLF_buffer(mono, NULL, NULL, 0, 0, 0);
1209 }
1210
1211 void BKE_stamp_info(Scene *scene, Object *camera, struct ImBuf *ibuf)
1212 {
1213         struct StampData stamp_data;
1214
1215         if (!ibuf)      return;
1216         
1217         /* fill all the data values, no prefix */
1218         stampdata(scene, camera, &stamp_data, 0);
1219         
1220         if (stamp_data.file[0])         IMB_metadata_change_field (ibuf, "File",                stamp_data.file);
1221         if (stamp_data.note[0])         IMB_metadata_change_field (ibuf, "Note",                stamp_data.note);
1222         if (stamp_data.date[0])         IMB_metadata_change_field (ibuf, "Date",                stamp_data.date);
1223         if (stamp_data.marker[0])       IMB_metadata_change_field (ibuf, "Marker",      stamp_data.marker);
1224         if (stamp_data.time[0])         IMB_metadata_change_field (ibuf, "Time",                stamp_data.time);
1225         if (stamp_data.frame[0])        IMB_metadata_change_field (ibuf, "Frame",       stamp_data.frame);
1226         if (stamp_data.camera[0])       IMB_metadata_change_field (ibuf, "Camera",      stamp_data.camera);
1227         if (stamp_data.cameralens[0]) IMB_metadata_change_field (ibuf, "Lens",  stamp_data.cameralens);
1228         if (stamp_data.scene[0])        IMB_metadata_change_field (ibuf, "Scene",       stamp_data.scene);
1229         if (stamp_data.strip[0])        IMB_metadata_change_field (ibuf, "Strip",       stamp_data.strip);
1230         if (stamp_data.rendertime[0]) IMB_metadata_change_field (ibuf, "RenderTime", stamp_data.rendertime);
1231 }
1232
1233 int BKE_alphatest_ibuf(ImBuf *ibuf)
1234 {
1235         int tot;
1236         if(ibuf->rect_float) {
1237                 float *buf= ibuf->rect_float;
1238                 for(tot= ibuf->x * ibuf->y; tot--; buf+=4) {
1239                         if(buf[3] < 1.0f) {
1240                                 return TRUE;
1241                         }
1242                 }
1243         }
1244         else if (ibuf->rect) {
1245                 unsigned char *buf= (unsigned char *)ibuf->rect;
1246                 for(tot= ibuf->x * ibuf->y; tot--; buf+=4) {
1247                         if(buf[3] != 255) {
1248                                 return TRUE;
1249                         }
1250                 }
1251         }
1252
1253         return FALSE;
1254 }
1255
1256 int BKE_write_ibuf(ImBuf *ibuf, const char *name, int imtype, int subimtype, int quality)
1257 {
1258         int ok;
1259         (void)subimtype; /* quies unused warnings */
1260
1261         if(imtype == -1) {
1262                 /* use whatever existing image type is set by 'ibuf' */
1263         }
1264         else if(imtype== R_IRIS) {
1265                 ibuf->ftype= IMAGIC;
1266         }
1267 #ifdef WITH_HDR
1268         else if (imtype==R_RADHDR) {
1269                 ibuf->ftype= RADHDR;
1270         }
1271 #endif
1272         else if (ELEM5(imtype, R_PNG, R_FFMPEG, R_H264, R_THEORA, R_XVID)) {
1273                 ibuf->ftype= PNG;
1274
1275                 if(imtype==R_PNG)
1276                         ibuf->ftype |= quality;  /* quality is actually compression 0-100 --> 0-9 */
1277
1278         }
1279 #ifdef WITH_DDS
1280         else if (imtype==R_DDS) {
1281                 ibuf->ftype= DDS;
1282         }
1283 #endif
1284         else if (imtype==R_BMP) {
1285                 ibuf->ftype= BMP;
1286         }
1287 #ifdef WITH_TIFF
1288         else if (imtype==R_TIFF) {
1289                 ibuf->ftype= TIF;
1290
1291                 if(subimtype & R_TIFF_16BIT)
1292                         ibuf->ftype |= TIF_16BIT;
1293         }
1294 #endif
1295 #ifdef WITH_OPENEXR
1296         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
1297                 ibuf->ftype= OPENEXR;
1298                 if(subimtype & R_OPENEXR_HALF)
1299                         ibuf->ftype |= OPENEXR_HALF;
1300                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
1301                 
1302                 if(!(subimtype & R_OPENEXR_ZBUF))
1303                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1304                 
1305         }
1306 #endif
1307 #ifdef WITH_CINEON
1308         else if (imtype==R_CINEON) {
1309                 ibuf->ftype = CINEON;
1310         }
1311         else if (imtype==R_DPX) {
1312                 ibuf->ftype = DPX;
1313         }
1314 #endif
1315         else if (imtype==R_TARGA) {
1316                 ibuf->ftype= TGA;
1317         }
1318         else if(imtype==R_RAWTGA) {
1319                 ibuf->ftype= RAWTGA;
1320         }
1321 #ifdef WITH_OPENJPEG
1322         else if(imtype==R_JP2) {
1323                 if(quality < 10) quality= 90;
1324                 ibuf->ftype= JP2|quality;
1325                 
1326                 if (subimtype & R_JPEG2K_16BIT) {
1327                         ibuf->ftype |= JP2_16BIT;
1328                 } else if (subimtype & R_JPEG2K_12BIT) {
1329                         ibuf->ftype |= JP2_12BIT;
1330                 }
1331                 
1332                 if (subimtype & R_JPEG2K_YCC) {
1333                         ibuf->ftype |= JP2_YCC;
1334                 }
1335                 
1336                 if (subimtype & R_JPEG2K_CINE_PRESET) {
1337                         ibuf->ftype |= JP2_CINE;
1338                         if (subimtype & R_JPEG2K_CINE_48FPS)
1339                                 ibuf->ftype |= JP2_CINE_48FPS;
1340                 }
1341         }
1342 #endif
1343         else {
1344                 /* R_JPEG90, etc. default we save jpegs */
1345                 if(quality < 10) quality= 90;
1346                 ibuf->ftype= JPG|quality;
1347                 if(ibuf->depth==32) ibuf->depth= 24;    /* unsupported feature only confuses other s/w */
1348         }
1349         
1350         BLI_make_existing_file(name);
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 int BKE_write_ibuf_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, int imtype, int subimtype, int quality)
1361 {
1362         if(scene && scene->r.stamp & R_STAMP_ALL)
1363                 BKE_stamp_info(scene, camera, ibuf);
1364
1365         return BKE_write_ibuf(ibuf, name, imtype, subimtype, quality);
1366 }
1367
1368
1369 void BKE_makepicstring(char *string, const char *base, int frame, int imtype, const short use_ext, const short use_frames)
1370 {
1371         if (string==NULL) return;
1372         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1373         BLI_path_abs(string, G.main->name);
1374
1375         if(use_frames)
1376                 BLI_path_frame(string, frame, 4);
1377
1378         if(use_ext)
1379                 BKE_add_image_extension(string, imtype);
1380                 
1381 }
1382
1383 /* used by sequencer too */
1384 struct anim *openanim(char *name, int flags)
1385 {
1386         struct anim *anim;
1387         struct ImBuf *ibuf;
1388         
1389         anim = IMB_open_anim(name, flags);
1390         if (anim == NULL) return NULL;
1391
1392         ibuf = IMB_anim_absolute(anim, 0);
1393         if (ibuf == NULL) {
1394                 if(BLI_exists(name))
1395                         printf("not an anim: %s\n", name);
1396                 else
1397                         printf("anim file doesn't exist: %s\n", name);
1398                 IMB_free_anim(anim);
1399                 return NULL;
1400         }
1401         IMB_freeImBuf(ibuf);
1402         
1403         return(anim);
1404 }
1405
1406 /* ************************* New Image API *************** */
1407
1408
1409 /* Notes about Image storage 
1410 - packedfile
1411   -> written in .blend
1412 - filename
1413   -> written in .blend
1414 - movie
1415   -> comes from packedfile or filename
1416 - renderresult
1417   -> comes from packedfile or filename
1418 - listbase
1419   -> ibufs from exrhandle
1420 - flipbook array
1421   -> ibufs come from movie, temporary renderresult or sequence
1422 - ibuf
1423   -> comes from packedfile or filename or generated
1424
1425 */
1426
1427
1428 /* forces existence of 1 Image for renderout or nodes, returns Image */
1429 /* name is only for default, when making new one */
1430 Image *BKE_image_verify_viewer(int type, const char *name)
1431 {
1432         Image *ima;
1433         
1434         for(ima=G.main->image.first; ima; ima= ima->id.next)
1435                 if(ima->source==IMA_SRC_VIEWER)
1436                         if(ima->type==type)
1437                                 break;
1438         
1439         if(ima==NULL)
1440                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1441         
1442         /* happens on reload, imagewindow cannot be image user when hidden*/
1443         if(ima->id.us==0)
1444                 id_us_plus(&ima->id);
1445
1446         return ima;
1447 }
1448
1449 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1450 {
1451         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1452 }
1453
1454 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1455 {
1456         if(ima==NULL)
1457                 return;
1458         
1459         switch(signal) {
1460         case IMA_SIGNAL_FREE:
1461                 image_free_buffers(ima);
1462                 if(iuser)
1463                         iuser->ok= 1;
1464                 break;
1465         case IMA_SIGNAL_SRC_CHANGE:
1466                 if(ima->type == IMA_TYPE_UV_TEST)
1467                         if(ima->source != IMA_SRC_GENERATED)
1468                                 ima->type= IMA_TYPE_IMAGE;
1469
1470                 if(ima->source==IMA_SRC_GENERATED) {
1471                         if(ima->gen_x==0 || ima->gen_y==0) {
1472                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1473                                 if(ibuf) {
1474                                         ima->gen_x= ibuf->x;
1475                                         ima->gen_y= ibuf->y;
1476                                 }
1477                         }
1478                 }
1479
1480                 /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
1481                 if(ima->type!=IMA_TYPE_MULTILAYER)
1482                         image_free_buffers(ima);
1483
1484                 ima->ok= 1;
1485                 if(iuser)
1486                         iuser->ok= 1;
1487                 break;
1488                         
1489         case IMA_SIGNAL_RELOAD:
1490                 /* try to repack file */
1491                 if(ima->packedfile) {
1492                         PackedFile *pf;
1493                         pf = newPackedFile(NULL, ima->name);
1494                         if (pf) {
1495                                 freePackedFile(ima->packedfile);
1496                                 ima->packedfile = pf;
1497                                 image_free_buffers(ima);
1498                         } else {
1499                                 printf("ERROR: Image not available. Keeping packed image\n");
1500                         }
1501                 }
1502                 else
1503                         image_free_buffers(ima);
1504                 
1505                 if(iuser)
1506                         iuser->ok= 1;
1507                 
1508                 break;
1509         case IMA_SIGNAL_USER_NEW_IMAGE:
1510                 if(iuser) {
1511                         iuser->ok= 1;
1512                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1513                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1514                                         iuser->multi_index= 0;
1515                                         iuser->layer= iuser->pass= 0;
1516                                 }
1517                         }
1518                 }
1519                 break;
1520         }
1521         
1522         /* dont use notifiers because they are not 100% sure to succseed
1523          * this also makes sure all scenes are accounted for. */
1524         {
1525                 Scene *scene;
1526                 for(scene= G.main->scene.first; scene; scene= scene->id.next) {
1527                         if(scene->nodetree) {
1528                                 NodeTagIDChanged(scene->nodetree, &ima->id);
1529                         }
1530                 }
1531         }
1532 }
1533
1534 /* if layer or pass changes, we need an index for the imbufs list */
1535 /* note it is called for rendered results, but it doesnt use the index! */
1536 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1537 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1538 {
1539         RenderLayer *rl;
1540         RenderPass *rpass= NULL;
1541         
1542         if(rr==NULL) 
1543                 return NULL;
1544         
1545         if(iuser) {
1546                 short index= 0, rl_index= 0, rp_index;
1547                 
1548                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1549                         rp_index= 0;
1550                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1551                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1552                                         break;
1553                         if(rpass)
1554                                 break;
1555                 }
1556                 
1557                 if(rpass)
1558                         iuser->multi_index= index;
1559                 else 
1560                         iuser->multi_index= 0;
1561         }
1562         if(rpass==NULL) {
1563                 rl= rr->layers.first;
1564                 if(rl)
1565                         rpass= rl->passes.first;
1566         }
1567         
1568         return rpass;
1569 }
1570
1571 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
1572 {
1573         if(ima->rr) {
1574                 return ima->rr;
1575         }
1576         else if(ima->type==IMA_TYPE_R_RESULT) {
1577                 if(ima->render_slot == ima->last_render_slot)
1578                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
1579                 else
1580                         return ima->renders[ima->render_slot];
1581         }
1582         else
1583                 return NULL;
1584 }
1585
1586 void BKE_image_release_renderresult(Scene *scene, Image *ima)
1587 {
1588         if(ima->rr);
1589         else if(ima->type==IMA_TYPE_R_RESULT) {
1590                 if(ima->render_slot == ima->last_render_slot)
1591                         RE_ReleaseResult(RE_GetRender(scene->id.name));
1592         }
1593 }
1594
1595 void BKE_image_backup_render(Scene *scene, Image *ima)
1596 {
1597         /* called right before rendering, ima->renders contains render
1598            result pointers for everything but the current render */
1599         Render *re= RE_GetRender(scene->id.name);
1600         int slot= ima->render_slot, last= ima->last_render_slot;
1601
1602         if(slot != last) {
1603                 if(ima->renders[slot]) {
1604                         RE_FreeRenderResult(ima->renders[slot]);
1605                         ima->renders[slot]= NULL;
1606                 }
1607
1608                 ima->renders[last]= NULL;
1609                 RE_SwapResult(re, &ima->renders[last]);
1610         }
1611
1612         ima->last_render_slot= slot;
1613 }
1614
1615 /* after imbuf load, openexr type can return with a exrhandle open */
1616 /* in that case we have to build a render-result */
1617 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1618 {
1619         
1620         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1621
1622 #ifdef WITH_OPENEXR
1623         IMB_exr_close(ibuf->userdata);
1624 #endif
1625
1626         ibuf->userdata= NULL;
1627         if(ima->rr)
1628                 ima->rr->framenr= framenr;
1629 }
1630
1631 /* common stuff to do with images after loading */
1632 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1633 {
1634         /* preview is NULL when it has never been used as an icon before */
1635         if(G.background==0 && ima->preview==NULL)
1636                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1637
1638         /* fields */
1639         if (ima->flag & IMA_FIELDS) {
1640                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1641                 else de_interlace_ng(ibuf);
1642         }
1643         /* timer */
1644         ima->lastused = clock() / CLOCKS_PER_SEC;
1645         
1646         ima->ok= IMA_OK_LOADED;
1647         
1648 }
1649
1650 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1651 {
1652         struct ImBuf *ibuf;
1653         unsigned short numlen;
1654         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1655         int flag;
1656         
1657         /* XXX temp stuff? */
1658         if(ima->lastframe != frame)
1659                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1660
1661         ima->lastframe= frame;
1662         BLI_strncpy(name, ima->name, sizeof(name));
1663         BLI_stringdec(name, head, tail, &numlen);
1664         BLI_stringenc(name, head, tail, numlen, frame);
1665
1666         if(ima->id.lib)
1667                 BLI_path_abs(name, ima->id.lib->filepath);
1668         else
1669                 BLI_path_abs(name, G.main->name);
1670         
1671         flag= IB_rect|IB_multilayer;
1672         if(ima->flag & IMA_DO_PREMUL)
1673                 flag |= IB_premul;
1674
1675         /* read ibuf */
1676         ibuf = IMB_loadiffname(name, flag);
1677         if(G.f & G_DEBUG) printf("loaded %s\n", name);
1678         
1679         if (ibuf) {
1680 #ifdef WITH_OPENEXR
1681                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1682                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1683                         image_create_multilayer(ima, ibuf, frame);      
1684                         ima->type= IMA_TYPE_MULTILAYER;
1685                         IMB_freeImBuf(ibuf);
1686                         ibuf= NULL;
1687                 }
1688                 else {
1689                         image_initialize_after_load(ima, ibuf);
1690                         image_assign_ibuf(ima, ibuf, 0, frame);
1691                 }
1692 #else
1693                 image_initialize_after_load(ima, ibuf);
1694                 image_assign_ibuf(ima, ibuf, 0, frame);
1695 #endif
1696         }
1697         else
1698                 ima->ok= 0;
1699         
1700         if(iuser)
1701                 iuser->ok= ima->ok;
1702         
1703         return ibuf;
1704 }
1705
1706 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1707 {
1708         struct ImBuf *ibuf= NULL;
1709         
1710         /* either we load from RenderResult, or we have to load a new one */
1711         
1712         /* check for new RenderResult */
1713         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1714                 /* copy to survive not found multilayer image */
1715                 RenderResult *oldrr= ima->rr;
1716         
1717                 ima->rr= NULL;
1718                 ibuf = image_load_sequence_file(ima, iuser, frame);
1719                 
1720                 if(ibuf) { /* actually an error */
1721                         ima->type= IMA_TYPE_IMAGE;
1722                         printf("error, multi is normal image\n");
1723                 }
1724                 // printf("loaded new result %p\n", ima->rr);
1725                 /* free result if new one found */
1726                 if(ima->rr) {
1727                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1728                         if(oldrr) RE_FreeRenderResult(oldrr);
1729                 }
1730                 else {
1731                         ima->rr= oldrr;
1732                 }
1733
1734         }
1735         if(ima->rr) {
1736                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1737                 
1738                 if(rpass) {
1739                         // printf("load from pass %s\n", rpass->name);
1740                         /* since we free  render results, we copy the rect */
1741                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
1742                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1743                         ibuf->flags |= IB_rectfloat;
1744                         ibuf->mall= IB_rectfloat;
1745                         ibuf->channels= rpass->channels;
1746                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1747                         
1748                         image_initialize_after_load(ima, ibuf);
1749                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
1750                         
1751                 }
1752                 // else printf("pass not found\n");
1753         }
1754         else
1755                 ima->ok= 0;
1756         
1757         if(iuser)
1758                 iuser->ok= ima->ok;
1759         
1760         return ibuf;
1761 }
1762
1763
1764 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
1765 {
1766         struct ImBuf *ibuf= NULL;
1767         
1768         ima->lastframe= frame;
1769         
1770         if(ima->anim==NULL) {
1771                 char str[FILE_MAX];
1772                 
1773                 BLI_strncpy(str, ima->name, FILE_MAX);
1774                 if(ima->id.lib)
1775                         BLI_path_abs(str, ima->id.lib->filepath);
1776                 else
1777                         BLI_path_abs(str, G.main->name);
1778                 
1779                 ima->anim = openanim(str, IB_rect);
1780                 
1781                 /* let's initialize this user */
1782                 if(ima->anim && iuser && iuser->frames==0)
1783                         iuser->frames= IMB_anim_get_duration(ima->anim);
1784         }
1785         
1786         if(ima->anim) {
1787                 int dur = IMB_anim_get_duration(ima->anim);
1788                 int fra= frame-1;
1789                 
1790                 if(fra<0) fra = 0;
1791                 if(fra>(dur-1)) fra= dur-1;
1792                 ibuf = IMB_anim_absolute(ima->anim, fra);
1793                 
1794                 if(ibuf) {
1795                         image_initialize_after_load(ima, ibuf);
1796                         image_assign_ibuf(ima, ibuf, 0, frame);
1797                 }
1798                 else
1799                         ima->ok= 0;
1800         }
1801         else
1802                 ima->ok= 0;
1803         
1804         if(iuser)
1805                 iuser->ok= ima->ok;
1806         
1807         return ibuf;
1808 }
1809
1810 /* warning, 'iuser' can be NULL */
1811 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
1812 {
1813         struct ImBuf *ibuf;
1814         char str[FILE_MAX];
1815         int assign = 0, flag;
1816         
1817         /* always ensure clean ima */
1818         image_free_buffers(ima);
1819         
1820         /* is there a PackedFile with this image ? */
1821         if (ima->packedfile) {
1822                 flag = IB_rect|IB_multilayer;
1823                 if(ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
1824                 
1825                 ibuf = IMB_ibImageFromMemory((unsigned char*)ima->packedfile->data, ima->packedfile->size, flag);
1826         } 
1827         else {
1828                 flag= IB_rect|IB_multilayer|IB_metadata;
1829                 if(ima->flag & IMA_DO_PREMUL)
1830                         flag |= IB_premul;
1831                         
1832                 /* get the right string */
1833                 BLI_strncpy(str, ima->name, sizeof(str));
1834                 if(ima->id.lib)
1835                         BLI_path_abs(str, ima->id.lib->filepath);
1836                 else
1837                         BLI_path_abs(str, G.main->name);
1838                 
1839                 /* read ibuf */
1840                 ibuf = IMB_loadiffname(str, flag);
1841         }
1842         
1843         if (ibuf) {
1844                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1845                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1846                         image_create_multilayer(ima, ibuf, cfra);       
1847                         ima->type= IMA_TYPE_MULTILAYER;
1848                         IMB_freeImBuf(ibuf);
1849                         ibuf= NULL;
1850                 }
1851                 else {
1852                         image_initialize_after_load(ima, ibuf);
1853                         assign= 1;
1854
1855                         /* check if the image is a font image... */
1856                         detectBitmapFont(ibuf);
1857                         
1858                         /* make packed file for autopack */
1859                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
1860                                 ima->packedfile = newPackedFile(NULL, str);
1861                 }
1862         }
1863         else
1864                 ima->ok= 0;
1865         
1866         if(assign)
1867                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1868
1869         if(iuser)
1870                 iuser->ok= ima->ok;
1871         
1872         return ibuf;
1873 }
1874
1875 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
1876 {
1877         ImBuf *ibuf= NULL;
1878         
1879         if(ima->rr==NULL) {
1880                 ibuf = image_load_image_file(ima, iuser, 0);
1881                 if(ibuf) { /* actually an error */
1882                         ima->type= IMA_TYPE_IMAGE;
1883                         return ibuf;
1884                 }
1885         }
1886         if(ima->rr) {
1887                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1888
1889                 if(rpass) {
1890                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
1891                         
1892                         image_initialize_after_load(ima, ibuf);
1893                         
1894                         ibuf->rect_float= rpass->rect;
1895                         ibuf->flags |= IB_rectfloat;
1896                         ibuf->channels= rpass->channels;
1897                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1898
1899                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1900                 }
1901         }
1902         
1903         if(ibuf==NULL) 
1904                 ima->ok= 0;
1905         if(iuser)
1906                 iuser->ok= ima->ok;
1907         
1908         return ibuf;
1909 }
1910
1911
1912 /* showing RGBA result itself (from compo/sequence) or
1913    like exr, using layers etc */
1914 /* always returns a single ibuf, also during render progress */
1915 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
1916 {
1917         Render *re;
1918         RenderResult rres;
1919         float *rectf, *rectz;
1920         unsigned int *rect;
1921         float dither;
1922         int channels, layer, pass;
1923         ImBuf *ibuf;
1924         int from_render= (ima->render_slot == ima->last_render_slot);
1925
1926         if(!(iuser && iuser->scene))
1927                 return NULL;
1928
1929         /* if we the caller is not going to release the lock, don't give the image */
1930         if(!lock_r)
1931                 return NULL;
1932
1933         re= RE_GetRender(iuser->scene->id.name);
1934
1935         channels= 4;
1936         layer= (iuser)? iuser->layer: 0;
1937         pass= (iuser)? iuser->pass: 0;
1938
1939         if(from_render) {
1940                 RE_AcquireResultImage(re, &rres);
1941         }
1942         else if(ima->renders[ima->render_slot]) {
1943                 rres= *(ima->renders[ima->render_slot]);
1944                 rres.have_combined= rres.rectf != NULL;
1945         }
1946         else
1947                 memset(&rres, 0, sizeof(RenderResult));
1948         
1949         if(!(rres.rectx > 0 && rres.recty > 0)) {
1950                 if(from_render)
1951                         RE_ReleaseResultImage(re);
1952                 return NULL;
1953         }
1954
1955         /* release is done in BKE_image_release_ibuf using lock_r */
1956         if(from_render) {
1957                 BLI_lock_thread(LOCK_VIEWER);
1958                 *lock_r= re;
1959         }
1960
1961         /* this gives active layer, composite or seqence result */
1962         rect= (unsigned int *)rres.rect32;
1963         rectf= rres.rectf;
1964         rectz= rres.rectz;
1965         dither= iuser->scene->r.dither_intensity;
1966
1967         /* combined layer gets added as first layer */
1968         if(rres.have_combined && layer==0);
1969         else if(rres.layers.first) {
1970                 RenderLayer *rl= BLI_findlink(&rres.layers, layer-(rres.have_combined?1:0));
1971                 if(rl) {
1972                         RenderPass *rpass;
1973
1974                         /* there's no combined pass, is in renderlayer itself */
1975                         if(pass==0) {
1976                                 rectf= rl->rectf;
1977                         }
1978                         else {
1979                                 rpass= BLI_findlink(&rl->passes, pass-1);
1980                                 if(rpass) {
1981                                         channels= rpass->channels;
1982                                         rectf= rpass->rect;
1983                                         dither= 0.0f; /* don't dither passes */
1984                                 }
1985                         }
1986
1987                         for(rpass= rl->passes.first; rpass; rpass= rpass->next)
1988                                 if(rpass->passtype == SCE_PASS_Z)
1989                                         rectz= rpass->rect;
1990                 }
1991         }
1992
1993         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1994
1995         /* make ibuf if needed, and initialize it */
1996         if(ibuf==NULL) {
1997                 ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
1998                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1999         }
2000
2001         ibuf->x= rres.rectx;
2002         ibuf->y= rres.recty;
2003         
2004         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
2005                 imb_freerectImBuf(ibuf);
2006
2007         if(rect)
2008                 ibuf->rect= rect;
2009         
2010         if(rectf) {
2011                 ibuf->rect_float= rectf;
2012                 ibuf->flags |= IB_rectfloat;
2013                 ibuf->channels= channels;
2014         }
2015         else {
2016                 ibuf->rect_float= NULL;
2017                 ibuf->flags &= ~IB_rectfloat;
2018         }
2019
2020         if(rectz) {
2021                 ibuf->zbuf_float= rectz;
2022                 ibuf->flags |= IB_zbuffloat;
2023         }
2024         else {
2025                 ibuf->zbuf_float= NULL;
2026                 ibuf->flags &= ~IB_zbuffloat;
2027         }
2028
2029         /* since its possible to access the buffer from the image directly, set the profile [#25073] */
2030         ibuf->profile= (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) ? IB_PROFILE_LINEAR_RGB : IB_PROFILE_NONE;
2031
2032         ibuf->dither= dither;
2033
2034         ima->ok= IMA_OK_LOADED;
2035
2036         return ibuf;
2037 }
2038
2039 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2040 {
2041         ImBuf *ibuf = NULL;
2042         int frame = 0, index = 0;
2043
2044         /* see if we already have an appropriate ibuf, with image source and type */
2045         if(ima->source==IMA_SRC_MOVIE) {
2046                 frame= iuser?iuser->framenr:ima->lastframe;
2047                 ibuf= image_get_ibuf(ima, 0, frame);
2048                 /* XXX temp stuff? */
2049                 if(ima->lastframe != frame)
2050                         ima->tpageflag |= IMA_TPAGE_REFRESH;
2051                 ima->lastframe = frame;
2052         }
2053         else if(ima->source==IMA_SRC_SEQUENCE) {
2054                 if(ima->type==IMA_TYPE_IMAGE) {
2055                         frame= iuser?iuser->framenr:ima->lastframe;
2056                         ibuf= image_get_ibuf(ima, 0, frame);
2057                         
2058                         /* XXX temp stuff? */
2059                         if(ima->lastframe != frame) {
2060                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2061                         }
2062                         ima->lastframe = frame;
2063                 }       
2064                 else if(ima->type==IMA_TYPE_MULTILAYER) {
2065                         frame= iuser?iuser->framenr:ima->lastframe;
2066                         index= iuser?iuser->multi_index:IMA_NO_INDEX;
2067                         ibuf= image_get_ibuf(ima, index, frame);
2068                 }
2069         }
2070         else if(ima->source==IMA_SRC_FILE) {
2071                 if(ima->type==IMA_TYPE_IMAGE)
2072                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2073                 else if(ima->type==IMA_TYPE_MULTILAYER)
2074                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2075         }
2076         else if(ima->source == IMA_SRC_GENERATED) {
2077                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2078         }
2079         else if(ima->source == IMA_SRC_VIEWER) {
2080                 /* always verify entirely, not that this shouldn't happen
2081                  * as part of texture sampling in rendering anyway, so not
2082                  * a big bottleneck */
2083         }
2084
2085         *frame_r = frame;
2086         *index_r = index;
2087
2088         return ibuf;
2089 }
2090
2091 /* Checks optional ImageUser and verifies/creates ImBuf. */
2092 /* use this one if you want to get a render result in progress,
2093  * if not, use BKE_image_get_ibuf which doesn't require a release */
2094 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2095 {
2096         ImBuf *ibuf= NULL;
2097         float color[] = {0, 0, 0, 1};
2098         int frame= 0, index= 0;
2099
2100         /* This function is intended to be thread-safe. It postpones the mutex lock
2101          * until it needs to load the image, if the image is already there it
2102          * should just get the pointer and return. The reason is that a lot of mutex
2103          * locks appears to be very slow on certain multicore macs, causing a render
2104          * with image textures to actually slow down as more threads are used.
2105          *
2106          * Note that all the image loading functions should also make sure they do
2107          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2108          * That means, the last two steps must be, 1) add the ibuf to the list and
2109          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2110         
2111         if(lock_r)
2112                 *lock_r= NULL;
2113
2114         /* quick reject tests */
2115         if(ima==NULL) 
2116                 return NULL;
2117         if(iuser) {
2118                 if(iuser->ok==0)
2119                         return NULL;
2120         }
2121         else if(ima->ok==0)
2122                 return NULL;
2123         
2124         /* try to get the ibuf without locking */
2125         ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2126
2127         if(ibuf == NULL) {
2128                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2129                  * load the image */
2130                 BLI_lock_thread(LOCK_IMAGE);
2131
2132                 /* need to check ok flag and loading ibuf again, because the situation
2133                  * might have changed in the meantime */
2134                 if(iuser) {
2135                         if(iuser->ok==0) {
2136                                 BLI_unlock_thread(LOCK_IMAGE);
2137                                 return NULL;
2138                         }
2139                 }
2140                 else if(ima->ok==0) {
2141                         BLI_unlock_thread(LOCK_IMAGE);
2142                         return NULL;
2143                 }
2144
2145                 ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2146
2147                 if(ibuf == NULL) {
2148                         /* we are sure we have to load the ibuf, using source and type */
2149                         if(ima->source==IMA_SRC_MOVIE) {
2150                                 /* source is from single file, use flipbook to store ibuf */
2151                                 ibuf= image_load_movie_file(ima, iuser, frame);
2152                         }
2153                         else if(ima->source==IMA_SRC_SEQUENCE) {
2154                                 if(ima->type==IMA_TYPE_IMAGE) {
2155                                         /* regular files, ibufs in flipbook, allows saving */
2156                                         ibuf= image_load_sequence_file(ima, iuser, frame);
2157                                 }
2158                                 /* no else; on load the ima type can change */
2159                                 if(ima->type==IMA_TYPE_MULTILAYER) {
2160                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2161                                         ibuf= image_load_sequence_multilayer(ima, iuser, frame);
2162                                 }
2163                         }
2164                         else if(ima->source==IMA_SRC_FILE) {
2165                                 
2166                                 if(ima->type==IMA_TYPE_IMAGE)
2167                                         ibuf= image_load_image_file(ima, iuser, frame); /* cfra only for '#', this global is OK */
2168                                 /* no else; on load the ima type can change */
2169                                 if(ima->type==IMA_TYPE_MULTILAYER)
2170                                         /* keeps render result, stores ibufs in listbase, allows saving */
2171                                         ibuf= image_get_ibuf_multilayer(ima, iuser);
2172                                         
2173                         }
2174                         else if(ima->source == IMA_SRC_GENERATED) {
2175                                 /* generated is: ibuf is allocated dynamically */
2176                                 /* UV testgrid or black or solid etc */
2177                                 if(ima->gen_x==0) ima->gen_x= 1024;
2178                                 if(ima->gen_y==0) ima->gen_y= 1024;
2179                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, 0, ima->gen_type, color);
2180                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2181                                 ima->ok= IMA_OK_LOADED;
2182                         }
2183                         else if(ima->source == IMA_SRC_VIEWER) {
2184                                 if(ima->type==IMA_TYPE_R_RESULT) {
2185                                         /* always verify entirely, and potentially
2186                                            returns pointer to release later */
2187                                         ibuf= image_get_render_result(ima, iuser, lock_r);
2188                                 }
2189                                 else if(ima->type==IMA_TYPE_COMPOSITE) {
2190                                         /* requires lock/unlock, otherwise don't return image */
2191                                         if(lock_r) {
2192                                                 /* unlock in BKE_image_release_ibuf */
2193                                                 BLI_lock_thread(LOCK_VIEWER);
2194                                                 *lock_r= ima;
2195
2196                                                 /* XXX anim play for viewer nodes not yet supported */
2197                                                 frame= 0; // XXX iuser?iuser->framenr:0;
2198                                                 ibuf= image_get_ibuf(ima, 0, frame);
2199
2200                                                 if(!ibuf) {
2201                                                         /* Composite Viewer, all handled in compositor */
2202                                                         /* fake ibuf, will be filled in compositor */
2203                                                         ibuf= IMB_allocImBuf(256, 256, 32, IB_rect);
2204                                                         image_assign_ibuf(ima, ibuf, 0, frame);
2205                                                 }
2206                                         }
2207                                 }
2208                         }
2209                 }
2210
2211                 BLI_unlock_thread(LOCK_IMAGE);
2212         }
2213
2214         tag_image_time(ima);
2215
2216         return ibuf;
2217 }
2218
2219 void BKE_image_release_ibuf(Image *ima, void *lock)
2220 {
2221         /* for getting image during threaded render / compositing, need to release */
2222         if(lock == ima) {
2223                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2224         }
2225         else if(lock) {
2226                 RE_ReleaseResultImage(lock); /* render result */
2227                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2228         }
2229 }
2230
2231 /* warning, this can allocate generated images */
2232 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2233 {
2234         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2235 }
2236
2237 void BKE_image_user_calc_frame(ImageUser *iuser, int cfra, int fieldnr)
2238 {
2239         int len;
2240         
2241         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2242         len= (iuser->fie_ima*iuser->frames)/2;
2243         
2244         if(len==0) {
2245                 iuser->framenr= 0;
2246         }
2247         else {
2248                 int imanr;
2249                 cfra= cfra - iuser->sfra+1;
2250
2251                 /* cyclic */
2252                 if(iuser->cycl) {
2253                         cfra= ( (cfra) % len );
2254                         if(cfra < 0) cfra+= len;
2255                         if(cfra==0) cfra= len;
2256                 }
2257                 
2258                 if(cfra<0) cfra= 0;
2259                 else if(cfra>len) cfra= len;
2260                 
2261                 /* convert current frame to current field */
2262                 cfra= 2*(cfra);
2263                 if(fieldnr) cfra++;
2264                 
2265                 /* transform to images space */
2266                 imanr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
2267                 if(imanr>iuser->frames) imanr= iuser->frames;
2268                 imanr+= iuser->offset;
2269                 
2270                 if(iuser->cycl) {
2271                         imanr= ( (imanr) % len );
2272                         while(imanr < 0) imanr+= len;
2273                         if(imanr==0) imanr= len;
2274                 }
2275         
2276                 /* allows image users to handle redraws */
2277                 if(iuser->flag & IMA_ANIM_ALWAYS)
2278                         if(imanr!=iuser->framenr)
2279                                 iuser->flag |= IMA_ANIM_REFRESHED;
2280                 
2281                 iuser->framenr= imanr;
2282                 if(iuser->ok==0) iuser->ok= 1;
2283         }
2284 }