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