Reverted the change of auto-turning on premul for images from last
[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 (do_prefix)          sprintf(stamp_data->file, "File %s", G.sce);
910                 else                            sprintf(stamp_data->file, "%s", G.sce);
911                 stamp_data->note[0] = '\0';
912         } else {
913                 stamp_data->file[0] = '\0';
914         }
915         
916         if (G.scene->r.stamp & R_STAMP_NOTE) {
917                 /* Never do prefix for Note */
918                 sprintf(stamp_data->note, "%s", G.scene->r.stamp_udata);
919         } else {
920                 stamp_data->note[0] = '\0';
921         }
922         
923         if (G.scene->r.stamp & R_STAMP_DATE) {
924 #ifdef WIN32
925                 _strdate (sdate);
926                 sprintf (text, "%s", sdate);
927 #else
928                 t = time (NULL);
929                 tl = localtime (&t);
930                 sprintf (text, "%04d-%02d-%02d", tl->tm_year+1900, tl->tm_mon+1, tl->tm_mday);
931 #endif /* WIN32 */
932                 if (do_prefix)          sprintf(stamp_data->date, "Date %s", text);
933                 else                            sprintf(stamp_data->date, "%s", text);
934         } else {
935                 stamp_data->date[0] = '\0';
936         }
937         
938         if (G.scene->r.stamp & R_STAMP_MARKER) {
939                 TimeMarker *marker = get_frame_marker(CFRA);
940         
941                 if (marker) strcpy(text, marker->name);
942                 else            strcpy(text, "<none>");
943                 
944                 if (do_prefix)          sprintf(stamp_data->marker, "Marker %s", text);
945                 else                            sprintf(stamp_data->marker, "%s", text);
946         } else {
947                 stamp_data->marker[0] = '\0';
948         }
949         
950         if (G.scene->r.stamp & R_STAMP_TIME) {
951                 int h, m, s, f;
952                 h= m= s= f= 0;
953                 f = (int)(G.scene->r.cfra % G.scene->r.frs_sec);
954                 s = (int)(G.scene->r.cfra / G.scene->r.frs_sec);
955
956                 if (s) {
957                         m = (int)(s / 60);
958                         s %= 60;
959
960                         if (m) {
961                                 h = (int)(m / 60);
962                                 m %= 60;
963                         }
964                 }
965
966                 if (G.scene->r.frs_sec < 100)
967                         sprintf (text, "%02d:%02d:%02d.%02d", h, m, s, f);
968                 else
969                         sprintf (text, "%02d:%02d:%02d.%03d", h, m, s, f);
970                 
971                 if (do_prefix)          sprintf(stamp_data->time, "Time %s", text);
972                 else                            sprintf(stamp_data->time, "%s", text);
973         } else {
974                 stamp_data->time[0] = '\0';
975         }
976         
977         if (G.scene->r.stamp & R_STAMP_FRAME) {
978                 char format[32];
979                 if (do_prefix)          sprintf(format, "Frame %%0%di\n", 1 + (int) log10(G.scene->r.efra));
980                 else                            sprintf(format, "%%0%di\n", 1 + (int) log10(G.scene->r.efra));
981                 sprintf (stamp_data->frame, format, G.scene->r.cfra);
982         } else {
983                 stamp_data->frame[0] = '\0';
984         }
985
986         if (G.scene->r.stamp & R_STAMP_CAMERA) {
987                 if (do_prefix)          sprintf(stamp_data->camera, "Camera %s", ((Camera *) G.scene->camera)->id.name+2);
988                 else                            sprintf(stamp_data->camera, "%s", ((Camera *) G.scene->camera)->id.name+2);
989         } else {
990                 stamp_data->camera[0] = '\0';
991         }
992
993         if (G.scene->r.stamp & R_STAMP_SCENE) {
994                 if (do_prefix)          sprintf(stamp_data->scene, "Scene %s", G.scene->id.name+2);
995                 else                            sprintf(stamp_data->scene, "%s", G.scene->id.name+2);
996         } else {
997                 stamp_data->scene[0] = '\0';
998         }
999         
1000         if (G.scene->r.stamp & R_STAMP_SEQSTRIP) {
1001                 Sequence *seq = get_forground_frame_seq(CFRA);
1002         
1003                 if (seq) strcpy(text, seq->name+2);
1004                 else            strcpy(text, "<none>");
1005                 
1006                 if (do_prefix)          sprintf(stamp_data->strip, "Strip %s", text);
1007                 else                            sprintf(stamp_data->strip, "%s", text);
1008         } else {
1009                 stamp_data->strip[0] = '\0';
1010         }
1011 }
1012
1013 void BKE_stamp_buf(unsigned char *rect, float *rectf, int width, int height, int channels)
1014 {
1015         struct StampData stamp_data;
1016         
1017         int x=1,y=1;
1018         int font_height;
1019         int text_width;
1020         int text_pad;
1021         struct BMF_Font *font;
1022         
1023         if (!rect && !rectf)
1024                 return;
1025         
1026         stampdata(&stamp_data, 1);
1027         
1028         switch (G.scene->r.stamp_font_id) {
1029         case 1: /* tiny */
1030                 font = BMF_GetFont(BMF_kHelveticaBold8);
1031                 break;
1032         case 2: /* small */
1033                 font = BMF_GetFont(BMF_kHelveticaBold10);
1034                 break;
1035         case 3: /* medium */
1036                 font = BMF_GetFont(BMF_kScreen12);
1037                 break;
1038         case 0: /* large - default */
1039                 font = BMF_GetFont(BMF_kScreen15);
1040                 break;
1041         case 4: /* huge */
1042                 font = BMF_GetFont(BMF_kHelveticaBold14);
1043                 break;
1044         default:
1045                 font = NULL;
1046                 break;
1047         }
1048         
1049         font_height = BMF_GetFontHeight(font);
1050         /* All texts get halfspace+1 pixel on each side and 1 pix
1051         above and below as padding against their backing rectangles */
1052         text_pad = BMF_GetStringWidth(font, " ");
1053         
1054         x = 1; /* Inits for everyone, text position, so 1 for padding, not 0 */
1055         y = height - font_height - 1; /* Also inits for everyone, notice padding pixel */
1056         
1057         if (stamp_data.file[0]) {
1058                 /* Top left corner */
1059                 text_width = BMF_GetStringWidth(font, stamp_data.file);
1060                 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);
1061                 BMF_DrawStringBuf(font, stamp_data.file, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1062                 y -= font_height+2; /* Top and bottom 1 pix padding each */
1063         }
1064
1065         /* Top left corner, below File */
1066         if (stamp_data.note[0]) {
1067                 text_width = BMF_GetStringWidth(font, stamp_data.note);
1068                 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);
1069                 BMF_DrawStringBuf(font, stamp_data.note, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1070                 y -= font_height+2; /* Top and bottom 1 pix padding each */
1071         }
1072         
1073         /* Top left corner, below File (or Note) */
1074         if (stamp_data.date[0]) {
1075                 text_width = BMF_GetStringWidth(font, stamp_data.date);
1076                 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);
1077                 BMF_DrawStringBuf(font, stamp_data.date, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1078         }
1079
1080         /* Bottom left corner, leaving space for timing */
1081         if (stamp_data.marker[0]) {
1082                 x = 1;
1083                 y = font_height+2+1; /* 2 for padding in TIME|FRAME fields below and 1 for padding in this one */
1084                 text_width = BMF_GetStringWidth(font, stamp_data.marker);
1085                 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);
1086                 BMF_DrawStringBuf(font, stamp_data.marker, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1087         }
1088         
1089         /* Left bottom corner */
1090         if (stamp_data.time[0]) {
1091                 x = 1;
1092                 y = 1;
1093                 text_width = BMF_GetStringWidth(font, stamp_data.time);
1094                 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);
1095                 BMF_DrawStringBuf(font, stamp_data.time, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1096                 x += text_width+text_pad+2; /* Both sides have 1 pix additional padding each */
1097         }
1098         
1099         if (stamp_data.frame[0]) {
1100                 text_width = BMF_GetStringWidth(font, stamp_data.frame);
1101                 /* Left bottom corner (after SMPTE if exists) */
1102                 if (!stamp_data.time[0])        x = 1;
1103                 y = 1;
1104                 buf_rectfill_area(rect, rectf, width, height, G.scene->r.bg_stamp, x-1, y-1, x+text_width+text_pad+1, y+font_height+1);
1105                 BMF_DrawStringBuf(font, stamp_data.frame, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1106         }
1107
1108         if (stamp_data.camera[0]) {
1109                 text_width = BMF_GetStringWidth(font, stamp_data.camera);
1110                 /* Center of bottom edge */
1111                 x = (width/2) - (BMF_GetStringWidth(font, stamp_data.camera)/2);
1112                 y = 1;
1113                 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);
1114                 BMF_DrawStringBuf(font, stamp_data.camera, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1115         }
1116         
1117         if (stamp_data.scene[0]) {
1118                 text_width = BMF_GetStringWidth(font, stamp_data.scene);
1119                 /* Bottom right corner */
1120                 x = width - (text_width+1+text_pad);
1121                 y = 1;
1122                 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);
1123                 BMF_DrawStringBuf(font, stamp_data.scene, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1124         }
1125         
1126         if (stamp_data.strip[0]) {
1127                 text_width = BMF_GetStringWidth(font, stamp_data.strip);
1128                 /* Top right corner */
1129                 x = width - (text_width+1+text_pad);
1130                 y = height - font_height - 1;
1131                 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);
1132                 BMF_DrawStringBuf(font, stamp_data.strip, x+(text_pad/2), y, G.scene->r.fg_stamp, rect, rectf, width, height, channels);
1133         }
1134         
1135 }
1136
1137 void BKE_stamp_info(struct ImBuf *ibuf)
1138 {
1139         struct StampData stamp_data;
1140
1141         if (!ibuf)      return;
1142         
1143         /* fill all the data values, no prefix */
1144         stampdata(&stamp_data, 0);
1145         
1146         if (stamp_data.file[0])         IMB_imginfo_change_field (ibuf, "File",         stamp_data.file);
1147         if (stamp_data.note[0])         IMB_imginfo_change_field (ibuf, "Note",         stamp_data.note);
1148         if (stamp_data.date[0])         IMB_imginfo_change_field (ibuf, "Date",         stamp_data.date);
1149         if (stamp_data.marker[0])       IMB_imginfo_change_field (ibuf, "Marker",       stamp_data.marker);
1150         if (stamp_data.time[0])         IMB_imginfo_change_field (ibuf, "Time",         stamp_data.time);
1151         if (stamp_data.frame[0])        IMB_imginfo_change_field (ibuf, "Frame",        stamp_data.frame);
1152         if (stamp_data.camera[0])       IMB_imginfo_change_field (ibuf, "Camera",       stamp_data.camera);
1153         if (stamp_data.scene[0])        IMB_imginfo_change_field (ibuf, "Scene",        stamp_data.scene);
1154         if (stamp_data.strip[0])        IMB_imginfo_change_field (ibuf, "Strip",        stamp_data.strip);
1155 }
1156
1157 int BKE_write_ibuf(ImBuf *ibuf, char *name, int imtype, int subimtype, int quality)
1158 {
1159         int ok;
1160         
1161         if(imtype==0);
1162         else if(imtype== R_IRIS) 
1163                 ibuf->ftype= IMAGIC;
1164         else if ((imtype==R_RADHDR)) {
1165                 ibuf->ftype= RADHDR;
1166         }
1167         else if (imtype==R_PNG || imtype==R_FFMPEG) {
1168                 ibuf->ftype= PNG;
1169         }
1170 #ifdef WITH_DDS
1171         else if ((imtype==R_DDS)) {
1172                 ibuf->ftype= DDS;
1173         }
1174 #endif
1175         else if ((imtype==R_BMP)) {
1176                 ibuf->ftype= BMP;
1177         }
1178         else if ((G.have_libtiff) && (imtype==R_TIFF)) {
1179                 ibuf->ftype= TIF;
1180         }
1181 #ifdef WITH_OPENEXR
1182         else if (imtype==R_OPENEXR || imtype==R_MULTILAYER) {
1183                 ibuf->ftype= OPENEXR;
1184                 if(subimtype & R_OPENEXR_HALF)
1185                         ibuf->ftype |= OPENEXR_HALF;
1186                 ibuf->ftype |= (quality & OPENEXR_COMPRESS);
1187                 
1188                 if(!(subimtype & R_OPENEXR_ZBUF))
1189                         ibuf->zbuf_float = NULL;        /* signal for exr saving */
1190                 
1191         }
1192 #endif
1193         else if (imtype==R_CINEON) {
1194                 ibuf->ftype = CINEON;
1195         }
1196         else if (imtype==R_DPX) {
1197                 ibuf->ftype = DPX;
1198         }
1199         else if (imtype==R_TARGA) {
1200                 ibuf->ftype= TGA;
1201         }
1202         else if(imtype==R_RAWTGA) {
1203                 ibuf->ftype= RAWTGA;
1204         }
1205         else if(imtype==R_HAMX) {
1206                 ibuf->ftype= AN_hamx;
1207         }
1208         else {
1209                 /* R_JPEG90, R_MOVIE, etc. default we save jpegs */
1210                 if(quality < 10) quality= 90;
1211                 ibuf->ftype= JPG|quality;
1212                 if(ibuf->depth==32) ibuf->depth= 24;    /* unsupported feature only confuses other s/w */
1213         }
1214         
1215         BLI_make_existing_file(name);
1216
1217         if(G.scene->r.scemode & R_STAMP_INFO)
1218                 BKE_stamp_info(ibuf);
1219         
1220         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1221         if (ok == 0) {
1222                 perror(name);
1223         }
1224         
1225         return(ok);
1226 }
1227
1228
1229 void BKE_makepicstring(char *string, char *base, int frame, int imtype)
1230 {
1231         short i, len, digits= 4;        /* digits in G.scene? */
1232         char num[10];
1233
1234         if (string==NULL) return;
1235
1236         BLI_strncpy(string, base, FILE_MAX - 10);       /* weak assumption */
1237         BLI_convertstringcode(string, G.sce, frame);
1238
1239         len= strlen(string);
1240                         
1241         i= digits - sprintf(num, "%d", frame);
1242         for(; i>0; i--){
1243                 string[len]= '0';
1244                 len++;
1245         }
1246         string[len]= 0;
1247         strcat(string, num);
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                 /*ok, this is *not* what a user expects when he clicks the premul
1667                   button, that his image is actually changed.  This should be a
1668                   render-time option, not a modification to the image! - joeedh*/
1669                 /*if(ima->flag & IMA_DO_PREMUL)
1670                         converttopremul(ibuf);*/
1671         }
1672         else
1673                 ima->ok= 0;
1674         
1675         if(iuser)
1676                 iuser->ok= ima->ok;
1677         
1678         return ibuf;
1679 }
1680
1681 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
1682 {
1683         ImBuf *ibuf= NULL;
1684         
1685         if(ima->rr==NULL) {
1686                 ibuf = image_load_image_file(ima, iuser, 0);
1687                 if(ibuf) { /* actually an error */
1688                         ima->type= IMA_TYPE_IMAGE;
1689                         return ibuf;
1690                 }
1691         }
1692         if(ima->rr) {
1693                 RenderPass *rpass= BKE_image_multilayer_index(ima->rr, iuser);
1694
1695                 if(rpass) {
1696                         ibuf= IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0, 0);
1697                         
1698                         image_assign_ibuf(ima, ibuf, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1699                         image_initialize_after_load(ima, ibuf);
1700                         
1701                         ibuf->rect_float= rpass->rect;
1702                         ibuf->flags |= IB_rectfloat;
1703                         ibuf->channels= rpass->channels;
1704                 }
1705         }
1706         
1707         if(ibuf==NULL) 
1708                 ima->ok= 0;
1709         if(iuser)
1710                 iuser->ok= ima->ok;
1711         
1712         return ibuf;
1713 }
1714
1715
1716 /* showing RGBA result itself (from compo/sequence) or
1717    like exr, using layers etc */
1718 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser)
1719 {
1720         RenderResult *rr= RE_GetResult(RE_GetRender(G.scene->id.name));
1721         
1722         if(rr && iuser) {
1723                 RenderResult rres;
1724                 float *rectf;
1725                 unsigned int *rect;
1726                 int channels= 4, layer= iuser->layer;
1727                 
1728                 /* this gives active layer, composite or seqence result */
1729                 RE_GetResultImage(RE_GetRender(G.scene->id.name), &rres);
1730                 rect= (unsigned int *)rres.rect32;
1731                 rectf= rres.rectf;
1732                 
1733                 /* get compo/seq result by default */
1734                 if(rr->rectf && layer==0);
1735                 else if(rr->layers.first) {
1736                         RenderLayer *rl= BLI_findlink(&rr->layers, iuser->layer-(rr->rectf?1:0));
1737                         if(rl) {
1738                                 /* there's no combined pass, is in renderlayer itself */
1739                                 if(iuser->pass==0) {
1740                                         rectf= rl->rectf;
1741                                 }
1742                                 else {
1743                                         RenderPass *rpass= BLI_findlink(&rl->passes, iuser->pass-1);
1744                                         if(rpass) {
1745                                                 channels= rpass->channels;
1746                                                 rectf= rpass->rect;
1747                                         }
1748                                 }
1749                         }
1750                 }
1751                 
1752                 if(rectf || rect) {
1753                         ImBuf *ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1754
1755                         /* make ibuf if needed, and initialize it */
1756                         if(ibuf==NULL) {
1757                                 ibuf= IMB_allocImBuf(rr->rectx, rr->recty, 32, 0, 0);
1758                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1759                         }
1760                         ibuf->x= rr->rectx;
1761                         ibuf->y= rr->recty;
1762                         
1763                         if(ibuf->rect_float!=rectf || rect) /* ensure correct redraw */
1764                                 imb_freerectImBuf(ibuf);
1765                         if(rect)
1766                                 ibuf->rect= rect;
1767                         
1768                         ibuf->rect_float= rectf;
1769                         ibuf->flags |= IB_rectfloat;
1770                         ibuf->channels= channels;
1771                         
1772                         ima->ok= IMA_OK_LOADED;
1773                         return ibuf;
1774                 }
1775         }
1776         
1777         return NULL;
1778 }
1779
1780 /* Checks optional ImageUser and verifies/creates ImBuf. */
1781 /* returns ibuf */
1782 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
1783 {
1784         ImBuf *ibuf= NULL;
1785         float color[] = {0, 0, 0, 1};
1786
1787         /* quick reject tests */
1788         if(ima==NULL) 
1789                 return NULL;
1790         if(iuser) {
1791                 if(iuser->ok==0)
1792                         return NULL;
1793         }
1794         else if(ima->ok==0)
1795                 return NULL;
1796         
1797         BLI_lock_thread(LOCK_IMAGE);
1798         
1799         /* handle image source and types */
1800         if(ima->source==IMA_SRC_MOVIE) {
1801                 /* source is from single file, use flipbook to store ibuf */
1802                 int frame= iuser?iuser->framenr:ima->lastframe;
1803                 
1804                 ibuf= image_get_ibuf(ima, 0, frame);
1805                 if(ibuf==NULL)
1806                         ibuf= image_load_movie_file(ima, iuser, frame);
1807         }
1808         else if(ima->source==IMA_SRC_SEQUENCE) {
1809                 
1810                 if(ima->type==IMA_TYPE_IMAGE) {
1811                         /* regular files, ibufs in flipbook, allows saving */
1812                         int frame= iuser?iuser->framenr:ima->lastframe;
1813                         
1814                         ibuf= image_get_ibuf(ima, 0, frame);
1815                         if(ibuf==NULL)
1816                                 ibuf= image_load_sequence_file(ima, iuser, frame);
1817                         else
1818                                 BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
1819                 }
1820                 /* no else; on load the ima type can change */
1821                 if(ima->type==IMA_TYPE_MULTILAYER) {
1822                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
1823                         int frame= iuser?iuser->framenr:ima->lastframe;
1824                         int index= iuser?iuser->multi_index:IMA_NO_INDEX;
1825                         
1826                         ibuf= image_get_ibuf(ima, index, frame);
1827                         if(G.rt) printf("seq multi fra %d id %d ibuf %p %s\n", frame, index, ibuf, ima->id.name);
1828                         if(ibuf==NULL)
1829                                 ibuf= image_load_sequence_multilayer(ima, iuser, frame);
1830                         else
1831                                 BLI_strncpy(ima->name, ibuf->name, sizeof(ima->name));
1832                 }
1833
1834         }
1835         else if(ima->source==IMA_SRC_FILE) {
1836                 
1837                 if(ima->type==IMA_TYPE_IMAGE) {
1838                         ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1839                         if(ibuf==NULL)
1840                                 ibuf= image_load_image_file(ima, iuser, G.scene->r.cfra);       /* cfra only for '#', this global is OK */
1841                 }
1842                 /* no else; on load the ima type can change */
1843                 if(ima->type==IMA_TYPE_MULTILAYER) {
1844                         /* keeps render result, stores ibufs in listbase, allows saving */
1845                         ibuf= image_get_ibuf(ima, iuser?iuser->multi_index:IMA_NO_INDEX, 0);
1846                         if(ibuf==NULL)
1847                                 ibuf= image_get_ibuf_multilayer(ima, iuser);
1848                 }
1849                         
1850         }
1851         else if(ima->source == IMA_SRC_GENERATED) {
1852                 /* generated is: ibuf is allocated dynamically */
1853                 ibuf= image_get_ibuf(ima, IMA_NO_INDEX, 0);
1854                 
1855                 if(ibuf==NULL) {
1856                         if(ima->type==IMA_TYPE_VERSE) {
1857                                 /* todo */
1858                         }
1859                         else { /* always fall back to IMA_TYPE_UV_TEST */
1860                                 /* UV testgrid or black or solid etc */
1861                                 if(ima->gen_x==0) ima->gen_x= 256;
1862                                 if(ima->gen_y==0) ima->gen_y= 256;
1863                                 ibuf= add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 0, ima->gen_type, color);
1864                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1865                                 ima->ok= IMA_OK_LOADED;
1866                         }
1867                 }
1868         }
1869         else if(ima->source == IMA_SRC_VIEWER) {
1870                 if(ima->type==IMA_TYPE_R_RESULT) {
1871                         /* always verify entirely */
1872                         ibuf= image_get_render_result(ima, iuser);
1873                 }
1874                 else if(ima->type==IMA_TYPE_COMPOSITE) {
1875                         int frame= iuser?iuser->framenr:0;
1876                         
1877                         /* Composite Viewer, all handled in compositor */
1878                         ibuf= image_get_ibuf(ima, 0, frame);
1879                         if(ibuf==NULL) {
1880                                 /* fake ibuf, will be filled in compositor */
1881                                 ibuf= IMB_allocImBuf(256, 256, 32, IB_rect, 0);
1882                                 image_assign_ibuf(ima, ibuf, 0, frame);
1883                         }
1884                 }
1885         }
1886
1887         if(G.rendering==0)
1888                 tag_image_time(ima);
1889
1890         BLI_unlock_thread(LOCK_IMAGE);
1891
1892         return ibuf;
1893 }
1894
1895
1896 void BKE_image_user_calc_imanr(ImageUser *iuser, int cfra, int fieldnr)
1897 {
1898         int imanr, len;
1899         
1900         /* here (+fie_ima/2-1) makes sure that division happens correctly */
1901         len= (iuser->fie_ima*iuser->frames)/2;
1902         
1903         if(len==0) {
1904                 iuser->framenr= 0;
1905         }
1906         else {
1907                 cfra= cfra - iuser->sfra+1;
1908                 
1909                 /* cyclic */
1910                 if(iuser->cycl) {
1911                         cfra= ( (cfra) % len );
1912                         if(cfra < 0) cfra+= len;
1913                         if(cfra==0) cfra= len;
1914                 }
1915                 
1916                 if(cfra<1) cfra= 1;
1917                 else if(cfra>len) cfra= len;
1918                 
1919                 /* convert current frame to current field */
1920                 cfra= 2*(cfra);
1921                 if(fieldnr) cfra++;
1922                 
1923                 /* transform to images space */
1924                 imanr= (cfra+iuser->fie_ima-2)/iuser->fie_ima;
1925                 if(imanr>iuser->frames) imanr= iuser->frames;
1926                 imanr+= iuser->offset;
1927                 
1928                 if(iuser->cycl) {
1929                         imanr= ( (imanr) % len );
1930                         while(imanr < 0) imanr+= len;
1931                         if(imanr==0) imanr= len;
1932                 }
1933         
1934                 /* allows image users to handle redraws */
1935                 if(iuser->flag & IMA_ANIM_ALWAYS)
1936                         if(imanr!=iuser->framenr)
1937                                 iuser->flag |= IMA_ANIM_REFRESHED;
1938                 
1939                 iuser->framenr= imanr;
1940                 if(iuser->ok==0) iuser->ok= 1;
1941         }
1942 }
1943