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