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