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