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