77607ae25b6ad55fadad433368c6674cf54d2d26
[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         else if (imtype==R_RADHDR)
664                 return RADHDR;
665         else if (imtype==R_PNG)
666                 return PNG;
667 #ifdef WITH_DDS
668         else if (imtype==R_DDS)
669                 return DDS;
670 #endif
671         else if (imtype==R_BMP)
672                 return BMP;
673         else if (imtype==R_TIFF)
674                 return TIF;
675         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER)
676                 return OPENEXR;
677         else if (imtype==R_CINEON)
678                 return CINEON;
679         else if (imtype==R_DPX)
680                 return DPX;
681         else if (imtype==R_TARGA)
682                 return TGA;
683         else if(imtype==R_RAWTGA)
684                 return RAWTGA;
685 #ifdef WITH_OPENJPEG
686         else if(imtype==R_JP2)
687                 return JP2;
688 #endif
689         else
690                 return JPG|90;
691 }
692
693 int BKE_ftype_to_imtype(int ftype)
694 {
695         if(ftype==0)
696                 return TGA;
697         else if(ftype == IMAGIC) 
698                 return R_IRIS;
699         else if (ftype & RADHDR)
700                 return R_RADHDR;
701         else if (ftype & PNG)
702                 return R_PNG;
703 #ifdef WITH_DDS
704         else if (ftype & DDS)
705                 return R_DDS;
706 #endif
707         else if (ftype & BMP)
708                 return R_BMP;
709         else if (ftype & TIF)
710                 return R_TIFF;
711         else if (ftype & OPENEXR)
712                 return R_OPENEXR;
713         else if (ftype & CINEON)
714                 return R_CINEON;
715         else if (ftype & DPX)
716                 return R_DPX;
717         else if (ftype & TGA)
718                 return R_TARGA;
719         else if(ftype & RAWTGA)
720                 return R_RAWTGA;
721 #ifdef WITH_OPENJPEG
722         else if(ftype & JP2)
723                 return R_JP2;
724 #endif
725         else
726                 return R_JPEG90;
727 }
728
729
730 int BKE_imtype_is_movie(int imtype)
731 {
732         switch(imtype) {
733         case R_AVIRAW:
734         case R_AVIJPEG:
735         case R_AVICODEC:
736         case R_QUICKTIME:
737         case R_FFMPEG:
738         case R_H264:
739         case R_THEORA:
740         case R_XVID:
741         case R_FRAMESERVER:
742                         return 1;
743         }
744         return 0;
745 }
746
747 void BKE_add_image_extension(char *string, int imtype)
748 {
749         char *extension="";
750         
751         if(imtype== R_IRIS) {
752                 if(!BLI_testextensie(string, ".rgb"))
753                         extension= ".rgb";
754         }
755         else if(imtype==R_IRIZ) {
756                 if(!BLI_testextensie(string, ".rgb"))
757                         extension= ".rgb";
758         }
759         else if(imtype==R_RADHDR) {
760                 if(!BLI_testextensie(string, ".hdr"))
761                         extension= ".hdr";
762         }
763         else if (ELEM5(imtype, R_PNG, R_FFMPEG, R_H264, R_THEORA, R_XVID)) {
764                 if(!BLI_testextensie(string, ".png"))
765                         extension= ".png";
766         }
767 #ifdef WITH_DDS
768         else if(imtype==R_DDS) {
769                 if(!BLI_testextensie(string, ".dds"))
770                         extension= ".dds";
771         }
772 #endif
773         else if(imtype==R_RAWTGA) {
774                 if(!BLI_testextensie(string, ".tga"))
775                         extension= ".tga";
776         }
777         else if(imtype==R_BMP) {
778                 if(!BLI_testextensie(string, ".bmp"))
779                         extension= ".bmp";
780         }
781 #ifdef WITH_TIFF
782         else if(imtype==R_TIFF) {
783                 if(!BLI_testextensie(string, ".tif") && 
784                         !BLI_testextensie(string, ".tiff")) extension= ".tif";
785         }
786 #endif
787 #ifdef WITH_OPENEXR
788         else if( ELEM(imtype, R_OPENEXR, R_MULTILAYER)) {
789                 if(!BLI_testextensie(string, ".exr"))
790                         extension= ".exr";
791         }
792 #endif
793         else if(imtype==R_CINEON){
794                 if (!BLI_testextensie(string, ".cin"))
795                         extension= ".cin";
796         }
797         else if(imtype==R_DPX){
798                 if (!BLI_testextensie(string, ".dpx"))
799                         extension= ".dpx";
800         }
801         else if(imtype==R_TARGA) {
802                 if(!BLI_testextensie(string, ".tga"))
803                         extension= ".tga";
804         }
805 #ifdef WITH_OPENJPEG
806         else if(imtype==R_JP2) {
807                 if(!BLI_testextensie(string, ".jp2"))
808                         extension= ".jp2";
809         }
810 #endif
811         else { //   R_AVICODEC, R_AVIRAW, R_AVIJPEG, R_JPEG90, R_QUICKTIME etc
812                 if(!( BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
813                         extension= ".jpg";
814         }
815
816         strcat(string, extension);
817 }
818
819 /* could allow access externally - 512 is for long names, 64 is for id names */
820 typedef struct StampData {
821         char    file[512];
822         char    note[512];
823         char    date[512];
824         char    marker[512];
825         char    time[512];
826         char    frame[512];
827         char    camera[64];
828         char    scene[64];
829         char    strip[64];
830         char    rendertime[64];
831 } StampData;
832
833 static void stampdata(Scene *scene, StampData *stamp_data, int do_prefix)
834 {
835         char text[256];
836         struct tm *tl;
837         time_t t;
838
839         if (scene->r.stamp & R_STAMP_FILENAME) {
840                 if (G.relbase_valid) {
841                         if (do_prefix)          sprintf(stamp_data->file, "File %s", G.sce);
842                         else                            sprintf(stamp_data->file, "%s", G.sce);
843                 } else {
844                         if (do_prefix)          strcpy(stamp_data->file, "File <untitled>");
845                         else                            strcpy(stamp_data->file, "<untitled>");
846                 }
847         } else {
848                 stamp_data->file[0] = '\0';
849         }
850         
851         if (scene->r.stamp & R_STAMP_NOTE) {
852                 /* Never do prefix for Note */
853                 sprintf(stamp_data->note, "%s", scene->r.stamp_udata);
854         } else {
855                 stamp_data->note[0] = '\0';
856         }
857         
858         if (scene->r.stamp & R_STAMP_DATE) {
859
860                 t = time (NULL);
861                 tl = localtime (&t);
862                 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);
863
864                 if (do_prefix)          sprintf(stamp_data->date, "Date %s", text);
865                 else                            sprintf(stamp_data->date, "%s", text);
866         } else {
867                 stamp_data->date[0] = '\0';
868         }
869         
870         if (scene->r.stamp & R_STAMP_MARKER) {
871                 char *name = scene_find_last_marker_name(scene, CFRA);
872         
873                 if (name)       strcpy(text, name);
874                 else            strcpy(text, "<none>");
875                 
876                 if (do_prefix)          sprintf(stamp_data->marker, "Marker %s", text);
877                 else                            sprintf(stamp_data->marker, "%s", text);
878         } else {
879                 stamp_data->marker[0] = '\0';
880         }
881         
882         if (scene->r.stamp & R_STAMP_TIME) {
883                 int h, m, s, f;
884                 h= m= s= f= 0;
885                 f = (int)(scene->r.cfra % scene->r.frs_sec);
886                 s = (int)(scene->r.cfra / scene->r.frs_sec);
887
888                 if (s) {
889                         m = (int)(s / 60);
890                         s %= 60;
891
892                         if (m) {
893                                 h = (int)(m / 60);
894                                 m %= 60;
895                         }
896                 }
897
898                 if (scene->r.frs_sec < 100)
899                         sprintf (text, "%02d:%02d:%02d.%02d", h, m, s, f);
900                 else
901                         sprintf (text, "%02d:%02d:%02d.%03d", h, m, s, f);
902                 
903                 if (do_prefix)          sprintf(stamp_data->time, "Time %s", text);
904                 else                            sprintf(stamp_data->time, "%s", text);
905         } else {
906                 stamp_data->time[0] = '\0';
907         }
908         
909         if (scene->r.stamp & R_STAMP_FRAME) {
910                 char format[32];
911                 if (do_prefix)          sprintf(format, "Frame %%0%di", 1 + (int) log10(scene->r.efra));
912                 else                            sprintf(format, "%%0%di", 1 + (int) log10(scene->r.efra));
913                 sprintf (stamp_data->frame, format, scene->r.cfra);
914         } else {
915                 stamp_data->frame[0] = '\0';
916         }
917
918         if (scene->r.stamp & R_STAMP_CAMERA) {
919                 if (scene->camera) strcpy(text, ((Camera *) scene->camera)->id.name+2);
920                 else            strcpy(text, "<none>");
921                 
922                 if (do_prefix)          sprintf(stamp_data->camera, "Camera %s", text);
923                 else                            sprintf(stamp_data->camera, "%s", text);
924         } else {
925                 stamp_data->camera[0] = '\0';
926         }
927
928         if (scene->r.stamp & R_STAMP_SCENE) {
929                 if (do_prefix)          sprintf(stamp_data->scene, "Scene %s", scene->id.name+2);
930                 else                            sprintf(stamp_data->scene, "%s", scene->id.name+2);
931         } else {
932                 stamp_data->scene[0] = '\0';
933         }
934         
935         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
936                 Sequence *seq= NULL; //XXX = get_foreground_frame_seq(scene->r.cfra);
937         
938                 if (seq) strcpy(text, seq->name+2);
939                 else            strcpy(text, "<none>");
940                 
941                 if (do_prefix)          sprintf(stamp_data->strip, "Strip %s", text);
942                 else                            sprintf(stamp_data->strip, "%s", text);
943         } else {
944                 stamp_data->strip[0] = '\0';
945         }
946
947         {
948                 Render *re= RE_GetRender(scene->id.name);
949                 RenderStats *stats= re ? RE_GetStats(re):NULL;
950
951                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
952                         BLI_timestr(stats->lastframetime, text);
953
954                         if (do_prefix)          sprintf(stamp_data->rendertime, "RenderTime %s", text);
955                         else                            sprintf(stamp_data->rendertime, "%s", text);
956                 } else {
957                         stamp_data->rendertime[0] = '\0';
958                 }
959         }
960 }
961
962 // XXX - Bad level call.
963 extern int datatoc_bmonofont_ttf_size;
964 extern char datatoc_bmonofont_ttf[];
965
966 // XXX - copied from text_font_begin ! Change all the BLF_* here
967 static int mono= -1;
968
969 int stamp_font_begin(int size)
970 {
971         if (mono == -1)
972                 mono= BLF_load_mem_unique("monospace", (unsigned char *)datatoc_bmonofont_ttf, datatoc_bmonofont_ttf_size);
973
974         BLF_aspect(mono, 1.0);
975         BLF_size(mono, size, 72);
976         return(mono); // XXX This is for image_gen.c!!
977 }
978
979 void BKE_stamp_buf(Scene *scene, unsigned char *rect, float *rectf, int width, int height, int channels)
980 {
981         struct StampData stamp_data;
982         float w, h, pad;
983         int x, y;
984         float h_fixed;
985         
986         if (!rect && !rectf)
987                 return;
988         
989         stampdata(scene, &stamp_data, 1);
990
991         /* TODO, do_versions */
992         if(scene->r.stamp_font_id < 8)
993                 scene->r.stamp_font_id= 12;
994
995         stamp_font_begin(scene->r.stamp_font_id);
996
997         BLF_buffer(mono, rectf, rect, width, height, channels);
998         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
999         pad= BLF_width(mono, "--");
1000
1001         /* use 'h_fixed' rather then 'h', aligns better */
1002         // BLF_width_and_height(mono, "^|/_AgPpJjlYy", &w, &h_fixed);
1003         {
1004                 rctf box;
1005                 BLF_boundbox(mono, "^|/_AgPpJjlYy", &box);
1006                 h_fixed= box.ymax - box.ymin;
1007         }
1008
1009         x= 0;
1010         y= height;
1011
1012         if (stamp_data.file[0]) {
1013                 /* Top left corner */
1014                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h= h_fixed;
1015                 y -= h;
1016
1017                 /* also a little of space to the background. */
1018                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y-3, w+3, y+h+2);
1019
1020                 /* and draw the text. */
1021                 BLF_position(mono, x, y, 0.0);
1022                 BLF_draw_buffer(mono, stamp_data.file);
1023
1024                 /* the extra pixel for background. */
1025                 y -= 4;
1026         }
1027
1028         /* Top left corner, below File */
1029         if (stamp_data.note[0]) {
1030                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h= h_fixed;
1031                 y -= h;
1032
1033                 /* and space for background. */
1034                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-3, w+3, y+h+2);
1035
1036                 BLF_position(mono, x, y+1, 0.0);
1037                 BLF_draw_buffer(mono, stamp_data.note);
1038
1039                 /* the extra pixel for background. */
1040                 y -= 4;
1041         }
1042         
1043         /* Top left corner, below File (or Note) */
1044         if (stamp_data.date[0]) {
1045                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h= h_fixed;
1046                 y -= h;
1047
1048                 /* and space for background. */
1049                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-3, w+3, y+h+2);
1050
1051                 BLF_position(mono, x, y, 0.0);
1052                 BLF_draw_buffer(mono, stamp_data.date);
1053
1054                 /* the extra pixel for background. */
1055                 y -= 4;
1056         }
1057
1058         /* Top left corner, below File, Date or Note */
1059         if (stamp_data.rendertime[0]) {
1060                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h= h_fixed;
1061                 y -= h;
1062
1063                 /* and space for background. */
1064                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y-3, w+3, y+h+2);
1065
1066                 BLF_position(mono, x, y, 0.0);
1067                 BLF_draw_buffer(mono, stamp_data.rendertime);
1068         }
1069
1070         x= 0;
1071         y= 0;
1072
1073         /* Bottom left corner, leaving space for timing */
1074         if (stamp_data.marker[0]) {
1075                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h= h_fixed;
1076
1077                 /* extra space for background. */
1078                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, w+2, y+h+2);
1079
1080                 /* and pad the text. */
1081                 BLF_position(mono, x, y+3, 0.0);
1082                 BLF_draw_buffer(mono, stamp_data.marker);
1083
1084                 /* space width. */
1085                 x += w + pad;
1086         }
1087         
1088         /* Left bottom corner */
1089         if (stamp_data.time[0]) {
1090                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h= h_fixed;
1091
1092                 /* extra space for background */
1093                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+2);
1094
1095                 /* and pad the text. */
1096                 BLF_position(mono, x, y+3, 0.0);
1097                 BLF_draw_buffer(mono, stamp_data.time);
1098
1099                 /* space width. */
1100                 x += w + pad;
1101         }
1102         
1103         if (stamp_data.frame[0]) {
1104                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h= h_fixed;
1105
1106                 /* extra space for background. */
1107                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+2);
1108
1109                 /* and pad the text. */
1110                 BLF_position(mono, x, y+3, 0.0);
1111                 BLF_draw_buffer(mono, stamp_data.frame);
1112
1113                 /* space width. */
1114                 x += w + pad;
1115         }
1116
1117         if (stamp_data.camera[0]) {
1118                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h= h_fixed;
1119
1120                 /* extra space for background. */
1121                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+2, y+h+2);
1122                 BLF_position(mono, x, y+3, 0.0);
1123                 BLF_draw_buffer(mono, stamp_data.camera);
1124         }
1125         
1126         if (stamp_data.scene[0]) {
1127                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h= h_fixed;
1128
1129                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1130                 x= width - w - 2;
1131
1132                 /* extra space for background. */
1133                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y, x+w+3, y+h+2);
1134
1135                 /* and pad the text. */
1136                 BLF_position(mono, x, y+3, 0.0);
1137                 BLF_draw_buffer(mono, stamp_data.scene);
1138         }
1139         
1140         if (stamp_data.strip[0]) {
1141                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h= h_fixed;
1142
1143                 /* Top right corner, with an extra space because blenfont is too strict! */
1144                 x= width - w - pad;
1145                 y= height - h;
1146
1147                 /* extra space for background. */
1148                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x, y-3, x+w+pad, y+h+2);
1149
1150                 BLF_position(mono, x, y, 0.0);
1151                 BLF_draw_buffer(mono, stamp_data.strip);
1152         }
1153
1154         /* cleanup the buffer. */
1155         BLF_buffer(mono, NULL, NULL, 0, 0, 0);
1156 }
1157
1158 void BKE_stamp_info(Scene *scene, struct ImBuf *ibuf)
1159 {
1160         struct StampData stamp_data;
1161
1162         if (!ibuf)      return;
1163         
1164         /* fill all the data values, no prefix */
1165         stampdata(scene, &stamp_data, 0);
1166         
1167         if (stamp_data.file[0])         IMB_metadata_change_field (ibuf, "File",                stamp_data.file);
1168         if (stamp_data.note[0])         IMB_metadata_change_field (ibuf, "Note",                stamp_data.note);
1169         if (stamp_data.date[0])         IMB_metadata_change_field (ibuf, "Date",                stamp_data.date);
1170         if (stamp_data.marker[0])       IMB_metadata_change_field (ibuf, "Marker",      stamp_data.marker);
1171         if (stamp_data.time[0])         IMB_metadata_change_field (ibuf, "Time",                stamp_data.time);
1172         if (stamp_data.frame[0])        IMB_metadata_change_field (ibuf, "Frame",       stamp_data.frame);
1173         if (stamp_data.camera[0])       IMB_metadata_change_field (ibuf, "Camera",      stamp_data.camera);
1174         if (stamp_data.scene[0])        IMB_metadata_change_field (ibuf, "Scene",       stamp_data.scene);
1175         if (stamp_data.strip[0])        IMB_metadata_change_field (ibuf, "Strip",       stamp_data.strip);
1176         if (stamp_data.rendertime[0]) IMB_metadata_change_field (ibuf, "RenderTime", stamp_data.rendertime);
1177 }
1178
1179 int BKE_write_ibuf(Scene *scene, ImBuf *ibuf, char *name, int imtype, int subimtype, int quality)
1180 {
1181         int ok;
1182         
1183         if(imtype==0);
1184         else if(imtype== R_IRIS) 
1185                 ibuf->ftype= IMAGIC;
1186         else if ((imtype==R_RADHDR)) {
1187                 ibuf->ftype= RADHDR;
1188         }
1189         else if (ELEM5(imtype, R_PNG, R_FFMPEG, R_H264, R_THEORA, R_XVID)) {
1190                 ibuf->ftype= PNG;
1191
1192                 if(imtype==R_PNG)
1193                         ibuf->ftype |= quality;  /* quality is actually compression 0-100 --> 0-9 */
1194
1195         }
1196 #ifdef WITH_DDS
1197         else if ((imtype==R_DDS)) {
1198                 ibuf->ftype= DDS;
1199         }
1200 #endif
1201         else if ((imtype==R_BMP)) {
1202                 ibuf->ftype= BMP;
1203         }
1204 #ifdef WITH_TIFF
1205         else if (imtype==R_TIFF) {
1206                 ibuf->ftype= TIF;
1207
1208                 if(subimtype & R_TIFF_16BIT)
1209                         ibuf->ftype |= TIF_16BIT;
1210         }
1211 #endif
1212 #ifdef WITH_OPENEXR
1213         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
1214                 ibuf->ftype= OPENEXR;
1215                 if(subimtype & R_OPENEXR_HALF)
1216                         ibuf->ftype |= OPENEXR_HALF;
1217                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
1218                 
1219                 if(!(subimtype & R_OPENEXR_ZBUF))
1220                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1221                 
1222         }
1223 #endif
1224         else if (imtype==R_CINEON) {
1225                 ibuf->ftype = CINEON;
1226         }
1227         else if (imtype==R_DPX) {
1228                 ibuf->ftype = DPX;
1229         }
1230         else if (imtype==R_TARGA) {
1231                 ibuf->ftype= TGA;
1232         }
1233         else if(imtype==R_RAWTGA) {
1234                 ibuf->ftype= RAWTGA;
1235         }
1236 #ifdef WITH_OPENJPEG
1237         else if(imtype==R_JP2) {
1238                 if(quality < 10) quality= 90;
1239                 ibuf->ftype= JP2|quality;
1240                 
1241                 if (subimtype & R_JPEG2K_16BIT) {
1242                         ibuf->ftype |= JP2_16BIT;
1243                 } else if (subimtype & R_JPEG2K_12BIT) {
1244                         ibuf->ftype |= JP2_12BIT;
1245                 }
1246                 
1247                 if (subimtype & R_JPEG2K_YCC) {
1248                         ibuf->ftype |= JP2_YCC;
1249                 }
1250                 
1251                 if (subimtype & R_JPEG2K_CINE_PRESET) {
1252                         ibuf->ftype |= JP2_CINE;
1253                         if (subimtype & R_JPEG2K_CINE_48FPS)
1254                                 ibuf->ftype |= JP2_CINE_48FPS;
1255                 }
1256         }
1257 #endif
1258         else {
1259                 /* R_JPEG90, etc. default we save jpegs */
1260                 if(quality < 10) quality= 90;
1261                 ibuf->ftype= JPG|quality;
1262                 if(ibuf->depth==32) ibuf->depth= 24;    /* unsupported feature only confuses other s/w */
1263         }
1264         
1265         BLI_make_existing_file(name);
1266
1267         if(scene && scene->r.stamp & R_STAMP_ALL)
1268                 BKE_stamp_info(scene, ibuf);
1269         
1270         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1271         if (ok == 0) {
1272                 perror(name);
1273         }
1274         
1275         return(ok);
1276 }
1277
1278
1279 void BKE_makepicstring(char *string, char *base, int frame, int imtype, int use_ext)
1280 {
1281         if (string==NULL) return;
1282         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1283         BLI_path_abs(string, G.sce);
1284         BLI_path_frame(string, frame, 4);
1285
1286         if(use_ext)
1287                 BKE_add_image_extension(string, imtype);
1288                 
1289 }
1290
1291 /* used by sequencer too */
1292 struct anim *openanim(char *name, int flags)
1293 {
1294         struct anim *anim;
1295         struct ImBuf *ibuf;
1296         
1297         anim = IMB_open_anim(name, flags);
1298         if (anim == NULL) return(0);
1299
1300         ibuf = IMB_anim_absolute(anim, 0);
1301         if (ibuf == NULL) {
1302                 if(BLI_exists(name))
1303                         printf("not an anim: %s\n", name);
1304                 else
1305                         printf("anim file doesn't exist: %s\n", name);
1306                 IMB_free_anim(anim);
1307                 return(0);
1308         }
1309         IMB_freeImBuf(ibuf);
1310         
1311         return(anim);
1312 }
1313
1314 /* ************************* New Image API *************** */
1315
1316
1317 /* Notes about Image storage 
1318 - packedfile
1319   -> written in .blend
1320 - filename
1321   -> written in .blend
1322 - movie
1323   -> comes from packedfile or filename
1324 - renderresult
1325   -> comes from packedfile or filename
1326 - listbase
1327   -> ibufs from exrhandle
1328 - flipbook array
1329   -> ibufs come from movie, temporary renderresult or sequence
1330 - ibuf
1331   -> comes from packedfile or filename or generated
1332
1333 */
1334
1335
1336 /* forces existence of 1 Image for renderout or nodes, returns Image */
1337 /* name is only for default, when making new one */
1338 Image *BKE_image_verify_viewer(int type, const char *name)
1339 {
1340         Image *ima;
1341         
1342         for(ima=G.main->image.first; ima; ima= ima->id.next)
1343                 if(ima->source==IMA_SRC_VIEWER)
1344                         if(ima->type==type)
1345                                 break;
1346         
1347         if(ima==NULL)
1348                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1349         
1350         /* happens on reload, imagewindow cannot be image user when hidden*/
1351         if(ima->id.us==0)
1352                 id_us_plus(&ima->id);
1353
1354         return ima;
1355 }
1356
1357 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1358 {
1359         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1360 }
1361
1362 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1363 {
1364         if(ima==NULL)
1365                 return;
1366         
1367         switch(signal) {
1368         case IMA_SIGNAL_FREE:
1369                 image_free_buffers(ima);
1370                 if(iuser)
1371                         iuser->ok= 1;
1372                 break;
1373         case IMA_SIGNAL_SRC_CHANGE:
1374                 if(ima->type == IMA_TYPE_UV_TEST)
1375                         if(ima->source != IMA_SRC_GENERATED)
1376                                 ima->type= IMA_TYPE_IMAGE;
1377
1378                 if(ima->source==IMA_SRC_GENERATED) {
1379                         if(ima->gen_x==0 || ima->gen_y==0) {
1380                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1381                                 if(ibuf) {
1382                                         ima->gen_x= ibuf->x;
1383                                         ima->gen_y= ibuf->y;
1384                                 }
1385                         }
1386                 }
1387
1388                 image_free_buffers(ima);
1389
1390                 ima->ok= 1;
1391                 if(iuser)
1392                         iuser->ok= 1;
1393                 break;
1394                         
1395         case IMA_SIGNAL_RELOAD:
1396                 /* try to repack file */
1397                 if(ima->packedfile) {
1398                         PackedFile *pf;
1399                         pf = newPackedFile(NULL, ima->name);
1400                         if (pf) {
1401                                 freePackedFile(ima->packedfile);
1402                                 ima->packedfile = pf;
1403                                 image_free_buffers(ima);
1404                         } else {
1405                                 printf("ERROR: Image not available. Keeping packed image\n");
1406                         }
1407                 }
1408                 else
1409                         image_free_buffers(ima);
1410                 
1411                 if(iuser)
1412                         iuser->ok= 1;
1413                 
1414                 break;
1415         case IMA_SIGNAL_USER_NEW_IMAGE:
1416                 if(iuser) {
1417                         iuser->ok= 1;
1418                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1419                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1420                                         iuser->multi_index= 0;
1421                                         iuser->layer= iuser->pass= 0;
1422                                 }
1423                         }
1424                 }
1425                 break;
1426         }
1427 }
1428
1429 /* if layer or pass changes, we need an index for the imbufs list */
1430 /* note it is called for rendered results, but it doesnt use the index! */
1431 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1432 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1433 {
1434         RenderLayer *rl;
1435         RenderPass *rpass= NULL;
1436         
1437         if(rr==NULL) 
1438                 return NULL;
1439         
1440         if(iuser) {
1441                 short index= 0, rl_index= 0, rp_index;
1442                 
1443                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1444                         rp_index= 0;
1445                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1446                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1447                                         break;
1448                         if(rpass)
1449                                 break;
1450                 }
1451                 
1452                 if(rpass)
1453                         iuser->multi_index= index;
1454                 else 
1455                         iuser->multi_index= 0;
1456         }
1457         if(rpass==NULL) {
1458                 rl= rr->layers.first;
1459                 if(rl)
1460                         rpass= rl->passes.first;
1461         }
1462         
1463         return rpass;
1464 }
1465
1466 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
1467 {
1468         if(ima->rr) {
1469                 return ima->rr;
1470         }
1471         else if(ima->type==IMA_TYPE_R_RESULT) {
1472                 if(ima->render_slot == ima->last_render_slot)
1473                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
1474                 else
1475                         return ima->renders[ima->render_slot];
1476         }
1477         else
1478                 return NULL;
1479 }
1480
1481 void BKE_image_release_renderresult(Scene *scene, Image *ima)
1482 {
1483         if(ima->rr);
1484         else if(ima->type==IMA_TYPE_R_RESULT) {
1485                 if(ima->render_slot == ima->last_render_slot)
1486                         RE_ReleaseResult(RE_GetRender(scene->id.name));
1487         }
1488 }
1489
1490 void BKE_image_backup_render(Scene *scene, Image *ima)
1491 {
1492         /* called right before rendering, ima->renders contains render
1493            result pointers for everything but the current render */
1494         Render *re= RE_GetRender(scene->id.name);
1495         int slot= ima->render_slot, last= ima->last_render_slot;
1496
1497         if(slot != last) {
1498                 if(ima->renders[slot]) {
1499                         RE_FreeRenderResult(ima->renders[slot]);
1500                         ima->renders[slot]= NULL;
1501                 }
1502
1503                 ima->renders[last]= NULL;
1504                 RE_SwapResult(re, &ima->renders[last]);
1505         }
1506
1507         ima->last_render_slot= slot;
1508 }
1509
1510 /* after imbuf load, openexr type can return with a exrhandle open */
1511 /* in that case we have to build a render-result */
1512 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1513 {
1514         
1515         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1516
1517 #ifdef WITH_OPENEXR
1518         IMB_exr_close(ibuf->userdata);
1519 #endif
1520
1521         ibuf->userdata= NULL;
1522         if(ima->rr)
1523                 ima->rr->framenr= framenr;
1524 }
1525
1526 /* common stuff to do with images after loading */
1527 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1528 {
1529         
1530         
1531         /* preview is NULL when it has never been used as an icon before */
1532         if(G.background==0 && ima->preview==NULL)
1533                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1534         
1535         /* stringcodes also in ibuf, ibuf->name is used to retrieve original (buttons) */
1536         BLI_strncpy(ibuf->name, ima->name, FILE_MAX);
1537         
1538         /* fields */
1539         if (ima->flag & IMA_FIELDS) {
1540                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1541                 else de_interlace_ng(ibuf);
1542         }
1543         /* timer */
1544         ima->lastused = clock() / CLOCKS_PER_SEC;
1545         
1546         ima->ok= IMA_OK_LOADED;
1547         
1548 }
1549
1550 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1551 {
1552         struct ImBuf *ibuf;
1553         unsigned short numlen;
1554         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1555         int flag;
1556         
1557         /* XXX temp stuff? */
1558         if(ima->lastframe != frame)
1559                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1560
1561         ima->lastframe= frame;
1562
1563         BLI_stringdec(ima->name, head, tail, &numlen);
1564         BLI_stringenc(ima->name, head, tail, numlen, frame);
1565         BLI_strncpy(name, ima->name, sizeof(name));
1566         
1567         if(ima->id.lib)
1568                 BLI_path_abs(name, ima->id.lib->filepath);
1569         else
1570                 BLI_path_abs(name, G.sce);
1571         
1572         flag= IB_rect|IB_multilayer;
1573         if(ima->flag & IMA_DO_PREMUL)
1574                 flag |= IB_premul;
1575
1576         /* read ibuf */
1577         ibuf = IMB_loadiffname(name, flag);
1578         if(G.f & G_DEBUG) printf("loaded %s\n", name);
1579         
1580         if (ibuf) {
1581 #ifdef WITH_OPENEXR
1582                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1583                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1584                         image_create_multilayer(ima, ibuf, frame);      
1585                         ima->type= IMA_TYPE_MULTILAYER;
1586                         IMB_freeImBuf(ibuf);
1587                         ibuf= NULL;
1588                 }
1589                 else {
1590                         image_initialize_after_load(ima, ibuf);
1591                         image_assign_ibuf(ima, ibuf, 0, frame);
1592                 }
1593 #else
1594                 image_initialize_after_load(ima, ibuf);
1595                 image_assign_ibuf(ima, ibuf, 0, frame);
1596 #endif
1597         }
1598         else
1599                 ima->ok= 0;
1600         
1601         if(iuser)
1602                 iuser->ok= ima->ok;
1603         
1604         return ibuf;
1605 }
1606
1607 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1608 {
1609         struct ImBuf *ibuf= NULL;
1610         
1611         /* either we load from RenderResult, or we have to load a new one */
1612         
1613         /* check for new RenderResult */
1614         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1615                 /* copy to survive not found multilayer image */
1616                 RenderResult *oldrr= ima->rr;
1617         
1618                 ima->rr= NULL;
1619                 ibuf = image_load_sequence_file(ima, iuser, frame);
1620                 
1621                 if(ibuf) { /* actually an error */
1622                         ima->type= IMA_TYPE_IMAGE;
1623                         printf("error, multi is normal image\n");
1624                 }
1625                 // printf("loaded new result %p\n", ima->rr);
1626                 /* free result if new one found */
1627                 if(ima->rr) {
1628                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1629                         if(oldrr) RE_FreeRenderResult(oldrr);
1630                 }
1631                 else {
1632                         ima->rr= oldrr;
1633                 }
1634
1635         }
1636         if(ima->rr) {
1637                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1638                 
1639                 if(rpass) {
1640                         // printf("load from pass %s\n", rpass->name);
1641                         /* since we free  render results, we copy the rect */
1642                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1643                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1644                         ibuf->flags |= IB_rectfloat;
1645                         ibuf->mall= IB_rectfloat;
1646                         ibuf->channels= rpass->channels;
1647                         
1648                         image_initialize_after_load(ima, ibuf);
1649                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
1650                         
1651                 }
1652                 // else printf("pass not found\n");
1653         }
1654         else
1655                 ima->ok= 0;
1656         
1657         if(iuser)
1658                 iuser->ok= ima->ok;
1659         
1660         return ibuf;
1661 }
1662
1663
1664 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
1665 {
1666         struct ImBuf *ibuf= NULL;
1667         
1668         ima->lastframe= frame;
1669         
1670         if(ima->anim==NULL) {
1671                 char str[FILE_MAX];
1672                 
1673                 BLI_strncpy(str, ima->name, FILE_MAX);
1674                 if(ima->id.lib)
1675                         BLI_path_abs(str, ima->id.lib->filepath);
1676                 else
1677                         BLI_path_abs(str, G.sce);
1678                 
1679                 ima->anim = openanim(str, IB_rect);
1680                 
1681                 /* let's initialize this user */
1682                 if(ima->anim && iuser && iuser->frames==0)
1683                         iuser->frames= IMB_anim_get_duration(ima->anim);
1684         }
1685         
1686         if(ima->anim) {
1687                 int dur = IMB_anim_get_duration(ima->anim);
1688                 int fra= frame-1;
1689                 
1690                 if(fra<0) fra = 0;
1691                 if(fra>(dur-1)) fra= dur-1;
1692                 ibuf = IMB_anim_absolute(ima->anim, fra);
1693                 
1694                 if(ibuf) {
1695                         image_initialize_after_load(ima, ibuf);
1696                         image_assign_ibuf(ima, ibuf, 0, frame);
1697                 }
1698                 else
1699                         ima->ok= 0;
1700         }
1701         else
1702                 ima->ok= 0;
1703         
1704         if(iuser)
1705                 iuser->ok= ima->ok;
1706         
1707         return ibuf;
1708 }
1709
1710 /* cfra used for # code, Image can only have this # for all its users
1711  * warning, 'iuser' can be NULL */
1712 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
1713 {
1714         struct ImBuf *ibuf;
1715         char str[FILE_MAX];
1716         int assign = 0, flag;
1717         
1718         /* always ensure clean ima */
1719         image_free_buffers(ima);
1720         
1721         /* is there a PackedFile with this image ? */
1722         if (ima->packedfile) {
1723                 flag = IB_rect|IB_multilayer;
1724                 if(ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
1725                 
1726                 ibuf = IMB_ibImageFromMemory((unsigned char*)ima->packedfile->data, ima->packedfile->size, flag);
1727         } 
1728         else {
1729                 flag= IB_rect|IB_multilayer|IB_metadata;
1730                 if(ima->flag & IMA_DO_PREMUL)
1731                         flag |= IB_premul;
1732                         
1733                 /* get the right string */
1734                 BLI_strncpy(str, ima->name, sizeof(str));
1735                 if(ima->id.lib)
1736                         BLI_path_abs(str, ima->id.lib->filepath);
1737                 else
1738                         BLI_path_abs(str, G.sce);
1739                 
1740                 BLI_path_frame(str, cfra, 0);
1741                 
1742                 /* read ibuf */
1743                 ibuf = IMB_loadiffname(str, flag);
1744         }
1745         
1746         if (ibuf) {
1747                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1748                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1749                         image_create_multilayer(ima, ibuf, cfra);       
1750                         ima->type= IMA_TYPE_MULTILAYER;
1751                         IMB_freeImBuf(ibuf);
1752                         ibuf= NULL;
1753                 }
1754                 else {
1755                         image_initialize_after_load(ima, ibuf);
1756                         assign= 1;
1757
1758                         /* check if the image is a font image... */
1759                         detectBitmapFont(ibuf);
1760                         
1761                         /* make packed file for autopack */
1762                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
1763                                 ima->packedfile = newPackedFile(NULL, str);
1764                 }
1765         }
1766         else
1767                 ima->ok= 0;
1768         
1769         if(assign)
1770                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1771
1772         if(iuser)
1773                 iuser->ok= ima->ok;
1774         
1775         return ibuf;
1776 }
1777
1778 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
1779 {
1780         ImBuf *ibuf= NULL;
1781         
1782         if(ima->rr==NULL) {
1783                 ibuf = image_load_image_file(ima, iuser, 0);
1784                 if(ibuf) { /* actually an error */
1785                         ima->type= IMA_TYPE_IMAGE;
1786                         return ibuf;
1787                 }
1788         }
1789         if(ima->rr) {
1790                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1791
1792                 if(rpass) {
1793                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1794                         
1795                         image_initialize_after_load(ima, ibuf);
1796                         
1797                         ibuf->rect_float= rpass->rect;
1798                         ibuf->flags |= IB_rectfloat;
1799                         ibuf->channels= rpass->channels;
1800                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1801
1802                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1803                 }
1804         }
1805         
1806         if(ibuf==NULL) 
1807                 ima->ok= 0;
1808         if(iuser)
1809                 iuser->ok= ima->ok;
1810         
1811         return ibuf;
1812 }
1813
1814
1815 /* showing RGBA result itself (from compo/sequence) or
1816    like exr, using layers etc */
1817 /* always returns a single ibuf, also during render progress */
1818 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
1819 {
1820         Render *re;
1821         RenderResult rres;
1822         float *rectf, *rectz;
1823         unsigned int *rect;
1824         float dither;
1825         int channels, layer, pass;
1826         ImBuf *ibuf;
1827         int from_render= (ima->render_slot == ima->last_render_slot);
1828
1829         if(!(iuser && iuser->scene))
1830                 return NULL;
1831
1832         /* if we the caller is not going to release the lock, don't give the image */
1833         if(!lock_r)
1834                 return NULL;
1835
1836         re= RE_GetRender(iuser->scene->id.name);
1837
1838         channels= 4;
1839         layer= (iuser)? iuser->layer: 0;
1840         pass= (iuser)? iuser->pass: 0;
1841
1842         if(from_render) {
1843                 RE_AcquireResultImage(re, &rres);
1844         }
1845         else if(ima->renders[ima->render_slot]) {
1846                 rres= *(ima->renders[ima->render_slot]);
1847                 rres.have_combined= rres.rectf != NULL;
1848         }
1849         else
1850                 memset(&rres, 0, sizeof(RenderResult));
1851         
1852         if(!(rres.rectx > 0 && rres.recty > 0)) {
1853                 if(from_render)
1854                         RE_ReleaseResultImage(re);
1855                 return NULL;
1856         }
1857
1858         /* release is done in BKE_image_release_ibuf using lock_r */
1859         if(from_render) {
1860                 BLI_lock_thread(LOCK_VIEWER);
1861                 *lock_r= re;
1862         }
1863
1864         /* this gives active layer, composite or seqence result */
1865         rect= (unsigned int *)rres.rect32;
1866         rectf= rres.rectf;
1867         rectz= rres.rectz;
1868         dither= iuser->scene->r.dither_intensity;
1869
1870         /* combined layer gets added as first layer */
1871         if(rres.have_combined && layer==0);
1872         else if(rres.layers.first) {
1873                 RenderLayer *rl= BLI_findlink(&rres.layers, layer-(rres.have_combined?1:0));
1874                 if(rl) {
1875                         RenderPass *rpass;
1876
1877                         /* there's no combined pass, is in renderlayer itself */
1878                         if(pass==0) {
1879                                 rectf= rl->rectf;
1880                         }
1881                         else {
1882                                 rpass= BLI_findlink(&rl->passes, pass-1);
1883                                 if(rpass) {
1884                                         channels= rpass->channels;
1885                                         rectf= rpass->rect;
1886                                         dither= 0.0f; /* don't dither passes */
1887                                 }
1888                         }
1889
1890                         for(rpass= rl->passes.first; rpass; rpass= rpass->next)
1891                                 if(rpass->passtype == SCE_PASS_Z)
1892                                         rectz= rpass->rect;
1893                 }
1894         }
1895
1896         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1897
1898         /* make ibuf if needed, and initialize it */
1899         if(ibuf==NULL) {
1900                 ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, 0, 0);
1901                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1902         }
1903
1904         ibuf->x= rres.rectx;
1905         ibuf->y= rres.recty;
1906         
1907         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
1908                 imb_freerectImBuf(ibuf);
1909
1910         if(rect)
1911                 ibuf->rect= rect;
1912         
1913         if(rectf) {
1914                 ibuf->rect_float= rectf;
1915                 ibuf->flags |= IB_rectfloat;
1916                 ibuf->channels= channels;
1917         }
1918         else {
1919                 ibuf->rect_float= NULL;
1920                 ibuf->flags &= ~IB_rectfloat;
1921         }
1922
1923         if(rectz) {
1924                 ibuf->zbuf_float= rectz;
1925                 ibuf->flags |= IB_zbuffloat;
1926         }
1927         else {
1928                 ibuf->zbuf_float= NULL;
1929                 ibuf->flags &= ~IB_zbuffloat;
1930         }
1931
1932         ibuf->dither= dither;
1933
1934         ima->ok= IMA_OK_LOADED;
1935
1936         return ibuf;
1937 }
1938
1939 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
1940 {
1941         ImBuf *ibuf = NULL;
1942         int frame = 0, index = 0;
1943
1944         /* see if we already have an appropriate ibuf, with image source and type */
1945         if(ima->source==IMA_SRC_MOVIE) {
1946                 frame= iuser?iuser->framenr:ima->lastframe;
1947                 ibuf= image_get_ibuf(ima, 0, frame);
1948                 /* XXX temp stuff? */
1949                 if(ima->lastframe != frame)
1950                         ima->tpageflag |= IMA_TPAGE_REFRESH;
1951                 ima->lastframe = frame;
1952         }
1953         else if(ima->source==IMA_SRC_SEQUENCE) {
1954                 if(ima->type==IMA_TYPE_IMAGE) {
1955                         frame= iuser?iuser->framenr:ima->lastframe;
1956                         ibuf= image_get_ibuf(ima, 0, frame);
1957                         
1958                         /* XXX temp stuff? */
1959                         if(ima->lastframe != frame)
1960                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1961                         ima->lastframe = frame;
1962                 }       
1963                 else if(ima->type==IMA_TYPE_MULTILAYER) {
1964                         frame= iuser?iuser->framenr:ima->lastframe;
1965                         index= iuser?iuser->multi_index:IMA_NO_INDEX;
1966                         ibuf= image_get_ibuf(ima, index, frame);
1967                 }
1968         }
1969         else if(ima->source==IMA_SRC_FILE) {
1970                 if(ima->type==IMA_TYPE_IMAGE)
1971                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1972                 else if(ima->type==IMA_TYPE_MULTILAYER)
1973                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1974         }
1975         else if(ima->source == IMA_SRC_GENERATED) {
1976                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1977         }
1978         else if(ima->source == IMA_SRC_VIEWER) {
1979                 if(ima->type==IMA_TYPE_R_RESULT) {
1980                         /* always verify entirely, not that this shouldn't happen
1981                          * during render anyway */
1982                 }
1983                 else if(ima->type==IMA_TYPE_COMPOSITE) {
1984                         frame= iuser?iuser->framenr:0;
1985                         ibuf= image_get_ibuf(ima, 0, frame);
1986                 }
1987         }
1988
1989         *frame_r = frame;
1990         *index_r = index;
1991
1992         return ibuf;
1993 }
1994
1995 /* Checks optional ImageUser and verifies/creates ImBuf. */
1996 /* use this one if you want to get a render result in progress,
1997  * if not, use BKE_image_get_ibuf which doesn't require a release */
1998 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
1999 {
2000         ImBuf *ibuf= NULL;
2001         float color[] = {0, 0, 0, 1};
2002         int frame= 0, index= 0;
2003
2004         /* This function is intended to be thread-safe. It postpones the mutex lock
2005          * until it needs to load the image, if the image is already there it
2006          * should just get the pointer and return. The reason is that a lot of mutex
2007          * locks appears to be very slow on certain multicore macs, causing a render
2008          * with image textures to actually slow down as more threads are used.
2009          *
2010          * Note that all the image loading functions should also make sure they do
2011          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2012          * That means, the last two steps must be, 1) add the ibuf to the list and
2013          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2014         
2015         if(lock_r)
2016                 *lock_r= NULL;
2017
2018         /* quick reject tests */
2019         if(ima==NULL) 
2020                 return NULL;
2021         if(iuser) {
2022                 if(iuser->ok==0)
2023                         return NULL;
2024         }
2025         else if(ima->ok==0)
2026                 return NULL;
2027         
2028         /* try to get the ibuf without locking */
2029         ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2030
2031         if(ibuf == NULL) {
2032                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2033                  * load the image */
2034                 BLI_lock_thread(LOCK_IMAGE);
2035
2036                 /* need to check ok flag and loading ibuf again, because the situation
2037                  * might have changed in the meantime */
2038                 if(iuser) {
2039                         if(iuser->ok==0) {
2040                                 BLI_unlock_thread(LOCK_IMAGE);
2041                                 return NULL;
2042                         }
2043                 }
2044                 else if(ima->ok==0) {
2045                         BLI_unlock_thread(LOCK_IMAGE);
2046                         return NULL;
2047                 }
2048
2049                 ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2050
2051                 if(ibuf == NULL) {
2052                         /* we are sure we have to load the ibuf, using source and type */
2053                         if(ima->source==IMA_SRC_MOVIE) {
2054                                 /* source is from single file, use flipbook to store ibuf */
2055                                 ibuf= image_load_movie_file(ima, iuser, frame);
2056                         }
2057                         else if(ima->source==IMA_SRC_SEQUENCE) {
2058                                 if(ima->type==IMA_TYPE_IMAGE) {
2059                                         /* regular files, ibufs in flipbook, allows saving */
2060                                         ibuf= image_load_sequence_file(ima, iuser, frame);
2061                                 }
2062                                 /* no else; on load the ima type can change */
2063                                 if(ima->type==IMA_TYPE_MULTILAYER) {
2064                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2065                                         ibuf= image_load_sequence_multilayer(ima, iuser, frame);
2066                                 }
2067
2068                                 if(ibuf)
2069                                         BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
2070                         }
2071                         else if(ima->source==IMA_SRC_FILE) {
2072                                 
2073                                 if(ima->type==IMA_TYPE_IMAGE)
2074                                         ibuf= image_load_image_file(ima, iuser, frame); /* cfra only for '#', this global is OK */
2075                                 /* no else; on load the ima type can change */
2076                                 if(ima->type==IMA_TYPE_MULTILAYER)
2077                                         /* keeps render result, stores ibufs in listbase, allows saving */
2078                                         ibuf= image_get_ibuf_multilayer(ima, iuser);
2079                                         
2080                         }
2081                         else if(ima->source == IMA_SRC_GENERATED) {
2082                                 /* generated is: ibuf is allocated dynamically */
2083                                 /* UV testgrid or black or solid etc */
2084                                 if(ima->gen_x==0) ima->gen_x= 1024;
2085                                 if(ima->gen_y==0) ima->gen_y= 1024;
2086                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, 0, ima->gen_type, color);
2087                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2088                                 ima->ok= IMA_OK_LOADED;
2089                         }
2090                         else if(ima->source == IMA_SRC_VIEWER) {
2091                                 if(ima->type==IMA_TYPE_R_RESULT) {
2092                                         /* always verify entirely, and potentially
2093                                            returns pointer to release later */
2094                                         ibuf= image_get_render_result(ima, iuser, lock_r);
2095                                 }
2096                                 else if(ima->type==IMA_TYPE_COMPOSITE) {
2097                                         /* requires lock/unlock, otherwise don't return image */
2098                                         if(lock_r) {
2099                                                 /* unlock in BKE_image_release_ibuf */
2100                                                 BLI_lock_thread(LOCK_VIEWER);
2101                                                 *lock_r= ima;
2102
2103                                                 /* Composite Viewer, all handled in compositor */
2104                                                 /* fake ibuf, will be filled in compositor */
2105                                                 ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
2106                                                 image_assign_ibuf(ima, ibuf, 0, frame);
2107                                         }
2108                                 }
2109                         }
2110                 }
2111
2112                 BLI_unlock_thread(LOCK_IMAGE);
2113         }
2114
2115         /* we assuming that if it is not rendering, it's also not multithreaded
2116          * (a somewhat weak assumption) */
2117         if(G.rendering==0)
2118                 tag_image_time(ima);
2119
2120         return ibuf;
2121 }
2122
2123 void BKE_image_release_ibuf(Image *ima, void *lock)
2124 {
2125         /* for getting image during threaded render / compositing, need to release */
2126         if(lock == ima) {
2127                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2128         }
2129         else if(lock) {
2130                 RE_ReleaseResultImage(lock); /* render result */
2131                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2132         }
2133 }
2134
2135 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2136 {
2137         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2138 }
2139
2140 void BKE_image_user_calc_frame(ImageUser *iuser, int cfra, int fieldnr)
2141 {
2142         int imanr, len;
2143         
2144         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2145         len= (iuser->fie_ima*iuser->frames)/2;
2146         
2147         if(len==0) {
2148                 iuser->framenr= 0;
2149         }
2150         else {
2151                 cfra= cfra - iuser->sfra+1;
2152                 
2153                 /* cyclic */
2154                 if(iuser->cycl) {
2155                         cfra= ( (cfra) % len );
2156                         if(cfra < 0) cfra+= len;
2157                         if(cfra==0) cfra= len;
2158                 }
2159                 
2160                 if(cfra<1) cfra= 1;
2161                 else if(cfra>len) cfra= len;
2162                 
2163                 /* convert current frame to current field */
2164                 cfra= 2*(cfra);
2165                 if(fieldnr) cfra++;
2166                 
2167                 /* transform to images space */
2168                 imanr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
2169                 if(imanr>iuser->frames) imanr= iuser->frames;
2170                 imanr+= iuser->offset;
2171                 
2172                 if(iuser->cycl) {
2173                         imanr= ( (imanr) % len );
2174                         while(imanr < 0) imanr+= len;
2175                         if(imanr==0) imanr= len;
2176                 }
2177         
2178                 /* allows image users to handle redraws */
2179                 if(iuser->flag & IMA_ANIM_ALWAYS)
2180                         if(imanr!=iuser->framenr)
2181                                 iuser->flag |= IMA_ANIM_REFRESHED;
2182                 
2183                 iuser->framenr= imanr;
2184                 if(iuser->ok==0) iuser->ok= 1;
2185         }
2186 }