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