rename image type defines to be less ambiguous, also set BMP as not supporting alpha...
[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 *iman= copy_image(ima);
389
390                 iman->id.us= 0;
391
392                 /* Remap paths of new ID using old library as base. */
393                 BKE_id_lib_local_paths(bmain, &iman->id);
394
395                 tex= bmain->tex.first;
396                 while(tex) {
397                         if(tex->id.lib==NULL) {
398                                 if(tex->ima==ima) {
399                                         tex->ima = iman;
400                                         iman->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 = iman;
411                                         iman->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 = iman;
433                                                                 if(iman->id.us == 0) {
434                                                                         tface->tpage->id.us= 1;
435                                                                 }
436                                                                 id_lib_extern((ID*)iman);
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_alpha(const char imtype)
904 {
905         switch(imtype) {
906         case R_IMF_IMTYPE_TARGA:
907         case R_IMF_IMTYPE_IRIS:
908         case R_IMF_IMTYPE_PNG:
909         /* case R_IMF_IMTYPE_BMP: */ /* read but not write */
910         case R_IMF_IMTYPE_RADHDR:
911         case R_IMF_IMTYPE_TIFF:
912         case R_IMF_IMTYPE_OPENEXR:
913         case R_IMF_IMTYPE_MULTILAYER:
914         case R_IMF_IMTYPE_DDS:
915         case R_IMF_IMTYPE_JP2:
916                         return 1;
917         }
918         return 0;
919 }
920
921 int BKE_imtype_supports_zbuf(const char imtype)
922 {
923         switch(imtype) {
924         case R_IMF_IMTYPE_IRIZ:
925         case R_IMF_IMTYPE_OPENEXR: /* but not R_IMF_IMTYPE_MULTILAYER */
926                         return 1;
927         }
928         return 0;
929 }
930
931 int BKE_imtype_supports_compress(const char imtype)
932 {
933         switch(imtype) {
934         case R_IMF_IMTYPE_PNG:
935                         return 1;
936         }
937         return 0;
938 }
939
940 int BKE_imtype_supports_quality(const char imtype)
941 {
942         switch(imtype) {
943         case R_IMF_IMTYPE_JPEG90:
944         case R_IMF_IMTYPE_JP2:
945         case R_IMF_IMTYPE_AVIJPEG:
946                         return 1;
947         }
948         return 0;
949 }
950
951 char BKE_imtype_valid_depths(const char imtype)
952 {
953         switch (imtype) {
954         case R_IMF_IMTYPE_RADHDR:
955                 return R_IMF_CHAN_DEPTH_32;
956         case R_IMF_IMTYPE_TIFF:
957                 return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_16;
958         case R_IMF_IMTYPE_OPENEXR:
959                 return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32;
960         case R_IMF_IMTYPE_MULTILAYER:
961                 return R_IMF_CHAN_DEPTH_32;
962         /* eeh, cineone does some strange 10bits per channel */
963         case R_IMF_IMTYPE_DPX:
964         case R_IMF_IMTYPE_CINEON:
965                 return R_IMF_CHAN_DEPTH_12;
966         case R_IMF_IMTYPE_JP2:
967                 return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
968         /* most formats are 8bit only */
969         default:
970                 return R_IMF_CHAN_DEPTH_8;
971         }
972 }
973
974 int BKE_add_image_extension(char *string, const char imtype)
975 {
976         const char *extension= NULL;
977         
978         if(imtype== R_IMF_IMTYPE_IRIS) {
979                 if(!BLI_testextensie(string, ".rgb"))
980                         extension= ".rgb";
981         }
982         else if(imtype==R_IMF_IMTYPE_IRIZ) {
983                 if(!BLI_testextensie(string, ".rgb"))
984                         extension= ".rgb";
985         }
986 #ifdef WITH_HDR
987         else if(imtype==R_IMF_IMTYPE_RADHDR) {
988                 if(!BLI_testextensie(string, ".hdr"))
989                         extension= ".hdr";
990         }
991 #endif
992         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
993                 if(!BLI_testextensie(string, ".png"))
994                         extension= ".png";
995         }
996 #ifdef WITH_DDS
997         else if(imtype==R_IMF_IMTYPE_DDS) {
998                 if(!BLI_testextensie(string, ".dds"))
999                         extension= ".dds";
1000         }
1001 #endif
1002         else if(imtype==R_IMF_IMTYPE_RAWTGA) {
1003                 if(!BLI_testextensie(string, ".tga"))
1004                         extension= ".tga";
1005         }
1006         else if(imtype==R_IMF_IMTYPE_BMP) {
1007                 if(!BLI_testextensie(string, ".bmp"))
1008                         extension= ".bmp";
1009         }
1010 #ifdef WITH_TIFF
1011         else if(imtype==R_IMF_IMTYPE_TIFF) {
1012                 if(!BLI_testextensie(string, ".tif") && 
1013                         !BLI_testextensie(string, ".tiff")) extension= ".tif";
1014         }
1015 #endif
1016 #ifdef WITH_OPENEXR
1017         else if( ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
1018                 if(!BLI_testextensie(string, ".exr"))
1019                         extension= ".exr";
1020         }
1021 #endif
1022 #ifdef WITH_CINEON
1023         else if(imtype==R_IMF_IMTYPE_CINEON){
1024                 if (!BLI_testextensie(string, ".cin"))
1025                         extension= ".cin";
1026         }
1027         else if(imtype==R_IMF_IMTYPE_DPX){
1028                 if (!BLI_testextensie(string, ".dpx"))
1029                         extension= ".dpx";
1030         }
1031 #endif
1032         else if(imtype==R_IMF_IMTYPE_TARGA) {
1033                 if(!BLI_testextensie(string, ".tga"))
1034                         extension= ".tga";
1035         }
1036 #ifdef WITH_OPENJPEG
1037         else if(imtype==R_IMF_IMTYPE_JP2) {
1038                 if(!BLI_testextensie(string, ".jp2"))
1039                         extension= ".jp2";
1040         }
1041 #endif
1042         else { //   R_IMF_IMTYPE_AVICODEC, R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90, R_IMF_IMTYPE_QUICKTIME etc
1043                 if(!( BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
1044                         extension= ".jpg";
1045         }
1046
1047         if(extension) {
1048                 /* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */
1049                 /* remove any other known image extension */
1050                 if(BLI_testextensie_array(string, imb_ext_image)
1051                                   || (G.have_quicktime && BLI_testextensie_array(string, imb_ext_image_qt))) {
1052                         return BLI_replace_extension(string, FILE_MAX, extension);
1053                 } else {
1054                         return BLI_ensure_extension(string, FILE_MAX, extension);
1055                         return TRUE;
1056                 }
1057                 
1058         }
1059         else {
1060                 return FALSE;
1061         }
1062 }
1063
1064 /* could allow access externally - 512 is for long names, 64 is for id names */
1065 typedef struct StampData {
1066         char    file[512];
1067         char    note[512];
1068         char    date[512];
1069         char    marker[512];
1070         char    time[512];
1071         char    frame[512];
1072         char    camera[64];
1073         char    cameralens[64];
1074         char    scene[64];
1075         char    strip[64];
1076         char    rendertime[64];
1077 } StampData;
1078
1079 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix)
1080 {
1081         char text[256];
1082         struct tm *tl;
1083         time_t t;
1084
1085         if (scene->r.stamp & R_STAMP_FILENAME) {
1086                 BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), do_prefix ? "File %s":"%s", G.relbase_valid ? G.main->name:"<untitled>");
1087         } else {
1088                 stamp_data->file[0] = '\0';
1089         }
1090         
1091         if (scene->r.stamp & R_STAMP_NOTE) {
1092                 /* Never do prefix for Note */
1093                 BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", scene->r.stamp_udata);
1094         } else {
1095                 stamp_data->note[0] = '\0';
1096         }
1097         
1098         if (scene->r.stamp & R_STAMP_DATE) {
1099                 t = time(NULL);
1100                 tl = localtime(&t);
1101                 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);
1102                 BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), do_prefix ? "Date %s":"%s", text);
1103         } else {
1104                 stamp_data->date[0] = '\0';
1105         }
1106         
1107         if (scene->r.stamp & R_STAMP_MARKER) {
1108                 char *name = scene_find_last_marker_name(scene, CFRA);
1109
1110                 if (name)       BLI_strncpy(text, name, sizeof(text));
1111                 else            strcpy(text, "<none>");
1112
1113                 BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), do_prefix ? "Marker %s":"%s", text);
1114         } else {
1115                 stamp_data->marker[0] = '\0';
1116         }
1117         
1118         if (scene->r.stamp & R_STAMP_TIME) {
1119                 int f = (int)(scene->r.cfra % scene->r.frs_sec);
1120                 int s = (int)(scene->r.cfra / scene->r.frs_sec);
1121                 int h= 0;
1122                 int m= 0;
1123
1124                 if (s) {
1125                         m = (int)(s / 60);
1126                         s %= 60;
1127
1128                         if (m) {
1129                                 h = (int)(m / 60);
1130                                 m %= 60;
1131                         }
1132                 }
1133
1134                 if (scene->r.frs_sec < 100)
1135                         BLI_snprintf(text, sizeof(text), "%02d:%02d:%02d.%02d", h, m, s, f);
1136                 else
1137                         BLI_snprintf(text, sizeof(text), "%02d:%02d:%02d.%03d", h, m, s, f);
1138
1139                 BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), do_prefix ? "Time %s":"%s", text);
1140         } else {
1141                 stamp_data->time[0] = '\0';
1142         }
1143         
1144         if (scene->r.stamp & R_STAMP_FRAME) {
1145                 char format[32];
1146                 int digits= 1;
1147                 
1148                 if(scene->r.efra>9)
1149                         digits= 1 + (int) log10(scene->r.efra);
1150
1151                 BLI_snprintf(format, sizeof(format), do_prefix ? "Frame %%0%di":"%%0%di", digits);
1152                 BLI_snprintf (stamp_data->frame, sizeof(stamp_data->frame), format, scene->r.cfra);
1153         } else {
1154                 stamp_data->frame[0] = '\0';
1155         }
1156
1157         if (scene->r.stamp & R_STAMP_CAMERA) {
1158                 BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), do_prefix ? "Camera %s":"%s", camera ? camera->id.name+2 : "<none>");
1159         } else {
1160                 stamp_data->camera[0] = '\0';
1161         }
1162
1163         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1164                 if (camera && camera->type == OB_CAMERA) {
1165                         BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)camera->data)->lens);
1166                 }
1167                 else            strcpy(text, "<none>");
1168
1169                 BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), do_prefix ? "Lens %s":"%s", text);
1170         } else {
1171                 stamp_data->cameralens[0] = '\0';
1172         }
1173
1174         if (scene->r.stamp & R_STAMP_SCENE) {
1175                 BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), do_prefix ? "Scene %s":"%s", scene->id.name+2);
1176         } else {
1177                 stamp_data->scene[0] = '\0';
1178         }
1179         
1180         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1181                 Sequence *seq= seq_foreground_frame_get(scene, scene->r.cfra);
1182         
1183                 if (seq)        BLI_strncpy(text, seq->name+2, sizeof(text));
1184                 else            strcpy(text, "<none>");
1185
1186                 BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), do_prefix ? "Strip %s":"%s", text);
1187         } else {
1188                 stamp_data->strip[0] = '\0';
1189         }
1190
1191         {
1192                 Render *re= RE_GetRender(scene->id.name);
1193                 RenderStats *stats= re ? RE_GetStats(re):NULL;
1194
1195                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1196                         BLI_timestr(stats->lastframetime, text);
1197
1198                         BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), do_prefix ? "RenderTime %s":"%s", text);
1199                 } else {
1200                         stamp_data->rendertime[0] = '\0';
1201                 }
1202         }
1203 }
1204
1205 void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rectf, int width, int height, int channels)
1206 {
1207         struct StampData stamp_data;
1208         float w, h, pad;
1209         int x, y, y_ofs;
1210         float h_fixed;
1211         const int mono= blf_mono_font_render; // XXX
1212
1213 #define BUFF_MARGIN_X 2
1214 #define BUFF_MARGIN_Y 1
1215
1216         if (!rect && !rectf)
1217                 return;
1218         
1219         stampdata(scene, camera, &stamp_data, 1);
1220
1221         /* TODO, do_versions */
1222         if(scene->r.stamp_font_id < 8)
1223                 scene->r.stamp_font_id= 12;
1224
1225         /* set before return */
1226         BLF_size(mono, scene->r.stamp_font_id, 72);
1227         
1228         BLF_buffer(mono, rectf, rect, width, height, channels);
1229         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1230         pad= BLF_width_max(mono);
1231
1232         /* use 'h_fixed' rather than 'h', aligns better */
1233         h_fixed= BLF_height_max(mono);
1234         y_ofs = -BLF_descender(mono);
1235
1236         x= 0;
1237         y= height;
1238
1239         if (stamp_data.file[0]) {
1240                 /* Top left corner */
1241                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h= h_fixed;
1242                 y -= h;
1243
1244                 /* also a little of space to the background. */
1245                 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);
1246
1247                 /* and draw the text. */
1248                 BLF_position(mono, x, y + y_ofs, 0.0);
1249                 BLF_draw_buffer(mono, stamp_data.file);
1250
1251                 /* the extra pixel for background. */
1252                 y -= BUFF_MARGIN_Y * 2;
1253         }
1254
1255         /* Top left corner, below File */
1256         if (stamp_data.note[0]) {
1257                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h= h_fixed;
1258                 y -= h;
1259
1260                 /* and space for background. */
1261                 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);
1262
1263                 BLF_position(mono, x, y + y_ofs, 0.0);
1264                 BLF_draw_buffer(mono, stamp_data.note);
1265
1266                 /* the extra pixel for background. */
1267                 y -= BUFF_MARGIN_Y * 2;
1268         }
1269         
1270         /* Top left corner, below File (or Note) */
1271         if (stamp_data.date[0]) {
1272                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h= h_fixed;
1273                 y -= h;
1274
1275                 /* and space for background. */
1276                 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);
1277
1278                 BLF_position(mono, x, y + y_ofs, 0.0);
1279                 BLF_draw_buffer(mono, stamp_data.date);
1280
1281                 /* the extra pixel for background. */
1282                 y -= BUFF_MARGIN_Y * 2;
1283         }
1284
1285         /* Top left corner, below File, Date or Note */
1286         if (stamp_data.rendertime[0]) {
1287                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h= h_fixed;
1288                 y -= h;
1289
1290                 /* and space for background. */
1291                 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);
1292
1293                 BLF_position(mono, x, y + y_ofs, 0.0);
1294                 BLF_draw_buffer(mono, stamp_data.rendertime);
1295         }
1296
1297         x= 0;
1298         y= 0;
1299
1300         /* Bottom left corner, leaving space for timing */
1301         if (stamp_data.marker[0]) {
1302                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h= h_fixed;
1303
1304                 /* extra space for background. */
1305                 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);
1306
1307                 /* and pad the text. */
1308                 BLF_position(mono, x, y + y_ofs, 0.0);
1309                 BLF_draw_buffer(mono, stamp_data.marker);
1310
1311                 /* space width. */
1312                 x += w + pad;
1313         }
1314         
1315         /* Left bottom corner */
1316         if (stamp_data.time[0]) {
1317                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h= h_fixed;
1318
1319                 /* extra space for background */
1320                 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);
1321
1322                 /* and pad the text. */
1323                 BLF_position(mono, x, y + y_ofs, 0.0);
1324                 BLF_draw_buffer(mono, stamp_data.time);
1325
1326                 /* space width. */
1327                 x += w + pad;
1328         }
1329         
1330         if (stamp_data.frame[0]) {
1331                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h= h_fixed;
1332
1333                 /* extra space for background. */
1334                 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);
1335
1336                 /* and pad the text. */
1337                 BLF_position(mono, x, y + y_ofs, 0.0);
1338                 BLF_draw_buffer(mono, stamp_data.frame);
1339
1340                 /* space width. */
1341                 x += w + pad;
1342         }
1343
1344         if (stamp_data.camera[0]) {
1345                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h= h_fixed;
1346
1347                 /* extra space for background. */
1348                 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);
1349                 BLF_position(mono, x, y + y_ofs, 0.0);
1350                 BLF_draw_buffer(mono, stamp_data.camera);
1351
1352                 /* space width. */
1353                 x += w + pad;
1354         }
1355
1356         if (stamp_data.cameralens[0]) {
1357                 BLF_width_and_height(mono, stamp_data.cameralens, &w, &h); h= h_fixed;
1358
1359                 /* extra space for background. */
1360                 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);
1361                 BLF_position(mono, x, y + y_ofs, 0.0);
1362                 BLF_draw_buffer(mono, stamp_data.cameralens);
1363         }
1364         
1365         if (stamp_data.scene[0]) {
1366                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h= h_fixed;
1367
1368                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1369                 x= width - w - 2;
1370
1371                 /* extra space for background. */
1372                 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);
1373
1374                 /* and pad the text. */
1375                 BLF_position(mono, x, y+y_ofs, 0.0);
1376                 BLF_draw_buffer(mono, stamp_data.scene);
1377         }
1378         
1379         if (stamp_data.strip[0]) {
1380                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h= h_fixed;
1381
1382                 /* Top right corner, with an extra space because blenfont is too strict! */
1383                 x= width - w - pad;
1384                 y= height - h;
1385
1386                 /* extra space for background. */
1387                 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);
1388
1389                 BLF_position(mono, x, y + y_ofs, 0.0);
1390                 BLF_draw_buffer(mono, stamp_data.strip);
1391         }
1392
1393         /* cleanup the buffer. */
1394         BLF_buffer(mono, NULL, NULL, 0, 0, 0);
1395
1396 #undef BUFF_MARGIN_X
1397 #undef BUFF_MARGIN_Y
1398 }
1399
1400 void BKE_stamp_info(Scene *scene, Object *camera, struct ImBuf *ibuf)
1401 {
1402         struct StampData stamp_data;
1403
1404         if (!ibuf)      return;
1405         
1406         /* fill all the data values, no prefix */
1407         stampdata(scene, camera, &stamp_data, 0);
1408         
1409         if (stamp_data.file[0])         IMB_metadata_change_field (ibuf, "File",                stamp_data.file);
1410         if (stamp_data.note[0])         IMB_metadata_change_field (ibuf, "Note",                stamp_data.note);
1411         if (stamp_data.date[0])         IMB_metadata_change_field (ibuf, "Date",                stamp_data.date);
1412         if (stamp_data.marker[0])       IMB_metadata_change_field (ibuf, "Marker",      stamp_data.marker);
1413         if (stamp_data.time[0])         IMB_metadata_change_field (ibuf, "Time",                stamp_data.time);
1414         if (stamp_data.frame[0])        IMB_metadata_change_field (ibuf, "Frame",       stamp_data.frame);
1415         if (stamp_data.camera[0])       IMB_metadata_change_field (ibuf, "Camera",      stamp_data.camera);
1416         if (stamp_data.cameralens[0]) IMB_metadata_change_field (ibuf, "Lens",  stamp_data.cameralens);
1417         if (stamp_data.scene[0])        IMB_metadata_change_field (ibuf, "Scene",       stamp_data.scene);
1418         if (stamp_data.strip[0])        IMB_metadata_change_field (ibuf, "Strip",       stamp_data.strip);
1419         if (stamp_data.rendertime[0]) IMB_metadata_change_field (ibuf, "RenderTime", stamp_data.rendertime);
1420 }
1421
1422 int BKE_alphatest_ibuf(ImBuf *ibuf)
1423 {
1424         int tot;
1425         if(ibuf->rect_float) {
1426                 float *buf= ibuf->rect_float;
1427                 for(tot= ibuf->x * ibuf->y; tot--; buf+=4) {
1428                         if(buf[3] < 1.0f) {
1429                                 return TRUE;
1430                         }
1431                 }
1432         }
1433         else if (ibuf->rect) {
1434                 unsigned char *buf= (unsigned char *)ibuf->rect;
1435                 for(tot= ibuf->x * ibuf->y; tot--; buf+=4) {
1436                         if(buf[3] != 255) {
1437                                 return TRUE;
1438                         }
1439                 }
1440         }
1441
1442         return FALSE;
1443 }
1444
1445 int BKE_write_ibuf(ImBuf *ibuf, const char *name, ImageFormatData *imf)
1446 {
1447         char imtype= imf->imtype;
1448         char compress= imf->compress;
1449         char quality= imf->quality;
1450
1451         int ok;
1452
1453         if(imtype == -1) {
1454                 /* use whatever existing image type is set by 'ibuf' */
1455         }
1456         else if(imtype== R_IMF_IMTYPE_IRIS) {
1457                 ibuf->ftype= IMAGIC;
1458         }
1459 #ifdef WITH_HDR
1460         else if (imtype==R_IMF_IMTYPE_RADHDR) {
1461                 ibuf->ftype= RADHDR;
1462         }
1463 #endif
1464         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1465                 ibuf->ftype= PNG;
1466
1467                 if(imtype==R_IMF_IMTYPE_PNG)
1468                         ibuf->ftype |= compress;
1469
1470         }
1471 #ifdef WITH_DDS
1472         else if (imtype==R_IMF_IMTYPE_DDS) {
1473                 ibuf->ftype= DDS;
1474         }
1475 #endif
1476         else if (imtype==R_IMF_IMTYPE_BMP) {
1477                 ibuf->ftype= BMP;
1478         }
1479 #ifdef WITH_TIFF
1480         else if (imtype==R_IMF_IMTYPE_TIFF) {
1481                 ibuf->ftype= TIF;
1482
1483                 if(imf->depth == R_IMF_CHAN_DEPTH_16)
1484                         ibuf->ftype |= TIF_16BIT;
1485         }
1486 #endif
1487 #ifdef WITH_OPENEXR
1488         else if (imtype==R_IMF_IMTYPE_OPENEXR || imtype==R_IMF_IMTYPE_MULTILAYER) {
1489                 ibuf->ftype= OPENEXR;
1490                 if(imf->depth == R_IMF_CHAN_DEPTH_16)
1491                         ibuf->ftype |= OPENEXR_HALF;
1492                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
1493                 
1494                 if(!(imf->flag & R_IMF_FLAG_ZBUF))
1495                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1496                 
1497         }
1498 #endif
1499 #ifdef WITH_CINEON
1500         else if (imtype==R_IMF_IMTYPE_CINEON) {
1501                 ibuf->ftype = CINEON;
1502         }
1503         else if (imtype==R_IMF_IMTYPE_DPX) {
1504                 ibuf->ftype = DPX;
1505         }
1506 #endif
1507         else if (imtype==R_IMF_IMTYPE_TARGA) {
1508                 ibuf->ftype= TGA;
1509         }
1510         else if(imtype==R_IMF_IMTYPE_RAWTGA) {
1511                 ibuf->ftype= RAWTGA;
1512         }
1513 #ifdef WITH_OPENJPEG
1514         else if(imtype==R_IMF_IMTYPE_JP2) {
1515                 if(quality < 10) quality= 90;
1516                 ibuf->ftype= JP2|quality;
1517                 
1518                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1519                         ibuf->ftype |= JP2_16BIT;
1520                 } else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1521                         ibuf->ftype |= JP2_12BIT;
1522                 }
1523                 
1524                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
1525                         ibuf->ftype |= JP2_YCC;
1526                 }
1527
1528                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
1529                         ibuf->ftype |= JP2_CINE;
1530                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
1531                                 ibuf->ftype |= JP2_CINE_48FPS;
1532                 }
1533         }
1534 #endif
1535         else {
1536                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
1537                 if(quality < 10) quality= 90;
1538                 ibuf->ftype= JPG|quality;
1539                 if(ibuf->planes==32) ibuf->planes= 24;  /* unsupported feature only confuses other s/w */
1540         }
1541         
1542         BLI_make_existing_file(name);
1543         
1544         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1545         if (ok == 0) {
1546                 perror(name);
1547         }
1548         
1549         return(ok);
1550 }
1551
1552 int BKE_write_ibuf_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, struct ImageFormatData *imf)
1553 {
1554         if(scene && scene->r.stamp & R_STAMP_ALL)
1555                 BKE_stamp_info(scene, camera, ibuf);
1556
1557         return BKE_write_ibuf(ibuf, name, imf);
1558 }
1559
1560
1561 void BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, const char imtype, const short use_ext, const short use_frames)
1562 {
1563         if (string==NULL) return;
1564         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1565         BLI_path_abs(string, relbase);
1566
1567         if(use_frames)
1568                 BLI_path_frame(string, frame, 4);
1569
1570         if(use_ext)
1571                 BKE_add_image_extension(string, imtype);
1572                 
1573 }
1574
1575 /* used by sequencer too */
1576 struct anim *openanim(const char *name, int flags, int streamindex)
1577 {
1578         struct anim *anim;
1579         struct ImBuf *ibuf;
1580         
1581         anim = IMB_open_anim(name, flags, streamindex);
1582         if (anim == NULL) return NULL;
1583
1584         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
1585         if (ibuf == NULL) {
1586                 if(BLI_exists(name))
1587                         printf("not an anim: %s\n", name);
1588                 else
1589                         printf("anim file doesn't exist: %s\n", name);
1590                 IMB_free_anim(anim);
1591                 return NULL;
1592         }
1593         IMB_freeImBuf(ibuf);
1594         
1595         return(anim);
1596 }
1597
1598 /* ************************* New Image API *************** */
1599
1600
1601 /* Notes about Image storage 
1602 - packedfile
1603   -> written in .blend
1604 - filename
1605   -> written in .blend
1606 - movie
1607   -> comes from packedfile or filename
1608 - renderresult
1609   -> comes from packedfile or filename
1610 - listbase
1611   -> ibufs from exrhandle
1612 - flipbook array
1613   -> ibufs come from movie, temporary renderresult or sequence
1614 - ibuf
1615   -> comes from packedfile or filename or generated
1616
1617 */
1618
1619
1620 /* forces existence of 1 Image for renderout or nodes, returns Image */
1621 /* name is only for default, when making new one */
1622 Image *BKE_image_verify_viewer(int type, const char *name)
1623 {
1624         Image *ima;
1625         
1626         for(ima=G.main->image.first; ima; ima= ima->id.next)
1627                 if(ima->source==IMA_SRC_VIEWER)
1628                         if(ima->type==type)
1629                                 break;
1630         
1631         if(ima==NULL)
1632                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1633         
1634         /* happens on reload, imagewindow cannot be image user when hidden*/
1635         if(ima->id.us==0)
1636                 id_us_plus(&ima->id);
1637
1638         return ima;
1639 }
1640
1641 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1642 {
1643         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1644 }
1645
1646 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1647 {
1648         if(ima==NULL)
1649                 return;
1650         
1651         switch(signal) {
1652         case IMA_SIGNAL_FREE:
1653                 image_free_buffers(ima);
1654                 if(iuser)
1655                         iuser->ok= 1;
1656                 break;
1657         case IMA_SIGNAL_SRC_CHANGE:
1658                 if(ima->type == IMA_TYPE_UV_TEST)
1659                         if(ima->source != IMA_SRC_GENERATED)
1660                                 ima->type= IMA_TYPE_IMAGE;
1661
1662                 if(ima->source==IMA_SRC_GENERATED) {
1663                         if(ima->gen_x==0 || ima->gen_y==0) {
1664                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1665                                 if(ibuf) {
1666                                         ima->gen_x= ibuf->x;
1667                                         ima->gen_y= ibuf->y;
1668                                 }
1669                         }
1670                 }
1671
1672                 /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
1673                 if(ima->type!=IMA_TYPE_MULTILAYER)
1674                         image_free_buffers(ima);
1675
1676                 ima->ok= 1;
1677                 if(iuser)
1678                         iuser->ok= 1;
1679                 break;
1680                         
1681         case IMA_SIGNAL_RELOAD:
1682                 /* try to repack file */
1683                 if(ima->packedfile) {
1684                         PackedFile *pf;
1685                         pf = newPackedFile(NULL, ima->name, ID_BLEND_PATH(G.main, &ima->id));
1686                         if (pf) {
1687                                 freePackedFile(ima->packedfile);
1688                                 ima->packedfile = pf;
1689                                 image_free_buffers(ima);
1690                         } else {
1691                                 printf("ERROR: Image not available. Keeping packed image\n");
1692                         }
1693                 }
1694                 else
1695                         image_free_buffers(ima);
1696                 
1697                 if(iuser)
1698                         iuser->ok= 1;
1699                 
1700                 break;
1701         case IMA_SIGNAL_USER_NEW_IMAGE:
1702                 if(iuser) {
1703                         iuser->ok= 1;
1704                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1705                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1706                                         iuser->multi_index= 0;
1707                                         iuser->layer= iuser->pass= 0;
1708                                 }
1709                         }
1710                 }
1711                 break;
1712         }
1713         
1714         /* dont use notifiers because they are not 100% sure to succseed
1715          * this also makes sure all scenes are accounted for. */
1716         {
1717                 Scene *scene;
1718                 for(scene= G.main->scene.first; scene; scene= scene->id.next) {
1719                         if(scene->nodetree) {
1720                                 nodeUpdateID(scene->nodetree, &ima->id);
1721                         }
1722                 }
1723         }
1724 }
1725
1726 /* if layer or pass changes, we need an index for the imbufs list */
1727 /* note it is called for rendered results, but it doesnt use the index! */
1728 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1729 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1730 {
1731         RenderLayer *rl;
1732         RenderPass *rpass= NULL;
1733         
1734         if(rr==NULL) 
1735                 return NULL;
1736         
1737         if(iuser) {
1738                 short index= 0, rl_index= 0, rp_index;
1739                 
1740                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1741                         rp_index= 0;
1742                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1743                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1744                                         break;
1745                         if(rpass)
1746                                 break;
1747                 }
1748                 
1749                 if(rpass)
1750                         iuser->multi_index= index;
1751                 else 
1752                         iuser->multi_index= 0;
1753         }
1754         if(rpass==NULL) {
1755                 rl= rr->layers.first;
1756                 if(rl)
1757                         rpass= rl->passes.first;
1758         }
1759         
1760         return rpass;
1761 }
1762
1763 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
1764 {
1765         if(ima->rr) {
1766                 return ima->rr;
1767         }
1768         else if(ima->type==IMA_TYPE_R_RESULT) {
1769                 if(ima->render_slot == ima->last_render_slot)
1770                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
1771                 else
1772                         return ima->renders[ima->render_slot];
1773         }
1774         else
1775                 return NULL;
1776 }
1777
1778 void BKE_image_release_renderresult(Scene *scene, Image *ima)
1779 {
1780         if(ima->rr);
1781         else if(ima->type==IMA_TYPE_R_RESULT) {
1782                 if(ima->render_slot == ima->last_render_slot)
1783                         RE_ReleaseResult(RE_GetRender(scene->id.name));
1784         }
1785 }
1786
1787 void BKE_image_backup_render(Scene *scene, Image *ima)
1788 {
1789         /* called right before rendering, ima->renders contains render
1790            result pointers for everything but the current render */
1791         Render *re= RE_GetRender(scene->id.name);
1792         int slot= ima->render_slot, last= ima->last_render_slot;
1793
1794         if(slot != last) {
1795                 if(ima->renders[slot]) {
1796                         RE_FreeRenderResult(ima->renders[slot]);
1797                         ima->renders[slot]= NULL;
1798                 }
1799
1800                 ima->renders[last]= NULL;
1801                 RE_SwapResult(re, &ima->renders[last]);
1802         }
1803
1804         ima->last_render_slot= slot;
1805 }
1806
1807 /* after imbuf load, openexr type can return with a exrhandle open */
1808 /* in that case we have to build a render-result */
1809 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1810 {
1811         
1812         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1813
1814 #ifdef WITH_OPENEXR
1815         IMB_exr_close(ibuf->userdata);
1816 #endif
1817
1818         ibuf->userdata= NULL;
1819         if(ima->rr)
1820                 ima->rr->framenr= framenr;
1821 }
1822
1823 /* common stuff to do with images after loading */
1824 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1825 {
1826         /* preview is NULL when it has never been used as an icon before */
1827         if(G.background==0 && ima->preview==NULL)
1828                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1829
1830         /* fields */
1831         if (ima->flag & IMA_FIELDS) {
1832                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1833                 else de_interlace_ng(ibuf);
1834         }
1835         /* timer */
1836         ima->lastused = clock() / CLOCKS_PER_SEC;
1837         
1838         ima->ok= IMA_OK_LOADED;
1839         
1840 }
1841
1842 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1843 {
1844         struct ImBuf *ibuf;
1845         unsigned short numlen;
1846         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1847         int flag;
1848         
1849         /* XXX temp stuff? */
1850         if(ima->lastframe != frame)
1851                 ima->tpageflag |= IMA_TPAGE_REFRESH;
1852
1853         ima->lastframe= frame;
1854         BLI_strncpy(name, ima->name, sizeof(name));
1855         BLI_stringdec(name, head, tail, &numlen);
1856         BLI_stringenc(name, head, tail, numlen, frame);
1857
1858         BLI_path_abs(name, ID_BLEND_PATH(G.main, &ima->id));
1859         
1860         flag= IB_rect|IB_multilayer;
1861         if(ima->flag & IMA_DO_PREMUL)
1862                 flag |= IB_premul;
1863
1864         /* read ibuf */
1865         ibuf = IMB_loadiffname(name, flag);
1866
1867 #if 0
1868         if(ibuf) {
1869                 printf(AT" loaded %s\n", name);
1870         } else {
1871                 printf(AT" missed %s\n", name);
1872         }
1873 #endif
1874
1875         if (ibuf) {
1876 #ifdef WITH_OPENEXR
1877                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1878                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1879                         image_create_multilayer(ima, ibuf, frame);      
1880                         ima->type= IMA_TYPE_MULTILAYER;
1881                         IMB_freeImBuf(ibuf);
1882                         ibuf= NULL;
1883                 }
1884                 else {
1885                         image_initialize_after_load(ima, ibuf);
1886                         image_assign_ibuf(ima, ibuf, 0, frame);
1887                 }
1888 #else
1889                 image_initialize_after_load(ima, ibuf);
1890                 image_assign_ibuf(ima, ibuf, 0, frame);
1891 #endif
1892         }
1893         else
1894                 ima->ok= 0;
1895         
1896         if(iuser)
1897                 iuser->ok= ima->ok;
1898         
1899         return ibuf;
1900 }
1901
1902 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1903 {
1904         struct ImBuf *ibuf= NULL;
1905         
1906         /* either we load from RenderResult, or we have to load a new one */
1907         
1908         /* check for new RenderResult */
1909         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1910                 /* copy to survive not found multilayer image */
1911                 RenderResult *oldrr= ima->rr;
1912         
1913                 ima->rr= NULL;
1914                 ibuf = image_load_sequence_file(ima, iuser, frame);
1915                 
1916                 if(ibuf) { /* actually an error */
1917                         ima->type= IMA_TYPE_IMAGE;
1918                         printf("error, multi is normal image\n");
1919                 }
1920                 // printf("loaded new result %p\n", ima->rr);
1921                 /* free result if new one found */
1922                 if(ima->rr) {
1923                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1924                         if(oldrr) RE_FreeRenderResult(oldrr);
1925                 }
1926                 else {
1927                         ima->rr= oldrr;
1928                 }
1929
1930         }
1931         if(ima->rr) {
1932                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1933                 
1934                 if(rpass) {
1935                         // printf("load from pass %s\n", rpass->name);
1936                         /* since we free  render results, we copy the rect */
1937                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
1938                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1939                         ibuf->flags |= IB_rectfloat;
1940                         ibuf->mall= IB_rectfloat;
1941                         ibuf->channels= rpass->channels;
1942                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1943                         
1944                         image_initialize_after_load(ima, ibuf);
1945                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
1946                         
1947                 }
1948                 // else printf("pass not found\n");
1949         }
1950         else
1951                 ima->ok= 0;
1952         
1953         if(iuser)
1954                 iuser->ok= ima->ok;
1955         
1956         return ibuf;
1957 }
1958
1959
1960 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
1961 {
1962         struct ImBuf *ibuf= NULL;
1963         
1964         ima->lastframe= frame;
1965         
1966         if(ima->anim==NULL) {
1967                 char str[FILE_MAX];
1968                 
1969                 BLI_strncpy(str, ima->name, FILE_MAX);
1970                 BLI_path_abs(str, ID_BLEND_PATH(G.main, &ima->id));
1971
1972                 /* FIXME: make several stream accessible in image editor, too*/
1973                 ima->anim = openanim(str, IB_rect, 0);
1974                 
1975                 /* let's initialize this user */
1976                 if(ima->anim && iuser && iuser->frames==0)
1977                         iuser->frames= IMB_anim_get_duration(ima->anim,
1978                                                              IMB_TC_RECORD_RUN);
1979         }
1980         
1981         if(ima->anim) {
1982                 int dur = IMB_anim_get_duration(ima->anim,
1983                                                 IMB_TC_RECORD_RUN);
1984                 int fra= frame-1;
1985                 
1986                 if(fra<0) fra = 0;
1987                 if(fra>(dur-1)) fra= dur-1;
1988                 ibuf = IMB_makeSingleUser(
1989                         IMB_anim_absolute(ima->anim, fra,
1990                                           IMB_TC_RECORD_RUN,
1991                                           IMB_PROXY_NONE));
1992                 
1993                 if(ibuf) {
1994                         image_initialize_after_load(ima, ibuf);
1995                         image_assign_ibuf(ima, ibuf, 0, frame);
1996                 }
1997                 else
1998                         ima->ok= 0;
1999         }
2000         else
2001                 ima->ok= 0;
2002         
2003         if(iuser)
2004                 iuser->ok= ima->ok;
2005         
2006         return ibuf;
2007 }
2008
2009 /* warning, 'iuser' can be NULL */
2010 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
2011 {
2012         struct ImBuf *ibuf;
2013         char str[FILE_MAX];
2014         int assign = 0, flag;
2015         
2016         /* always ensure clean ima */
2017         image_free_buffers(ima);
2018         
2019         /* is there a PackedFile with this image ? */
2020         if (ima->packedfile) {
2021                 flag = IB_rect|IB_multilayer;
2022                 if(ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
2023                 
2024                 ibuf = IMB_ibImageFromMemory((unsigned char*)ima->packedfile->data, ima->packedfile->size, flag, "<packed data>");
2025         } 
2026         else {
2027                 flag= IB_rect|IB_multilayer|IB_metadata;
2028                 if(ima->flag & IMA_DO_PREMUL)
2029                         flag |= IB_premul;
2030                         
2031                 /* get the right string */
2032                 BLI_strncpy(str, ima->name, sizeof(str));
2033                 BLI_path_abs(str, ID_BLEND_PATH(G.main, &ima->id));
2034                 
2035                 /* read ibuf */
2036                 ibuf = IMB_loadiffname(str, flag);
2037         }
2038         
2039         if (ibuf) {
2040                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2041                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
2042                         image_create_multilayer(ima, ibuf, cfra);       
2043                         ima->type= IMA_TYPE_MULTILAYER;
2044                         IMB_freeImBuf(ibuf);
2045                         ibuf= NULL;
2046                 }
2047                 else {
2048                         image_initialize_after_load(ima, ibuf);
2049                         assign= 1;
2050
2051                         /* check if the image is a font image... */
2052                         detectBitmapFont(ibuf);
2053                         
2054                         /* make packed file for autopack */
2055                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
2056                                 ima->packedfile = newPackedFile(NULL, str, ID_BLEND_PATH(G.main, &ima->id));
2057                 }
2058         }
2059         else
2060                 ima->ok= 0;
2061         
2062         if(assign)
2063                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2064
2065         if(iuser)
2066                 iuser->ok= ima->ok;
2067         
2068         return ibuf;
2069 }
2070
2071 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
2072 {
2073         ImBuf *ibuf= NULL;
2074         
2075         if(ima->rr==NULL) {
2076                 ibuf = image_load_image_file(ima, iuser, 0);
2077                 if(ibuf) { /* actually an error */
2078                         ima->type= IMA_TYPE_IMAGE;
2079                         return ibuf;
2080                 }
2081         }
2082         if(ima->rr) {
2083                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
2084
2085                 if(rpass) {
2086                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2087                         
2088                         image_initialize_after_load(ima, ibuf);
2089                         
2090                         ibuf->rect_float= rpass->rect;
2091                         ibuf->flags |= IB_rectfloat;
2092                         ibuf->channels= rpass->channels;
2093                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2094
2095                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2096                 }
2097         }
2098         
2099         if(ibuf==NULL) 
2100                 ima->ok= 0;
2101         if(iuser)
2102                 iuser->ok= ima->ok;
2103         
2104         return ibuf;
2105 }
2106
2107
2108 /* showing RGBA result itself (from compo/sequence) or
2109    like exr, using layers etc */
2110 /* always returns a single ibuf, also during render progress */
2111 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
2112 {
2113         Render *re;
2114         RenderResult rres;
2115         float *rectf, *rectz;
2116         unsigned int *rect;
2117         float dither;
2118         int channels, layer, pass;
2119         ImBuf *ibuf;
2120         int from_render= (ima->render_slot == ima->last_render_slot);
2121
2122         if(!(iuser && iuser->scene))
2123                 return NULL;
2124
2125         /* if we the caller is not going to release the lock, don't give the image */
2126         if(!lock_r)
2127                 return NULL;
2128
2129         re= RE_GetRender(iuser->scene->id.name);
2130
2131         channels= 4;
2132         layer= (iuser)? iuser->layer: 0;
2133         pass= (iuser)? iuser->pass: 0;
2134
2135         if(from_render) {
2136                 RE_AcquireResultImage(re, &rres);
2137         }
2138         else if(ima->renders[ima->render_slot]) {
2139                 rres= *(ima->renders[ima->render_slot]);
2140                 rres.have_combined= rres.rectf != NULL;
2141         }
2142         else
2143                 memset(&rres, 0, sizeof(RenderResult));
2144         
2145         if(!(rres.rectx > 0 && rres.recty > 0)) {
2146                 if(from_render)
2147                         RE_ReleaseResultImage(re);
2148                 return NULL;
2149         }
2150
2151         /* release is done in BKE_image_release_ibuf using lock_r */
2152         if(from_render) {
2153                 BLI_lock_thread(LOCK_VIEWER);
2154                 *lock_r= re;
2155         }
2156
2157         /* this gives active layer, composite or seqence result */
2158         rect= (unsigned int *)rres.rect32;
2159         rectf= rres.rectf;
2160         rectz= rres.rectz;
2161         dither= iuser->scene->r.dither_intensity;
2162
2163         /* combined layer gets added as first layer */
2164         if(rres.have_combined && layer==0);
2165         else if(rres.layers.first) {
2166                 RenderLayer *rl= BLI_findlink(&rres.layers, layer-(rres.have_combined?1:0));
2167                 if(rl) {
2168                         RenderPass *rpass;
2169
2170                         /* there's no combined pass, is in renderlayer itself */
2171                         if(pass==0) {
2172                                 rectf= rl->rectf;
2173                         }
2174                         else {
2175                                 rpass= BLI_findlink(&rl->passes, pass-1);
2176                                 if(rpass) {
2177                                         channels= rpass->channels;
2178                                         rectf= rpass->rect;
2179                                         dither= 0.0f; /* don't dither passes */
2180                                 }
2181                         }
2182
2183                         for(rpass= rl->passes.first; rpass; rpass= rpass->next)
2184                                 if(rpass->passtype == SCE_PASS_Z)
2185                                         rectz= rpass->rect;
2186                 }
2187         }
2188
2189         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2190
2191         /* make ibuf if needed, and initialize it */
2192         if(ibuf==NULL) {
2193                 ibuf= IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
2194                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2195         }
2196
2197         ibuf->x= rres.rectx;
2198         ibuf->y= rres.recty;
2199         
2200         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
2201                 imb_freerectImBuf(ibuf);
2202
2203         if(rect)
2204                 ibuf->rect= rect;
2205         
2206         if(rectf) {
2207                 ibuf->rect_float= rectf;
2208                 ibuf->flags |= IB_rectfloat;
2209                 ibuf->channels= channels;
2210         }
2211         else {
2212                 ibuf->rect_float= NULL;
2213                 ibuf->flags &= ~IB_rectfloat;
2214         }
2215
2216         if(rectz) {
2217                 ibuf->zbuf_float= rectz;
2218                 ibuf->flags |= IB_zbuffloat;
2219         }
2220         else {
2221                 ibuf->zbuf_float= NULL;
2222                 ibuf->flags &= ~IB_zbuffloat;
2223         }
2224
2225         /* since its possible to access the buffer from the image directly, set the profile [#25073] */
2226         ibuf->profile= (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) ? IB_PROFILE_LINEAR_RGB : IB_PROFILE_NONE;
2227
2228         ibuf->dither= dither;
2229
2230         ima->ok= IMA_OK_LOADED;
2231
2232         return ibuf;
2233 }
2234
2235 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2236 {
2237         ImBuf *ibuf = NULL;
2238         int frame = 0, index = 0;
2239
2240         /* see if we already have an appropriate ibuf, with image source and type */
2241         if(ima->source==IMA_SRC_MOVIE) {
2242                 frame= iuser?iuser->framenr:ima->lastframe;
2243                 ibuf= image_get_ibuf(ima, 0, frame);
2244                 /* XXX temp stuff? */
2245                 if(ima->lastframe != frame)
2246                         ima->tpageflag |= IMA_TPAGE_REFRESH;
2247                 ima->lastframe = frame;
2248         }
2249         else if(ima->source==IMA_SRC_SEQUENCE) {
2250                 if(ima->type==IMA_TYPE_IMAGE) {
2251                         frame= iuser?iuser->framenr:ima->lastframe;
2252                         ibuf= image_get_ibuf(ima, 0, frame);
2253                         
2254                         /* XXX temp stuff? */
2255                         if(ima->lastframe != frame) {
2256                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2257                         }
2258                         ima->lastframe = frame;
2259                 }       
2260                 else if(ima->type==IMA_TYPE_MULTILAYER) {
2261                         frame= iuser?iuser->framenr:ima->lastframe;
2262                         index= iuser?iuser->multi_index:IMA_NO_INDEX;
2263                         ibuf= image_get_ibuf(ima, index, frame);
2264                 }
2265         }
2266         else if(ima->source==IMA_SRC_FILE) {
2267                 if(ima->type==IMA_TYPE_IMAGE)
2268                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2269                 else if(ima->type==IMA_TYPE_MULTILAYER)
2270                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
2271         }
2272         else if(ima->source == IMA_SRC_GENERATED) {
2273                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
2274         }
2275         else if(ima->source == IMA_SRC_VIEWER) {
2276                 /* always verify entirely, not that this shouldn't happen
2277                  * as part of texture sampling in rendering anyway, so not
2278                  * a big bottleneck */
2279         }
2280
2281         *frame_r = frame;
2282         *index_r = index;
2283
2284         return ibuf;
2285 }
2286
2287 /* Checks optional ImageUser and verifies/creates ImBuf. */
2288 /* use this one if you want to get a render result in progress,
2289  * if not, use BKE_image_get_ibuf which doesn't require a release */
2290 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2291 {
2292         ImBuf *ibuf= NULL;
2293         float color[] = {0, 0, 0, 1};
2294         int frame= 0, index= 0;
2295
2296         /* This function is intended to be thread-safe. It postpones the mutex lock
2297          * until it needs to load the image, if the image is already there it
2298          * should just get the pointer and return. The reason is that a lot of mutex
2299          * locks appears to be very slow on certain multicore macs, causing a render
2300          * with image textures to actually slow down as more threads are used.
2301          *
2302          * Note that all the image loading functions should also make sure they do
2303          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2304          * That means, the last two steps must be, 1) add the ibuf to the list and
2305          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2306         
2307         if(lock_r)
2308                 *lock_r= NULL;
2309
2310         /* quick reject tests */
2311         if(ima==NULL) 
2312                 return NULL;
2313         if(iuser) {
2314                 if(iuser->ok==0)
2315                         return NULL;
2316         }
2317         else if(ima->ok==0)
2318                 return NULL;
2319         
2320         /* try to get the ibuf without locking */
2321         ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2322
2323         if(ibuf == NULL) {
2324                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2325                  * load the image */
2326                 BLI_lock_thread(LOCK_IMAGE);
2327
2328                 /* need to check ok flag and loading ibuf again, because the situation
2329                  * might have changed in the meantime */
2330                 if(iuser) {
2331                         if(iuser->ok==0) {
2332                                 BLI_unlock_thread(LOCK_IMAGE);
2333                                 return NULL;
2334                         }
2335                 }
2336                 else if(ima->ok==0) {
2337                         BLI_unlock_thread(LOCK_IMAGE);
2338                         return NULL;
2339                 }
2340
2341                 ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2342
2343                 if(ibuf == NULL) {
2344                         /* we are sure we have to load the ibuf, using source and type */
2345                         if(ima->source==IMA_SRC_MOVIE) {
2346                                 /* source is from single file, use flipbook to store ibuf */
2347                                 ibuf= image_load_movie_file(ima, iuser, frame);
2348                         }
2349                         else if(ima->source==IMA_SRC_SEQUENCE) {
2350                                 if(ima->type==IMA_TYPE_IMAGE) {
2351                                         /* regular files, ibufs in flipbook, allows saving */
2352                                         ibuf= image_load_sequence_file(ima, iuser, frame);
2353                                 }
2354                                 /* no else; on load the ima type can change */
2355                                 if(ima->type==IMA_TYPE_MULTILAYER) {
2356                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2357                                         ibuf= image_load_sequence_multilayer(ima, iuser, frame);
2358                                 }
2359                         }
2360                         else if(ima->source==IMA_SRC_FILE) {
2361                                 
2362                                 if(ima->type==IMA_TYPE_IMAGE)
2363                                         ibuf= image_load_image_file(ima, iuser, frame); /* cfra only for '#', this global is OK */
2364                                 /* no else; on load the ima type can change */
2365                                 if(ima->type==IMA_TYPE_MULTILAYER)
2366                                         /* keeps render result, stores ibufs in listbase, allows saving */
2367                                         ibuf= image_get_ibuf_multilayer(ima, iuser);
2368                                         
2369                         }
2370                         else if(ima->source == IMA_SRC_GENERATED) {
2371                                 /* generated is: ibuf is allocated dynamically */
2372                                 /* UV testgrid or black or solid etc */
2373                                 if(ima->gen_x==0) ima->gen_x= 1024;
2374                                 if(ima->gen_y==0) ima->gen_y= 1024;
2375                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, (ima->gen_flag & IMA_GEN_FLOAT) != 0, ima->gen_type, color);
2376                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2377                                 ima->ok= IMA_OK_LOADED;
2378                         }
2379                         else if(ima->source == IMA_SRC_VIEWER) {
2380                                 if(ima->type==IMA_TYPE_R_RESULT) {
2381                                         /* always verify entirely, and potentially
2382                                            returns pointer to release later */
2383                                         ibuf= image_get_render_result(ima, iuser, lock_r);
2384                                 }
2385                                 else if(ima->type==IMA_TYPE_COMPOSITE) {
2386                                         /* requires lock/unlock, otherwise don't return image */
2387                                         if(lock_r) {
2388                                                 /* unlock in BKE_image_release_ibuf */
2389                                                 BLI_lock_thread(LOCK_VIEWER);
2390                                                 *lock_r= ima;
2391
2392                                                 /* XXX anim play for viewer nodes not yet supported */
2393                                                 frame= 0; // XXX iuser?iuser->framenr:0;
2394                                                 ibuf= image_get_ibuf(ima, 0, frame);
2395
2396                                                 if(!ibuf) {
2397                                                         /* Composite Viewer, all handled in compositor */
2398                                                         /* fake ibuf, will be filled in compositor */
2399                                                         ibuf= IMB_allocImBuf(256, 256, 32, IB_rect);
2400                                                         image_assign_ibuf(ima, ibuf, 0, frame);
2401                                                 }
2402                                         }
2403                                 }
2404                         }
2405                 }
2406
2407                 BLI_unlock_thread(LOCK_IMAGE);
2408         }
2409
2410         tag_image_time(ima);
2411
2412         return ibuf;
2413 }
2414
2415 void BKE_image_release_ibuf(Image *ima, void *lock)
2416 {
2417         /* for getting image during threaded render / compositing, need to release */
2418         if(lock == ima) {
2419                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2420         }
2421         else if(lock) {
2422                 RE_ReleaseResultImage(lock); /* render result */
2423                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2424         }
2425 }
2426
2427 /* warning, this can allocate generated images */
2428 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2429 {
2430         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2431         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2432 }
2433
2434 int BKE_image_user_get_frame(const ImageUser *iuser, int cfra, int fieldnr)
2435 {
2436         const int len= (iuser->fie_ima*iuser->frames)/2;
2437
2438         if(len==0) {
2439                 return 0;
2440         }
2441         else {
2442                 int framenr;
2443                 cfra= cfra - iuser->sfra+1;
2444
2445                 /* cyclic */
2446                 if(iuser->cycl) {
2447                         cfra= ( (cfra) % len );
2448                         if(cfra < 0) cfra+= len;
2449                         if(cfra==0) cfra= len;
2450                 }
2451
2452                 if(cfra<0) cfra= 0;
2453                 else if(cfra>len) cfra= len;
2454
2455                 /* convert current frame to current field */
2456                 cfra= 2*(cfra);
2457                 if(fieldnr) cfra++;
2458
2459                 /* transform to images space */
2460                 framenr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
2461                 if(framenr>iuser->frames) framenr= iuser->frames;
2462                 framenr+= iuser->offset;
2463
2464                 if(iuser->cycl) {
2465                         framenr= ( (framenr) % len );
2466                         while(framenr < 0) framenr+= len;
2467                         if(framenr==0) framenr= len;
2468                 }
2469
2470                 return framenr;
2471         }
2472 }
2473
2474 void BKE_image_user_calc_frame(ImageUser *iuser, int cfra, int fieldnr)
2475 {
2476         const int framenr= BKE_image_user_get_frame(iuser, cfra, fieldnr);
2477
2478         /* allows image users to handle redraws */
2479         if(iuser->flag & IMA_ANIM_ALWAYS)
2480                 if(framenr!=iuser->framenr)
2481                         iuser->flag |= IMA_ANIM_REFRESHED;
2482
2483         iuser->framenr= framenr;
2484         if(iuser->ok==0) iuser->ok= 1;
2485 }
2486
2487 int BKE_image_has_alpha(struct Image *image)
2488 {
2489         ImBuf *ibuf;
2490         void *lock;
2491         int planes;
2492         
2493         ibuf= BKE_image_acquire_ibuf(image, NULL, &lock);
2494         planes = (ibuf?ibuf->planes:0);
2495         BKE_image_release_ibuf(image, lock);
2496
2497         if (planes == 32)
2498                 return 1;
2499         else
2500                 return 0;
2501 }
2502