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