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