Fix for [#8303] stamp gives wrong file name when using unsaved files
[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 #ifdef WITH_OPENEXR
1187         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
1188                 ibuf->ftype= OPENEXR;
1189                 if(subimtype & R_OPENEXR_HALF)
1190                         ibuf->ftype |= OPENEXR_HALF;
1191                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
1192                 
1193                 if(!(subimtype & R_OPENEXR_ZBUF))
1194                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1195                 
1196         }
1197 #endif
1198         else if (imtype==R_CINEON) {
1199                 ibuf->ftype = CINEON;
1200         }
1201         else if (imtype==R_DPX) {
1202                 ibuf->ftype = DPX;
1203         }
1204         else if (imtype==R_TARGA) {
1205                 ibuf->ftype= TGA;
1206         }
1207         else if(imtype==R_RAWTGA) {
1208                 ibuf->ftype= RAWTGA;
1209         }
1210         else if(imtype==R_HAMX) {
1211                 ibuf->ftype= AN_hamx;
1212         }
1213         else {
1214                 /* R_JPEG90, R_MOVIE, etc. default we save jpegs */
1215                 if(quality < 10) quality= 90;
1216                 ibuf->ftype= JPG|quality;
1217                 if(ibuf->depth==32) ibuf->depth= 24;    /* unsupported feature only confuses other s/w */
1218         }
1219         
1220         BLI_make_existing_file(name);
1221
1222         if(G.scene->r.scemode & R_STAMP_INFO)
1223                 BKE_stamp_info(ibuf);
1224         
1225         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1226         if (ok == 0) {
1227                 perror(name);
1228         }
1229         
1230         return(ok);
1231 }
1232
1233
1234 void BKE_makepicstring(char *string, char *base, int frame, int imtype)
1235 {
1236         short i, len, digits= 4;        /* digits in G.scene? */
1237         char num[10];
1238
1239         if (string==NULL) return;
1240
1241         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1242         BLI_convertstringcode(string, G.sce, frame);
1243
1244         len= strlen(string);
1245                         
1246         i= digits - sprintf(num, "%d", frame);
1247         for(; i>0; i--){
1248                 string[len]= '0';
1249                 len++;
1250         }
1251         string[len]= 0;
1252         strcat(string, num);
1253
1254         if(G.scene->r.scemode & R_EXTENSION) 
1255                 BKE_add_image_extension(string, imtype);
1256                 
1257 }
1258
1259 /* used by sequencer too */
1260 struct anim *openanim(char *name, int flags)
1261 {
1262         struct anim *anim;
1263         struct ImBuf *ibuf;
1264         
1265         anim = IMB_open_anim(name, flags);
1266         if (anim == NULL) return(0);
1267
1268         ibuf = IMB_anim_absolute(anim, 0);
1269         if (ibuf == NULL) {
1270                 printf("not an anim; %s\n", name);
1271                 IMB_free_anim(anim);
1272                 return(0);
1273         }
1274         IMB_freeImBuf(ibuf);
1275         
1276         return(anim);
1277 }
1278
1279 /* ************************* New Image API *************** */
1280
1281
1282 /* Notes about Image storage 
1283 - packedfile
1284   -> written in .blend
1285 - filename
1286   -> written in .blend
1287 - movie
1288   -> comes from packedfile or filename
1289 - renderresult
1290   -> comes from packedfile or filename
1291 - listbase
1292   -> ibufs from exrhandle
1293 - flipbook array
1294   -> ibufs come from movie, temporary renderresult or sequence
1295 - ibuf
1296   -> comes from packedfile or filename or generated
1297
1298 */
1299
1300
1301 /* forces existance of 1 Image for renderout or nodes, returns Image */
1302 /* name is only for default, when making new one */
1303 Image *BKE_image_verify_viewer(int type, const char *name)
1304 {
1305         Image *ima;
1306         
1307         for(ima=G.main->image.first; ima; ima= ima->id.next)
1308                 if(ima->source==IMA_SRC_VIEWER)
1309                         if(ima->type==type)
1310                                 break;
1311         
1312         if(ima==NULL)
1313                 ima= image_alloc(name, IMA_SRC_VIEWER, type);
1314         
1315         /* happens on reload, imagewindow cannot be image user when hidden*/
1316         if(ima->id.us==0)
1317                 id_us_plus(&ima->id);
1318
1319         return ima;
1320 }
1321
1322 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1323 {
1324         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1325 }
1326
1327 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1328 {
1329         if(ima==NULL)
1330                 return;
1331         
1332         switch(signal) {
1333         case IMA_SIGNAL_FREE:
1334                 image_free_buffers(ima);
1335                 if(iuser)
1336                         iuser->ok= 1;
1337                 break;
1338         case IMA_SIGNAL_SRC_CHANGE:
1339                 if(ima->type==IMA_TYPE_MULTILAYER)
1340                         image_free_buffers(ima);
1341                 else if(ima->source==IMA_SRC_GENERATED) {
1342                         if(ima->gen_x==0 || ima->gen_y==0) {
1343                                 ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1344                                 if(ibuf) {
1345                                         ima->gen_x= ibuf->x;
1346                                         ima->gen_y= ibuf->y;
1347                                 }
1348                         }
1349                 }
1350                 ima->ok= 1;
1351                 if(iuser)
1352                         iuser->ok= 1;
1353                 break;
1354                         
1355         case IMA_SIGNAL_RELOAD:
1356                 /* try to repack file */
1357                 if(ima->packedfile) {
1358                         PackedFile *pf;
1359                         pf = newPackedFile(ima->name);
1360                         if (pf) {
1361                                 freePackedFile(ima->packedfile);
1362                                 ima->packedfile = pf;
1363                                 image_free_buffers(ima);
1364                         } else {
1365                                 printf("ERROR: Image not available. Keeping packed image\n");
1366                         }
1367                 }
1368                 else
1369                         image_free_buffers(ima);
1370                 
1371                 if(iuser)
1372                         iuser->ok= 1;
1373                 
1374                 break;
1375         case IMA_SIGNAL_USER_NEW_IMAGE:
1376                 if(iuser) {
1377                         iuser->ok= 1;
1378                         if(ima->source==IMA_SRC_FILE || ima->source==IMA_SRC_SEQUENCE) {
1379                                 if(ima->type==IMA_TYPE_MULTILAYER) {
1380                                         iuser->multi_index= 0;
1381                                         iuser->layer= iuser->pass= 0;
1382                                 }
1383                         }
1384                 }
1385                 break;
1386         }
1387 }
1388
1389 /* if layer or pass changes, we need an index for the imbufs list */
1390 /* note it is called for rendered results, but it doesnt use the index! */
1391 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1392 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1393 {
1394         RenderLayer *rl;
1395         RenderPass *rpass= NULL;
1396         
1397         if(rr==NULL) 
1398                 return NULL;
1399         
1400         if(iuser) {
1401                 short index= 0, rl_index= 0, rp_index;
1402                 
1403                 for(rl= rr->layers.first; rl; rl= rl->next, rl_index++) {
1404                         rp_index= 0;
1405                         for(rpass= rl->passes.first; rpass; rpass= rpass->next, index++, rp_index++)
1406                                 if(iuser->layer==rl_index && iuser->pass==rp_index)
1407                                         break;
1408                         if(rpass)
1409                                 break;
1410                 }
1411                 
1412                 if(rpass)
1413                         iuser->multi_index= index;
1414                 else 
1415                         iuser->multi_index= 0;
1416         }
1417         if(rpass==NULL) {
1418                 rl= rr->layers.first;
1419                 if(rl)
1420                         rpass= rl->passes.first;
1421         }
1422         
1423         return rpass;
1424 }
1425
1426 RenderResult *BKE_image_get_renderresult(Image *ima)
1427 {
1428         if(ima->rr)
1429                 return ima->rr;
1430         if(ima->type==IMA_TYPE_R_RESULT)
1431                 return RE_GetResult(RE_GetRender(G.scene->id.name));
1432         return NULL;
1433 }
1434
1435 /* after imbuf load, openexr type can return with a exrhandle open */
1436 /* in that case we have to build a render-result */
1437 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
1438 {
1439         
1440         ima->rr= RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
1441
1442 #ifdef WITH_OPENEXR
1443         IMB_exr_close(ibuf->userdata);
1444 #endif
1445
1446         ibuf->userdata= NULL;
1447         if(ima->rr)
1448                 ima->rr->framenr= framenr;
1449 }
1450
1451 /* common stuff to do with images after loading */
1452 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
1453 {
1454         
1455         
1456         /* preview is NULL when it has never been used as an icon before */
1457         if(G.background==0 && ima->preview==NULL)
1458                 BKE_icon_changed(BKE_icon_getid(&ima->id));
1459         
1460         /* stringcodes also in ibuf, ibuf->name is used to retrieve original (buttons) */
1461         BLI_strncpy(ibuf->name, ima->name, FILE_MAX);
1462         
1463         /* fields */
1464         if (ima->flag & IMA_FIELDS) {
1465                 if(ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
1466                 else de_interlace_ng(ibuf);
1467         }
1468         /* timer */
1469         ima->lastused = clock() / CLOCKS_PER_SEC;
1470         
1471         ima->ok= IMA_OK_LOADED;
1472         
1473 }
1474
1475 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
1476 {
1477         struct ImBuf *ibuf;
1478         unsigned short numlen;
1479         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX];
1480         
1481         ima->lastframe= frame;
1482
1483         BLI_stringdec(ima->name, head, tail, &numlen);
1484         BLI_stringenc(ima->name, head, tail, numlen, frame);
1485         BLI_strncpy(name, ima->name, sizeof(name));
1486         
1487         if(ima->id.lib)
1488                 BLI_convertstringcode(name, ima->id.lib->filename, frame);
1489         else
1490                 BLI_convertstringcode(name, G.sce, frame);
1491         
1492         /* read ibuf */
1493         ibuf = IMB_loadiffname(name, IB_rect|IB_multilayer);
1494         if(G.f & G_DEBUG) printf("loaded %s\n", name);
1495         
1496         if (ibuf) {
1497 #ifdef WITH_OPENEXR
1498                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
1499                 if (ibuf->ftype==OPENEXR && ibuf->userdata) {
1500                         image_create_multilayer(ima, ibuf, frame);      
1501                         ima->type= IMA_TYPE_MULTILAYER;
1502                         IMB_freeImBuf(ibuf);
1503                         ibuf= NULL;
1504                 }
1505                 else {
1506                         image_assign_ibuf(ima, ibuf, 0, frame);
1507                         image_initialize_after_load(ima, ibuf);
1508                 }
1509 #else
1510                 image_assign_ibuf(ima, ibuf, 0, frame);
1511                 image_initialize_after_load(ima, ibuf);
1512 #endif
1513         }
1514         else
1515                 ima->ok= 0;
1516         
1517         if(iuser)
1518                 iuser->ok= ima->ok;
1519         
1520         return ibuf;
1521 }
1522
1523 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
1524 {
1525         struct ImBuf *ibuf= NULL;
1526         
1527         /* either we load from RenderResult, or we have to load a new one */
1528         
1529         /* check for new RenderResult */
1530         if(ima->rr==NULL || frame!=ima->rr->framenr) {
1531                 /* copy to survive not found multilayer image */
1532                 RenderResult *oldrr= ima->rr;
1533         
1534                 ima->rr= NULL;
1535                 ibuf = image_load_sequence_file(ima, iuser, frame);
1536                 
1537                 if(ibuf) { /* actually an error */
1538                         ima->type= IMA_TYPE_IMAGE;
1539                         printf("error, multi is normal image\n");
1540                 }
1541                 // printf("loaded new result %p\n", ima->rr);
1542                 /* free result if new one found */
1543                 if(ima->rr) {
1544                         // if(oldrr) printf("freed previous result %p\n", oldrr);
1545                         if(oldrr) RE_FreeRenderResult(oldrr);
1546                 }
1547                 else
1548                         ima->rr= oldrr;
1549
1550         }
1551         if(ima->rr) {
1552                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1553                 
1554                 if(rpass) {
1555                         // printf("load from pass %s\n", rpass->name);
1556                         /* since we free  render results, we copy the rect */
1557                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1558                         ibuf->rect_float= MEM_dupallocN(rpass->rect);
1559                         ibuf->flags |= IB_rectfloat;
1560                         ibuf->mall= IB_rectfloat;
1561                         ibuf->channels= rpass->channels;
1562                         
1563                         image_assign_ibuf(ima, ibuf, iuser->multi_index, frame);
1564                         image_initialize_after_load(ima, ibuf);
1565                         
1566                 }
1567                 // else printf("pass not found\n");
1568         }
1569         else
1570                 ima->ok= 0;
1571         
1572         if(iuser)
1573                 iuser->ok= ima->ok;
1574         
1575         return ibuf;
1576 }
1577
1578
1579 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
1580 {
1581         struct ImBuf *ibuf= NULL;
1582         
1583         ima->lastframe= frame;
1584         
1585         if(ima->anim==NULL) {
1586                 char str[FILE_MAX];
1587                 
1588                 BLI_strncpy(str, ima->name, FILE_MAX);
1589                 if(ima->id.lib)
1590                         BLI_convertstringcode(str, ima->id.lib->filename, 0);
1591                 else
1592                         BLI_convertstringcode(str, G.sce, 0);
1593                 
1594                 ima->anim = openanim(str, IB_cmap | IB_rect);
1595                 
1596                 /* let's initialize this user */
1597                 if(ima->anim && iuser && iuser->frames==0)
1598                         iuser->frames= IMB_anim_get_duration(ima->anim);
1599         }
1600         
1601         if(ima->anim) {
1602                 int dur = IMB_anim_get_duration(ima->anim);
1603                 int fra= frame-1;
1604                 
1605                 if(fra<0) fra = 0;
1606                 if(fra>(dur-1)) fra= dur-1;
1607                 ibuf = IMB_anim_absolute(ima->anim, fra);
1608                 
1609                 if(ibuf) {
1610                         image_assign_ibuf(ima, ibuf, 0, frame);
1611                         image_initialize_after_load(ima, ibuf);
1612                 }
1613                 else
1614                         ima->ok= 0;
1615         }
1616         else
1617                 ima->ok= 0;
1618         
1619         if(iuser)
1620                 iuser->ok= ima->ok;
1621         
1622         return ibuf;
1623 }
1624
1625 /* cfra used for # code, Image can only have this # for all its users */
1626 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
1627 {
1628         struct ImBuf *ibuf;
1629         char str[FILE_MAX];
1630         
1631         /* always ensure clean ima */
1632         image_free_buffers(ima);
1633         
1634         /* is there a PackedFile with this image ? */
1635         if (ima->packedfile) {
1636                 ibuf = IMB_ibImageFromMemory((int *) ima->packedfile->data, ima->packedfile->size, IB_rect|IB_multilayer);
1637         } 
1638         else {
1639                         
1640                 /* get the right string */
1641                 BLI_strncpy(str, ima->name, sizeof(str));
1642                 if(ima->id.lib)
1643                         BLI_convertstringcode(str, ima->id.lib->filename, cfra);
1644                 else
1645                         BLI_convertstringcode(str, G.sce, 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                 /*ok, this is *not* what a user expects when he clicks the premul
1672                   button, that his image is actually changed.  This should be a
1673                   render-time option, not a modification to the image! - joeedh*/
1674                 /*if(ima->flag & IMA_DO_PREMUL)
1675                         converttopremul(ibuf);*/
1676         }
1677         else
1678                 ima->ok= 0;
1679         
1680         if(iuser)
1681                 iuser->ok= ima->ok;
1682         
1683         return ibuf;
1684 }
1685
1686 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
1687 {
1688         ImBuf *ibuf= NULL;
1689         
1690         if(ima->rr==NULL) {
1691                 ibuf = image_load_image_file(ima, iuser, 0);
1692                 if(ibuf) { /* actually an error */
1693                         ima->type= IMA_TYPE_IMAGE;
1694                         return ibuf;
1695                 }
1696         }
1697         if(ima->rr) {
1698                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1699
1700                 if(rpass) {
1701                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1702                         
1703                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1704                         image_initialize_after_load(ima, ibuf);
1705                         
1706                         ibuf->rect_float= rpass->rect;
1707                         ibuf->flags |= IB_rectfloat;
1708                         ibuf->channels= rpass->channels;
1709                 }
1710         }
1711         
1712         if(ibuf==NULL) 
1713                 ima->ok= 0;
1714         if(iuser)
1715                 iuser->ok= ima->ok;
1716         
1717         return ibuf;
1718 }
1719
1720
1721 /* showing RGBA result itself (from compo/sequence) or
1722    like exr, using layers etc */
1723 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser)
1724 {
1725         RenderResult *rr= RE_GetResult(RE_GetRender(G.scene->id.name));
1726         
1727         if(rr && iuser) {
1728                 RenderResult rres;
1729                 float *rectf;
1730                 unsigned int *rect;
1731                 int channels= 4, layer= iuser->layer;
1732                 
1733                 /* this gives active layer, composite or seqence result */
1734                 RE_GetResultImage(RE_GetRender(G.scene->id.name), &rres);
1735                 rect= (unsigned int *)rres.rect32;
1736                 rectf= rres.rectf;
1737                 
1738                 /* get compo/seq result by default */
1739                 if(rr->rectf && layer==0);
1740                 else if(rr->layers.first) {
1741                         RenderLayer *rl= BLI_findlink(&rr->layers, iuser->layer-(rr->rectf?1:0));
1742                         if(rl) {
1743                                 /* there's no combined pass, is in renderlayer itself */
1744                                 if(iuser->pass==0) {
1745                                         rectf= rl->rectf;
1746                                 }
1747                                 else {
1748                                         RenderPass *rpass= BLI_findlink(&rl->passes, iuser->pass-1);
1749                                         if(rpass) {
1750                                                 channels= rpass->channels;
1751                                                 rectf= rpass->rect;
1752                                         }
1753                                 }
1754                         }
1755                 }
1756                 
1757                 if(rectf || rect) {
1758                         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1759
1760                         /* make ibuf if needed, and initialize it */
1761                         if(ibuf==NULL) {
1762                                 ibuf= IMB_allocImBuf(rr->rectx, rr->recty, 32, 0, 0);
1763                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1764                         }
1765                         ibuf->x= rr->rectx;
1766                         ibuf->y= rr->recty;
1767                         
1768                         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
1769                                 imb_freerectImBuf(ibuf);
1770                         if(rect)
1771                                 ibuf->rect= rect;
1772                         
1773                         ibuf->rect_float= rectf;
1774                         ibuf->flags |= IB_rectfloat;
1775                         ibuf->channels= channels;
1776                         
1777                         ima->ok= IMA_OK_LOADED;
1778                         return ibuf;
1779                 }
1780         }
1781         
1782         return NULL;
1783 }
1784
1785 /* Checks optional ImageUser and verifies/creates ImBuf. */
1786 /* returns ibuf */
1787 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
1788 {
1789         ImBuf *ibuf= NULL;
1790         float color[] = {0, 0, 0, 1};
1791
1792         /* quick reject tests */
1793         if(ima==NULL) 
1794                 return NULL;
1795         if(iuser) {
1796                 if(iuser->ok==0)
1797                         return NULL;
1798         }
1799         else if(ima->ok==0)
1800                 return NULL;
1801         
1802         BLI_lock_thread(LOCK_IMAGE);
1803         
1804         /* handle image source and types */
1805         if(ima->source==IMA_SRC_MOVIE) {
1806                 /* source is from single file, use flipbook to store ibuf */
1807                 int frame= iuser?iuser->framenr:ima->lastframe;
1808                 
1809                 ibuf= image_get_ibuf(ima, 0, frame);
1810                 if(ibuf==NULL)
1811                         ibuf= image_load_movie_file(ima, iuser, frame);
1812         }
1813         else if(ima->source==IMA_SRC_SEQUENCE) {
1814                 
1815                 if(ima->type==IMA_TYPE_IMAGE) {
1816                         /* regular files, ibufs in flipbook, allows saving */
1817                         int frame= iuser?iuser->framenr:ima->lastframe;
1818                         
1819                         ibuf= image_get_ibuf(ima, 0, frame);
1820                         if(ibuf==NULL)
1821                                 ibuf= image_load_sequence_file(ima, iuser, frame);
1822                         else
1823                                 BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
1824                 }
1825                 /* no else; on load the ima type can change */
1826                 if(ima->type==IMA_TYPE_MULTILAYER) {
1827                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
1828                         int frame= iuser?iuser->framenr:ima->lastframe;
1829                         int index= iuser?iuser->multi_index:IMA_NO_INDEX;
1830                         
1831                         ibuf= image_get_ibuf(ima, index, frame);
1832                         if(G.rt) printf("seq multi fra %d id %d ibuf %p %s\n", frame, index, ibuf, ima->id.name);
1833                         if(ibuf==NULL)
1834                                 ibuf= image_load_sequence_multilayer(ima, iuser, frame);
1835                         else
1836                                 BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
1837                 }
1838
1839         }
1840         else if(ima->source==IMA_SRC_FILE) {
1841                 
1842                 if(ima->type==IMA_TYPE_IMAGE) {
1843                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1844                         if(ibuf==NULL)
1845                                 ibuf= image_load_image_file(ima, iuser, G.scene->r.cfra);       /* cfra only for '#', this global is OK */
1846                 }
1847                 /* no else; on load the ima type can change */
1848                 if(ima->type==IMA_TYPE_MULTILAYER) {
1849                         /* keeps render result, stores ibufs in listbase, allows saving */
1850                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1851                         if(ibuf==NULL)
1852                                 ibuf= image_get_ibuf_multilayer(ima, iuser);
1853                 }
1854                         
1855         }
1856         else if(ima->source == IMA_SRC_GENERATED) {
1857                 /* generated is: ibuf is allocated dynamically */
1858                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1859                 
1860                 if(ibuf==NULL) {
1861                         if(ima->type==IMA_TYPE_VERSE) {
1862                                 /* todo */
1863                         }
1864                         else { /* always fall back to IMA_TYPE_UV_TEST */
1865                                 /* UV testgrid or black or solid etc */
1866                                 if(ima->gen_x==0) ima->gen_x= 256;
1867                                 if(ima->gen_y==0) ima->gen_y= 256;
1868                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 0, ima->gen_type, color);
1869                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1870                                 ima->ok= IMA_OK_LOADED;
1871                         }
1872                 }
1873         }
1874         else if(ima->source == IMA_SRC_VIEWER) {
1875                 if(ima->type==IMA_TYPE_R_RESULT) {
1876                         /* always verify entirely */
1877                         ibuf= image_get_render_result(ima, iuser);
1878                 }
1879                 else if(ima->type==IMA_TYPE_COMPOSITE) {
1880                         int frame= iuser?iuser->framenr:0;
1881                         
1882                         /* Composite Viewer, all handled in compositor */
1883                         ibuf= image_get_ibuf(ima, 0, frame);
1884                         if(ibuf==NULL) {
1885                                 /* fake ibuf, will be filled in compositor */
1886                                 ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
1887                                 image_assign_ibuf(ima, ibuf, 0, frame);
1888                         }
1889                 }
1890         }
1891
1892         if(G.rendering==0)
1893                 tag_image_time(ima);
1894
1895         BLI_unlock_thread(LOCK_IMAGE);
1896
1897         return ibuf;
1898 }
1899
1900
1901 void BKE_image_user_calc_imanr(ImageUser *iuser, int cfra, int fieldnr)
1902 {
1903         int imanr, len;
1904         
1905         /* here (+fie_ima/2-1) makes sure that division happens correctly */
1906         len= (iuser->fie_ima*iuser->frames)/2;
1907         
1908         if(len==0) {
1909                 iuser->framenr= 0;
1910         }
1911         else {
1912                 cfra= cfra - iuser->sfra+1;
1913                 
1914                 /* cyclic */
1915                 if(iuser->cycl) {
1916                         cfra= ( (cfra) % len );
1917                         if(cfra < 0) cfra+= len;
1918                         if(cfra==0) cfra= len;
1919                 }
1920                 
1921                 if(cfra<1) cfra= 1;
1922                 else if(cfra>len) cfra= len;
1923                 
1924                 /* convert current frame to current field */
1925                 cfra= 2*(cfra);
1926                 if(fieldnr) cfra++;
1927                 
1928                 /* transform to images space */
1929                 imanr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
1930                 if(imanr>iuser->frames) imanr= iuser->frames;
1931                 imanr+= iuser->offset;
1932                 
1933                 if(iuser->cycl) {
1934                         imanr= ( (imanr) % len );
1935                         while(imanr < 0) imanr+= len;
1936                         if(imanr==0) imanr= len;
1937                 }
1938         
1939                 /* allows image users to handle redraws */
1940                 if(iuser->flag & IMA_ANIM_ALWAYS)
1941                         if(imanr!=iuser->framenr)
1942                                 iuser->flag |= IMA_ANIM_REFRESHED;
1943                 
1944                 iuser->framenr= imanr;
1945                 if(iuser->ok==0) iuser->ok= 1;
1946         }
1947 }
1948