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