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