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