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