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