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