Changed BLI_convertstringcode to replace any number of hashes with the frame number.
[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
250         image_free_buffers(ima);
251         if (ima->packedfile) {
252                 freePackedFile(ima->packedfile);
253                 ima->packedfile = NULL;
254         }
255         BKE_icon_delete(&ima->id);
256         ima->id.icon_id = 0;
257         if (ima->preview) {
258                 BKE_previewimg_free(&ima->preview);
259         }
260         
261 }
262
263 /* only image block itself */
264 static Image *image_alloc(const char *name, short source, short type)
265 {
266         Image *ima;
267         
268         ima= alloc_libblock(&G.main->image, ID_IM, name);
269         if(ima) {
270                 ima->ok= IMA_OK;
271                 
272                 ima->xrep= ima->yrep= 1;
273                 ima->aspx= ima->aspy= 1.0;
274                 ima->gen_x= 256; ima->gen_y= 256;
275                 ima->gen_type= 1;       /* no defines yet? */
276                 
277                 ima->source= source;
278                 ima->type= type;
279         }
280         return ima;
281 }
282
283 /* get the ibuf from an image cache, local use here only */
284 static ImBuf *image_get_ibuf(Image *ima, int index, int frame)
285 {
286         if(index==IMA_NO_INDEX)
287                 return ima->ibufs.first;
288         else {
289                 ImBuf *ibuf;
290                 
291                 index= IMA_MAKE_INDEX(frame, index);
292                 for(ibuf= ima->ibufs.first; ibuf; ibuf= ibuf->next)
293                         if(ibuf->index==index)
294                                 return ibuf;
295                 return NULL;
296         }
297 }
298
299 /* no ima->ibuf anymore, but listbase */
300 static void image_remove_ibuf(Image *ima, ImBuf *ibuf)
301 {
302         if(ibuf) {
303                 BLI_remlink(&ima->ibufs, ibuf);
304                 IMB_freeImBuf(ibuf);
305         }
306 }
307
308
309 /* no ima->ibuf anymore, but listbase */
310 static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int frame)
311 {
312         if(ibuf) {
313                 ImBuf *link;
314                 
315                 if(index!=IMA_NO_INDEX)
316                         index= IMA_MAKE_INDEX(frame, index);
317                 
318                 /* insert based on index */
319                 for(link= ima->ibufs.first; link; link= link->next)
320                         if(link->index>=index)
321                                 break;
322                 /* now we don't want copies? */
323                 if(link && ibuf->index==link->index) {
324                         ImBuf *prev= ibuf->prev;
325                         image_remove_ibuf(ima, link);
326                         link= prev;
327                 }
328                 
329                 /* this function accepts link==NULL */
330                 BLI_insertlinkbefore(&ima->ibufs, link, ibuf);
331                 
332                 ibuf->index= index;
333         }
334         
335 }
336
337 /* checks if image was already loaded, then returns same image */
338 /* otherwise creates new. */
339 /* does not load ibuf itself */
340 Image *BKE_add_image_file(const char *name)
341 {
342         Image *ima;
343         int file, len;
344         const char *libname;
345         char str[FILE_MAX], strtest[FILE_MAX];
346         
347         /* escape when name is directory */
348         len= strlen(name);
349         if(len) {
350                 if(name[len-1]=='/' || name[len-1]=='\\')
351                         return NULL;
352         }
353         
354         BLI_strncpy(str, name, sizeof(str));
355         BLI_convertstringcode(str, G.sce, G.scene->r.cfra);
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, G.scene->r.cfra);
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, frame);
1248
1249         if(G.scene->r.scemode & R_EXTENSION) 
1250                 BKE_add_image_extension(string, imtype);
1251                 
1252 }
1253
1254 /* used by sequencer too */
1255 struct anim *openanim(char *name, int flags)
1256 {
1257         struct anim *anim;
1258         struct ImBuf *ibuf;
1259         
1260         anim = IMB_open_anim(name, flags);
1261         if (anim == NULL) return(0);
1262
1263         ibuf = IMB_anim_absolute(anim, 0);
1264         if (ibuf == NULL) {
1265                 printf("not an anim; %s\n", name);
1266                 IMB_free_anim(anim);
1267                 return(0);
1268         }
1269         IMB_freeImBuf(ibuf);
1270         
1271         return(anim);
1272 }
1273
1274 /* ************************* New Image API *************** */
1275
1276
1277 /* Notes about Image storage 
1278 - packedfile
1279   -> written in .blend
1280 - filename
1281   -> written in .blend
1282 - movie
1283   -> comes from packedfile or filename
1284 - renderresult
1285   -> comes from packedfile or filename
1286 - listbase
1287   -> ibufs from exrhandle
1288 - flipbook array
1289   -> ibufs come from movie, temporary renderresult or sequence
1290 - ibuf
1291   -> comes from packedfile or filename or generated
1292
1293 */
1294
1295
1296 /* forces existance of 1 Image for renderout or nodes, returns Image */
1297 /* name is only for default, when making new one */
1298 Image *BKE_image_verify_viewer(int type, const char *name)
1299 {
1300         Image *ima;
1301         
1302         for(ima=G.main->image.first; ima; ima= ima->id.next)
1303                 if(ima->source==IMA_SRC_VIEWER)
1304                         if(ima->type==type)
1305                                 break;
1306         
1307         if(ima==NULL)
1308                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1309         
1310         /* happens on reload, imagewindow cannot be image user when hidden*/
1311         if(ima->id.us==0)
1312                 id_us_plus(&ima->id);
1313
1314         return ima;
1315 }
1316
1317 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1318 {
1319         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1320 }
1321
1322 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1323 {
1324         if(ima==NULL)
1325                 return;
1326         
1327         switch(signal) {
1328         case IMA_SIGNAL_FREE:
1329                 image_free_buffers(ima);
1330                 if(iuser)
1331                         iuser->ok= 1;
1332                 break;
1333         case IMA_SIGNAL_SRC_CHANGE:
1334                 if(ima->type==IMA_TYPE_MULTILAYER)
1335                         image_free_buffers(ima);
1336                 else if(ima->source==IMA_SRC_GENERATED) {
1337                         if(ima->gen_x==0 || ima->gen_y==0) {
1338                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1339                                 if(ibuf) {
1340                                         ima->gen_x= ibuf->x;
1341                                         ima->gen_y= ibuf->y;
1342                                 }
1343                         }
1344                 }
1345                 ima->ok= 1;
1346                 if(iuser)
1347                         iuser->ok= 1;
1348                 break;
1349                         
1350         case IMA_SIGNAL_RELOAD:
1351                 /* try to repack file */
1352                 if(ima->packedfile) {
1353                         PackedFile *pf;
1354                         pf = newPackedFile(ima->name);
1355                         if (pf) {
1356                                 freePackedFile(ima->packedfile);
1357                                 ima->packedfile = pf;
1358                                 image_free_buffers(ima);
1359                         } else {
1360                                 printf("ERROR: Image not available. Keeping packed image\n");
1361                         }
1362                 }
1363                 else
1364                         image_free_buffers(ima);
1365                 
1366                 if(iuser)
1367                         iuser->ok= 1;
1368                 
1369                 break;
1370         case IMA_SIGNAL_USER_NEW_IMAGE:
1371                 if(iuser) {
1372                         iuser->ok= 1;
1373                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1374                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1375                                         iuser->multi_index= 0;
1376                                         iuser->layer= iuser->pass= 0;
1377                                 }
1378                         }
1379                 }
1380                 break;
1381         }
1382 }
1383
1384 /* if layer or pass changes, we need an index for the imbufs list */
1385 /* note it is called for rendered results, but it doesnt use the index! */
1386 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1387 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1388 {
1389         RenderLayer *rl;
1390         RenderPass *rpass= NULL;
1391         
1392         if(rr==NULL) 
1393                 return NULL;
1394         
1395         if(iuser) {
1396                 short index= 0, rl_index= 0, rp_index;
1397                 
1398                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1399                         rp_index= 0;
1400                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1401                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1402                                         break;
1403                         if(rpass)
1404                                 break;
1405                 }
1406                 
1407                 if(rpass)
1408                         iuser->multi_index= index;
1409                 else 
1410                         iuser->multi_index= 0;
1411         }
1412         if(rpass==NULL) {
1413                 rl= rr->layers.first;
1414                 if(rl)
1415                         rpass= rl->passes.first;
1416         }
1417         
1418         return rpass;
1419 }
1420
1421 RenderResult *BKE_image_get_renderresult(Image *ima)
1422 {
1423         if(ima->rr)
1424                 return ima->rr;
1425         if(ima->type==IMA_TYPE_R_RESULT)
1426                 return RE_GetResult(RE_GetRender(G.scene->id.name));
1427         return NULL;
1428 }
1429
1430 /* after imbuf load, openexr type can return with a exrhandle open */
1431 /* in that case we have to build a render-result */
1432 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1433 {
1434         
1435         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1436
1437 #ifdef WITH_OPENEXR
1438         IMB_exr_close(ibuf->userdata);
1439 #endif
1440
1441         ibuf->userdata= NULL;
1442         if(ima->rr)
1443                 ima->rr->framenr= framenr;
1444 }
1445
1446 /* common stuff to do with images after loading */
1447 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1448 {
1449         
1450         
1451         /* preview is NULL when it has never been used as an icon before */
1452         if(G.background==0 && ima->preview==NULL)
1453                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1454         
1455         /* stringcodes also in ibuf, ibuf->name is used to retrieve original (buttons) */
1456         BLI_strncpy(ibuf->name, ima->name, FILE_MAX);
1457         
1458         /* fields */
1459         if (ima->flag & IMA_FIELDS) {
1460                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1461                 else de_interlace_ng(ibuf);
1462         }
1463         /* timer */
1464         ima->lastused = clock() / CLOCKS_PER_SEC;
1465         
1466         ima->ok= IMA_OK_LOADED;
1467         
1468 }
1469
1470 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1471 {
1472         struct ImBuf *ibuf;
1473         unsigned short numlen;
1474         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1475         
1476         ima->lastframe= frame;
1477
1478         BLI_stringdec(ima->name, head, tail, &numlen);
1479         BLI_stringenc(ima->name, head, tail, numlen, frame);
1480         BLI_strncpy(name, ima->name, sizeof(name));
1481         
1482         if(ima->id.lib)
1483                 BLI_convertstringcode(name, ima->id.lib->filename, frame);
1484         else
1485                 BLI_convertstringcode(name, G.sce, frame);
1486         
1487         /* read ibuf */
1488         ibuf = IMB_loadiffname(name, IB_rect|IB_multilayer);
1489         if(G.f & G_DEBUG) printf("loaded %s\n", name);
1490         
1491         if (ibuf) {
1492 #ifdef WITH_OPENEXR
1493                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1494                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1495                         image_create_multilayer(ima, ibuf, frame);      
1496                         ima->type= IMA_TYPE_MULTILAYER;
1497                         IMB_freeImBuf(ibuf);
1498                         ibuf= NULL;
1499                 }
1500                 else {
1501                         image_assign_ibuf(ima, ibuf, 0, frame);
1502                         image_initialize_after_load(ima, ibuf);
1503                 }
1504 #else
1505                 image_assign_ibuf(ima, ibuf, 0, frame);
1506                 image_initialize_after_load(ima, ibuf);
1507 #endif
1508         }
1509         else
1510                 ima->ok= 0;
1511         
1512         if(iuser)
1513                 iuser->ok= ima->ok;
1514         
1515         return ibuf;
1516 }
1517
1518 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1519 {
1520         struct ImBuf *ibuf= NULL;
1521         
1522         /* either we load from RenderResult, or we have to load a new one */
1523         
1524         /* check for new RenderResult */
1525         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1526                 /* copy to survive not found multilayer image */
1527                 RenderResult *oldrr= ima->rr;
1528         
1529                 ima->rr= NULL;
1530                 ibuf = image_load_sequence_file(ima, iuser, frame);
1531                 
1532                 if(ibuf) { /* actually an error */
1533                         ima->type= IMA_TYPE_IMAGE;
1534                         printf("error, multi is normal image\n");
1535                 }
1536                 // printf("loaded new result %p\n", ima->rr);
1537                 /* free result if new one found */
1538                 if(ima->rr) {
1539                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1540                         if(oldrr) RE_FreeRenderResult(oldrr);
1541                 }
1542                 else
1543                         ima->rr= oldrr;
1544
1545         }
1546         if(ima->rr) {
1547                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1548                 
1549                 if(rpass) {
1550                         // printf("load from pass %s\n", rpass->name);
1551                         /* since we free  render results, we copy the rect */
1552                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1553                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1554                         ibuf->flags |= IB_rectfloat;
1555                         ibuf->mall= IB_rectfloat;
1556                         ibuf->channels= rpass->channels;
1557                         
1558                         image_assign_ibuf(ima, ibuf, iuser->multi_index, frame);
1559                         image_initialize_after_load(ima, ibuf);
1560                         
1561                 }
1562                 // else printf("pass not found\n");
1563         }
1564         else
1565                 ima->ok= 0;
1566         
1567         if(iuser)
1568                 iuser->ok= ima->ok;
1569         
1570         return ibuf;
1571 }
1572
1573
1574 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
1575 {
1576         struct ImBuf *ibuf= NULL;
1577         
1578         ima->lastframe= frame;
1579         
1580         if(ima->anim==NULL) {
1581                 char str[FILE_MAX];
1582                 
1583                 BLI_strncpy(str, ima->name, FILE_MAX);
1584                 if(ima->id.lib)
1585                         BLI_convertstringcode(str, ima->id.lib->filename, 0);
1586                 else
1587                         BLI_convertstringcode(str, G.sce, 0);
1588                 
1589                 ima->anim = openanim(str, IB_cmap | IB_rect);
1590                 
1591                 /* let's initialize this user */
1592                 if(ima->anim && iuser && iuser->frames==0)
1593                         iuser->frames= IMB_anim_get_duration(ima->anim);
1594         }
1595         
1596         if(ima->anim) {
1597                 int dur = IMB_anim_get_duration(ima->anim);
1598                 int fra= frame-1;
1599                 
1600                 if(fra<0) fra = 0;
1601                 if(fra>(dur-1)) fra= dur-1;
1602                 ibuf = IMB_anim_absolute(ima->anim, fra);
1603                 
1604                 if(ibuf) {
1605                         image_assign_ibuf(ima, ibuf, 0, frame);
1606                         image_initialize_after_load(ima, ibuf);
1607                 }
1608                 else
1609                         ima->ok= 0;
1610         }
1611         else
1612                 ima->ok= 0;
1613         
1614         if(iuser)
1615                 iuser->ok= ima->ok;
1616         
1617         return ibuf;
1618 }
1619
1620 /* cfra used for # code, Image can only have this # for all its users */
1621 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
1622 {
1623         struct ImBuf *ibuf;
1624         char str[FILE_MAX];
1625         
1626         /* always ensure clean ima */
1627         image_free_buffers(ima);
1628         
1629         /* is there a PackedFile with this image ? */
1630         if (ima->packedfile) {
1631                 ibuf = IMB_ibImageFromMemory((int *) ima->packedfile->data, ima->packedfile->size, IB_rect|IB_multilayer);
1632         } 
1633         else {
1634                         
1635                 /* get the right string */
1636                 BLI_strncpy(str, ima->name, sizeof(str));
1637                 if(ima->id.lib)
1638                         BLI_convertstringcode(str, ima->id.lib->filename, cfra);
1639                 else
1640                         BLI_convertstringcode(str, G.sce, cfra);
1641                 
1642                 /* read ibuf */
1643                 ibuf = IMB_loadiffname(str, IB_rect|IB_multilayer|IB_imginfo);
1644         }
1645         
1646         if (ibuf) {
1647                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1648                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1649                         image_create_multilayer(ima, ibuf, cfra);       
1650                         ima->type= IMA_TYPE_MULTILAYER;
1651                         IMB_freeImBuf(ibuf);
1652                         ibuf= NULL;
1653                 }
1654                 else {
1655                         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1656                         image_initialize_after_load(ima, ibuf);
1657
1658                         /* check if the image is a font image... */
1659                         detectBitmapFont(ibuf);
1660                         
1661                         /* make packed file for autopack */
1662                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
1663                                 ima->packedfile = newPackedFile(str);
1664                 }
1665                 
1666                 if(ima->flag & IMA_DO_PREMUL)
1667                         converttopremul(ibuf);
1668         }
1669         else
1670                 ima->ok= 0;
1671         
1672         if(iuser)
1673                 iuser->ok= ima->ok;
1674         
1675         return ibuf;
1676 }
1677
1678 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
1679 {
1680         ImBuf *ibuf= NULL;
1681         
1682         if(ima->rr==NULL) {
1683                 ibuf = image_load_image_file(ima, iuser, 0);
1684                 if(ibuf) { /* actually an error */
1685                         ima->type= IMA_TYPE_IMAGE;
1686                         return ibuf;
1687                 }
1688         }
1689         if(ima->rr) {
1690                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1691
1692                 if(rpass) {
1693                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1694                         
1695                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1696                         image_initialize_after_load(ima, ibuf);
1697                         
1698                         ibuf->rect_float= rpass->rect;
1699                         ibuf->flags |= IB_rectfloat;
1700                         ibuf->channels= rpass->channels;
1701                 }
1702         }
1703         
1704         if(ibuf==NULL) 
1705                 ima->ok= 0;
1706         if(iuser)
1707                 iuser->ok= ima->ok;
1708         
1709         return ibuf;
1710 }
1711
1712
1713 /* showing RGBA result itself (from compo/sequence) or
1714    like exr, using layers etc */
1715 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser)
1716 {
1717         RenderResult *rr= RE_GetResult(RE_GetRender(G.scene->id.name));
1718         
1719         if(rr && iuser) {
1720                 RenderResult rres;
1721                 float *rectf;
1722                 unsigned int *rect;
1723                 int channels= 4, layer= iuser->layer;
1724                 
1725                 /* this gives active layer, composite or seqence result */
1726                 RE_GetResultImage(RE_GetRender(G.scene->id.name), &rres);
1727                 rect= (unsigned int *)rres.rect32;
1728                 rectf= rres.rectf;
1729                 
1730                 /* get compo/seq result by default */
1731                 if(rr->rectf && layer==0);
1732                 else if(rr->layers.first) {
1733                         RenderLayer *rl= BLI_findlink(&rr->layers, iuser->layer-(rr->rectf?1:0));
1734                         if(rl) {
1735                                 /* there's no combined pass, is in renderlayer itself */
1736                                 if(iuser->pass==0) {
1737                                         rectf= rl->rectf;
1738                                 }
1739                                 else {
1740                                         RenderPass *rpass= BLI_findlink(&rl->passes, iuser->pass-1);
1741                                         if(rpass) {
1742                                                 channels= rpass->channels;
1743                                                 rectf= rpass->rect;
1744                                         }
1745                                 }
1746                         }
1747                 }
1748                 
1749                 if(rectf || rect) {
1750                         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1751
1752                         /* make ibuf if needed, and initialize it */
1753                         if(ibuf==NULL) {
1754                                 ibuf= IMB_allocImBuf(rr->rectx, rr->recty, 32, 0, 0);
1755                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1756                         }
1757                         ibuf->x= rr->rectx;
1758                         ibuf->y= rr->recty;
1759                         
1760                         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
1761                                 imb_freerectImBuf(ibuf);
1762                         if(rect)
1763                                 ibuf->rect= rect;
1764                         
1765                         ibuf->rect_float= rectf;
1766                         ibuf->flags |= IB_rectfloat;
1767                         ibuf->channels= channels;
1768                         ibuf->zbuf_float= rres.rectz;
1769                         ibuf->flags |= IB_zbuffloat;
1770                         
1771                         ima->ok= IMA_OK_LOADED;
1772                         return ibuf;
1773                 }
1774         }
1775         
1776         return NULL;
1777 }
1778
1779 /* Checks optional ImageUser and verifies/creates ImBuf. */
1780 /* returns ibuf */
1781 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
1782 {
1783         ImBuf *ibuf= NULL;
1784         float color[] = {0, 0, 0, 1};
1785
1786         /* quick reject tests */
1787         if(ima==NULL) 
1788                 return NULL;
1789         if(iuser) {
1790                 if(iuser->ok==0)
1791                         return NULL;
1792         }
1793         else if(ima->ok==0)
1794                 return NULL;
1795         
1796         BLI_lock_thread(LOCK_IMAGE);
1797         
1798         /* handle image source and types */
1799         if(ima->source==IMA_SRC_MOVIE) {
1800                 /* source is from single file, use flipbook to store ibuf */
1801                 int frame= iuser?iuser->framenr:ima->lastframe;
1802                 
1803                 ibuf= image_get_ibuf(ima, 0, frame);
1804                 if(ibuf==NULL)
1805                         ibuf= image_load_movie_file(ima, iuser, frame);
1806         }
1807         else if(ima->source==IMA_SRC_SEQUENCE) {
1808                 
1809                 if(ima->type==IMA_TYPE_IMAGE) {
1810                         /* regular files, ibufs in flipbook, allows saving */
1811                         int frame= iuser?iuser->framenr:ima->lastframe;
1812                         
1813                         ibuf= image_get_ibuf(ima, 0, frame);
1814                         if(ibuf==NULL)
1815                                 ibuf= image_load_sequence_file(ima, iuser, frame);
1816                         else
1817                                 BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
1818                 }
1819                 /* no else; on load the ima type can change */
1820                 if(ima->type==IMA_TYPE_MULTILAYER) {
1821                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
1822                         int frame= iuser?iuser->framenr:ima->lastframe;
1823                         int index= iuser?iuser->multi_index:IMA_NO_INDEX;
1824                         
1825                         ibuf= image_get_ibuf(ima, index, frame);
1826                         if(G.rt) printf("seq multi fra %d id %d ibuf %p %s\n", frame, index, ibuf, ima->id.name);
1827                         if(ibuf==NULL)
1828                                 ibuf= image_load_sequence_multilayer(ima, iuser, frame);
1829                         else
1830                                 BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
1831                 }
1832
1833         }
1834         else if(ima->source==IMA_SRC_FILE) {
1835                 
1836                 if(ima->type==IMA_TYPE_IMAGE) {
1837                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1838                         if(ibuf==NULL)
1839                                 ibuf= image_load_image_file(ima, iuser, G.scene->r.cfra);       /* cfra only for '#', this global is OK */
1840                 }
1841                 /* no else; on load the ima type can change */
1842                 if(ima->type==IMA_TYPE_MULTILAYER) {
1843                         /* keeps render result, stores ibufs in listbase, allows saving */
1844                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1845                         if(ibuf==NULL)
1846                                 ibuf= image_get_ibuf_multilayer(ima, iuser);
1847                 }
1848                         
1849         }
1850         else if(ima->source == IMA_SRC_GENERATED) {
1851                 /* generated is: ibuf is allocated dynamically */
1852                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1853                 
1854                 if(ibuf==NULL) {
1855                         if(ima->type==IMA_TYPE_VERSE) {
1856                                 /* todo */
1857                         }
1858                         else { /* always fall back to IMA_TYPE_UV_TEST */
1859                                 /* UV testgrid or black or solid etc */
1860                                 if(ima->gen_x==0) ima->gen_x= 256;
1861                                 if(ima->gen_y==0) ima->gen_y= 256;
1862                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 0, ima->gen_type, color);
1863                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1864                                 ima->ok= IMA_OK_LOADED;
1865                         }
1866                 }
1867         }
1868         else if(ima->source == IMA_SRC_VIEWER) {
1869                 if(ima->type==IMA_TYPE_R_RESULT) {
1870                         /* always verify entirely */
1871                         ibuf= image_get_render_result(ima, iuser);
1872                 }
1873                 else if(ima->type==IMA_TYPE_COMPOSITE) {
1874                         int frame= iuser?iuser->framenr:0;
1875                         
1876                         /* Composite Viewer, all handled in compositor */
1877                         ibuf= image_get_ibuf(ima, 0, frame);
1878                         if(ibuf==NULL) {
1879                                 /* fake ibuf, will be filled in compositor */
1880                                 ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
1881                                 image_assign_ibuf(ima, ibuf, 0, frame);
1882                         }
1883                 }
1884         }
1885
1886         if(G.rendering==0)
1887                 tag_image_time(ima);
1888
1889         BLI_unlock_thread(LOCK_IMAGE);
1890
1891         return ibuf;
1892 }
1893
1894
1895 void BKE_image_user_calc_imanr(ImageUser *iuser, int cfra, int fieldnr)
1896 {
1897         int imanr, len;
1898         
1899         /* here (+fie_ima/2-1) makes sure that division happens correctly */
1900         len= (iuser->fie_ima*iuser->frames)/2;
1901         
1902         if(len==0) {
1903                 iuser->framenr= 0;
1904         }
1905         else {
1906                 cfra= cfra - iuser->sfra+1;
1907                 
1908                 /* cyclic */
1909                 if(iuser->cycl) {
1910                         cfra= ( (cfra) % len );
1911                         if(cfra < 0) cfra+= len;
1912                         if(cfra==0) cfra= len;
1913                 }
1914                 
1915                 if(cfra<1) cfra= 1;
1916                 else if(cfra>len) cfra= len;
1917                 
1918                 /* convert current frame to current field */
1919                 cfra= 2*(cfra);
1920                 if(fieldnr) cfra++;
1921                 
1922                 /* transform to images space */
1923                 imanr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
1924                 if(imanr>iuser->frames) imanr= iuser->frames;
1925                 imanr+= iuser->offset;
1926                 
1927                 if(iuser->cycl) {
1928                         imanr= ( (imanr) % len );
1929                         while(imanr < 0) imanr+= len;
1930                         if(imanr==0) imanr= len;
1931                 }
1932         
1933                 /* allows image users to handle redraws */
1934                 if(iuser->flag & IMA_ANIM_ALWAYS)
1935                         if(imanr!=iuser->framenr)
1936                                 iuser->flag |= IMA_ANIM_REFRESHED;
1937                 
1938                 iuser->framenr= imanr;
1939                 if(iuser->ok==0) iuser->ok= 1;
1940         }
1941 }
1942