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