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