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