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