Merge 16964:17122
[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         else
771                 return JPG|90;
772 }
773
774 int BKE_ftype_to_imtype(int ftype)
775 {
776         if(ftype==0)
777                 return TGA;
778         else if(ftype == IMAGIC) 
779                 return R_IRIS;
780         else if (ftype & RADHDR)
781                 return R_RADHDR;
782         else if (ftype & PNG)
783                 return R_PNG;
784 #ifdef WITH_DDS
785         else if (ftype & DDS)
786                 return R_DDS;
787 #endif
788         else if (ftype & BMP)
789                 return R_BMP;
790         else if (ftype & TIF)
791                 return R_TIFF;
792         else if (ftype & OPENEXR)
793                 return R_OPENEXR;
794         else if (ftype & CINEON)
795                 return R_CINEON;
796         else if (ftype & DPX)
797                 return R_DPX;
798         else if (ftype & TGA)
799                 return R_TARGA;
800         else if(ftype & RAWTGA)
801                 return R_RAWTGA;
802         else if(ftype == AN_hamx)
803                 return R_HAMX;
804         else
805                 return R_JPEG90;
806 }
807
808
809 int BKE_imtype_is_movie(int imtype)
810 {
811         switch(imtype) {
812         case R_MOVIE:
813         case R_AVIRAW:
814         case R_AVIJPEG:
815         case R_AVICODEC:
816         case R_QUICKTIME:
817         case R_FFMPEG:
818         case R_FRAMESERVER:
819                         return 1;
820         }
821         return 0;
822 }
823
824 void BKE_add_image_extension(char *string, int imtype)
825 {
826         char *extension="";
827         
828         if(G.scene->r.imtype== R_IRIS) {
829                 if(!BLI_testextensie(string, ".rgb"))
830                         extension= ".rgb";
831         }
832         else if(imtype==R_IRIZ) {
833                 if(!BLI_testextensie(string, ".rgb"))
834                         extension= ".rgb";
835         }
836         else if(imtype==R_RADHDR) {
837                 if(!BLI_testextensie(string, ".hdr"))
838                         extension= ".hdr";
839         }
840         else if(imtype==R_PNG || imtype==R_FFMPEG) {
841                 if(!BLI_testextensie(string, ".png"))
842                         extension= ".png";
843         }
844 #ifdef WITH_DDS
845         else if(imtype==R_DDS) {
846                 if(!BLI_testextensie(string, ".dds"))
847                         extension= ".dds";
848         }
849 #endif
850         else if(imtype==R_RAWTGA) {
851                 if(!BLI_testextensie(string, ".tga"))
852                         extension= ".tga";
853         }
854         else if(imtype==R_BMP) {
855                 if(!BLI_testextensie(string, ".bmp"))
856                         extension= ".bmp";
857         }
858         else if(G.have_libtiff && (imtype==R_TIFF)) {
859                 if(!BLI_testextensie(string, ".tif") && 
860                         !BLI_testextensie(string, ".tiff")) extension= ".tif";
861         }
862 #ifdef WITH_OPENEXR
863         else if( ELEM(imtype, R_OPENEXR, R_MULTILAYER)) {
864                 if(!BLI_testextensie(string, ".exr"))
865                         extension= ".exr";
866         }
867 #endif
868         else if(imtype==R_CINEON){
869                 if (!BLI_testextensie(string, ".cin"))
870                         extension= ".cin";
871         }
872         else if(imtype==R_DPX){
873                 if (!BLI_testextensie(string, ".dpx"))
874                         extension= ".dpx";
875         }
876         else if(imtype==R_TARGA) {
877                 if(!BLI_testextensie(string, ".tga"))
878                         extension= ".tga";
879         }
880         else { //   R_MOVIE, R_AVICODEC, R_AVIRAW, R_AVIJPEG, R_JPEG90, R_QUICKTIME etc
881                 if(!( BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
882                         extension= ".jpg";
883         }
884
885         strcat(string, extension);
886 }
887
888 /* could allow access externally - 512 is for long names, 64 is for id names */
889 typedef struct StampData {
890         char    file[512];
891         char    note[512];
892         char    date[512];
893         char    marker[512];
894         char    time[512];
895         char    frame[512];
896         char    camera[64];
897         char    scene[64];
898         char    strip[64];
899 } StampData;
900
901 static void stampdata(StampData *stamp_data, int do_prefix)
902 {
903         char text[256];
904         
905 #ifndef WIN32
906         struct tm *tl;
907         time_t t;
908 #else
909         char sdate[9];
910 #endif /* WIN32 */
911         
912         if (G.scene->r.stamp & R_STAMP_FILENAME) {
913                 if (G.relbase_valid) {
914                         if (do_prefix)          sprintf(stamp_data->file, "File %s", G.sce);
915                         else                            sprintf(stamp_data->file, "%s", G.sce);
916                 } else {
917                         if (do_prefix)          strcpy(stamp_data->file, "File <untitled>");
918                         else                            strcpy(stamp_data->file, "<untitled>");
919                 }
920                 stamp_data->note[0] = '\0';
921         } else {
922                 stamp_data->file[0] = '\0';
923         }
924         
925         if (G.scene->r.stamp & R_STAMP_NOTE) {
926                 /* Never do prefix for Note */
927                 sprintf(stamp_data->note, "%s", G.scene->r.stamp_udata);
928         } else {
929                 stamp_data->note[0] = '\0';
930         }
931         
932         if (G.scene->r.stamp & R_STAMP_DATE) {
933 #ifdef WIN32
934                 _strdate (sdate);
935                 sprintf (text, "%s", sdate);
936 #else
937                 t = time (NULL);
938                 tl = localtime (&t);
939                 sprintf (text, "%04d-%02d-%02d", tl->tm_year+1900, tl->tm_mon+1, tl->tm_mday);
940 #endif /* WIN32 */
941                 if (do_prefix)          sprintf(stamp_data->date, "Date %s", text);
942                 else                            sprintf(stamp_data->date, "%s", text);
943         } else {
944                 stamp_data->date[0] = '\0';
945         }
946         
947         if (G.scene->r.stamp & R_STAMP_MARKER) {
948                 TimeMarker *marker = get_frame_marker(CFRA);
949         
950                 if (marker) strcpy(text, marker->name);
951                 else            strcpy(text, "<none>");
952                 
953                 if (do_prefix)          sprintf(stamp_data->marker, "Marker %s", text);
954                 else                            sprintf(stamp_data->marker, "%s", text);
955         } else {
956                 stamp_data->marker[0] = '\0';
957         }
958         
959         if (G.scene->r.stamp & R_STAMP_TIME) {
960                 int h, m, s, f;
961                 h= m= s= f= 0;
962                 f = (int)(G.scene->r.cfra % G.scene->r.frs_sec);
963                 s = (int)(G.scene->r.cfra / G.scene->r.frs_sec);
964
965                 if (s) {
966                         m = (int)(s / 60);
967                         s %= 60;
968
969                         if (m) {
970                                 h = (int)(m / 60);
971                                 m %= 60;
972                         }
973                 }
974
975                 if (G.scene->r.frs_sec < 100)
976                         sprintf (text, "%02d:%02d:%02d.%02d", h, m, s, f);
977                 else
978                         sprintf (text, "%02d:%02d:%02d.%03d", h, m, s, f);
979                 
980                 if (do_prefix)          sprintf(stamp_data->time, "Time %s", text);
981                 else                            sprintf(stamp_data->time, "%s", text);
982         } else {
983                 stamp_data->time[0] = '\0';
984         }
985         
986         if (G.scene->r.stamp & R_STAMP_FRAME) {
987                 char format[32];
988                 if (do_prefix)          sprintf(format, "Frame %%0%di\n", 1 + (int) log10(G.scene->r.efra));
989                 else                            sprintf(format, "%%0%di\n", 1 + (int) log10(G.scene->r.efra));
990                 sprintf (stamp_data->frame, format, G.scene->r.cfra);
991         } else {
992                 stamp_data->frame[0] = '\0';
993         }
994
995         if (G.scene->r.stamp & R_STAMP_CAMERA) {
996                 if (G.scene->camera) strcpy(text, ((Camera *) G.scene->camera)->id.name+2);
997                 else            strcpy(text, "<none>");
998                 
999                 if (do_prefix)          sprintf(stamp_data->camera, "Camera %s", text);
1000                 else                            sprintf(stamp_data->camera, "%s", text);
1001         } else {
1002                 stamp_data->camera[0] = '\0';
1003         }
1004
1005         if (G.scene->r.stamp & R_STAMP_SCENE) {
1006                 if (do_prefix)          sprintf(stamp_data->scene, "Scene %s", G.scene->id.name+2);
1007                 else                            sprintf(stamp_data->scene, "%s", G.scene->id.name+2);
1008         } else {
1009                 stamp_data->scene[0] = '\0';
1010         }
1011         
1012         if (G.scene->r.stamp & R_STAMP_SEQSTRIP) {
1013                 Sequence *seq = get_forground_frame_seq(CFRA);
1014         
1015                 if (seq) strcpy(text, seq->name+2);
1016                 else            strcpy(text, "<none>");
1017                 
1018                 if (do_prefix)          sprintf(stamp_data->strip, "Strip %s", text);
1019                 else                            sprintf(stamp_data->strip, "%s", text);
1020         } else {
1021                 stamp_data->strip[0] = '\0';
1022         }
1023 }
1024
1025 void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height, int channels)
1026 {
1027         struct StampData stamp_data;
1028         
1029         int x=1,y=1;
1030         int font_height;
1031         int text_width;
1032         int text_pad;
1033         struct BMF_Font *font;
1034         
1035         if (!rect && !rectf)
1036                 return;
1037         
1038         stampdata(&stamp_data, 1);
1039         
1040         switch (G.scene->r.stamp_font_id) {
1041         case 1: /* tiny */
1042                 font = BMF_GetFont(BMF_kHelveticaBold8);
1043                 break;
1044         case 2: /* small */
1045                 font = BMF_GetFont(BMF_kHelveticaBold10);
1046                 break;
1047         case 3: /* medium */
1048                 font = BMF_GetFont(BMF_kScreen12);
1049                 break;
1050         case 0: /* large - default */
1051                 font = BMF_GetFont(BMF_kScreen15);
1052                 break;
1053         case 4: /* huge */
1054                 font = BMF_GetFont(BMF_kHelveticaBold14);
1055                 break;
1056         default:
1057                 font = NULL;
1058                 break;
1059         }
1060         
1061         font_height = BMF_GetFontHeight(font);
1062         /* All texts get halfspace+1 pixel on each side and 1 pix
1063         above and below as padding against their backing rectangles */
1064         text_pad = BMF_GetStringWidth(font, " ");
1065         
1066         x = 1; /* Inits for everyone, text position, so 1 for padding, not 0 */
1067         y = height - font_height - 1; /* Also inits for everyone, notice padding pixel */
1068         
1069         if (stamp_data.file[0]) {
1070                 /* Top left corner */
1071                 text_width = BMF_GetStringWidth(font, stamp_data.file);
1072                 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);
1073                 BMF_DrawStringBuf(font, stamp_data.file, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1074                 y -= font_height+2; /* Top and bottom 1 pix padding each */
1075         }
1076
1077         /* Top left corner, below File */
1078         if (stamp_data.note[0]) {
1079                 text_width = BMF_GetStringWidth(font, stamp_data.note);
1080                 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);
1081                 BMF_DrawStringBuf(font, stamp_data.note, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1082                 y -= font_height+2; /* Top and bottom 1 pix padding each */
1083         }
1084         
1085         /* Top left corner, below File (or Note) */
1086         if (stamp_data.date[0]) {
1087                 text_width = BMF_GetStringWidth(font, stamp_data.date);
1088                 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);
1089                 BMF_DrawStringBuf(font, stamp_data.date, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1090         }
1091
1092         /* Bottom left corner, leaving space for timing */
1093         if (stamp_data.marker[0]) {
1094                 x = 1;
1095                 y = font_height+2+1; /* 2 for padding in TIME|FRAME fields below and 1 for padding in this one */
1096                 text_width = BMF_GetStringWidth(font, stamp_data.marker);
1097                 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);
1098                 BMF_DrawStringBuf(font, stamp_data.marker, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1099         }
1100         
1101         /* Left bottom corner */
1102         if (stamp_data.time[0]) {
1103                 x = 1;
1104                 y = 1;
1105                 text_width = BMF_GetStringWidth(font, stamp_data.time);
1106                 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);
1107                 BMF_DrawStringBuf(font, stamp_data.time, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1108                 x += text_width+text_pad+2; /* Both sides have 1 pix additional padding each */
1109         }
1110         
1111         if (stamp_data.frame[0]) {
1112                 text_width = BMF_GetStringWidth(font, stamp_data.frame);
1113                 /* Left bottom corner (after SMPTE if exists) */
1114                 if (!stamp_data.time[0])        x = 1;
1115                 y = 1;
1116                 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);
1117                 BMF_DrawStringBuf(font, stamp_data.frame, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1118         }
1119
1120         if (stamp_data.camera[0]) {
1121                 text_width = BMF_GetStringWidth(font, stamp_data.camera);
1122                 /* Center of bottom edge */
1123                 x = (width/2) - (BMF_GetStringWidth(font, stamp_data.camera)/2);
1124                 y = 1;
1125                 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);
1126                 BMF_DrawStringBuf(font, stamp_data.camera, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1127         }
1128         
1129         if (stamp_data.scene[0]) {
1130                 text_width = BMF_GetStringWidth(font, stamp_data.scene);
1131                 /* Bottom right corner */
1132                 x = width - (text_width+1+text_pad);
1133                 y = 1;
1134                 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);
1135                 BMF_DrawStringBuf(font, stamp_data.scene, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1136         }
1137         
1138         if (stamp_data.strip[0]) {
1139                 text_width = BMF_GetStringWidth(font, stamp_data.strip);
1140                 /* Top right corner */
1141                 x = width - (text_width+1+text_pad);
1142                 y = height - font_height - 1;
1143                 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);
1144                 BMF_DrawStringBuf(font, stamp_data.strip, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1145         }
1146         
1147 }
1148
1149 void BKE_stamp_info(struct ImBuf *ibuf)
1150 {
1151         struct StampData stamp_data;
1152
1153         if (!ibuf)      return;
1154         
1155         /* fill all the data values, no prefix */
1156         stampdata(&stamp_data, 0);
1157         
1158         if (stamp_data.file[0])         IMB_imginfo_change_field (ibuf, "File",         stamp_data.file);
1159         if (stamp_data.note[0])         IMB_imginfo_change_field (ibuf, "Note",         stamp_data.note);
1160         if (stamp_data.date[0])         IMB_imginfo_change_field (ibuf, "Date",         stamp_data.date);
1161         if (stamp_data.marker[0])       IMB_imginfo_change_field (ibuf, "Marker",       stamp_data.marker);
1162         if (stamp_data.time[0])         IMB_imginfo_change_field (ibuf, "Time",         stamp_data.time);
1163         if (stamp_data.frame[0])        IMB_imginfo_change_field (ibuf, "Frame",        stamp_data.frame);
1164         if (stamp_data.camera[0])       IMB_imginfo_change_field (ibuf, "Camera",       stamp_data.camera);
1165         if (stamp_data.scene[0])        IMB_imginfo_change_field (ibuf, "Scene",        stamp_data.scene);
1166         if (stamp_data.strip[0])        IMB_imginfo_change_field (ibuf, "Strip",        stamp_data.strip);
1167 }
1168
1169 int BKE_write_ibuf(ImBuf *ibuf, char *name, int imtype, int subimtype, int quality)
1170 {
1171         int ok;
1172         
1173         if(imtype==0);
1174         else if(imtype== R_IRIS) 
1175                 ibuf->ftype= IMAGIC;
1176         else if ((imtype==R_RADHDR)) {
1177                 ibuf->ftype= RADHDR;
1178         }
1179         else if (imtype==R_PNG || imtype==R_FFMPEG) {
1180                 ibuf->ftype= PNG;
1181         }
1182 #ifdef WITH_DDS
1183         else if ((imtype==R_DDS)) {
1184                 ibuf->ftype= DDS;
1185         }
1186 #endif
1187         else if ((imtype==R_BMP)) {
1188                 ibuf->ftype= BMP;
1189         }
1190         else if ((G.have_libtiff) && (imtype==R_TIFF)) {
1191                 ibuf->ftype= TIF;
1192
1193                 if(subimtype & R_TIFF_16BIT)
1194                         ibuf->ftype |= TIF_16BIT;
1195         }
1196 #ifdef WITH_OPENEXR
1197         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
1198                 ibuf->ftype= OPENEXR;
1199                 if(subimtype & R_OPENEXR_HALF)
1200                         ibuf->ftype |= OPENEXR_HALF;
1201                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
1202                 
1203                 if(!(subimtype & R_OPENEXR_ZBUF))
1204                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1205                 
1206         }
1207 #endif
1208         else if (imtype==R_CINEON) {
1209                 ibuf->ftype = CINEON;
1210         }
1211         else if (imtype==R_DPX) {
1212                 ibuf->ftype = DPX;
1213         }
1214         else if (imtype==R_TARGA) {
1215                 ibuf->ftype= TGA;
1216         }
1217         else if(imtype==R_RAWTGA) {
1218                 ibuf->ftype= RAWTGA;
1219         }
1220         else if(imtype==R_HAMX) {
1221                 ibuf->ftype= AN_hamx;
1222         }
1223         else {
1224                 /* R_JPEG90, R_MOVIE, etc. default we save jpegs */
1225                 if(quality < 10) quality= 90;
1226                 ibuf->ftype= JPG|quality;
1227                 if(ibuf->depth==32) ibuf->depth= 24;    /* unsupported feature only confuses other s/w */
1228         }
1229         
1230         BLI_make_existing_file(name);
1231
1232         if(G.scene->r.scemode & R_STAMP_INFO)
1233                 BKE_stamp_info(ibuf);
1234         
1235         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1236         if (ok == 0) {
1237                 perror(name);
1238         }
1239         
1240         return(ok);
1241 }
1242
1243
1244 void BKE_makepicstring(char *string, char *base, int frame, int imtype)
1245 {
1246         if (string==NULL) return;
1247
1248         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1249         
1250         /* if we dont have any #'s to insert numbers into, use 4 numbers by default */
1251         if (strchr(string, '#')==NULL)
1252                 strcat(string, "####"); /* 4 numbers */
1253         
1254         BLI_convertstringcode(string, G.sce);
1255         BLI_convertstringframe(string, frame);
1256
1257         if(G.scene->r.scemode & R_EXTENSION) 
1258                 BKE_add_image_extension(string, imtype);
1259                 
1260 }
1261
1262 /* used by sequencer too */
1263 struct anim *openanim(char *name, int flags)
1264 {
1265         struct anim *anim;
1266         struct ImBuf *ibuf;
1267         
1268         anim = IMB_open_anim(name, flags);
1269         if (anim == NULL) return(0);
1270
1271         ibuf = IMB_anim_absolute(anim, 0);
1272         if (ibuf == NULL) {
1273                 printf("not an anim; %s\n", name);
1274                 IMB_free_anim(anim);
1275                 return(0);
1276         }
1277         IMB_freeImBuf(ibuf);
1278         
1279         return(anim);
1280 }
1281
1282 /* ************************* New Image API *************** */
1283
1284
1285 /* Notes about Image storage 
1286 - packedfile
1287   -> written in .blend
1288 - filename
1289   -> written in .blend
1290 - movie
1291   -> comes from packedfile or filename
1292 - renderresult
1293   -> comes from packedfile or filename
1294 - listbase
1295   -> ibufs from exrhandle
1296 - flipbook array
1297   -> ibufs come from movie, temporary renderresult or sequence
1298 - ibuf
1299   -> comes from packedfile or filename or generated
1300
1301 */
1302
1303
1304 /* forces existance of 1 Image for renderout or nodes, returns Image */
1305 /* name is only for default, when making new one */
1306 Image *BKE_image_verify_viewer(int type, const char *name)
1307 {
1308         Image *ima;
1309         
1310         for(ima=G.main->image.first; ima; ima= ima->id.next)
1311                 if(ima->source==IMA_SRC_VIEWER)
1312                         if(ima->type==type)
1313                                 break;
1314         
1315         if(ima==NULL)
1316                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1317         
1318         /* happens on reload, imagewindow cannot be image user when hidden*/
1319         if(ima->id.us==0)
1320                 id_us_plus(&ima->id);
1321
1322         return ima;
1323 }
1324
1325 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1326 {
1327         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1328 }
1329
1330 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1331 {
1332         if(ima==NULL)
1333                 return;
1334         
1335         switch(signal) {
1336         case IMA_SIGNAL_FREE:
1337                 image_free_buffers(ima);
1338                 if(iuser)
1339                         iuser->ok= 1;
1340                 break;
1341         case IMA_SIGNAL_SRC_CHANGE:
1342                 if(ima->type==IMA_TYPE_MULTILAYER)
1343                         image_free_buffers(ima);
1344                 else if(ima->source==IMA_SRC_GENERATED) {
1345                         if(ima->gen_x==0 || ima->gen_y==0) {
1346                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1347                                 if(ibuf) {
1348                                         ima->gen_x= ibuf->x;
1349                                         ima->gen_y= ibuf->y;
1350                                 }
1351                         }
1352                 }
1353                 ima->ok= 1;
1354                 if(iuser)
1355                         iuser->ok= 1;
1356                 break;
1357                         
1358         case IMA_SIGNAL_RELOAD:
1359                 /* try to repack file */
1360                 if(ima->packedfile) {
1361                         PackedFile *pf;
1362                         pf = newPackedFile(ima->name);
1363                         if (pf) {
1364                                 freePackedFile(ima->packedfile);
1365                                 ima->packedfile = pf;
1366                                 image_free_buffers(ima);
1367                         } else {
1368                                 printf("ERROR: Image not available. Keeping packed image\n");
1369                         }
1370                 }
1371                 else
1372                         image_free_buffers(ima);
1373                 
1374                 if(iuser)
1375                         iuser->ok= 1;
1376                 
1377                 break;
1378         case IMA_SIGNAL_USER_NEW_IMAGE:
1379                 if(iuser) {
1380                         iuser->ok= 1;
1381                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1382                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1383                                         iuser->multi_index= 0;
1384                                         iuser->layer= iuser->pass= 0;
1385                                 }
1386                         }
1387                 }
1388                 break;
1389         }
1390 }
1391
1392 /* if layer or pass changes, we need an index for the imbufs list */
1393 /* note it is called for rendered results, but it doesnt use the index! */
1394 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1395 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1396 {
1397         RenderLayer *rl;
1398         RenderPass *rpass= NULL;
1399         
1400         if(rr==NULL) 
1401                 return NULL;
1402         
1403         if(iuser) {
1404                 short index= 0, rl_index= 0, rp_index;
1405                 
1406                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1407                         rp_index= 0;
1408                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1409                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1410                                         break;
1411                         if(rpass)
1412                                 break;
1413                 }
1414                 
1415                 if(rpass)
1416                         iuser->multi_index= index;
1417                 else 
1418                         iuser->multi_index= 0;
1419         }
1420         if(rpass==NULL) {
1421                 rl= rr->layers.first;
1422                 if(rl)
1423                         rpass= rl->passes.first;
1424         }
1425         
1426         return rpass;
1427 }
1428
1429 RenderResult *BKE_image_get_renderresult(Image *ima)
1430 {
1431         if(ima->rr)
1432                 return ima->rr;
1433         if(ima->type==IMA_TYPE_R_RESULT)
1434                 return RE_GetResult(RE_GetRender(G.scene->id.name));
1435         return NULL;
1436 }
1437
1438 /* after imbuf load, openexr type can return with a exrhandle open */
1439 /* in that case we have to build a render-result */
1440 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1441 {
1442         
1443         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1444
1445 #ifdef WITH_OPENEXR
1446         IMB_exr_close(ibuf->userdata);
1447 #endif
1448
1449         ibuf->userdata= NULL;
1450         if(ima->rr)
1451                 ima->rr->framenr= framenr;
1452 }
1453
1454 /* common stuff to do with images after loading */
1455 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1456 {
1457         
1458         
1459         /* preview is NULL when it has never been used as an icon before */
1460         if(G.background==0 && ima->preview==NULL)
1461                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1462         
1463         /* stringcodes also in ibuf, ibuf->name is used to retrieve original (buttons) */
1464         BLI_strncpy(ibuf->name, ima->name, FILE_MAX);
1465         
1466         /* fields */
1467         if (ima->flag & IMA_FIELDS) {
1468                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1469                 else de_interlace_ng(ibuf);
1470         }
1471         /* timer */
1472         ima->lastused = clock() / CLOCKS_PER_SEC;
1473         
1474         ima->ok= IMA_OK_LOADED;
1475         
1476 }
1477
1478 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1479 {
1480         struct ImBuf *ibuf;
1481         unsigned short numlen;
1482         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1483         
1484         ima->lastframe= frame;
1485
1486         BLI_stringdec(ima->name, head, tail, &numlen);
1487         BLI_stringenc(ima->name, head, tail, numlen, frame);
1488         BLI_strncpy(name, ima->name, sizeof(name));
1489         
1490         if(ima->id.lib)
1491                 BLI_convertstringcode(name, ima->id.lib->filename);
1492         else
1493                 BLI_convertstringcode(name, G.sce);
1494         
1495         BLI_convertstringframe(name, frame); /* TODO - should this be here? */
1496         
1497         /* read ibuf */
1498         ibuf = IMB_loadiffname(name, IB_rect|IB_multilayer);
1499         if(G.f & G_DEBUG) printf("loaded %s\n", name);
1500         
1501         if (ibuf) {
1502 #ifdef WITH_OPENEXR
1503                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1504                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1505                         image_create_multilayer(ima, ibuf, frame);      
1506                         ima->type= IMA_TYPE_MULTILAYER;
1507                         IMB_freeImBuf(ibuf);
1508                         ibuf= NULL;
1509                 }
1510                 else {
1511                         image_initialize_after_load(ima, ibuf);
1512                         image_assign_ibuf(ima, ibuf, 0, frame);
1513                 }
1514 #else
1515                 image_initialize_after_load(ima, ibuf);
1516                 image_assign_ibuf(ima, ibuf, 0, frame);
1517 #endif
1518                 
1519                 if(ima->flag & IMA_DO_PREMUL)
1520                         converttopremul(ibuf);
1521                 
1522         }
1523         else
1524                 ima->ok= 0;
1525         
1526         if(iuser)
1527                 iuser->ok= ima->ok;
1528         
1529         return ibuf;
1530 }
1531
1532 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1533 {
1534         struct ImBuf *ibuf= NULL;
1535         
1536         /* either we load from RenderResult, or we have to load a new one */
1537         
1538         /* check for new RenderResult */
1539         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1540                 /* copy to survive not found multilayer image */
1541                 RenderResult *oldrr= ima->rr;
1542         
1543                 ima->rr= NULL;
1544                 ibuf = image_load_sequence_file(ima, iuser, frame);
1545                 
1546                 if(ibuf) { /* actually an error */
1547                         ima->type= IMA_TYPE_IMAGE;
1548                         printf("error, multi is normal image\n");
1549                 }
1550                 // printf("loaded new result %p\n", ima->rr);
1551                 /* free result if new one found */
1552                 if(ima->rr) {
1553                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1554                         if(oldrr) RE_FreeRenderResult(oldrr);
1555                 }
1556                 else {
1557                         ima->rr= oldrr;
1558                 }
1559
1560         }
1561         if(ima->rr) {
1562                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1563                 
1564                 if(rpass) {
1565                         // printf("load from pass %s\n", rpass->name);
1566                         /* since we free  render results, we copy the rect */
1567                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1568                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1569                         ibuf->flags |= IB_rectfloat;
1570                         ibuf->mall= IB_rectfloat;
1571                         ibuf->channels= rpass->channels;
1572                         
1573                         image_initialize_after_load(ima, ibuf);
1574                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:0, frame);
1575                         
1576                 }
1577                 // else printf("pass not found\n");
1578         }
1579         else
1580                 ima->ok= 0;
1581         
1582         if(iuser)
1583                 iuser->ok= ima->ok;
1584         
1585         return ibuf;
1586 }
1587
1588
1589 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
1590 {
1591         struct ImBuf *ibuf= NULL;
1592         
1593         ima->lastframe= frame;
1594         
1595         if(ima->anim==NULL) {
1596                 char str[FILE_MAX];
1597                 
1598                 BLI_strncpy(str, ima->name, FILE_MAX);
1599                 if(ima->id.lib)
1600                         BLI_convertstringcode(str, ima->id.lib->filename);
1601                 else
1602                         BLI_convertstringcode(str, G.sce);
1603                 
1604                 ima->anim = openanim(str, IB_cmap | IB_rect);
1605                 
1606                 /* let's initialize this user */
1607                 if(ima->anim && iuser && iuser->frames==0)
1608                         iuser->frames= IMB_anim_get_duration(ima->anim);
1609         }
1610         
1611         if(ima->anim) {
1612                 int dur = IMB_anim_get_duration(ima->anim);
1613                 int fra= frame-1;
1614                 
1615                 if(fra<0) fra = 0;
1616                 if(fra>(dur-1)) fra= dur-1;
1617                 ibuf = IMB_anim_absolute(ima->anim, fra);
1618                 
1619                 if(ibuf) {
1620                         image_initialize_after_load(ima, ibuf);
1621                         image_assign_ibuf(ima, ibuf, 0, frame);
1622                 }
1623                 else
1624                         ima->ok= 0;
1625         }
1626         else
1627                 ima->ok= 0;
1628         
1629         if(iuser)
1630                 iuser->ok= ima->ok;
1631         
1632         return ibuf;
1633 }
1634
1635 /* cfra used for # code, Image can only have this # for all its users */
1636 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
1637 {
1638         struct ImBuf *ibuf;
1639         char str[FILE_MAX];
1640         int assign = 0;
1641         
1642         /* always ensure clean ima */
1643         image_free_buffers(ima);
1644         
1645         /* is there a PackedFile with this image ? */
1646         if (ima->packedfile) {
1647                 ibuf = IMB_ibImageFromMemory((int *) ima->packedfile->data, ima->packedfile->size, IB_rect|IB_multilayer);
1648         } 
1649         else {
1650                         
1651                 /* get the right string */
1652                 BLI_strncpy(str, ima->name, sizeof(str));
1653                 if(ima->id.lib)
1654                         BLI_convertstringcode(str, ima->id.lib->filename);
1655                 else
1656                         BLI_convertstringcode(str, G.sce);
1657                 
1658                 BLI_convertstringframe(str, cfra);
1659                 
1660                 /* read ibuf */
1661                 ibuf = IMB_loadiffname(str, IB_rect|IB_multilayer|IB_imginfo);
1662         }
1663         
1664         if (ibuf) {
1665                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1666                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1667                         image_create_multilayer(ima, ibuf, cfra);       
1668                         ima->type= IMA_TYPE_MULTILAYER;
1669                         IMB_freeImBuf(ibuf);
1670                         ibuf= NULL;
1671                 }
1672                 else {
1673                         image_initialize_after_load(ima, ibuf);
1674                         assign= 1;
1675
1676                         /* check if the image is a font image... */
1677                         detectBitmapFont(ibuf);
1678                         
1679                         /* make packed file for autopack */
1680                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
1681                                 ima->packedfile = newPackedFile(str);
1682                 }
1683                 
1684                 if(ima->flag & IMA_DO_PREMUL)
1685                         converttopremul(ibuf);
1686         }
1687         else
1688                 ima->ok= 0;
1689         
1690         if(assign)
1691                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1692
1693         if(iuser)
1694                 iuser->ok= ima->ok;
1695         
1696         return ibuf;
1697 }
1698
1699 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
1700 {
1701         ImBuf *ibuf= NULL;
1702         
1703         if(ima->rr==NULL) {
1704                 ibuf = image_load_image_file(ima, iuser, 0);
1705                 if(ibuf) { /* actually an error */
1706                         ima->type= IMA_TYPE_IMAGE;
1707                         return ibuf;
1708                 }
1709         }
1710         if(ima->rr) {
1711                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1712
1713                 if(rpass) {
1714                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1715                         
1716                         image_initialize_after_load(ima, ibuf);
1717                         
1718                         ibuf->rect_float= rpass->rect;
1719                         ibuf->flags |= IB_rectfloat;
1720                         ibuf->channels= rpass->channels;
1721
1722                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1723                 }
1724         }
1725         
1726         if(ibuf==NULL) 
1727                 ima->ok= 0;
1728         if(iuser)
1729                 iuser->ok= ima->ok;
1730         
1731         return ibuf;
1732 }
1733
1734
1735 /* showing RGBA result itself (from compo/sequence) or
1736    like exr, using layers etc */
1737 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser)
1738 {
1739         RenderResult *rr= RE_GetResult(RE_GetRender(G.scene->id.name));
1740         
1741         if(rr) {
1742                 RenderResult rres;
1743                 float *rectf;
1744                 unsigned int *rect;
1745                 float dither;
1746                 int channels, layer, pass;
1747
1748                 channels= 4;
1749                 layer= (iuser)? iuser->layer: 0;
1750                 pass= (iuser)? iuser->pass: 0;
1751                 
1752                 /* this gives active layer, composite or seqence result */
1753                 RE_GetResultImage(RE_GetRender(G.scene->id.name), &rres);
1754                 rect= (unsigned int *)rres.rect32;
1755                 rectf= rres.rectf;
1756                 dither= G.scene->r.dither_intensity;
1757
1758                 /* get compo/seq result by default */
1759                 if(rr->rectf && layer==0);
1760                 else if(rr->layers.first) {
1761                         RenderLayer *rl= BLI_findlink(&rr->layers, layer-(rr->rectf?1:0));
1762                         if(rl) {
1763                                 /* there's no combined pass, is in renderlayer itself */
1764                                 if(pass==0) {
1765                                         rectf= rl->rectf;
1766                                 }
1767                                 else {
1768                                         RenderPass *rpass= BLI_findlink(&rl->passes, pass-1);
1769                                         if(rpass) {
1770                                                 channels= rpass->channels;
1771                                                 rectf= rpass->rect;
1772                                                 dither= 0.0f; /* don't dither passes */
1773                                         }
1774                                 }
1775                         }
1776                 }
1777                 
1778                 if(rectf || rect) {
1779                         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1780
1781                         /* make ibuf if needed, and initialize it */
1782                         if(ibuf==NULL) {
1783                                 ibuf= IMB_allocImBuf(rr->rectx, rr->recty, 32, 0, 0);
1784                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1785                         }
1786                         ibuf->x= rr->rectx;
1787                         ibuf->y= rr->recty;
1788                         
1789                         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
1790                                 imb_freerectImBuf(ibuf);
1791                         if(rect)
1792                                 ibuf->rect= rect;
1793                         
1794                         ibuf->rect_float= rectf;
1795                         ibuf->flags |= IB_rectfloat;
1796                         ibuf->channels= channels;
1797                         ibuf->zbuf_float= rres.rectz;
1798                         ibuf->flags |= IB_zbuffloat;
1799                         ibuf->dither= dither;
1800                         
1801                         ima->ok= IMA_OK_LOADED;
1802                         return ibuf;
1803                 }
1804         }
1805         
1806         return NULL;
1807 }
1808
1809 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
1810 {
1811         ImBuf *ibuf = NULL;
1812         int frame = 0, index = 0;
1813
1814         /* see if we already have an appropriate ibuf, with image source and type */
1815         if(ima->source==IMA_SRC_MOVIE) {
1816                 frame= iuser?iuser->framenr:ima->lastframe;
1817                 ibuf= image_get_ibuf(ima, 0, frame);
1818         }
1819         else if(ima->source==IMA_SRC_SEQUENCE) {
1820                 if(ima->type==IMA_TYPE_IMAGE) {
1821                         frame= iuser?iuser->framenr:ima->lastframe;
1822                         ibuf= image_get_ibuf(ima, 0, frame);
1823                 }
1824                 else if(ima->type==IMA_TYPE_MULTILAYER) {
1825                         frame= iuser?iuser->framenr:ima->lastframe;
1826                         index= iuser?iuser->multi_index:IMA_NO_INDEX;
1827                         ibuf= image_get_ibuf(ima, index, frame);
1828                 }
1829         }
1830         else if(ima->source==IMA_SRC_FILE) {
1831                 if(ima->type==IMA_TYPE_IMAGE)
1832                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1833                 else if(ima->type==IMA_TYPE_MULTILAYER)
1834                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1835         }
1836         else if(ima->source == IMA_SRC_GENERATED) {
1837                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1838         }
1839         else if(ima->source == IMA_SRC_VIEWER) {
1840                 if(ima->type==IMA_TYPE_R_RESULT) {
1841                         /* always verify entirely, not that this shouldn't happen
1842                          * during render anyway */
1843                 }
1844                 else if(ima->type==IMA_TYPE_COMPOSITE) {
1845                         frame= iuser?iuser->framenr:0;
1846                         ibuf= image_get_ibuf(ima, 0, frame);
1847                 }
1848         }
1849
1850         *frame_r = frame;
1851         *index_r = index;
1852
1853         return ibuf;
1854 }
1855
1856 /* Checks optional ImageUser and verifies/creates ImBuf. */
1857 /* returns ibuf */
1858 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
1859 {
1860         ImBuf *ibuf= NULL;
1861         float color[] = {0, 0, 0, 1};
1862         int frame= 0, index= 0;
1863
1864         /* This function is intended to be thread-safe. It postpones the mutex lock
1865          * until it needs to load the image, if the image is already there it
1866          * should just get the pointer and return. The reason is that a lot of mutex
1867          * locks appears to be very slow on certain multicore macs, causing a render
1868          * with image textures to actually slow down as more threads are used.
1869          *
1870          * Note that all the image loading functions should also make sure they do
1871          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
1872          * That means, the last two steps must be, 1) add the ibuf to the list and
1873          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
1874
1875         /* quick reject tests */
1876         if(ima==NULL) 
1877                 return NULL;
1878         if(iuser) {
1879                 if(iuser->ok==0)
1880                         return NULL;
1881         }
1882         else if(ima->ok==0)
1883                 return NULL;
1884         
1885         /* try to get the ibuf without locking */
1886         ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
1887
1888         if(ibuf == NULL) {
1889                 /* couldn't get ibuf and image is not ok, so let's lock and try to
1890                  * load the image */
1891                 BLI_lock_thread(LOCK_IMAGE);
1892
1893                 /* need to check ok flag and loading ibuf again, because the situation
1894                  * might have changed in the meantime */
1895                 if(iuser) {
1896                         if(iuser->ok==0) {
1897                                 BLI_unlock_thread(LOCK_IMAGE);
1898                                 return NULL;
1899                         }
1900                 }
1901                 else if(ima->ok==0) {
1902                         BLI_unlock_thread(LOCK_IMAGE);
1903                         return NULL;
1904                 }
1905
1906                 ibuf= image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
1907
1908                 if(ibuf == NULL) {
1909                         /* we are sure we have to load the ibuf, using source and type */
1910                         if(ima->source==IMA_SRC_MOVIE) {
1911                                 /* source is from single file, use flipbook to store ibuf */
1912                                 ibuf= image_load_movie_file(ima, iuser, frame);
1913                         }
1914                         else if(ima->source==IMA_SRC_SEQUENCE) {
1915                                 if(ima->type==IMA_TYPE_IMAGE) {
1916                                         /* regular files, ibufs in flipbook, allows saving */
1917                                         ibuf= image_load_sequence_file(ima, iuser, frame);
1918                                 }
1919                                 /* no else; on load the ima type can change */
1920                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1921                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
1922                                         ibuf= image_load_sequence_multilayer(ima, iuser, frame);
1923                                 }
1924
1925                                 if(ibuf)
1926                                         BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
1927                         }
1928                         else if(ima->source==IMA_SRC_FILE) {
1929                                 
1930                                 if(ima->type==IMA_TYPE_IMAGE)
1931                                         ibuf= image_load_image_file(ima, iuser, G.scene->r.cfra);       /* cfra only for '#', this global is OK */
1932                                 /* no else; on load the ima type can change */
1933                                 if(ima->type==IMA_TYPE_MULTILAYER)
1934                                         /* keeps render result, stores ibufs in listbase, allows saving */
1935                                         ibuf= image_get_ibuf_multilayer(ima, iuser);
1936                                         
1937                         }
1938                         else if(ima->source == IMA_SRC_GENERATED) {
1939                                 /* generated is: ibuf is allocated dynamically */
1940                                 if(ima->type==IMA_TYPE_VERSE) {
1941                                         /* todo */
1942                                 }
1943                                 else { /* always fall back to IMA_TYPE_UV_TEST */
1944                                         /* UV testgrid or black or solid etc */
1945                                         if(ima->gen_x==0) ima->gen_x= 256;
1946                                         if(ima->gen_y==0) ima->gen_y= 256;
1947                                         ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 0, ima->gen_type, color);
1948                                         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1949                                         ima->ok= IMA_OK_LOADED;
1950                                 }
1951                         }
1952                         else if(ima->source == IMA_SRC_VIEWER) {
1953                                 if(ima->type==IMA_TYPE_R_RESULT) {
1954                                         /* always verify entirely */
1955                                         ibuf= image_get_render_result(ima, iuser);
1956                                 }
1957                                 else if(ima->type==IMA_TYPE_COMPOSITE) {
1958                                         /* Composite Viewer, all handled in compositor */
1959                                         /* fake ibuf, will be filled in compositor */
1960                                         ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
1961                                         image_assign_ibuf(ima, ibuf, 0, frame);
1962                                 }
1963                         }
1964                 }
1965
1966                 BLI_unlock_thread(LOCK_IMAGE);
1967         }
1968
1969         /* we assuming that if it is not rendering, it's also not multithreaded
1970          * (a somewhat weak assumption) */
1971         if(G.rendering==0)
1972                 tag_image_time(ima);
1973
1974         return ibuf;
1975 }
1976
1977
1978 void BKE_image_user_calc_imanr(ImageUser *iuser, int cfra, int fieldnr)
1979 {
1980         int imanr, len;
1981         
1982         /* here (+fie_ima/2-1) makes sure that division happens correctly */
1983         len= (iuser->fie_ima*iuser->frames)/2;
1984         
1985         if(len==0) {
1986                 iuser->framenr= 0;
1987         }
1988         else {
1989                 cfra= cfra - iuser->sfra+1;
1990                 
1991                 /* cyclic */
1992                 if(iuser->cycl) {
1993                         cfra= ( (cfra) % len );
1994                         if(cfra < 0) cfra+= len;
1995                         if(cfra==0) cfra= len;
1996                 }
1997                 
1998                 if(cfra<1) cfra= 1;
1999                 else if(cfra>len) cfra= len;
2000                 
2001                 /* convert current frame to current field */
2002                 cfra= 2*(cfra);
2003                 if(fieldnr) cfra++;
2004                 
2005                 /* transform to images space */
2006                 imanr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
2007                 if(imanr>iuser->frames) imanr= iuser->frames;
2008                 imanr+= iuser->offset;
2009                 
2010                 if(iuser->cycl) {
2011                         imanr= ( (imanr) % len );
2012                         while(imanr < 0) imanr+= len;
2013                         if(imanr==0) imanr= len;
2014                 }
2015         
2016                 /* allows image users to handle redraws */
2017                 if(iuser->flag & IMA_ANIM_ALWAYS)
2018                         if(imanr!=iuser->framenr)
2019                                 iuser->flag |= IMA_ANIM_REFRESHED;
2020                 
2021                 iuser->framenr= imanr;
2022                 if(iuser->ok==0) iuser->ok= 1;
2023         }
2024 }
2025