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