Fix #31747, broken image sequence loading after r47432.
[blender.git] / source / blender / blenkernel / intern / image.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, 2006, full recode
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/image.c
27  *  \ingroup bke
28  */
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 #ifdef _WIN32
44 #define open _open
45 #define close _close
46 #endif
47
48 #include "MEM_guardedalloc.h"
49
50 #include "IMB_imbuf_types.h"
51 #include "IMB_imbuf.h"
52
53 #ifdef WITH_OPENEXR
54 #include "intern/openexr/openexr_multi.h"
55 #endif
56
57 #include "DNA_packedFile_types.h"
58 #include "DNA_scene_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_camera_types.h"
61 #include "DNA_sequence_types.h"
62 #include "DNA_userdef_types.h"
63 #include "DNA_brush_types.h"
64 #include "DNA_mesh_types.h"
65 #include "DNA_meshdata_types.h"
66
67 #include "BLI_blenlib.h"
68 #include "BLI_threads.h"
69 #include "BLI_utildefines.h"
70 #include "BLI_bpath.h"
71
72 #include "BKE_bmfont.h"
73 #include "BKE_global.h"
74 #include "BKE_icons.h"
75 #include "BKE_image.h"
76 #include "BKE_library.h"
77 #include "BKE_main.h"
78 #include "BKE_packedFile.h"
79 #include "BKE_scene.h"
80 #include "BKE_node.h"
81 #include "BKE_sequencer.h" /* seq_foreground_frame_get() */
82 #include "BKE_utildefines.h"
83
84 #include "BLF_api.h"
85
86 #include "PIL_time.h"
87
88 #include "RE_pipeline.h"
89
90 #include "GPU_draw.h"
91
92 #include "BLO_sys_types.h" // for intptr_t support
93
94 /* for image user iteration */
95 #include "DNA_node_types.h"
96 #include "DNA_space_types.h"
97 #include "DNA_screen_types.h"
98 #include "DNA_view3d_types.h"
99
100 #include "WM_api.h"
101
102 /* max int, to indicate we don't store sequences in ibuf */
103 #define IMA_NO_INDEX    0x7FEFEFEF
104
105 /* quick lookup: supports 1 million frames, thousand passes */
106 #define IMA_MAKE_INDEX(frame, index)    ((frame) << 10) + index
107 #define IMA_INDEX_FRAME(index)          (index >> 10)
108 #define IMA_INDEX_PASS(index)           (index & ~1023)
109
110 /* ******** IMAGE PROCESSING ************* */
111
112 static void de_interlace_ng(struct ImBuf *ibuf) /* neogeo fields */
113 {
114         struct ImBuf *tbuf1, *tbuf2;
115         
116         if (ibuf == NULL) return;
117         if (ibuf->flags & IB_fields) return;
118         ibuf->flags |= IB_fields;
119         
120         if (ibuf->rect) {
121                 /* make copies */
122                 tbuf1 = IMB_allocImBuf(ibuf->x, (ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
123                 tbuf2 = IMB_allocImBuf(ibuf->x, (ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
124                 
125                 ibuf->x *= 2;
126                 
127                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
128                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
129                 
130                 ibuf->x /= 2;
131                 IMB_rectcpy(ibuf, tbuf1, 0, 0, 0, 0, tbuf1->x, tbuf1->y);
132                 IMB_rectcpy(ibuf, tbuf2, 0, tbuf2->y, 0, 0, tbuf2->x, tbuf2->y);
133                 
134                 IMB_freeImBuf(tbuf1);
135                 IMB_freeImBuf(tbuf2);
136         }
137         ibuf->y /= 2;
138 }
139
140 static void de_interlace_st(struct ImBuf *ibuf) /* standard fields */
141 {
142         struct ImBuf *tbuf1, *tbuf2;
143         
144         if (ibuf == NULL) return;
145         if (ibuf->flags & IB_fields) return;
146         ibuf->flags |= IB_fields;
147         
148         if (ibuf->rect) {
149                 /* make copies */
150                 tbuf1 = IMB_allocImBuf(ibuf->x, (ibuf->y >> 1), (unsigned char)32, IB_rect);
151                 tbuf2 = IMB_allocImBuf(ibuf->x, (ibuf->y >> 1), (unsigned char)32, IB_rect);
152                 
153                 ibuf->x *= 2;
154                 
155                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
156                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
157                 
158                 ibuf->x /= 2;
159                 IMB_rectcpy(ibuf, tbuf2, 0, 0, 0, 0, tbuf2->x, tbuf2->y);
160                 IMB_rectcpy(ibuf, tbuf1, 0, tbuf2->y, 0, 0, tbuf1->x, tbuf1->y);
161                 
162                 IMB_freeImBuf(tbuf1);
163                 IMB_freeImBuf(tbuf2);
164         }
165         ibuf->y /= 2;
166 }
167
168 void BKE_image_de_interlace(Image *ima, int odd)
169 {
170         ImBuf *ibuf = BKE_image_get_ibuf(ima, NULL);
171         if (ibuf) {
172                 if (odd)
173                         de_interlace_st(ibuf);
174                 else
175                         de_interlace_ng(ibuf);
176         }
177 }
178
179 /* ***************** ALLOC & FREE, DATA MANAGING *************** */
180
181 static void image_free_buffers(Image *ima)
182 {
183         ImBuf *ibuf;
184         
185         while ((ibuf = ima->ibufs.first)) {
186                 BLI_remlink(&ima->ibufs, ibuf);
187                 
188                 if (ibuf->userdata) {
189                         MEM_freeN(ibuf->userdata);
190                         ibuf->userdata = NULL;
191                 }
192                 IMB_freeImBuf(ibuf);
193         }
194         
195         if (ima->anim) IMB_free_anim(ima->anim);
196         ima->anim = NULL;
197
198         if (ima->rr) {
199                 RE_FreeRenderResult(ima->rr);
200                 ima->rr = NULL;
201         }       
202         
203         GPU_free_image(ima);
204         
205         ima->ok = IMA_OK;
206 }
207
208 /* called by library too, do not free ima itself */
209 void BKE_image_free(Image *ima)
210 {
211         int a;
212
213         image_free_buffers(ima);
214         if (ima->packedfile) {
215                 freePackedFile(ima->packedfile);
216                 ima->packedfile = NULL;
217         }
218         BKE_icon_delete(&ima->id);
219         ima->id.icon_id = 0;
220
221         BKE_previewimg_free(&ima->preview);
222
223         for (a = 0; a < IMA_MAX_RENDER_SLOT; a++) {
224                 if (ima->renders[a]) {
225                         RE_FreeRenderResult(ima->renders[a]);
226                         ima->renders[a] = NULL;
227                 }
228         }
229 }
230
231 /* only image block itself */
232 static Image *image_alloc(const char *name, short source, short type)
233 {
234         Image *ima;
235         
236         ima = BKE_libblock_alloc(&G.main->image, ID_IM, name);
237         if (ima) {
238                 ima->ok = IMA_OK;
239                 
240                 ima->xrep = ima->yrep = 1;
241                 ima->aspx = ima->aspy = 1.0;
242                 ima->gen_x = 1024; ima->gen_y = 1024;
243                 ima->gen_type = 1;   /* no defines yet? */
244                 
245                 ima->source = source;
246                 ima->type = type;
247         }
248         return ima;
249 }
250
251 /* get the ibuf from an image cache, local use here only */
252 static ImBuf *image_get_ibuf(Image *ima, int index, int frame)
253 {
254         /* this function is intended to be thread safe. with IMA_NO_INDEX this
255          * should be OK, but when iterating over the list this is more tricky
256          * */
257         if (index == IMA_NO_INDEX)
258                 return ima->ibufs.first;
259         else {
260                 ImBuf *ibuf;
261
262                 index = IMA_MAKE_INDEX(frame, index);
263                 for (ibuf = ima->ibufs.first; ibuf; ibuf = ibuf->next)
264                         if (ibuf->index == index)
265                                 return ibuf;
266
267                 return NULL;
268         }
269 }
270
271 /* no ima->ibuf anymore, but listbase */
272 static void image_remove_ibuf(Image *ima, ImBuf *ibuf)
273 {
274         if (ibuf) {
275                 BLI_remlink(&ima->ibufs, ibuf);
276                 IMB_freeImBuf(ibuf);
277         }
278 }
279
280
281 /* no ima->ibuf anymore, but listbase */
282 static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int frame)
283 {
284         if (ibuf) {
285                 ImBuf *link;
286                 
287                 if (index != IMA_NO_INDEX)
288                         index = IMA_MAKE_INDEX(frame, index);
289                 
290                 /* insert based on index */
291                 for (link = ima->ibufs.first; link; link = link->next)
292                         if (link->index >= index)
293                                 break;
294
295                 ibuf->index = index;
296                 if (ima->flag & IMA_CM_PREDIVIDE)
297                         ibuf->flags |= IB_cm_predivide;
298                 else
299                         ibuf->flags &= ~IB_cm_predivide;
300
301                 /* this function accepts (link == NULL) */
302                 BLI_insertlinkbefore(&ima->ibufs, link, ibuf);
303
304                 /* now we don't want copies? */
305                 if (link && ibuf->index == link->index)
306                         image_remove_ibuf(ima, link);
307         }
308 }
309
310 /* empty image block, of similar type and filename */
311 Image *BKE_image_copy(Image *ima)
312 {
313         Image *nima = image_alloc(ima->id.name + 2, ima->source, ima->type);
314
315         BLI_strncpy(nima->name, ima->name, sizeof(ima->name));
316
317         nima->flag = ima->flag;
318         nima->tpageflag = ima->tpageflag;
319         
320         nima->gen_x = ima->gen_x;
321         nima->gen_y = ima->gen_y;
322         nima->gen_type = ima->gen_type;
323
324         nima->animspeed = ima->animspeed;
325
326         nima->aspx = ima->aspx;
327         nima->aspy = ima->aspy;
328
329         return nima;
330 }
331
332 static void extern_local_image(Image *UNUSED(ima))
333 {
334         /* Nothing to do: images don't link to other IDs. This function exists to
335          * match id_make_local pattern. */
336 }
337
338 void BKE_image_make_local(struct Image *ima)
339 {
340         Main *bmain = G.main;
341         Tex *tex;
342         Brush *brush;
343         Mesh *me;
344         int is_local = FALSE, is_lib = FALSE;
345
346         /* - only lib users: do nothing
347          * - only local users: set flag
348          * - mixed: make copy
349          */
350
351         if (ima->id.lib == NULL) return;
352
353         /* Can't take short cut here: must check meshes at least because of bogus
354          * texface ID refs. - z0r */
355 #if 0
356         if (ima->id.us == 1) {
357                 id_clear_lib_data(bmain, &ima->id);
358                 extern_local_image(ima);
359                 return;
360         }
361 #endif
362
363         for (tex = bmain->tex.first; tex; tex = tex->id.next) {
364                 if (tex->ima == ima) {
365                         if (tex->id.lib) is_lib = TRUE;
366                         else is_local = TRUE;
367                 }
368         }
369         for (brush = bmain->brush.first; brush; brush = brush->id.next) {
370                 if (brush->clone.image == ima) {
371                         if (brush->id.lib) is_lib = TRUE;
372                         else is_local = TRUE;
373                 }
374         }
375         for (me = bmain->mesh.first; me; me = me->id.next) {
376                 if (me->mtface) {
377                         MTFace *tface;
378                         int a, i;
379
380                         for (i = 0; i < me->fdata.totlayer; i++) {
381                                 if (me->fdata.layers[i].type == CD_MTFACE) {
382                                         tface = (MTFace *)me->fdata.layers[i].data;
383
384                                         for (a = 0; a < me->totface; a++, tface++) {
385                                                 if (tface->tpage == ima) {
386                                                         if (me->id.lib) is_lib = TRUE;
387                                                         else is_local = TRUE;
388                                                 }
389                                         }
390                                 }
391                         }
392                 }
393
394                 if (me->mtpoly) {
395                         MTexPoly *mtpoly;
396                         int a, i;
397
398                         for (i = 0; i < me->pdata.totlayer; i++) {
399                                 if (me->pdata.layers[i].type == CD_MTEXPOLY) {
400                                         mtpoly = (MTexPoly *)me->pdata.layers[i].data;
401
402                                         for (a = 0; a < me->totpoly; a++, mtpoly++) {
403                                                 if (mtpoly->tpage == ima) {
404                                                         if (me->id.lib) is_lib = TRUE;
405                                                         else is_local = TRUE;
406                                                 }
407                                         }
408                                 }
409                         }
410                 }
411
412         }
413
414         if (is_local && is_lib == FALSE) {
415                 id_clear_lib_data(bmain, &ima->id);
416                 extern_local_image(ima);
417         }
418         else if (is_local && is_lib) {
419                 Image *ima_new = BKE_image_copy(ima);
420
421                 ima_new->id.us = 0;
422
423                 /* Remap paths of new ID using old library as base. */
424                 BKE_id_lib_local_paths(bmain, ima->id.lib, &ima_new->id);
425
426                 tex = bmain->tex.first;
427                 while (tex) {
428                         if (tex->id.lib == NULL) {
429                                 if (tex->ima == ima) {
430                                         tex->ima = ima_new;
431                                         ima_new->id.us++;
432                                         ima->id.us--;
433                                 }
434                         }
435                         tex = tex->id.next;
436                 }
437                 brush = bmain->brush.first;
438                 while (brush) {
439                         if (brush->id.lib == NULL) {
440                                 if (brush->clone.image == ima) {
441                                         brush->clone.image = ima_new;
442                                         ima_new->id.us++;
443                                         ima->id.us--;
444                                 }
445                         }
446                         brush = brush->id.next;
447                 }
448                 /* Transfer references in texfaces. Texfaces don't add to image ID
449                  * user count *unless* there are no other users. See
450                  * readfile.c:lib_link_mtface. */
451                 me = bmain->mesh.first;
452                 while (me) {
453                         if (me->mtface) {
454                                 MTFace *tface;
455                                 int a, i;
456
457                                 for (i = 0; i < me->fdata.totlayer; i++) {
458                                         if (me->fdata.layers[i].type == CD_MTFACE) {
459                                                 tface = (MTFace *)me->fdata.layers[i].data;
460
461                                                 for (a = 0; a < me->totface; a++, tface++) {
462                                                         if (tface->tpage == ima) {
463                                                                 tface->tpage = ima_new;
464                                                                 if (ima_new->id.us == 0) {
465                                                                         tface->tpage->id.us = 1;
466                                                                 }
467                                                                 id_lib_extern((ID *)ima_new);
468                                                         }
469                                                 }
470                                         }
471                                 }
472                         }
473
474                         if (me->mtpoly) {
475                                 MTexPoly *mtpoly;
476                                 int a, i;
477
478                                 for (i = 0; i < me->pdata.totlayer; i++) {
479                                         if (me->pdata.layers[i].type == CD_MTEXPOLY) {
480                                                 mtpoly = (MTexPoly *)me->pdata.layers[i].data;
481
482                                                 for (a = 0; a < me->totpoly; a++, mtpoly++) {
483                                                         if (mtpoly->tpage == ima) {
484                                                                 mtpoly->tpage = ima_new;
485                                                                 if (ima_new->id.us == 0) {
486                                                                         mtpoly->tpage->id.us = 1;
487                                                                 }
488                                                                 id_lib_extern((ID *)ima_new);
489                                                         }
490                                                 }
491                                         }
492                                 }
493                         }
494
495                         me = me->id.next;
496                 }
497         }
498 }
499
500 void BKE_image_merge(Image *dest, Image *source)
501 {
502         ImBuf *ibuf;
503         
504         /* sanity check */
505         if (dest && source && dest != source) {
506         
507                 while ((ibuf = source->ibufs.first)) {
508                         BLI_remlink(&source->ibufs, ibuf);
509                         image_assign_ibuf(dest, ibuf, IMA_INDEX_PASS(ibuf->index), IMA_INDEX_FRAME(ibuf->index));
510                 }
511                 
512                 BKE_libblock_free(&G.main->image, source);
513         }
514 }
515
516 /* note, we could be clever and scale all imbuf's but since some are mipmaps its not so simple */
517 void BKE_image_scale(Image *image, int width, int height)
518 {
519         ImBuf *ibuf;
520         void *lock;
521
522         ibuf = BKE_image_acquire_ibuf(image, NULL, &lock);
523
524         IMB_scaleImBuf(ibuf, width, height);
525         ibuf->userflags |= IB_BITMAPDIRTY;
526
527         BKE_image_release_ibuf(image, lock);
528 }
529
530 Image *BKE_image_load(const char *filepath)
531 {
532         Image *ima;
533         int file, len;
534         const char *libname;
535         char str[FILE_MAX];
536
537         BLI_strncpy(str, filepath, sizeof(str));
538         BLI_path_abs(str, G.main->name);
539
540         /* exists? */
541         file = BLI_open(str, O_BINARY | O_RDONLY, 0);
542         if (file == -1) return NULL;
543         close(file);
544
545         /* create a short library name */
546         len = strlen(filepath);
547
548         while (len > 0 && filepath[len - 1] != '/' && filepath[len - 1] != '\\') len--;
549         libname = filepath + len;
550
551         ima = image_alloc(libname, IMA_SRC_FILE, IMA_TYPE_IMAGE);
552         BLI_strncpy(ima->name, filepath, sizeof(ima->name));
553
554         if (BLI_testextensie_array(filepath, imb_ext_movie))
555                 ima->source = IMA_SRC_MOVIE;
556
557         return ima;
558 }
559
560 /* checks if image was already loaded, then returns same image */
561 /* otherwise creates new. */
562 /* does not load ibuf itself */
563 /* pass on optional frame for #name images */
564 Image *BKE_image_load_exists(const char *filepath)
565 {
566         Image *ima;
567         char str[FILE_MAX], strtest[FILE_MAX];
568         
569         BLI_strncpy(str, filepath, sizeof(str));
570         BLI_path_abs(str, G.main->name);
571
572         /* first search an identical image */
573         for (ima = G.main->image.first; ima; ima = ima->id.next) {
574                 if (ima->source != IMA_SRC_VIEWER && ima->source != IMA_SRC_GENERATED) {
575                         BLI_strncpy(strtest, ima->name, sizeof(ima->name));
576                         BLI_path_abs(strtest, G.main->name);
577                         
578                         if (BLI_path_cmp(strtest, str) == 0) {
579                                 if (ima->anim == NULL || ima->id.us == 0) {
580                                         BLI_strncpy(ima->name, filepath, sizeof(ima->name));    /* for stringcode */
581                                         ima->id.us++;                                       /* officially should not, it doesn't link here! */
582                                         if (ima->ok == 0)
583                                                 ima->ok = IMA_OK;
584                                         /* RETURN! */
585                                         return ima;
586                                 }
587                         }
588                 }
589         }
590
591         return BKE_image_load(filepath);
592 }
593
594 static ImBuf *add_ibuf_size(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short uvtestgrid, float color[4])
595 {
596         ImBuf *ibuf;
597         unsigned char *rect = NULL;
598         float *rect_float = NULL;
599         
600         if (floatbuf) {
601                 ibuf = IMB_allocImBuf(width, height, depth, IB_rectfloat);
602                 rect_float = (float *)ibuf->rect_float;
603                 ibuf->profile = IB_PROFILE_LINEAR_RGB;
604         }
605         else {
606                 ibuf = IMB_allocImBuf(width, height, depth, IB_rect);
607                 rect = (unsigned char *)ibuf->rect;
608                 ibuf->profile = IB_PROFILE_SRGB;
609         }
610         
611         BLI_strncpy(ibuf->name, name, sizeof(ibuf->name));
612         ibuf->userflags |= IB_BITMAPDIRTY;
613         
614         switch (uvtestgrid) {
615                 case 1:
616                         BKE_image_buf_fill_checker(rect, rect_float, width, height);
617                         break;
618                 case 2:
619                         BKE_image_buf_fill_checker_color(rect, rect_float, width, height);
620                         break;
621                 default:
622                         BKE_image_buf_fill_color(rect, rect_float, width, height, color);
623         }
624
625         return ibuf;
626 }
627
628 /* adds new image block, creates ImBuf and initializes color */
629 Image *BKE_image_add_generated(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short uvtestgrid, float color[4])
630 {
631         /* on save, type is changed to FILE in editsima.c */
632         Image *ima = image_alloc(name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
633         
634         if (ima) {
635                 ImBuf *ibuf;
636                 
637                 /* BLI_strncpy(ima->name, name, FILE_MAX); */ /* don't do this, this writes in ain invalid filepath! */
638                 ima->gen_x = width;
639                 ima->gen_y = height;
640                 ima->gen_type = uvtestgrid;
641                 ima->gen_flag |= (floatbuf ? IMA_GEN_FLOAT : 0);
642                 
643                 ibuf = add_ibuf_size(width, height, ima->name, depth, floatbuf, uvtestgrid, color);
644                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
645                 
646                 ima->ok = IMA_OK_LOADED;
647         }
648
649         return ima;
650 }
651
652 /* creates an image image owns the imbuf passed */
653 Image *BKE_image_add_from_imbuf(ImBuf *ibuf)
654 {
655         /* on save, type is changed to FILE in editsima.c */
656         Image *ima;
657
658         ima = image_alloc(BLI_path_basename(ibuf->name), IMA_SRC_FILE, IMA_TYPE_IMAGE);
659
660         if (ima) {
661                 BLI_strncpy(ima->name, ibuf->name, FILE_MAX);
662                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
663                 ima->ok = IMA_OK_LOADED;
664         }
665
666         return ima;
667 }
668
669 /* packs rect from memory as PNG */
670 void BKE_image_memorypack(Image *ima)
671 {
672         ImBuf *ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
673         
674         if (ibuf == NULL)
675                 return;
676         if (ima->packedfile) {
677                 freePackedFile(ima->packedfile);
678                 ima->packedfile = NULL;
679         }
680         
681         ibuf->ftype = PNG;
682         ibuf->planes = R_IMF_PLANES_RGBA;
683         
684         IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem);
685         if (ibuf->encodedbuffer == NULL) {
686                 printf("memory save for pack error\n");
687         }
688         else {
689                 PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
690                 
691                 pf->data = ibuf->encodedbuffer;
692                 pf->size = ibuf->encodedsize;
693                 ima->packedfile = pf;
694                 ibuf->encodedbuffer = NULL;
695                 ibuf->encodedsize = 0;
696                 ibuf->userflags &= ~IB_BITMAPDIRTY;
697                 
698                 if (ima->source == IMA_SRC_GENERATED) {
699                         ima->source = IMA_SRC_FILE;
700                         ima->type = IMA_TYPE_IMAGE;
701                 }
702         }
703 }
704
705 void BKE_image_tag_time(Image *ima)
706 {
707         if (ima)
708                 ima->lastused = (int)PIL_check_seconds_timer();
709 }
710
711 #if 0
712 static void tag_all_images_time() 
713 {
714         Image *ima;
715         int ctime = (int)PIL_check_seconds_timer();
716
717         ima = G.main->image.first;
718         while (ima) {
719                 if (ima->bindcode || ima->repbind || ima->ibufs.first) {
720                         ima->lastused = ctime;
721                 }
722         }
723 }
724 #endif
725
726 void free_old_images(void)
727 {
728         Image *ima;
729         static int lasttime = 0;
730         int ctime = (int)PIL_check_seconds_timer();
731         
732         /* 
733          * Run garbage collector once for every collecting period of time 
734          * if textimeout is 0, that's the option to NOT run the collector
735          */
736         if (U.textimeout == 0 || ctime % U.texcollectrate || ctime == lasttime)
737                 return;
738
739         /* of course not! */
740         if (G.rendering)
741                 return;
742         
743         lasttime = ctime;
744
745         ima = G.main->image.first;
746         while (ima) {
747                 if ((ima->flag & IMA_NOCOLLECT) == 0 && ctime - ima->lastused > U.textimeout) {
748                         /* If it's in GL memory, deallocate and set time tag to current time
749                          * This gives textures a "second chance" to be used before dying. */
750                         if (ima->bindcode || ima->repbind) {
751                                 GPU_free_image(ima);
752                                 ima->lastused = ctime;
753                         }
754                         /* Otherwise, just kill the buffers */
755                         else if (ima->ibufs.first) {
756                                 image_free_buffers(ima);
757                         }
758                 }
759                 ima = ima->id.next;
760         }
761 }
762
763 static uintptr_t image_mem_size(Image *ima)
764 {
765         ImBuf *ibuf, *ibufm;
766         int level;
767         uintptr_t size = 0;
768
769         size = 0;
770         
771         /* viewers have memory depending on other rules, has no valid rect pointer */
772         if (ima->source == IMA_SRC_VIEWER)
773                 return 0;
774         
775         for (ibuf = ima->ibufs.first; ibuf; ibuf = ibuf->next) {
776                 if (ibuf->rect) size += MEM_allocN_len(ibuf->rect);
777                 else if (ibuf->rect_float) size += MEM_allocN_len(ibuf->rect_float);
778
779                 for (level = 0; level < IB_MIPMAP_LEVELS; level++) {
780                         ibufm = ibuf->mipmap[level];
781                         if (ibufm) {
782                                 if (ibufm->rect) size += MEM_allocN_len(ibufm->rect);
783                                 else if (ibufm->rect_float) size += MEM_allocN_len(ibufm->rect_float);
784                         }
785                 }
786         }
787
788         return size;
789 }
790
791 void BKE_image_print_memlist(void)
792 {
793         Image *ima;
794         uintptr_t size, totsize = 0;
795
796         for (ima = G.main->image.first; ima; ima = ima->id.next)
797                 totsize += image_mem_size(ima);
798
799         printf("\ntotal image memory len: %.3f MB\n", (double)totsize / (double)(1024 * 1024));
800
801         for (ima = G.main->image.first; ima; ima = ima->id.next) {
802                 size = image_mem_size(ima);
803
804                 if (size)
805                         printf("%s len: %.3f MB\n", ima->id.name + 2, (double)size / (double)(1024 * 1024));
806         }
807 }
808
809 void BKE_image_free_all_textures(void)
810 {
811         Tex *tex;
812         Image *ima;
813         /* unsigned int totsize = 0; */
814         
815         for (ima = G.main->image.first; ima; ima = ima->id.next)
816                 ima->id.flag &= ~LIB_DOIT;
817         
818         for (tex = G.main->tex.first; tex; tex = tex->id.next)
819                 if (tex->ima)
820                         tex->ima->id.flag |= LIB_DOIT;
821         
822         for (ima = G.main->image.first; ima; ima = ima->id.next) {
823                 if (ima->ibufs.first && (ima->id.flag & LIB_DOIT)) {
824                         ImBuf *ibuf;
825                         
826                         for (ibuf = ima->ibufs.first; ibuf; ibuf = ibuf->next) {
827                                 /* escape when image is painted on */
828                                 if (ibuf->userflags & IB_BITMAPDIRTY)
829                                         break;
830                                 
831 #if 0
832                                 if (ibuf->mipmap[0]) 
833                                         totsize += 1.33 * ibuf->x * ibuf->y * 4;
834                                 else
835                                         totsize += ibuf->x * ibuf->y * 4;
836 #endif
837                         }
838                         if (ibuf == NULL)
839                                 image_free_buffers(ima);
840                 }
841         }
842         /* printf("freed total %d MB\n", totsize/(1024*1024)); */
843 }
844
845 /* except_frame is weak, only works for seqs without offset... */
846 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
847 {
848         ImBuf *ibuf, *nbuf;
849
850         for (ibuf = ima->ibufs.first; ibuf; ibuf = nbuf) {
851                 nbuf = ibuf->next;
852                 if (ibuf->userflags & IB_BITMAPDIRTY)
853                         continue;
854                 if (ibuf->index == IMA_NO_INDEX)
855                         continue;
856                 if (except_frame != IMA_INDEX_FRAME(ibuf->index)) {
857                         BLI_remlink(&ima->ibufs, ibuf);
858                         
859                         if (ibuf->userdata) {
860                                 MEM_freeN(ibuf->userdata);
861                                 ibuf->userdata = NULL;
862                         }
863                         IMB_freeImBuf(ibuf);
864                 }                                       
865         }
866 }
867
868 void BKE_image_all_free_anim_ibufs(int cfra)
869 {
870         Image *ima;
871         
872         for (ima = G.main->image.first; ima; ima = ima->id.next)
873                 if (ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE))
874                         BKE_image_free_anim_ibufs(ima, cfra);
875 }
876
877
878 /* *********** READ AND WRITE ************** */
879
880 int BKE_imtype_to_ftype(const char imtype)
881 {
882         if (imtype == R_IMF_IMTYPE_TARGA)
883                 return TGA;
884         else if (imtype == R_IMF_IMTYPE_RAWTGA)
885                 return RAWTGA;
886         else if (imtype == R_IMF_IMTYPE_IRIS)
887                 return IMAGIC;
888 #ifdef WITH_HDR
889         else if (imtype == R_IMF_IMTYPE_RADHDR)
890                 return RADHDR;
891 #endif
892         else if (imtype == R_IMF_IMTYPE_PNG)
893                 return PNG;
894 #ifdef WITH_DDS
895         else if (imtype == R_IMF_IMTYPE_DDS)
896                 return DDS;
897 #endif
898         else if (imtype == R_IMF_IMTYPE_BMP)
899                 return BMP;
900 #ifdef WITH_TIFF
901         else if (imtype == R_IMF_IMTYPE_TIFF)
902                 return TIF;
903 #endif
904         else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER)
905                 return OPENEXR;
906 #ifdef WITH_CINEON
907         else if (imtype == R_IMF_IMTYPE_CINEON)
908                 return CINEON;
909         else if (imtype == R_IMF_IMTYPE_DPX)
910                 return DPX;
911 #endif
912 #ifdef WITH_OPENJPEG
913         else if (imtype == R_IMF_IMTYPE_JP2)
914                 return JP2;
915 #endif
916         else
917                 return JPG | 90;
918 }
919
920 char BKE_ftype_to_imtype(const int ftype)
921 {
922         if (ftype == 0)
923                 return R_IMF_IMTYPE_TARGA;
924         else if (ftype == IMAGIC) 
925                 return R_IMF_IMTYPE_IRIS;
926 #ifdef WITH_HDR
927         else if (ftype & RADHDR)
928                 return R_IMF_IMTYPE_RADHDR;
929 #endif
930         else if (ftype & PNG)
931                 return R_IMF_IMTYPE_PNG;
932 #ifdef WITH_DDS
933         else if (ftype & DDS)
934                 return R_IMF_IMTYPE_DDS;
935 #endif
936         else if (ftype & BMP)
937                 return R_IMF_IMTYPE_BMP;
938 #ifdef WITH_TIFF
939         else if (ftype & TIF)
940                 return R_IMF_IMTYPE_TIFF;
941 #endif
942         else if (ftype & OPENEXR)
943                 return R_IMF_IMTYPE_OPENEXR;
944 #ifdef WITH_CINEON
945         else if (ftype & CINEON)
946                 return R_IMF_IMTYPE_CINEON;
947         else if (ftype & DPX)
948                 return R_IMF_IMTYPE_DPX;
949 #endif
950         else if (ftype & TGA)
951                 return R_IMF_IMTYPE_TARGA;
952         else if (ftype & RAWTGA)
953                 return R_IMF_IMTYPE_RAWTGA;
954 #ifdef WITH_OPENJPEG
955         else if (ftype & JP2)
956                 return R_IMF_IMTYPE_JP2;
957 #endif
958         else
959                 return R_IMF_IMTYPE_JPEG90;
960 }
961
962
963 int BKE_imtype_is_movie(const char imtype)
964 {
965         switch (imtype) {
966                 case R_IMF_IMTYPE_AVIRAW:
967                 case R_IMF_IMTYPE_AVIJPEG:
968                 case R_IMF_IMTYPE_AVICODEC:
969                 case R_IMF_IMTYPE_QUICKTIME:
970                 case R_IMF_IMTYPE_FFMPEG:
971                 case R_IMF_IMTYPE_H264:
972                 case R_IMF_IMTYPE_THEORA:
973                 case R_IMF_IMTYPE_XVID:
974                 case R_IMF_IMTYPE_FRAMESERVER:
975                         return 1;
976         }
977         return 0;
978 }
979
980 int BKE_imtype_supports_zbuf(const char imtype)
981 {
982         switch (imtype) {
983                 case R_IMF_IMTYPE_IRIZ:
984                 case R_IMF_IMTYPE_OPENEXR: /* but not R_IMF_IMTYPE_MULTILAYER */
985                         return 1;
986         }
987         return 0;
988 }
989
990 int BKE_imtype_supports_compress(const char imtype)
991 {
992         switch (imtype) {
993                 case R_IMF_IMTYPE_PNG:
994                         return 1;
995         }
996         return 0;
997 }
998
999 int BKE_imtype_supports_quality(const char imtype)
1000 {
1001         switch (imtype) {
1002                 case R_IMF_IMTYPE_JPEG90:
1003                 case R_IMF_IMTYPE_JP2:
1004                 case R_IMF_IMTYPE_AVIJPEG:
1005                         return 1;
1006         }
1007         return 0;
1008 }
1009
1010 char BKE_imtype_valid_channels(const char imtype)
1011 {
1012         char chan_flag = IMA_CHAN_FLAG_RGB; /* assume all support rgb */
1013
1014         /* alpha */
1015         switch (imtype) {
1016                 case R_IMF_IMTYPE_TARGA:
1017                 case R_IMF_IMTYPE_IRIS:
1018                 case R_IMF_IMTYPE_PNG:
1019                 /* case R_IMF_IMTYPE_BMP: */ /* read but not write */
1020                 case R_IMF_IMTYPE_RADHDR:
1021                 case R_IMF_IMTYPE_TIFF:
1022                 case R_IMF_IMTYPE_OPENEXR:
1023                 case R_IMF_IMTYPE_MULTILAYER:
1024                 case R_IMF_IMTYPE_DDS:
1025                 case R_IMF_IMTYPE_JP2:
1026                 case R_IMF_IMTYPE_QUICKTIME:
1027                         chan_flag |= IMA_CHAN_FLAG_ALPHA;
1028         }
1029
1030         /* bw */
1031         switch (imtype) {
1032                 case R_IMF_IMTYPE_PNG:
1033                 case R_IMF_IMTYPE_JPEG90:
1034                 case R_IMF_IMTYPE_TARGA:
1035                 case R_IMF_IMTYPE_RAWTGA:
1036                 case R_IMF_IMTYPE_TIFF:
1037                 case R_IMF_IMTYPE_IRIS:
1038                         chan_flag |= IMA_CHAN_FLAG_BW;
1039         }
1040
1041         return chan_flag;
1042 }
1043
1044 char BKE_imtype_valid_depths(const char imtype)
1045 {
1046         switch (imtype) {
1047                 case R_IMF_IMTYPE_RADHDR:
1048                         return R_IMF_CHAN_DEPTH_32;
1049                 case R_IMF_IMTYPE_TIFF:
1050                         return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_16;
1051                 case R_IMF_IMTYPE_OPENEXR:
1052                         return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32;
1053                 case R_IMF_IMTYPE_MULTILAYER:
1054                         return R_IMF_CHAN_DEPTH_32;
1055                 /* eeh, cineone does some strange 10bits per channel */
1056                 case R_IMF_IMTYPE_DPX:
1057                 case R_IMF_IMTYPE_CINEON:
1058                         return R_IMF_CHAN_DEPTH_12;
1059                 case R_IMF_IMTYPE_JP2:
1060                         return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
1061                 /* most formats are 8bit only */
1062                 default:
1063                         return R_IMF_CHAN_DEPTH_8;
1064         }
1065 }
1066
1067
1068 /* string is from command line --render-format arg, keep in sync with
1069  * creator.c help info */
1070 char BKE_imtype_from_arg(const char *imtype_arg)
1071 {
1072         if      (!strcmp(imtype_arg, "TGA")) return R_IMF_IMTYPE_TARGA;
1073         else if (!strcmp(imtype_arg, "IRIS")) return R_IMF_IMTYPE_IRIS;
1074 #ifdef WITH_DDS
1075         else if (!strcmp(imtype_arg, "DDS")) return R_IMF_IMTYPE_DDS;
1076 #endif
1077         else if (!strcmp(imtype_arg, "JPEG")) return R_IMF_IMTYPE_JPEG90;
1078         else if (!strcmp(imtype_arg, "IRIZ")) return R_IMF_IMTYPE_IRIZ;
1079         else if (!strcmp(imtype_arg, "RAWTGA")) return R_IMF_IMTYPE_RAWTGA;
1080         else if (!strcmp(imtype_arg, "AVIRAW")) return R_IMF_IMTYPE_AVIRAW;
1081         else if (!strcmp(imtype_arg, "AVIJPEG")) return R_IMF_IMTYPE_AVIJPEG;
1082         else if (!strcmp(imtype_arg, "PNG")) return R_IMF_IMTYPE_PNG;
1083         else if (!strcmp(imtype_arg, "AVICODEC")) return R_IMF_IMTYPE_AVICODEC;
1084         else if (!strcmp(imtype_arg, "QUICKTIME")) return R_IMF_IMTYPE_QUICKTIME;
1085         else if (!strcmp(imtype_arg, "BMP")) return R_IMF_IMTYPE_BMP;
1086 #ifdef WITH_HDR
1087         else if (!strcmp(imtype_arg, "HDR")) return R_IMF_IMTYPE_RADHDR;
1088 #endif
1089 #ifdef WITH_TIFF
1090         else if (!strcmp(imtype_arg, "TIFF")) return R_IMF_IMTYPE_TIFF;
1091 #endif
1092 #ifdef WITH_OPENEXR
1093         else if (!strcmp(imtype_arg, "EXR")) return R_IMF_IMTYPE_OPENEXR;
1094         else if (!strcmp(imtype_arg, "MULTILAYER")) return R_IMF_IMTYPE_MULTILAYER;
1095 #endif
1096         else if (!strcmp(imtype_arg, "MPEG")) return R_IMF_IMTYPE_FFMPEG;
1097         else if (!strcmp(imtype_arg, "FRAMESERVER")) return R_IMF_IMTYPE_FRAMESERVER;
1098 #ifdef WITH_CINEON
1099         else if (!strcmp(imtype_arg, "CINEON")) return R_IMF_IMTYPE_CINEON;
1100         else if (!strcmp(imtype_arg, "DPX")) return R_IMF_IMTYPE_DPX;
1101 #endif
1102 #ifdef WITH_OPENJPEG
1103         else if (!strcmp(imtype_arg, "JP2")) return R_IMF_IMTYPE_JP2;
1104 #endif
1105         else return R_IMF_IMTYPE_INVALID;
1106 }
1107
1108 int BKE_add_image_extension(char *string, const char imtype)
1109 {
1110         const char *extension = NULL;
1111         
1112         if (imtype == R_IMF_IMTYPE_IRIS) {
1113                 if (!BLI_testextensie(string, ".rgb"))
1114                         extension = ".rgb";
1115         }
1116         else if (imtype == R_IMF_IMTYPE_IRIZ) {
1117                 if (!BLI_testextensie(string, ".rgb"))
1118                         extension = ".rgb";
1119         }
1120 #ifdef WITH_HDR
1121         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1122                 if (!BLI_testextensie(string, ".hdr"))
1123                         extension = ".hdr";
1124         }
1125 #endif
1126         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1127                 if (!BLI_testextensie(string, ".png"))
1128                         extension = ".png";
1129         }
1130 #ifdef WITH_DDS
1131         else if (imtype == R_IMF_IMTYPE_DDS) {
1132                 if (!BLI_testextensie(string, ".dds"))
1133                         extension = ".dds";
1134         }
1135 #endif
1136         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
1137                 if (!BLI_testextensie(string, ".tga"))
1138                         extension = ".tga";
1139         }
1140         else if (imtype == R_IMF_IMTYPE_BMP) {
1141                 if (!BLI_testextensie(string, ".bmp"))
1142                         extension = ".bmp";
1143         }
1144 #ifdef WITH_TIFF
1145         else if (imtype == R_IMF_IMTYPE_TIFF) {
1146                 if (!BLI_testextensie(string, ".tif") &&
1147                     !BLI_testextensie(string, ".tiff"))
1148                 {
1149                         extension = ".tif";
1150                 }
1151         }
1152 #endif
1153 #ifdef WITH_OPENEXR
1154         else if (ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
1155                 if (!BLI_testextensie(string, ".exr"))
1156                         extension = ".exr";
1157         }
1158 #endif
1159 #ifdef WITH_CINEON
1160         else if (imtype == R_IMF_IMTYPE_CINEON) {
1161                 if (!BLI_testextensie(string, ".cin"))
1162                         extension = ".cin";
1163         }
1164         else if (imtype == R_IMF_IMTYPE_DPX) {
1165                 if (!BLI_testextensie(string, ".dpx"))
1166                         extension = ".dpx";
1167         }
1168 #endif
1169         else if (imtype == R_IMF_IMTYPE_TARGA) {
1170                 if (!BLI_testextensie(string, ".tga"))
1171                         extension = ".tga";
1172         }
1173 #ifdef WITH_OPENJPEG
1174         else if (imtype == R_IMF_IMTYPE_JP2) {
1175                 if (!BLI_testextensie(string, ".jp2"))
1176                         extension = ".jp2";
1177         }
1178 #endif
1179         else { //   R_IMF_IMTYPE_AVICODEC, R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90, R_IMF_IMTYPE_QUICKTIME etc
1180                 if (!(BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
1181                         extension = ".jpg";
1182         }
1183
1184         if (extension) {
1185                 /* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */
1186                 /* remove any other known image extension */
1187                 if (BLI_testextensie_array(string, imb_ext_image) ||
1188                     (G.have_quicktime && BLI_testextensie_array(string, imb_ext_image_qt)))
1189                 {
1190                         return BLI_replace_extension(string, FILE_MAX, extension);
1191                 }
1192                 else {
1193                         return BLI_ensure_extension(string, FILE_MAX, extension);
1194                 }
1195                 
1196         }
1197         else {
1198                 return FALSE;
1199         }
1200 }
1201
1202 void BKE_imformat_defaults(ImageFormatData *im_format)
1203 {
1204         memset(im_format, 0, sizeof(*im_format));
1205         im_format->planes = R_IMF_PLANES_RGB;
1206         im_format->imtype = R_IMF_IMTYPE_PNG;
1207         im_format->quality = 90;
1208         im_format->compress = 90;
1209 }
1210
1211 /* could allow access externally - 512 is for long names, 64 is for id names */
1212 typedef struct StampData {
1213         char file[512];
1214         char note[512];
1215         char date[512];
1216         char marker[512];
1217         char time[512];
1218         char frame[512];
1219         char camera[64];
1220         char cameralens[64];
1221         char scene[64];
1222         char strip[64];
1223         char rendertime[64];
1224 } StampData;
1225
1226 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix)
1227 {
1228         char text[256];
1229         struct tm *tl;
1230         time_t t;
1231
1232         if (scene->r.stamp & R_STAMP_FILENAME) {
1233                 BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), do_prefix ? "File %s" : "%s", G.relbase_valid ? G.main->name : "<untitled>");
1234         }
1235         else {
1236                 stamp_data->file[0] = '\0';
1237         }
1238         
1239         if (scene->r.stamp & R_STAMP_NOTE) {
1240                 /* Never do prefix for Note */
1241                 BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", scene->r.stamp_udata);
1242         }
1243         else {
1244                 stamp_data->note[0] = '\0';
1245         }
1246         
1247         if (scene->r.stamp & R_STAMP_DATE) {
1248                 t = time(NULL);
1249                 tl = localtime(&t);
1250                 BLI_snprintf(text, sizeof(text), "%04d/%02d/%02d %02d:%02d:%02d", tl->tm_year + 1900, tl->tm_mon + 1, tl->tm_mday, tl->tm_hour, tl->tm_min, tl->tm_sec);
1251                 BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), do_prefix ? "Date %s" : "%s", text);
1252         }
1253         else {
1254                 stamp_data->date[0] = '\0';
1255         }
1256         
1257         if (scene->r.stamp & R_STAMP_MARKER) {
1258                 char *name = BKE_scene_find_last_marker_name(scene, CFRA);
1259
1260                 if (name) BLI_strncpy(text, name, sizeof(text));
1261                 else BLI_strncpy(text, "<none>", sizeof(text));
1262
1263                 BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), do_prefix ? "Marker %s" : "%s", text);
1264         }
1265         else {
1266                 stamp_data->marker[0] = '\0';
1267         }
1268         
1269         if (scene->r.stamp & R_STAMP_TIME) {
1270                 int f = (int)(scene->r.cfra % scene->r.frs_sec);
1271                 int s = (int)(scene->r.cfra / scene->r.frs_sec);
1272                 int h = 0;
1273                 int m = 0;
1274
1275                 if (s) {
1276                         m = (int)(s / 60);
1277                         s %= 60;
1278
1279                         if (m) {
1280                                 h = (int)(m / 60);
1281                                 m %= 60;
1282                         }
1283                 }
1284
1285                 if (scene->r.frs_sec < 100)
1286                         BLI_snprintf(text, sizeof(text), "%02d:%02d:%02d.%02d", h, m, s, f);
1287                 else
1288                         BLI_snprintf(text, sizeof(text), "%02d:%02d:%02d.%03d", h, m, s, f);
1289
1290                 BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), do_prefix ? "Time %s" : "%s", text);
1291         }
1292         else {
1293                 stamp_data->time[0] = '\0';
1294         }
1295         
1296         if (scene->r.stamp & R_STAMP_FRAME) {
1297                 char fmtstr[32];
1298                 int digits = 1;
1299                 
1300                 if (scene->r.efra > 9)
1301                         digits = 1 + (int) log10(scene->r.efra);
1302
1303                 BLI_snprintf(fmtstr, sizeof(fmtstr), do_prefix ? "Frame %%0%di" : "%%0%di", digits);
1304                 BLI_snprintf(stamp_data->frame, sizeof(stamp_data->frame), fmtstr, scene->r.cfra);
1305         }
1306         else {
1307                 stamp_data->frame[0] = '\0';
1308         }
1309
1310         if (scene->r.stamp & R_STAMP_CAMERA) {
1311                 BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), do_prefix ? "Camera %s" : "%s", camera ? camera->id.name + 2 : "<none>");
1312         }
1313         else {
1314                 stamp_data->camera[0] = '\0';
1315         }
1316
1317         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1318                 if (camera && camera->type == OB_CAMERA) {
1319                         BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)camera->data)->lens);
1320                 }
1321                 else BLI_strncpy(text, "<none>", sizeof(text));
1322
1323                 BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), do_prefix ? "Lens %s" : "%s", text);
1324         }
1325         else {
1326                 stamp_data->cameralens[0] = '\0';
1327         }
1328
1329         if (scene->r.stamp & R_STAMP_SCENE) {
1330                 BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), do_prefix ? "Scene %s" : "%s", scene->id.name + 2);
1331         }
1332         else {
1333                 stamp_data->scene[0] = '\0';
1334         }
1335         
1336         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1337                 Sequence *seq = seq_foreground_frame_get(scene, scene->r.cfra);
1338         
1339                 if (seq) BLI_strncpy(text, seq->name + 2, sizeof(text));
1340                 else BLI_strncpy(text, "<none>", sizeof(text));
1341
1342                 BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), do_prefix ? "Strip %s" : "%s", text);
1343         }
1344         else {
1345                 stamp_data->strip[0] = '\0';
1346         }
1347
1348         {
1349                 Render *re = RE_GetRender(scene->id.name);
1350                 RenderStats *stats = re ? RE_GetStats(re) : NULL;
1351
1352                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1353                         BLI_timestr(stats->lastframetime, text);
1354
1355                         BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), do_prefix ? "RenderTime %s" : "%s", text);
1356                 }
1357                 else {
1358                         stamp_data->rendertime[0] = '\0';
1359                 }
1360         }
1361 }
1362
1363 void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rectf, int width, int height, int channels)
1364 {
1365         struct StampData stamp_data;
1366         float w, h, pad;
1367         int x, y, y_ofs;
1368         float h_fixed;
1369         const int mono = blf_mono_font_render; // XXX
1370
1371 #define BUFF_MARGIN_X 2
1372 #define BUFF_MARGIN_Y 1
1373
1374         if (!rect && !rectf)
1375                 return;
1376         
1377         stampdata(scene, camera, &stamp_data, 1);
1378
1379         /* TODO, do_versions */
1380         if (scene->r.stamp_font_id < 8)
1381                 scene->r.stamp_font_id = 12;
1382
1383         /* set before return */
1384         BLF_size(mono, scene->r.stamp_font_id, 72);
1385         
1386         BLF_buffer(mono, rectf, rect, width, height, channels);
1387         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1388         pad = BLF_width_max(mono);
1389
1390         /* use 'h_fixed' rather than 'h', aligns better */
1391         h_fixed = BLF_height_max(mono);
1392         y_ofs = -BLF_descender(mono);
1393
1394         x = 0;
1395         y = height;
1396
1397         if (stamp_data.file[0]) {
1398                 /* Top left corner */
1399                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h = h_fixed;
1400                 y -= h;
1401
1402                 /* also a little of space to the background. */
1403                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1404
1405                 /* and draw the text. */
1406                 BLF_position(mono, x, y + y_ofs, 0.0);
1407                 BLF_draw_buffer(mono, stamp_data.file);
1408
1409                 /* the extra pixel for background. */
1410                 y -= BUFF_MARGIN_Y * 2;
1411         }
1412
1413         /* Top left corner, below File */
1414         if (stamp_data.note[0]) {
1415                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h = h_fixed;
1416                 y -= h;
1417
1418                 /* and space for background. */
1419                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1420
1421                 BLF_position(mono, x, y + y_ofs, 0.0);
1422                 BLF_draw_buffer(mono, stamp_data.note);
1423
1424                 /* the extra pixel for background. */
1425                 y -= BUFF_MARGIN_Y * 2;
1426         }
1427         
1428         /* Top left corner, below File (or Note) */
1429         if (stamp_data.date[0]) {
1430                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h = h_fixed;
1431                 y -= h;
1432
1433                 /* and space for background. */
1434                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1435
1436                 BLF_position(mono, x, y + y_ofs, 0.0);
1437                 BLF_draw_buffer(mono, stamp_data.date);
1438
1439                 /* the extra pixel for background. */
1440                 y -= BUFF_MARGIN_Y * 2;
1441         }
1442
1443         /* Top left corner, below File, Date or Note */
1444         if (stamp_data.rendertime[0]) {
1445                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h = h_fixed;
1446                 y -= h;
1447
1448                 /* and space for background. */
1449                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, 0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1450
1451                 BLF_position(mono, x, y + y_ofs, 0.0);
1452                 BLF_draw_buffer(mono, stamp_data.rendertime);
1453         }
1454
1455         x = 0;
1456         y = 0;
1457
1458         /* Bottom left corner, leaving space for timing */
1459         if (stamp_data.marker[0]) {
1460                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h = h_fixed;
1461
1462                 /* extra space for background. */
1463                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1464
1465                 /* and pad the text. */
1466                 BLF_position(mono, x, y + y_ofs, 0.0);
1467                 BLF_draw_buffer(mono, stamp_data.marker);
1468
1469                 /* space width. */
1470                 x += w + pad;
1471         }
1472         
1473         /* Left bottom corner */
1474         if (stamp_data.time[0]) {
1475                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h = h_fixed;
1476
1477                 /* extra space for background */
1478                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x - BUFF_MARGIN_X, y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1479
1480                 /* and pad the text. */
1481                 BLF_position(mono, x, y + y_ofs, 0.0);
1482                 BLF_draw_buffer(mono, stamp_data.time);
1483
1484                 /* space width. */
1485                 x += w + pad;
1486         }
1487         
1488         if (stamp_data.frame[0]) {
1489                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h = h_fixed;
1490
1491                 /* extra space for background. */
1492                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1493
1494                 /* and pad the text. */
1495                 BLF_position(mono, x, y + y_ofs, 0.0);
1496                 BLF_draw_buffer(mono, stamp_data.frame);
1497
1498                 /* space width. */
1499                 x += w + pad;
1500         }
1501
1502         if (stamp_data.camera[0]) {
1503                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h = h_fixed;
1504
1505                 /* extra space for background. */
1506                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1507                 BLF_position(mono, x, y + y_ofs, 0.0);
1508                 BLF_draw_buffer(mono, stamp_data.camera);
1509
1510                 /* space width. */
1511                 x += w + pad;
1512         }
1513
1514         if (stamp_data.cameralens[0]) {
1515                 BLF_width_and_height(mono, stamp_data.cameralens, &w, &h); h = h_fixed;
1516
1517                 /* extra space for background. */
1518                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1519                 BLF_position(mono, x, y + y_ofs, 0.0);
1520                 BLF_draw_buffer(mono, stamp_data.cameralens);
1521         }
1522         
1523         if (stamp_data.scene[0]) {
1524                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h = h_fixed;
1525
1526                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1527                 x = width - w - 2;
1528
1529                 /* extra space for background. */
1530                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1531
1532                 /* and pad the text. */
1533                 BLF_position(mono, x, y + y_ofs, 0.0);
1534                 BLF_draw_buffer(mono, stamp_data.scene);
1535         }
1536         
1537         if (stamp_data.strip[0]) {
1538                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h = h_fixed;
1539
1540                 /* Top right corner, with an extra space because blenfont is too strict! */
1541                 x = width - w - pad;
1542                 y = height - h;
1543
1544                 /* extra space for background. */
1545                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1546
1547                 BLF_position(mono, x, y + y_ofs, 0.0);
1548                 BLF_draw_buffer(mono, stamp_data.strip);
1549         }
1550
1551         /* cleanup the buffer. */
1552         BLF_buffer(mono, NULL, NULL, 0, 0, 0);
1553
1554 #undef BUFF_MARGIN_X
1555 #undef BUFF_MARGIN_Y
1556 }
1557
1558 void BKE_imbuf_stamp_info(Scene *scene, Object *camera, struct ImBuf *ibuf)
1559 {
1560         struct StampData stamp_data;
1561
1562         if (!ibuf) return;
1563         
1564         /* fill all the data values, no prefix */
1565         stampdata(scene, camera, &stamp_data, 0);
1566         
1567         if (stamp_data.file[0]) IMB_metadata_change_field(ibuf, "File",        stamp_data.file);
1568         if (stamp_data.note[0]) IMB_metadata_change_field(ibuf, "Note",        stamp_data.note);
1569         if (stamp_data.date[0]) IMB_metadata_change_field(ibuf, "Date",        stamp_data.date);
1570         if (stamp_data.marker[0]) IMB_metadata_change_field(ibuf, "Marker",    stamp_data.marker);
1571         if (stamp_data.time[0]) IMB_metadata_change_field(ibuf, "Time",        stamp_data.time);
1572         if (stamp_data.frame[0]) IMB_metadata_change_field(ibuf, "Frame",      stamp_data.frame);
1573         if (stamp_data.camera[0]) IMB_metadata_change_field(ibuf, "Camera",    stamp_data.camera);
1574         if (stamp_data.cameralens[0]) IMB_metadata_change_field(ibuf, "Lens",  stamp_data.cameralens);
1575         if (stamp_data.scene[0]) IMB_metadata_change_field(ibuf, "Scene",      stamp_data.scene);
1576         if (stamp_data.strip[0]) IMB_metadata_change_field(ibuf, "Strip",      stamp_data.strip);
1577         if (stamp_data.rendertime[0]) IMB_metadata_change_field(ibuf, "RenderTime", stamp_data.rendertime);
1578 }
1579
1580 int BKE_imbuf_alpha_test(ImBuf *ibuf)
1581 {
1582         int tot;
1583         if (ibuf->rect_float) {
1584                 float *buf = ibuf->rect_float;
1585                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1586                         if (buf[3] < 1.0f) {
1587                                 return TRUE;
1588                         }
1589                 }
1590         }
1591         else if (ibuf->rect) {
1592                 unsigned char *buf = (unsigned char *)ibuf->rect;
1593                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1594                         if (buf[3] != 255) {
1595                                 return TRUE;
1596                         }
1597                 }
1598         }
1599
1600         return FALSE;
1601 }
1602
1603 /* note: imf->planes is ignored here, its assumed the image channels
1604  * are already set */
1605 int BKE_imbuf_write(ImBuf *ibuf, const char *name, ImageFormatData *imf)
1606 {
1607         char imtype = imf->imtype;
1608         char compress = imf->compress;
1609         char quality = imf->quality;
1610
1611         int ok;
1612
1613         if (imtype == R_IMF_IMTYPE_IRIS) {
1614                 ibuf->ftype = IMAGIC;
1615         }
1616 #ifdef WITH_HDR
1617         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1618                 ibuf->ftype = RADHDR;
1619         }
1620 #endif
1621         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1622                 ibuf->ftype = PNG;
1623
1624                 if (imtype == R_IMF_IMTYPE_PNG)
1625                         ibuf->ftype |= compress;
1626
1627         }
1628 #ifdef WITH_DDS
1629         else if (imtype == R_IMF_IMTYPE_DDS) {
1630                 ibuf->ftype = DDS;
1631         }
1632 #endif
1633         else if (imtype == R_IMF_IMTYPE_BMP) {
1634                 ibuf->ftype = BMP;
1635         }
1636 #ifdef WITH_TIFF
1637         else if (imtype == R_IMF_IMTYPE_TIFF) {
1638                 ibuf->ftype = TIF;
1639
1640                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1641                         ibuf->ftype |= TIF_16BIT;
1642         }
1643 #endif
1644 #ifdef WITH_OPENEXR
1645         else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER) {
1646                 ibuf->ftype = OPENEXR;
1647                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1648                         ibuf->ftype |= OPENEXR_HALF;
1649                 ibuf->ftype |= (imf->exr_codec & OPENEXR_COMPRESS);
1650                 
1651                 if (!(imf->flag & R_IMF_FLAG_ZBUF))
1652                         ibuf->zbuf_float = NULL;    /* signal for exr saving */
1653                 
1654         }
1655 #endif
1656 #ifdef WITH_CINEON
1657         else if (imtype == R_IMF_IMTYPE_CINEON) {
1658                 ibuf->ftype = CINEON;
1659         }
1660         else if (imtype == R_IMF_IMTYPE_DPX) {
1661                 ibuf->ftype = DPX;
1662         }
1663 #endif
1664         else if (imtype == R_IMF_IMTYPE_TARGA) {
1665                 ibuf->ftype = TGA;
1666         }
1667         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
1668                 ibuf->ftype = RAWTGA;
1669         }
1670 #ifdef WITH_OPENJPEG
1671         else if (imtype == R_IMF_IMTYPE_JP2) {
1672                 if (quality < 10) quality = 90;
1673                 ibuf->ftype = JP2 | quality;
1674                 
1675                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1676                         ibuf->ftype |= JP2_16BIT;
1677                 }
1678                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1679                         ibuf->ftype |= JP2_12BIT;
1680                 }
1681                 
1682                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
1683                         ibuf->ftype |= JP2_YCC;
1684                 }
1685
1686                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
1687                         ibuf->ftype |= JP2_CINE;
1688                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
1689                                 ibuf->ftype |= JP2_CINE_48FPS;
1690                 }
1691         }
1692 #endif
1693         else {
1694                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
1695                 if (quality < 10) quality = 90;
1696                 ibuf->ftype = JPG | quality;
1697         }
1698         
1699         BLI_make_existing_file(name);
1700         
1701         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1702         if (ok == 0) {
1703                 perror(name);
1704         }
1705         
1706         return(ok);
1707 }
1708
1709 /* same as BKE_imbuf_write() but crappy workaround not to perminantly modify
1710  * _some_, values in the imbuf */
1711 int BKE_imbuf_write_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
1712                        const short save_copy)
1713 {
1714         ImBuf ibuf_back = *ibuf;
1715         int ok;
1716
1717         /* all data is rgba anyway,
1718          * this just controls how to save for some formats */
1719         ibuf->planes = imf->planes;
1720
1721         ok = BKE_imbuf_write(ibuf, name, imf);
1722
1723         if (save_copy) {
1724                 /* note that we are not restoring _all_ settings */
1725                 ibuf->planes = ibuf_back.planes;
1726                 ibuf->ftype =  ibuf_back.ftype;
1727         }
1728
1729         return ok;
1730 }
1731
1732 int BKE_imbuf_write_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, struct ImageFormatData *imf)
1733 {
1734         if (scene && scene->r.stamp & R_STAMP_ALL)
1735                 BKE_imbuf_stamp_info(scene, camera, ibuf);
1736
1737         return BKE_imbuf_write(ibuf, name, imf);
1738 }
1739
1740
1741 void BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, const char imtype, const short use_ext, const short use_frames)
1742 {
1743         if (string == NULL) return;
1744         BLI_strncpy(string, base, FILE_MAX - 10);   /* weak assumption */
1745         BLI_path_abs(string, relbase);
1746
1747         if (use_frames)
1748                 BLI_path_frame(string, frame, 4);
1749
1750         if (use_ext)
1751                 BKE_add_image_extension(string, imtype);
1752                 
1753 }
1754
1755 /* used by sequencer too */
1756 struct anim *openanim(const char *name, int flags, int streamindex)
1757 {
1758         struct anim *anim;
1759         struct ImBuf *ibuf;
1760         
1761         anim = IMB_open_anim(name, flags, streamindex);
1762         if (anim == NULL) return NULL;
1763
1764         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
1765         if (ibuf == NULL) {
1766                 if (BLI_exists(name))
1767                         printf("not an anim: %s\n", name);
1768                 else
1769                         printf("anim file doesn't exist: %s\n", name);
1770                 IMB_free_anim(anim);
1771                 return NULL;
1772         }
1773         IMB_freeImBuf(ibuf);
1774         
1775         return(anim);
1776 }
1777
1778 /* ************************* New Image API *************** */
1779
1780
1781 /* Notes about Image storage 
1782  * - packedfile
1783  *   -> written in .blend
1784  * - filename
1785  *   -> written in .blend
1786  * - movie
1787  *   -> comes from packedfile or filename
1788  * - renderresult
1789  *   -> comes from packedfile or filename
1790  * - listbase
1791  *   -> ibufs from exrhandle
1792  * - flipbook array
1793  *   -> ibufs come from movie, temporary renderresult or sequence
1794  * - ibuf
1795  *   -> comes from packedfile or filename or generated
1796  */
1797
1798
1799 /* forces existence of 1 Image for renderout or nodes, returns Image */
1800 /* name is only for default, when making new one */
1801 Image *BKE_image_verify_viewer(int type, const char *name)
1802 {
1803         Image *ima;
1804         
1805         for (ima = G.main->image.first; ima; ima = ima->id.next)
1806                 if (ima->source == IMA_SRC_VIEWER)
1807                         if (ima->type == type)
1808                                 break;
1809         
1810         if (ima == NULL)
1811                 ima = image_alloc(name, IMA_SRC_VIEWER, type);
1812         
1813         /* happens on reload, imagewindow cannot be image user when hidden*/
1814         if (ima->id.us == 0)
1815                 id_us_plus(&ima->id);
1816
1817         return ima;
1818 }
1819
1820 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1821 {
1822         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1823 }
1824
1825 void BKE_image_walk_all_users(const Main *mainp, void *customdata,
1826                               void callback(Image *ima, ImageUser *iuser, void *customdata))
1827 {
1828         wmWindowManager *wm;
1829         wmWindow *win;
1830         Tex *tex;
1831
1832         /* texture users */
1833         for (tex = mainp->tex.first; tex; tex = tex->id.next) {
1834                 if (tex->type == TEX_IMAGE && tex->ima) {
1835                         if (ELEM(tex->ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
1836                                 callback(tex->ima, &tex->iuser, customdata);
1837                         }
1838                 }
1839         }
1840
1841         /* image window, compo node users */
1842         for (wm = mainp->wm.first; wm; wm = wm->id.next) { /* only 1 wm */
1843                 for (win = wm->windows.first; win; win = win->next) {
1844                         ScrArea *sa;
1845                         for (sa = win->screen->areabase.first; sa; sa = sa->next) {
1846                                 if (sa->spacetype == SPACE_VIEW3D) {
1847                                         View3D *v3d = sa->spacedata.first;
1848                                         BGpic *bgpic;
1849                                         for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
1850                                                 callback(bgpic->ima, &bgpic->iuser, customdata);
1851                                         }
1852                                 }
1853                                 else if (sa->spacetype == SPACE_IMAGE) {
1854                                         SpaceImage *sima = sa->spacedata.first;
1855                                         callback(sima->image, &sima->iuser, customdata);
1856                                 }
1857                                 else if (sa->spacetype == SPACE_NODE) {
1858                                         SpaceNode *snode = sa->spacedata.first;
1859                                         if ((snode->treetype == NTREE_COMPOSIT) && (snode->nodetree)) {
1860                                                 bNode *node;
1861                                                 for (node = snode->nodetree->nodes.first; node; node = node->next) {
1862                                                         if (node->id && node->type == CMP_NODE_IMAGE) {
1863                                                                 Image *ima = (Image *)node->id;
1864                                                                 ImageUser *iuser = node->storage;
1865                                                                 callback(ima, iuser, customdata);
1866                                                         }
1867                                                 }
1868                                         }
1869                                 }
1870                         }
1871                 }
1872         }
1873 }
1874
1875 static void image_tag_frame_recalc(Image *ima, ImageUser *iuser, void *customdata)
1876 {
1877         Image *changed_image = customdata;
1878
1879         if (ima == changed_image) {
1880                 iuser->flag |= IMA_NEED_FRAME_RECALC;
1881         }
1882 }
1883
1884 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1885 {
1886         if (ima == NULL)
1887                 return;
1888         
1889         switch (signal) {
1890                 case IMA_SIGNAL_FREE:
1891                         image_free_buffers(ima);
1892                         if (iuser)
1893                                 iuser->ok = 1;
1894                         break;
1895                 case IMA_SIGNAL_SRC_CHANGE:
1896                         if (ima->type == IMA_TYPE_UV_TEST)
1897                                 if (ima->source != IMA_SRC_GENERATED)
1898                                         ima->type = IMA_TYPE_IMAGE;
1899
1900                         if (ima->source == IMA_SRC_GENERATED) {
1901                                 if (ima->gen_x == 0 || ima->gen_y == 0) {
1902                                         ImBuf *ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
1903                                         if (ibuf) {
1904                                                 ima->gen_x = ibuf->x;
1905                                                 ima->gen_y = ibuf->y;
1906                                         }
1907                                 }
1908                         }
1909
1910                         /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
1911                         if (ima->type != IMA_TYPE_MULTILAYER)
1912                                 image_free_buffers(ima);
1913
1914                         ima->ok = 1;
1915                         if (iuser)
1916                                 iuser->ok = 1;
1917
1918                         BKE_image_walk_all_users(G.main, ima, image_tag_frame_recalc);
1919
1920                         break;
1921
1922                 case IMA_SIGNAL_RELOAD:
1923                         /* try to repack file */
1924                         if (ima->packedfile) {
1925                                 PackedFile *pf;
1926                                 pf = newPackedFile(NULL, ima->name, ID_BLEND_PATH(G.main, &ima->id));
1927                                 if (pf) {
1928                                         freePackedFile(ima->packedfile);
1929                                         ima->packedfile = pf;
1930                                         image_free_buffers(ima);
1931                                 }
1932                                 else {
1933                                         printf("ERROR: Image not available. Keeping packed image\n");
1934                                 }
1935                         }
1936                         else
1937                                 image_free_buffers(ima);
1938                 
1939                         if (iuser)
1940                                 iuser->ok = 1;
1941                 
1942                         break;
1943                 case IMA_SIGNAL_USER_NEW_IMAGE:
1944                         if (iuser) {
1945                                 iuser->ok = 1;
1946                                 if (ima->source == IMA_SRC_FILE || ima->source == IMA_SRC_SEQUENCE) {
1947                                         if (ima->type == IMA_TYPE_MULTILAYER) {
1948                                                 iuser->multi_index = 0;
1949                                                 iuser->layer = iuser->pass = 0;
1950                                         }
1951                                 }
1952                         }
1953                         break;
1954         }
1955         
1956         /* don't use notifiers because they are not 100% sure to succeeded
1957          * this also makes sure all scenes are accounted for. */
1958         {
1959                 Scene *scene;
1960                 for (scene = G.main->scene.first; scene; scene = scene->id.next) {
1961                         if (scene->nodetree) {
1962                                 nodeUpdateID(scene->nodetree, &ima->id);
1963                         }
1964                 }
1965         }
1966 }
1967
1968 /* if layer or pass changes, we need an index for the imbufs list */
1969 /* note it is called for rendered results, but it doesnt use the index! */
1970 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
1971 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
1972 {
1973         RenderLayer *rl;
1974         RenderPass *rpass = NULL;
1975         
1976         if (rr == NULL)
1977                 return NULL;
1978         
1979         if (iuser) {
1980                 short index = 0, rl_index = 0, rp_index;
1981                 
1982                 for (rl = rr->layers.first; rl; rl = rl->next, rl_index++) {
1983                         rp_index = 0;
1984                         for (rpass = rl->passes.first; rpass; rpass = rpass->next, index++, rp_index++)
1985                                 if (iuser->layer == rl_index && iuser->pass == rp_index)
1986                                         break;
1987                         if (rpass)
1988                                 break;
1989                 }
1990                 
1991                 if (rpass)
1992                         iuser->multi_index = index;
1993                 else 
1994                         iuser->multi_index = 0;
1995         }
1996         if (rpass == NULL) {
1997                 rl = rr->layers.first;
1998                 if (rl)
1999                         rpass = rl->passes.first;
2000         }
2001         
2002         return rpass;
2003 }
2004
2005 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
2006 {
2007         if (ima->rr) {
2008                 return ima->rr;
2009         }
2010         else if (ima->type == IMA_TYPE_R_RESULT) {
2011                 if (ima->render_slot == ima->last_render_slot)
2012                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
2013                 else
2014                         return ima->renders[ima->render_slot];
2015         }
2016         else
2017                 return NULL;
2018 }
2019
2020 void BKE_image_release_renderresult(Scene *scene, Image *ima)
2021 {
2022         if (ima->rr) ;
2023         else if (ima->type == IMA_TYPE_R_RESULT) {
2024                 if (ima->render_slot == ima->last_render_slot)
2025                         RE_ReleaseResult(RE_GetRender(scene->id.name));
2026         }
2027 }
2028
2029 void BKE_image_backup_render(Scene *scene, Image *ima)
2030 {
2031         /* called right before rendering, ima->renders contains render
2032          * result pointers for everything but the current render */
2033         Render *re = RE_GetRender(scene->id.name);
2034         int slot = ima->render_slot, last = ima->last_render_slot;
2035
2036         if (slot != last) {
2037                 if (ima->renders[slot]) {
2038                         RE_FreeRenderResult(ima->renders[slot]);
2039                         ima->renders[slot] = NULL;
2040                 }
2041
2042                 ima->renders[last] = NULL;
2043                 RE_SwapResult(re, &ima->renders[last]);
2044         }
2045
2046         ima->last_render_slot = slot;
2047 }
2048
2049 /* after imbuf load, openexr type can return with a exrhandle open */
2050 /* in that case we have to build a render-result */
2051 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
2052 {
2053         
2054         ima->rr = RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
2055
2056 #ifdef WITH_OPENEXR
2057         IMB_exr_close(ibuf->userdata);
2058 #endif
2059
2060         ibuf->userdata = NULL;
2061         if (ima->rr)
2062                 ima->rr->framenr = framenr;
2063 }
2064
2065 /* common stuff to do with images after loading */
2066 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
2067 {
2068         /* preview is NULL when it has never been used as an icon before */
2069         if (G.background == 0 && ima->preview == NULL)
2070                 BKE_icon_changed(BKE_icon_getid(&ima->id));
2071
2072         /* fields */
2073         if (ima->flag & IMA_FIELDS) {
2074                 if (ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
2075                 else de_interlace_ng(ibuf);
2076         }
2077         /* timer */
2078         ima->lastused = clock() / CLOCKS_PER_SEC;
2079         
2080         ima->ok = IMA_OK_LOADED;
2081         
2082 }
2083
2084 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
2085 {
2086         struct ImBuf *ibuf;
2087         char name[FILE_MAX];
2088         int flag;
2089         
2090         /* XXX temp stuff? */
2091         if (ima->lastframe != frame)
2092                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2093
2094         ima->lastframe = frame;
2095         BKE_image_user_file_path(iuser, ima, name);
2096         
2097         flag = IB_rect | IB_multilayer;
2098         if (ima->flag & IMA_DO_PREMUL)
2099                 flag |= IB_premul;
2100
2101         /* read ibuf */
2102         ibuf = IMB_loadiffname(name, flag);
2103
2104 #if 0
2105         if (ibuf) {
2106                 printf(AT " loaded %s\n", name);
2107         }
2108         else {
2109                 printf(AT " missed %s\n", name);
2110         }
2111 #endif
2112
2113         if (ibuf) {
2114 #ifdef WITH_OPENEXR
2115                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2116                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2117                         image_create_multilayer(ima, ibuf, frame);      
2118                         ima->type = IMA_TYPE_MULTILAYER;
2119                         IMB_freeImBuf(ibuf);
2120                         ibuf = NULL;
2121                 }
2122                 else {
2123                         image_initialize_after_load(ima, ibuf);
2124                         image_assign_ibuf(ima, ibuf, 0, frame);
2125                 }
2126 #else
2127                 image_initialize_after_load(ima, ibuf);
2128                 image_assign_ibuf(ima, ibuf, 0, frame);
2129 #endif
2130         }
2131         else
2132                 ima->ok = 0;
2133         
2134         if (iuser)
2135                 iuser->ok = ima->ok;
2136         
2137         return ibuf;
2138 }
2139
2140 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
2141 {
2142         struct ImBuf *ibuf = NULL;
2143         
2144         /* either we load from RenderResult, or we have to load a new one */
2145         
2146         /* check for new RenderResult */
2147         if (ima->rr == NULL || frame != ima->rr->framenr) {
2148                 /* copy to survive not found multilayer image */
2149                 RenderResult *oldrr = ima->rr;
2150         
2151                 ima->rr = NULL;
2152                 ibuf = image_load_sequence_file(ima, iuser, frame);
2153                 
2154                 if (ibuf) { /* actually an error */
2155                         ima->type = IMA_TYPE_IMAGE;
2156                         printf("error, multi is normal image\n");
2157                 }
2158                 // printf("loaded new result %p\n", ima->rr);
2159                 /* free result if new one found */
2160                 if (ima->rr) {
2161                         // if (oldrr) printf("freed previous result %p\n", oldrr);
2162                         if (oldrr) RE_FreeRenderResult(oldrr);
2163                 }
2164                 else {
2165                         ima->rr = oldrr;
2166                 }
2167
2168         }
2169         if (ima->rr) {
2170                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2171                 
2172                 if (rpass) {
2173                         // printf("load from pass %s\n", rpass->name);
2174                         /* since we free  render results, we copy the rect */
2175                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2176                         ibuf->rect_float = MEM_dupallocN(rpass->rect);
2177                         ibuf->flags |= IB_rectfloat;
2178                         ibuf->mall = IB_rectfloat;
2179                         ibuf->channels = rpass->channels;
2180                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2181                         
2182                         image_initialize_after_load(ima, ibuf);
2183                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : 0, frame);
2184                         
2185                 }
2186                 // else printf("pass not found\n");
2187         }
2188         else
2189                 ima->ok = 0;
2190         
2191         if (iuser)
2192                 iuser->ok = ima->ok;
2193         
2194         return ibuf;
2195 }
2196
2197
2198 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
2199 {
2200         struct ImBuf *ibuf = NULL;
2201         
2202         ima->lastframe = frame;
2203         
2204         if (ima->anim == NULL) {
2205                 char str[FILE_MAX];
2206                 
2207                 BKE_image_user_file_path(iuser, ima, str);
2208
2209                 /* FIXME: make several stream accessible in image editor, too*/
2210                 ima->anim = openanim(str, IB_rect, 0);
2211                 
2212                 /* let's initialize this user */
2213                 if (ima->anim && iuser && iuser->frames == 0)
2214                         iuser->frames = IMB_anim_get_duration(ima->anim,
2215                                                               IMB_TC_RECORD_RUN);
2216         }
2217         
2218         if (ima->anim) {
2219                 int dur = IMB_anim_get_duration(ima->anim,
2220                                                 IMB_TC_RECORD_RUN);
2221                 int fra = frame - 1;
2222                 
2223                 if (fra < 0) fra = 0;
2224                 if (fra > (dur - 1)) fra = dur - 1;
2225                 ibuf = IMB_makeSingleUser(
2226                     IMB_anim_absolute(ima->anim, fra,
2227                                       IMB_TC_RECORD_RUN,
2228                                       IMB_PROXY_NONE));
2229                 
2230                 if (ibuf) {
2231                         image_initialize_after_load(ima, ibuf);
2232                         image_assign_ibuf(ima, ibuf, 0, frame);
2233                 }
2234                 else
2235                         ima->ok = 0;
2236         }
2237         else
2238                 ima->ok = 0;
2239         
2240         if (iuser)
2241                 iuser->ok = ima->ok;
2242         
2243         return ibuf;
2244 }
2245
2246 /* warning, 'iuser' can be NULL */
2247 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
2248 {
2249         struct ImBuf *ibuf;
2250         char str[FILE_MAX];
2251         int assign = 0, flag;
2252         
2253         /* always ensure clean ima */
2254         image_free_buffers(ima);
2255         
2256         /* is there a PackedFile with this image ? */
2257         if (ima->packedfile) {
2258                 flag = IB_rect | IB_multilayer;
2259                 if (ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
2260                 
2261                 ibuf = IMB_ibImageFromMemory((unsigned char *)ima->packedfile->data,
2262                                              ima->packedfile->size, flag, "<packed data>");
2263         } 
2264         else {
2265                 flag = IB_rect | IB_multilayer | IB_metadata;
2266                 if (ima->flag & IMA_DO_PREMUL)
2267                         flag |= IB_premul;
2268                         
2269                 /* get the right string */
2270                 BKE_image_user_frame_calc(iuser, cfra, 0);
2271                 BKE_image_user_file_path(iuser, ima, str);
2272                 
2273                 /* read ibuf */
2274                 ibuf = IMB_loadiffname(str, flag);
2275         }
2276         
2277         if (ibuf) {
2278                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2279                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2280                         image_create_multilayer(ima, ibuf, cfra);       
2281                         ima->type = IMA_TYPE_MULTILAYER;
2282                         IMB_freeImBuf(ibuf);
2283                         ibuf = NULL;
2284                 }
2285                 else {
2286                         image_initialize_after_load(ima, ibuf);
2287                         assign = 1;
2288
2289                         /* check if the image is a font image... */
2290                         detectBitmapFont(ibuf);
2291                         
2292                         /* make packed file for autopack */
2293                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
2294                                 ima->packedfile = newPackedFile(NULL, str, ID_BLEND_PATH(G.main, &ima->id));
2295                 }
2296         }
2297         else
2298                 ima->ok = 0;
2299         
2300         if (assign)
2301                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2302
2303         if (iuser)
2304                 iuser->ok = ima->ok;
2305         
2306         return ibuf;
2307 }
2308
2309 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
2310 {
2311         ImBuf *ibuf = NULL;
2312         
2313         if (ima->rr == NULL) {
2314                 ibuf = image_load_image_file(ima, iuser, 0);
2315                 if (ibuf) { /* actually an error */
2316                         ima->type = IMA_TYPE_IMAGE;
2317                         return ibuf;
2318                 }
2319         }
2320         if (ima->rr) {
2321                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2322
2323                 if (rpass) {
2324                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2325                         
2326                         image_initialize_after_load(ima, ibuf);
2327                         
2328                         ibuf->rect_float = rpass->rect;
2329                         ibuf->flags |= IB_rectfloat;
2330                         ibuf->channels = rpass->channels;
2331                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2332
2333                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2334                 }
2335         }
2336         
2337         if (ibuf == NULL)
2338                 ima->ok = 0;
2339         if (iuser)
2340                 iuser->ok = ima->ok;
2341         
2342         return ibuf;
2343 }
2344
2345
2346 /* showing RGBA result itself (from compo/sequence) or
2347  * like exr, using layers etc */
2348 /* always returns a single ibuf, also during render progress */
2349 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
2350 {
2351         Render *re;
2352         RenderResult rres;
2353         float *rectf, *rectz;
2354         unsigned int *rect;
2355         float dither;
2356         int channels, layer, pass;
2357         ImBuf *ibuf;
2358         int from_render = (ima->render_slot == ima->last_render_slot);
2359
2360         if (!(iuser && iuser->scene))
2361                 return NULL;
2362
2363         /* if we the caller is not going to release the lock, don't give the image */
2364         if (!lock_r)
2365                 return NULL;
2366
2367         re = RE_GetRender(iuser->scene->id.name);
2368
2369         channels = 4;
2370         layer = (iuser) ? iuser->layer : 0;
2371         pass = (iuser) ? iuser->pass : 0;
2372
2373         if (from_render) {
2374                 RE_AcquireResultImage(re, &rres);
2375         }
2376         else if (ima->renders[ima->render_slot]) {
2377                 rres = *(ima->renders[ima->render_slot]);
2378                 rres.have_combined = rres.rectf != NULL;
2379         }
2380         else
2381                 memset(&rres, 0, sizeof(RenderResult));
2382         
2383         if (!(rres.rectx > 0 && rres.recty > 0)) {
2384                 if (from_render)
2385                         RE_ReleaseResultImage(re);
2386                 return NULL;
2387         }
2388
2389         /* release is done in BKE_image_release_ibuf using lock_r */
2390         if (from_render) {
2391                 BLI_lock_thread(LOCK_VIEWER);
2392                 *lock_r = re;
2393         }
2394
2395         /* this gives active layer, composite or seqence result */
2396         rect = (unsigned int *)rres.rect32;
2397         rectf = rres.rectf;
2398         rectz = rres.rectz;
2399         dither = iuser->scene->r.dither_intensity;
2400
2401         /* combined layer gets added as first layer */
2402         if (rres.have_combined && layer == 0) ;
2403         else if (rres.layers.first) {
2404                 RenderLayer *rl = BLI_findlink(&rres.layers, layer - (rres.have_combined ? 1 : 0));
2405                 if (rl) {
2406                         RenderPass *rpass;
2407
2408                         /* there's no combined pass, is in renderlayer itself */
2409                         if (pass == 0) {
2410                                 rectf = rl->rectf;
2411                         }
2412                         else {
2413                                 rpass = BLI_findlink(&rl->passes, pass - 1);
2414                                 if (rpass) {
2415                                         channels = rpass->channels;
2416                                         rectf = rpass->rect;
2417                                         dither = 0.0f; /* don't dither passes */
2418                                 }
2419                         }
2420
2421                         for (rpass = rl->passes.first; rpass; rpass = rpass->next)
2422                                 if (rpass->passtype == SCE_PASS_Z)
2423                                         rectz = rpass->rect;
2424                 }
2425         }
2426
2427         ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2428
2429         /* make ibuf if needed, and initialize it */
2430         if (ibuf == NULL) {
2431                 ibuf = IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
2432                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2433         }
2434
2435         ibuf->x = rres.rectx;
2436         ibuf->y = rres.recty;
2437         
2438         /* free rect buffer if float buffer changes, so it can be recreated with
2439          * the updated result, and also in case we got byte buffer from sequencer,
2440          * so we don't keep reference to freed buffer */
2441         if (ibuf->rect_float != rectf || rect || !rectf)
2442                 imb_freerectImBuf(ibuf);
2443
2444         if (rect)
2445                 ibuf->rect = rect;
2446         
2447         if (rectf) {
2448                 ibuf->rect_float = rectf;
2449                 ibuf->flags |= IB_rectfloat;
2450                 ibuf->channels = channels;
2451         }
2452         else {
2453                 ibuf->rect_float = NULL;
2454                 ibuf->flags &= ~IB_rectfloat;
2455         }
2456
2457         if (rectz) {
2458                 ibuf->zbuf_float = rectz;
2459                 ibuf->flags |= IB_zbuffloat;
2460         }
2461         else {
2462                 ibuf->zbuf_float = NULL;
2463                 ibuf->flags &= ~IB_zbuffloat;
2464         }
2465
2466         /* since its possible to access the buffer from the image directly, set the profile [#25073] */
2467         ibuf->profile = (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) ? IB_PROFILE_LINEAR_RGB : IB_PROFILE_NONE;
2468         ibuf->dither = dither;
2469
2470         if (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT_PREDIVIDE) {
2471                 ibuf->flags |= IB_cm_predivide;
2472                 ima->flag |= IMA_CM_PREDIVIDE;
2473         }
2474         else {
2475                 ibuf->flags &= ~IB_cm_predivide;
2476                 ima->flag &= ~IMA_CM_PREDIVIDE;
2477         }
2478
2479         ima->ok = IMA_OK_LOADED;
2480
2481         return ibuf;
2482 }
2483
2484 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2485 {
2486         ImBuf *ibuf = NULL;
2487         int frame = 0, index = 0;
2488
2489         /* see if we already have an appropriate ibuf, with image source and type */
2490         if (ima->source == IMA_SRC_MOVIE) {
2491                 frame = iuser ? iuser->framenr : ima->lastframe;
2492                 ibuf = image_get_ibuf(ima, 0, frame);
2493                 /* XXX temp stuff? */
2494                 if (ima->lastframe != frame)
2495                         ima->tpageflag |= IMA_TPAGE_REFRESH;
2496                 ima->lastframe = frame;
2497         }
2498         else if (ima->source == IMA_SRC_SEQUENCE) {
2499                 if (ima->type == IMA_TYPE_IMAGE) {
2500                         frame = iuser ? iuser->framenr : ima->lastframe;
2501                         ibuf = image_get_ibuf(ima, 0, frame);
2502                         
2503                         /* XXX temp stuff? */
2504                         if (ima->lastframe != frame) {
2505                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2506                         }
2507                         ima->lastframe = frame;
2508                 }       
2509                 else if (ima->type == IMA_TYPE_MULTILAYER) {
2510                         frame = iuser ? iuser->framenr : ima->lastframe;
2511                         index = iuser ? iuser->multi_index : IMA_NO_INDEX;
2512                         ibuf = image_get_ibuf(ima, index, frame);
2513                 }
2514         }
2515         else if (ima->source == IMA_SRC_FILE) {
2516                 if (ima->type == IMA_TYPE_IMAGE)
2517                         ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2518                 else if (ima->type == IMA_TYPE_MULTILAYER)
2519                         ibuf = image_get_ibuf(ima, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2520         }
2521         else if (ima->source == IMA_SRC_GENERATED) {
2522                 ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2523         }
2524         else if (ima->source == IMA_SRC_VIEWER) {
2525                 /* always verify entirely, not that this shouldn't happen
2526                  * as part of texture sampling in rendering anyway, so not
2527                  * a big bottleneck */
2528         }
2529
2530         *frame_r = frame;
2531         *index_r = index;
2532
2533         return ibuf;
2534 }
2535
2536 /* Checks optional ImageUser and verifies/creates ImBuf. */
2537 /* use this one if you want to get a render result in progress,
2538  * if not, use BKE_image_get_ibuf which doesn't require a release */
2539 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2540 {
2541         ImBuf *ibuf = NULL;
2542         float color[] = {0, 0, 0, 1};
2543         int frame = 0, index = 0;
2544
2545         /* This function is intended to be thread-safe. It postpones the mutex lock
2546          * until it needs to load the image, if the image is already there it
2547          * should just get the pointer and return. The reason is that a lot of mutex
2548          * locks appears to be very slow on certain multicore macs, causing a render
2549          * with image textures to actually slow down as more threads are used.
2550          *
2551          * Note that all the image loading functions should also make sure they do
2552          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2553          * That means, the last two steps must be, 1) add the ibuf to the list and
2554          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2555         
2556         if (lock_r)
2557                 *lock_r = NULL;
2558
2559         /* quick reject tests */
2560         if (ima == NULL)
2561                 return NULL;
2562         if (iuser) {
2563                 if (iuser->ok == 0)
2564                         return NULL;
2565         }
2566         else if (ima->ok == 0)
2567                 return NULL;
2568         
2569         /* try to get the ibuf without locking */
2570         ibuf = image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2571
2572         if (ibuf == NULL) {
2573                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2574                  * load the image */
2575                 BLI_lock_thread(LOCK_IMAGE);
2576
2577                 /* need to check ok flag and loading ibuf again, because the situation
2578                  * might have changed in the meantime */
2579                 if (iuser) {
2580                         if (iuser->ok == 0) {
2581                                 BLI_unlock_thread(LOCK_IMAGE);
2582                                 return NULL;
2583                         }
2584                 }
2585                 else if (ima->ok == 0) {
2586                         BLI_unlock_thread(LOCK_IMAGE);
2587                         return NULL;
2588                 }
2589
2590                 ibuf = image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2591
2592                 if (ibuf == NULL) {
2593                         /* we are sure we have to load the ibuf, using source and type */
2594                         if (ima->source == IMA_SRC_MOVIE) {
2595                                 /* source is from single file, use flipbook to store ibuf */
2596                                 ibuf = image_load_movie_file(ima, iuser, frame);
2597                         }
2598                         else if (ima->source == IMA_SRC_SEQUENCE) {
2599                                 if (ima->type == IMA_TYPE_IMAGE) {
2600                                         /* regular files, ibufs in flipbook, allows saving */
2601                                         ibuf = image_load_sequence_file(ima, iuser, frame);
2602                                 }
2603                                 /* no else; on load the ima type can change */
2604                                 if (ima->type == IMA_TYPE_MULTILAYER) {
2605                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2606                                         ibuf = image_load_sequence_multilayer(ima, iuser, frame);
2607                                 }
2608                         }
2609                         else if (ima->source == IMA_SRC_FILE) {
2610                                 
2611                                 if (ima->type == IMA_TYPE_IMAGE)
2612                                         ibuf = image_load_image_file(ima, iuser, frame);  /* cfra only for '#', this global is OK */
2613                                 /* no else; on load the ima type can change */
2614                                 if (ima->type == IMA_TYPE_MULTILAYER)
2615                                         /* keeps render result, stores ibufs in listbase, allows saving */
2616                                         ibuf = image_get_ibuf_multilayer(ima, iuser);
2617                                         
2618                         }
2619                         else if (ima->source == IMA_SRC_GENERATED) {
2620                                 /* generated is: ibuf is allocated dynamically */
2621                                 /* UV testgrid or black or solid etc */
2622                                 if (ima->gen_x == 0) ima->gen_x = 1024;
2623                                 if (ima->gen_y == 0) ima->gen_y = 1024;
2624                                 ibuf = add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, (ima->gen_flag & IMA_GEN_FLOAT) != 0, ima->gen_type, color);
2625                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2626                                 ima->ok = IMA_OK_LOADED;
2627                         }
2628                         else if (ima->source == IMA_SRC_VIEWER) {
2629                                 if (ima->type == IMA_TYPE_R_RESULT) {
2630                                         /* always verify entirely, and potentially
2631                                          * returns pointer to release later */
2632                                         ibuf = image_get_render_result(ima, iuser, lock_r);
2633                                 }
2634                                 else if (ima->type == IMA_TYPE_COMPOSITE) {
2635                                         /* requires lock/unlock, otherwise don't return image */
2636                                         if (lock_r) {
2637                                                 /* unlock in BKE_image_release_ibuf */
2638                                                 BLI_lock_thread(LOCK_VIEWER);
2639                                                 *lock_r = ima;
2640
2641                                                 /* XXX anim play for viewer nodes not yet supported */
2642                                                 frame = 0; // XXX iuser?iuser->framenr:0;
2643                                                 ibuf = image_get_ibuf(ima, 0, frame);
2644
2645                                                 if (!ibuf) {
2646                                                         /* Composite Viewer, all handled in compositor */
2647                                                         /* fake ibuf, will be filled in compositor */
2648                                                         ibuf = IMB_allocImBuf(256, 256, 32, IB_rect);
2649                                                         image_assign_ibuf(ima, ibuf, 0, frame);
2650                                                 }
2651                                         }
2652                                 }
2653                         }
2654                 }
2655
2656                 BLI_unlock_thread(LOCK_IMAGE);
2657         }
2658
2659         BKE_image_tag_time(ima);
2660
2661         return ibuf;
2662 }
2663
2664 void BKE_image_release_ibuf(Image *ima, void *lock)
2665 {
2666         /* for getting image during threaded render / compositing, need to release */
2667         if (lock == ima) {
2668                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2669         }
2670         else if (lock) {
2671                 RE_ReleaseResultImage(lock); /* render result */
2672                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2673         }
2674 }
2675
2676 /* warning, this can allocate generated images */
2677 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2678 {
2679         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2680         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2681 }
2682
2683 int BKE_image_user_frame_get(const ImageUser *iuser, int cfra, int fieldnr)
2684 {
2685         const int len = (iuser->fie_ima * iuser->frames) / 2;
2686
2687         if (len == 0) {
2688                 return 0;
2689         }
2690         else {
2691                 int framenr;
2692                 cfra = cfra - iuser->sfra + 1;
2693
2694                 /* cyclic */
2695                 if (iuser->cycl) {
2696                         cfra = ((cfra) % len);
2697                         if (cfra < 0) cfra += len;
2698                         if (cfra == 0) cfra = len;
2699                 }
2700
2701                 if (cfra < 0) cfra = 0;
2702                 else if (cfra > len) cfra = len;
2703
2704                 /* convert current frame to current field */
2705                 cfra = 2 * (cfra);
2706                 if (fieldnr) cfra++;
2707
2708                 /* transform to images space */
2709                 framenr = (cfra + iuser->fie_ima - 2) / iuser->fie_ima;
2710                 if (framenr > iuser->frames) framenr = iuser->frames;
2711                 framenr += iuser->offset;
2712
2713                 if (iuser->cycl) {
2714                         framenr = ((framenr) % len);
2715                         while (framenr < 0) framenr += len;
2716                         if (framenr == 0) framenr = len;
2717                 }
2718
2719                 return framenr;
2720         }
2721 }
2722
2723 void BKE_image_user_frame_calc(ImageUser *iuser, int cfra, int fieldnr)
2724 {
2725         const int framenr = BKE_image_user_frame_get(iuser, cfra, fieldnr);
2726
2727         /* allows image users to handle redraws */
2728         if (iuser->flag & IMA_ANIM_ALWAYS)
2729                 if (framenr != iuser->framenr)
2730                         iuser->flag |= IMA_ANIM_REFRESHED;
2731
2732         iuser->framenr = framenr;
2733         if (iuser->ok == 0) iuser->ok = 1;
2734 }
2735
2736 void BKE_image_user_check_frame_calc(ImageUser *iuser, int cfra, int fieldnr)
2737 {
2738         if ((iuser->flag & IMA_ANIM_ALWAYS) || (iuser->flag & IMA_NEED_FRAME_RECALC)) {
2739                 BKE_image_user_frame_calc(iuser, cfra, fieldnr);
2740
2741                 iuser->flag &= ~IMA_NEED_FRAME_RECALC;
2742         }
2743 }
2744
2745 void BKE_image_user_file_path(ImageUser *iuser, Image *ima, char *filepath)
2746 {
2747         BLI_strncpy(filepath, ima->name, FILE_MAX);
2748
2749         if (ima->source == IMA_SRC_SEQUENCE) {
2750                 char head[FILE_MAX], tail[FILE_MAX];
2751                 unsigned short numlen;
2752                 int frame = iuser->framenr;
2753
2754                 BLI_stringdec(filepath, head, tail, &numlen);
2755                 BLI_stringenc(filepath, head, tail, numlen, frame);
2756         }
2757
2758         BLI_path_abs(filepath, ID_BLEND_PATH(G.main, &ima->id));
2759 }
2760
2761 int BKE_image_has_alpha(struct Image *image)
2762 {
2763         ImBuf *ibuf;
2764         void *lock;
2765         int planes;
2766         
2767         ibuf = BKE_image_acquire_ibuf(image, NULL, &lock);
2768         planes = (ibuf ? ibuf->planes : 0);
2769         BKE_image_release_ibuf(image, lock);
2770
2771         if (planes == 32)
2772                 return 1;
2773         else
2774                 return 0;
2775 }