3ba216dcc13937b7d2ef04a9b958a5aeb93cc722
[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 void BKE_stamp_info_callback(void *data, struct StampData *stamp_data, StampCallback callback, bool noskip)
2098 {
2099         if ((callback == NULL) || (stamp_data == NULL)) {
2100                 return;
2101         }
2102
2103 #define CALL(member, value_str) \
2104         if (noskip || stamp_data->member[0]) { \
2105                 callback(data, value_str, stamp_data->member, sizeof(stamp_data->member)); \
2106         } ((void)0)
2107
2108         CALL(file, "File");
2109         CALL(note, "Note");
2110         CALL(date, "Date");
2111         CALL(marker, "Marker");
2112         CALL(time, "Time");
2113         CALL(frame, "Frame");
2114         CALL(frame_range, "FrameRange");
2115         CALL(camera, "Camera");
2116         CALL(cameralens, "Lens");
2117         CALL(scene, "Scene");
2118         CALL(strip, "Strip");
2119         CALL(rendertime, "RenderTime");
2120         CALL(memory, "Memory");
2121         CALL(hostname, "Hostname");
2122
2123         LISTBASE_FOREACH(StampDataCustomField *, custom_field, &stamp_data->custom_fields) {
2124                 if (noskip || custom_field->value[0]) {
2125                         callback(data, custom_field->key, custom_field->value, strlen(custom_field->value) + 1);
2126                 }
2127         }
2128
2129 #undef CALL
2130 }
2131
2132 void BKE_render_result_stamp_data(RenderResult *rr, const char *key, const char *value)
2133 {
2134         StampData *stamp_data;
2135         if (rr->stamp_data == NULL) {
2136                 rr->stamp_data = MEM_callocN(sizeof(StampData), "RenderResult.stamp_data");
2137         }
2138         stamp_data = rr->stamp_data;
2139         StampDataCustomField *field = MEM_mallocN(sizeof(StampDataCustomField),
2140                                                   "StampData Custom Field");
2141         STRNCPY(field->key, key);
2142         field->value = BLI_strdup(value);
2143         BLI_addtail(&stamp_data->custom_fields, field);
2144 }
2145
2146 void BKE_stamp_data_free(struct StampData *stamp_data)
2147 {
2148         if (stamp_data == NULL) {
2149                 return;
2150         }
2151         LISTBASE_FOREACH(StampDataCustomField *, custom_field, &stamp_data->custom_fields) {
2152                 MEM_freeN(custom_field->value);
2153         }
2154         BLI_freelistN(&stamp_data->custom_fields);
2155         MEM_freeN(stamp_data);
2156 }
2157
2158 /* wrap for callback only */
2159 static void metadata_set_field(void *data, const char *propname, char *propvalue, int UNUSED(len))
2160 {
2161         /* We know it is an ImBuf* because that's what we pass to BKE_stamp_info_callback. */
2162         struct ImBuf *imbuf = data;
2163         IMB_metadata_set_field(imbuf->metadata, propname, propvalue);
2164 }
2165
2166 static void metadata_get_field(void *data, const char *propname, char *propvalue, int len)
2167 {
2168         /* We know it is an ImBuf* because that's what we pass to BKE_stamp_info_callback. */
2169         struct ImBuf *imbuf = data;
2170         IMB_metadata_get_field(imbuf->metadata, propname, propvalue, len);
2171 }
2172
2173 void BKE_imbuf_stamp_info(RenderResult *rr, struct ImBuf *ibuf)
2174 {
2175         struct StampData *stamp_data = rr->stamp_data;
2176         IMB_metadata_ensure(&ibuf->metadata);
2177         BKE_stamp_info_callback(ibuf, stamp_data, metadata_set_field, false);
2178 }
2179
2180 void BKE_stamp_info_from_imbuf(RenderResult *rr, struct ImBuf *ibuf)
2181 {
2182         if (rr->stamp_data == NULL) {
2183                 rr->stamp_data = MEM_callocN(sizeof(StampData), "RenderResult.stamp_data");
2184         }
2185         struct StampData *stamp_data = rr->stamp_data;
2186         IMB_metadata_ensure(&ibuf->metadata);
2187         BKE_stamp_info_callback(ibuf, stamp_data, metadata_get_field, true);
2188 }
2189
2190 bool BKE_imbuf_alpha_test(ImBuf *ibuf)
2191 {
2192         int tot;
2193         if (ibuf->rect_float) {
2194                 const float *buf = ibuf->rect_float;
2195                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
2196                         if (buf[3] < 1.0f) {
2197                                 return true;
2198                         }
2199                 }
2200         }
2201         else if (ibuf->rect) {
2202                 unsigned char *buf = (unsigned char *)ibuf->rect;
2203                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
2204                         if (buf[3] != 255) {
2205                                 return true;
2206                         }
2207                 }
2208         }
2209
2210         return false;
2211 }
2212
2213 /* note: imf->planes is ignored here, its assumed the image channels
2214  * are already set */
2215 void BKE_imbuf_write_prepare(ImBuf *ibuf, const ImageFormatData *imf)
2216 {
2217         char imtype = imf->imtype;
2218         char compress = imf->compress;
2219         char quality = imf->quality;
2220
2221         /* initialize all from image format */
2222         ibuf->foptions.flag = 0;
2223
2224         if (imtype == R_IMF_IMTYPE_IRIS) {
2225                 ibuf->ftype = IMB_FTYPE_IMAGIC;
2226         }
2227 #ifdef WITH_HDR
2228         else if (imtype == R_IMF_IMTYPE_RADHDR) {
2229                 ibuf->ftype = IMB_FTYPE_RADHDR;
2230         }
2231 #endif
2232         else if (ELEM(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
2233                 ibuf->ftype = IMB_FTYPE_PNG;
2234
2235                 if (imtype == R_IMF_IMTYPE_PNG) {
2236                         if (imf->depth == R_IMF_CHAN_DEPTH_16)
2237                                 ibuf->foptions.flag |= PNG_16BIT;
2238
2239                         ibuf->foptions.quality = compress;
2240                 }
2241
2242         }
2243 #ifdef WITH_DDS
2244         else if (imtype == R_IMF_IMTYPE_DDS) {
2245                 ibuf->ftype = IMB_FTYPE_DDS;
2246         }
2247 #endif
2248         else if (imtype == R_IMF_IMTYPE_BMP) {
2249                 ibuf->ftype = IMB_FTYPE_BMP;
2250         }
2251 #ifdef WITH_TIFF
2252         else if (imtype == R_IMF_IMTYPE_TIFF) {
2253                 ibuf->ftype = IMB_FTYPE_TIF;
2254
2255                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2256                         ibuf->foptions.flag |= TIF_16BIT;
2257                 }
2258                 if (imf->tiff_codec == R_IMF_TIFF_CODEC_NONE) {
2259                         ibuf->foptions.flag |= TIF_COMPRESS_NONE;
2260                 }
2261                 else if (imf->tiff_codec == R_IMF_TIFF_CODEC_DEFLATE) {
2262                         ibuf->foptions.flag |= TIF_COMPRESS_DEFLATE;
2263                 }
2264                 else if (imf->tiff_codec == R_IMF_TIFF_CODEC_LZW) {
2265                         ibuf->foptions.flag |= TIF_COMPRESS_LZW;
2266                 }
2267                 else if (imf->tiff_codec == R_IMF_TIFF_CODEC_PACKBITS) {
2268                         ibuf->foptions.flag |= TIF_COMPRESS_PACKBITS;
2269                 }
2270         }
2271 #endif
2272 #ifdef WITH_OPENEXR
2273         else if (ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
2274                 ibuf->ftype = IMB_FTYPE_OPENEXR;
2275                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
2276                         ibuf->foptions.flag |= OPENEXR_HALF;
2277                 ibuf->foptions.flag |= (imf->exr_codec & OPENEXR_COMPRESS);
2278
2279                 if (!(imf->flag & R_IMF_FLAG_ZBUF)) {
2280                         /* Signal for exr saving. */
2281                         IMB_freezbuffloatImBuf(ibuf);
2282                 }
2283
2284         }
2285 #endif
2286 #ifdef WITH_CINEON
2287         else if (imtype == R_IMF_IMTYPE_CINEON) {
2288                 ibuf->ftype = IMB_FTYPE_CINEON;
2289                 if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
2290                         ibuf->foptions.flag |= CINEON_LOG;
2291                 }
2292                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2293                         ibuf->foptions.flag |= CINEON_16BIT;
2294                 }
2295                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
2296                         ibuf->foptions.flag |= CINEON_12BIT;
2297                 }
2298                 else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
2299                         ibuf->foptions.flag |= CINEON_10BIT;
2300                 }
2301         }
2302         else if (imtype == R_IMF_IMTYPE_DPX) {
2303                 ibuf->ftype = IMB_FTYPE_DPX;
2304                 if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
2305                         ibuf->foptions.flag |= CINEON_LOG;
2306                 }
2307                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2308                         ibuf->foptions.flag |= CINEON_16BIT;
2309                 }
2310                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
2311                         ibuf->foptions.flag |= CINEON_12BIT;
2312                 }
2313                 else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
2314                         ibuf->foptions.flag |= CINEON_10BIT;
2315                 }
2316         }
2317 #endif
2318         else if (imtype == R_IMF_IMTYPE_TARGA) {
2319                 ibuf->ftype = IMB_FTYPE_TGA;
2320         }
2321         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
2322                 ibuf->ftype = IMB_FTYPE_TGA;
2323                 ibuf->foptions.flag = RAWTGA;
2324         }
2325 #ifdef WITH_OPENJPEG
2326         else if (imtype == R_IMF_IMTYPE_JP2) {
2327                 if (quality < 10) quality = 90;
2328                 ibuf->ftype = IMB_FTYPE_JP2;
2329                 ibuf->foptions.quality = quality;
2330
2331                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2332                         ibuf->foptions.flag |= JP2_16BIT;
2333                 }
2334                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
2335                         ibuf->foptions.flag |= JP2_12BIT;
2336                 }
2337
2338                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
2339                         ibuf->foptions.flag |= JP2_YCC;
2340                 }
2341
2342                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
2343                         ibuf->foptions.flag |= JP2_CINE;
2344                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
2345                                 ibuf->foptions.flag |= JP2_CINE_48FPS;
2346                 }
2347
2348                 if (imf->jp2_codec == R_IMF_JP2_CODEC_JP2)
2349                         ibuf->foptions.flag |= JP2_JP2;
2350                 else if (imf->jp2_codec == R_IMF_JP2_CODEC_J2K)
2351                         ibuf->foptions.flag |= JP2_J2K;
2352                 else
2353                         BLI_assert(!"Unsupported jp2 codec was specified in im_format->jp2_codec");
2354         }
2355 #endif
2356         else {
2357                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
2358                 if (quality < 10) quality = 90;
2359                 ibuf->ftype = IMB_FTYPE_JPG;
2360                 ibuf->foptions.quality = quality;
2361         }
2362 }
2363
2364 int BKE_imbuf_write(ImBuf *ibuf, const char *name, const ImageFormatData *imf)
2365 {
2366         int ok;
2367
2368         BKE_imbuf_write_prepare(ibuf, imf);
2369
2370         BLI_make_existing_file(name);
2371
2372         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
2373         if (ok == 0) {
2374                 perror(name);
2375         }
2376
2377         return(ok);
2378 }
2379
2380 /* same as BKE_imbuf_write() but crappy workaround not to permanently modify
2381  * _some_, values in the imbuf */
2382 int BKE_imbuf_write_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
2383                        const bool save_copy)
2384 {
2385         ImBuf ibuf_back = *ibuf;
2386         int ok;
2387
2388         /* all data is rgba anyway,
2389          * this just controls how to save for some formats */
2390         ibuf->planes = imf->planes;
2391
2392         ok = BKE_imbuf_write(ibuf, name, imf);
2393
2394         if (save_copy) {
2395                 /* note that we are not restoring _all_ settings */
2396                 ibuf->planes = ibuf_back.planes;
2397                 ibuf->ftype =  ibuf_back.ftype;
2398                 ibuf->foptions =  ibuf_back.foptions;
2399         }
2400
2401         return ok;
2402 }
2403
2404 int BKE_imbuf_write_stamp(
2405         Scene *scene, struct RenderResult *rr, ImBuf *ibuf, const char *name,
2406         const struct ImageFormatData *imf)
2407 {
2408         if (scene && scene->r.stamp & R_STAMP_ALL)
2409                 BKE_imbuf_stamp_info(rr, ibuf);
2410
2411         return BKE_imbuf_write(ibuf, name, imf);
2412 }
2413
2414 static void do_makepicstring(
2415         char *string, const char *base, const char *relbase, int frame, const char imtype,
2416         const ImageFormatData *im_format, const short use_ext, const short use_frames,
2417         const char *suffix)
2418 {
2419         if (string == NULL) return;
2420         BLI_strncpy(string, base, FILE_MAX - 10);   /* weak assumption */
2421         BLI_path_abs(string, relbase);
2422
2423         if (use_frames)
2424                 BLI_path_frame(string, frame, 4);
2425
2426         if (suffix)
2427                 BLI_path_suffix(string, FILE_MAX, suffix, "");
2428
2429         if (use_ext)
2430                 do_add_image_extension(string, imtype, im_format);
2431 }
2432
2433 void BKE_image_path_from_imformat(
2434         char *string, const char *base, const char *relbase, int frame,
2435         const ImageFormatData *im_format, const bool use_ext, const bool use_frames, const char *suffix)
2436 {
2437         do_makepicstring(string, base, relbase, frame, im_format->imtype, im_format, use_ext, use_frames, suffix);
2438 }
2439
2440 void BKE_image_path_from_imtype(
2441         char *string, const char *base, const char *relbase, int frame,
2442         const char imtype, const bool use_ext, const bool use_frames, const char *view)
2443 {
2444         do_makepicstring(string, base, relbase, frame, imtype, NULL, use_ext, use_frames, view);
2445 }
2446
2447 struct anim *openanim_noload(const char *name, int flags, int streamindex, char colorspace[IMA_MAX_SPACE])
2448 {
2449         struct anim *anim;
2450
2451         anim = IMB_open_anim(name, flags, streamindex, colorspace);
2452         return anim;
2453 }
2454
2455 /* used by sequencer too */
2456 struct anim *openanim(const char *name, int flags, int streamindex, char colorspace[IMA_MAX_SPACE])
2457 {
2458         struct anim *anim;
2459         struct ImBuf *ibuf;
2460
2461         anim = IMB_open_anim(name, flags, streamindex, colorspace);
2462         if (anim == NULL) return NULL;
2463
2464         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
2465         if (ibuf == NULL) {
2466                 if (BLI_exists(name))
2467                         printf("not an anim: %s\n", name);
2468                 else
2469                         printf("anim file doesn't exist: %s\n", name);
2470                 IMB_free_anim(anim);
2471                 return NULL;
2472         }
2473         IMB_freeImBuf(ibuf);
2474
2475         return(anim);
2476 }
2477
2478 /* ************************* New Image API *************** */
2479
2480
2481 /* Notes about Image storage
2482  * - packedfile
2483  *   -> written in .blend
2484  * - filename
2485  *   -> written in .blend
2486  * - movie
2487  *   -> comes from packedfile or filename
2488  * - renderresult
2489  *   -> comes from packedfile or filename
2490  * - listbase
2491  *   -> ibufs from exrhandle
2492  * - flipbook array
2493  *   -> ibufs come from movie, temporary renderresult or sequence
2494  * - ibuf
2495  *   -> comes from packedfile or filename or generated
2496  */
2497
2498
2499 /* forces existence of 1 Image for renderout or nodes, returns Image */
2500 /* name is only for default, when making new one */
2501 Image *BKE_image_verify_viewer(Main *bmain, int type, const char *name)
2502 {
2503         Image *ima;
2504
2505         for (ima = bmain->image.first; ima; ima = ima->id.next)
2506                 if (ima->source == IMA_SRC_VIEWER)
2507                         if (ima->type == type)
2508                                 break;
2509
2510         if (ima == NULL)
2511                 ima = image_alloc(bmain, name, IMA_SRC_VIEWER, type);
2512
2513         /* happens on reload, imagewindow cannot be image user when hidden*/
2514         if (ima->id.us == 0)
2515                 id_us_plus(&ima->id);
2516
2517         return ima;
2518 }
2519
2520 static void image_viewer_create_views(const RenderData *rd, Image *ima)
2521 {
2522         if ((rd->scemode & R_MULTIVIEW) == 0) {
2523                 image_add_view(ima, "", "");
2524         }
2525         else {
2526                 SceneRenderView *srv;
2527                 for (srv = rd->views.first; srv; srv = srv->next) {
2528                         if (BKE_scene_multiview_is_render_view_active(rd, srv) == false)
2529                                 continue;
2530                         image_add_view(ima, srv->name, "");
2531                 }
2532         }
2533 }
2534
2535 /* Reset the image cache and views when the Viewer Nodes views don't match the scene views */
2536 void BKE_image_verify_viewer_views(const RenderData *rd, Image *ima, ImageUser *iuser)
2537 {
2538         bool do_reset;
2539         const bool is_multiview = (rd->scemode & R_MULTIVIEW) != 0;
2540
2541         BLI_thread_lock(LOCK_DRAW_IMAGE);
2542
2543         if (!BKE_scene_multiview_is_stereo3d(rd))
2544                 iuser->flag &= ~IMA_SHOW_STEREO;
2545
2546         /* see if all scene render views are in the image view list */
2547         do_reset = (BKE_scene_multiview_num_views_get(rd) != BLI_listbase_count(&ima->views));
2548
2549         /* multiview also needs to be sure all the views are synced */
2550         if (is_multiview && !do_reset) {
2551                 SceneRenderView *srv;
2552                 ImageView *iv;
2553
2554                 for (iv = ima->views.first; iv; iv = iv->next) {
2555                         srv = BLI_findstring(&rd->views, iv->name, offsetof(SceneRenderView, name));
2556                         if ((srv == NULL) || (BKE_scene_multiview_is_render_view_active(rd, srv) == false)) {
2557                                 do_reset = true;
2558                                 break;
2559                         }
2560                 }
2561         }
2562
2563         if (do_reset) {
2564                 BLI_spin_lock(&image_spin);
2565
2566                 image_free_cached_frames(ima);
2567                 BKE_image_free_views(ima);
2568
2569                 /* add new views */
2570                 image_viewer_create_views(rd, ima);
2571
2572                 BLI_spin_unlock(&image_spin);
2573         }
2574
2575         BLI_thread_unlock(LOCK_DRAW_IMAGE);
2576 }
2577
2578 void BKE_image_walk_all_users(const Main *mainp, void *customdata,
2579                               void callback(Image *ima, ImageUser *iuser, void *customdata))
2580 {
2581         wmWindowManager *wm;
2582         wmWindow *win;
2583         Tex *tex;
2584
2585         /* texture users */
2586         for (tex = mainp->tex.first; tex; tex = tex->id.next) {
2587                 if (tex->type == TEX_IMAGE && tex->ima) {
2588                         callback(tex->ima, &tex->iuser, customdata);
2589                 }
2590
2591                 if (tex->nodetree) {
2592                         bNode *node;
2593                         for (node = tex->nodetree->nodes.first; node; node = node->next) {
2594                                 if (node->id && node->type == TEX_NODE_IMAGE) {
2595                                         Image *ima = (Image *)node->id;
2596                                         ImageUser *iuser = node->storage;
2597                                         callback(ima, iuser, customdata);
2598                                 }
2599                         }
2600                 }
2601         }
2602
2603         for (Camera *cam = mainp->camera.first; cam; cam = cam->id.next) {
2604                 for (CameraBGImage *bgpic = cam->bg_images.first; bgpic; bgpic = bgpic->next) {
2605                         callback(bgpic->ima, &bgpic->iuser, customdata);
2606                 }
2607         }
2608
2609         /* image window, compo node users */
2610         for (wm = mainp->wm.first; wm; wm = wm->id.next) { /* only 1 wm */
2611                 for (win = wm->windows.first; win; win = win->next) {
2612                         const bScreen *screen = BKE_workspace_active_screen_get(win->workspace_hook);
2613
2614                         for (ScrArea *sa = screen->areabase.first; sa; sa = sa->next) {
2615                                 if (sa->spacetype == SPACE_IMAGE) {
2616                                         SpaceImage *sima = sa->spacedata.first;
2617                                         callback(sima->image, &sima->iuser, customdata);
2618                                 }
2619                                 else if (sa->spacetype == SPACE_NODE) {
2620                                         SpaceNode *snode = sa->spacedata.first;
2621                                         if (snode->nodetree && snode->nodetree->type == NTREE_COMPOSIT) {
2622                                                 bNode *node;
2623                                                 for (node = snode->nodetree->nodes.first; node; node = node->next) {
2624                                                         if (node->id && node->type == CMP_NODE_IMAGE) {
2625                                                                 Image *ima = (Image *)node->id;
2626                                                                 ImageUser *iuser = node->storage;
2627                                                                 callback(ima, iuser, customdata);
2628                                                         }
2629                                                 }
2630                                         }
2631                                 }
2632                         }
2633                 }
2634         }
2635 }
2636
2637 static void image_tag_frame_recalc(Image *ima, ImageUser *iuser, void *customdata)
2638 {
2639         Image *changed_image = customdata;
2640
2641         if (ima == changed_image && BKE_image_is_animated(ima)) {
2642                 iuser->flag |= IMA_NEED_FRAME_RECALC;
2643         }
2644 }
2645
2646 static void image_init_imageuser(Image *ima, ImageUser *iuser)
2647 {
2648         RenderResult *rr = ima->rr;
2649
2650         iuser->multi_index = 0;
2651         iuser->layer = iuser->pass = iuser->view = 0;
2652
2653         if (rr)
2654                 BKE_image_multilayer_index(rr, iuser);
2655 }
2656
2657 void BKE_image_init_imageuser(Image *ima, ImageUser *iuser)
2658 {
2659         image_init_imageuser(ima, iuser);
2660 }
2661
2662 void BKE_image_signal(Main *bmain, Image *ima, ImageUser *iuser, int signal)
2663 {
2664         if (ima == NULL)
2665                 return;
2666
2667         BLI_spin_lock(&image_spin);
2668
2669         switch (signal) {
2670                 case IMA_SIGNAL_FREE:
2671                         BKE_image_free_buffers(ima);
2672
2673                         if (iuser) {
2674                                 iuser->ok = 1;
2675                                 if (iuser->scene) {
2676                                         image_update_views_format(ima, iuser);
2677                                 }
2678                         }
2679                         break;
2680                 case IMA_SIGNAL_SRC_CHANGE:
2681                         if (ima->type == IMA_TYPE_UV_TEST)
2682                                 if (ima->source != IMA_SRC_GENERATED)
2683                                         ima->type = IMA_TYPE_IMAGE;
2684
2685                         if (ima->source == IMA_SRC_GENERATED) {
2686                                 if (ima->gen_x == 0 || ima->gen_y == 0) {
2687                                         ImBuf *ibuf = image_get_cached_ibuf_for_index_frame(ima, IMA_NO_INDEX, 0);
2688                                         if (ibuf) {
2689                                                 ima->gen_x = ibuf->x;
2690                                                 ima->gen_y = ibuf->y;
2691                                                 IMB_freeImBuf(ibuf);
2692                                         }
2693                                 }
2694
2695                                 /* Changing source type to generated will likely change file format
2696                                  * used by generated image buffer. Saving different file format to
2697                                  * the old name might confuse other applications.
2698                                  *
2699                                  * Here we ensure original image path wouldn't be used when saving
2700                                  * generated image.
2701                                  */
2702                                 ima->name[0] = '\0';
2703                         }
2704
2705                         /* image buffers for non-sequence multilayer will share buffers with RenderResult,
2706                          * however sequence multilayer will own buffers. Such logic makes switching from
2707                          * single multilayer file to sequence completely unstable
2708                          * since changes in nodes seems this workaround isn't needed anymore, all sockets
2709                          * are nicely detecting anyway, but freeing buffers always here makes multilayer
2710                          * sequences behave stable
2711                          */
2712                         BKE_image_free_buffers(ima);
2713
2714                         ima->ok = 1;
2715                         if (iuser)
2716                                 iuser->ok = 1;
2717
2718                         BKE_image_walk_all_users(bmain, ima, image_tag_frame_recalc);
2719
2720                         break;
2721
2722                 case IMA_SIGNAL_RELOAD:
2723                         /* try to repack file */
2724                         if (BKE_image_has_packedfile(ima)) {
2725                                 const int totfiles = image_num_files(ima);
2726
2727                                 if (totfiles != BLI_listbase_count_at_most(&ima->packedfiles, totfiles + 1)) {
2728                                         /* in case there are new available files to be loaded */
2729                                         image_free_packedfiles(ima);
2730                                         BKE_image_packfiles(NULL, ima, ID_BLEND_PATH(bmain, &ima->id));
2731                                 }
2732                                 else {
2733                                         ImagePackedFile *imapf;
2734                                         for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next) {
2735                                                 PackedFile *pf;
2736                                                 pf = newPackedFile(NULL, imapf->filepath, ID_BLEND_PATH(bmain, &ima->id));
2737                                                 if (pf) {
2738                                                         freePackedFile(imapf->packedfile);
2739                                                         imapf->packedfile = pf;
2740                                                 }
2741                                                 else {
2742                                                         printf("ERROR: Image \"%s\" not available. Keeping packed image\n", imapf->filepath);
2743                                                 }
2744                                         }
2745                                 }
2746
2747                                 if (BKE_image_has_packedfile(ima))
2748                                         BKE_image_free_buffers(ima);
2749                         }
2750                         else
2751                                 BKE_image_free_buffers(ima);
2752
2753                         if (iuser) {
2754                                 iuser->ok = 1;
2755                                 if (iuser->scene) {
2756                                         image_update_views_format(ima, iuser);
2757                                 }
2758                         }
2759
2760                         break;
2761                 case IMA_SIGNAL_USER_NEW_IMAGE:
2762                         if (iuser) {
2763                                 iuser->ok = 1;
2764                                 if (ima->source == IMA_SRC_FILE || ima->source == IMA_SRC_SEQUENCE) {
2765                                         if (ima->type == IMA_TYPE_MULTILAYER) {
2766                                                 image_init_imageuser(ima, iuser);
2767                                         }
2768                                 }
2769                         }
2770                         break;
2771                 case IMA_SIGNAL_COLORMANAGE:
2772                         BKE_image_free_buffers(ima);
2773
2774                         ima->ok = 1;
2775
2776                         if (iuser)
2777                                 iuser->ok = 1;
2778
2779                         break;
2780         }
2781
2782         BLI_spin_unlock(&image_spin);
2783
2784         /* don't use notifiers because they are not 100% sure to succeeded
2785          * this also makes sure all scenes are accounted for. */
2786         {
2787                 Scene *scene;
2788                 for (scene = bmain->scene.first; scene; scene = scene->id.next) {
2789                         if (scene->nodetree) {
2790                                 nodeUpdateID(scene->nodetree, &ima->id);
2791                         }
2792                 }
2793         }
2794 }
2795
2796 /* return renderpass for a given pass index and active view */
2797 /* fallback to available if there are missing passes for active view */
2798 static RenderPass *image_render_pass_get(RenderLayer *rl, const int pass, const int view, int *r_passindex)
2799 {
2800         RenderPass *rpass_ret = NULL;
2801         RenderPass *rpass;
2802
2803         int rp_index = 0;
2804         const char *rp_name = "";
2805
2806         for (rpass = rl->passes.first; rpass; rpass = rpass->next, rp_index++) {
2807                 if (rp_index == pass) {
2808                         rpass_ret = rpass;
2809                         if (view == 0) {
2810                                 /* no multiview or left eye */
2811                                 break;
2812                         }
2813                         else {
2814                                 rp_name = rpass->name;
2815                         }
2816                 }
2817                 /* multiview */
2818                 else if (rp_name[0] &&
2819                          STREQ(rpass->name, rp_name) &&
2820                          (rpass->view_id == view))
2821                 {
2822                         rpass_ret = rpass;
2823                         break;
2824                 }
2825         }
2826
2827         /* fallback to the first pass in the layer */
2828         if (rpass_ret == NULL) {
2829                 rp_index = 0;
2830                 rpass_ret = rl->passes.first;
2831         }
2832
2833         if (r_passindex) {
2834                 *r_passindex = (rpass == rpass_ret ? rp_index : pass);
2835         }
2836
2837         return rpass_ret;
2838 }
2839
2840 /* if layer or pass changes, we need an index for the imbufs list */
2841 /* note it is called for rendered results, but it doesn't use the index! */
2842 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
2843 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
2844 {
2845         RenderLayer *rl;
2846         RenderPass *rpass = NULL;
2847
2848         if (rr == NULL)
2849                 return NULL;
2850
2851         if (iuser) {
2852                 short index = 0, rv_index, rl_index = 0;
2853                 bool is_stereo = (iuser->flag & IMA_SHOW_STEREO) && RE_RenderResult_is_stereo(rr);
2854
2855                 rv_index = is_stereo ? iuser->multiview_eye : iuser->view;
2856                 if (RE_HasCombinedLayer(rr)) rl_index += 1;
2857
2858                 for (rl = rr->layers.first; rl; rl = rl->next, rl_index++) {
2859                         if (iuser->layer == rl_index) {
2860                                 int rp_index;
2861                                 rpass = image_render_pass_get(rl, iuser->pass, rv_index, &rp_index);
2862                                 iuser->multi_index = index + rp_index;
2863                                 break;
2864                         }
2865                         else {
2866                                 index += BLI_listbase_count(&rl->passes);
2867                         }
2868                 }
2869         }
2870
2871         return rpass;
2872 }
2873
2874 void BKE_image_multiview_index(Image *ima, ImageUser *iuser)
2875 {
2876         if (iuser) {
2877                 bool is_stereo = BKE_image_is_stereo(ima) && (iuser->flag & IMA_SHOW_STEREO);
2878                 if (is_stereo) {
2879                         iuser->multi_index = iuser->multiview_eye;
2880                 }
2881                 else {
2882                         if ((iuser->view < 0) || (iuser->view >= BLI_listbase_count_at_most(&ima->views, iuser->view + 1))) {
2883                                 iuser->multi_index = iuser->view = 0;
2884                         }
2885                         else {
2886                                 iuser->multi_index = iuser->view;
2887                         }
2888                 }
2889         }
2890 }
2891
2892 /* if layer or pass changes, we need an index for the imbufs list */
2893 /* note it is called for rendered results, but it doesn't use the index! */
2894 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
2895 bool BKE_image_is_multilayer(Image *ima)
2896 {
2897         if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE)) {
2898                 if (ima->type == IMA_TYPE_MULTILAYER) {
2899                         return true;
2900                 }
2901         }
2902         else if (ima->source == IMA_SRC_VIEWER) {
2903                 if (ima->type == IMA_TYPE_R_RESULT) {
2904                         return true;
2905                 }
2906         }
2907         return false;
2908 }
2909
2910 bool BKE_image_is_multiview(Image *ima)
2911 {
2912         ImageView *view = ima->views.first;
2913         return (view && (view->next || view->name[0]));
2914 }
2915
2916 bool BKE_image_is_stereo(Image *ima)
2917 {
2918         return BKE_image_is_multiview(ima) &&
2919                (BLI_findstring(&ima->views, STEREO_LEFT_NAME, offsetof(ImageView, name)) &&
2920                 BLI_findstring(&ima->views, STEREO_RIGHT_NAME, offsetof(ImageView, name)));
2921 }
2922
2923 static void image_init_multilayer_multiview(Image *ima, RenderResult *rr)
2924 {
2925         /* update image views from render views, but only if they actually changed,
2926          * to avoid invalid memory access during render. ideally these should always
2927          * be acquired with a mutex along with the render result, but there are still
2928          * some places with just an image pointer that need to access views */
2929         if (rr && BLI_listbase_count(&ima->views) == BLI_listbase_count(&rr->views)) {
2930                 ImageView *iv = ima->views.first;
2931                 RenderView *rv = rr->views.first;
2932                 bool modified = false;
2933                 for (; rv; rv = rv->next, iv = iv->next) {
2934                         modified |= !STREQ(rv->name, iv->name);
2935                 }
2936                 if (!modified)
2937                         return;
2938         }
2939
2940         BKE_image_free_views(ima);
2941
2942         if (rr) {
2943                 for (RenderView *rv = rr->views.first; rv; rv = rv->next) {
2944                         ImageView *iv = MEM_callocN(sizeof(ImageView), "Viewer Image View");
2945                         STRNCPY(iv->name, rv->name);
2946                         BLI_addtail(&ima->views, iv);
2947                 }
2948         }
2949 }
2950
2951
2952 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
2953 {
2954         RenderResult *rr = NULL;
2955         if (ima->rr) {
2956                 rr = ima->rr;
2957         }
2958         else if (ima->type == IMA_TYPE_R_RESULT) {
2959                 if (ima->render_slot == ima->last_render_slot)
2960                         rr = RE_AcquireResultRead(RE_GetSceneRender(scene));
2961                 else
2962                         rr = BKE_image_get_renderslot(ima, ima->render_slot)->render;
2963
2964                 /* set proper views */
2965                 image_init_multilayer_multiview(ima, rr);
2966         }
2967
2968         return rr;
2969 }
2970
2971 void BKE_image_release_renderresult(Scene *scene, Image *ima)
2972 {
2973         if (ima->rr) {
2974                 /* pass */
2975         }
2976         else if (ima->type == IMA_TYPE_R_RESULT) {
2977                 if (ima->render_slot == ima->last_render_slot)
2978                         RE_ReleaseResult(RE_GetSceneRender(scene));
2979         }
2980 }
2981
2982 bool BKE_image_is_openexr(struct Image *ima)
2983 {
2984 #ifdef WITH_OPENEXR
2985         if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE)) {
2986                 return BLI_path_extension_check(ima->name, ".exr");
2987         }
2988 #else
2989         UNUSED_VARS(ima);
2990 #endif
2991         return false;
2992 }
2993
2994 void BKE_image_backup_render(Scene *scene, Image *ima, bool free_current_slot)
2995 {
2996         /* called right before rendering, ima->renderslots contains render
2997          * result pointers for everything but the current render */
2998         Render *re = RE_GetSceneRender(scene);
2999
3000         /* Ensure we always have a valid render slot. */
3001         if (!ima->renderslots.first) {
3002                 BKE_image_add_renderslot(ima, NULL);
3003                 ima->render_slot = 0;
3004                 ima->last_render_slot = 0;
3005         }
3006         else if (ima->render_slot >= BLI_listbase_count(&ima->renderslots)) {
3007                 ima->render_slot = 0;
3008                 ima->last_render_slot = 0;
3009         }
3010
3011         RenderSlot *last_slot = BKE_image_get_renderslot(ima, ima->last_render_slot);
3012         RenderSlot *cur_slot = BKE_image_get_renderslot(ima, ima->render_slot);
3013
3014         if (last_slot && ima->render_slot != ima->last_render_slot) {
3015                 last_slot->render = NULL;
3016                 RE_SwapResult(re, &last_slot->render);
3017
3018                 if (cur_slot->render) {
3019                         if (free_current_slot) {
3020                                 BKE_image_clear_renderslot(ima, NULL, ima->render_slot);
3021                         }
3022                         else {
3023                                 RE_SwapResult(re, &cur_slot->render);
3024                         }
3025                 }
3026         }
3027
3028         ima->last_render_slot = ima->render_slot;
3029 }
3030
3031 /**************************** multiview load openexr *********************************/
3032
3033 static void image_add_view(Image *ima, const char *viewname, const char *filepath)
3034 {
3035         ImageView *iv;
3036
3037         iv = MEM_mallocN(sizeof(ImageView), "Viewer Image View");
3038         STRNCPY(iv->name, viewname);
3039         STRNCPY(iv->filepath, filepath);
3040
3041         /* For stereo drawing we need to ensure:
3042          * STEREO_LEFT_NAME  == STEREO_LEFT_ID and
3043          * STEREO_RIGHT_NAME == STEREO_RIGHT_ID */
3044
3045         if (STREQ(viewname, STEREO_LEFT_NAME)) {
3046                 BLI_addhead(&ima->views, iv);
3047         }
3048         else if (STREQ(viewname, STEREO_RIGHT_NAME)) {
3049                 ImageView *left_iv = BLI_findstring(&ima->views, STEREO_LEFT_NAME, offsetof(ImageView, name));
3050
3051                 if (left_iv == NULL) {
3052                         BLI_addhead(&ima->views, iv);
3053                 }
3054                 else {
3055                         BLI_insertlinkafter(&ima->views, left_iv, iv);
3056                 }
3057         }
3058         else {
3059                 BLI_addtail(&ima->views, iv);
3060         }
3061 }
3062
3063 /* after imbuf load, openexr type can return with a exrhandle open */
3064 /* in that case we have to build a render-result */
3065 #ifdef WITH_OPENEXR
3066 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
3067 {
3068         const char *colorspace = ima->colorspace_settings.name;
3069         bool predivide = (ima->alpha_mode == IMA_ALPHA_PREMUL);
3070
3071         /* only load rr once for multiview */
3072         if (!ima->rr)
3073                 ima->rr = RE_MultilayerConvert(ibuf->userdata, colorspace, predivide, ibuf->x, ibuf->y);
3074
3075         IMB_exr_close(ibuf->userdata);
3076
3077         ibuf->userdata = NULL;
3078         if (ima->rr != NULL) {
3079                 ima->rr->framenr = framenr;
3080                 BKE_stamp_info_from_imbuf(ima->rr, ibuf);
3081         }
3082
3083         /* set proper views */
3084         image_init_multilayer_multiview(ima, ima->rr);
3085 }
3086 #endif  /* WITH_OPENEXR */
3087
3088 /* common stuff to do with images after loading */
3089 static void image_initialize_after_load(Image *ima, ImBuf *UNUSED(ibuf))
3090 {
3091         /* Preview is NULL when it has never been used as an icon before.
3092          * Never handle previews/icons outside of main thread. */
3093         if (G.background == 0 && ima->preview == NULL && BLI_thread_is_main()) {
3094                 BKE_icon_changed(BKE_icon_id_ensure(&ima->id));
3095         }
3096
3097         /* timer */
3098         BKE_image_tag_time(ima);
3099
3100         ima->ok = IMA_OK_LOADED;
3101
3102 }
3103
3104 static int imbuf_alpha_flags_for_image(Image *ima)
3105 {
3106         int flag = 0;
3107
3108         if (ima->flag & IMA_IGNORE_ALPHA)
3109                 flag |= IB_ignore_alpha;
3110         else if (ima->alpha_mode == IMA_ALPHA_PREMUL)
3111                 flag |= IB_alphamode_premul;
3112
3113         return flag;
3114 }
3115
3116 /* the number of files will vary according to the stereo format */
3117 static int image_num_files(Image *ima)
3118 {
3119         const bool is_multiview = BKE_image_is_multiview(ima);
3120
3121         if (!is_multiview) {
3122                 return 1;
3123         }
3124         else if (ima->views_format == R_IMF_VIEWS_STEREO_3D) {
3125                 return 1;
3126         }
3127         /* R_IMF_VIEWS_INDIVIDUAL */
3128         else {
3129                 return BLI_listbase_count(&ima->views);
3130         }
3131 }
3132
3133 static ImBuf *load_sequence_single(Image *ima, ImageUser *iuser, int frame, const int view_id, bool *r_assign)
3134 {
3135         struct ImBuf *ibuf;
3136         char name[FILE_MAX];
3137         int flag;
3138         ImageUser iuser_t = {0};
3139
3140         /* XXX temp stuff? */
3141         if (ima->lastframe != frame)
3142                 ima->tpageflag |= IMA_TPAGE_REFRESH;
3143
3144         ima->lastframe = frame;
3145
3146         if (iuser) {
3147                 iuser_t = *iuser;
3148         }
3149         else {
3150                 /* TODO(sergey): Do we need to initialize something here? */
3151         }
3152
3153         iuser_t.view = view_id;
3154         BKE_image_user_file_path(&iuser_t, ima, name);
3155
3156         flag = IB_rect | IB_multilayer;
3157         flag |= imbuf_alpha_flags_for_image(ima);
3158
3159         /* read ibuf */
3160         ibuf = IMB_loadiffname(name, flag, ima->colorspace_settings.name);
3161
3162 #if 0
3163         if (ibuf) {
3164                 printf(AT " loaded %s\n", name);
3165         }
3166         else {
3167                 printf(AT " missed %s\n", name);
3168         }
3169 #endif
3170
3171         if (ibuf) {
3172 #ifdef WITH_OPENEXR
3173                 if (ibuf->ftype == IMB_FTYPE_OPENEXR && ibuf->userdata) {
3174                         /* Handle multilayer and multiview cases, don't assign ibuf here.
3175                          * will be set layer in BKE_image_acquire_ibuf from ima->rr. */
3176                         if (IMB_exr_has_multilayer(ibuf->userdata)) {
3177                                 image_create_multilayer(ima, ibuf, frame);
3178                                 ima->type = IMA_TYPE_MULTILAYER;
3179                                 IMB_freeImBuf(ibuf);
3180                                 ibuf = NULL;
3181                         }
3182                 }
3183                 else {
3184                         image_initialize_after_load(ima, ibuf);
3185                         *r_assign = true;
3186                 }
3187 #else
3188                 image_initialize_after_load(ima, ibuf);
3189                 *r_assign = true;
3190 #endif
3191         }
3192
3193         return ibuf;
3194 }
3195
3196 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
3197 {
3198         struct ImBuf *ibuf = NULL;
3199         const bool is_multiview = BKE_image_is_multiview(ima);
3200         const int totfiles = image_num_files(ima);
3201         bool assign = false;
3202
3203         if (!is_multiview) {
3204                 ibuf = load_sequence_single(ima, iuser, frame, 0, &assign);
3205                 if (assign) {
3206                         image_assign_ibuf(ima, ibuf, 0, frame);
3207                 }
3208         }
3209         else {
3210                 const int totviews = BLI_listbase_count(&ima->views);
3211                 int i;
3212                 struct ImBuf **ibuf_arr;
3213
3214                 ibuf_arr = MEM_mallocN(sizeof(ImBuf *) * totviews, "Image Views Imbufs");
3215
3216                 for (i = 0; i < totfiles; i++)
3217                         ibuf_arr[i] = load_sequence_single(ima, iuser, frame, i, &assign);
3218
3219                 if (BKE_image_is_stereo(ima) && ima->views_format == R_IMF_VIEWS_STEREO_3D)
3220                         IMB_ImBufFromStereo3d(ima->stereo3d_format, ibuf_arr[0], &ibuf_arr[0], &ibuf_arr[1]);
3221
3222                 /* return the original requested ImBuf */
3223                 ibuf = ibuf_arr[(iuser ? iuser->multi_index : 0)];
3224
3225                 if (assign) {
3226                         for (i = 0; i < totviews; i++) {
3227                                 image_assign_ibuf(ima, ibuf_arr[i], i, frame);
3228                         }
3229                 }
3230
3231                 /* "remove" the others (decrease their refcount) */
3232                 for (i = 0; i < totviews; i++) {
3233                         if (ibuf_arr[i] != ibuf) {
3234                                 IMB_freeImBuf(ibuf_arr[i]);
3235                         }
3236                 }
3237
3238                 /* cleanup */
3239                 MEM_freeN(ibuf_arr);
3240         }
3241
3242         return ibuf;
3243 }
3244
3245 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
3246 {
3247         struct ImBuf *ibuf = NULL;
3248
3249         /* either we load from RenderResult, or we have to load a new one */
3250
3251         /* check for new RenderResult */
3252         if (ima->rr == NULL || frame != ima->rr->framenr) {
3253                 if (ima->rr) {
3254                         /* Cached image buffers shares pointers with render result,
3255                          * need to ensure there's no image buffers are hanging around
3256                          * with dead links after freeing the render result.
3257                          */
3258                         image_free_cached_frames(ima);
3259                         RE_FreeRenderResult(ima->rr);
3260                         ima->rr = NULL;
3261                 }
3262
3263                 ibuf = image_load_sequence_file(ima, iuser, frame);
3264
3265                 if (ibuf) { /* actually an error */
3266                         ima->type = IMA_TYPE_IMAGE;
3267                         printf("error, multi is normal image\n");
3268                 }
3269         }
3270         if (ima->rr) {
3271                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
3272
3273                 if (rpass) {
3274                         // printf("load from pass %s\n", rpass->name);
3275                         /* since we free  render results, we copy the rect */
3276                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
3277                         ibuf->rect_float = MEM_dupallocN(rpass->rect);
3278                         ibuf->flags |= IB_rectfloat;
3279                         ibuf->mall = IB_rectfloat;
3280                         ibuf->channels = rpass->channels;
3281
3282                         BKE_imbuf_stamp_info(ima->rr, ibuf);
3283
3284                         image_initialize_after_load(ima, ibuf);
3285                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : 0, frame);
3286
3287                 }
3288                 // else printf("pass not found\n");
3289         }
3290         else
3291                 ima->ok = 0;
3292
3293         if (iuser)
3294                 iuser->ok = ima->ok;
3295
3296         return ibuf;
3297 }
3298
3299 static ImBuf *load_movie_single(Image *ima, ImageUser *iuser, int frame, const int view_id)
3300 {
3301         struct ImBuf *ibuf = NULL;
3302         ImageAnim *ia;
3303
3304         ia = BLI_findlink(&ima->anims, view_id);
3305
3306         if (ia->anim == NULL) {
3307                 char str[FILE_MAX];
3308                 int flags = IB_rect;
3309                 ImageUser iuser_t;
3310
3311                 if (ima->flag & IMA_DEINTERLACE) {
3312                         flags |= IB_animdeinterlace;
3313                 }
3314
3315                 if (iuser)
3316                         iuser_t = *iuser;
3317
3318                 iuser_t.view = view_id;
3319
3320                 BKE_image_user_file_path(&iuser_t, ima, str);
3321
3322                 /* FIXME: make several stream accessible in image editor, too*/
3323                 ia->anim = openanim(str, flags, 0, ima->colorspace_settings.name);
3324
3325                 /* let's initialize this user */
3326                 if (ia->anim && iuser && iuser->frames == 0)
3327                         iuser->frames = IMB_anim_get_duration(ia->anim,
3328                                                               IMB_TC_RECORD_RUN);
3329         }
3330
3331         if (ia->anim) {
3332         &n