fbcd943e13f1ed139efb40c229cb5f32e808747c
[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 int 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         if (ibuf) {
525                 IMB_scaleImBuf(ibuf, width, height);
526                 ibuf->userflags |= IB_BITMAPDIRTY;
527         }
528
529         BKE_image_release_ibuf(image, lock);
530
531         return (ibuf != NULL);
532 }
533
534 Image *BKE_image_load(const char *filepath)
535 {
536         Image *ima;
537         int file, len;
538         const char *libname;
539         char str[FILE_MAX];
540
541         BLI_strncpy(str, filepath, sizeof(str));
542         BLI_path_abs(str, G.main->name);
543
544         /* exists? */
545         file = BLI_open(str, O_BINARY | O_RDONLY, 0);
546         if (file == -1) return NULL;
547         close(file);
548
549         /* create a short library name */
550         len = strlen(filepath);
551
552         while (len > 0 && filepath[len - 1] != '/' && filepath[len - 1] != '\\') len--;
553         libname = filepath + len;
554
555         ima = image_alloc(libname, IMA_SRC_FILE, IMA_TYPE_IMAGE);
556         BLI_strncpy(ima->name, filepath, sizeof(ima->name));
557
558         if (BLI_testextensie_array(filepath, imb_ext_movie))
559                 ima->source = IMA_SRC_MOVIE;
560
561         return ima;
562 }
563
564 /* checks if image was already loaded, then returns same image */
565 /* otherwise creates new. */
566 /* does not load ibuf itself */
567 /* pass on optional frame for #name images */
568 Image *BKE_image_load_exists(const char *filepath)
569 {
570         Image *ima;
571         char str[FILE_MAX], strtest[FILE_MAX];
572
573         BLI_strncpy(str, filepath, sizeof(str));
574         BLI_path_abs(str, G.main->name);
575
576         /* first search an identical image */
577         for (ima = G.main->image.first; ima; ima = ima->id.next) {
578                 if (ima->source != IMA_SRC_VIEWER && ima->source != IMA_SRC_GENERATED) {
579                         BLI_strncpy(strtest, ima->name, sizeof(ima->name));
580                         BLI_path_abs(strtest, G.main->name);
581
582                         if (BLI_path_cmp(strtest, str) == 0) {
583                                 if (ima->anim == NULL || ima->id.us == 0) {
584                                         BLI_strncpy(ima->name, filepath, sizeof(ima->name));    /* for stringcode */
585                                         ima->id.us++;                                       /* officially should not, it doesn't link here! */
586                                         if (ima->ok == 0)
587                                                 ima->ok = IMA_OK;
588                                         /* RETURN! */
589                                         return ima;
590                                 }
591                         }
592                 }
593         }
594
595         return BKE_image_load(filepath);
596 }
597
598 static ImBuf *add_ibuf_size(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short uvtestgrid, float color[4])
599 {
600         ImBuf *ibuf;
601         unsigned char *rect = NULL;
602         float *rect_float = NULL;
603
604         if (floatbuf) {
605                 ibuf = IMB_allocImBuf(width, height, depth, IB_rectfloat);
606                 rect_float = ibuf->rect_float;
607                 ibuf->profile = IB_PROFILE_LINEAR_RGB;
608         }
609         else {
610                 ibuf = IMB_allocImBuf(width, height, depth, IB_rect);
611                 rect = (unsigned char *)ibuf->rect;
612                 ibuf->profile = IB_PROFILE_SRGB;
613         }
614
615         BLI_strncpy(ibuf->name, name, sizeof(ibuf->name));
616         ibuf->userflags |= IB_BITMAPDIRTY;
617
618         switch (uvtestgrid) {
619                 case 1:
620                         BKE_image_buf_fill_checker(rect, rect_float, width, height);
621                         break;
622                 case 2:
623                         BKE_image_buf_fill_checker_color(rect, rect_float, width, height);
624                         break;
625                 default:
626                         BKE_image_buf_fill_color(rect, rect_float, width, height, color);
627         }
628
629         return ibuf;
630 }
631
632 /* adds new image block, creates ImBuf and initializes color */
633 Image *BKE_image_add_generated(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short uvtestgrid, float color[4])
634 {
635         /* on save, type is changed to FILE in editsima.c */
636         Image *ima = image_alloc(name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
637
638         if (ima) {
639                 ImBuf *ibuf;
640
641                 /* BLI_strncpy(ima->name, name, FILE_MAX); */ /* don't do this, this writes in ain invalid filepath! */
642                 ima->gen_x = width;
643                 ima->gen_y = height;
644                 ima->gen_type = uvtestgrid;
645                 ima->gen_flag |= (floatbuf ? IMA_GEN_FLOAT : 0);
646
647                 ibuf = add_ibuf_size(width, height, ima->name, depth, floatbuf, uvtestgrid, color);
648                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
649
650                 ima->ok = IMA_OK_LOADED;
651         }
652
653         return ima;
654 }
655
656 /* creates an image image owns the imbuf passed */
657 Image *BKE_image_add_from_imbuf(ImBuf *ibuf)
658 {
659         /* on save, type is changed to FILE in editsima.c */
660         Image *ima;
661
662         ima = image_alloc(BLI_path_basename(ibuf->name), IMA_SRC_FILE, IMA_TYPE_IMAGE);
663
664         if (ima) {
665                 BLI_strncpy(ima->name, ibuf->name, FILE_MAX);
666                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
667                 ima->ok = IMA_OK_LOADED;
668         }
669
670         return ima;
671 }
672
673 /* packs rect from memory as PNG */
674 void BKE_image_memorypack(Image *ima)
675 {
676         ImBuf *ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
677
678         if (ibuf == NULL)
679                 return;
680         if (ima->packedfile) {
681                 freePackedFile(ima->packedfile);
682                 ima->packedfile = NULL;
683         }
684
685         ibuf->ftype = PNG;
686         ibuf->planes = R_IMF_PLANES_RGBA;
687
688         IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem);
689         if (ibuf->encodedbuffer == NULL) {
690                 printf("memory save for pack error\n");
691         }
692         else {
693                 PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
694
695                 pf->data = ibuf->encodedbuffer;
696                 pf->size = ibuf->encodedsize;
697                 ima->packedfile = pf;
698                 ibuf->encodedbuffer = NULL;
699                 ibuf->encodedsize = 0;
700                 ibuf->userflags &= ~IB_BITMAPDIRTY;
701
702                 if (ima->source == IMA_SRC_GENERATED) {
703                         ima->source = IMA_SRC_FILE;
704                         ima->type = IMA_TYPE_IMAGE;
705                 }
706         }
707 }
708
709 void BKE_image_tag_time(Image *ima)
710 {
711         if (ima)
712                 ima->lastused = (int)PIL_check_seconds_timer();
713 }
714
715 #if 0
716 static void tag_all_images_time()
717 {
718         Image *ima;
719         int ctime = (int)PIL_check_seconds_timer();
720
721         ima = G.main->image.first;
722         while (ima) {
723                 if (ima->bindcode || ima->repbind || ima->ibufs.first) {
724                         ima->lastused = ctime;
725                 }
726         }
727 }
728 #endif
729
730 void free_old_images(void)
731 {
732         Image *ima;
733         static int lasttime = 0;
734         int ctime = (int)PIL_check_seconds_timer();
735
736         /*
737          * Run garbage collector once for every collecting period of time
738          * if textimeout is 0, that's the option to NOT run the collector
739          */
740         if (U.textimeout == 0 || ctime % U.texcollectrate || ctime == lasttime)
741                 return;
742
743         /* of course not! */
744         if (G.is_rendering)
745                 return;
746
747         lasttime = ctime;
748
749         ima = G.main->image.first;
750         while (ima) {
751                 if ((ima->flag & IMA_NOCOLLECT) == 0 && ctime - ima->lastused > U.textimeout) {
752                         /* If it's in GL memory, deallocate and set time tag to current time
753                          * This gives textures a "second chance" to be used before dying. */
754                         if (ima->bindcode || ima->repbind) {
755                                 GPU_free_image(ima);
756                                 ima->lastused = ctime;
757                         }
758                         /* Otherwise, just kill the buffers */
759                         else if (ima->ibufs.first) {
760                                 image_free_buffers(ima);
761                         }
762                 }
763                 ima = ima->id.next;
764         }
765 }
766
767 static uintptr_t image_mem_size(Image *ima)
768 {
769         ImBuf *ibuf, *ibufm;
770         int level;
771         uintptr_t size = 0;
772
773         size = 0;
774
775         /* viewers have memory depending on other rules, has no valid rect pointer */
776         if (ima->source == IMA_SRC_VIEWER)
777                 return 0;
778
779         for (ibuf = ima->ibufs.first; ibuf; ibuf = ibuf->next) {
780                 if (ibuf->rect) size += MEM_allocN_len(ibuf->rect);
781                 else if (ibuf->rect_float) size += MEM_allocN_len(ibuf->rect_float);
782
783                 for (level = 0; level < IB_MIPMAP_LEVELS; level++) {
784                         ibufm = ibuf->mipmap[level];
785                         if (ibufm) {
786                                 if (ibufm->rect) size += MEM_allocN_len(ibufm->rect);
787                                 else if (ibufm->rect_float) size += MEM_allocN_len(ibufm->rect_float);
788                         }
789                 }
790         }
791
792         return size;
793 }
794
795 void BKE_image_print_memlist(void)
796 {
797         Image *ima;
798         uintptr_t size, totsize = 0;
799
800         for (ima = G.main->image.first; ima; ima = ima->id.next)
801                 totsize += image_mem_size(ima);
802
803         printf("\ntotal image memory len: %.3f MB\n", (double)totsize / (double)(1024 * 1024));
804
805         for (ima = G.main->image.first; ima; ima = ima->id.next) {
806                 size = image_mem_size(ima);
807
808                 if (size)
809                         printf("%s len: %.3f MB\n", ima->id.name + 2, (double)size / (double)(1024 * 1024));
810         }
811 }
812
813 void BKE_image_free_all_textures(void)
814 {
815         Tex *tex;
816         Image *ima;
817         /* unsigned int totsize = 0; */
818
819         for (ima = G.main->image.first; ima; ima = ima->id.next)
820                 ima->id.flag &= ~LIB_DOIT;
821
822         for (tex = G.main->tex.first; tex; tex = tex->id.next)
823                 if (tex->ima)
824                         tex->ima->id.flag |= LIB_DOIT;
825
826         for (ima = G.main->image.first; ima; ima = ima->id.next) {
827                 if (ima->ibufs.first && (ima->id.flag & LIB_DOIT)) {
828                         ImBuf *ibuf;
829
830                         for (ibuf = ima->ibufs.first; ibuf; ibuf = ibuf->next) {
831                                 /* escape when image is painted on */
832                                 if (ibuf->userflags & IB_BITMAPDIRTY)
833                                         break;
834
835 #if 0
836                                 if (ibuf->mipmap[0])
837                                         totsize += 1.33 * ibuf->x * ibuf->y * 4;
838                                 else
839                                         totsize += ibuf->x * ibuf->y * 4;
840 #endif
841                         }
842                         if (ibuf == NULL)
843                                 image_free_buffers(ima);
844                 }
845         }
846         /* printf("freed total %d MB\n", totsize/(1024*1024)); */
847 }
848
849 /* except_frame is weak, only works for seqs without offset... */
850 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
851 {
852         ImBuf *ibuf, *nbuf;
853
854         for (ibuf = ima->ibufs.first; ibuf; ibuf = nbuf) {
855                 nbuf = ibuf->next;
856                 if (ibuf->userflags & IB_BITMAPDIRTY)
857                         continue;
858                 if (ibuf->index == IMA_NO_INDEX)
859                         continue;
860                 if (except_frame != IMA_INDEX_FRAME(ibuf->index)) {
861                         BLI_remlink(&ima->ibufs, ibuf);
862
863                         if (ibuf->userdata) {
864                                 MEM_freeN(ibuf->userdata);
865                                 ibuf->userdata = NULL;
866                         }
867                         IMB_freeImBuf(ibuf);
868                 }
869         }
870 }
871
872 void BKE_image_all_free_anim_ibufs(int cfra)
873 {
874         Image *ima;
875
876         for (ima = G.main->image.first; ima; ima = ima->id.next)
877                 if (ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE))
878                         BKE_image_free_anim_ibufs(ima, cfra);
879 }
880
881
882 /* *********** READ AND WRITE ************** */
883
884 int BKE_imtype_to_ftype(const char imtype)
885 {
886         if (imtype == R_IMF_IMTYPE_TARGA)
887                 return TGA;
888         else if (imtype == R_IMF_IMTYPE_RAWTGA)
889                 return RAWTGA;
890         else if (imtype == R_IMF_IMTYPE_IRIS)
891                 return IMAGIC;
892 #ifdef WITH_HDR
893         else if (imtype == R_IMF_IMTYPE_RADHDR)
894                 return RADHDR;
895 #endif
896         else if (imtype == R_IMF_IMTYPE_PNG)
897                 return PNG;
898 #ifdef WITH_DDS
899         else if (imtype == R_IMF_IMTYPE_DDS)
900                 return DDS;
901 #endif
902         else if (imtype == R_IMF_IMTYPE_BMP)
903                 return BMP;
904 #ifdef WITH_TIFF
905         else if (imtype == R_IMF_IMTYPE_TIFF)
906                 return TIF;
907 #endif
908         else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER)
909                 return OPENEXR;
910 #ifdef WITH_CINEON
911         else if (imtype == R_IMF_IMTYPE_CINEON)
912                 return CINEON;
913         else if (imtype == R_IMF_IMTYPE_DPX)
914                 return DPX;
915 #endif
916 #ifdef WITH_OPENJPEG
917         else if (imtype == R_IMF_IMTYPE_JP2)
918                 return JP2;
919 #endif
920         else
921                 return JPG | 90;
922 }
923
924 char BKE_ftype_to_imtype(const int ftype)
925 {
926         if (ftype == 0)
927                 return R_IMF_IMTYPE_TARGA;
928         else if (ftype == IMAGIC)
929                 return R_IMF_IMTYPE_IRIS;
930 #ifdef WITH_HDR
931         else if (ftype & RADHDR)
932                 return R_IMF_IMTYPE_RADHDR;
933 #endif
934         else if (ftype & PNG)
935                 return R_IMF_IMTYPE_PNG;
936 #ifdef WITH_DDS
937         else if (ftype & DDS)
938                 return R_IMF_IMTYPE_DDS;
939 #endif
940         else if (ftype & BMP)
941                 return R_IMF_IMTYPE_BMP;
942 #ifdef WITH_TIFF
943         else if (ftype & TIF)
944                 return R_IMF_IMTYPE_TIFF;
945 #endif
946         else if (ftype & OPENEXR)
947                 return R_IMF_IMTYPE_OPENEXR;
948 #ifdef WITH_CINEON
949         else if (ftype & CINEON)
950                 return R_IMF_IMTYPE_CINEON;
951         else if (ftype & DPX)
952                 return R_IMF_IMTYPE_DPX;
953 #endif
954         else if (ftype & TGA)
955                 return R_IMF_IMTYPE_TARGA;
956         else if (ftype & RAWTGA)
957                 return R_IMF_IMTYPE_RAWTGA;
958 #ifdef WITH_OPENJPEG
959         else if (ftype & JP2)
960                 return R_IMF_IMTYPE_JP2;
961 #endif
962         else
963                 return R_IMF_IMTYPE_JPEG90;
964 }
965
966
967 int BKE_imtype_is_movie(const char imtype)
968 {
969         switch (imtype) {
970                 case R_IMF_IMTYPE_AVIRAW:
971                 case R_IMF_IMTYPE_AVIJPEG:
972                 case R_IMF_IMTYPE_QUICKTIME:
973                 case R_IMF_IMTYPE_FFMPEG:
974                 case R_IMF_IMTYPE_H264:
975                 case R_IMF_IMTYPE_THEORA:
976                 case R_IMF_IMTYPE_XVID:
977                 case R_IMF_IMTYPE_FRAMESERVER:
978                         return 1;
979         }
980         return 0;
981 }
982
983 int BKE_imtype_supports_zbuf(const char imtype)
984 {
985         switch (imtype) {
986                 case R_IMF_IMTYPE_IRIZ:
987                 case R_IMF_IMTYPE_OPENEXR: /* but not R_IMF_IMTYPE_MULTILAYER */
988                         return 1;
989         }
990         return 0;
991 }
992
993 int BKE_imtype_supports_compress(const char imtype)
994 {
995         switch (imtype) {
996                 case R_IMF_IMTYPE_PNG:
997                         return 1;
998         }
999         return 0;
1000 }
1001
1002 int BKE_imtype_supports_quality(const char imtype)
1003 {
1004         switch (imtype) {
1005                 case R_IMF_IMTYPE_JPEG90:
1006                 case R_IMF_IMTYPE_JP2:
1007                 case R_IMF_IMTYPE_AVIJPEG:
1008                         return 1;
1009         }
1010         return 0;
1011 }
1012
1013 char BKE_imtype_valid_channels(const char imtype)
1014 {
1015         char chan_flag = IMA_CHAN_FLAG_RGB; /* assume all support rgb */
1016
1017         /* alpha */
1018         switch (imtype) {
1019                 case R_IMF_IMTYPE_TARGA:
1020                 case R_IMF_IMTYPE_IRIS:
1021                 case R_IMF_IMTYPE_PNG:
1022                 /* case R_IMF_IMTYPE_BMP: */ /* read but not write */
1023                 case R_IMF_IMTYPE_RADHDR:
1024                 case R_IMF_IMTYPE_TIFF:
1025                 case R_IMF_IMTYPE_OPENEXR:
1026                 case R_IMF_IMTYPE_MULTILAYER:
1027                 case R_IMF_IMTYPE_DDS:
1028                 case R_IMF_IMTYPE_JP2:
1029                 case R_IMF_IMTYPE_QUICKTIME:
1030                         chan_flag |= IMA_CHAN_FLAG_ALPHA;
1031         }
1032
1033         /* bw */
1034         switch (imtype) {
1035                 case R_IMF_IMTYPE_PNG:
1036                 case R_IMF_IMTYPE_JPEG90:
1037                 case R_IMF_IMTYPE_TARGA:
1038                 case R_IMF_IMTYPE_RAWTGA:
1039                 case R_IMF_IMTYPE_TIFF:
1040                 case R_IMF_IMTYPE_IRIS:
1041                         chan_flag |= IMA_CHAN_FLAG_BW;
1042         }
1043
1044         return chan_flag;
1045 }
1046
1047 char BKE_imtype_valid_depths(const char imtype)
1048 {
1049         switch (imtype) {
1050                 case R_IMF_IMTYPE_RADHDR:
1051                         return R_IMF_CHAN_DEPTH_32;
1052                 case R_IMF_IMTYPE_TIFF:
1053                         return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_16;
1054                 case R_IMF_IMTYPE_OPENEXR:
1055                         return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32;
1056                 case R_IMF_IMTYPE_MULTILAYER:
1057                         return R_IMF_CHAN_DEPTH_32;
1058                 /* eeh, cineone does some strange 10bits per channel */
1059                 case R_IMF_IMTYPE_DPX:
1060                 case R_IMF_IMTYPE_CINEON:
1061                         return R_IMF_CHAN_DEPTH_12;
1062                 case R_IMF_IMTYPE_JP2:
1063                         return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
1064                 /* most formats are 8bit only */
1065                 default:
1066                         return R_IMF_CHAN_DEPTH_8;
1067         }
1068 }
1069
1070
1071 /* string is from command line --render-format arg, keep in sync with
1072  * creator.c help info */
1073 char BKE_imtype_from_arg(const char *imtype_arg)
1074 {
1075         if      (!strcmp(imtype_arg, "TGA")) return R_IMF_IMTYPE_TARGA;
1076         else if (!strcmp(imtype_arg, "IRIS")) return R_IMF_IMTYPE_IRIS;
1077 #ifdef WITH_DDS
1078         else if (!strcmp(imtype_arg, "DDS")) return R_IMF_IMTYPE_DDS;
1079 #endif
1080         else if (!strcmp(imtype_arg, "JPEG")) return R_IMF_IMTYPE_JPEG90;
1081         else if (!strcmp(imtype_arg, "IRIZ")) return R_IMF_IMTYPE_IRIZ;
1082         else if (!strcmp(imtype_arg, "RAWTGA")) return R_IMF_IMTYPE_RAWTGA;
1083         else if (!strcmp(imtype_arg, "AVIRAW")) return R_IMF_IMTYPE_AVIRAW;
1084         else if (!strcmp(imtype_arg, "AVIJPEG")) return R_IMF_IMTYPE_AVIJPEG;
1085         else if (!strcmp(imtype_arg, "PNG")) return R_IMF_IMTYPE_PNG;
1086         else if (!strcmp(imtype_arg, "QUICKTIME")) return R_IMF_IMTYPE_QUICKTIME;
1087         else if (!strcmp(imtype_arg, "BMP")) return R_IMF_IMTYPE_BMP;
1088 #ifdef WITH_HDR
1089         else if (!strcmp(imtype_arg, "HDR")) return R_IMF_IMTYPE_RADHDR;
1090 #endif
1091 #ifdef WITH_TIFF
1092         else if (!strcmp(imtype_arg, "TIFF")) return R_IMF_IMTYPE_TIFF;
1093 #endif
1094 #ifdef WITH_OPENEXR
1095         else if (!strcmp(imtype_arg, "EXR")) return R_IMF_IMTYPE_OPENEXR;
1096         else if (!strcmp(imtype_arg, "MULTILAYER")) return R_IMF_IMTYPE_MULTILAYER;
1097 #endif
1098         else if (!strcmp(imtype_arg, "MPEG")) return R_IMF_IMTYPE_FFMPEG;
1099         else if (!strcmp(imtype_arg, "FRAMESERVER")) return R_IMF_IMTYPE_FRAMESERVER;
1100 #ifdef WITH_CINEON
1101         else if (!strcmp(imtype_arg, "CINEON")) return R_IMF_IMTYPE_CINEON;
1102         else if (!strcmp(imtype_arg, "DPX")) return R_IMF_IMTYPE_DPX;
1103 #endif
1104 #ifdef WITH_OPENJPEG
1105         else if (!strcmp(imtype_arg, "JP2")) return R_IMF_IMTYPE_JP2;
1106 #endif
1107         else return R_IMF_IMTYPE_INVALID;
1108 }
1109
1110 int BKE_add_image_extension(char *string, const char imtype)
1111 {
1112         const char *extension = NULL;
1113
1114         if (imtype == R_IMF_IMTYPE_IRIS) {
1115                 if (!BLI_testextensie(string, ".rgb"))
1116                         extension = ".rgb";
1117         }
1118         else if (imtype == R_IMF_IMTYPE_IRIZ) {
1119                 if (!BLI_testextensie(string, ".rgb"))
1120                         extension = ".rgb";
1121         }
1122 #ifdef WITH_HDR
1123         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1124                 if (!BLI_testextensie(string, ".hdr"))
1125                         extension = ".hdr";
1126         }
1127 #endif
1128         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1129                 if (!BLI_testextensie(string, ".png"))
1130                         extension = ".png";
1131         }
1132 #ifdef WITH_DDS
1133         else if (imtype == R_IMF_IMTYPE_DDS) {
1134                 if (!BLI_testextensie(string, ".dds"))
1135                         extension = ".dds";
1136         }
1137 #endif
1138         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
1139                 if (!BLI_testextensie(string, ".tga"))
1140                         extension = ".tga";
1141         }
1142         else if (imtype == R_IMF_IMTYPE_BMP) {
1143                 if (!BLI_testextensie(string, ".bmp"))
1144                         extension = ".bmp";
1145         }
1146 #ifdef WITH_TIFF
1147         else if (imtype == R_IMF_IMTYPE_TIFF) {
1148                 if (!BLI_testextensie(string, ".tif") &&
1149                     !BLI_testextensie(string, ".tiff"))
1150                 {
1151                         extension = ".tif";
1152                 }
1153         }
1154 #endif
1155 #ifdef WITH_OPENEXR
1156         else if (ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
1157                 if (!BLI_testextensie(string, ".exr"))
1158                         extension = ".exr";
1159         }
1160 #endif
1161 #ifdef WITH_CINEON
1162         else if (imtype == R_IMF_IMTYPE_CINEON) {
1163                 if (!BLI_testextensie(string, ".cin"))
1164                         extension = ".cin";
1165         }
1166         else if (imtype == R_IMF_IMTYPE_DPX) {
1167                 if (!BLI_testextensie(string, ".dpx"))
1168                         extension = ".dpx";
1169         }
1170 #endif
1171         else if (imtype == R_IMF_IMTYPE_TARGA) {
1172                 if (!BLI_testextensie(string, ".tga"))
1173                         extension = ".tga";
1174         }
1175 #ifdef WITH_OPENJPEG
1176         else if (imtype == R_IMF_IMTYPE_JP2) {
1177                 if (!BLI_testextensie(string, ".jp2"))
1178                         extension = ".jp2";
1179         }
1180 #endif
1181         else { //   R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90, R_IMF_IMTYPE_QUICKTIME etc
1182                 if (!(BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
1183                         extension = ".jpg";
1184         }
1185
1186         if (extension) {
1187                 /* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */
1188                 /* remove any other known image extension */
1189                 if (BLI_testextensie_array(string, imb_ext_image) ||
1190                     (G.have_quicktime && BLI_testextensie_array(string, imb_ext_image_qt)))
1191                 {
1192                         return BLI_replace_extension(string, FILE_MAX, extension);
1193                 }
1194                 else {
1195                         return BLI_ensure_extension(string, FILE_MAX, extension);
1196                 }
1197
1198         }
1199         else {
1200                 return FALSE;
1201         }
1202 }
1203
1204 void BKE_imformat_defaults(ImageFormatData *im_format)
1205 {
1206         memset(im_format, 0, sizeof(*im_format));
1207         im_format->planes = R_IMF_PLANES_RGB;
1208         im_format->imtype = R_IMF_IMTYPE_PNG;
1209         im_format->quality = 90;
1210         im_format->compress = 90;
1211 }
1212
1213 void BKE_imbuf_to_image_format(struct ImageFormatData *im_format, const ImBuf *imbuf)
1214 {
1215         BKE_imformat_defaults(im_format);
1216
1217         /* file type */
1218
1219         if (imbuf->ftype == IMAGIC)
1220                 im_format->imtype = R_IMF_IMTYPE_IRIS;
1221
1222 #ifdef WITH_HDR
1223         else if (imbuf->ftype == RADHDR)
1224                 im_format->imtype = R_IMF_IMTYPE_RADHDR;
1225 #endif
1226
1227         else if (imbuf->ftype == PNG)
1228                 im_format->imtype = R_IMF_IMTYPE_PNG;
1229
1230 #ifdef WITH_DDS
1231         else if (imbuf->ftype == DDS)
1232                 im_format->imtype = R_IMF_IMTYPE_DDS;
1233 #endif
1234
1235         else if (imbuf->ftype == BMP)
1236                 im_format->imtype = R_IMF_IMTYPE_BMP;
1237
1238 #ifdef WITH_TIFF
1239         else if (imbuf->ftype & TIF) {
1240                 im_format->imtype = R_IMF_IMTYPE_TIFF;
1241                 if (imbuf->ftype & TIF_16BIT)
1242                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1243         }
1244 #endif
1245
1246 #ifdef WITH_OPENEXR
1247         else if (imbuf->ftype & OPENEXR) {
1248                 im_format->imtype = R_IMF_IMTYPE_OPENEXR;
1249                 if (imbuf->ftype & OPENEXR_HALF)
1250                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1251                 if (imbuf->ftype & OPENEXR_COMPRESS)
1252                         im_format->exr_codec = R_IMF_EXR_CODEC_ZIP;  // Can't determine compression
1253                 if (imbuf->zbuf_float)
1254                         im_format->flag |= R_IMF_FLAG_ZBUF;
1255         }
1256 #endif
1257
1258 #ifdef WITH_CINEON
1259         else if (imbuf->ftype == CINEON)
1260                 im_format->imtype = R_IMF_IMTYPE_CINEON;
1261         else if (imbuf->ftype == DPX)
1262                 im_format->imtype = R_IMF_IMTYPE_DPX;
1263 #endif
1264
1265         else if (imbuf->ftype == TGA) {
1266                 im_format->imtype = R_IMF_IMTYPE_TARGA;
1267         }
1268         else if (imbuf->ftype == RAWTGA) {
1269                 im_format->imtype = R_IMF_IMTYPE_RAWTGA;
1270         }
1271
1272 #ifdef WITH_OPENJPEG
1273         else if (imbuf->ftype & JP2) {
1274                 im_format->imtype = R_IMF_IMTYPE_JP2;
1275                 im_format->quality = imbuf->ftype & ~JPG_MSK;
1276
1277                 if (imbuf->ftype & JP2_16BIT)
1278                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1279                 else if (imbuf->ftype & JP2_12BIT)
1280                         im_format->depth = R_IMF_CHAN_DEPTH_12;
1281
1282                 if (imbuf->ftype & JP2_YCC)
1283                         im_format->jp2_flag |= R_IMF_JP2_FLAG_YCC;
1284
1285                 if (imbuf->ftype & JP2_CINE) {
1286                         im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_PRESET;
1287                         if (imbuf->ftype & JP2_CINE_48FPS)
1288                                 im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_48;
1289                 }
1290         }
1291 #endif
1292
1293         else {
1294                 im_format->imtype = R_IMF_IMTYPE_JPEG90;
1295                 im_format->quality = imbuf->ftype & ~JPG_MSK;
1296         }
1297
1298         /* planes */
1299         switch (imbuf->channels) {
1300                 case 0:
1301                 case 4: im_format->planes = R_IMF_PLANES_RGBA;
1302                         break;
1303                 case 3: im_format->planes = R_IMF_PLANES_RGB;
1304                         break;
1305                 case 1: im_format->planes = R_IMF_PLANES_BW;
1306                         break;
1307                 default: im_format->planes = R_IMF_PLANES_RGB;
1308                         break;
1309         }
1310
1311 }
1312
1313 static void timecode_simple_string(char *text, size_t text_size, const int cfra, int const frs_sec)
1314 {
1315         int f = (int)(cfra % frs_sec);
1316         int s = (int)(cfra / frs_sec);
1317         int h = 0;
1318         int m = 0;
1319
1320         if (s) {
1321                 m = (int)(s / 60);
1322                 s %= 60;
1323
1324                 if (m) {
1325                         h = (int)(m / 60);
1326                         m %= 60;
1327                 }
1328         }
1329
1330         if (frs_sec < 100) {
1331                 BLI_snprintf(text, text_size, "%02d:%02d:%02d.%02d", h, m, s, f);
1332         }
1333         else {
1334                 BLI_snprintf(text, text_size, "%02d:%02d:%02d.%03d", h, m, s, f);
1335         }
1336 }
1337
1338 /* could allow access externally - 512 is for long names, 64 is for id names */
1339 typedef struct StampData {
1340         char file[512];
1341         char note[512];
1342         char date[512];
1343         char marker[512];
1344         char time[512];
1345         char frame[512];
1346         char camera[64];
1347         char cameralens[64];
1348         char scene[64];
1349         char strip[64];
1350         char rendertime[64];
1351 } StampData;
1352
1353 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix)
1354 {
1355         char text[256];
1356         struct tm *tl;
1357         time_t t;
1358
1359         if (scene->r.stamp & R_STAMP_FILENAME) {
1360                 BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), do_prefix ? "File %s" : "%s", G.relbase_valid ? G.main->name : "<untitled>");
1361         }
1362         else {
1363                 stamp_data->file[0] = '\0';
1364         }
1365
1366         if (scene->r.stamp & R_STAMP_NOTE) {
1367                 /* Never do prefix for Note */
1368                 BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", scene->r.stamp_udata);
1369         }
1370         else {
1371                 stamp_data->note[0] = '\0';
1372         }
1373
1374         if (scene->r.stamp & R_STAMP_DATE) {
1375                 t = time(NULL);
1376                 tl = localtime(&t);
1377                 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);
1378                 BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), do_prefix ? "Date %s" : "%s", text);
1379         }
1380         else {
1381                 stamp_data->date[0] = '\0';
1382         }
1383
1384         if (scene->r.stamp & R_STAMP_MARKER) {
1385                 char *name = BKE_scene_find_last_marker_name(scene, CFRA);
1386
1387                 if (name) BLI_strncpy(text, name, sizeof(text));
1388                 else BLI_strncpy(text, "<none>", sizeof(text));
1389
1390                 BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), do_prefix ? "Marker %s" : "%s", text);
1391         }
1392         else {
1393                 stamp_data->marker[0] = '\0';
1394         }
1395
1396         if (scene->r.stamp & R_STAMP_TIME) {
1397                 timecode_simple_string(text, sizeof(text), scene->r.cfra, scene->r.frs_sec);
1398                 BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), do_prefix ? "Time %s" : "%s", text);
1399         }
1400         else {
1401                 stamp_data->time[0] = '\0';
1402         }
1403
1404         if (scene->r.stamp & R_STAMP_FRAME) {
1405                 char fmtstr[32];
1406                 int digits = 1;
1407
1408                 if (scene->r.efra > 9)
1409                         digits = 1 + (int) log10(scene->r.efra);
1410
1411                 BLI_snprintf(fmtstr, sizeof(fmtstr), do_prefix ? "Frame %%0%di" : "%%0%di", digits);
1412                 BLI_snprintf(stamp_data->frame, sizeof(stamp_data->frame), fmtstr, scene->r.cfra);
1413         }
1414         else {
1415                 stamp_data->frame[0] = '\0';
1416         }
1417
1418         if (scene->r.stamp & R_STAMP_CAMERA) {
1419                 BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), do_prefix ? "Camera %s" : "%s", camera ? camera->id.name + 2 : "<none>");
1420         }
1421         else {
1422                 stamp_data->camera[0] = '\0';
1423         }
1424
1425         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1426                 if (camera && camera->type == OB_CAMERA) {
1427                         BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)camera->data)->lens);
1428                 }
1429                 else BLI_strncpy(text, "<none>", sizeof(text));
1430
1431                 BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), do_prefix ? "Lens %s" : "%s", text);
1432         }
1433         else {
1434                 stamp_data->cameralens[0] = '\0';
1435         }
1436
1437         if (scene->r.stamp & R_STAMP_SCENE) {
1438                 BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), do_prefix ? "Scene %s" : "%s", scene->id.name + 2);
1439         }
1440         else {
1441                 stamp_data->scene[0] = '\0';
1442         }
1443
1444         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1445                 Sequence *seq = BKE_sequencer_foreground_frame_get(scene, scene->r.cfra);
1446
1447                 if (seq) BLI_strncpy(text, seq->name + 2, sizeof(text));
1448                 else BLI_strncpy(text, "<none>", sizeof(text));
1449
1450                 BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), do_prefix ? "Strip %s" : "%s", text);
1451         }
1452         else {
1453                 stamp_data->strip[0] = '\0';
1454         }
1455
1456         {
1457                 Render *re = RE_GetRender(scene->id.name);
1458                 RenderStats *stats = re ? RE_GetStats(re) : NULL;
1459
1460                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1461                         BLI_timestr(stats->lastframetime, text);
1462
1463                         BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), do_prefix ? "RenderTime %s" : "%s", text);
1464                 }
1465                 else {
1466                         stamp_data->rendertime[0] = '\0';
1467                 }
1468         }
1469 }
1470
1471 void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rectf, int width, int height, int channels)
1472 {
1473         struct StampData stamp_data;
1474         float w, h, pad;
1475         int x, y, y_ofs;
1476         float h_fixed;
1477         const int mono = blf_mono_font_render; // XXX
1478
1479 #define BUFF_MARGIN_X 2
1480 #define BUFF_MARGIN_Y 1
1481
1482         if (!rect && !rectf)
1483                 return;
1484
1485         stampdata(scene, camera, &stamp_data, 1);
1486
1487         /* TODO, do_versions */
1488         if (scene->r.stamp_font_id < 8)
1489                 scene->r.stamp_font_id = 12;
1490
1491         /* set before return */
1492         BLF_size(mono, scene->r.stamp_font_id, 72);
1493
1494         BLF_buffer(mono, rectf, rect, width, height, channels);
1495         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1496         pad = BLF_width_max(mono);
1497
1498         /* use 'h_fixed' rather than 'h', aligns better */
1499         h_fixed = BLF_height_max(mono);
1500         y_ofs = -BLF_descender(mono);
1501
1502         x = 0;
1503         y = height;
1504
1505         if (stamp_data.file[0]) {
1506                 /* Top left corner */
1507                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h = h_fixed;
1508                 y -= h;
1509
1510                 /* also a little of space to the background. */
1511                 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);
1512
1513                 /* and draw the text. */
1514                 BLF_position(mono, x, y + y_ofs, 0.0);
1515                 BLF_draw_buffer(mono, stamp_data.file);
1516
1517                 /* the extra pixel for background. */
1518                 y -= BUFF_MARGIN_Y * 2;
1519         }
1520
1521         /* Top left corner, below File */
1522         if (stamp_data.note[0]) {
1523                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h = h_fixed;
1524                 y -= h;
1525
1526                 /* and space for background. */
1527                 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);
1528
1529                 BLF_position(mono, x, y + y_ofs, 0.0);
1530                 BLF_draw_buffer(mono, stamp_data.note);
1531
1532                 /* the extra pixel for background. */
1533                 y -= BUFF_MARGIN_Y * 2;
1534         }
1535
1536         /* Top left corner, below File (or Note) */
1537         if (stamp_data.date[0]) {
1538                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h = h_fixed;
1539                 y -= h;
1540
1541                 /* and space for background. */
1542                 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);
1543
1544                 BLF_position(mono, x, y + y_ofs, 0.0);
1545                 BLF_draw_buffer(mono, stamp_data.date);
1546
1547                 /* the extra pixel for background. */
1548                 y -= BUFF_MARGIN_Y * 2;
1549         }
1550
1551         /* Top left corner, below File, Date or Note */
1552         if (stamp_data.rendertime[0]) {
1553                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h = h_fixed;
1554                 y -= h;
1555
1556                 /* and space for background. */
1557                 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);
1558
1559                 BLF_position(mono, x, y + y_ofs, 0.0);
1560                 BLF_draw_buffer(mono, stamp_data.rendertime);
1561         }
1562
1563         x = 0;
1564         y = 0;
1565
1566         /* Bottom left corner, leaving space for timing */
1567         if (stamp_data.marker[0]) {
1568                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h = h_fixed;
1569
1570                 /* extra space for background. */
1571                 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);
1572
1573                 /* and pad the text. */
1574                 BLF_position(mono, x, y + y_ofs, 0.0);
1575                 BLF_draw_buffer(mono, stamp_data.marker);
1576
1577                 /* space width. */
1578                 x += w + pad;
1579         }
1580
1581         /* Left bottom corner */
1582         if (stamp_data.time[0]) {
1583                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h = h_fixed;
1584
1585                 /* extra space for background */
1586                 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);
1587
1588                 /* and pad the text. */
1589                 BLF_position(mono, x, y + y_ofs, 0.0);
1590                 BLF_draw_buffer(mono, stamp_data.time);
1591
1592                 /* space width. */
1593                 x += w + pad;
1594         }
1595
1596         if (stamp_data.frame[0]) {
1597                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h = h_fixed;
1598
1599                 /* extra space for background. */
1600                 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);
1601
1602                 /* and pad the text. */
1603                 BLF_position(mono, x, y + y_ofs, 0.0);
1604                 BLF_draw_buffer(mono, stamp_data.frame);
1605
1606                 /* space width. */
1607                 x += w + pad;
1608         }
1609
1610         if (stamp_data.camera[0]) {
1611                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h = h_fixed;
1612
1613                 /* extra space for background. */
1614                 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);
1615                 BLF_position(mono, x, y + y_ofs, 0.0);
1616                 BLF_draw_buffer(mono, stamp_data.camera);
1617
1618                 /* space width. */
1619                 x += w + pad;
1620         }
1621
1622         if (stamp_data.cameralens[0]) {
1623                 BLF_width_and_height(mono, stamp_data.cameralens, &w, &h); h = h_fixed;
1624
1625                 /* extra space for background. */
1626                 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);
1627                 BLF_position(mono, x, y + y_ofs, 0.0);
1628                 BLF_draw_buffer(mono, stamp_data.cameralens);
1629         }
1630
1631         if (stamp_data.scene[0]) {
1632                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h = h_fixed;
1633
1634                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1635                 x = width - w - 2;
1636
1637                 /* extra space for background. */
1638                 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);
1639
1640                 /* and pad the text. */
1641                 BLF_position(mono, x, y + y_ofs, 0.0);
1642                 BLF_draw_buffer(mono, stamp_data.scene);
1643         }
1644
1645         if (stamp_data.strip[0]) {
1646                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h = h_fixed;
1647
1648                 /* Top right corner, with an extra space because blenfont is too strict! */
1649                 x = width - w - pad;
1650                 y = height - h;
1651
1652                 /* extra space for background. */
1653                 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);
1654
1655                 BLF_position(mono, x, y + y_ofs, 0.0);
1656                 BLF_draw_buffer(mono, stamp_data.strip);
1657         }
1658
1659         /* cleanup the buffer. */
1660         BLF_buffer(mono, NULL, NULL, 0, 0, 0);
1661
1662 #undef BUFF_MARGIN_X
1663 #undef BUFF_MARGIN_Y
1664 }
1665
1666 void BKE_imbuf_stamp_info(Scene *scene, Object *camera, struct ImBuf *ibuf)
1667 {
1668         struct StampData stamp_data;
1669
1670         if (!ibuf) return;
1671
1672         /* fill all the data values, no prefix */
1673         stampdata(scene, camera, &stamp_data, 0);
1674
1675         if (stamp_data.file[0]) IMB_metadata_change_field(ibuf, "File",        stamp_data.file);
1676         if (stamp_data.note[0]) IMB_metadata_change_field(ibuf, "Note",        stamp_data.note);
1677         if (stamp_data.date[0]) IMB_metadata_change_field(ibuf, "Date",        stamp_data.date);
1678         if (stamp_data.marker[0]) IMB_metadata_change_field(ibuf, "Marker",    stamp_data.marker);
1679         if (stamp_data.time[0]) IMB_metadata_change_field(ibuf, "Time",        stamp_data.time);
1680         if (stamp_data.frame[0]) IMB_metadata_change_field(ibuf, "Frame",      stamp_data.frame);
1681         if (stamp_data.camera[0]) IMB_metadata_change_field(ibuf, "Camera",    stamp_data.camera);
1682         if (stamp_data.cameralens[0]) IMB_metadata_change_field(ibuf, "Lens",  stamp_data.cameralens);
1683         if (stamp_data.scene[0]) IMB_metadata_change_field(ibuf, "Scene",      stamp_data.scene);
1684         if (stamp_data.strip[0]) IMB_metadata_change_field(ibuf, "Strip",      stamp_data.strip);
1685         if (stamp_data.rendertime[0]) IMB_metadata_change_field(ibuf, "RenderTime", stamp_data.rendertime);
1686 }
1687
1688 int BKE_imbuf_alpha_test(ImBuf *ibuf)
1689 {
1690         int tot;
1691         if (ibuf->rect_float) {
1692                 float *buf = ibuf->rect_float;
1693                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1694                         if (buf[3] < 1.0f) {
1695                                 return TRUE;
1696                         }
1697                 }
1698         }
1699         else if (ibuf->rect) {
1700                 unsigned char *buf = (unsigned char *)ibuf->rect;
1701                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1702                         if (buf[3] != 255) {
1703                                 return TRUE;
1704                         }
1705                 }
1706         }
1707
1708         return FALSE;
1709 }
1710
1711 /* note: imf->planes is ignored here, its assumed the image channels
1712  * are already set */
1713 int BKE_imbuf_write(ImBuf *ibuf, const char *name, ImageFormatData *imf)
1714 {
1715         char imtype = imf->imtype;
1716         char compress = imf->compress;
1717         char quality = imf->quality;
1718
1719         int ok;
1720
1721         if (imtype == R_IMF_IMTYPE_IRIS) {
1722                 ibuf->ftype = IMAGIC;
1723         }
1724 #ifdef WITH_HDR
1725         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1726                 ibuf->ftype = RADHDR;
1727         }
1728 #endif
1729         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1730                 ibuf->ftype = PNG;
1731
1732                 if (imtype == R_IMF_IMTYPE_PNG)
1733                         ibuf->ftype |= compress;
1734
1735         }
1736 #ifdef WITH_DDS
1737         else if (imtype == R_IMF_IMTYPE_DDS) {
1738                 ibuf->ftype = DDS;
1739         }
1740 #endif
1741         else if (imtype == R_IMF_IMTYPE_BMP) {
1742                 ibuf->ftype = BMP;
1743         }
1744 #ifdef WITH_TIFF
1745         else if (imtype == R_IMF_IMTYPE_TIFF) {
1746                 ibuf->ftype = TIF;
1747
1748                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1749                         ibuf->ftype |= TIF_16BIT;
1750         }
1751 #endif
1752 #ifdef WITH_OPENEXR
1753         else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER) {
1754                 ibuf->ftype = OPENEXR;
1755                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1756                         ibuf->ftype |= OPENEXR_HALF;
1757                 ibuf->ftype |= (imf->exr_codec & OPENEXR_COMPRESS);
1758
1759                 if (!(imf->flag & R_IMF_FLAG_ZBUF))
1760                         ibuf->zbuf_float = NULL;    /* signal for exr saving */
1761
1762         }
1763 #endif
1764 #ifdef WITH_CINEON
1765         else if (imtype == R_IMF_IMTYPE_CINEON) {
1766                 ibuf->ftype = CINEON;
1767         }
1768         else if (imtype == R_IMF_IMTYPE_DPX) {
1769                 ibuf->ftype = DPX;
1770         }
1771 #endif
1772         else if (imtype == R_IMF_IMTYPE_TARGA) {
1773                 ibuf->ftype = TGA;
1774         }
1775         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
1776                 ibuf->ftype = RAWTGA;
1777         }
1778 #ifdef WITH_OPENJPEG
1779         else if (imtype == R_IMF_IMTYPE_JP2) {
1780                 if (quality < 10) quality = 90;
1781                 ibuf->ftype = JP2 | quality;
1782
1783                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1784                         ibuf->ftype |= JP2_16BIT;
1785                 }
1786                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1787                         ibuf->ftype |= JP2_12BIT;
1788                 }
1789
1790                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
1791                         ibuf->ftype |= JP2_YCC;
1792                 }
1793
1794                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
1795                         ibuf->ftype |= JP2_CINE;
1796                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
1797                                 ibuf->ftype |= JP2_CINE_48FPS;
1798                 }
1799         }
1800 #endif
1801         else {
1802                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
1803                 if (quality < 10) quality = 90;
1804                 ibuf->ftype = JPG | quality;
1805         }
1806
1807         BLI_make_existing_file(name);
1808
1809         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1810         if (ok == 0) {
1811                 perror(name);
1812         }
1813
1814         return(ok);
1815 }
1816
1817 /* same as BKE_imbuf_write() but crappy workaround not to perminantly modify
1818  * _some_, values in the imbuf */
1819 int BKE_imbuf_write_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
1820                        const short save_copy)
1821 {
1822         ImBuf ibuf_back = *ibuf;
1823         int ok;
1824
1825         /* all data is rgba anyway,
1826          * this just controls how to save for some formats */
1827         ibuf->planes = imf->planes;
1828
1829         ok = BKE_imbuf_write(ibuf, name, imf);
1830
1831         if (save_copy) {
1832                 /* note that we are not restoring _all_ settings */
1833                 ibuf->planes = ibuf_back.planes;
1834                 ibuf->ftype =  ibuf_back.ftype;
1835         }
1836
1837         return ok;
1838 }
1839
1840 int BKE_imbuf_write_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, struct ImageFormatData *imf)
1841 {
1842         if (scene && scene->r.stamp & R_STAMP_ALL)
1843                 BKE_imbuf_stamp_info(scene, camera, ibuf);
1844
1845         return BKE_imbuf_write(ibuf, name, imf);
1846 }
1847
1848
1849 void BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, const char imtype, const short use_ext, const short use_frames)
1850 {
1851         if (string == NULL) return;
1852         BLI_strncpy(string, base, FILE_MAX - 10);   /* weak assumption */
1853         BLI_path_abs(string, relbase);
1854
1855         if (use_frames)
1856                 BLI_path_frame(string, frame, 4);
1857
1858         if (use_ext)
1859                 BKE_add_image_extension(string, imtype);
1860
1861 }
1862
1863 /* used by sequencer too */
1864 struct anim *openanim(const char *name, int flags, int streamindex)
1865 {
1866         struct anim *anim;
1867         struct ImBuf *ibuf;
1868
1869         anim = IMB_open_anim(name, flags, streamindex);
1870         if (anim == NULL) return NULL;
1871
1872         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
1873         if (ibuf == NULL) {
1874                 if (BLI_exists(name))
1875                         printf("not an anim: %s\n", name);
1876                 else
1877                         printf("anim file doesn't exist: %s\n", name);
1878                 IMB_free_anim(anim);
1879                 return NULL;
1880         }
1881         IMB_freeImBuf(ibuf);
1882
1883         return(anim);
1884 }
1885
1886 /* ************************* New Image API *************** */
1887
1888
1889 /* Notes about Image storage
1890  * - packedfile
1891  *   -> written in .blend
1892  * - filename
1893  *   -> written in .blend
1894  * - movie
1895  *   -> comes from packedfile or filename
1896  * - renderresult
1897  *   -> comes from packedfile or filename
1898  * - listbase
1899  *   -> ibufs from exrhandle
1900  * - flipbook array
1901  *   -> ibufs come from movie, temporary renderresult or sequence
1902  * - ibuf
1903  *   -> comes from packedfile or filename or generated
1904  */
1905
1906
1907 /* forces existence of 1 Image for renderout or nodes, returns Image */
1908 /* name is only for default, when making new one */
1909 Image *BKE_image_verify_viewer(int type, const char *name)
1910 {
1911         Image *ima;
1912
1913         for (ima = G.main->image.first; ima; ima = ima->id.next)
1914                 if (ima->source == IMA_SRC_VIEWER)
1915                         if (ima->type == type)
1916                                 break;
1917
1918         if (ima == NULL)
1919                 ima = image_alloc(name, IMA_SRC_VIEWER, type);
1920
1921         /* happens on reload, imagewindow cannot be image user when hidden*/
1922         if (ima->id.us == 0)
1923                 id_us_plus(&ima->id);
1924
1925         return ima;
1926 }
1927
1928 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1929 {
1930         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1931 }
1932
1933 void BKE_image_walk_all_users(const Main *mainp, void *customdata,
1934                               void callback(Image *ima, ImageUser *iuser, void *customdata))
1935 {
1936         wmWindowManager *wm;
1937         wmWindow *win;
1938         Tex *tex;
1939
1940         /* texture users */
1941         for (tex = mainp->tex.first; tex; tex = tex->id.next) {
1942                 if (tex->type == TEX_IMAGE && tex->ima) {
1943                         if (ELEM(tex->ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
1944                                 callback(tex->ima, &tex->iuser, customdata);
1945                         }
1946                 }
1947         }
1948
1949         /* image window, compo node users */
1950         for (wm = mainp->wm.first; wm; wm = wm->id.next) { /* only 1 wm */
1951                 for (win = wm->windows.first; win; win = win->next) {
1952                         ScrArea *sa;
1953                         for (sa = win->screen->areabase.first; sa; sa = sa->next) {
1954                                 if (sa->spacetype == SPACE_VIEW3D) {
1955                                         View3D *v3d = sa->spacedata.first;
1956                                         BGpic *bgpic;
1957                                         for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
1958                                                 callback(bgpic->ima, &bgpic->iuser, customdata);
1959                                         }
1960                                 }
1961                                 else if (sa->spacetype == SPACE_IMAGE) {
1962                                         SpaceImage *sima = sa->spacedata.first;
1963                                         callback(sima->image, &sima->iuser, customdata);
1964                                 }
1965                                 else if (sa->spacetype == SPACE_NODE) {
1966                                         SpaceNode *snode = sa->spacedata.first;
1967                                         if ((snode->treetype == NTREE_COMPOSIT) && (snode->nodetree)) {
1968                                                 bNode *node;
1969                                                 for (node = snode->nodetree->nodes.first; node; node = node->next) {
1970                                                         if (node->id && node->type == CMP_NODE_IMAGE) {
1971                                                                 Image *ima = (Image *)node->id;
1972                                                                 ImageUser *iuser = node->storage;
1973                                                                 callback(ima, iuser, customdata);
1974                                                         }
1975                                                 }
1976                                         }
1977                                 }
1978                         }
1979                 }
1980         }
1981 }
1982
1983 static void image_tag_frame_recalc(Image *ima, ImageUser *iuser, void *customdata)
1984 {
1985         Image *changed_image = customdata;
1986
1987         if (ima == changed_image) {
1988                 iuser->flag |= IMA_NEED_FRAME_RECALC;
1989         }
1990 }
1991
1992 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
1993 {
1994         if (ima == NULL)
1995                 return;
1996
1997         switch (signal) {
1998                 case IMA_SIGNAL_FREE:
1999                         image_free_buffers(ima);
2000                         if (iuser)
2001                                 iuser->ok = 1;
2002                         break;
2003                 case IMA_SIGNAL_SRC_CHANGE:
2004                         if (ima->type == IMA_TYPE_UV_TEST)
2005                                 if (ima->source != IMA_SRC_GENERATED)
2006                                         ima->type = IMA_TYPE_IMAGE;
2007
2008                         if (ima->source == IMA_SRC_GENERATED) {
2009                                 if (ima->gen_x == 0 || ima->gen_y == 0) {
2010                                         ImBuf *ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2011                                         if (ibuf) {
2012                                                 ima->gen_x = ibuf->x;
2013                                                 ima->gen_y = ibuf->y;
2014                                         }
2015                                 }
2016                         }
2017
2018                         /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
2019                         if (ima->type != IMA_TYPE_MULTILAYER)
2020                                 image_free_buffers(ima);
2021
2022                         ima->ok = 1;
2023                         if (iuser)
2024                                 iuser->ok = 1;
2025
2026                         BKE_image_walk_all_users(G.main, ima, image_tag_frame_recalc);
2027
2028                         break;
2029
2030                 case IMA_SIGNAL_RELOAD:
2031                         /* try to repack file */
2032                         if (ima->packedfile) {
2033                                 PackedFile *pf;
2034                                 pf = newPackedFile(NULL, ima->name, ID_BLEND_PATH(G.main, &ima->id));
2035                                 if (pf) {
2036                                         freePackedFile(ima->packedfile);
2037                                         ima->packedfile = pf;
2038                                         image_free_buffers(ima);
2039                                 }
2040                                 else {
2041                                         printf("ERROR: Image not available. Keeping packed image\n");
2042                                 }
2043                         }
2044                         else
2045                                 image_free_buffers(ima);
2046
2047                         if (iuser)
2048                                 iuser->ok = 1;
2049
2050                         break;
2051                 case IMA_SIGNAL_USER_NEW_IMAGE:
2052                         if (iuser) {
2053                                 iuser->ok = 1;
2054                                 if (ima->source == IMA_SRC_FILE || ima->source == IMA_SRC_SEQUENCE) {
2055                                         if (ima->type == IMA_TYPE_MULTILAYER) {
2056                                                 iuser->multi_index = 0;
2057                                                 iuser->layer = iuser->pass = 0;
2058                                         }
2059                                 }
2060                         }
2061                         break;
2062         }
2063
2064         /* don't use notifiers because they are not 100% sure to succeeded
2065          * this also makes sure all scenes are accounted for. */
2066         {
2067                 Scene *scene;
2068                 for (scene = G.main->scene.first; scene; scene = scene->id.next) {
2069                         if (scene->nodetree) {
2070                                 nodeUpdateID(scene->nodetree, &ima->id);
2071                         }
2072                 }
2073         }
2074 }
2075
2076 /* if layer or pass changes, we need an index for the imbufs list */
2077 /* note it is called for rendered results, but it doesnt use the index! */
2078 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
2079 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
2080 {
2081         RenderLayer *rl;
2082         RenderPass *rpass = NULL;
2083
2084         if (rr == NULL)
2085                 return NULL;
2086
2087         if (iuser) {
2088                 short index = 0, rl_index = 0, rp_index;
2089
2090                 for (rl = rr->layers.first; rl; rl = rl->next, rl_index++) {
2091                         rp_index = 0;
2092                         for (rpass = rl->passes.first; rpass; rpass = rpass->next, index++, rp_index++)
2093                                 if (iuser->layer == rl_index && iuser->pass == rp_index)
2094                                         break;
2095                         if (rpass)
2096                                 break;
2097                 }
2098
2099                 if (rpass)
2100                         iuser->multi_index = index;
2101                 else
2102                         iuser->multi_index = 0;
2103         }
2104         if (rpass == NULL) {
2105                 rl = rr->layers.first;
2106                 if (rl)
2107                         rpass = rl->passes.first;
2108         }
2109
2110         return rpass;
2111 }
2112
2113 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
2114 {
2115         if (ima->rr) {
2116                 return ima->rr;
2117         }
2118         else if (ima->type == IMA_TYPE_R_RESULT) {
2119                 if (ima->render_slot == ima->last_render_slot)
2120                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
2121                 else
2122                         return ima->renders[ima->render_slot];
2123         }
2124         else
2125                 return NULL;
2126 }
2127
2128 void BKE_image_release_renderresult(Scene *scene, Image *ima)
2129 {
2130         if (ima->rr) ;
2131         else if (ima->type == IMA_TYPE_R_RESULT) {
2132                 if (ima->render_slot == ima->last_render_slot)
2133                         RE_ReleaseResult(RE_GetRender(scene->id.name));
2134         }
2135 }
2136
2137 void BKE_image_backup_render(Scene *scene, Image *ima)
2138 {
2139         /* called right before rendering, ima->renders contains render
2140          * result pointers for everything but the current render */
2141         Render *re = RE_GetRender(scene->id.name);
2142         int slot = ima->render_slot, last = ima->last_render_slot;
2143
2144         if (slot != last) {
2145                 if (ima->renders[slot]) {
2146                         RE_FreeRenderResult(ima->renders[slot]);
2147                         ima->renders[slot] = NULL;
2148                 }
2149
2150                 ima->renders[last] = NULL;
2151                 RE_SwapResult(re, &ima->renders[last]);
2152         }
2153
2154         ima->last_render_slot = slot;
2155 }
2156
2157 /* after imbuf load, openexr type can return with a exrhandle open */
2158 /* in that case we have to build a render-result */
2159 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
2160 {
2161
2162         ima->rr = RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
2163
2164 #ifdef WITH_OPENEXR
2165         IMB_exr_close(ibuf->userdata);
2166 #endif
2167
2168         ibuf->userdata = NULL;
2169         if (ima->rr)
2170                 ima->rr->framenr = framenr;
2171 }
2172
2173 /* common stuff to do with images after loading */
2174 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
2175 {
2176         /* preview is NULL when it has never been used as an icon before */
2177         if (G.background == 0 && ima->preview == NULL)
2178                 BKE_icon_changed(BKE_icon_getid(&ima->id));
2179
2180         /* fields */
2181         if (ima->flag & IMA_FIELDS) {
2182                 if (ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
2183                 else de_interlace_ng(ibuf);
2184         }
2185         /* timer */
2186         ima->lastused = clock() / CLOCKS_PER_SEC;
2187
2188         ima->ok = IMA_OK_LOADED;
2189
2190 }
2191
2192 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
2193 {
2194         struct ImBuf *ibuf;
2195         char name[FILE_MAX];
2196         int flag;
2197
2198         /* XXX temp stuff? */
2199         if (ima->lastframe != frame)
2200                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2201
2202         ima->lastframe = frame;
2203         BKE_image_user_file_path(iuser, ima, name);
2204
2205         flag = IB_rect | IB_multilayer;
2206         if (ima->flag & IMA_DO_PREMUL)
2207                 flag |= IB_premul;
2208
2209         /* read ibuf */
2210         ibuf = IMB_loadiffname(name, flag);
2211
2212 #if 0
2213         if (ibuf) {
2214                 printf(AT " loaded %s\n", name);
2215         }
2216         else {
2217                 printf(AT " missed %s\n", name);
2218         }
2219 #endif
2220
2221         if (ibuf) {
2222 #ifdef WITH_OPENEXR
2223                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2224                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2225                         image_create_multilayer(ima, ibuf, frame);
2226                         ima->type = IMA_TYPE_MULTILAYER;
2227                         IMB_freeImBuf(ibuf);
2228                         ibuf = NULL;
2229                 }
2230                 else {
2231                         image_initialize_after_load(ima, ibuf);
2232                         image_assign_ibuf(ima, ibuf, 0, frame);
2233                 }
2234 #else
2235                 image_initialize_after_load(ima, ibuf);
2236                 image_assign_ibuf(ima, ibuf, 0, frame);
2237 #endif
2238         }
2239         else
2240                 ima->ok = 0;
2241
2242         if (iuser)
2243                 iuser->ok = ima->ok;
2244
2245         return ibuf;
2246 }
2247
2248 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
2249 {
2250         struct ImBuf *ibuf = NULL;
2251
2252         /* either we load from RenderResult, or we have to load a new one */
2253
2254         /* check for new RenderResult */
2255         if (ima->rr == NULL || frame != ima->rr->framenr) {
2256                 /* copy to survive not found multilayer image */
2257                 RenderResult *oldrr = ima->rr;
2258
2259                 ima->rr = NULL;
2260                 ibuf = image_load_sequence_file(ima, iuser, frame);
2261
2262                 if (ibuf) { /* actually an error */
2263                         ima->type = IMA_TYPE_IMAGE;
2264                         printf("error, multi is normal image\n");
2265                 }
2266                 // printf("loaded new result %p\n", ima->rr);
2267                 /* free result if new one found */
2268                 if (ima->rr) {
2269                         // if (oldrr) printf("freed previous result %p\n", oldrr);
2270                         if (oldrr) RE_FreeRenderResult(oldrr);
2271                 }
2272                 else {
2273                         ima->rr = oldrr;
2274                 }
2275
2276         }
2277         if (ima->rr) {
2278                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2279
2280                 if (rpass) {
2281                         // printf("load from pass %s\n", rpass->name);
2282                         /* since we free  render results, we copy the rect */
2283                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2284                         ibuf->rect_float = MEM_dupallocN(rpass->rect);
2285                         ibuf->flags |= IB_rectfloat;
2286                         ibuf->mall = IB_rectfloat;
2287                         ibuf->channels = rpass->channels;
2288                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2289
2290                         image_initialize_after_load(ima, ibuf);
2291                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : 0, frame);
2292
2293                 }
2294                 // else printf("pass not found\n");
2295         }
2296         else
2297                 ima->ok = 0;
2298
2299         if (iuser)
2300                 iuser->ok = ima->ok;
2301
2302         return ibuf;
2303 }
2304
2305
2306 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
2307 {
2308         struct ImBuf *ibuf = NULL;
2309
2310         ima->lastframe = frame;
2311
2312         if (ima->anim == NULL) {
2313                 char str[FILE_MAX];
2314
2315                 BKE_image_user_file_path(iuser, ima, str);
2316
2317                 /* FIXME: make several stream accessible in image editor, too*/
2318                 ima->anim = openanim(str, IB_rect, 0);
2319
2320                 /* let's initialize this user */
2321                 if (ima->anim && iuser && iuser->frames == 0)
2322                         iuser->frames = IMB_anim_get_duration(ima->anim,
2323                                                               IMB_TC_RECORD_RUN);
2324         }
2325
2326         if (ima->anim) {
2327                 int dur = IMB_anim_get_duration(ima->anim,
2328                                                 IMB_TC_RECORD_RUN);
2329                 int fra = frame - 1;
2330
2331                 if (fra < 0) fra = 0;
2332                 if (fra > (dur - 1)) fra = dur - 1;
2333                 ibuf = IMB_makeSingleUser(
2334                     IMB_anim_absolute(ima->anim, fra,
2335                                       IMB_TC_RECORD_RUN,
2336                                       IMB_PROXY_NONE));
2337
2338                 if (ibuf) {
2339                         image_initialize_after_load(ima, ibuf);
2340                         image_assign_ibuf(ima, ibuf, 0, frame);
2341                 }
2342                 else
2343                         ima->ok = 0;
2344         }
2345         else
2346                 ima->ok = 0;
2347
2348         if (iuser)
2349                 iuser->ok = ima->ok;
2350
2351         return ibuf;
2352 }
2353
2354 /* warning, 'iuser' can be NULL */
2355 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
2356 {
2357         struct ImBuf *ibuf;
2358         char str[FILE_MAX];
2359         int assign = 0, flag;
2360
2361         /* always ensure clean ima */
2362         image_free_buffers(ima);
2363
2364         /* is there a PackedFile with this image ? */
2365         if (ima->packedfile) {
2366                 flag = IB_rect | IB_multilayer;
2367                 if (ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
2368
2369                 ibuf = IMB_ibImageFromMemory((unsigned char *)ima->packedfile->data,
2370                                              ima->packedfile->size, flag, "<packed data>");
2371         }
2372         else {
2373                 flag = IB_rect | IB_multilayer | IB_metadata;
2374                 if (ima->flag & IMA_DO_PREMUL)
2375                         flag |= IB_premul;
2376
2377                 /* get the right string */
2378                 BKE_image_user_frame_calc(iuser, cfra, 0);
2379                 BKE_image_user_file_path(iuser, ima, str);
2380
2381                 /* read ibuf */
2382                 ibuf = IMB_loadiffname(str, flag);
2383         }
2384
2385         if (ibuf) {
2386                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2387                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2388                         image_create_multilayer(ima, ibuf, cfra);
2389                         ima->type = IMA_TYPE_MULTILAYER;
2390                         IMB_freeImBuf(ibuf);
2391                         ibuf = NULL;
2392                 }
2393                 else {
2394                         image_initialize_after_load(ima, ibuf);
2395                         assign = 1;
2396
2397                         /* check if the image is a font image... */
2398                         detectBitmapFont(ibuf);
2399
2400                         /* make packed file for autopack */
2401                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
2402                                 ima->packedfile = newPackedFile(NULL, str, ID_BLEND_PATH(G.main, &ima->id));
2403                 }
2404         }
2405         else
2406                 ima->ok = 0;
2407
2408         if (assign)
2409                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2410
2411         if (iuser)
2412                 iuser->ok = ima->ok;
2413
2414         return ibuf;
2415 }
2416
2417 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
2418 {
2419         ImBuf *ibuf = NULL;
2420
2421         if (ima->rr == NULL) {
2422                 ibuf = image_load_image_file(ima, iuser, 0);
2423                 if (ibuf) { /* actually an error */
2424                         ima->type = IMA_TYPE_IMAGE;
2425                         return ibuf;
2426                 }
2427         }
2428         if (ima->rr) {
2429                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2430
2431                 if (rpass) {
2432                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2433
2434                         image_initialize_after_load(ima, ibuf);
2435
2436                         ibuf->rect_float = rpass->rect;
2437                         ibuf->flags |= IB_rectfloat;
2438                         ibuf->channels = rpass->channels;
2439                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2440
2441                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2442                 }
2443         }
2444
2445         if (ibuf == NULL)
2446                 ima->ok = 0;
2447         if (iuser)
2448                 iuser->ok = ima->ok;
2449
2450         return ibuf;
2451 }
2452
2453
2454 /* showing RGBA result itself (from compo/sequence) or
2455  * like exr, using layers etc */
2456 /* always returns a single ibuf, also during render progress */
2457 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
2458 {
2459         Render *re;
2460         RenderResult rres;
2461         float *rectf, *rectz;
2462         unsigned int *rect;
2463         float dither;
2464         int channels, layer, pass;
2465         ImBuf *ibuf;
2466         int from_render = (ima->render_slot == ima->last_render_slot);
2467
2468         if (!(iuser && iuser->scene))
2469                 return NULL;
2470
2471         /* if we the caller is not going to release the lock, don't give the image */
2472         if (!lock_r)
2473                 return NULL;
2474
2475         re = RE_GetRender(iuser->scene->id.name);
2476
2477         channels = 4;
2478         layer = (iuser) ? iuser->layer : 0;
2479         pass = (iuser) ? iuser->pass : 0;
2480
2481         if (from_render) {
2482                 RE_AcquireResultImage(re, &rres);
2483         }
2484         else if (ima->renders[ima->render_slot]) {
2485                 rres = *(ima->renders[ima->render_slot]);
2486                 rres.have_combined = rres.rectf != NULL;
2487         }
2488         else
2489                 memset(&rres, 0, sizeof(RenderResult));
2490
2491         if (!(rres.rectx > 0 && rres.recty > 0)) {
2492                 if (from_render)
2493                         RE_ReleaseResultImage(re);
2494                 return NULL;
2495         }
2496
2497         /* release is done in BKE_image_release_ibuf using lock_r */
2498         if (from_render) {
2499                 BLI_lock_thread(LOCK_VIEWER);
2500                 *lock_r = re;
2501         }
2502
2503         /* this gives active layer, composite or seqence result */
2504         rect = (unsigned int *)rres.rect32;
2505         rectf = rres.rectf;
2506         rectz = rres.rectz;
2507         dither = iuser->scene->r.dither_intensity;
2508
2509         /* combined layer gets added as first layer */
2510         if (rres.have_combined && layer == 0) ;
2511         else if (rres.layers.first) {
2512                 RenderLayer *rl = BLI_findlink(&rres.layers, layer - (rres.have_combined ? 1 : 0));
2513                 if (rl) {
2514                         RenderPass *rpass;
2515
2516                         /* there's no combined pass, is in renderlayer itself */
2517                         if (pass == 0) {
2518                                 rectf = rl->rectf;
2519                         }
2520                         else {
2521                                 rpass = BLI_findlink(&rl->passes, pass - 1);
2522                                 if (rpass) {
2523                                         channels = rpass->channels;
2524                                         rectf = rpass->rect;
2525                                         dither = 0.0f; /* don't dither passes */
2526                                 }
2527                         }
2528
2529                         for (rpass = rl->passes.first; rpass; rpass = rpass->next)
2530                                 if (rpass->passtype == SCE_PASS_Z)
2531                                         rectz = rpass->rect;
2532                 }
2533         }
2534
2535         ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2536
2537         /* make ibuf if needed, and initialize it */
2538         if (ibuf == NULL) {
2539                 ibuf = IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
2540                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2541         }
2542
2543         ibuf->x = rres.rectx;
2544         ibuf->y = rres.recty;
2545
2546         /* free rect buffer if float buffer changes, so it can be recreated with
2547          * the updated result, and also in case we got byte buffer from sequencer,
2548          * so we don't keep reference to freed buffer */
2549         if (ibuf->rect_float != rectf || rect || !rectf)
2550                 imb_freerectImBuf(ibuf);
2551
2552         if (rect)
2553                 ibuf->rect = rect;
2554
2555         if (rectf) {
2556                 ibuf->rect_float = rectf;
2557                 ibuf->flags |= IB_rectfloat;
2558                 ibuf->channels = channels;
2559         }
2560         else {
2561                 ibuf->rect_float = NULL;
2562                 ibuf->flags &= ~IB_rectfloat;
2563         }
2564
2565         if (rectz) {
2566                 ibuf->zbuf_float = rectz;
2567                 ibuf->flags |= IB_zbuffloat;
2568         }
2569         else {
2570                 ibuf->zbuf_float = NULL;
2571                 ibuf->flags &= ~IB_zbuffloat;
2572         }
2573
2574         /* since its possible to access the buffer from the image directly, set the profile [#25073] */
2575         ibuf->profile = (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) ? IB_PROFILE_LINEAR_RGB : IB_PROFILE_NONE;
2576         ibuf->dither = dither;
2577
2578         if (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT_PREDIVIDE) {
2579                 ibuf->flags |= IB_cm_predivide;
2580                 ima->flag |= IMA_CM_PREDIVIDE;
2581         }
2582         else {
2583                 ibuf->flags &= ~IB_cm_predivide;
2584                 ima->flag &= ~IMA_CM_PREDIVIDE;
2585         }
2586
2587         ima->ok = IMA_OK_LOADED;
2588
2589         return ibuf;
2590 }
2591
2592 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2593 {
2594         ImBuf *ibuf = NULL;
2595         int frame = 0, index = 0;
2596
2597         /* see if we already have an appropriate ibuf, with image source and type */
2598         if (ima->source == IMA_SRC_MOVIE) {
2599                 frame = iuser ? iuser->framenr : ima->lastframe;
2600                 ibuf = image_get_ibuf(ima, 0, frame);
2601                 /* XXX temp stuff? */
2602                 if (ima->lastframe != frame)
2603                         ima->tpageflag |= IMA_TPAGE_REFRESH;
2604                 ima->lastframe = frame;
2605         }
2606         else if (ima->source == IMA_SRC_SEQUENCE) {
2607                 if (ima->type == IMA_TYPE_IMAGE) {
2608                         frame = iuser ? iuser->framenr : ima->lastframe;
2609                         ibuf = image_get_ibuf(ima, 0, frame);
2610
2611                         /* XXX temp stuff? */
2612                         if (ima->lastframe != frame) {
2613                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2614                         }
2615                         ima->lastframe = frame;
2616                 }
2617                 else if (ima->type == IMA_TYPE_MULTILAYER) {
2618                         frame = iuser ? iuser->framenr : ima->lastframe;
2619                         index = iuser ? iuser->multi_index : IMA_NO_INDEX;
2620                         ibuf = image_get_ibuf(ima, index, frame);
2621                 }
2622         }
2623         else if (ima->source == IMA_SRC_FILE) {
2624                 if (ima->type == IMA_TYPE_IMAGE)
2625                         ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2626                 else if (ima->type == IMA_TYPE_MULTILAYER)
2627                         ibuf = image_get_ibuf(ima, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2628         }
2629         else if (ima->source == IMA_SRC_GENERATED) {
2630                 ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2631         }
2632         else if (ima->source == IMA_SRC_VIEWER) {
2633                 /* always verify entirely, not that this shouldn't happen
2634                  * as part of texture sampling in rendering anyway, so not
2635                  * a big bottleneck */
2636         }
2637
2638         *frame_r = frame;
2639         *index_r = index;
2640
2641         return ibuf;
2642 }
2643
2644 /* Checks optional ImageUser and verifies/creates ImBuf. */
2645 /* use this one if you want to get a render result in progress,
2646  * if not, use BKE_image_get_ibuf which doesn't require a release */
2647 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2648 {
2649         ImBuf *ibuf = NULL;
2650         float color[] = {0, 0, 0, 1};
2651         int frame = 0, index = 0;
2652
2653         /* This function is intended to be thread-safe. It postpones the mutex lock
2654          * until it needs to load the image, if the image is already there it
2655          * should just get the pointer and return. The reason is that a lot of mutex
2656          * locks appears to be very slow on certain multicore macs, causing a render
2657          * with image textures to actually slow down as more threads are used.
2658          *
2659          * Note that all the image loading functions should also make sure they do
2660          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2661          * That means, the last two steps must be, 1) add the ibuf to the list and
2662          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2663
2664         if (lock_r)
2665                 *lock_r = NULL;
2666
2667         /* quick reject tests */
2668         if (ima == NULL)
2669                 return NULL;
2670         if (iuser) {
2671                 if (iuser->ok == 0)
2672                         return NULL;
2673         }
2674         else if (ima->ok == 0)
2675                 return NULL;
2676
2677         /* try to get the ibuf without locking */
2678         ibuf = image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2679
2680         if (ibuf == NULL) {
2681                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2682                  * load the image */
2683                 BLI_lock_thread(LOCK_IMAGE);
2684
2685                 /* need to check ok flag and loading ibuf again, because the situation
2686                  * might have changed in the meantime */
2687                 if (iuser) {
2688                         if (iuser->ok == 0) {
2689                                 BLI_unlock_thread(LOCK_IMAGE);
2690                                 return NULL;
2691                         }
2692                 }
2693                 else if (ima->ok == 0) {
2694                         BLI_unlock_thread(LOCK_IMAGE);
2695                         return NULL;
2696                 }
2697
2698                 ibuf = image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2699
2700                 if (ibuf == NULL) {
2701                         /* we are sure we have to load the ibuf, using source and type */
2702                         if (ima->source == IMA_SRC_MOVIE) {
2703                                 /* source is from single file, use flipbook to store ibuf */
2704                                 ibuf = image_load_movie_file(ima, iuser, frame);
2705                         }
2706                         else if (ima->source == IMA_SRC_SEQUENCE) {
2707                                 if (ima->type == IMA_TYPE_IMAGE) {
2708                                         /* regular files, ibufs in flipbook, allows saving */
2709                                         ibuf = image_load_sequence_file(ima, iuser, frame);
2710                                 }
2711                                 /* no else; on load the ima type can change */
2712                                 if (ima->type == IMA_TYPE_MULTILAYER) {
2713                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2714                                         ibuf = image_load_sequence_multilayer(ima, iuser, frame);
2715                                 }
2716                         }
2717                         else if (ima->source == IMA_SRC_FILE) {
2718
2719                                 if (ima->type == IMA_TYPE_IMAGE)
2720                                         ibuf = image_load_image_file(ima, iuser, frame);  /* cfra only for '#', this global is OK */
2721                                 /* no else; on load the ima type can change */
2722                                 if (ima->type == IMA_TYPE_MULTILAYER)
2723                                         /* keeps render result, stores ibufs in listbase, allows saving */
2724                                         ibuf = image_get_ibuf_multilayer(ima, iuser);
2725
2726                         }
2727                         else if (ima->source == IMA_SRC_GENERATED) {
2728                                 /* generated is: ibuf is allocated dynamically */
2729                                 /* UV testgrid or black or solid etc */
2730                                 if (ima->gen_x == 0) ima->gen_x = 1024;
2731                                 if (ima->gen_y == 0) ima->gen_y = 1024;
2732                                 ibuf = add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, (ima->gen_flag & IMA_GEN_FLOAT) != 0, ima->gen_type, color);
2733                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2734                                 ima->ok = IMA_OK_LOADED;
2735                         }
2736                         else if (ima->source == IMA_SRC_VIEWER) {
2737                                 if (ima->type == IMA_TYPE_R_RESULT) {
2738                                         /* always verify entirely, and potentially
2739                                          * returns pointer to release later */
2740                                         ibuf = image_get_render_result(ima, iuser, lock_r);
2741                                 }
2742                                 else if (ima->type == IMA_TYPE_COMPOSITE) {
2743                                         /* requires lock/unlock, otherwise don't return image */
2744                                         if (lock_r) {
2745                                                 /* unlock in BKE_image_release_ibuf */
2746                                                 BLI_lock_thread(LOCK_VIEWER);
2747                                                 *lock_r = ima;
2748
2749                                                 /* XXX anim play for viewer nodes not yet supported */
2750                                                 frame = 0; // XXX iuser?iuser->framenr:0;
2751                                                 ibuf = image_get_ibuf(ima, 0, frame);
2752
2753                                                 if (!ibuf) {
2754                                                         /* Composite Viewer, all handled in compositor */
2755                                                         /* fake ibuf, will be filled in compositor */
2756                                                         ibuf = IMB_allocImBuf(256, 256, 32, IB_rect);
2757                                                         image_assign_ibuf(ima, ibuf, 0, frame);
2758                                                 }
2759                                         }
2760                                 }
2761                         }
2762                 }
2763
2764                 BLI_unlock_thread(LOCK_IMAGE);
2765         }
2766
2767         BKE_image_tag_time(ima);
2768
2769         return ibuf;
2770 }
2771
2772 void BKE_image_release_ibuf(Image *ima, void *lock)
2773 {
2774         /* for getting image during threaded render / compositing, need to release */
2775         if (lock == ima) {
2776                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2777         }
2778         else if (lock) {
2779                 RE_ReleaseResultImage(lock); /* render result */
2780                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2781         }
2782 }
2783
2784 /* warning, this can allocate generated images */
2785 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2786 {
2787         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2788         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2789 }
2790
2791 int BKE_image_user_frame_get(const ImageUser *iuser, int cfra, int fieldnr, short *r_is_in_range)
2792 {
2793         const int len = (iuser->fie_ima * iuser->frames) / 2;
2794
2795         if (r_is_in_range) {
2796                 *r_is_in_range = FALSE;
2797         }
2798
2799         if (len == 0) {
2800                 return 0;
2801         }
2802         else {
2803                 int framenr;
2804                 cfra = cfra - iuser->sfra + 1;
2805
2806                 /* cyclic */
2807                 if (iuser->cycl) {
2808                         cfra = ((cfra) % len);
2809                         if (cfra < 0) cfra += len;
2810                         if (cfra == 0) cfra = len;
2811
2812                         if (r_is_in_range) {
2813                                 *r_is_in_range = TRUE;
2814                         }
2815                 }
2816
2817                 if (cfra < 0) {
2818                         cfra = 0;
2819                 }
2820                 else if (cfra > len) {
2821                         cfra = len;
2822                 }
2823                 else {
2824                         if (r_is_in_range) {
2825                                 *r_is_in_range = TRUE;
2826                         }
2827                 }
2828
2829                 /* convert current frame to current field */
2830                 cfra = 2 * (cfra);
2831                 if (fieldnr) cfra++;
2832
2833                 /* transform to images space */
2834                 framenr = (cfra + iuser->fie_ima - 2) / iuser->fie_ima;
2835                 if (framenr > iuser->frames) framenr = iuser->frames;
2836
2837                 if (iuser->cycl) {
2838                         framenr = ((framenr) % len);
2839                         while (framenr < 0) framenr += len;
2840                         if (framenr == 0) framenr = len;
2841                 }
2842
2843                 /* important to apply after else we cant loop on frames 100 - 110 for eg. */
2844                 framenr += iuser->offset;
2845
2846                 return framenr;
2847         }
2848 }
2849
2850 void BKE_image_user_frame_calc(ImageUser *iuser, int cfra, int fieldnr)
2851 {
2852         if (iuser) {
2853                 short is_in_range;
2854                 const int framenr = BKE_image_user_frame_get(iuser, cfra, fieldnr, &is_in_range);
2855
2856                 if (is_in_range) {
2857                         iuser->flag |= IMA_USER_FRAME_IN_RANGE;
2858                 }
2859                 else {
2860                         iuser->flag &= ~IMA_USER_FRAME_IN_RANGE;
2861                 }
2862
2863                 /* allows image users to handle redraws */
2864                 if (iuser->flag & IMA_ANIM_ALWAYS)
2865                         if (framenr != iuser->framenr)
2866                                 iuser->flag |= IMA_ANIM_REFRESHED;
2867
2868                 iuser->framenr = framenr;
2869                 if (iuser->ok == 0) iuser->ok = 1;
2870         }
2871 }
2872
2873 void BKE_image_user_check_frame_calc(ImageUser *iuser, int cfra, int fieldnr)
2874 {
2875         if ((iuser->flag & IMA_ANIM_ALWAYS) || (iuser->flag & IMA_NEED_FRAME_RECALC)) {
2876                 BKE_image_user_frame_calc(iuser, cfra, fieldnr);
2877
2878                 iuser->flag &= ~IMA_NEED_FRAME_RECALC;
2879         }
2880 }
2881
2882 void BKE_image_user_file_path(ImageUser *iuser, Image *ima, char *filepath)
2883 {
2884         BLI_strncpy(filepath, ima->name, FILE_MAX);
2885
2886         if (ima->source == IMA_SRC_SEQUENCE) {
2887                 char head[FILE_MAX], tail[FILE_MAX];
2888                 unsigned short numlen;
2889                 int frame = iuser ? iuser->framenr : ima->lastframe;
2890
2891                 BLI_stringdec(filepath, head, tail, &numlen);
2892                 BLI_stringenc(filepath, head, tail, numlen, frame);
2893         }
2894
2895         BLI_path_abs(filepath, ID_BLEND_PATH(G.main, &ima->id));
2896 }
2897
2898 int BKE_image_has_alpha(struct Image *image)
2899 {
2900         ImBuf *ibuf;
2901         void *lock;
2902         int planes;
2903
2904         ibuf = BKE_image_acquire_ibuf(image, NULL, &lock);
2905         planes = (ibuf ? ibuf->planes : 0);
2906         BKE_image_release_ibuf(image, lock);
2907
2908         if (planes == 32)
2909                 return 1;
2910         else
2911                 return 0;
2912 }