8676a5fb271383f70e3790e19513edfa8f925f8d
[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 void BKE_imbuf_to_image_format(struct ImageFormatData *im_format, const ImBuf *imbuf)
1212 {
1213         BKE_imformat_defaults(im_format);
1214
1215         // file type
1216
1217         if (imbuf->ftype == IMAGIC)
1218                 im_format->imtype = R_IMF_IMTYPE_IRIS;
1219
1220 #ifdef WITH_HDR
1221         else if (imbuf->ftype == RADHDR)
1222                 im_format->imtype = R_IMF_IMTYPE_RADHDR;
1223 #endif
1224
1225         else if (imbuf->ftype == PNG)
1226                 im_format->imtype = R_IMF_IMTYPE_PNG;
1227
1228 #ifdef WITH_DDS
1229         else if (imbuf->ftype == DDS)
1230                 im_format->imtype = R_IMF_IMTYPE_DDS;
1231 #endif
1232
1233         else if (imbuf->ftype == BMP)
1234                 im_format->imtype = R_IMF_IMTYPE_BMP;
1235
1236 #ifdef WITH_TIFF
1237         else if (imbuf->ftype & TIF) {
1238                 im_format->imtype = R_IMF_IMTYPE_TIFF;
1239                 if (imbuf->ftype & TIF_16BIT)
1240                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1241         }
1242 #endif
1243
1244 #ifdef WITH_OPENEXR
1245         else if (imbuf->ftype & OPENEXR) {
1246                 im_format->imtype = R_IMF_IMTYPE_OPENEXR; 
1247                 if (imbuf->ftype & OPENEXR_HALF)
1248                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1249                 if (imbuf->ftype & OPENEXR_COMPRESS)
1250                         im_format->exr_codec = R_IMF_EXR_CODEC_ZIP; // Can't determine compression
1251                 if (imbuf->zbuf_float)
1252                         im_format->flag |= R_IMF_FLAG_ZBUF;
1253         }
1254 #endif
1255
1256 #ifdef WITH_CINEON
1257         else if (imbuf->ftype == CINEON)
1258                 im_format->imtype = R_IMF_IMTYPE_CINEON;
1259         else if (imbuf->ftype == DPX)
1260                 im_format->imtype = R_IMF_IMTYPE_DPX;
1261 #endif
1262
1263         else if (imbuf->ftype == TGA) {
1264                 im_format->imtype = R_IMF_IMTYPE_TARGA;
1265         }
1266         else if (imbuf->ftype == RAWTGA) {
1267                 im_format->imtype = R_IMF_IMTYPE_RAWTGA;
1268         }
1269
1270 #ifdef WITH_OPENJPEG
1271         else if (imbuf->ftype & JP2) {
1272                 im_format->imtype = R_IMF_IMTYPE_JP2;
1273                 im_format->quality = imbuf->ftype & ~JPG_MSK;
1274
1275                 if (imbuf->ftype & JP2_16BIT)
1276                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1277                 else if (imbuf->ftype & JP2_12BIT)
1278                         im_format->depth = R_IMF_CHAN_DEPTH_12;
1279
1280                 if(imbuf->ftype & JP2_YCC)
1281                         im_format->jp2_flag |= R_IMF_JP2_FLAG_YCC;
1282
1283                 if(imbuf->ftype & JP2_CINE) {
1284                         im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_PRESET;
1285                         if (imbuf->ftype & JP2_CINE_48FPS)
1286                                 im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_48;
1287                 }
1288         }
1289 #endif
1290
1291         else {
1292                 im_format->imtype = R_IMF_IMTYPE_JPEG90;
1293                 im_format->quality = imbuf->ftype & ~JPG_MSK;
1294         }
1295
1296         // planes
1297         switch (imbuf->channels) {
1298                 case 0:
1299                 case 4: im_format->planes = R_IMF_PLANES_RGBA;
1300                                 break;
1301                 case 3: im_format->planes = R_IMF_PLANES_RGB;
1302                                 break;
1303                 case 1: im_format->planes = R_IMF_PLANES_BW;
1304                                 break;
1305                 default:im_format->planes = R_IMF_PLANES_RGB;
1306                                 break;
1307         }
1308
1309 }
1310
1311 /* could allow access externally - 512 is for long names, 64 is for id names */
1312 typedef struct StampData {
1313         char file[512];
1314         char note[512];
1315         char date[512];
1316         char marker[512];
1317         char time[512];
1318         char frame[512];
1319         char camera[64];
1320         char cameralens[64];
1321         char scene[64];
1322         char strip[64];
1323         char rendertime[64];
1324 } StampData;
1325
1326 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix)
1327 {
1328         char text[256];
1329         struct tm *tl;
1330         time_t t;
1331
1332         if (scene->r.stamp & R_STAMP_FILENAME) {
1333                 BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), do_prefix ? "File %s" : "%s", G.relbase_valid ? G.main->name : "<untitled>");
1334         }
1335         else {
1336                 stamp_data->file[0] = '\0';
1337         }
1338         
1339         if (scene->r.stamp & R_STAMP_NOTE) {
1340                 /* Never do prefix for Note */
1341                 BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", scene->r.stamp_udata);
1342         }
1343         else {
1344                 stamp_data->note[0] = '\0';
1345         }
1346         
1347         if (scene->r.stamp & R_STAMP_DATE) {
1348                 t = time(NULL);
1349                 tl = localtime(&t);
1350                 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);
1351                 BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), do_prefix ? "Date %s" : "%s", text);
1352         }
1353         else {
1354                 stamp_data->date[0] = '\0';
1355         }
1356         
1357         if (scene->r.stamp & R_STAMP_MARKER) {
1358                 char *name = BKE_scene_find_last_marker_name(scene, CFRA);
1359
1360                 if (name) BLI_strncpy(text, name, sizeof(text));
1361                 else BLI_strncpy(text, "<none>", sizeof(text));
1362
1363                 BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), do_prefix ? "Marker %s" : "%s", text);
1364         }
1365         else {
1366                 stamp_data->marker[0] = '\0';
1367         }
1368         
1369         if (scene->r.stamp & R_STAMP_TIME) {
1370                 int f = (int)(scene->r.cfra % scene->r.frs_sec);
1371                 int s = (int)(scene->r.cfra / scene->r.frs_sec);
1372                 int h = 0;
1373                 int m = 0;
1374
1375                 if (s) {
1376                         m = (int)(s / 60);
1377                         s %= 60;
1378
1379                         if (m) {
1380                                 h = (int)(m / 60);
1381                                 m %= 60;
1382                         }
1383                 }
1384
1385                 if (scene->r.frs_sec < 100)
1386                         BLI_snprintf(text, sizeof(text), "%02d:%02d:%02d.%02d", h, m, s, f);
1387                 else
1388                         BLI_snprintf(text, sizeof(text), "%02d:%02d:%02d.%03d", h, m, s, f);
1389
1390                 BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), do_prefix ? "Time %s" : "%s", text);
1391         }
1392         else {
1393                 stamp_data->time[0] = '\0';
1394         }
1395         
1396         if (scene->r.stamp & R_STAMP_FRAME) {
1397                 char fmtstr[32];
1398                 int digits = 1;
1399                 
1400                 if (scene->r.efra > 9)
1401                         digits = 1 + (int) log10(scene->r.efra);
1402
1403                 BLI_snprintf(fmtstr, sizeof(fmtstr), do_prefix ? "Frame %%0%di" : "%%0%di", digits);
1404                 BLI_snprintf(stamp_data->frame, sizeof(stamp_data->frame), fmtstr, scene->r.cfra);
1405         }
1406         else {
1407                 stamp_data->frame[0] = '\0';
1408         }
1409
1410         if (scene->r.stamp & R_STAMP_CAMERA) {
1411                 BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), do_prefix ? "Camera %s" : "%s", camera ? camera->id.name + 2 : "<none>");
1412         }
1413         else {
1414                 stamp_data->camera[0] = '\0';
1415         }
1416
1417         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1418                 if (camera && camera->type == OB_CAMERA) {
1419                         BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)camera->data)->lens);
1420                 }
1421                 else BLI_strncpy(text, "<none>", sizeof(text));
1422
1423                 BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), do_prefix ? "Lens %s" : "%s", text);
1424         }
1425         else {
1426                 stamp_data->cameralens[0] = '\0';
1427         }
1428
1429         if (scene->r.stamp & R_STAMP_SCENE) {
1430                 BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), do_prefix ? "Scene %s" : "%s", scene->id.name + 2);
1431         }
1432         else {
1433                 stamp_data->scene[0] = '\0';
1434         }
1435         
1436         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1437                 Sequence *seq = seq_foreground_frame_get(scene, scene->r.cfra);
1438         
1439                 if (seq) BLI_strncpy(text, seq->name + 2, sizeof(text));
1440                 else BLI_strncpy(text, "<none>", sizeof(text));
1441
1442                 BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), do_prefix ? "Strip %s" : "%s", text);
1443         }
1444         else {
1445                 stamp_data->strip[0] = '\0';
1446         }
1447
1448         {
1449                 Render *re = RE_GetRender(scene->id.name);
1450                 RenderStats *stats = re ? RE_GetStats(re) : NULL;
1451
1452                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1453                         BLI_timestr(stats->lastframetime, text);
1454
1455                         BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), do_prefix ? "RenderTime %s" : "%s", text);
1456                 }
1457                 else {
1458                         stamp_data->rendertime[0] = '\0';
1459                 }
1460         }
1461 }
1462
1463 void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rectf, int width, int height, int channels)
1464 {
1465         struct StampData stamp_data;
1466         float w, h, pad;
1467         int x, y, y_ofs;
1468         float h_fixed;
1469         const int mono = blf_mono_font_render; // XXX
1470
1471 #define BUFF_MARGIN_X 2
1472 #define BUFF_MARGIN_Y 1
1473
1474         if (!rect && !rectf)
1475                 return;
1476         
1477         stampdata(scene, camera, &stamp_data, 1);
1478
1479         /* TODO, do_versions */
1480         if (scene->r.stamp_font_id < 8)
1481                 scene->r.stamp_font_id = 12;
1482
1483         /* set before return */
1484         BLF_size(mono, scene->r.stamp_font_id, 72);
1485         
1486         BLF_buffer(mono, rectf, rect, width, height, channels);
1487         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1488         pad = BLF_width_max(mono);
1489
1490         /* use 'h_fixed' rather than 'h', aligns better */
1491         h_fixed = BLF_height_max(mono);
1492         y_ofs = -BLF_descender(mono);
1493
1494         x = 0;
1495         y = height;
1496
1497         if (stamp_data.file[0]) {
1498                 /* Top left corner */
1499                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h = h_fixed;
1500                 y -= h;
1501
1502                 /* also a little of space to the background. */
1503                 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);
1504
1505                 /* and draw the text. */
1506                 BLF_position(mono, x, y + y_ofs, 0.0);
1507                 BLF_draw_buffer(mono, stamp_data.file);
1508
1509                 /* the extra pixel for background. */
1510                 y -= BUFF_MARGIN_Y * 2;
1511         }
1512
1513         /* Top left corner, below File */
1514         if (stamp_data.note[0]) {
1515                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h = h_fixed;
1516                 y -= h;
1517
1518                 /* and space for background. */
1519                 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);
1520
1521                 BLF_position(mono, x, y + y_ofs, 0.0);
1522                 BLF_draw_buffer(mono, stamp_data.note);
1523
1524                 /* the extra pixel for background. */
1525                 y -= BUFF_MARGIN_Y * 2;
1526         }
1527         
1528         /* Top left corner, below File (or Note) */
1529         if (stamp_data.date[0]) {
1530                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h = h_fixed;
1531                 y -= h;
1532
1533                 /* and space for background. */
1534                 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);
1535
1536                 BLF_position(mono, x, y + y_ofs, 0.0);
1537                 BLF_draw_buffer(mono, stamp_data.date);
1538
1539                 /* the extra pixel for background. */
1540                 y -= BUFF_MARGIN_Y * 2;
1541         }
1542
1543         /* Top left corner, below File, Date or Note */
1544         if (stamp_data.rendertime[0]) {
1545                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h = h_fixed;
1546                 y -= h;
1547
1548                 /* and space for background. */
1549                 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);
1550
1551                 BLF_position(mono, x, y + y_ofs, 0.0);
1552                 BLF_draw_buffer(mono, stamp_data.rendertime);
1553         }
1554
1555         x = 0;
1556         y = 0;
1557
1558         /* Bottom left corner, leaving space for timing */
1559         if (stamp_data.marker[0]) {
1560                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h = h_fixed;
1561
1562                 /* extra space for background. */
1563                 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);
1564
1565                 /* and pad the text. */
1566                 BLF_position(mono, x, y + y_ofs, 0.0);
1567                 BLF_draw_buffer(mono, stamp_data.marker);
1568
1569                 /* space width. */
1570                 x += w + pad;
1571         }
1572         
1573         /* Left bottom corner */
1574         if (stamp_data.time[0]) {
1575                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h = h_fixed;
1576
1577                 /* extra space for background */
1578                 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);
1579
1580                 /* and pad the text. */
1581                 BLF_position(mono, x, y + y_ofs, 0.0);
1582                 BLF_draw_buffer(mono, stamp_data.time);
1583
1584                 /* space width. */
1585                 x += w + pad;
1586         }
1587         
1588         if (stamp_data.frame[0]) {
1589                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h = h_fixed;
1590
1591                 /* extra space for background. */
1592                 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);
1593
1594                 /* and pad the text. */
1595                 BLF_position(mono, x, y + y_ofs, 0.0);
1596                 BLF_draw_buffer(mono, stamp_data.frame);
1597
1598                 /* space width. */
1599                 x += w + pad;
1600         }
1601
1602         if (stamp_data.camera[0]) {
1603                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h = h_fixed;
1604
1605                 /* extra space for background. */
1606                 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);
1607                 BLF_position(mono, x, y + y_ofs, 0.0);
1608                 BLF_draw_buffer(mono, stamp_data.camera);
1609
1610                 /* space width. */
1611                 x += w + pad;
1612         }
1613
1614         if (stamp_data.cameralens[0]) {
1615                 BLF_width_and_height(mono, stamp_data.cameralens, &w, &h); h = h_fixed;
1616
1617                 /* extra space for background. */
1618                 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);
1619                 BLF_position(mono, x, y + y_ofs, 0.0);
1620                 BLF_draw_buffer(mono, stamp_data.cameralens);
1621         }
1622         
1623         if (stamp_data.scene[0]) {
1624                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h = h_fixed;
1625
1626                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1627                 x = width - w - 2;
1628
1629                 /* extra space for background. */
1630                 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);
1631
1632                 /* and pad the text. */
1633                 BLF_position(mono, x, y + y_ofs, 0.0);
1634                 BLF_draw_buffer(mono, stamp_data.scene);
1635         }
1636         
1637         if (stamp_data.strip[0]) {
1638                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h = h_fixed;
1639
1640                 /* Top right corner, with an extra space because blenfont is too strict! */
1641                 x = width - w - pad;
1642                 y = height - h;
1643
1644                 /* extra space for background. */
1645                 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);
1646
1647                 BLF_position(mono, x, y + y_ofs, 0.0);
1648                 BLF_draw_buffer(mono, stamp_data.strip);
1649         }
1650
1651         /* cleanup the buffer. */
1652         BLF_buffer(mono, NULL, NULL, 0, 0, 0);
1653
1654 #undef BUFF_MARGIN_X
1655 #undef BUFF_MARGIN_Y
1656 }
1657
1658 void BKE_imbuf_stamp_info(Scene *scene, Object *camera, struct ImBuf *ibuf)
1659 {
1660         struct StampData stamp_data;
1661
1662         if (!ibuf) return;
1663         
1664         /* fill all the data values, no prefix */
1665         stampdata(scene, camera, &stamp_data, 0);
1666         
1667         if (stamp_data.file[0]) IMB_metadata_change_field(ibuf, "File",        stamp_data.file);
1668         if (stamp_data.note[0]) IMB_metadata_change_field(ibuf, "Note",        stamp_data.note);
1669         if (stamp_data.date[0]) IMB_metadata_change_field(ibuf, "Date",        stamp_data.date);
1670         if (stamp_data.marker[0]) IMB_metadata_change_field(ibuf, "Marker",    stamp_data.marker);
1671         if (stamp_data.time[0]) IMB_metadata_change_field(ibuf, "Time",        stamp_data.time);
1672         if (stamp_data.frame[0]) IMB_metadata_change_field(ibuf, "Frame",      stamp_data.frame);
1673         if (stamp_data.camera[0]) IMB_metadata_change_field(ibuf, "Camera",    stamp_data.camera);
1674         if (stamp_data.cameralens[0]) IMB_metadata_change_field(ibuf, "Lens",  stamp_data.cameralens);
1675         if (stamp_data.scene[0]) IMB_metadata_change_field(ibuf, "Scene",      stamp_data.scene);
1676         if (stamp_data.strip[0]) IMB_metadata_change_field(ibuf, "Strip",      stamp_data.strip);
1677         if (stamp_data.rendertime[0]) IMB_metadata_change_field(ibuf, "RenderTime", stamp_data.rendertime);
1678 }
1679
1680 int BKE_imbuf_alpha_test(ImBuf *ibuf)
1681 {
1682         int tot;
1683         if (ibuf->rect_float) {
1684                 float *buf = ibuf->rect_float;
1685                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1686                         if (buf[3] < 1.0f) {
1687                                 return TRUE;
1688                         }
1689                 }
1690         }
1691         else if (ibuf->rect) {
1692                 unsigned char *buf = (unsigned char *)ibuf->rect;
1693                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1694                         if (buf[3] != 255) {
1695                                 return TRUE;
1696                         }
1697                 }
1698         }
1699
1700         return FALSE;
1701 }
1702
1703 /* note: imf->planes is ignored here, its assumed the image channels
1704  * are already set */
1705 int BKE_imbuf_write(ImBuf *ibuf, const char *name, ImageFormatData *imf)
1706 {
1707         char imtype = imf->imtype;
1708         char compress = imf->compress;
1709         char quality = imf->quality;
1710
1711         int ok;
1712
1713         if (imtype == R_IMF_IMTYPE_IRIS) {
1714                 ibuf->ftype = IMAGIC;
1715         }
1716 #ifdef WITH_HDR
1717         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1718                 ibuf->ftype = RADHDR;
1719         }
1720 #endif
1721         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1722                 ibuf->ftype = PNG;
1723
1724                 if (imtype == R_IMF_IMTYPE_PNG)
1725                         ibuf->ftype |= compress;
1726
1727         }
1728 #ifdef WITH_DDS
1729         else if (imtype == R_IMF_IMTYPE_DDS) {
1730                 ibuf->ftype = DDS;
1731         }
1732 #endif
1733         else if (imtype == R_IMF_IMTYPE_BMP) {
1734                 ibuf->ftype = BMP;
1735         }
1736 #ifdef WITH_TIFF
1737         else if (imtype == R_IMF_IMTYPE_TIFF) {
1738                 ibuf->ftype = TIF;
1739
1740                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1741                         ibuf->ftype |= TIF_16BIT;
1742         }
1743 #endif
1744 #ifdef WITH_OPENEXR
1745         else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER) {
1746                 ibuf->ftype = OPENEXR;
1747                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1748                         ibuf->ftype |= OPENEXR_HALF;
1749                 ibuf->ftype |= (imf->exr_codec & OPENEXR_COMPRESS);
1750                 
1751                 if (!(imf->flag & R_IMF_FLAG_ZBUF))
1752                         ibuf->zbuf_float = NULL;    /* signal for exr saving */
1753                 
1754         }
1755 #endif
1756 #ifdef WITH_CINEON
1757         else if (imtype == R_IMF_IMTYPE_CINEON) {
1758                 ibuf->ftype = CINEON;
1759         }
1760         else if (imtype == R_IMF_IMTYPE_DPX) {
1761                 ibuf->ftype = DPX;
1762         }
1763 #endif
1764         else if (imtype == R_IMF_IMTYPE_TARGA) {
1765                 ibuf->ftype = TGA;
1766         }
1767         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
1768                 ibuf->ftype = RAWTGA;
1769         }
1770 #ifdef WITH_OPENJPEG
1771         else if (imtype == R_IMF_IMTYPE_JP2) {
1772                 if (quality < 10) quality = 90;
1773                 ibuf->ftype = JP2 | quality;
1774                 
1775                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1776                         ibuf->ftype |= JP2_16BIT;
1777                 }
1778                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1779                         ibuf->ftype |= JP2_12BIT;
1780                 }
1781                 
1782                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
1783                         ibuf->ftype |= JP2_YCC;
1784                 }
1785
1786                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
1787                         ibuf->ftype |= JP2_CINE;
1788                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
1789                                 ibuf->ftype |= JP2_CINE_48FPS;
1790                 }
1791         }
1792 #endif
1793         else {
1794                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
1795                 if (quality < 10) quality = 90;
1796                 ibuf->ftype = JPG | quality;
1797         }
1798         
1799         BLI_make_existing_file(name);
1800         
1801         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1802         if (ok == 0) {
1803                 perror(name);
1804         }
1805         
1806         return(ok);
1807 }
1808
1809 /* same as BKE_imbuf_write() but crappy workaround not to perminantly modify
1810  * _some_, values in the imbuf */
1811 int BKE_imbuf_write_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
1812                        const short save_copy)
1813 {
1814         ImBuf ibuf_back = *ibuf;
1815         int ok;
1816
1817         /* all data is rgba anyway,
1818          * this just controls how to save for some formats */
1819         ibuf->planes = imf->planes;
1820
1821         ok = BKE_imbuf_write(ibuf, name, imf);
1822
1823         if (save_copy) {
1824                 /* note that we are not restoring _all_ settings */
1825                 ibuf->planes = ibuf_back.planes;
1826                 ibuf->ftype =  ibuf_back.ftype;
1827         }
1828
1829         return ok;
1830 }
1831
1832 int BKE_imbuf_write_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, struct ImageFormatData *imf)
1833 {
1834         if (scene && scene->r.stamp & R_STAMP_ALL)
1835                 BKE_imbuf_stamp_info(scene, camera, ibuf);
1836
1837         return BKE_imbuf_write(ibuf, name, imf);
1838 }
1839
1840
1841 void BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, const char imtype, const short use_ext, const short use_frames)
1842 {
1843         if (string == NULL) return;
1844         BLI_strncpy(string, base, FILE_MAX - 10);   /* weak assumption */
1845         BLI_path_abs(string, relbase);
1846
1847         if (use_frames)
1848                 BLI_path_frame(string, frame, 4);
1849
1850         if (use_ext)
1851                 BKE_add_image_extension(string, imtype);
1852                 
1853 }
1854
1855 /* used by sequencer too */
1856 struct anim *openanim(const char *name, int flags, int streamindex)
1857 {
1858         struct anim *anim;
1859         struct ImBuf *ibuf;
1860         
1861         anim = IMB_open_anim(name, flags, streamindex);
1862         if (anim == NULL) return NULL;
1863
1864         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
1865         if (ibuf == NULL) {
1866                 if (BLI_exists(name))
1867                         printf("not an anim: %s\n", name);
1868                 else
1869                         printf("anim file doesn't exist: %s\n", name);
1870                 IMB_free_anim(anim);
1871                 return NULL;
1872         }
1873         IMB_freeImBuf(ibuf);
1874         
1875         return(anim);
1876 }
1877
1878 /* ************************* New Image API *************** */
1879
1880
1881 /* Notes about Image storage 
1882  * - packedfile
1883  *   -> written in .blend
1884  * - filename
1885  *   -> written in .blend
1886  * - movie
1887  *   -> comes from packedfile or filename
1888  * - renderresult
1889  *   -> comes from packedfile or filename
1890  * - listbase
1891  *   -> ibufs from exrhandle
1892  * - flipbook array
1893  *   -> ibufs come from movie, temporary renderresult or sequence
1894  * - ibuf
1895  *   -> comes from packedfile or filename or generated
1896  */
1897
1898
1899 /* forces existence of 1 Image for renderout or nodes, returns Image */
1900 /* name is only for default, when making new one */
1901 Image *BKE_image_verify_viewer(int type, const char *name)
1902 {
1903         Image *ima;
1904         
1905         for (ima = G.main->image.first; ima; ima = ima->id.next)
1906                 if (ima->source == IMA_SRC_VIEWER)
1907                         if (ima->type == type)
1908                                 break;
1909         
1910         if (ima == NULL)
1911                 ima = image_alloc(name, IMA_SRC_VIEWER, type);
1912         
1913         /* happens on reload, imagewindow cannot be image user when hidden*/
1914         if (ima->id.us == 0)
1915                 id_us_plus(&ima->id);
1916
1917         return ima;
1918 }
1919
1920 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1921 {
1922         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1923 }
1924
1925 void BKE_image_walk_all_users(const Main *mainp, void *customdata,
1926                               void callback(Image *ima, ImageUser *iuser, void *customdata))
1927 {
1928         wmWindowManager *wm;
1929         wmWindow *win;
1930         Tex *tex;
1931
1932         /* texture users */
1933         for (tex = mainp->tex.first; tex; tex = tex->id.next) {
1934                 if (tex->type == TEX_IMAGE && tex->ima) {
1935                         if (ELEM(tex->ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
1936                                 callback(tex->ima, &tex->iuser, customdata);
1937                         }
1938                 }
1939         }
1940
1941         /* image window, compo node users */
1942         for (wm = mainp->wm.first; wm; wm = wm->id.next) { /* only 1 wm */
1943                 for (win = wm->windows.first; win; win = win->next) {
1944                         ScrArea *sa;
1945                         for (sa = win->screen->areabase.first; sa; sa = sa->next) {
1946                                 if (sa->spacetype == SPACE_VIEW3D) {
1947                                         View3D *v3d = sa->spacedata.first;
1948                                         BGpic *bgpic;
1949                                         for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
1950                                                 callback(bgpic->ima, &bgpic->iuser, customdata);
1951                                         }
1952                                 }
1953                                 else if (sa->spacetype == SPACE_IMAGE) {
1954                                         SpaceImage *sima = sa->spacedata.first;
1955                                         callback(sima->image, &sima->iuser, customdata);
1956                                 }
1957                                 else if (sa->spacetype == SPACE_NODE) {
1958                                         SpaceNode *snode = sa->spacedata.first;
1959                                         if ((snode->treetype == NTREE_COMPOSIT) && (snode->nodetree)) {
1960                                                 bNode *node;
1961                                                 for (node = snode->nodetree->nodes.first; node; node = node->next) {
1962                                                         if (node->id && node->type == CMP_NODE_IMAGE) {
1963                                                                 Image *ima = (Image *)node->id;
1964                                                                 ImageUser *iuser = node->storage;
1965                                                                 callback(ima, iuser, customdata);
1966                                                         }
1967                                                 }
1968                                         }
1969                                 }
1970                         }
1971                 }
1972         }
1973 }
1974
1975 static void image_tag_frame_recalc(Image *ima, ImageUser *iuser, void *customdata)
1976 {
1977         Image *changed_image = customdata;
1978
1979         if (ima == changed_image) {
1980                 iuser->flag |= IMA_NEED_FRAME_RECALC;
1981         }
1982 }
1983
1984 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1985 {
1986         if (ima == NULL)
1987                 return;
1988         
1989         switch (signal) {
1990                 case IMA_SIGNAL_FREE:
1991                         image_free_buffers(ima);
1992                         if (iuser)
1993                                 iuser->ok = 1;
1994                         break;
1995                 case IMA_SIGNAL_SRC_CHANGE:
1996                         if (ima->type == IMA_TYPE_UV_TEST)
1997                                 if (ima->source != IMA_SRC_GENERATED)
1998                                         ima->type = IMA_TYPE_IMAGE;
1999
2000                         if (ima->source == IMA_SRC_GENERATED) {
2001                                 if (ima->gen_x == 0 || ima->gen_y == 0) {
2002                                         ImBuf *ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2003                                         if (ibuf) {
2004                                                 ima->gen_x = ibuf->x;
2005                                                 ima->gen_y = ibuf->y;
2006                                         }
2007                                 }
2008                         }
2009
2010                         /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
2011                         if (ima->type != IMA_TYPE_MULTILAYER)
2012                                 image_free_buffers(ima);
2013
2014                         ima->ok = 1;
2015                         if (iuser)
2016                                 iuser->ok = 1;
2017
2018                         BKE_image_walk_all_users(G.main, ima, image_tag_frame_recalc);
2019
2020                         break;
2021
2022                 case IMA_SIGNAL_RELOAD:
2023                         /* try to repack file */
2024                         if (ima->packedfile) {
2025                                 PackedFile *pf;
2026                                 pf = newPackedFile(NULL, ima->name, ID_BLEND_PATH(G.main, &ima->id));
2027                                 if (pf) {
2028                                         freePackedFile(ima->packedfile);
2029                                         ima->packedfile = pf;
2030                                         image_free_buffers(ima);
2031                                 }
2032                                 else {
2033                                         printf("ERROR: Image not available. Keeping packed image\n");
2034                                 }
2035                         }
2036                         else
2037                                 image_free_buffers(ima);
2038                 
2039                         if (iuser)
2040                                 iuser->ok = 1;
2041                 
2042                         break;
2043                 case IMA_SIGNAL_USER_NEW_IMAGE:
2044                         if (iuser) {
2045                                 iuser->ok = 1;
2046                                 if (ima->source == IMA_SRC_FILE || ima->source == IMA_SRC_SEQUENCE) {
2047                                         if (ima->type == IMA_TYPE_MULTILAYER) {
2048                                                 iuser->multi_index = 0;
2049                                                 iuser->layer = iuser->pass = 0;
2050                                         }
2051                                 }
2052                         }
2053                         break;
2054         }
2055         
2056         /* don't use notifiers because they are not 100% sure to succeeded
2057          * this also makes sure all scenes are accounted for. */
2058         {
2059                 Scene *scene;
2060                 for (scene = G.main->scene.first; scene; scene = scene->id.next) {
2061                         if (scene->nodetree) {
2062                                 nodeUpdateID(scene->nodetree, &ima->id);
2063                         }
2064                 }
2065         }
2066 }
2067
2068 /* if layer or pass changes, we need an index for the imbufs list */
2069 /* note it is called for rendered results, but it doesnt use the index! */
2070 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
2071 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
2072 {
2073         RenderLayer *rl;
2074         RenderPass *rpass = NULL;
2075         
2076         if (rr == NULL)
2077                 return NULL;
2078         
2079         if (iuser) {
2080                 short index = 0, rl_index = 0, rp_index;
2081                 
2082                 for (rl = rr->layers.first; rl; rl = rl->next, rl_index++) {
2083                         rp_index = 0;
2084                         for (rpass = rl->passes.first; rpass; rpass = rpass->next, index++, rp_index++)
2085                                 if (iuser->layer == rl_index && iuser->pass == rp_index)
2086                                         break;
2087                         if (rpass)
2088                                 break;
2089                 }
2090                 
2091                 if (rpass)
2092                         iuser->multi_index = index;
2093                 else 
2094                         iuser->multi_index = 0;
2095         }
2096         if (rpass == NULL) {
2097                 rl = rr->layers.first;
2098                 if (rl)
2099                         rpass = rl->passes.first;
2100         }
2101         
2102         return rpass;
2103 }
2104
2105 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
2106 {
2107         if (ima->rr) {
2108                 return ima->rr;
2109         }
2110         else if (ima->type == IMA_TYPE_R_RESULT) {
2111                 if (ima->render_slot == ima->last_render_slot)
2112                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
2113                 else
2114                         return ima->renders[ima->render_slot];
2115         }
2116         else
2117                 return NULL;
2118 }
2119
2120 void BKE_image_release_renderresult(Scene *scene, Image *ima)
2121 {
2122         if (ima->rr) ;
2123         else if (ima->type == IMA_TYPE_R_RESULT) {
2124                 if (ima->render_slot == ima->last_render_slot)
2125                         RE_ReleaseResult(RE_GetRender(scene->id.name));
2126         }
2127 }
2128
2129 void BKE_image_backup_render(Scene *scene, Image *ima)
2130 {
2131         /* called right before rendering, ima->renders contains render
2132          * result pointers for everything but the current render */
2133         Render *re = RE_GetRender(scene->id.name);
2134         int slot = ima->render_slot, last = ima->last_render_slot;
2135
2136         if (slot != last) {
2137                 if (ima->renders[slot]) {
2138                         RE_FreeRenderResult(ima->renders[slot]);
2139                         ima->renders[slot] = NULL;
2140                 }
2141
2142                 ima->renders[last] = NULL;
2143                 RE_SwapResult(re, &ima->renders[last]);
2144         }
2145
2146         ima->last_render_slot = slot;
2147 }
2148
2149 /* after imbuf load, openexr type can return with a exrhandle open */
2150 /* in that case we have to build a render-result */
2151 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
2152 {
2153         
2154         ima->rr = RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
2155
2156 #ifdef WITH_OPENEXR
2157         IMB_exr_close(ibuf->userdata);
2158 #endif
2159
2160         ibuf->userdata = NULL;
2161         if (ima->rr)
2162                 ima->rr->framenr = framenr;
2163 }
2164
2165 /* common stuff to do with images after loading */
2166 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
2167 {
2168         /* preview is NULL when it has never been used as an icon before */
2169         if (G.background == 0 && ima->preview == NULL)
2170                 BKE_icon_changed(BKE_icon_getid(&ima->id));
2171
2172         /* fields */
2173         if (ima->flag & IMA_FIELDS) {
2174                 if (ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
2175                 else de_interlace_ng(ibuf);
2176         }
2177         /* timer */
2178         ima->lastused = clock() / CLOCKS_PER_SEC;
2179         
2180         ima->ok = IMA_OK_LOADED;
2181         
2182 }
2183
2184 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
2185 {
2186         struct ImBuf *ibuf;
2187         char name[FILE_MAX];
2188         int flag;
2189         
2190         /* XXX temp stuff? */
2191         if (ima->lastframe != frame)
2192                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2193
2194         ima->lastframe = frame;
2195         BKE_image_user_file_path(iuser, ima, name);
2196         
2197         flag = IB_rect | IB_multilayer;
2198         if (ima->flag & IMA_DO_PREMUL)
2199                 flag |= IB_premul;
2200
2201         /* read ibuf */
2202         ibuf = IMB_loadiffname(name, flag);
2203
2204 #if 0
2205         if (ibuf) {
2206                 printf(AT " loaded %s\n", name);
2207         }
2208         else {
2209                 printf(AT " missed %s\n", name);
2210         }
2211 #endif
2212
2213         if (ibuf) {
2214 #ifdef WITH_OPENEXR
2215                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2216                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2217                         image_create_multilayer(ima, ibuf, frame);      
2218                         ima->type = IMA_TYPE_MULTILAYER;
2219                         IMB_freeImBuf(ibuf);
2220                         ibuf = NULL;
2221                 }
2222                 else {
2223                         image_initialize_after_load(ima, ibuf);
2224                         image_assign_ibuf(ima, ibuf, 0, frame);
2225                 }
2226 #else
2227                 image_initialize_after_load(ima, ibuf);
2228                 image_assign_ibuf(ima, ibuf, 0, frame);
2229 #endif
2230         }
2231         else
2232                 ima->ok = 0;
2233         
2234         if (iuser)
2235                 iuser->ok = ima->ok;
2236         
2237         return ibuf;
2238 }
2239
2240 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
2241 {
2242         struct ImBuf *ibuf = NULL;
2243         
2244         /* either we load from RenderResult, or we have to load a new one */
2245         
2246         /* check for new RenderResult */
2247         if (ima->rr == NULL || frame != ima->rr->framenr) {
2248                 /* copy to survive not found multilayer image */
2249                 RenderResult *oldrr = ima->rr;
2250         
2251                 ima->rr = NULL;
2252                 ibuf = image_load_sequence_file(ima, iuser, frame);
2253                 
2254                 if (ibuf) { /* actually an error */
2255                         ima->type = IMA_TYPE_IMAGE;
2256                         printf("error, multi is normal image\n");
2257                 }
2258                 // printf("loaded new result %p\n", ima->rr);
2259                 /* free result if new one found */
2260                 if (ima->rr) {
2261                         // if (oldrr) printf("freed previous result %p\n", oldrr);
2262                         if (oldrr) RE_FreeRenderResult(oldrr);
2263                 }
2264                 else {
2265                         ima->rr = oldrr;
2266                 }
2267
2268         }
2269         if (ima->rr) {
2270                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2271                 
2272                 if (rpass) {
2273                         // printf("load from pass %s\n", rpass->name);
2274                         /* since we free  render results, we copy the rect */
2275                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2276                         ibuf->rect_float = MEM_dupallocN(rpass->rect);
2277                         ibuf->flags |= IB_rectfloat;
2278                         ibuf->mall = IB_rectfloat;
2279                         ibuf->channels = rpass->channels;
2280                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2281                         
2282                         image_initialize_after_load(ima, ibuf);
2283                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : 0, frame);
2284                         
2285                 }
2286                 // else printf("pass not found\n");
2287         }
2288         else
2289                 ima->ok = 0;
2290         
2291         if (iuser)
2292                 iuser->ok = ima->ok;
2293         
2294         return ibuf;
2295 }
2296
2297
2298 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
2299 {
2300         struct ImBuf *ibuf = NULL;
2301         
2302         ima->lastframe = frame;
2303         
2304         if (ima->anim == NULL) {
2305                 char str[FILE_MAX];
2306                 
2307                 BKE_image_user_file_path(iuser, ima, str);
2308
2309                 /* FIXME: make several stream accessible in image editor, too*/
2310                 ima->anim = openanim(str, IB_rect, 0);
2311                 
2312                 /* let's initialize this user */
2313                 if (ima->anim && iuser && iuser->frames == 0)
2314                         iuser->frames = IMB_anim_get_duration(ima->anim,
2315                                                               IMB_TC_RECORD_RUN);
2316         }
2317         
2318         if (ima->anim) {
2319                 int dur = IMB_anim_get_duration(ima->anim,
2320                                                 IMB_TC_RECORD_RUN);
2321                 int fra = frame - 1;
2322                 
2323                 if (fra < 0) fra = 0;
2324                 if (fra > (dur - 1)) fra = dur - 1;
2325                 ibuf = IMB_makeSingleUser(
2326                     IMB_anim_absolute(ima->anim, fra,
2327                                       IMB_TC_RECORD_RUN,
2328                                       IMB_PROXY_NONE));
2329                 
2330                 if (ibuf) {
2331                         image_initialize_after_load(ima, ibuf);
2332                         image_assign_ibuf(ima, ibuf, 0, frame);
2333                 }
2334                 else
2335                         ima->ok = 0;
2336         }
2337         else
2338                 ima->ok = 0;
2339         
2340         if (iuser)
2341                 iuser->ok = ima->ok;
2342         
2343         return ibuf;
2344 }
2345
2346 /* warning, 'iuser' can be NULL */
2347 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
2348 {
2349         struct ImBuf *ibuf;
2350         char str[FILE_MAX];
2351         int assign = 0, flag;
2352         
2353         /* always ensure clean ima */
2354         image_free_buffers(ima);
2355         
2356         /* is there a PackedFile with this image ? */
2357         if (ima->packedfile) {
2358                 flag = IB_rect | IB_multilayer;
2359                 if (ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
2360                 
2361                 ibuf = IMB_ibImageFromMemory((unsigned char *)ima->packedfile->data,
2362                                              ima->packedfile->size, flag, "<packed data>");
2363         } 
2364         else {
2365                 flag = IB_rect | IB_multilayer | IB_metadata;
2366                 if (ima->flag & IMA_DO_PREMUL)
2367                         flag |= IB_premul;
2368                         
2369                 /* get the right string */
2370                 BKE_image_user_frame_calc(iuser, cfra, 0);
2371                 BKE_image_user_file_path(iuser, ima, str);
2372                 
2373                 /* read ibuf */
2374                 ibuf = IMB_loadiffname(str, flag);
2375         }
2376         
2377         if (ibuf) {
2378                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2379                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2380                         image_create_multilayer(ima, ibuf, cfra);       
2381                         ima->type = IMA_TYPE_MULTILAYER;
2382                         IMB_freeImBuf(ibuf);
2383                         ibuf = NULL;
2384                 }
2385                 else {
2386                         image_initialize_after_load(ima, ibuf);
2387                         assign = 1;
2388
2389                         /* check if the image is a font image... */
2390                         detectBitmapFont(ibuf);
2391                         
2392                         /* make packed file for autopack */
2393                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
2394                                 ima->packedfile = newPackedFile(NULL, str, ID_BLEND_PATH(G.main, &ima->id));
2395                 }
2396         }
2397         else
2398                 ima->ok = 0;
2399         
2400         if (assign)
2401                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2402
2403         if (iuser)
2404                 iuser->ok = ima->ok;
2405         
2406         return ibuf;
2407 }
2408
2409 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
2410 {
2411         ImBuf *ibuf = NULL;
2412         
2413         if (ima->rr == NULL) {
2414                 ibuf = image_load_image_file(ima, iuser, 0);
2415                 if (ibuf) { /* actually an error */
2416                         ima->type = IMA_TYPE_IMAGE;
2417                         return ibuf;
2418                 }
2419         }
2420         if (ima->rr) {
2421                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2422
2423                 if (rpass) {
2424                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2425                         
2426                         image_initialize_after_load(ima, ibuf);
2427                         
2428                         ibuf->rect_float = rpass->rect;
2429                         ibuf->flags |= IB_rectfloat;
2430                         ibuf->channels = rpass->channels;
2431                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2432
2433                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2434                 }
2435         }
2436         
2437         if (ibuf == NULL)
2438                 ima->ok = 0;
2439         if (iuser)
2440                 iuser->ok = ima->ok;
2441         
2442         return ibuf;
2443 }
2444
2445
2446 /* showing RGBA result itself (from compo/sequence) or
2447  * like exr, using layers etc */
2448 /* always returns a single ibuf, also during render progress */
2449 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
2450 {
2451         Render *re;
2452         RenderResult rres;
2453         float *rectf, *rectz;
2454         unsigned int *rect;
2455         float dither;
2456         int channels, layer, pass;
2457         ImBuf *ibuf;
2458         int from_render = (ima->render_slot == ima->last_render_slot);
2459
2460         if (!(iuser && iuser->scene))
2461                 return NULL;
2462
2463         /* if we the caller is not going to release the lock, don't give the image */
2464         if (!lock_r)
2465                 return NULL;
2466
2467         re = RE_GetRender(iuser->scene->id.name);
2468
2469         channels = 4;
2470         layer = (iuser) ? iuser->layer : 0;
2471         pass = (iuser) ? iuser->pass : 0;
2472
2473         if (from_render) {
2474                 RE_AcquireResultImage(re, &rres);
2475         }
2476         else if (ima->renders[ima->render_slot]) {
2477                 rres = *(ima->renders[ima->render_slot]);
2478                 rres.have_combined = rres.rectf != NULL;
2479         }
2480         else
2481                 memset(&rres, 0, sizeof(RenderResult));
2482         
2483         if (!(rres.rectx > 0 && rres.recty > 0)) {
2484                 if (from_render)
2485                         RE_ReleaseResultImage(re);
2486                 return NULL;
2487         }
2488
2489         /* release is done in BKE_image_release_ibuf using lock_r */
2490         if (from_render) {
2491                 BLI_lock_thread(LOCK_VIEWER);
2492                 *lock_r = re;
2493         }
2494
2495         /* this gives active layer, composite or seqence result */
2496         rect = (unsigned int *)rres.rect32;
2497         rectf = rres.rectf;
2498         rectz = rres.rectz;
2499         dither = iuser->scene->r.dither_intensity;
2500
2501         /* combined layer gets added as first layer */
2502         if (rres.have_combined && layer == 0) ;
2503         else if (rres.layers.first) {
2504                 RenderLayer *rl = BLI_findlink(&rres.layers, layer - (rres.have_combined ? 1 : 0));
2505                 if (rl) {
2506                         RenderPass *rpass;
2507
2508                         /* there's no combined pass, is in renderlayer itself */
2509                         if (pass == 0) {
2510                                 rectf = rl->rectf;
2511                         }
2512                         else {
2513                                 rpass = BLI_findlink(&rl->passes, pass - 1);
2514                                 if (rpass) {
2515                                         channels = rpass->channels;
2516                                         rectf = rpass->rect;
2517                                         dither = 0.0f; /* don't dither passes */
2518                                 }
2519                         }
2520
2521                         for (rpass = rl->passes.first; rpass; rpass = rpass->next)
2522                                 if (rpass->passtype == SCE_PASS_Z)
2523                                         rectz = rpass->rect;
2524                 }
2525         }
2526
2527         ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2528
2529         /* make ibuf if needed, and initialize it */
2530         if (ibuf == NULL) {
2531                 ibuf = IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
2532                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2533         }
2534
2535         ibuf->x = rres.rectx;
2536         ibuf->y = rres.recty;
2537         
2538         /* free rect buffer if float buffer changes, so it can be recreated with
2539          * the updated result, and also in case we got byte buffer from sequencer,
2540          * so we don't keep reference to freed buffer */
2541         if (ibuf->rect_float != rectf || rect || !rectf)
2542                 imb_freerectImBuf(ibuf);
2543
2544         if (rect)
2545                 ibuf->rect = rect;
2546         
2547         if (rectf) {
2548                 ibuf->rect_float = rectf;
2549                 ibuf->flags |= IB_rectfloat;
2550                 ibuf->channels = channels;
2551         }
2552         else {
2553                 ibuf->rect_float = NULL;
2554                 ibuf->flags &= ~IB_rectfloat;
2555         }
2556
2557         if (rectz) {
2558                 ibuf->zbuf_float = rectz;
2559                 ibuf->flags |= IB_zbuffloat;
2560         }
2561         else {
2562                 ibuf->zbuf_float = NULL;
2563                 ibuf->flags &= ~IB_zbuffloat;
2564         }
2565
2566         /* since its possible to access the buffer from the image directly, set the profile [#25073] */
2567         ibuf->profile = (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) ? IB_PROFILE_LINEAR_RGB : IB_PROFILE_NONE;
2568         ibuf->dither = dither;
2569
2570         if (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT_PREDIVIDE) {
2571                 ibuf->flags |= IB_cm_predivide;
2572                 ima->flag |= IMA_CM_PREDIVIDE;
2573         }
2574         else {
2575                 ibuf->flags &= ~IB_cm_predivide;
2576                 ima->flag &= ~IMA_CM_PREDIVIDE;
2577         }
2578
2579         ima->ok = IMA_OK_LOADED;
2580
2581         return ibuf;
2582 }
2583
2584 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2585 {
2586         ImBuf *ibuf = NULL;
2587         int frame = 0, index = 0;
2588
2589         /* see if we already have an appropriate ibuf, with image source and type */
2590         if (ima->source == IMA_SRC_MOVIE) {
2591                 frame = iuser ? iuser->framenr : ima->lastframe;
2592                 ibuf = image_get_ibuf(ima, 0, frame);
2593                 /* XXX temp stuff? */
2594                 if (ima->lastframe != frame)
2595                         ima->tpageflag |= IMA_TPAGE_REFRESH;
2596                 ima->lastframe = frame;
2597         }
2598         else if (ima->source == IMA_SRC_SEQUENCE) {
2599                 if (ima->type == IMA_TYPE_IMAGE) {
2600                         frame = iuser ? iuser->framenr : ima->lastframe;
2601                         ibuf = image_get_ibuf(ima, 0, frame);
2602                         
2603                         /* XXX temp stuff? */
2604                         if (ima->lastframe != frame) {
2605                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2606                         }
2607                         ima->lastframe = frame;
2608                 }       
2609                 else if (ima->type == IMA_TYPE_MULTILAYER) {
2610                         frame = iuser ? iuser->framenr : ima->lastframe;
2611                         index = iuser ? iuser->multi_index : IMA_NO_INDEX;
2612                         ibuf = image_get_ibuf(ima, index, frame);
2613                 }
2614         }
2615         else if (ima->source == IMA_SRC_FILE) {
2616                 if (ima->type == IMA_TYPE_IMAGE)
2617                         ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2618                 else if (ima->type == IMA_TYPE_MULTILAYER)
2619                         ibuf = image_get_ibuf(ima, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2620         }
2621         else if (ima->source == IMA_SRC_GENERATED) {
2622                 ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2623         }
2624         else if (ima->source == IMA_SRC_VIEWER) {
2625                 /* always verify entirely, not that this shouldn't happen
2626                  * as part of texture sampling in rendering anyway, so not
2627                  * a big bottleneck */
2628         }
2629
2630         *frame_r = frame;
2631         *index_r = index;
2632
2633         return ibuf;
2634 }
2635
2636 /* Checks optional ImageUser and verifies/creates ImBuf. */
2637 /* use this one if you want to get a render result in progress,
2638  * if not, use BKE_image_get_ibuf which doesn't require a release */
2639 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2640 {
2641         ImBuf *ibuf = NULL;
2642         float color[] = {0, 0, 0, 1};
2643         int frame = 0, index = 0;
2644
2645         /* This function is intended to be thread-safe. It postpones the mutex lock
2646          * until it needs to load the image, if the image is already there it
2647          * should just get the pointer and return. The reason is that a lot of mutex
2648          * locks appears to be very slow on certain multicore macs, causing a render
2649          * with image textures to actually slow down as more threads are used.
2650          *
2651          * Note that all the image loading functions should also make sure they do
2652          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2653          * That means, the last two steps must be, 1) add the ibuf to the list and
2654          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2655         
2656         if (lock_r)
2657                 *lock_r = NULL;
2658
2659         /* quick reject tests */
2660         if (ima == NULL)
2661                 return NULL;
2662         if (iuser) {
2663                 if (iuser->ok == 0)
2664                         return NULL;
2665         }
2666         else if (ima->ok == 0)
2667                 return NULL;
2668         
2669         /* try to get the ibuf without locking */
2670         ibuf = image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2671
2672         if (ibuf == NULL) {
2673                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2674                  * load the image */
2675                 BLI_lock_thread(LOCK_IMAGE);
2676
2677                 /* need to check ok flag and loading ibuf again, because the situation
2678                  * might have changed in the meantime */
2679                 if (iuser) {
2680                         if (iuser->ok == 0) {
2681                                 BLI_unlock_thread(LOCK_IMAGE);
2682                                 return NULL;
2683                         }
2684                 }
2685                 else if (ima->ok == 0) {
2686                         BLI_unlock_thread(LOCK_IMAGE);
2687                         return NULL;
2688                 }
2689
2690                 ibuf = image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2691
2692                 if (ibuf == NULL) {
2693                         /* we are sure we have to load the ibuf, using source and type */
2694                         if (ima->source == IMA_SRC_MOVIE) {
2695                                 /* source is from single file, use flipbook to store ibuf */
2696                                 ibuf = image_load_movie_file(ima, iuser, frame);
2697                         }
2698                         else if (ima->source == IMA_SRC_SEQUENCE) {
2699                                 if (ima->type == IMA_TYPE_IMAGE) {
2700                                         /* regular files, ibufs in flipbook, allows saving */
2701                                         ibuf = image_load_sequence_file(ima, iuser, frame);
2702                                 }
2703                                 /* no else; on load the ima type can change */
2704                                 if (ima->type == IMA_TYPE_MULTILAYER) {
2705                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2706                                         ibuf = image_load_sequence_multilayer(ima, iuser, frame);
2707                                 }
2708                         }
2709                         else if (ima->source == IMA_SRC_FILE) {
2710                                 
2711                                 if (ima->type == IMA_TYPE_IMAGE)
2712                                         ibuf = image_load_image_file(ima, iuser, frame);  /* cfra only for '#', this global is OK */
2713                                 /* no else; on load the ima type can change */
2714                                 if (ima->type == IMA_TYPE_MULTILAYER)
2715                                         /* keeps render result, stores ibufs in listbase, allows saving */
2716                                         ibuf = image_get_ibuf_multilayer(ima, iuser);
2717                                         
2718                         }
2719                         else if (ima->source == IMA_SRC_GENERATED) {
2720                                 /* generated is: ibuf is allocated dynamically */
2721                                 /* UV testgrid or black or solid etc */
2722                                 if (ima->gen_x == 0) ima->gen_x = 1024;
2723                                 if (ima->gen_y == 0) ima->gen_y = 1024;
2724                                 ibuf = add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, (ima->gen_flag & IMA_GEN_FLOAT) != 0, ima->gen_type, color);
2725                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2726                                 ima->ok = IMA_OK_LOADED;
2727                         }
2728                         else if (ima->source == IMA_SRC_VIEWER) {
2729                                 if (ima->type == IMA_TYPE_R_RESULT) {
2730                                         /* always verify entirely, and potentially
2731                                          * returns pointer to release later */
2732                                         ibuf = image_get_render_result(ima, iuser, lock_r);
2733                                 }
2734                                 else if (ima->type == IMA_TYPE_COMPOSITE) {
2735                                         /* requires lock/unlock, otherwise don't return image */
2736                                         if (lock_r) {
2737                                                 /* unlock in BKE_image_release_ibuf */
2738                                                 BLI_lock_thread(LOCK_VIEWER);
2739                                                 *lock_r = ima;
2740
2741                                                 /* XXX anim play for viewer nodes not yet supported */
2742                                                 frame = 0; // XXX iuser?iuser->framenr:0;
2743                                                 ibuf = image_get_ibuf(ima, 0, frame);
2744
2745                                                 if (!ibuf) {
2746                                                         /* Composite Viewer, all handled in compositor */
2747                                                         /* fake ibuf, will be filled in compositor */
2748                                                         ibuf = IMB_allocImBuf(256, 256, 32, IB_rect);
2749                                                         image_assign_ibuf(ima, ibuf, 0, frame);
2750                                                 }
2751                                         }
2752                                 }
2753                         }
2754                 }
2755
2756                 BLI_unlock_thread(LOCK_IMAGE);
2757         }
2758
2759         BKE_image_tag_time(ima);
2760
2761         return ibuf;
2762 }
2763
2764 void BKE_image_release_ibuf(Image *ima, void *lock)
2765 {
2766         /* for getting image during threaded render / compositing, need to release */
2767         if (lock == ima) {
2768                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2769         }
2770         else if (lock) {
2771                 RE_ReleaseResultImage(lock); /* render result */
2772                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2773         }
2774 }
2775
2776 /* warning, this can allocate generated images */
2777 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2778 {
2779         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2780         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2781 }
2782
2783 int BKE_image_user_frame_get(const ImageUser *iuser, int cfra, int fieldnr)
2784 {
2785         const int len = (iuser->fie_ima * iuser->frames) / 2;
2786
2787         if (len == 0) {
2788                 return 0;
2789         }
2790         else {
2791                 int framenr;
2792                 cfra = cfra - iuser->sfra + 1;
2793
2794                 /* cyclic */
2795                 if (iuser->cycl) {
2796                         cfra = ((cfra) % len);
2797                         if (cfra < 0) cfra += len;
2798                         if (cfra == 0) cfra = len;
2799                 }
2800
2801                 if (cfra < 0) cfra = 0;
2802                 else if (cfra > len) cfra = len;
2803
2804                 /* convert current frame to current field */
2805                 cfra = 2 * (cfra);
2806                 if (fieldnr) cfra++;
2807
2808                 /* transform to images space */
2809                 framenr = (cfra + iuser->fie_ima - 2) / iuser->fie_ima;
2810                 if (framenr > iuser->frames) framenr = iuser->frames;
2811                 framenr += iuser->offset;
2812
2813                 if (iuser->cycl) {
2814                         framenr = ((framenr) % len);
2815                         while (framenr < 0) framenr += len;
2816                         if (framenr == 0) framenr = len;
2817                 }
2818
2819                 return framenr;
2820         }
2821 }
2822
2823 void BKE_image_user_frame_calc(ImageUser *iuser, int cfra, int fieldnr)
2824 {
2825         if (iuser) {
2826                 const int framenr = BKE_image_user_frame_get(iuser, cfra, fieldnr);
2827                 
2828                 /* allows image users to handle redraws */
2829                 if (iuser->flag & IMA_ANIM_ALWAYS)
2830                         if (framenr != iuser->framenr)
2831                                 iuser->flag |= IMA_ANIM_REFRESHED;
2832                 
2833                 iuser->framenr = framenr;
2834                 if (iuser->ok == 0) iuser->ok = 1;
2835         }
2836 }
2837
2838 void BKE_image_user_check_frame_calc(ImageUser *iuser, int cfra, int fieldnr)
2839 {
2840         if ((iuser->flag & IMA_ANIM_ALWAYS) || (iuser->flag & IMA_NEED_FRAME_RECALC)) {
2841                 BKE_image_user_frame_calc(iuser, cfra, fieldnr);
2842
2843                 iuser->flag &= ~IMA_NEED_FRAME_RECALC;
2844         }
2845 }
2846
2847 void BKE_image_user_file_path(ImageUser *iuser, Image *ima, char *filepath)
2848 {
2849         BLI_strncpy(filepath, ima->name, FILE_MAX);
2850
2851         if (ima->source == IMA_SRC_SEQUENCE) {
2852                 char head[FILE_MAX], tail[FILE_MAX];
2853                 unsigned short numlen;
2854                 int frame = iuser->framenr;
2855
2856                 BLI_stringdec(filepath, head, tail, &numlen);
2857                 BLI_stringenc(filepath, head, tail, numlen, frame);
2858         }
2859
2860         BLI_path_abs(filepath, ID_BLEND_PATH(G.main, &ima->id));
2861 }
2862
2863 int BKE_image_has_alpha(struct Image *image)
2864 {
2865         ImBuf *ibuf;
2866         void *lock;
2867         int planes;
2868         
2869         ibuf = BKE_image_acquire_ibuf(image, NULL, &lock);
2870         planes = (ibuf ? ibuf->planes : 0);
2871         BKE_image_release_ibuf(image, lock);
2872
2873         if (planes == 32)
2874                 return 1;
2875         else
2876                 return 0;
2877 }