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