Merge branch 'master' into 28
[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 #include "MEM_guardedalloc.h"
44
45 #include "IMB_colormanagement.h"
46 #include "IMB_imbuf_types.h"
47 #include "IMB_imbuf.h"
48 #include "IMB_moviecache.h"
49 #include "IMB_metadata.h"
50
51 #ifdef WITH_OPENEXR
52 #  include "intern/openexr/openexr_multi.h"
53 #endif
54
55 #include "DNA_packedFile_types.h"
56 #include "DNA_scene_types.h"
57 #include "DNA_object_types.h"
58 #include "DNA_camera_types.h"
59 #include "DNA_sequence_types.h"
60 #include "DNA_brush_types.h"
61 #include "DNA_mesh_types.h"
62 #include "DNA_meshdata_types.h"
63
64 #include "BLI_blenlib.h"
65 #include "BLI_math_vector.h"
66 #include "BLI_mempool.h"
67 #include "BLI_threads.h"
68 #include "BLI_timecode.h"  /* for stamp timecode format */
69 #include "BLI_utildefines.h"
70
71 #include "BKE_bmfont.h"
72 #include "BKE_colortools.h"
73 #include "BKE_global.h"
74 #include "BKE_icons.h"
75 #include "BKE_image.h"
76 #include "BKE_library.h"
77 #include "BKE_library_query.h"
78 #include "BKE_library_remap.h"
79 #include "BKE_main.h"
80 #include "BKE_packedFile.h"
81 #include "BKE_report.h"
82 #include "BKE_scene.h"
83 #include "BKE_node.h"
84 #include "BKE_sequencer.h" /* seq_foreground_frame_get() */
85 #include "BKE_workspace.h"
86
87 #include "BLF_api.h"
88
89 #include "PIL_time.h"
90
91 #include "RE_pipeline.h"
92
93 #include "GPU_draw.h"
94
95 #include "BLI_sys_types.h" // for intptr_t support
96
97 /* for image user iteration */
98 #include "DNA_node_types.h"
99 #include "DNA_space_types.h"
100 #include "DNA_screen_types.h"
101 #include "DNA_view3d_types.h"
102
103 static SpinLock image_spin;
104
105 /* prototypes */
106 static int image_num_files(struct Image *ima);
107 static ImBuf *image_acquire_ibuf(Image *ima, ImageUser *iuser, void **r_lock);
108 static void image_update_views_format(Image *ima, ImageUser *iuser);
109 static void image_add_view(Image *ima, const char *viewname, const char *filepath);
110
111 /* max int, to indicate we don't store sequences in ibuf */
112 #define IMA_NO_INDEX    0x7FEFEFEF
113
114 /* quick lookup: supports 1 million frames, thousand passes */
115 #define IMA_MAKE_INDEX(frame, index)    (((frame) << 10) + (index))
116 #define IMA_INDEX_FRAME(index)           ((index) >> 10)
117 #if 0
118 #define IMA_INDEX_PASS(index)           (index & ~1023)
119 #endif
120
121 /* ******** IMAGE CACHE ************* */
122
123 typedef struct ImageCacheKey {
124         int index;
125 } ImageCacheKey;
126
127 static unsigned int imagecache_hashhash(const void *key_v)
128 {
129         const ImageCacheKey *key = key_v;
130         return key->index;
131 }
132
133 static bool imagecache_hashcmp(const void *a_v, const void *b_v)
134 {
135         const ImageCacheKey *a = a_v;
136         const ImageCacheKey *b = b_v;
137
138         return (a->index != b->index);
139 }
140
141 static void imagecache_keydata(void *userkey, int *framenr, int *proxy, int *render_flags)
142 {
143         ImageCacheKey *key = userkey;
144
145         *framenr = IMA_INDEX_FRAME(key->index);
146         *proxy = IMB_PROXY_NONE;
147         *render_flags = 0;
148 }
149
150 static void imagecache_put(Image *image, int index, ImBuf *ibuf)
151 {
152         ImageCacheKey key;
153
154         if (image->cache == NULL) {
155                 // char cache_name[64];
156                 // SNPRINTF(cache_name, "Image Datablock %s", image->id.name);
157
158                 image->cache = IMB_moviecache_create("Image Datablock Cache", sizeof(ImageCacheKey),
159                                                      imagecache_hashhash, imagecache_hashcmp);
160                 IMB_moviecache_set_getdata_callback(image->cache, imagecache_keydata);
161         }
162
163         key.index = index;
164
165         IMB_moviecache_put(image->cache, &key, ibuf);
166 }
167
168 static struct ImBuf *imagecache_get(Image *image, int index)
169 {
170         if (image->cache) {
171                 ImageCacheKey key;
172                 key.index = index;
173                 return IMB_moviecache_get(image->cache, &key);
174         }
175
176         return NULL;
177 }
178
179 void BKE_images_init(void)
180 {
181         BLI_spin_init(&image_spin);
182 }
183
184 void BKE_images_exit(void)
185 {
186         BLI_spin_end(&image_spin);
187 }
188
189 /* ******** IMAGE PROCESSING ************* */
190
191 static void de_interlace_ng(struct ImBuf *ibuf) /* neogeo fields */
192 {
193         struct ImBuf *tbuf1, *tbuf2;
194
195         if (ibuf == NULL) return;
196         if (ibuf->flags & IB_fields) return;
197         ibuf->flags |= IB_fields;
198
199         if (ibuf->rect) {
200                 /* make copies */
201                 tbuf1 = IMB_allocImBuf(ibuf->x, (ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
202                 tbuf2 = IMB_allocImBuf(ibuf->x, (ibuf->y >> 1), (unsigned char)32, (int)IB_rect);
203
204                 ibuf->x *= 2;
205
206                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
207                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
208
209                 ibuf->x /= 2;
210                 IMB_rectcpy(ibuf, tbuf1, 0, 0, 0, 0, tbuf1->x, tbuf1->y);
211                 IMB_rectcpy(ibuf, tbuf2, 0, tbuf2->y, 0, 0, tbuf2->x, tbuf2->y);
212
213                 IMB_freeImBuf(tbuf1);
214                 IMB_freeImBuf(tbuf2);
215         }
216         ibuf->y /= 2;
217 }
218
219 static void de_interlace_st(struct ImBuf *ibuf) /* standard fields */
220 {
221         struct ImBuf *tbuf1, *tbuf2;
222
223         if (ibuf == NULL) return;
224         if (ibuf->flags & IB_fields) return;
225         ibuf->flags |= IB_fields;
226
227         if (ibuf->rect) {
228                 /* make copies */
229                 tbuf1 = IMB_allocImBuf(ibuf->x, (ibuf->y >> 1), (unsigned char)32, IB_rect);
230                 tbuf2 = IMB_allocImBuf(ibuf->x, (ibuf->y >> 1), (unsigned char)32, IB_rect);
231
232                 ibuf->x *= 2;
233
234                 IMB_rectcpy(tbuf1, ibuf, 0, 0, 0, 0, ibuf->x, ibuf->y);
235                 IMB_rectcpy(tbuf2, ibuf, 0, 0, tbuf2->x, 0, ibuf->x, ibuf->y);
236
237                 ibuf->x /= 2;
238                 IMB_rectcpy(ibuf, tbuf2, 0, 0, 0, 0, tbuf2->x, tbuf2->y);
239                 IMB_rectcpy(ibuf, tbuf1, 0, tbuf2->y, 0, 0, tbuf1->x, tbuf1->y);
240
241                 IMB_freeImBuf(tbuf1);
242                 IMB_freeImBuf(tbuf2);
243         }
244         ibuf->y /= 2;
245 }
246
247 void BKE_image_de_interlace(Image *ima, int odd)
248 {
249         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
250         if (ibuf) {
251                 if (odd)
252                         de_interlace_st(ibuf);
253                 else
254                         de_interlace_ng(ibuf);
255         }
256         BKE_image_release_ibuf(ima, ibuf, NULL);
257 }
258
259 /* ***************** ALLOC & FREE, DATA MANAGING *************** */
260
261 static void image_free_cached_frames(Image *image)
262 {
263         if (image->cache) {
264                 IMB_moviecache_free(image->cache);
265                 image->cache = NULL;
266         }
267 }
268
269 static void image_free_packedfiles(Image *ima)
270 {
271         while (ima->packedfiles.last) {
272                 ImagePackedFile *imapf = ima->packedfiles.last;
273                 if (imapf->packedfile) {
274                         freePackedFile(imapf->packedfile);
275                 }
276                 BLI_remlink(&ima->packedfiles, imapf);
277                 MEM_freeN(imapf);
278         }
279 }
280
281 void BKE_image_free_packedfiles(Image *ima)
282 {
283         image_free_packedfiles(ima);
284 }
285
286 void BKE_image_free_views(Image *image)
287 {
288         BLI_freelistN(&image->views);
289 }
290
291 static void image_free_anims(Image *ima)
292 {
293         while (ima->anims.last) {
294                 ImageAnim *ia = ima->anims.last;
295                 if (ia->anim) {
296                         IMB_free_anim(ia->anim);
297                         ia->anim = NULL;
298                 }
299                 BLI_remlink(&ima->anims, ia);
300                 MEM_freeN(ia);
301         }
302 }
303
304 /**
305  * Simply free the image data from memory,
306  * on display the image can load again (except for render buffers).
307  */
308 void BKE_image_free_buffers_ex(Image *ima, bool do_lock)
309 {
310         if (do_lock) {
311                 BLI_spin_lock(&image_spin);
312         }
313         image_free_cached_frames(ima);
314
315         image_free_anims(ima);
316
317         if (ima->rr) {
318                 RE_FreeRenderResult(ima->rr);
319                 ima->rr = NULL;
320         }
321
322         if (!G.background) {
323                 /* Background mode doesn't use opnegl,
324                  * so we can avoid freeing GPU images and save some
325                  * time by skipping mutex lock.
326                  */
327                 GPU_free_image(ima);
328         }
329
330         ima->ok = IMA_OK;
331
332         if (do_lock) {
333                 BLI_spin_unlock(&image_spin);
334         }
335 }
336
337 void BKE_image_free_buffers(Image *ima)
338 {
339         BKE_image_free_buffers_ex(ima, false);
340 }
341
342 /** Free (or release) any data used by this image (does not free the image itself). */
343 void BKE_image_free(Image *ima)
344 {
345         int a;
346
347         /* Also frees animdata. */
348         BKE_image_free_buffers(ima);
349
350         image_free_packedfiles(ima);
351
352         for (a = 0; a < IMA_MAX_RENDER_SLOT; a++) {
353                 if (ima->renders[a]) {
354                         RE_FreeRenderResult(ima->renders[a]);
355                         ima->renders[a] = NULL;
356                 }
357         }
358
359         BKE_image_free_views(ima);
360         MEM_SAFE_FREE(ima->stereo3d_format);
361
362         BKE_icon_id_delete(&ima->id);
363         BKE_previewimg_free(&ima->preview);
364 }
365
366 /* only image block itself */
367 static void image_init(Image *ima, short source, short type)
368 {
369         BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(ima, id));
370
371         ima->ok = IMA_OK;
372
373         ima->aspx = ima->aspy = 1.0;
374         ima->gen_x = 1024; ima->gen_y = 1024;
375         ima->gen_type = IMA_GENTYPE_GRID;
376
377         ima->source = source;
378         ima->type = type;
379
380         if (source == IMA_SRC_VIEWER)
381                 ima->flag |= IMA_VIEW_AS_RENDER;
382
383         BKE_color_managed_colorspace_settings_init(&ima->colorspace_settings);
384         ima->stereo3d_format = MEM_callocN(sizeof(Stereo3dFormat), "Image Stereo Format");
385 }
386
387 void BKE_image_init(struct Image *image)
388 {
389         if (image) {
390                 image_init(image, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
391         }
392 }
393
394 static Image *image_alloc(Main *bmain, const char *name, short source, short type)
395 {
396         Image *ima;
397
398         ima = BKE_libblock_alloc(bmain, ID_IM, name, 0);
399         if (ima) {
400                 image_init(ima, source, type);
401         }
402
403         return ima;
404 }
405
406 /* Get the ibuf from an image cache by it's index and frame.
407  * Local use here only.
408  *
409  * Returns referenced image buffer if it exists, callee is to
410  * call IMB_freeImBuf to de-reference the image buffer after
411  * it's done handling it.
412  */
413 static ImBuf *image_get_cached_ibuf_for_index_frame(Image *ima, int index, int frame)
414 {
415         if (index != IMA_NO_INDEX) {
416                 index = IMA_MAKE_INDEX(frame, index);
417         }
418
419         return imagecache_get(ima, index);
420 }
421
422 /* no ima->ibuf anymore, but listbase */
423 static void image_assign_ibuf(Image *ima, ImBuf *ibuf, int index, int frame)
424 {
425         if (ibuf) {
426                 if (index != IMA_NO_INDEX)
427                         index = IMA_MAKE_INDEX(frame, index);
428
429                 imagecache_put(ima, index, ibuf);
430         }
431 }
432
433 static void copy_image_packedfiles(ListBase *lb_dst, const ListBase *lb_src)
434 {
435         const ImagePackedFile *imapf_src;
436
437         BLI_listbase_clear(lb_dst);
438         for (imapf_src = lb_src->first; imapf_src; imapf_src = imapf_src->next) {
439                 ImagePackedFile *imapf_dst = MEM_mallocN(sizeof(ImagePackedFile), "Image Packed Files (copy)");
440                 STRNCPY(imapf_dst->filepath, imapf_src->filepath);
441
442                 if (imapf_src->packedfile)
443                         imapf_dst->packedfile = dupPackedFile(imapf_src->packedfile);
444
445                 BLI_addtail(lb_dst, imapf_dst);
446         }
447 }
448
449 /**
450  * Only copy internal data of Image ID from source to already allocated/initialized destination.
451  * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
452  *
453  * WARNING! This function will not handle ID user count!
454  *
455  * \param flag  Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
456  */
457 void BKE_image_copy_data(Main *UNUSED(bmain), Image *ima_dst, const Image *ima_src, const int flag)
458 {
459         BKE_color_managed_colorspace_settings_copy(&ima_dst->colorspace_settings, &ima_src->colorspace_settings);
460
461         copy_image_packedfiles(&ima_dst->packedfiles, &ima_src->packedfiles);
462
463         ima_dst->stereo3d_format = MEM_dupallocN(ima_src->stereo3d_format);
464         BLI_duplicatelist(&ima_dst->views, &ima_src->views);
465
466         /* Cleanup stuff that cannot be copied. */
467         ima_dst->cache = NULL;
468         ima_dst->rr = NULL;
469         for (int i = 0; i < IMA_MAX_RENDER_SLOT; i++) {
470                 ima_dst->renders[i] = NULL;
471         }
472
473         BLI_listbase_clear(&ima_dst->anims);
474
475         for (int i = 0; i < TEXTARGET_COUNT; i++) {
476                 ima_dst->bindcode[i] = 0;
477                 ima_dst->gputexture[i] = NULL;
478         }
479
480         if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
481                 BKE_previewimg_id_copy(&ima_dst->id, &ima_src->id);
482         }
483         else {
484                 ima_dst->preview = NULL;
485         }
486 }
487
488 /* empty image block, of similar type and filename */
489 Image *BKE_image_copy(Main *bmain, const Image *ima)
490 {
491         Image *ima_copy;
492         BKE_id_copy_ex(bmain, &ima->id, (ID **)&ima_copy, 0, false);
493         return ima_copy;
494 }
495
496 void BKE_image_make_local(Main *bmain, Image *ima, const bool lib_local)
497 {
498         BKE_id_make_local_generic(bmain, &ima->id, true, lib_local);
499 }
500
501 void BKE_image_merge(Image *dest, Image *source)
502 {
503         /* sanity check */
504         if (dest && source && dest != source) {
505                 BLI_spin_lock(&image_spin);
506                 if (source->cache != NULL) {
507                         struct MovieCacheIter *iter;
508                         iter = IMB_moviecacheIter_new(source->cache);
509                         while (!IMB_moviecacheIter_done(iter)) {
510                                 ImBuf *ibuf = IMB_moviecacheIter_getImBuf(iter);
511                                 ImageCacheKey *key = IMB_moviecacheIter_getUserKey(iter);
512                                 imagecache_put(dest, key->index, ibuf);
513                                 IMB_moviecacheIter_step(iter);
514                         }
515                         IMB_moviecacheIter_free(iter);
516                 }
517                 BLI_spin_unlock(&image_spin);
518
519                 BKE_libblock_free(G.main, source);
520         }
521 }
522
523 /* note, we could be clever and scale all imbuf's but since some are mipmaps its not so simple */
524 bool BKE_image_scale(Image *image, int width, int height)
525 {
526         ImBuf *ibuf;
527         void *lock;
528
529         ibuf = BKE_image_acquire_ibuf(image, NULL, &lock);
530
531         if (ibuf) {
532                 IMB_scaleImBuf(ibuf, width, height);
533                 ibuf->userflags |= IB_BITMAPDIRTY;
534         }
535
536         BKE_image_release_ibuf(image, ibuf, lock);
537
538         return (ibuf != NULL);
539 }
540
541 bool BKE_image_has_bindcode(Image *ima)
542 {
543         bool has_bindcode = false;
544         for (int i = 0; i < TEXTARGET_COUNT; i++) {
545                 if (ima->bindcode[i]) {
546                         has_bindcode = true;
547                         break;
548                 }
549         }
550         return has_bindcode;
551 }
552
553 static void image_init_color_management(Image *ima)
554 {
555         ImBuf *ibuf;
556         char name[FILE_MAX];
557
558         BKE_image_user_file_path(NULL, ima, name);
559
560         /* will set input color space to image format default's */
561         ibuf = IMB_loadiffname(name, IB_test | IB_alphamode_detect, ima->colorspace_settings.name);
562
563         if (ibuf) {
564                 if (ibuf->flags & IB_alphamode_premul)
565                         ima->alpha_mode = IMA_ALPHA_PREMUL;
566                 else
567                         ima->alpha_mode = IMA_ALPHA_STRAIGHT;
568
569                 IMB_freeImBuf(ibuf);
570         }
571 }
572
573 char BKE_image_alpha_mode_from_extension_ex(const char *filepath)
574 {
575         if (BLI_testextensie_n(filepath, ".exr", ".cin", ".dpx", ".hdr", NULL)) {
576                 return IMA_ALPHA_PREMUL;
577         }
578         else {
579                 return IMA_ALPHA_STRAIGHT;
580         }
581 }
582
583 void BKE_image_alpha_mode_from_extension(Image *image)
584 {
585         image->alpha_mode = BKE_image_alpha_mode_from_extension_ex(image->name);
586 }
587
588 Image *BKE_image_load(Main *bmain, const char *filepath)
589 {
590         Image *ima;
591         int file;
592         char str[FILE_MAX];
593
594         STRNCPY(str, filepath);
595         BLI_path_abs(str, bmain->name);
596
597         /* exists? */
598         file = BLI_open(str, O_BINARY | O_RDONLY, 0);
599         if (file == -1)
600                 return NULL;
601         close(file);
602
603         ima = image_alloc(bmain, BLI_path_basename(filepath), IMA_SRC_FILE, IMA_TYPE_IMAGE);
604         STRNCPY(ima->name, filepath);
605
606         if (BLI_testextensie_array(filepath, imb_ext_movie))
607                 ima->source = IMA_SRC_MOVIE;
608
609         image_init_color_management(ima);
610
611         return ima;
612 }
613
614 /* checks if image was already loaded, then returns same image */
615 /* otherwise creates new. */
616 /* does not load ibuf itself */
617 /* pass on optional frame for #name images */
618 Image *BKE_image_load_exists_ex(const char *filepath, bool *r_exists)
619 {
620         Image *ima;
621         char str[FILE_MAX], strtest[FILE_MAX];
622
623         STRNCPY(str, filepath);
624         BLI_path_abs(str, G.main->name);
625
626         /* first search an identical filepath */
627         for (ima = G.main->image.first; ima; ima = ima->id.next) {
628                 if (ima->source != IMA_SRC_VIEWER && ima->source != IMA_SRC_GENERATED) {
629                         STRNCPY(strtest, ima->name);
630                         BLI_path_abs(strtest, ID_BLEND_PATH(G.main, &ima->id));
631
632                         if (BLI_path_cmp(strtest, str) == 0) {
633                                 if ((BKE_image_has_anim(ima) == false) ||
634                                     (ima->id.us == 0))
635                                 {
636                                         id_us_plus(&ima->id);  /* officially should not, it doesn't link here! */
637                                         if (ima->ok == 0)
638                                                 ima->ok = IMA_OK;
639                                         if (r_exists)
640                                                 *r_exists = true;
641                                         return ima;
642                                 }
643                         }
644                 }
645         }
646
647         if (r_exists)
648                 *r_exists = false;
649         return BKE_image_load(G.main, filepath);
650 }
651
652 Image *BKE_image_load_exists(const char *filepath)
653 {
654         return BKE_image_load_exists_ex(filepath, NULL);
655 }
656
657 static ImBuf *add_ibuf_size(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short gen_type,
658                             const float color[4], ColorManagedColorspaceSettings *colorspace_settings)
659 {
660         ImBuf *ibuf;
661         unsigned char *rect = NULL;
662         float *rect_float = NULL;
663
664         if (floatbuf) {
665                 ibuf = IMB_allocImBuf(width, height, depth, IB_rectfloat);
666
667                 if (colorspace_settings->name[0] == '\0') {
668                         const char *colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_FLOAT);
669
670                         STRNCPY(colorspace_settings->name, colorspace);
671                 }
672
673                 if (ibuf != NULL) {
674                         rect_float = ibuf->rect_float;
675                         IMB_colormanagement_check_is_data(ibuf, colorspace_settings->name);
676                 }
677         }
678         else {
679                 ibuf = IMB_allocImBuf(width, height, depth, IB_rect);
680
681                 if (colorspace_settings->name[0] == '\0') {
682                         const char *colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_BYTE);
683
684                         STRNCPY(colorspace_settings->name, colorspace);
685                 }
686
687                 if (ibuf != NULL) {
688                         rect = (unsigned char *)ibuf->rect;
689                         IMB_colormanagement_assign_rect_colorspace(ibuf, colorspace_settings->name);
690                 }
691         }
692
693         if (!ibuf) {
694                 return NULL;
695         }
696
697         STRNCPY(ibuf->name, name);
698         ibuf->userflags |= IB_BITMAPDIRTY;
699
700         switch (gen_type) {
701                 case IMA_GENTYPE_GRID:
702                         BKE_image_buf_fill_checker(rect, rect_float, width, height);
703                         break;
704                 case IMA_GENTYPE_GRID_COLOR:
705                         BKE_image_buf_fill_checker_color(rect, rect_float, width, height);
706                         break;
707                 default:
708                         BKE_image_buf_fill_color(rect, rect_float, width, height, color);
709                         break;
710         }
711
712         return ibuf;
713 }
714
715 /* adds new image block, creates ImBuf and initializes color */
716 Image *BKE_image_add_generated(
717         Main *bmain, unsigned int width, unsigned int height, const char *name,
718         int depth, int floatbuf, short gen_type, const float color[4], const bool stereo3d)
719 {
720         /* on save, type is changed to FILE in editsima.c */
721         Image *ima = image_alloc(bmain, name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
722
723         if (ima) {
724                 int view_id;
725                 const char *names[2] = {STEREO_LEFT_NAME, STEREO_RIGHT_NAME};
726
727                 /* STRNCPY(ima->name, name); */ /* don't do this, this writes in ain invalid filepath! */
728                 ima->gen_x = width;
729                 ima->gen_y = height;
730                 ima->gen_type = gen_type;
731                 ima->gen_flag |= (floatbuf ? IMA_GEN_FLOAT : 0);
732                 ima->gen_depth = depth;
733                 copy_v4_v4(ima->gen_color, color);
734
735                 for (view_id = 0; view_id < 2; view_id++) {
736                         ImBuf *ibuf;
737                         ibuf = add_ibuf_size(width, height, ima->name, depth, floatbuf, gen_type, color, &ima->colorspace_settings);
738                         image_assign_ibuf(ima, ibuf, stereo3d ? view_id : IMA_NO_INDEX, 0);
739
740                         /* image_assign_ibuf puts buffer to the cache, which increments user counter. */
741                         IMB_freeImBuf(ibuf);
742                         if (!stereo3d) break;
743
744                         image_add_view(ima, names[view_id], "");
745                 }
746
747                 ima->ok = IMA_OK_LOADED;
748         }
749
750         return ima;
751 }
752
753 /* Create an image image from ibuf. The refcount of ibuf is increased,
754  * caller should take care to drop its reference by calling
755  * IMB_freeImBuf if needed. */
756 Image *BKE_image_add_from_imbuf(ImBuf *ibuf, const char *name)
757 {
758         /* on save, type is changed to FILE in editsima.c */
759         Image *ima;
760
761         if (name == NULL) {
762                 name = BLI_path_basename(ibuf->name);
763         }
764
765         ima = image_alloc(G.main, name, IMA_SRC_FILE, IMA_TYPE_IMAGE);
766
767         if (ima) {
768                 STRNCPY(ima->name, ibuf->name);
769                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
770                 ima->ok = IMA_OK_LOADED;
771         }
772
773         return ima;
774 }
775
776 /* packs rects from memory as PNG
777  * convert multiview images to R_IMF_VIEWS_INDIVIDUAL
778  */
779 static void image_memorypack_multiview(Image *ima)
780 {
781         ImageView *iv;
782         int i;
783
784         image_free_packedfiles(ima);
785
786         for (i = 0, iv = ima->views.first; iv; iv = iv->next, i++) {
787                 ImBuf *ibuf = image_get_cached_ibuf_for_index_frame(ima, i, 0);
788
789                 ibuf->ftype = IMB_FTYPE_PNG;
790                 ibuf->planes = R_IMF_PLANES_RGBA;
791
792                 /* if the image was a R_IMF_VIEWS_STEREO_3D we force _L, _R suffices */
793                 if (ima->views_format == R_IMF_VIEWS_STEREO_3D) {
794                         const char *suffix[2] = {STEREO_LEFT_SUFFIX, STEREO_RIGHT_SUFFIX};
795                         BLI_path_suffix(iv->filepath, FILE_MAX, suffix[i], "");
796                 }
797
798                 IMB_saveiff(ibuf, iv->filepath, IB_rect | IB_mem);
799
800                 if (ibuf->encodedbuffer == NULL) {
801                         printf("memory save for pack error\n");
802                         IMB_freeImBuf(ibuf);
803                         image_free_packedfiles(ima);
804                         return;
805                 }
806                 else {
807                         ImagePackedFile *imapf;
808                         PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
809
810                         pf->data = ibuf->encodedbuffer;
811                         pf->size = ibuf->encodedsize;
812
813                         imapf = MEM_mallocN(sizeof(ImagePackedFile), "Image PackedFile");
814                         STRNCPY(imapf->filepath, iv->filepath);
815                         imapf->packedfile = pf;
816                         BLI_addtail(&ima->packedfiles, imapf);
817
818                         ibuf->encodedbuffer = NULL;
819                         ibuf->encodedsize = 0;
820                         ibuf->userflags &= ~IB_BITMAPDIRTY;
821                 }
822                 IMB_freeImBuf(ibuf);
823         }
824
825         if (ima->source == IMA_SRC_GENERATED) {
826                 ima->source = IMA_SRC_FILE;
827                 ima->type = IMA_TYPE_IMAGE;
828         }
829         ima->views_format = R_IMF_VIEWS_INDIVIDUAL;
830 }
831
832 /* packs rect from memory as PNG */
833 void BKE_image_memorypack(Image *ima)
834 {
835         ImBuf *ibuf;
836
837         if (BKE_image_is_multiview(ima)) {
838                 image_memorypack_multiview(ima);
839                 return;
840         }
841
842         ibuf = image_get_cached_ibuf_for_index_frame(ima, IMA_NO_INDEX, 0);
843
844         if (ibuf == NULL)
845                 return;
846
847         image_free_packedfiles(ima);
848
849         ibuf->ftype = IMB_FTYPE_PNG;
850         ibuf->planes = R_IMF_PLANES_RGBA;
851
852         IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem);
853         if (ibuf->encodedbuffer == NULL) {
854                 printf("memory save for pack error\n");
855         }
856         else {
857                 ImagePackedFile *imapf;
858                 PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
859
860                 pf->data = ibuf->encodedbuffer;
861                 pf->size = ibuf->encodedsize;
862
863                 imapf = MEM_mallocN(sizeof(ImagePackedFile), "Image PackedFile");
864                 STRNCPY(imapf->filepath, ima->name);
865                 imapf->packedfile = pf;
866                 BLI_addtail(&ima->packedfiles, imapf);
867
868                 ibuf->encodedbuffer = NULL;
869                 ibuf->encodedsize = 0;
870                 ibuf->userflags &= ~IB_BITMAPDIRTY;
871
872                 if (ima->source == IMA_SRC_GENERATED) {
873                         ima->source = IMA_SRC_FILE;
874                         ima->type = IMA_TYPE_IMAGE;
875                 }
876         }
877
878         IMB_freeImBuf(ibuf);
879 }
880
881 void BKE_image_packfiles(ReportList *reports, Image *ima, const char *basepath)
882 {
883         const int totfiles = image_num_files(ima);
884
885         if (totfiles == 1) {
886                 ImagePackedFile *imapf = MEM_mallocN(sizeof(ImagePackedFile), "Image packed file");
887                 BLI_addtail(&ima->packedfiles, imapf);
888                 imapf->packedfile = newPackedFile(reports, ima->name, basepath);
889                 if (imapf->packedfile) {
890                         STRNCPY(imapf->filepath, ima->name);
891                 }
892                 else {
893                         BLI_freelinkN(&ima->packedfiles, imapf);
894                 }
895         }
896         else {
897                 ImageView *iv;
898                 for (iv = ima->views.first; iv; iv = iv->next) {
899                         ImagePackedFile *imapf = MEM_mallocN(sizeof(ImagePackedFile), "Image packed file");
900                         BLI_addtail(&ima->packedfiles, imapf);
901
902                         imapf->packedfile = newPackedFile(reports, iv->filepath, basepath);
903                         if (imapf->packedfile) {
904                                 STRNCPY(imapf->filepath, iv->filepath);
905                         }
906                         else {
907                                 BLI_freelinkN(&ima->packedfiles, imapf);
908                         }
909                 }
910         }
911 }
912
913 void BKE_image_packfiles_from_mem(ReportList *reports, Image *ima, char *data, const size_t data_len)
914 {
915         const int totfiles = image_num_files(ima);
916
917         if (totfiles != 1) {
918                 BKE_report(reports, RPT_ERROR, "Cannot pack multiview images from raw data currently...");
919         }
920         else {
921                 ImagePackedFile *imapf = MEM_mallocN(sizeof(ImagePackedFile), __func__);
922                 BLI_addtail(&ima->packedfiles, imapf);
923                 imapf->packedfile = newPackedFileMemory(data, data_len);
924                 STRNCPY(imapf->filepath, ima->name);
925         }
926 }
927
928 void BKE_image_tag_time(Image *ima)
929 {
930         ima->lastused = PIL_check_seconds_timer_i();
931 }
932
933 #if 0
934 static void tag_all_images_time()
935 {
936         Image *ima;
937         int ctime = PIL_check_seconds_timer_i();
938
939         ima = G.main->image.first;
940         while (ima) {
941                 if (ima->bindcode || ima->repbind || ima->ibufs.first) {
942                         ima->lastused = ctime;
943                 }
944         }
945 }
946 #endif
947
948 static uintptr_t image_mem_size(Image *image)
949 {
950         uintptr_t size = 0;
951
952         /* viewers have memory depending on other rules, has no valid rect pointer */
953         if (image->source == IMA_SRC_VIEWER)
954                 return 0;
955
956         BLI_spin_lock(&image_spin);
957         if (image->cache != NULL) {
958                 struct MovieCacheIter *iter = IMB_moviecacheIter_new(image->cache);
959
960                 while (!IMB_moviecacheIter_done(iter)) {
961                         ImBuf *ibuf = IMB_moviecacheIter_getImBuf(iter);
962                         ImBuf *ibufm;
963                         int level;
964
965                         if (ibuf->rect) {
966                                 size += MEM_allocN_len(ibuf->rect);
967                         }
968                         if (ibuf->rect_float) {
969                                 size += MEM_allocN_len(ibuf->rect_float);
970                         }
971
972                         for (level = 0; level < IMB_MIPMAP_LEVELS; level++) {
973                                 ibufm = ibuf->mipmap[level];
974                                 if (ibufm) {
975                                         if (ibufm->rect) {
976                                                 size += MEM_allocN_len(ibufm->rect);
977                                         }
978                                         if (ibufm->rect_float) {
979                                                 size += MEM_allocN_len(ibufm->rect_float);
980                                         }
981                                 }
982                         }
983
984                         IMB_moviecacheIter_step(iter);
985                 }
986                 IMB_moviecacheIter_free(iter);
987         }
988         BLI_spin_unlock(&image_spin);
989
990         return size;
991 }
992
993 void BKE_image_print_memlist(void)
994 {
995         Image *ima;
996         uintptr_t size, totsize = 0;
997
998         for (ima = G.main->image.first; ima; ima = ima->id.next)
999                 totsize += image_mem_size(ima);
1000
1001         printf("\ntotal image memory len: %.3f MB\n", (double)totsize / (double)(1024 * 1024));
1002
1003         for (ima = G.main->image.first; ima; ima = ima->id.next) {
1004                 size = image_mem_size(ima);
1005
1006                 if (size)
1007                         printf("%s len: %.3f MB\n", ima->id.name + 2, (double)size / (double)(1024 * 1024));
1008         }
1009 }
1010
1011 static bool imagecache_check_dirty(ImBuf *ibuf, void *UNUSED(userkey), void *UNUSED(userdata))
1012 {
1013         return (ibuf->userflags & IB_BITMAPDIRTY) == 0;
1014 }
1015
1016 void BKE_image_free_all_textures(void)
1017 {
1018 #undef CHECK_FREED_SIZE
1019
1020         Tex *tex;
1021         Image *ima;
1022 #ifdef CHECK_FREED_SIZE
1023         uintptr_t tot_freed_size = 0;
1024 #endif
1025
1026         for (ima = G.main->image.first; ima; ima = ima->id.next)
1027                 ima->id.tag &= ~LIB_TAG_DOIT;
1028
1029         for (tex = G.main->tex.first; tex; tex = tex->id.next)
1030                 if (tex->ima)
1031                         tex->ima->id.tag |= LIB_TAG_DOIT;
1032
1033         for (ima = G.main->image.first; ima; ima = ima->id.next) {
1034                 if (ima->cache && (ima->id.tag & LIB_TAG_DOIT)) {
1035 #ifdef CHECK_FREED_SIZE
1036                         uintptr_t old_size = image_mem_size(ima);
1037 #endif
1038
1039                         IMB_moviecache_cleanup(ima->cache, imagecache_check_dirty, NULL);
1040
1041 #ifdef CHECK_FREED_SIZE
1042                         tot_freed_size += old_size - image_mem_size(ima);
1043 #endif
1044                 }
1045         }
1046 #ifdef CHECK_FREED_SIZE
1047         printf("%s: freed total %lu MB\n", __func__, tot_freed_size / (1024 * 1024));
1048 #endif
1049 }
1050
1051 static bool imagecache_check_free_anim(ImBuf *ibuf, void *UNUSED(userkey), void *userdata)
1052 {
1053         int except_frame = *(int *)userdata;
1054         return (ibuf->userflags & IB_BITMAPDIRTY) == 0 &&
1055                (ibuf->index != IMA_NO_INDEX) &&
1056                (except_frame != IMA_INDEX_FRAME(ibuf->index));
1057 }
1058
1059 /* except_frame is weak, only works for seqs without offset... */
1060 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
1061 {
1062         BLI_spin_lock(&image_spin);
1063         if (ima->cache != NULL) {
1064                 IMB_moviecache_cleanup(ima->cache, imagecache_check_free_anim, &except_frame);
1065         }
1066         BLI_spin_unlock(&image_spin);
1067 }
1068
1069 void BKE_image_all_free_anim_ibufs(int cfra)
1070 {
1071         Image *ima;
1072
1073         for (ima = G.main->image.first; ima; ima = ima->id.next)
1074                 if (BKE_image_is_animated(ima))
1075                         BKE_image_free_anim_ibufs(ima, cfra);
1076 }
1077
1078
1079 /* *********** READ AND WRITE ************** */
1080
1081 int BKE_image_imtype_to_ftype(const char imtype, ImbFormatOptions *r_options)
1082 {
1083         memset(r_options, 0, sizeof(*r_options));
1084
1085         if (imtype == R_IMF_IMTYPE_TARGA) {
1086                 return IMB_FTYPE_TGA;
1087         }
1088         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
1089                 r_options->flag = RAWTGA;
1090                 return IMB_FTYPE_TGA;
1091         }
1092         else if (imtype == R_IMF_IMTYPE_IRIS) {
1093                 return IMB_FTYPE_IMAGIC;
1094         }
1095 #ifdef WITH_HDR
1096         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1097                 return IMB_FTYPE_RADHDR;
1098         }
1099 #endif
1100         else if (imtype == R_IMF_IMTYPE_PNG) {
1101                 r_options->quality = 15;
1102                 return IMB_FTYPE_PNG;
1103         }
1104 #ifdef WITH_DDS
1105         else if (imtype == R_IMF_IMTYPE_DDS) {
1106                 return IMB_FTYPE_DDS;
1107         }
1108 #endif
1109         else if (imtype == R_IMF_IMTYPE_BMP) {
1110                 return IMB_FTYPE_BMP;
1111         }
1112 #ifdef WITH_TIFF
1113         else if (imtype == R_IMF_IMTYPE_TIFF) {
1114                 return IMB_FTYPE_TIF;
1115         }
1116 #endif
1117         else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER) {
1118                 return IMB_FTYPE_OPENEXR;
1119         }
1120 #ifdef WITH_CINEON
1121         else if (imtype == R_IMF_IMTYPE_CINEON) {
1122                 return IMB_FTYPE_CINEON;
1123         }
1124         else if (imtype == R_IMF_IMTYPE_DPX) {
1125                 return IMB_FTYPE_DPX;
1126         }
1127 #endif
1128 #ifdef WITH_OPENJPEG
1129         else if (imtype == R_IMF_IMTYPE_JP2) {
1130                 r_options->flag |= JP2_JP2;
1131                 r_options->quality = 90;
1132                 return IMB_FTYPE_JP2;
1133         }
1134 #endif
1135         else {
1136                 r_options->quality = 90;
1137                 return IMB_FTYPE_JPG;
1138         }
1139 }
1140
1141 char BKE_image_ftype_to_imtype(const int ftype, const ImbFormatOptions *options)
1142 {
1143         if (ftype == 0) {
1144                 return R_IMF_IMTYPE_TARGA;
1145         }
1146         else if (ftype == IMB_FTYPE_IMAGIC) {
1147                 return R_IMF_IMTYPE_IRIS;
1148         }
1149 #ifdef WITH_HDR
1150         else if (ftype == IMB_FTYPE_RADHDR) {
1151                 return R_IMF_IMTYPE_RADHDR;
1152         }
1153 #endif
1154         else if (ftype == IMB_FTYPE_PNG) {
1155                 return R_IMF_IMTYPE_PNG;
1156         }
1157 #ifdef WITH_DDS
1158         else if (ftype == IMB_FTYPE_DDS) {
1159                 return R_IMF_IMTYPE_DDS;
1160         }
1161 #endif
1162         else if (ftype == IMB_FTYPE_BMP) {
1163                 return R_IMF_IMTYPE_BMP;
1164         }
1165 #ifdef WITH_TIFF
1166         else if (ftype == IMB_FTYPE_TIF) {
1167                 return R_IMF_IMTYPE_TIFF;
1168         }
1169 #endif
1170         else if (ftype == IMB_FTYPE_OPENEXR) {
1171                 return R_IMF_IMTYPE_OPENEXR;
1172         }
1173 #ifdef WITH_CINEON
1174         else if (ftype == IMB_FTYPE_CINEON) {
1175                 return R_IMF_IMTYPE_CINEON;
1176         }
1177         else if (ftype == IMB_FTYPE_DPX) {
1178                 return R_IMF_IMTYPE_DPX;
1179         }
1180 #endif
1181         else if (ftype == IMB_FTYPE_TGA) {
1182                 if (options && (options->flag & RAWTGA)) {
1183                         return R_IMF_IMTYPE_RAWTGA;
1184                 }
1185                 else {
1186                         return R_IMF_IMTYPE_TARGA;
1187                 }
1188         }
1189 #ifdef WITH_OPENJPEG
1190         else if (ftype == IMB_FTYPE_JP2) {
1191                 return R_IMF_IMTYPE_JP2;
1192         }
1193 #endif
1194         else {
1195                 return R_IMF_IMTYPE_JPEG90;
1196         }
1197 }
1198
1199
1200 bool BKE_imtype_is_movie(const char imtype)
1201 {
1202         switch (imtype) {
1203                 case R_IMF_IMTYPE_AVIRAW:
1204                 case R_IMF_IMTYPE_AVIJPEG:
1205                 case R_IMF_IMTYPE_FFMPEG:
1206                 case R_IMF_IMTYPE_H264:
1207                 case R_IMF_IMTYPE_THEORA:
1208                 case R_IMF_IMTYPE_XVID:
1209                         return true;
1210         }
1211         return false;
1212 }
1213
1214 int BKE_imtype_supports_zbuf(const char imtype)
1215 {
1216         switch (imtype) {
1217                 case R_IMF_IMTYPE_IRIZ:
1218                 case R_IMF_IMTYPE_OPENEXR: /* but not R_IMF_IMTYPE_MULTILAYER */
1219                         return 1;
1220         }
1221         return 0;
1222 }
1223
1224 int BKE_imtype_supports_compress(const char imtype)
1225 {
1226         switch (imtype) {
1227                 case R_IMF_IMTYPE_PNG:
1228                         return 1;
1229         }
1230         return 0;
1231 }
1232
1233 int BKE_imtype_supports_quality(const char imtype)
1234 {
1235         switch (imtype) {
1236                 case R_IMF_IMTYPE_JPEG90:
1237                 case R_IMF_IMTYPE_JP2:
1238                 case R_IMF_IMTYPE_AVIJPEG:
1239                         return 1;
1240         }
1241         return 0;
1242 }
1243
1244 int BKE_imtype_requires_linear_float(const char imtype)
1245 {
1246         switch (imtype) {
1247                 case R_IMF_IMTYPE_CINEON:
1248                 case R_IMF_IMTYPE_DPX:
1249                 case R_IMF_IMTYPE_RADHDR:
1250                 case R_IMF_IMTYPE_OPENEXR:
1251                 case R_IMF_IMTYPE_MULTILAYER:
1252                         return true;
1253         }
1254         return 0;
1255 }
1256
1257 char BKE_imtype_valid_channels(const char imtype, bool write_file)
1258 {
1259         char chan_flag = IMA_CHAN_FLAG_RGB; /* assume all support rgb */
1260
1261         /* alpha */
1262         switch (imtype) {
1263                 case R_IMF_IMTYPE_BMP:
1264                         if (write_file) break;
1265                         ATTR_FALLTHROUGH;
1266                 case R_IMF_IMTYPE_TARGA:
1267                 case R_IMF_IMTYPE_RAWTGA:
1268                 case R_IMF_IMTYPE_IRIS:
1269                 case R_IMF_IMTYPE_PNG:
1270                 case R_IMF_IMTYPE_TIFF:
1271                 case R_IMF_IMTYPE_OPENEXR:
1272                 case R_IMF_IMTYPE_MULTILAYER:
1273                 case R_IMF_IMTYPE_DDS:
1274                 case R_IMF_IMTYPE_JP2:
1275                 case R_IMF_IMTYPE_DPX:
1276                         chan_flag |= IMA_CHAN_FLAG_ALPHA;
1277                         break;
1278         }
1279
1280         /* bw */
1281         switch (imtype) {
1282                 case R_IMF_IMTYPE_PNG:
1283                 case R_IMF_IMTYPE_JPEG90:
1284                 case R_IMF_IMTYPE_TARGA:
1285                 case R_IMF_IMTYPE_RAWTGA:
1286                 case R_IMF_IMTYPE_TIFF:
1287                 case R_IMF_IMTYPE_IRIS:
1288                         chan_flag |= IMA_CHAN_FLAG_BW;
1289                         break;
1290         }
1291
1292         return chan_flag;
1293 }
1294
1295 char BKE_imtype_valid_depths(const char imtype)
1296 {
1297         switch (imtype) {
1298                 case R_IMF_IMTYPE_RADHDR:
1299                         return R_IMF_CHAN_DEPTH_32;
1300                 case R_IMF_IMTYPE_TIFF:
1301                         return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_16;
1302                 case R_IMF_IMTYPE_OPENEXR:
1303                         return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32;
1304                 case R_IMF_IMTYPE_MULTILAYER:
1305                         return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32;
1306                 /* eeh, cineon does some strange 10bits per channel */
1307                 case R_IMF_IMTYPE_DPX:
1308                         return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_10 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
1309                 case R_IMF_IMTYPE_CINEON:
1310                         return R_IMF_CHAN_DEPTH_10;
1311                 case R_IMF_IMTYPE_JP2:
1312                         return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
1313                 case R_IMF_IMTYPE_PNG:
1314                         return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_16;
1315                 /* most formats are 8bit only */
1316                 default:
1317                         return R_IMF_CHAN_DEPTH_8;
1318         }
1319 }
1320
1321
1322 /* string is from command line --render-format arg, keep in sync with
1323  * creator_args.c help info */
1324 char BKE_imtype_from_arg(const char *imtype_arg)
1325 {
1326         if      (STREQ(imtype_arg, "TGA")) return R_IMF_IMTYPE_TARGA;
1327         else if (STREQ(imtype_arg, "IRIS")) return R_IMF_IMTYPE_IRIS;
1328 #ifdef WITH_DDS
1329         else if (STREQ(imtype_arg, "DDS")) return R_IMF_IMTYPE_DDS;
1330 #endif
1331         else if (STREQ(imtype_arg, "JPEG")) return R_IMF_IMTYPE_JPEG90;
1332         else if (STREQ(imtype_arg, "IRIZ")) return R_IMF_IMTYPE_IRIZ;
1333         else if (STREQ(imtype_arg, "RAWTGA")) return R_IMF_IMTYPE_RAWTGA;
1334         else if (STREQ(imtype_arg, "AVIRAW")) return R_IMF_IMTYPE_AVIRAW;
1335         else if (STREQ(imtype_arg, "AVIJPEG")) return R_IMF_IMTYPE_AVIJPEG;
1336         else if (STREQ(imtype_arg, "PNG")) return R_IMF_IMTYPE_PNG;
1337         else if (STREQ(imtype_arg, "BMP")) return R_IMF_IMTYPE_BMP;
1338 #ifdef WITH_HDR
1339         else if (STREQ(imtype_arg, "HDR")) return R_IMF_IMTYPE_RADHDR;
1340 #endif
1341 #ifdef WITH_TIFF
1342         else if (STREQ(imtype_arg, "TIFF")) return R_IMF_IMTYPE_TIFF;
1343 #endif
1344 #ifdef WITH_OPENEXR
1345         else if (STREQ(imtype_arg, "EXR")) return R_IMF_IMTYPE_OPENEXR;
1346         else if (STREQ(imtype_arg, "MULTILAYER")) return R_IMF_IMTYPE_MULTILAYER;
1347 #endif
1348         else if (STREQ(imtype_arg, "FFMPEG")) return R_IMF_IMTYPE_FFMPEG;
1349 #ifdef WITH_CINEON
1350         else if (STREQ(imtype_arg, "CINEON")) return R_IMF_IMTYPE_CINEON;
1351         else if (STREQ(imtype_arg, "DPX")) return R_IMF_IMTYPE_DPX;
1352 #endif
1353 #ifdef WITH_OPENJPEG
1354         else if (STREQ(imtype_arg, "JP2")) return R_IMF_IMTYPE_JP2;
1355 #endif
1356         else return R_IMF_IMTYPE_INVALID;
1357 }
1358
1359 static bool do_add_image_extension(char *string, const char imtype, const ImageFormatData *im_format)
1360 {
1361         const char *extension = NULL;
1362         const char *extension_test;
1363         (void)im_format;  /* may be unused, depends on build options */
1364
1365         if (imtype == R_IMF_IMTYPE_IRIS) {
1366                 if (!BLI_testextensie(string, extension_test = ".rgb"))
1367                         extension = extension_test;
1368         }
1369         else if (imtype == R_IMF_IMTYPE_IRIZ) {
1370                 if (!BLI_testextensie(string, extension_test = ".rgb"))
1371                         extension = extension_test;
1372         }
1373 #ifdef WITH_HDR
1374         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1375                 if (!BLI_testextensie(string, extension_test = ".hdr"))
1376                         extension = extension_test;
1377         }
1378 #endif
1379         else if (ELEM(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1380                 if (!BLI_testextensie(string, extension_test = ".png"))
1381                         extension = extension_test;
1382         }
1383 #ifdef WITH_DDS
1384         else if (imtype == R_IMF_IMTYPE_DDS) {
1385                 if (!BLI_testextensie(string, extension_test = ".dds"))
1386                         extension = extension_test;
1387         }
1388 #endif
1389         else if (ELEM(imtype, R_IMF_IMTYPE_TARGA, R_IMF_IMTYPE_RAWTGA)) {
1390                 if (!BLI_testextensie(string, extension_test = ".tga"))
1391                         extension = extension_test;
1392         }
1393         else if (imtype == R_IMF_IMTYPE_BMP) {
1394                 if (!BLI_testextensie(string, extension_test = ".bmp"))
1395                         extension = extension_test;
1396         }
1397 #ifdef WITH_TIFF
1398         else if (imtype == R_IMF_IMTYPE_TIFF) {
1399                 if (!BLI_testextensie_n(string, extension_test = ".tif", ".tiff", NULL)) {
1400                         extension = extension_test;
1401                 }
1402         }
1403 #endif
1404 #ifdef WITH_OPENIMAGEIO
1405         else if (imtype == R_IMF_IMTYPE_PSD) {
1406                 if (!BLI_testextensie(string, extension_test = ".psd"))
1407                         extension = extension_test;
1408         }
1409 #endif
1410 #ifdef WITH_OPENEXR
1411         else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER) {
1412                 if (!BLI_testextensie(string, extension_test = ".exr"))
1413                         extension = extension_test;
1414         }
1415 #endif
1416 #ifdef WITH_CINEON
1417         else if (imtype == R_IMF_IMTYPE_CINEON) {
1418                 if (!BLI_testextensie(string, extension_test = ".cin"))
1419                         extension = extension_test;
1420         }
1421         else if (imtype == R_IMF_IMTYPE_DPX) {
1422                 if (!BLI_testextensie(string, extension_test = ".dpx"))
1423                         extension = extension_test;
1424         }
1425 #endif
1426 #ifdef WITH_OPENJPEG
1427         else if (imtype == R_IMF_IMTYPE_JP2) {
1428                 if (im_format) {
1429                         if (im_format->jp2_codec == R_IMF_JP2_CODEC_JP2) {
1430                                 if (!BLI_testextensie(string, extension_test = ".jp2"))
1431                                         extension = extension_test;
1432                         }
1433                         else if (im_format->jp2_codec == R_IMF_JP2_CODEC_J2K) {
1434                                 if (!BLI_testextensie(string, extension_test = ".j2c"))
1435                                         extension = extension_test;
1436                         }
1437                         else
1438                                 BLI_assert(!"Unsupported jp2 codec was specified in im_format->jp2_codec");
1439                 }
1440                 else {
1441                         if (!BLI_testextensie(string, extension_test = ".jp2"))
1442                                 extension = extension_test;
1443                 }
1444         }
1445 #endif
1446         else { //   R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90 etc
1447                 if (!(BLI_testextensie_n(string, extension_test = ".jpg", ".jpeg", NULL)))
1448                         extension = extension_test;
1449         }
1450
1451         if (extension) {
1452                 /* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */
1453                 /* remove any other known image extension */
1454                 if (BLI_testextensie_array(string, imb_ext_image)) {
1455                         return BLI_replace_extension(string, FILE_MAX, extension);
1456                 }
1457                 else {
1458                         return BLI_ensure_extension(string, FILE_MAX, extension);
1459                 }
1460
1461         }
1462         else {
1463                 return false;
1464         }
1465 }
1466
1467 int BKE_image_path_ensure_ext_from_imformat(char *string, const ImageFormatData *im_format)
1468 {
1469         return do_add_image_extension(string, im_format->imtype, im_format);
1470 }
1471
1472 int BKE_image_path_ensure_ext_from_imtype(char *string, const char imtype)
1473 {
1474         return do_add_image_extension(string, imtype, NULL);
1475 }
1476
1477 void BKE_imformat_defaults(ImageFormatData *im_format)
1478 {
1479         memset(im_format, 0, sizeof(*im_format));
1480         im_format->planes = R_IMF_PLANES_RGBA;
1481         im_format->imtype = R_IMF_IMTYPE_PNG;
1482         im_format->depth = R_IMF_CHAN_DEPTH_8;
1483         im_format->quality = 90;
1484         im_format->compress = 15;
1485
1486         BKE_color_managed_display_settings_init(&im_format->display_settings);
1487         BKE_color_managed_view_settings_init(&im_format->view_settings);
1488 }
1489
1490 void BKE_imbuf_to_image_format(struct ImageFormatData *im_format, const ImBuf *imbuf)
1491 {
1492         int ftype        = imbuf->ftype;
1493         int custom_flags = imbuf->foptions.flag;
1494         char quality     = imbuf->foptions.quality;
1495
1496         BKE_imformat_defaults(im_format);
1497
1498         /* file type */
1499
1500         if (ftype == IMB_FTYPE_IMAGIC)
1501                 im_format->imtype = R_IMF_IMTYPE_IRIS;
1502
1503 #ifdef WITH_HDR
1504         else if (ftype == IMB_FTYPE_RADHDR)
1505                 im_format->imtype = R_IMF_IMTYPE_RADHDR;
1506 #endif
1507
1508         else if (ftype == IMB_FTYPE_PNG) {
1509                 im_format->imtype = R_IMF_IMTYPE_PNG;
1510
1511                 if (custom_flags & PNG_16BIT)
1512                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1513
1514                 im_format->compress = quality;
1515         }
1516
1517 #ifdef WITH_DDS
1518         else if (ftype == IMB_FTYPE_DDS)
1519                 im_format->imtype = R_IMF_IMTYPE_DDS;
1520 #endif
1521
1522         else if (ftype == IMB_FTYPE_BMP)
1523                 im_format->imtype = R_IMF_IMTYPE_BMP;
1524
1525 #ifdef WITH_TIFF
1526         else if (ftype == IMB_FTYPE_TIF) {
1527                 im_format->imtype = R_IMF_IMTYPE_TIFF;
1528                 if (custom_flags & TIF_16BIT)
1529                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1530                 if (custom_flags & TIF_COMPRESS_NONE)
1531                         im_format->tiff_codec = R_IMF_TIFF_CODEC_NONE;
1532                 if (custom_flags & TIF_COMPRESS_DEFLATE)
1533                         im_format->tiff_codec = R_IMF_TIFF_CODEC_DEFLATE;
1534                 if (custom_flags & TIF_COMPRESS_LZW)
1535                         im_format->tiff_codec = R_IMF_TIFF_CODEC_LZW;
1536                 if (custom_flags & TIF_COMPRESS_PACKBITS)
1537                         im_format->tiff_codec = R_IMF_TIFF_CODEC_PACKBITS;
1538         }
1539 #endif
1540
1541 #ifdef WITH_OPENEXR
1542         else if (ftype == IMB_FTYPE_OPENEXR) {
1543                 im_format->imtype = R_IMF_IMTYPE_OPENEXR;
1544                 if (custom_flags & OPENEXR_HALF)
1545                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1546                 if (custom_flags & OPENEXR_COMPRESS)
1547                         im_format->exr_codec = R_IMF_EXR_CODEC_ZIP;  // Can't determine compression
1548                 if (imbuf->zbuf_float)
1549                         im_format->flag |= R_IMF_FLAG_ZBUF;
1550         }
1551 #endif
1552
1553 #ifdef WITH_CINEON
1554         else if (ftype == IMB_FTYPE_CINEON)
1555                 im_format->imtype = R_IMF_IMTYPE_CINEON;
1556         else if (ftype == IMB_FTYPE_DPX)
1557                 im_format->imtype = R_IMF_IMTYPE_DPX;
1558 #endif
1559
1560         else if (ftype == IMB_FTYPE_TGA) {
1561                 if (custom_flags & RAWTGA)
1562                         im_format->imtype = R_IMF_IMTYPE_RAWTGA;
1563                 else
1564                         im_format->imtype = R_IMF_IMTYPE_TARGA;
1565         }
1566 #ifdef WITH_OPENJPEG
1567         else if (ftype == IMB_FTYPE_JP2) {
1568                 im_format->imtype = R_IMF_IMTYPE_JP2;
1569                 im_format->quality = quality;
1570
1571                 if (custom_flags & JP2_16BIT)
1572                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1573                 else if (custom_flags & JP2_12BIT)
1574                         im_format->depth = R_IMF_CHAN_DEPTH_12;
1575
1576                 if (custom_flags & JP2_YCC)
1577                         im_format->jp2_flag |= R_IMF_JP2_FLAG_YCC;
1578
1579                 if (custom_flags & JP2_CINE) {
1580                         im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_PRESET;
1581                         if (custom_flags & JP2_CINE_48FPS)
1582                                 im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_48;
1583                 }
1584
1585                 if (custom_flags & JP2_JP2)
1586                         im_format->jp2_codec = R_IMF_JP2_CODEC_JP2;
1587                 else if (custom_flags & JP2_J2K)
1588                         im_format->jp2_codec = R_IMF_JP2_CODEC_J2K;
1589                 else
1590                         BLI_assert(!"Unsupported jp2 codec was specified in file type");
1591         }
1592 #endif
1593
1594         else {
1595                 im_format->imtype = R_IMF_IMTYPE_JPEG90;
1596                 im_format->quality = quality;
1597         }
1598
1599         /* planes */
1600         im_format->planes = imbuf->planes;
1601 }
1602
1603
1604 #define STAMP_NAME_SIZE ((MAX_ID_NAME - 2) + 16)
1605 /* could allow access externally - 512 is for long names,
1606  * STAMP_NAME_SIZE is for id names, allowing them some room for description */
1607 typedef struct StampDataCustomField {
1608         struct StampDataCustomField *next, *prev;
1609         /* TODO(sergey): Think of better size here, maybe dynamically allocated even. */
1610         char key[512];
1611         char value[512];
1612         /* TODO(sergey): Support non-string values. */
1613 } StampDataCustomField;
1614
1615 typedef struct StampData {
1616         char file[512];
1617         char note[512];
1618         char date[512];
1619         char marker[512];
1620         char time[512];
1621         char frame[512];
1622         char frame_range[512];
1623         char camera[STAMP_NAME_SIZE];
1624         char cameralens[STAMP_NAME_SIZE];
1625         char scene[STAMP_NAME_SIZE];
1626         char strip[STAMP_NAME_SIZE];
1627         char rendertime[STAMP_NAME_SIZE];
1628         char memory[STAMP_NAME_SIZE];
1629
1630         /* Custom fields are used to put extra meta information header from render
1631          * engine to the result image.
1632          *
1633          * NOTE: This fields are not stamped onto the image. At least for now.
1634          */
1635         ListBase custom_fields;
1636 } StampData;
1637 #undef STAMP_NAME_SIZE
1638
1639 /**
1640  * \param do_prefix: Include a label like "File ", "Date ", etc. in the stamp data strings.
1641  * \param use_dynamic: Also include data that can change on a per-frame basis.
1642  */
1643 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix,
1644                       bool use_dynamic)
1645 {
1646         char text[256];
1647         struct tm *tl;
1648         time_t t;
1649
1650         if (scene->r.stamp & R_STAMP_FILENAME) {
1651                 SNPRINTF(stamp_data->file, do_prefix ? "File %s" : "%s", G.relbase_valid ? G.main->name : "<untitled>");
1652         }
1653         else {
1654                 stamp_data->file[0] = '\0';
1655         }
1656
1657         if (scene->r.stamp & R_STAMP_NOTE) {
1658                 /* Never do prefix for Note */
1659                 SNPRINTF(stamp_data->note, "%s", scene->r.stamp_udata);
1660         }
1661         else {
1662                 stamp_data->note[0] = '\0';
1663         }
1664
1665         if (scene->r.stamp & R_STAMP_DATE) {
1666                 t = time(NULL);
1667                 tl = localtime(&t);
1668                 SNPRINTF(text, "%04d/%02d/%02d %02d:%02d:%02d",
1669                          tl->tm_year + 1900, tl->tm_mon + 1, tl->tm_mday, tl->tm_hour, tl->tm_min, tl->tm_sec);
1670                 SNPRINTF(stamp_data->date, do_prefix ? "Date %s" : "%s", text);
1671         }
1672         else {
1673                 stamp_data->date[0] = '\0';
1674         }
1675
1676         if (use_dynamic && scene->r.stamp & R_STAMP_MARKER) {
1677                 const char *name = BKE_scene_find_last_marker_name(scene, CFRA);
1678
1679                 if (name) STRNCPY(text, name);
1680                 else STRNCPY(text, "<none>");
1681
1682                 SNPRINTF(stamp_data->marker, do_prefix ? "Marker %s" : "%s", text);
1683         }
1684         else {
1685                 stamp_data->marker[0] = '\0';
1686         }
1687
1688         if (use_dynamic && scene->r.stamp & R_STAMP_TIME) {
1689                 const short timecode_style = USER_TIMECODE_SMPTE_FULL;
1690                 BLI_timecode_string_from_time(text, sizeof(text), 0, FRA2TIME(scene->r.cfra), FPS, timecode_style);
1691                 SNPRINTF(stamp_data->time, do_prefix ? "Timecode %s" : "%s", text);
1692         }
1693         else {
1694                 stamp_data->time[0] = '\0';
1695         }
1696
1697         if (use_dynamic && scene->r.stamp & R_STAMP_FRAME) {
1698                 char fmtstr[32];
1699                 int digits = 1;
1700
1701                 if (scene->r.efra > 9)
1702                         digits = integer_digits_i(scene->r.efra);
1703
1704                 SNPRINTF(fmtstr, do_prefix ? "Frame %%0%di" : "%%0%di", digits);
1705                 SNPRINTF(stamp_data->frame, fmtstr, scene->r.cfra);
1706         }
1707         else {
1708                 stamp_data->frame[0] = '\0';
1709         }
1710
1711         if (scene->r.stamp & R_STAMP_FRAME_RANGE) {
1712                 SNPRINTF(stamp_data->frame_range,
1713                          do_prefix ? "Frame Range %d:%d" : "%d:%d",
1714                          scene->r.sfra, scene->r.efra);
1715         }
1716         else {
1717                 stamp_data->frame_range[0] = '\0';
1718         }
1719
1720         if (use_dynamic && scene->r.stamp & R_STAMP_CAMERA) {
1721                 SNPRINTF(stamp_data->camera, do_prefix ? "Camera %s" : "%s", camera ? camera->id.name + 2 : "<none>");
1722         }
1723         else {
1724                 stamp_data->camera[0] = '\0';
1725         }
1726
1727         if (use_dynamic && scene->r.stamp & R_STAMP_CAMERALENS) {
1728                 if (camera && camera->type == OB_CAMERA) {
1729                         SNPRINTF(text, "%.2f", ((Camera *)camera->data)->lens);
1730                 }
1731                 else {
1732                         STRNCPY(text, "<none>");
1733                 }
1734
1735                 SNPRINTF(stamp_data->cameralens, do_prefix ? "Lens %s" : "%s", text);
1736         }
1737         else {
1738                 stamp_data->cameralens[0] = '\0';
1739         }
1740
1741         if (scene->r.stamp & R_STAMP_SCENE) {
1742                 SNPRINTF(stamp_data->scene, do_prefix ? "Scene %s" : "%s", scene->id.name + 2);
1743         }
1744         else {
1745                 stamp_data->scene[0] = '\0';
1746         }
1747
1748         if (use_dynamic && scene->r.stamp & R_STAMP_SEQSTRIP) {
1749                 Sequence *seq = BKE_sequencer_foreground_frame_get(scene, scene->r.cfra);
1750
1751                 if (seq) STRNCPY(text, seq->name + 2);
1752                 else STRNCPY(text, "<none>");
1753
1754                 SNPRINTF(stamp_data->strip, do_prefix ? "Strip %s" : "%s", text);
1755         }
1756         else {
1757                 stamp_data->strip[0] = '\0';
1758         }
1759
1760         {
1761                 Render *re = RE_GetSceneRender(scene);
1762                 RenderStats *stats = re ? RE_GetStats(re) : NULL;
1763
1764                 if (use_dynamic && stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1765                         BLI_timecode_string_from_time_simple(text, sizeof(text), stats->lastframetime);
1766
1767                         SNPRINTF(stamp_data->rendertime, do_prefix ? "RenderTime %s" : "%s", text);
1768                 }
1769                 else {
1770                         stamp_data->rendertime[0] = '\0';
1771                 }
1772
1773                 if (use_dynamic && stats && (scene->r.stamp & R_STAMP_MEMORY)) {
1774                         SNPRINTF(stamp_data->memory, do_prefix ? "Peak Memory %.2fM" : "%.2fM", stats->mem_peak);
1775                 }
1776                 else {
1777                         stamp_data->memory[0] = '\0';
1778                 }
1779         }
1780         if (scene->r.stamp & R_STAMP_FRAME_RANGE) {
1781                 SNPRINTF(stamp_data->frame_range,
1782                              do_prefix ? "Frame Range %d:%d" : "%d:%d", scene->r.sfra, scene->r.efra);
1783         }
1784         else {
1785                 stamp_data->frame_range[0] = '\0';
1786         }
1787 }
1788
1789 /* Will always add prefix. */
1790 static void stampdata_from_template(StampData *stamp_data,
1791                                     const Scene *scene,
1792                                     const StampData *stamp_data_template)
1793 {
1794         if (scene->r.stamp & R_STAMP_FILENAME) {
1795                 SNPRINTF(stamp_data->file, "File %s", stamp_data_template->file);
1796         }
1797         else {
1798                 stamp_data->file[0] = '\0';
1799         }
1800         if (scene->r.stamp & R_STAMP_NOTE) {
1801                 SNPRINTF(stamp_data->note, "%s", stamp_data_template->note);
1802         }
1803         else {
1804                 stamp_data->note[0] = '\0';
1805         }
1806         if (scene->r.stamp & R_STAMP_DATE) {
1807                 SNPRINTF(stamp_data->date, "Date %s", stamp_data_template->date);
1808         }
1809         else {
1810                 stamp_data->date[0] = '\0';
1811         }
1812         if (scene->r.stamp & R_STAMP_MARKER) {
1813                 SNPRINTF(stamp_data->marker, "Marker %s", stamp_data_template->marker);
1814         }
1815         else {
1816                 stamp_data->marker[0] = '\0';
1817         }
1818         if (scene->r.stamp & R_STAMP_TIME) {
1819                 SNPRINTF(stamp_data->time, "Timecode %s", stamp_data_template->time);
1820         }
1821         else {
1822                 stamp_data->time[0] = '\0';
1823         }
1824         if (scene->r.stamp & R_STAMP_FRAME) {
1825                 SNPRINTF(stamp_data->frame, "Frame %s", stamp_data_template->frame);
1826         }
1827         else {
1828                 stamp_data->frame[0] = '\0';
1829         }
1830         if (scene->r.stamp & R_STAMP_CAMERA) {
1831                 SNPRINTF(stamp_data->camera, "Camera %s", stamp_data_template->camera);
1832         }
1833         else {
1834                 stamp_data->camera[0] = '\0';
1835         }
1836         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1837                 SNPRINTF(stamp_data->cameralens, "Lens %s", stamp_data_template->cameralens);
1838         }
1839         else {
1840                 stamp_data->cameralens[0] = '\0';
1841         }
1842         if (scene->r.stamp & R_STAMP_SCENE) {
1843                 SNPRINTF(stamp_data->scene, "Scene %s", stamp_data_template->scene);
1844         }
1845         else {
1846                 stamp_data->scene[0] = '\0';
1847         }
1848         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1849                 SNPRINTF(stamp_data->strip, "Strip %s", stamp_data_template->strip);
1850         }
1851         else {
1852                 stamp_data->strip[0] = '\0';
1853         }
1854         if (scene->r.stamp & R_STAMP_RENDERTIME) {
1855                 SNPRINTF(stamp_data->rendertime, "RenderTime %s", stamp_data_template->rendertime);
1856         }
1857         else {
1858                 stamp_data->rendertime[0] = '\0';
1859         }
1860         if (scene->r.stamp & R_STAMP_MEMORY) {
1861                 SNPRINTF(stamp_data->memory, "Peak Memory %s", stamp_data_template->memory);
1862         }
1863         else {
1864                 stamp_data->memory[0] = '\0';
1865         }
1866 }
1867
1868 void BKE_image_stamp_buf(
1869         Scene *scene, Object *camera, const StampData *stamp_data_template,
1870         unsigned char *rect, float *rectf, int width, int height, int channels)
1871 {
1872         struct StampData stamp_data;
1873         float w, h, pad;
1874         int x, y, y_ofs;
1875         float h_fixed;
1876         const int mono = blf_mono_font_render; // XXX
1877         struct ColorManagedDisplay *display;
1878         const char *display_device;
1879
1880         /* vars for calculating wordwrap */
1881         struct {
1882                 struct ResultBLF info;
1883                 rctf rect;
1884         } wrap;
1885
1886         /* this could be an argument if we want to operate on non linear float imbuf's
1887          * for now though this is only used for renders which use scene settings */
1888
1889 #define TEXT_SIZE_CHECK(str, w, h) \
1890         ((str[0]) && ((void)(h = h_fixed), (w = BLF_width(mono, str, sizeof(str)))))
1891
1892         /* must enable BLF_WORD_WRAP before using */
1893 #define TEXT_SIZE_CHECK_WORD_WRAP(str, w, h) \
1894         ((str[0]) && (BLF_boundbox_ex(mono, str, sizeof(str), &wrap.rect, &wrap.info), \
1895          (void)(h = h_fixed * wrap.info.lines), (w = BLI_rctf_size_x(&wrap.rect))))
1896
1897 #define BUFF_MARGIN_X 2
1898 #define BUFF_MARGIN_Y 1
1899
1900         if (!rect && !rectf)
1901                 return;
1902
1903         display_device = scene->display_settings.display_device;
1904         display = IMB_colormanagement_display_get_named(display_device);
1905
1906         if (stamp_data_template == NULL) {
1907                 stampdata(scene, camera, &stamp_data, (scene->r.stamp & R_STAMP_HIDE_LABELS) == 0, true);
1908         }
1909         else {
1910                 stampdata_from_template(&stamp_data, scene, stamp_data_template);
1911         }
1912
1913         /* TODO, do_versions */
1914         if (scene->r.stamp_font_id < 8)
1915                 scene->r.stamp_font_id = 12;
1916
1917         /* set before return */
1918         BLF_size(mono, scene->r.stamp_font_id, 72);
1919         BLF_wordwrap(mono, width - (BUFF_MARGIN_X * 2));
1920
1921         BLF_buffer(mono, rectf, rect, width, height, channels, display);
1922         BLF_buffer_col(mono, scene->r.fg_stamp);
1923         pad = BLF_width_max(mono);
1924
1925         /* use 'h_fixed' rather than 'h', aligns better */
1926         h_fixed = BLF_height_max(mono);
1927         y_ofs = -BLF_descender(mono);
1928
1929         x = 0;
1930         y = height;
1931
1932         if (TEXT_SIZE_CHECK(stamp_data.file, w, h)) {
1933                 /* Top left corner */
1934                 y -= h;
1935
1936                 /* also a little of space to the background. */
1937                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1938                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1939
1940                 /* and draw the text. */
1941                 BLF_position(mono, x, y + y_ofs, 0.0);
1942                 BLF_draw_buffer(mono, stamp_data.file, BLF_DRAW_STR_DUMMY_MAX);
1943
1944                 /* the extra pixel for background. */
1945                 y -= BUFF_MARGIN_Y * 2;
1946         }
1947
1948         /* Top left corner, below File */
1949         if (TEXT_SIZE_CHECK(stamp_data.date, w, h)) {
1950                 y -= h;
1951
1952                 /* and space for background. */
1953                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1954                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1955
1956                 BLF_position(mono, x, y + y_ofs, 0.0);
1957                 BLF_draw_buffer(mono, stamp_data.date, BLF_DRAW_STR_DUMMY_MAX);
1958
1959                 /* the extra pixel for background. */
1960                 y -= BUFF_MARGIN_Y * 2;
1961         }
1962
1963         /* Top left corner, below File, Date */
1964         if (TEXT_SIZE_CHECK(stamp_data.rendertime, w, h)) {
1965                 y -= h;
1966
1967                 /* and space for background. */
1968                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1969                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1970
1971                 BLF_position(mono, x, y + y_ofs, 0.0);
1972                 BLF_draw_buffer(mono, stamp_data.rendertime, BLF_DRAW_STR_DUMMY_MAX);
1973
1974                 /* the extra pixel for background. */
1975                 y -= BUFF_MARGIN_Y * 2;
1976         }
1977
1978         /* Top left corner, below File, Date, Rendertime */
1979         if (TEXT_SIZE_CHECK(stamp_data.memory, w, h)) {
1980                 y -= h;
1981
1982                 /* and space for background. */
1983                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1984                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1985
1986                 BLF_position(mono, x, y + y_ofs, 0.0);
1987                 BLF_draw_buffer(mono, stamp_data.memory, BLF_DRAW_STR_DUMMY_MAX);
1988
1989                 /* the extra pixel for background. */
1990                 y -= BUFF_MARGIN_Y * 2;
1991         }
1992
1993         /* Top left corner, below File, Date, Memory, Rendertime */
1994         BLF_enable(mono, BLF_WORD_WRAP);
1995         if (TEXT_SIZE_CHECK_WORD_WRAP(stamp_data.note, w, h)) {
1996                 y -= h;
1997
1998                 /* and space for background. */
1999                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
2000                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2001
2002                 BLF_position(mono, x, y + y_ofs + (h - h_fixed), 0.0);
2003                 BLF_draw_buffer(mono, stamp_data.note, BLF_DRAW_STR_DUMMY_MAX);
2004         }
2005         BLF_disable(mono, BLF_WORD_WRAP);
2006
2007         x = 0;
2008         y = 0;
2009
2010         /* Bottom left corner, leaving space for timing */
2011         if (TEXT_SIZE_CHECK(stamp_data.marker, w, h)) {
2012
2013                 /* extra space for background. */
2014                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp,  display,
2015                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2016
2017                 /* and pad the text. */
2018                 BLF_position(mono, x, y + y_ofs, 0.0);
2019                 BLF_draw_buffer(mono, stamp_data.marker, BLF_DRAW_STR_DUMMY_MAX);
2020
2021                 /* space width. */
2022                 x += w + pad;
2023         }
2024
2025         /* Left bottom corner */
2026         if (TEXT_SIZE_CHECK(stamp_data.time, w, h)) {
2027
2028                 /* extra space for background */
2029                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
2030                                   x - BUFF_MARGIN_X, y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2031
2032                 /* and pad the text. */
2033                 BLF_position(mono, x, y + y_ofs, 0.0);
2034                 BLF_draw_buffer(mono, stamp_data.time, BLF_DRAW_STR_DUMMY_MAX);
2035
2036                 /* space width. */
2037                 x += w + pad;
2038         }
2039
2040         if (TEXT_SIZE_CHECK(stamp_data.frame, w, h)) {
2041
2042                 /* extra space for background. */
2043                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
2044                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2045
2046                 /* and pad the text. */
2047                 BLF_position(mono, x, y + y_ofs, 0.0);
2048                 BLF_draw_buffer(mono, stamp_data.frame, BLF_DRAW_STR_DUMMY_MAX);
2049
2050                 /* space width. */
2051                 x += w + pad;
2052         }
2053
2054         if (TEXT_SIZE_CHECK(stamp_data.camera, w, h)) {
2055
2056                 /* extra space for background. */
2057                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
2058                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2059                 BLF_position(mono, x, y + y_ofs, 0.0);
2060                 BLF_draw_buffer(mono, stamp_data.camera, BLF_DRAW_STR_DUMMY_MAX);
2061
2062                 /* space width. */
2063                 x += w + pad;
2064         }
2065
2066         if (TEXT_SIZE_CHECK(stamp_data.cameralens, w, h)) {
2067
2068                 /* extra space for background. */
2069                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
2070                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2071                 BLF_position(mono, x, y + y_ofs, 0.0);
2072                 BLF_draw_buffer(mono, stamp_data.cameralens, BLF_DRAW_STR_DUMMY_MAX);
2073         }
2074
2075         if (TEXT_SIZE_CHECK(stamp_data.scene, w, h)) {
2076
2077                 /* Bottom right corner, with an extra space because blenfont is too strict! */
2078                 x = width - w - 2;
2079
2080                 /* extra space for background. */
2081                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
2082                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2083
2084                 /* and pad the text. */
2085                 BLF_position(mono, x, y + y_ofs, 0.0);
2086                 BLF_draw_buffer(mono, stamp_data.scene, BLF_DRAW_STR_DUMMY_MAX);
2087         }
2088
2089         if (TEXT_SIZE_CHECK(stamp_data.strip, w, h)) {
2090
2091                 /* Top right corner, with an extra space because blenfont is too strict! */
2092                 x = width - w - pad;
2093                 y = height - h;
2094
2095                 /* extra space for background. */
2096                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
2097                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2098
2099                 BLF_position(mono, x, y + y_ofs, 0.0);
2100                 BLF_draw_buffer(mono, stamp_data.strip, BLF_DRAW_STR_DUMMY_MAX);
2101         }
2102
2103         /* cleanup the buffer. */
2104         BLF_buffer(mono, NULL, NULL, 0, 0, 0, NULL);
2105         BLF_wordwrap(mono, 0);
2106
2107 #undef TEXT_SIZE_CHECK
2108 #undef TEXT_SIZE_CHECK_WORD_WRAP
2109 #undef BUFF_MARGIN_X
2110 #undef BUFF_MARGIN_Y
2111 }
2112
2113 void BKE_render_result_stamp_info(Scene *scene, Object *camera, struct RenderResult *rr, bool allocate_only)
2114 {
2115         struct StampData *stamp_data;
2116
2117         if (!(scene && (scene->r.stamp & R_STAMP_ALL)) && !allocate_only)
2118                 return;
2119
2120         if (!rr->stamp_data) {
2121                 stamp_data = MEM_callocN(sizeof(StampData), "RenderResult.stamp_data");
2122         }
2123         else {
2124                 stamp_data = rr->stamp_data;
2125         }
2126
2127         if (!allocate_only)
2128                 stampdata(scene, camera, stamp_data, 0, true);
2129
2130         if (!rr->stamp_data) {
2131                 rr->stamp_data = stamp_data;
2132         }
2133 }
2134
2135 struct StampData *BKE_stamp_info_from_scene_static(Scene *scene)
2136 {
2137         struct StampData *stamp_data;
2138
2139         if (!(scene && (scene->r.stamp & R_STAMP_ALL)))
2140                 return NULL;
2141
2142         /* Memory is allocated here (instead of by the caller) so that the caller
2143          * doesn't have to know the size of the StampData struct. */
2144         stamp_data = MEM_callocN(sizeof(StampData), __func__);
2145         stampdata(scene, NULL, stamp_data, 0, false);
2146
2147         return stamp_data;
2148 }
2149
2150 void BKE_stamp_info_callback(void *data, struct StampData *stamp_data, StampCallback callback, bool noskip)
2151 {
2152         if ((callback == NULL) || (stamp_data == NULL)) {
2153                 return;
2154         }
2155
2156 #define CALL(member, value_str) \
2157         if (noskip || stamp_data->member[0]) { \
2158                 callback(data, value_str, stamp_data->member, sizeof(stamp_data->member)); \
2159         } ((void)0)
2160
2161         CALL(file, "File");
2162         CALL(note, "Note");
2163         CALL(date, "Date");
2164         CALL(marker, "Marker");
2165         CALL(time, "Time");
2166         CALL(frame, "Frame");
2167         CALL(frame_range, "FrameRange");
2168         CALL(camera, "Camera");
2169         CALL(cameralens, "Lens");
2170         CALL(scene, "Scene");
2171         CALL(strip, "Strip");
2172         CALL(rendertime, "RenderTime");
2173         CALL(memory, "Memory");
2174
2175         for (StampDataCustomField *custom_field = stamp_data->custom_fields.first;
2176              custom_field != NULL;
2177              custom_field = custom_field->next)
2178         {
2179                 if (noskip || custom_field->value[0]) {
2180                         callback(data, custom_field->key, custom_field->value, sizeof(custom_field->value));
2181                 }
2182         }
2183
2184 #undef CALL
2185 }
2186
2187 void BKE_render_result_stamp_data(RenderResult *rr, const char *key, const char *value)
2188 {
2189         StampData *stamp_data;
2190         if (rr->stamp_data == NULL) {
2191                 rr->stamp_data = MEM_callocN(sizeof(StampData), "RenderResult.stamp_data");
2192         }
2193         stamp_data = rr->stamp_data;
2194         StampDataCustomField *field = MEM_mallocN(sizeof(StampDataCustomField),
2195                                                   "StampData Custom Field");
2196         STRNCPY(field->key, key);
2197         STRNCPY(field->value, value);
2198         BLI_addtail(&stamp_data->custom_fields, field);
2199 }
2200
2201 void BKE_stamp_data_free(struct StampData *stamp_data)
2202 {
2203         if (stamp_data == NULL) {
2204                 return;
2205         }
2206         BLI_freelistN(&stamp_data->custom_fields);
2207         MEM_freeN(stamp_data);
2208 }
2209
2210 /* wrap for callback only */
2211 static void metadata_set_field(void *data, const char *propname, char *propvalue, int UNUSED(len))
2212 {
2213         /* We know it is an ImBuf* because that's what we pass to BKE_stamp_info_callback. */
2214         struct ImBuf *imbuf = data;
2215         IMB_metadata_set_field(imbuf->metadata, propname, propvalue);
2216 }
2217
2218 static void metadata_get_field(void *data, const char *propname, char *propvalue, int len)
2219 {
2220         /* We know it is an ImBuf* because that's what we pass to BKE_stamp_info_callback. */
2221         struct ImBuf *imbuf = data;
2222         IMB_metadata_get_field(imbuf->metadata, propname, propvalue, len);
2223 }
2224
2225 void BKE_imbuf_stamp_info(RenderResult *rr, struct ImBuf *ibuf)
2226 {
2227         struct StampData *stamp_data = rr->stamp_data;
2228         IMB_metadata_ensure(&ibuf->metadata);
2229         BKE_stamp_info_callback(ibuf, stamp_data, metadata_set_field, false);
2230 }
2231
2232 void BKE_stamp_info_from_imbuf(RenderResult *rr, struct ImBuf *ibuf)
2233 {
2234         struct StampData *stamp_data = rr->stamp_data;
2235         IMB_metadata_ensure(&ibuf->metadata);
2236         BKE_stamp_info_callback(ibuf, stamp_data, metadata_get_field, true);
2237 }
2238
2239 bool BKE_imbuf_alpha_test(ImBuf *ibuf)
2240 {
2241         int tot;
2242         if (ibuf->rect_float) {
2243                 const float *buf = ibuf->rect_float;
2244                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
2245                         if (buf[3] < 1.0f) {
2246                                 return true;
2247                         }
2248                 }
2249         }
2250         else if (ibuf->rect) {
2251                 unsigned char *buf = (unsigned char *)ibuf->rect;
2252                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
2253                         if (buf[3] != 255) {
2254                                 return true;
2255                         }
2256                 }
2257         }
2258
2259         return false;
2260 }
2261
2262 /* note: imf->planes is ignored here, its assumed the image channels
2263  * are already set */
2264 void BKE_imbuf_write_prepare(ImBuf *ibuf, const ImageFormatData *imf)
2265 {
2266         char imtype = imf->imtype;
2267         char compress = imf->compress;
2268         char quality = imf->quality;
2269
2270         /* initialize all from image format */
2271         ibuf->foptions.flag = 0;
2272
2273         if (imtype == R_IMF_IMTYPE_IRIS) {
2274                 ibuf->ftype = IMB_FTYPE_IMAGIC;
2275         }
2276 #ifdef WITH_HDR
2277         else if (imtype == R_IMF_IMTYPE_RADHDR) {
2278                 ibuf->ftype = IMB_FTYPE_RADHDR;
2279         }
2280 #endif
2281         else if (ELEM(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
2282                 ibuf->ftype = IMB_FTYPE_PNG;
2283
2284                 if (imtype == R_IMF_IMTYPE_PNG) {
2285                         if (imf->depth == R_IMF_CHAN_DEPTH_16)
2286                                 ibuf->foptions.flag |= PNG_16BIT;
2287
2288                         ibuf->foptions.quality = compress;
2289                 }
2290
2291         }
2292 #ifdef WITH_DDS
2293         else if (imtype == R_IMF_IMTYPE_DDS) {
2294                 ibuf->ftype = IMB_FTYPE_DDS;
2295         }
2296 #endif
2297         else if (imtype == R_IMF_IMTYPE_BMP) {
2298                 ibuf->ftype = IMB_FTYPE_BMP;
2299         }
2300 #ifdef WITH_TIFF
2301         else if (imtype == R_IMF_IMTYPE_TIFF) {
2302                 ibuf->ftype = IMB_FTYPE_TIF;
2303
2304                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2305                         ibuf->foptions.flag |= TIF_16BIT;
2306                 }
2307                 if (imf->tiff_codec == R_IMF_TIFF_CODEC_NONE) {
2308                         ibuf->foptions.flag |= TIF_COMPRESS_NONE;
2309                 }
2310                 else if (imf->tiff_codec == R_IMF_TIFF_CODEC_DEFLATE) {
2311                         ibuf->foptions.flag |= TIF_COMPRESS_DEFLATE;
2312                 }
2313                 else if (imf->tiff_codec == R_IMF_TIFF_CODEC_LZW) {
2314                         ibuf->foptions.flag |= TIF_COMPRESS_LZW;
2315                 }
2316                 else if (imf->tiff_codec == R_IMF_TIFF_CODEC_PACKBITS) {
2317                         ibuf->foptions.flag |= TIF_COMPRESS_PACKBITS;
2318                 }
2319         }
2320 #endif
2321 #ifdef WITH_OPENEXR
2322         else if (ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
2323                 ibuf->ftype = IMB_FTYPE_OPENEXR;
2324                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
2325                         ibuf->foptions.flag |= OPENEXR_HALF;
2326                 ibuf->foptions.flag |= (imf->exr_codec & OPENEXR_COMPRESS);
2327
2328                 if (!(imf->flag & R_IMF_FLAG_ZBUF)) {
2329                         /* Signal for exr saving. */
2330                         IMB_freezbuffloatImBuf(ibuf);
2331                 }
2332
2333         }
2334 #endif
2335 #ifdef WITH_CINEON
2336         else if (imtype == R_IMF_IMTYPE_CINEON) {
2337                 ibuf->ftype = IMB_FTYPE_CINEON;
2338                 if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
2339                         ibuf->foptions.flag |= CINEON_LOG;
2340                 }
2341                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2342                         ibuf->foptions.flag |= CINEON_16BIT;
2343                 }
2344                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
2345                         ibuf->foptions.flag |= CINEON_12BIT;
2346                 }
2347                 else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
2348                         ibuf->foptions.flag |= CINEON_10BIT;
2349                 }
2350         }
2351         else if (imtype == R_IMF_IMTYPE_DPX) {
2352                 ibuf->ftype = IMB_FTYPE_DPX;
2353                 if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
2354                         ibuf->foptions.flag |= CINEON_LOG;
2355                 }
2356                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2357                         ibuf->foptions.flag |= CINEON_16BIT;
2358                 }
2359                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
2360                         ibuf->foptions.flag |= CINEON_12BIT;
2361                 }
2362                 else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
2363                         ibuf->foptions.flag |= CINEON_10BIT;
2364                 }
2365         }
2366 #endif
2367         else if (imtype == R_IMF_IMTYPE_TARGA) {
2368                 ibuf->ftype = IMB_FTYPE_TGA;
2369         }
2370         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
2371                 ibuf->ftype = IMB_FTYPE_TGA;
2372                 ibuf->foptions.flag = RAWTGA;
2373         }
2374 #ifdef WITH_OPENJPEG
2375         else if (imtype == R_IMF_IMTYPE_JP2) {
2376                 if (quality < 10) quality = 90;
2377                 ibuf->ftype = IMB_FTYPE_JP2;
2378                 ibuf->foptions.quality = quality;
2379
2380                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2381                         ibuf->foptions.flag |= JP2_16BIT;
2382                 }
2383                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
2384                         ibuf->foptions.flag |= JP2_12BIT;
2385                 }
2386
2387                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
2388                         ibuf->foptions.flag |= JP2_YCC;
2389                 }
2390
2391                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
2392                         ibuf->foptions.flag |= JP2_CINE;
2393                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
2394                                 ibuf->foptions.flag |= JP2_CINE_48FPS;
2395                 }
2396
2397                 if (imf->jp2_codec == R_IMF_JP2_CODEC_JP2)
2398                         ibuf->foptions.flag |= JP2_JP2;
2399                 else if (imf->jp2_codec == R_IMF_JP2_CODEC_J2K)
2400                         ibuf->foptions.flag |= JP2_J2K;
2401                 else
2402                         BLI_assert(!"Unsupported jp2 codec was specified in im_format->jp2_codec");
2403         }
2404 #endif
2405         else {
2406                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
2407                 if (quality < 10) quality = 90;
2408                 ibuf->ftype = IMB_FTYPE_JPG;
2409                 ibuf->foptions.quality = quality;
2410         }
2411 }
2412
2413 int BKE_imbuf_write(ImBuf *ibuf, const char *name, const ImageFormatData *imf)
2414 {
2415         int ok;
2416
2417         BKE_imbuf_write_prepare(ibuf, imf);
2418
2419         BLI_make_existing_file(name);
2420
2421         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
2422         if (ok == 0) {
2423                 perror(name);
2424         }
2425
2426         return(ok);
2427 }
2428
2429 /* same as BKE_imbuf_write() but crappy workaround not to permanently modify
2430  * _some_, values in the imbuf */
2431 int BKE_imbuf_write_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
2432                        const bool save_copy)
2433 {
2434         ImBuf ibuf_back = *ibuf;
2435         int ok;
2436
2437         /* all data is rgba anyway,
2438          * this just controls how to save for some formats */
2439         ibuf->planes = imf->planes;
2440
2441         ok = BKE_imbuf_write(ibuf, name, imf);
2442
2443         if (save_copy) {
2444                 /* note that we are not restoring _all_ settings */
2445                 ibuf->planes = ibuf_back.planes;
2446                 ibuf->ftype =  ibuf_back.ftype;
2447                 ibuf->foptions =  ibuf_back.foptions;
2448         }
2449
2450         return ok;
2451 }
2452
2453 int BKE_imbuf_write_stamp(
2454         Scene *scene, struct RenderResult *rr, ImBuf *ibuf, const char *name,
2455         const struct ImageFormatData *imf)
2456 {
2457         if (scene && scene->r.stamp & R_STAMP_ALL)
2458                 BKE_imbuf_stamp_info(rr, ibuf);
2459
2460         return BKE_imbuf_write(ibuf, name, imf);
2461 }
2462
2463 static void do_makepicstring(
2464         char *string, const char *base, const char *relbase, int frame, const char imtype,
2465         const ImageFormatData *im_format, const short use_ext, const short use_frames,
2466         const char *suffix)
2467 {
2468         if (string == NULL) return;
2469         BLI_strncpy(string, base, FILE_MAX - 10);   /* weak assumption */
2470         BLI_path_abs(string, relbase);
2471
2472         if (use_frames)
2473                 BLI_path_frame(string, frame, 4);
2474
2475         if (suffix)
2476                 BLI_path_suffix(string, FILE_MAX, suffix, "");
2477
2478         if (use_ext)
2479                 do_add_image_extension(string, imtype, im_format);
2480 }
2481
2482 void BKE_image_path_from_imformat(
2483         char *string, const char *base, const char *relbase, int frame,
2484         const ImageFormatData *im_format, const bool use_ext, const bool use_frames, const char *suffix)
2485 {
2486         do_makepicstring(string, base, relbase, frame, im_format->imtype, im_format, use_ext, use_frames, suffix);
2487 }
2488
2489 void BKE_image_path_from_imtype(
2490         char *string, const char *base, const char *relbase, int frame,
2491         const char imtype, const bool use_ext, const bool use_frames, const char *view)
2492 {
2493         do_makepicstring(string, base, relbase, frame, imtype, NULL, use_ext, use_frames, view);
2494 }
2495
2496 struct anim *openanim_noload(const char *name, int flags, int streamindex, char colorspace[IMA_MAX_SPACE])
2497 {
2498         struct anim *anim;
2499
2500         anim = IMB_open_anim(name, flags, streamindex, colorspace);
2501         return anim;
2502 }
2503
2504 /* used by sequencer too */
2505 struct anim *openanim(const char *name, int flags, int streamindex, char colorspace[IMA_MAX_SPACE])
2506 {
2507         struct anim *anim;
2508         struct ImBuf *ibuf;
2509
2510         anim = IMB_open_anim(name, flags, streamindex, colorspace);
2511         if (anim == NULL) return NULL;
2512
2513         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
2514         if (ibuf == NULL) {
2515                 if (BLI_exists(name))
2516                         printf("not an anim: %s\n", name);
2517                 else
2518                         printf("anim file doesn't exist: %s\n", name);
2519                 IMB_free_anim(anim);
2520                 return NULL;
2521         }
2522         IMB_freeImBuf(ibuf);
2523
2524         return(anim);
2525 }
2526
2527 /* ************************* New Image API *************** */
2528
2529
2530 /* Notes about Image storage
2531  * - packedfile
2532  *   -> written in .blend
2533  * - filename
2534  *   -> written in .blend
2535  * - movie
2536  *   -> comes from packedfile or filename
2537  * - renderresult
2538  *   -> comes from packedfile or filename
2539  * - listbase
2540  *   -> ibufs from exrhandle
2541  * - flipbook array
2542  *   -> ibufs come from movie, temporary renderresult or sequence
2543  * - ibuf
2544  *   -> comes from packedfile or filename or generated
2545  */
2546
2547
2548 /* forces existence of 1 Image for renderout or nodes, returns Image */
2549 /* name is only for default, when making new one */
2550 Image *BKE_image_verify_viewer(int type, const char *name)
2551 {
2552         Image *ima;
2553
2554         for (ima = G.main->image.first; ima; ima = ima->id.next)
2555                 if (ima->source == IMA_SRC_VIEWER)
2556                         if (ima->type == type)
2557                                 break;
2558
2559         if (ima == NULL)
2560                 ima = image_alloc(G.main, name, IMA_SRC_VIEWER, type);
2561
2562         /* happens on reload, imagewindow cannot be image user when hidden*/
2563         if (ima->id.us == 0)
2564                 id_us_plus(&ima->id);
2565
2566         return ima;
2567 }
2568
2569 static void image_viewer_create_views(const RenderData *rd, Image *ima)
2570 {
2571         if ((rd->scemode & R_MULTIVIEW) == 0) {
2572                 image_add_view(ima, "", "");
2573         }
2574         else {
2575                 SceneRenderView *srv;
2576                 for (srv = rd->views.first; srv; srv = srv->next) {
2577                         if (BKE_scene_multiview_is_render_view_active(rd, srv) == false)
2578                                 continue;
2579                         image_add_view(ima, srv->name, "");
2580                 }
2581         }
2582 }
2583
2584 /* Reset the image cache and views when the Viewer Nodes views don't match the scene views */
2585 void BKE_image_verify_viewer_views(const RenderData *rd, Image *ima, ImageUser *iuser)
2586 {
2587         bool do_reset;
2588         const bool is_multiview = (rd->scemode & R_MULTIVIEW) != 0;
2589
2590         BLI_thread_lock(LOCK_DRAW_IMAGE);
2591
2592         if (!BKE_scene_multiview_is_stereo3d(rd))
2593                 iuser->flag &= ~IMA_SHOW_STEREO;
2594
2595         /* see if all scene render views are in the image view list */
2596         do_reset = (BKE_scene_multiview_num_views_get(rd) != BLI_listbase_count(&ima->views));
2597
2598         /* multiview also needs to be sure all the views are synced */
2599         if (is_multiview && !do_reset) {
2600                 SceneRenderView *srv;
2601                 ImageView *iv;
2602
2603                 for (iv = ima->views.first; iv; iv = iv->next) {
2604                         srv = BLI_findstring(&rd->views, iv->name, offsetof(SceneRenderView, name));
2605                         if ((srv == NULL) || (BKE_scene_multiview_is_render_view_active(rd, srv) == false)) {
2606                                 do_reset = true;
2607                                 break;
2608                         }
2609                 }
2610         }
2611
2612         if (do_reset) {
2613                 BLI_spin_lock(&image_spin);
2614
2615                 image_free_cached_frames(ima);
2616                 BKE_image_free_views(ima);
2617
2618                 /* add new views */
2619                 image_viewer_create_views(rd, ima);
2620
2621                 BLI_spin_unlock(&image_spin);
2622         }
2623
2624         BLI_thread_unlock(LOCK_DRAW_IMAGE);
2625 }
2626
2627 void BKE_image_walk_all_users(const Main *mainp, void *customdata,
2628                               void callback(Image *ima, ImageUser *iuser, void *customdata))
2629 {
2630         wmWindowManager *wm;
2631         wmWindow *win;
2632         Tex *tex;
2633
2634         /* texture users */
2635         for (tex = mainp->tex.first; tex; tex = tex->id.next) {
2636                 if (tex->type == TEX_IMAGE && tex->ima) {
2637                         callback(tex->ima, &tex->iuser, customdata);
2638                 }
2639
2640                 if (tex->nodetree) {
2641                         bNode *node;
2642                         for (node = tex->nodetree->nodes.first; node; node = node->next) {
2643                                 if (node->id && node->type == TEX_NODE_IMAGE) {
2644                                         Image *ima = (Image *)node->id;
2645                                         ImageUser *iuser = node->storage;
2646                                         callback(ima, iuser, customdata);
2647                                 }
2648                         }
2649                 }
2650         }
2651
2652         for (Camera *cam = mainp->camera.first; cam; cam = cam->id.next) {
2653                 for (CameraBGImage *bgpic = cam->bg_images.first; bgpic; bgpic = bgpic->next) {
2654                         callback(bgpic->ima, &bgpic->iuser, customdata);
2655                 }
2656         }
2657
2658         /* image window, compo node users */
2659         for (wm = mainp->wm.first; wm; wm = wm->id.next) { /* only 1 wm */
2660                 for (win = wm->windows.first; win; win = win->next) {
2661                         const bScreen *screen = BKE_workspace_active_screen_get(win->workspace_hook);
2662
2663                         for (ScrArea *sa = screen->areabase.first; sa; sa = sa->next) {
2664                                 if (sa->spacetype == SPACE_IMAGE) {
2665                                         SpaceImage *sima = sa->spacedata.first;
2666                                         callback(sima->image, &sima->iuser, customdata);
2667                                 }
2668                                 else if (sa->spacetype == SPACE_NODE) {
2669                                         SpaceNode *snode = sa->spacedata.first;
2670                                         if (snode->nodetree && snode->nodetree->type == NTREE_COMPOSIT) {
2671                                                 bNode *node;
2672                                                 for (node = snode->nodetree->nodes.first; node; node = node->next) {
2673                                                         if (node->id && node->type == CMP_NODE_IMAGE) {
2674                                                                 Image *ima = (Image *)node->id;
2675                                                                 ImageUser *iuser = node->storage;
2676                                                                 callback(ima, iuser, customdata);
2677                                                         }
2678                                                 }
2679                                         }
2680                                 }
2681                         }
2682                 }
2683         }
2684 }
2685
2686 static void image_tag_frame_recalc(Image *ima, ImageUser *iuser, void *customdata)
2687 {
2688         Image *changed_image = customdata;
2689
2690         if (ima == changed_image && BKE_image_is_animated(ima)) {
2691                 iuser->flag |= IMA_NEED_FRAME_RECALC;
2692         }
2693 }
2694
2695 static void image_init_imageuser(Image *ima, ImageUser *iuser)
2696 {
2697         RenderResult *rr = ima->rr;
2698
2699         iuser->multi_index = 0;
2700         iuser->layer = iuser->pass = iuser->view = 0;
2701
2702         if (rr)
2703                 BKE_image_multilayer_index(rr, iuser);
2704 }
2705
2706 void BKE_image_init_imageuser(Image *ima, ImageUser *iuser)
2707 {
2708         image_init_imageuser(ima, iuser);
2709 }
2710
2711 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
2712 {
2713         if (ima == NULL)
2714                 return;
2715
2716         BLI_spin_lock(&image_spin);
2717
2718         switch (signal) {
2719                 case IMA_SIGNAL_FREE:
2720                         BKE_image_free_buffers(ima);
2721
2722                         if (iuser) {
2723                                 iuser->ok = 1;
2724                                 if (iuser->scene) {
2725                                         image_update_views_format(ima, iuser);
2726                                 }
2727                         }
2728                         break;
2729                 case IMA_SIGNAL_SRC_CHANGE:
2730                         if (ima->type == IMA_TYPE_UV_TEST)
2731                                 if (ima->source != IMA_SRC_GENERATED)
2732                                         ima->type = IMA_TYPE_IMAGE;
2733
2734                         if (ima->source == IMA_SRC_GENERATED) {
2735                                 if (ima->gen_x == 0 || ima->gen_y == 0) {
2736                                         ImBuf *ibuf = image_get_cached_ibuf_for_index_frame(ima, IMA_NO_INDEX, 0);
2737                                         if (ibuf) {
2738                                                 ima->gen_x = ibuf->x;
2739                                                 ima->gen_y = ibuf->y;
2740                                                 IMB_freeImBuf(ibuf);
2741                                         }
2742                                 }
2743
2744                                 /* Changing source type to generated will likely change file format
2745                                  * used by generated image buffer. Saving different file format to
2746                                  * the old name might confuse other applications.
2747                                  *
2748                                  * Here we ensure original image path wouldn't be used when saving
2749                                  * generated image.
2750                                  */
2751                                 ima->name[0] = '\0';
2752                         }
2753
2754 #if 0
2755                         /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
2756                         if (ima->type != IMA_TYPE_MULTILAYER)
2757                                 BKE_image_free_buffers(ima);
2758 #else
2759                         /* image buffers for non-sequence multilayer will share buffers with RenderResult,
2760                          * however sequence multilayer will own buffers. Such logic makes switching from
2761                          * single multilayer file to sequence completely unstable
2762                          * since changes in nodes seems this workaround isn't needed anymore, all sockets
2763                          * are nicely detecting anyway, but freeing buffers always here makes multilayer
2764                          * sequences behave stable
2765                          */
2766                         BKE_image_free_buffers(ima);
2767 #endif
2768
2769                         ima->ok = 1;
2770                         if (iuser)
2771                                 iuser->ok = 1;
2772
2773                         BKE_image_walk_all_users(G.main, ima, image_tag_frame_recalc);
2774
2775                         break;
2776
2777                 case IMA_SIGNAL_RELOAD:
2778                         /* try to repack file */
2779                         if (BKE_image_has_packedfile(ima)) {
2780                                 const int totfiles = image_num_files(ima);
2781
2782                                 if (totfiles != BLI_listbase_count_at_most(&ima->packedfiles, totfiles + 1)) {
2783                                         /* in case there are new available files to be loaded */
2784                                         image_free_packedfiles(ima);
2785                                         BKE_image_packfiles(NULL, ima, ID_BLEND_PATH(G.main, &ima->id));
2786                                 }
2787                                 else {
2788                                         ImagePackedFile *imapf;
2789                                         for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next) {
2790                                                 PackedFile *pf;
2791                                                 pf = newPackedFile(NULL, imapf->filepath, ID_BLEND_PATH(G.main, &ima->id));
2792                                                 if (pf) {
2793                                                         freePackedFile(imapf->packedfile);
2794                                                         imapf->packedfile = pf;
2795                                                 }
2796                                                 else {
2797                                                         printf("ERROR: Image \"%s\" not available. Keeping packed image\n", imapf->filepath);
2798                                                 }
2799                                         }
2800                                 }
2801
2802                                 if (BKE_image_has_packedfile(ima))
2803                                         BKE_image_free_buffers(ima);
2804                         }
2805                         else
2806                                 BKE_image_free_buffers(ima);
2807
2808                         if (iuser) {
2809                                 iuser->ok = 1;
2810                                 if (iuser->scene) {
2811                                         image_update_views_format(ima, iuser);
2812                                 }
2813                         }
2814
2815                         break;
2816                 case IMA_SIGNAL_USER_NEW_IMAGE:
2817                         if (iuser) {
2818                                 iuser->ok = 1;
2819                                 if (ima->source == IMA_SRC_FILE || ima->source == IMA_SRC_SEQUENCE) {
2820                                         if (ima->type == IMA_TYPE_MULTILAYER) {
2821                                                 image_init_imageuser(ima, iuser);
2822                                         }
2823                                 }
2824                         }
2825                         break;
2826                 case IMA_SIGNAL_COLORMANAGE:
2827                         BKE_image_free_buffers(ima);
2828
2829                         ima->ok = 1;
2830
2831                         if (iuser)
2832                                 iuser->ok = 1;
2833
2834                         break;
2835         }
2836
2837         BLI_spin_unlock(&image_spin);
2838
2839         /* don't use notifiers because they are not 100% sure to succeeded
2840          * this also makes sure all scenes are accounted for. */
2841         {
2842                 Scene *scene;
2843                 for (scene = G.main->scene.first; scene; scene = scene->id.next) {
2844                         if (scene->nodetree) {
2845                                 nodeUpdateID(scene->nodetree, &ima->id);
2846                         }
2847                 }
2848         }
2849 }
2850
2851 /* return renderpass for a given pass index and active view */
2852 /* fallback to available if there are missing passes for active view */
2853 static RenderPass *image_render_pass_get(RenderLayer *rl, const int pass, const int view, int *r_passindex)
2854 {
2855         RenderPass *rpass_ret = NULL;
2856         RenderPass *rpass;
2857
2858         int rp_index = 0;
2859         const char *rp_name = "";
2860
2861         for (rpass = rl->passes.first; rpass; rpass = rpass->next, rp_index++) {
2862                 if (rp_index == pass) {
2863                         rpass_ret = rpass;
2864                         if (view == 0) {
2865                                 /* no multiview or left eye */
2866                                 break;
2867                         }
2868                         else {
2869                                 rp_name = rpass->name;
2870                         }
2871                 }
2872                 /* multiview */
2873                 else if (rp_name[0] &&
2874                          STREQ(rpass->name, rp_name) &&
2875                          (rpass->view_id == view))
2876                 {
2877                         rpass_ret = rpass;
2878                         break;
2879                 }
2880         }
2881
2882         /* fallback to the first pass in the layer */
2883         if (rpass_ret == NULL) {
2884                 rp_index = 0;
2885                 rpass_ret = rl->passes.first;
2886         }
2887
2888         if (r_passindex) {
2889                 *r_passindex = (rpass == rpass_ret ? rp_index : pass);
2890         }
2891
2892         return rpass_ret;
2893 }
2894
2895 /* if layer or pass changes, we need an index for the imbufs list */
2896 /* note it is called for rendered results, but it doesnt use the index! */
2897 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
2898 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
2899 {
2900         RenderLayer *rl;
2901         RenderPass *rpass = NULL;
2902
2903         if (rr == NULL)
2904                 return NULL;
2905
2906         if (iuser) {
2907                 short index = 0, rv_index, rl_index = 0;
2908                 bool is_stereo = (iuser->flag & IMA_SHOW_STEREO) && RE_RenderResult_is_stereo(rr);
2909
2910                 rv_index = is_stereo ? iuser->multiview_eye : iuser->view;
2911                 if (RE_HasCombinedLayer(rr)) rl_index += 1;
2912
2913                 for (rl = rr->layers.first; rl; rl = rl->next, rl_index++) {
2914                         if (iuser->layer == rl_index) {
2915                                 int rp_index;
2916                                 rpass = image_render_pass_get(rl, iuser->pass, rv_index, &rp_index);
2917                                 iuser->multi_index = index + rp_index;
2918                                 break;
2919                         }
2920                         else {
2921                                 index += BLI_listbase_count(&rl->passes);
2922                         }
2923                 }
2924         }
2925
2926         return rpass;
2927 }
2928
2929 void BKE_image_multiview_index(Image *ima, ImageUser *iuser)
2930 {
2931         if (iuser) {
2932                 bool is_stereo = BKE_image_is_stereo(ima) && (iuser->flag & IMA_SHOW_STEREO);
2933                 if (is_stereo) {
2934                         iuser->multi_index = iuser->multiview_eye;
2935                 }
2936                 else {
2937                         if ((iuser->view < 0) || (iuser->view >= BLI_listbase_count_at_most(&ima->views, iuser->view + 1))) {
2938                                 iuser->multi_index = iuser->view = 0;
2939                         }
2940                         else {
2941                                 iuser->multi_index = iuser->view;
2942                         }
2943                 }
2944         }
2945 }
2946
2947 /* if layer or pass changes, we need an index for the imbufs list */
2948 /* note it is called for rendered results, but it doesnt use the index! */
2949 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
2950 bool BKE_image_is_multilayer(Image *ima)
2951 {
2952         if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE)) {
2953                 if (ima->type == IMA_TYPE_MULTILAYER) {
2954                         return true;
2955                 }
2956         }
2957         else if (ima->source == IMA_SRC_VIEWER) {
2958                 if (ima->type == IMA_TYPE_R_RESULT) {
2959                         return true;
2960                 }
2961         }
2962         return false;
2963 }
2964
2965 bool BKE_image_is_multiview(Image *ima)
2966 {
2967         ImageView *view = ima->views.first;
2968         return (view && (view->next || view->name[0]));
2969 }
2970
2971 bool BKE_image_is_stereo(Image *ima)
2972 {
2973         return BKE_image_is_multiview(ima) &&
2974                (BLI_findstring(&ima->views, STEREO_LEFT_NAME, offsetof(ImageView, name)) &&
2975                 BLI_findstring(&ima->views, STEREO_RIGHT_NAME, offsetof(ImageView, name)));
2976 }
2977
2978 static void image_init_multilayer_multiview(Image *ima, RenderResult *rr)
2979 {
2980         /* update image views from render views, but only if they actually changed,
2981          * to avoid invalid memory access during render. ideally these should always
2982          * be acquired with a mutex along with the render result, but there are still
2983          * some places with just an image pointer that need to access views */
2984         if (rr && BLI_listbase_count(&ima->views) == BLI_listbase_count(&rr->views)) {
2985                 ImageView *iv = ima->views.first;
2986                 RenderView *rv = rr->views.first;
2987                 bool modified = false;
2988                 for (; rv; rv = rv->next, iv = iv->next) {
2989                         modified |= !STREQ(rv->name, iv->name);
2990                 }
2991                 if (!modified)
2992                         return;
2993         }
2994
2995         BKE_image_free_views(ima);
2996
2997         if (rr) {
2998                 for (RenderView *rv = rr->views.first; rv; rv = rv->next) {
2999                         ImageView *iv = MEM_callocN(sizeof(ImageView), "Viewer Image View");
3000                         STRNCPY(iv->name, rv->name);
3001                         BLI_addtail(&ima->views, iv);
3002                 }
3003         }
3004 }
3005
3006
3007 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
3008 {
3009         RenderResult *rr = NULL;
3010         if (ima->rr) {
3011                 rr = ima->rr;
3012         }
3013         else if (ima->type == IMA_TYPE_R_RESULT) {
3014                 if (ima->render_slot == ima->last_render_slot)
3015                         rr = RE_AcquireResultRead(RE_GetSceneRender(scene));
3016                 else
3017                         rr = ima->renders[ima->render_slot];
3018
3019                 /* set proper views */
3020                 image_init_multilayer_multiview(ima, rr);
3021         }
3022
3023         return rr;
3024 }
3025
3026 void BKE_image_release_renderresult(Scene *scene, Image *ima)
3027 {
3028         if (ima->rr) {
3029                 /* pass */
3030         }
3031         else if (ima->type == IMA_TYPE_R_RESULT) {
3032                 if (ima->render_slot == ima->last_render_slot)
3033                         RE_ReleaseResult(RE_GetSceneRender(scene));
3034         }
3035 }
3036
3037 bool BKE_image_is_openexr(struct Image *ima)
3038 {
3039 #ifdef WITH_OPENEXR
3040         if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE)) {
3041                 return BLI_testextensie(ima->name, ".exr");
3042         }
3043 #else
3044         UNUSED_VARS(ima);
3045 #endif
3046         return false;
3047 }
3048
3049 void BKE_image_backup_render(Scene *scene, Image *ima, bool free_current_slot)
3050 {
3051         /* called right before rendering, ima->renders contains render
3052          * result pointers for everything but the current render */
3053         Render *re = RE_GetSceneRender(scene);
3054         int slot = ima->render_slot, last = ima->last_render_slot;
3055
3056         if (slot != last) {
3057                 ima->renders[last] = NULL;
3058                 RE_SwapResult(re, &ima->renders[last]);
3059
3060                 if (ima->renders[slot]) {
3061                         if (free_current_slot) {
3062                                 RE_FreeRenderResult(ima->renders[slot]);
3063                                 ima->renders[slot] = NULL;
3064                         }
3065                         else {
3066                                 RE_SwapResult(re, &ima->renders[slot]);
3067                         }
3068                 }
3069         }
3070
3071         ima->last_render_slot = slot;
3072 }
3073
3074 /**************************** multiview load openexr *********************************/
3075
3076 static void image_add_view(Image *ima, const char *viewname, const char *filepath)
3077 {
3078         ImageView *iv;
3079
3080         iv = MEM_mallocN(sizeof(ImageView), "Viewer Image View");
3081         STRNCPY(iv->name, viewname);
3082         STRNCPY(iv->filepath, filepath);
3083
3084         /* For stereo drawing we need to ensure:
3085          * STEREO_LEFT_NAME  == STEREO_LEFT_ID and
3086          * STEREO_RIGHT_NAME == STEREO_RIGHT_ID */
3087
3088         if (STREQ(viewname, STEREO_LEFT_NAME)) {
3089                 BLI_addhead(&ima->views, iv);
3090         }
3091         else if (STREQ(viewname, STEREO_RIGHT_NAME)) {
3092                 ImageView *left_iv = BLI_findstring(&ima->views, STEREO_LEFT_NAME, offsetof(ImageView, name));
3093
3094                 if (left_iv == NULL) {
3095                         BLI_addhead(&ima->views, iv);
3096                 }
3097                 else {
3098                         BLI_insertlinkafter(&ima->views, left_iv, iv);
3099                 }
3100         }
3101         else {
3102                 BLI_addtail(&ima->views, iv);
3103         }
3104 }
3105
3106 /* after imbuf load, openexr type can return with a exrhandle open */
3107 /* in that case we have to build a render-result */
3108 #ifdef WITH_OPENEXR
3109 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
3110 {
3111         const char *colorspace = ima->colorspace_settings.name;
3112         bool predivide = (ima->alpha_mode == IMA_ALPHA_PREMUL);
3113
3114         /* only load rr once for multiview */
3115         if (!ima->rr)
3116                 ima->rr = RE_MultilayerConvert(ibuf->userdata, colorspace, predivide, ibuf->x, ibuf->y);
3117
3118         IMB_exr_close(ibuf->userdata);
3119
3120         ibuf->userdata = NULL;
3121         if (ima->rr)
3122                 ima->rr->framenr = framenr;
3123
3124         /* set proper views */
3125         image_init_multilayer_multiview(ima, ima->rr);
3126 }
3127 #endif  /* WITH_OPENEXR */
3128
3129 /* common stuff to do with images after loading */
3130 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
3131 {
3132         /* Preview is NULL when it has never been used as an icon before.
3133          * Never handle previews/icons outside of main thread. */
3134         if (G.background == 0 && ima->preview == NULL && BLI_thread_is_main()) {
3135                 BKE_icon_changed(BKE_icon_id_ensure(&ima->id));
3136         }
3137
3138         /* fields */
3139         if (ima->flag & IMA_FIELDS) {
3140                 if (ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
3141                 else de_interlace_ng(ibuf);
3142         }
3143         /* timer */
3144         BKE_image_tag_time(ima);
3145
3146         ima->ok = IMA_OK_LOADED;
3147
3148 }
3149
3150 static int imbuf_alpha_flags_for_image(Image *ima)
3151 {
3152         int flag = 0;
3153
3154         if (ima->flag & IMA_IGNORE_ALPHA)
3155                 flag |= IB_ignore_alpha;
3156         else if (ima->alpha_mode == IMA_ALPHA_PREMUL)
3157                 flag |= IB_alphamode_premul;
3158
3159         return flag;
3160 }
3161
3162 /* the number of files will vary according to the stereo format */
3163 static int image_num_files(Image *ima)
3164 {
3165         const bool is_multiview = BKE_image_is_multiview(ima);
3166
3167         if (!is_multiview) {
3168                 return 1;
3169         }
3170         else if (ima->views_format == R_IMF_VIEWS_STEREO_3D) {
3171                 return 1;
3172         }
3173         /* R_IMF_VIEWS_INDIVIDUAL */
3174         else {
3175                 return BLI_listbase_count(&ima->views);
3176         }
3177 }
3178
3179 static ImBuf *load_sequence_single(Image *ima, ImageUser *iuser, int frame, const int view_id, bool *r_assign)
3180 {
3181         struct ImBuf *ibuf;
3182         char name[FILE_MAX];
3183         int flag;
3184         ImageUser iuser_t = {0};
3185
3186         /* XXX temp stuff? */
3187         if (ima->lastframe != frame)
3188                 ima->tpageflag |= IMA_TPAGE_REFRESH;
3189
3190         ima->lastframe = frame;
3191
3192         if (iuser) {
3193                 iuser_t = *iuser;
3194         }
3195         else {
3196                 /* TODO(sergey): Do we need to initialize something here? */
3197         }
3198
3199         iuser_t.view = view_id;
3200         BKE_image_user_file_path(&iuser_t, ima, name);
3201
3202         flag = IB_rect | IB_multilayer;
3203         flag |= imbuf_alpha_flags_for_image(ima);
3204
3205         /* read ibuf */
3206         ibuf = IMB_loadiffname(name, flag, ima->colorspace_settings.name);
3207
3208 #if 0
3209         if (ibuf) {
3210                 printf(AT " loaded %s\n", name);
3211         }
3212         else {
3213                 printf(AT " missed %s\n", name);
3214         }
3215 #endif
3216
3217         if (ibuf) {
3218 #ifdef WITH_OPENEXR
3219                 if (ibuf->ftype == IMB_FTYPE_OPENEXR && ibuf->userdata) {
3220                         /* Handle multilayer and multiview cases, don't assign ibuf here.
3221                          * will be set layer in BKE_image_acquire_ibuf from ima->rr. */
3222                         if (IMB_exr_has_multilayer(ibuf->userdata)) {
3223                                 image_create_multilayer(ima, ibuf, frame);
3224                                 ima->type = IMA_TYPE_MULTILAYER;
3225                                 IMB_freeImBuf(ibuf);
3226                                 ibuf = NULL;
3227                         }
3228                 }
3229                 else {
3230                         image_initialize_after_load(ima, ibuf);
3231                         *r_assign = true;
3232                 }
3233 #else
3234                 image_initialize_after_load(ima, ibuf);
3235                 *r_assign = true;
3236 #endif
3237         }
3238
3239         return ibuf;
3240 }
3241
3242 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
3243 {
3244         struct ImBuf *ibuf = NULL;
3245         const bool is_multiview = BKE_image_is_multiview(ima);
3246         const int totfiles = image_num_files(ima);
3247         bool assign = false;
3248
3249         if (!is_multiview) {
3250                 ibuf = load_sequence_single(ima, iuser, frame, 0, &assign);
3251                 if (assign) {
3252                         image_assign_ibuf(ima, ibuf, 0, frame);
3253                 }
3254         }
3255         else {
3256                 const int totviews = BLI_listbase_count(&ima->views);
3257                 int i;
3258                 struct ImBuf **ibuf_arr;
3259
3260                 ibuf_arr = MEM_mallocN(sizeof(ImBuf *) * totviews, "Image Views Imbufs");
3261
3262                 for (i = 0; i < totfiles; i++)
3263                         ibuf_arr[i] = load_sequence_single(ima, iuser, frame, i, &assign);
3264
3265                 if (BKE_image_is_stereo(ima) && ima->views_format == R_IMF_VIEWS_STEREO_3D)
3266                         IMB_ImBufFromStereo3d(ima->stereo3d_format, ibuf_arr[0], &ibuf_arr[0], &ibuf_arr[1]);
3267
3268                 /* return the original requested ImBuf */
3269                 ibuf = ibuf_arr[(iuser ? iuser->multi_index : 0)];
3270
3271                 if (assign) {
3272                         for (i = 0; i < totviews; i++) {
3273                                 image_assign_ibuf(ima, ibuf_arr[i], i, frame);
3274                         }
3275                 }
3276
3277                 /* "remove" the others (decrease their refcount) */
3278                 for (i = 0; i < totviews; i++) {
3279                         if (ibuf_arr[i] != ibuf) {
3280                                 IMB_freeImBuf(ibuf_arr[i]);
3281                         }
3282                 }
3283
3284                 /* cleanup */
3285                 MEM_freeN(ibuf_arr);
3286         }
3287
3288         return ibuf;
3289 }
3290
3291 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
3292 {
3293         struct ImBuf *ibuf = NULL;
3294
3295         /* either we load from RenderResult, or we have to load a new one */
3296
3297         /* check for new RenderResult */
3298         if (ima->rr == NULL || frame != ima->rr->framenr) {
3299                 if (ima->rr) {
3300                         /* Cached image buffers shares pointers with render result,
3301                          * need to ensure there's no image buffers are hanging around
3302                          * with dead links after freeing the render result.
3303                          */
3304                         image_free_cached_frames(ima);
3305                         RE_FreeRenderResult(ima->rr);
3306                         ima->rr = NULL;
3307                 }
3308
3309                 ibuf = image_load_sequence_file(ima, iuser, frame);
3310
3311                 if (ibuf) { /* actually an error */
3312                         ima->type = IMA_TYPE_IMAGE;
3313                         printf("error, multi is normal image\n");
3314                 }
3315         }
3316         if (ima->rr) {
3317                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
3318
3319                 if (rpass) {
3320                         // printf("load from pass %s\n", rpass->name);
3321                         /* since we free  render results, we copy the rect */
3322                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
3323                         ibuf->rect_float = MEM_dupallocN(rpass->rect);
3324                         ibuf->flags |= IB_rectfloat;
3325                         ibuf->mall = IB_rectfloat;
3326                         ibuf->channels = rpass->channels;
3327
3328                         image_initialize_after_load(ima, ibuf);
3329                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : 0, frame);
3330
3331                 }
3332                 // else printf("pass not found\n");
3333         }
3334         else
3335                 ima->ok = 0;
3336
3337         if (iuser)
3338                 iuser->ok = ima->ok;
3339
3340         return ibuf;
3341 }
3342
3343 static ImBuf *load_movie_single(Image *ima, ImageUser *iuser, int frame, const int view_id)
3344 {
3345         struct ImBuf *ibuf = NULL;
3346         ImageAnim *ia;
3347