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