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