b7885e08a6097257b973f9f11122796e7fc790e9
[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 }
1407
1408 void BKE_imbuf_to_image_format(struct ImageFormatData *im_format, const ImBuf *imbuf)
1409 {
1410         int ftype        = imbuf->ftype;
1411         int custom_flags = imbuf->foptions.flag;
1412         char quality     = imbuf->foptions.quality;
1413
1414         BKE_imformat_defaults(im_format);
1415
1416         /* file type */
1417
1418         if (ftype == IMB_FTYPE_IMAGIC)
1419                 im_format->imtype = R_IMF_IMTYPE_IRIS;
1420
1421 #ifdef WITH_HDR
1422         else if (ftype == IMB_FTYPE_RADHDR)
1423                 im_format->imtype = R_IMF_IMTYPE_RADHDR;
1424 #endif
1425
1426         else if (ftype == IMB_FTYPE_PNG) {
1427                 im_format->imtype = R_IMF_IMTYPE_PNG;
1428
1429                 if (custom_flags & PNG_16BIT)
1430                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1431
1432                 im_format->compress = quality;
1433         }
1434
1435 #ifdef WITH_DDS
1436         else if (ftype == IMB_FTYPE_DDS)
1437                 im_format->imtype = R_IMF_IMTYPE_DDS;
1438 #endif
1439
1440         else if (ftype == IMB_FTYPE_BMP)
1441                 im_format->imtype = R_IMF_IMTYPE_BMP;
1442
1443 #ifdef WITH_TIFF
1444         else if (ftype == IMB_FTYPE_TIF) {
1445                 im_format->imtype = R_IMF_IMTYPE_TIFF;
1446                 if (custom_flags & TIF_16BIT)
1447                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1448                 if (custom_flags & TIF_COMPRESS_NONE)
1449                         im_format->tiff_codec = R_IMF_TIFF_CODEC_NONE;
1450                 if (custom_flags & TIF_COMPRESS_DEFLATE)
1451                         im_format->tiff_codec = R_IMF_TIFF_CODEC_DEFLATE;
1452                 if (custom_flags & TIF_COMPRESS_LZW)
1453                         im_format->tiff_codec = R_IMF_TIFF_CODEC_LZW;
1454                 if (custom_flags & TIF_COMPRESS_PACKBITS)
1455                         im_format->tiff_codec = R_IMF_TIFF_CODEC_PACKBITS;
1456         }
1457 #endif
1458
1459 #ifdef WITH_OPENEXR
1460         else if (ftype == IMB_FTYPE_OPENEXR) {
1461                 im_format->imtype = R_IMF_IMTYPE_OPENEXR;
1462                 if (custom_flags & OPENEXR_HALF)
1463                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1464                 if (custom_flags & OPENEXR_COMPRESS)
1465                         im_format->exr_codec = R_IMF_EXR_CODEC_ZIP;  // Can't determine compression
1466                 if (imbuf->zbuf_float)
1467                         im_format->flag |= R_IMF_FLAG_ZBUF;
1468         }
1469 #endif
1470
1471 #ifdef WITH_CINEON
1472         else if (ftype == IMB_FTYPE_CINEON)
1473                 im_format->imtype = R_IMF_IMTYPE_CINEON;
1474         else if (ftype == IMB_FTYPE_DPX)
1475                 im_format->imtype = R_IMF_IMTYPE_DPX;
1476 #endif
1477
1478         else if (ftype == IMB_FTYPE_TGA) {
1479                 if (custom_flags & RAWTGA)
1480                         im_format->imtype = R_IMF_IMTYPE_RAWTGA;
1481                 else
1482                         im_format->imtype = R_IMF_IMTYPE_TARGA;
1483         }
1484 #ifdef WITH_OPENJPEG
1485         else if (ftype == IMB_FTYPE_JP2) {
1486                 im_format->imtype = R_IMF_IMTYPE_JP2;
1487                 im_format->quality = quality;
1488
1489                 if (custom_flags & JP2_16BIT)
1490                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1491                 else if (custom_flags & JP2_12BIT)
1492                         im_format->depth = R_IMF_CHAN_DEPTH_12;
1493
1494                 if (custom_flags & JP2_YCC)
1495                         im_format->jp2_flag |= R_IMF_JP2_FLAG_YCC;
1496
1497                 if (custom_flags & JP2_CINE) {
1498                         im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_PRESET;
1499                         if (custom_flags & JP2_CINE_48FPS)
1500                                 im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_48;
1501                 }
1502
1503                 if (custom_flags & JP2_JP2)
1504                         im_format->jp2_codec = R_IMF_JP2_CODEC_JP2;
1505                 else if (custom_flags & JP2_J2K)
1506                         im_format->jp2_codec = R_IMF_JP2_CODEC_J2K;
1507                 else
1508                         BLI_assert(!"Unsupported jp2 codec was specified in file type");
1509         }
1510 #endif
1511
1512         else {
1513                 im_format->imtype = R_IMF_IMTYPE_JPEG90;
1514                 im_format->quality = quality;
1515         }
1516
1517         /* planes */
1518         im_format->planes = imbuf->planes;
1519 }
1520
1521
1522 #define STAMP_NAME_SIZE ((MAX_ID_NAME - 2) + 16)
1523 /* could allow access externally - 512 is for long names,
1524  * STAMP_NAME_SIZE is for id names, allowing them some room for description */
1525 typedef struct StampDataCustomField {
1526         struct StampDataCustomField *next, *prev;
1527         /* TODO(sergey): Think of better size here, maybe dynamically allocated even. */
1528         char key[512];
1529         char value[512];
1530         /* TODO(sergey): Support non-string values. */
1531 } StampDataCustomField;
1532
1533 typedef struct StampData {
1534         char file[512];
1535         char note[512];
1536         char date[512];
1537         char marker[512];
1538         char time[512];
1539         char frame[512];
1540         char frame_range[512];
1541         char camera[STAMP_NAME_SIZE];
1542         char cameralens[STAMP_NAME_SIZE];
1543         char scene[STAMP_NAME_SIZE];
1544         char strip[STAMP_NAME_SIZE];
1545         char rendertime[STAMP_NAME_SIZE];
1546         char memory[STAMP_NAME_SIZE];
1547
1548         /* Custom fields are used to put extra meta information header from render
1549          * engine to the result image.
1550          *
1551          * NOTE: This fields are not stamped onto the image. At least for now.
1552          */
1553         ListBase custom_fields;
1554 } StampData;
1555 #undef STAMP_NAME_SIZE
1556
1557 /**
1558  * \param do_prefix: Include a label like "File ", "Date ", etc. in the stamp data strings.
1559  * \param use_dynamic: Also include data that can change on a per-frame basis.
1560  */
1561 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix,
1562                       bool use_dynamic)
1563 {
1564         char text[256];
1565         struct tm *tl;
1566         time_t t;
1567
1568         if (scene->r.stamp & R_STAMP_FILENAME) {
1569                 SNPRINTF(stamp_data->file, do_prefix ? "File %s" : "%s",
1570                          G.relbase_valid ? BKE_main_blendfile_path_from_global() : "<untitled>");
1571         }
1572         else {
1573                 stamp_data->file[0] = '\0';
1574         }
1575
1576         if (scene->r.stamp & R_STAMP_NOTE) {
1577                 /* Never do prefix for Note */
1578                 SNPRINTF(stamp_data->note, "%s", scene->r.stamp_udata);
1579         }
1580         else {
1581                 stamp_data->note[0] = '\0';
1582         }
1583
1584         if (scene->r.stamp & R_STAMP_DATE) {
1585                 t = time(NULL);
1586                 tl = localtime(&t);
1587                 SNPRINTF(text, "%04d/%02d/%02d %02d:%02d:%02d",
1588                          tl->tm_year + 1900, tl->tm_mon + 1, tl->tm_mday, tl->tm_hour, tl->tm_min, tl->tm_sec);
1589                 SNPRINTF(stamp_data->date, do_prefix ? "Date %s" : "%s", text);
1590         }
1591         else {
1592                 stamp_data->date[0] = '\0';
1593         }
1594
1595         if (use_dynamic && scene->r.stamp & R_STAMP_MARKER) {
1596                 const char *name = BKE_scene_find_last_marker_name(scene, CFRA);
1597
1598                 if (name) STRNCPY(text, name);
1599                 else STRNCPY(text, "<none>");
1600
1601                 SNPRINTF(stamp_data->marker, do_prefix ? "Marker %s" : "%s", text);
1602         }
1603         else {
1604                 stamp_data->marker[0] = '\0';
1605         }
1606
1607         if (use_dynamic && scene->r.stamp & R_STAMP_TIME) {
1608                 const short timecode_style = USER_TIMECODE_SMPTE_FULL;
1609                 BLI_timecode_string_from_time(text, sizeof(text), 0, FRA2TIME(scene->r.cfra), FPS, timecode_style);
1610                 SNPRINTF(stamp_data->time, do_prefix ? "Timecode %s" : "%s", text);
1611         }
1612         else {
1613                 stamp_data->time[0] = '\0';
1614         }
1615
1616         if (use_dynamic && scene->r.stamp & R_STAMP_FRAME) {
1617                 char fmtstr[32];
1618                 int digits = 1;
1619
1620                 if (scene->r.efra > 9)
1621                         digits = integer_digits_i(scene->r.efra);
1622
1623                 SNPRINTF(fmtstr, do_prefix ? "Frame %%0%di" : "%%0%di", digits);
1624                 SNPRINTF(stamp_data->frame, fmtstr, scene->r.cfra);
1625         }
1626         else {
1627                 stamp_data->frame[0] = '\0';
1628         }
1629
1630         if (scene->r.stamp & R_STAMP_FRAME_RANGE) {
1631                 SNPRINTF(stamp_data->frame_range,
1632                          do_prefix ? "Frame Range %d:%d" : "%d:%d",
1633                          scene->r.sfra, scene->r.efra);
1634         }
1635         else {
1636                 stamp_data->frame_range[0] = '\0';
1637         }
1638
1639         if (use_dynamic && scene->r.stamp & R_STAMP_CAMERA) {
1640                 SNPRINTF(stamp_data->camera, do_prefix ? "Camera %s" : "%s", camera ? camera->id.name + 2 : "<none>");
1641         }
1642         else {
1643                 stamp_data->camera[0] = '\0';
1644         }
1645
1646         if (use_dynamic && scene->r.stamp & R_STAMP_CAMERALENS) {
1647                 if (camera && camera->type == OB_CAMERA) {
1648                         SNPRINTF(text, "%.2f", ((Camera *)camera->data)->lens);
1649                 }
1650                 else {
1651                         STRNCPY(text, "<none>");
1652                 }
1653
1654                 SNPRINTF(stamp_data->cameralens, do_prefix ? "Lens %s" : "%s", text);
1655         }
1656         else {
1657                 stamp_data->cameralens[0] = '\0';
1658         }
1659
1660         if (scene->r.stamp & R_STAMP_SCENE) {
1661                 SNPRINTF(stamp_data->scene, do_prefix ? "Scene %s" : "%s", scene->id.name + 2);
1662         }
1663         else {
1664                 stamp_data->scene[0] = '\0';
1665         }
1666
1667         if (use_dynamic && scene->r.stamp & R_STAMP_SEQSTRIP) {
1668                 Sequence *seq = BKE_sequencer_foreground_frame_get(scene, scene->r.cfra);
1669
1670                 if (seq) STRNCPY(text, seq->name + 2);
1671                 else STRNCPY(text, "<none>");
1672
1673                 SNPRINTF(stamp_data->strip, do_prefix ? "Strip %s" : "%s", text);
1674         }
1675         else {
1676                 stamp_data->strip[0] = '\0';
1677         }
1678
1679         {
1680                 Render *re = RE_GetSceneRender(scene);
1681                 RenderStats *stats = re ? RE_GetStats(re) : NULL;
1682
1683                 if (use_dynamic && stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1684                         BLI_timecode_string_from_time_simple(text, sizeof(text), stats->lastframetime);
1685
1686                         SNPRINTF(stamp_data->rendertime, do_prefix ? "RenderTime %s" : "%s", text);
1687                 }
1688                 else {
1689                         stamp_data->rendertime[0] = '\0';
1690                 }
1691
1692                 if (use_dynamic && stats && (scene->r.stamp & R_STAMP_MEMORY)) {
1693                         SNPRINTF(stamp_data->memory, do_prefix ? "Peak Memory %.2fM" : "%.2fM", stats->mem_peak);
1694                 }
1695                 else {
1696                         stamp_data->memory[0] = '\0';
1697                 }
1698         }
1699         if (scene->r.stamp & R_STAMP_FRAME_RANGE) {
1700                 SNPRINTF(stamp_data->frame_range,
1701                              do_prefix ? "Frame Range %d:%d" : "%d:%d", scene->r.sfra, scene->r.efra);
1702         }
1703         else {
1704                 stamp_data->frame_range[0] = '\0';
1705         }
1706 }
1707
1708 /* Will always add prefix. */
1709 static void stampdata_from_template(StampData *stamp_data,
1710                                     const Scene *scene,
1711                                     const StampData *stamp_data_template)
1712 {
1713         if (scene->r.stamp & R_STAMP_FILENAME) {
1714                 SNPRINTF(stamp_data->file, "File %s", stamp_data_template->file);
1715         }
1716         else {
1717                 stamp_data->file[0] = '\0';
1718         }
1719         if (scene->r.stamp & R_STAMP_NOTE) {
1720                 SNPRINTF(stamp_data->note, "%s", stamp_data_template->note);
1721         }
1722         else {
1723                 stamp_data->note[0] = '\0';
1724         }
1725         if (scene->r.stamp & R_STAMP_DATE) {
1726                 SNPRINTF(stamp_data->date, "Date %s", stamp_data_template->date);
1727         }
1728         else {
1729                 stamp_data->date[0] = '\0';
1730         }
1731         if (scene->r.stamp & R_STAMP_MARKER) {
1732                 SNPRINTF(stamp_data->marker, "Marker %s", stamp_data_template->marker);
1733         }
1734         else {
1735                 stamp_data->marker[0] = '\0';
1736         }
1737         if (scene->r.stamp & R_STAMP_TIME) {
1738                 SNPRINTF(stamp_data->time, "Timecode %s", stamp_data_template->time);
1739         }
1740         else {
1741                 stamp_data->time[0] = '\0';
1742         }
1743         if (scene->r.stamp & R_STAMP_FRAME) {
1744                 SNPRINTF(stamp_data->frame, "Frame %s", stamp_data_template->frame);
1745         }
1746         else {
1747                 stamp_data->frame[0] = '\0';
1748         }
1749         if (scene->r.stamp & R_STAMP_CAMERA) {
1750                 SNPRINTF(stamp_data->camera, "Camera %s", stamp_data_template->camera);
1751         }
1752         else {
1753                 stamp_data->camera[0] = '\0';
1754         }
1755         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1756                 SNPRINTF(stamp_data->cameralens, "Lens %s", stamp_data_template->cameralens);
1757         }
1758         else {
1759                 stamp_data->cameralens[0] = '\0';
1760         }
1761         if (scene->r.stamp & R_STAMP_SCENE) {
1762                 SNPRINTF(stamp_data->scene, "Scene %s", stamp_data_template->scene);
1763         }
1764         else {
1765                 stamp_data->scene[0] = '\0';
1766         }
1767         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1768                 SNPRINTF(stamp_data->strip, "Strip %s", stamp_data_template->strip);
1769         }
1770         else {
1771                 stamp_data->strip[0] = '\0';
1772         }
1773         if (scene->r.stamp & R_STAMP_RENDERTIME) {
1774                 SNPRINTF(stamp_data->rendertime, "RenderTime %s", stamp_data_template->rendertime);
1775         }
1776         else {
1777                 stamp_data->rendertime[0] = '\0';
1778         }
1779         if (scene->r.stamp & R_STAMP_MEMORY) {
1780                 SNPRINTF(stamp_data->memory, "Peak Memory %s", stamp_data_template->memory);
1781         }
1782         else {
1783                 stamp_data->memory[0] = '\0';
1784         }
1785 }
1786
1787 void BKE_image_stamp_buf(
1788         Scene *scene, Object *camera, const StampData *stamp_data_template,
1789         unsigned char *rect, float *rectf, int width, int height, int channels)
1790 {
1791         struct StampData stamp_data;
1792         float w, h, pad;
1793         int x, y, y_ofs;
1794         float h_fixed;
1795         const int mono = blf_mono_font_render; // XXX
1796         struct ColorManagedDisplay *display;
1797         const char *display_device;
1798
1799         /* vars for calculating wordwrap */
1800         struct {
1801                 struct ResultBLF info;
1802                 rctf rect;
1803         } wrap;
1804
1805         /* this could be an argument if we want to operate on non linear float imbuf's
1806          * for now though this is only used for renders which use scene settings */
1807
1808 #define TEXT_SIZE_CHECK(str, w, h) \
1809         ((str[0]) && ((void)(h = h_fixed), (w = BLF_width(mono, str, sizeof(str)))))
1810
1811         /* must enable BLF_WORD_WRAP before using */
1812 #define TEXT_SIZE_CHECK_WORD_WRAP(str, w, h) \
1813         ((str[0]) && (BLF_boundbox_ex(mono, str, sizeof(str), &wrap.rect, &wrap.info), \
1814          (void)(h = h_fixed * wrap.info.lines), (w = BLI_rctf_size_x(&wrap.rect))))
1815
1816 #define BUFF_MARGIN_X 2
1817 #define BUFF_MARGIN_Y 1
1818
1819         if (!rect && !rectf)
1820                 return;
1821
1822         display_device = scene->display_settings.display_device;
1823         display = IMB_colormanagement_display_get_named(display_device);
1824
1825         if (stamp_data_template == NULL) {
1826                 stampdata(scene, camera, &stamp_data, (scene->r.stamp & R_STAMP_HIDE_LABELS) == 0, true);
1827         }
1828         else {
1829                 stampdata_from_template(&stamp_data, scene, stamp_data_template);
1830         }
1831
1832         /* TODO, do_versions */
1833         if (scene->r.stamp_font_id < 8)
1834                 scene->r.stamp_font_id = 12;
1835
1836         /* set before return */
1837         BLF_size(mono, scene->r.stamp_font_id, 72);
1838         BLF_wordwrap(mono, width - (BUFF_MARGIN_X * 2));
1839
1840         BLF_buffer(mono, rectf, rect, width, height, channels, display);
1841         BLF_buffer_col(mono, scene->r.fg_stamp);
1842         pad = BLF_width_max(mono);
1843
1844         /* use 'h_fixed' rather than 'h', aligns better */
1845         h_fixed = BLF_height_max(mono);
1846         y_ofs = -BLF_descender(mono);
1847
1848         x = 0;
1849         y = height;
1850
1851         if (TEXT_SIZE_CHECK(stamp_data.file, w, h)) {
1852                 /* Top left corner */
1853                 y -= h;
1854
1855                 /* also a little of space to the background. */
1856                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1857                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1858
1859                 /* and draw the text. */
1860                 BLF_position(mono, x, y + y_ofs, 0.0);
1861                 BLF_draw_buffer(mono, stamp_data.file, BLF_DRAW_STR_DUMMY_MAX);
1862
1863                 /* the extra pixel for background. */
1864                 y -= BUFF_MARGIN_Y * 2;
1865         }
1866
1867         /* Top left corner, below File */
1868         if (TEXT_SIZE_CHECK(stamp_data.date, w, h)) {
1869                 y -= h;
1870
1871                 /* and space for background. */
1872                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1873                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1874
1875                 BLF_position(mono, x, y + y_ofs, 0.0);
1876                 BLF_draw_buffer(mono, stamp_data.date, BLF_DRAW_STR_DUMMY_MAX);
1877
1878                 /* the extra pixel for background. */
1879                 y -= BUFF_MARGIN_Y * 2;
1880         }
1881
1882         /* Top left corner, below File, Date */
1883         if (TEXT_SIZE_CHECK(stamp_data.rendertime, w, h)) {
1884                 y -= h;
1885
1886                 /* and space for background. */
1887                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1888                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1889
1890                 BLF_position(mono, x, y + y_ofs, 0.0);
1891                 BLF_draw_buffer(mono, stamp_data.rendertime, BLF_DRAW_STR_DUMMY_MAX);
1892
1893                 /* the extra pixel for background. */
1894                 y -= BUFF_MARGIN_Y * 2;
1895         }
1896
1897         /* Top left corner, below File, Date, Rendertime */
1898         if (TEXT_SIZE_CHECK(stamp_data.memory, w, h)) {
1899                 y -= h;
1900
1901                 /* and space for background. */
1902                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1903                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1904
1905                 BLF_position(mono, x, y + y_ofs, 0.0);
1906                 BLF_draw_buffer(mono, stamp_data.memory, BLF_DRAW_STR_DUMMY_MAX);
1907
1908                 /* the extra pixel for background. */
1909                 y -= BUFF_MARGIN_Y * 2;
1910         }
1911
1912         /* Top left corner, below File, Date, Memory, Rendertime */
1913         BLF_enable(mono, BLF_WORD_WRAP);
1914         if (TEXT_SIZE_CHECK_WORD_WRAP(stamp_data.note, w, h)) {
1915                 y -= h;
1916
1917                 /* and space for background. */
1918                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1919                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1920
1921                 BLF_position(mono, x, y + y_ofs + (h - h_fixed), 0.0);
1922                 BLF_draw_buffer(mono, stamp_data.note, BLF_DRAW_STR_DUMMY_MAX);
1923         }
1924         BLF_disable(mono, BLF_WORD_WRAP);
1925
1926         x = 0;
1927         y = 0;
1928
1929         /* Bottom left corner, leaving space for timing */
1930         if (TEXT_SIZE_CHECK(stamp_data.marker, w, h)) {
1931
1932                 /* extra space for background. */
1933                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp,  display,
1934                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1935
1936                 /* and pad the text. */
1937                 BLF_position(mono, x, y + y_ofs, 0.0);
1938                 BLF_draw_buffer(mono, stamp_data.marker, BLF_DRAW_STR_DUMMY_MAX);
1939
1940                 /* space width. */
1941                 x += w + pad;
1942         }
1943
1944         /* Left bottom corner */
1945         if (TEXT_SIZE_CHECK(stamp_data.time, w, h)) {
1946
1947                 /* extra space for background */
1948                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1949                                   x - BUFF_MARGIN_X, y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1950
1951                 /* and pad the text. */
1952                 BLF_position(mono, x, y + y_ofs, 0.0);
1953                 BLF_draw_buffer(mono, stamp_data.time, BLF_DRAW_STR_DUMMY_MAX);
1954
1955                 /* space width. */
1956                 x += w + pad;
1957         }
1958
1959         if (TEXT_SIZE_CHECK(stamp_data.frame, w, h)) {
1960
1961                 /* extra space for background. */
1962                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1963                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1964
1965                 /* and pad the text. */
1966                 BLF_position(mono, x, y + y_ofs, 0.0);
1967                 BLF_draw_buffer(mono, stamp_data.frame, BLF_DRAW_STR_DUMMY_MAX);
1968
1969                 /* space width. */
1970                 x += w + pad;
1971         }
1972
1973         if (TEXT_SIZE_CHECK(stamp_data.camera, w, h)) {
1974
1975                 /* extra space for background. */
1976                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1977                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1978                 BLF_position(mono, x, y + y_ofs, 0.0);
1979                 BLF_draw_buffer(mono, stamp_data.camera, BLF_DRAW_STR_DUMMY_MAX);
1980
1981                 /* space width. */
1982                 x += w + pad;
1983         }
1984
1985         if (TEXT_SIZE_CHECK(stamp_data.cameralens, w, h)) {
1986
1987                 /* extra space for background. */
1988                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1989                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1990                 BLF_position(mono, x, y + y_ofs, 0.0);
1991                 BLF_draw_buffer(mono, stamp_data.cameralens, BLF_DRAW_STR_DUMMY_MAX);
1992         }
1993
1994         if (TEXT_SIZE_CHECK(stamp_data.scene, w, h)) {
1995
1996                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1997                 x = width - w - 2;
1998
1999                 /* extra space for background. */
2000                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
2001                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2002
2003                 /* and pad the text. */
2004                 BLF_position(mono, x, y + y_ofs, 0.0);
2005                 BLF_draw_buffer(mono, stamp_data.scene, BLF_DRAW_STR_DUMMY_MAX);
2006         }
2007
2008         if (TEXT_SIZE_CHECK(stamp_data.strip, w, h)) {
2009
2010                 /* Top right corner, with an extra space because blenfont is too strict! */
2011                 x = width - w - pad;
2012                 y = height - h;
2013
2014                 /* extra space for background. */
2015                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
2016                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2017
2018                 BLF_position(mono, x, y + y_ofs, 0.0);
2019                 BLF_draw_buffer(mono, stamp_data.strip, BLF_DRAW_STR_DUMMY_MAX);
2020         }
2021
2022         /* cleanup the buffer. */
2023         BLF_buffer(mono, NULL, NULL, 0, 0, 0, NULL);
2024         BLF_wordwrap(mono, 0);
2025
2026 #undef TEXT_SIZE_CHECK
2027 #undef TEXT_SIZE_CHECK_WORD_WRAP
2028 #undef BUFF_MARGIN_X
2029 #undef BUFF_MARGIN_Y
2030 }
2031
2032 void BKE_render_result_stamp_info(Scene *scene, Object *camera, struct RenderResult *rr, bool allocate_only)
2033 {
2034         struct StampData *stamp_data;
2035
2036         if (!(scene && (scene->r.stamp & R_STAMP_ALL)) && !allocate_only)
2037                 return;
2038
2039         if (!rr->stamp_data) {
2040                 stamp_data = MEM_callocN(sizeof(StampData), "RenderResult.stamp_data");
2041         }
2042         else {
2043                 stamp_data = rr->stamp_data;
2044         }
2045
2046         if (!allocate_only)
2047                 stampdata(scene, camera, stamp_data, 0, true);
2048
2049         if (!rr->stamp_data) {
2050                 rr->stamp_data = stamp_data;
2051         }
2052 }
2053
2054 struct StampData *BKE_stamp_info_from_scene_static(Scene *scene)
2055 {
2056         struct StampData *stamp_data;
2057
2058         if (!(scene && (scene->r.stamp & R_STAMP_ALL)))
2059                 return NULL;
2060
2061         /* Memory is allocated here (instead of by the caller) so that the caller
2062          * doesn't have to know the size of the StampData struct. */
2063         stamp_data = MEM_callocN(sizeof(StampData), __func__);
2064         stampdata(scene, NULL, stamp_data, 0, false);
2065
2066         return stamp_data;
2067 }
2068
2069 void BKE_stamp_info_callback(void *data, struct StampData *stamp_data, StampCallback callback, bool noskip)
2070 {
2071         if ((callback == NULL) || (stamp_data == NULL)) {
2072                 return;
2073         }
2074
2075 #define CALL(member, value_str) \
2076         if (noskip || stamp_data->member[0]) { \
2077                 callback(data, value_str, stamp_data->member, sizeof(stamp_data->member)); \
2078         } ((void)0)
2079
2080         CALL(file, "File");
2081         CALL(note, "Note");
2082         CALL(date, "Date");
2083         CALL(marker, "Marker");
2084         CALL(time, "Time");
2085         CALL(frame, "Frame");
2086         CALL(frame_range, "FrameRange");
2087         CALL(camera, "Camera");
2088         CALL(cameralens, "Lens");
2089         CALL(scene, "Scene");
2090         CALL(strip, "Strip");
2091         CALL(rendertime, "RenderTime");
2092         CALL(memory, "Memory");
2093
2094         for (StampDataCustomField *custom_field = stamp_data->custom_fields.first;
2095              custom_field != NULL;
2096              custom_field = custom_field->next)
2097         {
2098                 if (noskip || custom_field->value[0]) {
2099                         callback(data, custom_field->key, custom_field->value, sizeof(custom_field->value));
2100                 }
2101         }
2102
2103 #undef CALL
2104 }
2105
2106 void BKE_render_result_stamp_data(RenderResult *rr, const char *key, const char *value)
2107 {
2108         StampData *stamp_data;
2109         if (rr->stamp_data == NULL) {
2110                 rr->stamp_data = MEM_callocN(sizeof(StampData), "RenderResult.stamp_data");
2111         }
2112         stamp_data = rr->stamp_data;
2113         StampDataCustomField *field = MEM_mallocN(sizeof(StampDataCustomField),
2114                                                   "StampData Custom Field");
2115         STRNCPY(field->key, key);
2116         STRNCPY(field->value, value);
2117         BLI_addtail(&stamp_data->custom_fields, field);
2118 }
2119
2120 void BKE_stamp_data_free(struct StampData *stamp_data)
2121 {
2122         if (stamp_data == NULL) {
2123                 return;
2124         }
2125         BLI_freelistN(&stamp_data->custom_fields);
2126         MEM_freeN(stamp_data);
2127 }
2128
2129 /* wrap for callback only */
2130 static void metadata_set_field(void *data, const char *propname, char *propvalue, int UNUSED(len))
2131 {
2132         /* We know it is an ImBuf* because that's what we pass to BKE_stamp_info_callback. */
2133         struct ImBuf *imbuf = data;
2134         IMB_metadata_set_field(imbuf->metadata, propname, propvalue);
2135 }
2136
2137 static void metadata_get_field(void *data, const char *propname, char *propvalue, int len)
2138 {
2139         /* We know it is an ImBuf* because that's what we pass to BKE_stamp_info_callback. */
2140         struct ImBuf *imbuf = data;
2141         IMB_metadata_get_field(imbuf->metadata, propname, propvalue, len);
2142 }
2143
2144 void BKE_imbuf_stamp_info(RenderResult *rr, struct ImBuf *ibuf)
2145 {
2146         struct StampData *stamp_data = rr->stamp_data;
2147         IMB_metadata_ensure(&ibuf->metadata);
2148         BKE_stamp_info_callback(ibuf, stamp_data, metadata_set_field, false);
2149 }
2150
2151 void BKE_stamp_info_from_imbuf(RenderResult *rr, struct ImBuf *ibuf)
2152 {
2153         struct StampData *stamp_data = rr->stamp_data;
2154         IMB_metadata_ensure(&ibuf->metadata);
2155         BKE_stamp_info_callback(ibuf, stamp_data, metadata_get_field, true);
2156 }
2157
2158 bool BKE_imbuf_alpha_test(ImBuf *ibuf)
2159 {
2160         int tot;
2161         if (ibuf->rect_float) {
2162                 const float *buf = ibuf->rect_float;
2163                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
2164                         if (buf[3] < 1.0f) {
2165                                 return true;
2166                         }
2167                 }
2168         }
2169         else if (ibuf->rect) {
2170                 unsigned char *buf = (unsigned char *)ibuf->rect;
2171                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
2172                         if (buf[3] != 255) {
2173                                 return true;
2174                         }
2175                 }
2176         }
2177
2178         return false;
2179 }
2180
2181 /* note: imf->planes is ignored here, its assumed the image channels
2182  * are already set */
2183 void BKE_imbuf_write_prepare(ImBuf *ibuf, const ImageFormatData *imf)
2184 {
2185         char imtype = imf->imtype;
2186         char compress = imf->compress;
2187         char quality = imf->quality;
2188
2189         /* initialize all from image format */
2190         ibuf->foptions.flag = 0;
2191
2192         if (imtype == R_IMF_IMTYPE_IRIS) {
2193                 ibuf->ftype = IMB_FTYPE_IMAGIC;
2194         }
2195 #ifdef WITH_HDR
2196         else if (imtype == R_IMF_IMTYPE_RADHDR) {
2197                 ibuf->ftype = IMB_FTYPE_RADHDR;
2198         }
2199 #endif
2200         else if (ELEM(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
2201                 ibuf->ftype = IMB_FTYPE_PNG;
2202
2203                 if (imtype == R_IMF_IMTYPE_PNG) {
2204                         if (imf->depth == R_IMF_CHAN_DEPTH_16)
2205                                 ibuf->foptions.flag |= PNG_16BIT;
2206
2207                         ibuf->foptions.quality = compress;
2208                 }
2209
2210         }
2211 #ifdef WITH_DDS
2212         else if (imtype == R_IMF_IMTYPE_DDS) {
2213                 ibuf->ftype = IMB_FTYPE_DDS;
2214         }
2215 #endif
2216         else if (imtype == R_IMF_IMTYPE_BMP) {
2217                 ibuf->ftype = IMB_FTYPE_BMP;
2218         }
2219 #ifdef WITH_TIFF
2220         else if (imtype == R_IMF_IMTYPE_TIFF) {
2221                 ibuf->ftype = IMB_FTYPE_TIF;
2222
2223                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2224                         ibuf->foptions.flag |= TIF_16BIT;
2225                 }
2226                 if (imf->tiff_codec == R_IMF_TIFF_CODEC_NONE) {
2227                         ibuf->foptions.flag |= TIF_COMPRESS_NONE;
2228                 }
2229                 else if (imf->tiff_codec == R_IMF_TIFF_CODEC_DEFLATE) {
2230                         ibuf->foptions.flag |= TIF_COMPRESS_DEFLATE;
2231                 }
2232                 else if (imf->tiff_codec == R_IMF_TIFF_CODEC_LZW) {
2233                         ibuf->foptions.flag |= TIF_COMPRESS_LZW;
2234                 }
2235                 else if (imf->tiff_codec == R_IMF_TIFF_CODEC_PACKBITS) {
2236                         ibuf->foptions.flag |= TIF_COMPRESS_PACKBITS;
2237                 }
2238         }
2239 #endif
2240 #ifdef WITH_OPENEXR
2241         else if (ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
2242                 ibuf->ftype = IMB_FTYPE_OPENEXR;
2243                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
2244                         ibuf->foptions.flag |= OPENEXR_HALF;
2245                 ibuf->foptions.flag |= (imf->exr_codec & OPENEXR_COMPRESS);
2246
2247                 if (!(imf->flag & R_IMF_FLAG_ZBUF)) {
2248                         /* Signal for exr saving. */
2249                         IMB_freezbuffloatImBuf(ibuf);
2250                 }
2251
2252         }
2253 #endif
2254 #ifdef WITH_CINEON
2255         else if (imtype == R_IMF_IMTYPE_CINEON) {
2256                 ibuf->ftype = IMB_FTYPE_CINEON;
2257                 if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
2258                         ibuf->foptions.flag |= CINEON_LOG;
2259                 }
2260                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2261                         ibuf->foptions.flag |= CINEON_16BIT;
2262                 }
2263                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
2264                         ibuf->foptions.flag |= CINEON_12BIT;
2265                 }
2266                 else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
2267                         ibuf->foptions.flag |= CINEON_10BIT;
2268                 }
2269         }
2270         else if (imtype == R_IMF_IMTYPE_DPX) {
2271                 ibuf->ftype = IMB_FTYPE_DPX;
2272                 if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
2273                         ibuf->foptions.flag |= CINEON_LOG;
2274                 }
2275                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2276                         ibuf->foptions.flag |= CINEON_16BIT;
2277                 }
2278                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
2279                         ibuf->foptions.flag |= CINEON_12BIT;
2280                 }
2281                 else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
2282                         ibuf->foptions.flag |= CINEON_10BIT;
2283                 }
2284         }
2285 #endif
2286         else if (imtype == R_IMF_IMTYPE_TARGA) {
2287                 ibuf->ftype = IMB_FTYPE_TGA;
2288         }
2289         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
2290                 ibuf->ftype = IMB_FTYPE_TGA;
2291                 ibuf->foptions.flag = RAWTGA;
2292         }
2293 #ifdef WITH_OPENJPEG
2294         else if (imtype == R_IMF_IMTYPE_JP2) {
2295                 if (quality < 10) quality = 90;
2296                 ibuf->ftype = IMB_FTYPE_JP2;
2297                 ibuf->foptions.quality = quality;
2298
2299                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2300                         ibuf->foptions.flag |= JP2_16BIT;
2301                 }
2302                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
2303                         ibuf->foptions.flag |= JP2_12BIT;
2304                 }
2305
2306                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
2307                         ibuf->foptions.flag |= JP2_YCC;
2308                 }
2309
2310                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
2311                         ibuf->foptions.flag |= JP2_CINE;
2312                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
2313                                 ibuf->foptions.flag |= JP2_CINE_48FPS;
2314                 }
2315
2316                 if (imf->jp2_codec == R_IMF_JP2_CODEC_JP2)
2317                         ibuf->foptions.flag |= JP2_JP2;
2318                 else if (imf->jp2_codec == R_IMF_JP2_CODEC_J2K)
2319                         ibuf->foptions.flag |= JP2_J2K;
2320                 else
2321                         BLI_assert(!"Unsupported jp2 codec was specified in im_format->jp2_codec");
2322         }
2323 #endif
2324         else {
2325                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
2326                 if (quality < 10) quality = 90;
2327                 ibuf->ftype = IMB_FTYPE_JPG;
2328                 ibuf->foptions.quality = quality;
2329         }
2330 }
2331
2332 int BKE_imbuf_write(ImBuf *ibuf, const char *name, const ImageFormatData *imf)
2333 {
2334         int ok;
2335
2336         BKE_imbuf_write_prepare(ibuf, imf);
2337
2338         BLI_make_existing_file(name);
2339
2340         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
2341         if (ok == 0) {
2342                 perror(name);
2343         }
2344
2345         return(ok);
2346 }
2347
2348 /* same as BKE_imbuf_write() but crappy workaround not to permanently modify
2349  * _some_, values in the imbuf */
2350 int BKE_imbuf_write_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
2351                        const bool save_copy)
2352 {
2353         ImBuf ibuf_back = *ibuf;
2354         int ok;
2355
2356         /* all data is rgba anyway,
2357          * this just controls how to save for some formats */
2358         ibuf->planes = imf->planes;
2359
2360         ok = BKE_imbuf_write(ibuf, name, imf);
2361
2362         if (save_copy) {
2363                 /* note that we are not restoring _all_ settings */
2364                 ibuf->planes = ibuf_back.planes;
2365                 ibuf->ftype =  ibuf_back.ftype;
2366                 ibuf->foptions =  ibuf_back.foptions;
2367         }
2368
2369         return ok;
2370 }
2371
2372 int BKE_imbuf_write_stamp(
2373         Scene *scene, struct RenderResult *rr, ImBuf *ibuf, const char *name,
2374         const struct ImageFormatData *imf)
2375 {
2376         if (scene && scene->r.stamp & R_STAMP_ALL)
2377                 BKE_imbuf_stamp_info(rr, ibuf);
2378
2379         return BKE_imbuf_write(ibuf, name, imf);
2380 }
2381
2382 static void do_makepicstring(
2383         char *string, const char *base, const char *relbase, int frame, const char imtype,
2384         const ImageFormatData *im_format, const short use_ext, const short use_frames,
2385         const char *suffix)
2386 {
2387         if (string == NULL) return;
2388         BLI_strncpy(string, base, FILE_MAX - 10);   /* weak assumption */
2389         BLI_path_abs(string, relbase);
2390
2391         if (use_frames)
2392                 BLI_path_frame(string, frame, 4);
2393
2394         if (suffix)
2395                 BLI_path_suffix(string, FILE_MAX, suffix, "");
2396
2397         if (use_ext)
2398                 do_add_image_extension(string, imtype, im_format);
2399 }
2400
2401 void BKE_image_path_from_imformat(
2402         char *string, const char *base, const char *relbase, int frame,
2403         const ImageFormatData *im_format, const bool use_ext, const bool use_frames, const char *suffix)
2404 {
2405         do_makepicstring(string, base, relbase, frame, im_format->imtype, im_format, use_ext, use_frames, suffix);
2406 }
2407
2408 void BKE_image_path_from_imtype(
2409         char *string, const char *base, const char *relbase, int frame,
2410         const char imtype, const bool use_ext, const bool use_frames, const char *view)
2411 {
2412         do_makepicstring(string, base, relbase, frame, imtype, NULL, use_ext, use_frames, view);
2413 }
2414
2415 struct anim *openanim_noload(const char *name, int flags, int streamindex, char colorspace[IMA_MAX_SPACE])
2416 {
2417         struct anim *anim;
2418
2419         anim = IMB_open_anim(name, flags, streamindex, colorspace);
2420         return anim;
2421 }
2422
2423 /* used by sequencer too */
2424 struct anim *openanim(const char *name, int flags, int streamindex, char colorspace[IMA_MAX_SPACE])
2425 {
2426         struct anim *anim;
2427         struct ImBuf *ibuf;
2428
2429         anim = IMB_open_anim(name, flags, streamindex, colorspace);
2430         if (anim == NULL) return NULL;
2431
2432         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
2433         if (ibuf == NULL) {
2434                 if (BLI_exists(name))
2435                         printf("not an anim: %s\n", name);
2436                 else
2437                         printf("anim file doesn't exist: %s\n", name);
2438                 IMB_free_anim(anim);
2439                 return NULL;
2440         }
2441         IMB_freeImBuf(ibuf);
2442
2443         return(anim);
2444 }
2445
2446 /* ************************* New Image API *************** */
2447
2448
2449 /* Notes about Image storage
2450  * - packedfile
2451  *   -> written in .blend
2452  * - filename
2453  *   -> written in .blend
2454  * - movie
2455  *   -> comes from packedfile or filename
2456  * - renderresult
2457  *   -> comes from packedfile or filename
2458  * - listbase
2459  *   -> ibufs from exrhandle
2460  * - flipbook array
2461  *   -> ibufs come from movie, temporary renderresult or sequence
2462  * - ibuf
2463  *   -> comes from packedfile or filename or generated
2464  */
2465
2466
2467 /* forces existence of 1 Image for renderout or nodes, returns Image */
2468 /* name is only for default, when making new one */
2469 Image *BKE_image_verify_viewer(Main *bmain, int type, const char *name)
2470 {
2471         Image *ima;
2472
2473         for (ima = bmain->image.first; ima; ima = ima->id.next)
2474                 if (ima->source == IMA_SRC_VIEWER)
2475                         if (ima->type == type)
2476                                 break;
2477
2478         if (ima == NULL)
2479                 ima = image_alloc(bmain, name, IMA_SRC_VIEWER, type);
2480
2481         /* happens on reload, imagewindow cannot be image user when hidden*/
2482         if (ima->id.us == 0)
2483                 id_us_plus(&ima->id);
2484
2485         return ima;
2486 }
2487
2488 static void image_viewer_create_views(const RenderData *rd, Image *ima)
2489 {
2490         if ((rd->scemode & R_MULTIVIEW) == 0) {
2491                 image_add_view(ima, "", "");
2492         }
2493         else {
2494                 SceneRenderView *srv;
2495                 for (srv = rd->views.first; srv; srv = srv->next) {
2496                         if (BKE_scene_multiview_is_render_view_active(rd, srv) == false)
2497                                 continue;
2498                         image_add_view(ima, srv->name, "");
2499                 }
2500         }
2501 }
2502
2503 /* Reset the image cache and views when the Viewer Nodes views don't match the scene views */
2504 void BKE_image_verify_viewer_views(const RenderData *rd, Image *ima, ImageUser *iuser)
2505 {
2506         bool do_reset;
2507         const bool is_multiview = (rd->scemode & R_MULTIVIEW) != 0;
2508
2509         BLI_thread_lock(LOCK_DRAW_IMAGE);
2510
2511         if (!BKE_scene_multiview_is_stereo3d(rd))
2512                 iuser->flag &= ~IMA_SHOW_STEREO;
2513
2514         /* see if all scene render views are in the image view list */
2515         do_reset = (BKE_scene_multiview_num_views_get(rd) != BLI_listbase_count(&ima->views));
2516
2517         /* multiview also needs to be sure all the views are synced */
2518         if (is_multiview && !do_reset) {
2519                 SceneRenderView *srv;
2520                 ImageView *iv;
2521
2522                 for (iv = ima->views.first; iv; iv = iv->next) {
2523                         srv = BLI_findstring(&rd->views, iv->name, offsetof(SceneRenderView, name));
2524                         if ((srv == NULL) || (BKE_scene_multiview_is_render_view_active(rd, srv) == false)) {
2525                                 do_reset = true;
2526                                 break;
2527                         }
2528                 }
2529         }
2530
2531         if (do_reset) {
2532                 BLI_spin_lock(&image_spin);
2533
2534                 image_free_cached_frames(ima);
2535                 BKE_image_free_views(ima);
2536
2537                 /* add new views */
2538                 image_viewer_create_views(rd, ima);
2539
2540                 BLI_spin_unlock(&image_spin);
2541         }
2542
2543         BLI_thread_unlock(LOCK_DRAW_IMAGE);
2544 }
2545
2546 void BKE_image_walk_all_users(const Main *mainp, void *customdata,
2547                               void callback(Image *ima, ImageUser *iuser, void *customdata))
2548 {
2549         wmWindowManager *wm;
2550         wmWindow *win;
2551         Tex *tex;
2552
2553         /* texture users */
2554         for (tex = mainp->tex.first; tex; tex = tex->id.next) {
2555                 if (tex->type == TEX_IMAGE && tex->ima) {
2556                         callback(tex->ima, &tex->iuser, customdata);
2557                 }
2558
2559                 if (tex->nodetree) {
2560                         bNode *node;
2561                         for (node = tex->nodetree->nodes.first; node; node = node->next) {
2562                                 if (node->id && node->type == TEX_NODE_IMAGE) {
2563                                         Image *ima = (Image *)node->id;
2564                                         ImageUser *iuser = node->storage;
2565                                         callback(ima, iuser, customdata);
2566                                 }
2567                         }
2568                 }
2569         }
2570
2571         for (Camera *cam = mainp->camera.first; cam; cam = cam->id.next) {
2572                 for (CameraBGImage *bgpic = cam->bg_images.first; bgpic; bgpic = bgpic->next) {
2573                         callback(bgpic->ima, &bgpic->iuser, customdata);
2574                 }
2575         }
2576
2577         /* image window, compo node users */
2578         for (wm = mainp->wm.first; wm; wm = wm->id.next) { /* only 1 wm */
2579                 for (win = wm->windows.first; win; win = win->next) {
2580                         const bScreen *screen = BKE_workspace_active_screen_get(win->workspace_hook);
2581
2582                         for (ScrArea *sa = screen->areabase.first; sa; sa = sa->next) {
2583                                 if (sa->spacetype == SPACE_IMAGE) {
2584                                         SpaceImage *sima = sa->spacedata.first;
2585                                         callback(sima->image, &sima->iuser, customdata);
2586                                 }
2587                                 else if (sa->spacetype == SPACE_NODE) {
2588                                         SpaceNode *snode = sa->spacedata.first;
2589                                         if (snode->nodetree && snode->nodetree->type == NTREE_COMPOSIT) {
2590                                                 bNode *node;
2591                                                 for (node = snode->nodetree->nodes.first; node; node = node->next) {
2592                                                         if (node->id && node->type == CMP_NODE_IMAGE) {
2593                                                                 Image *ima = (Image *)node->id;
2594                                                                 ImageUser *iuser = node->storage;
2595                                                                 callback(ima, iuser, customdata);
2596                                                         }
2597                                                 }
2598                                         }
2599                                 }
2600                         }
2601                 }
2602         }
2603 }
2604
2605 static void image_tag_frame_recalc(Image *ima, ImageUser *iuser, void *customdata)
2606 {
2607         Image *changed_image = customdata;
2608
2609         if (ima == changed_image && BKE_image_is_animated(ima)) {
2610                 iuser->flag |= IMA_NEED_FRAME_RECALC;
2611         }
2612 }
2613
2614 static void image_init_imageuser(Image *ima, ImageUser *iuser)
2615 {
2616         RenderResult *rr = ima->rr;
2617
2618         iuser->multi_index = 0;
2619         iuser->layer = iuser->pass = iuser->view = 0;
2620
2621         if (rr)
2622                 BKE_image_multilayer_index(rr, iuser);
2623 }
2624
2625 void BKE_image_init_imageuser(Image *ima, ImageUser *iuser)
2626 {
2627         image_init_imageuser(ima, iuser);
2628 }
2629
2630 void BKE_image_signal(Main *bmain, Image *ima, ImageUser *iuser, int signal)
2631 {
2632         if (ima == NULL)
2633                 return;
2634
2635         BLI_spin_lock(&image_spin);
2636
2637         switch (signal) {
2638                 case IMA_SIGNAL_FREE:
2639                         BKE_image_free_buffers(ima);
2640
2641                         if (iuser) {
2642                                 iuser->ok = 1;
2643                                 if (iuser->scene) {
2644                                         image_update_views_format(ima, iuser);
2645                                 }
2646                         }
2647                         break;
2648                 case IMA_SIGNAL_SRC_CHANGE:
2649                         if (ima->type == IMA_TYPE_UV_TEST)
2650                                 if (ima->source != IMA_SRC_GENERATED)
2651                                         ima->type = IMA_TYPE_IMAGE;
2652
2653                         if (ima->source == IMA_SRC_GENERATED) {
2654                                 if (ima->gen_x == 0 || ima->gen_y == 0) {
2655                                         ImBuf *ibuf = image_get_cached_ibuf_for_index_frame(ima, IMA_NO_INDEX, 0);
2656                                         if (ibuf) {
2657                                                 ima->gen_x = ibuf->x;
2658                                                 ima->gen_y = ibuf->y;
2659                                                 IMB_freeImBuf(ibuf);
2660                                         }
2661                                 }
2662
2663                                 /* Changing source type to generated will likely change file format
2664                                  * used by generated image buffer. Saving different file format to
2665                                  * the old name might confuse other applications.
2666                                  *
2667                                  * Here we ensure original image path wouldn't be used when saving
2668                                  * generated image.
2669                                  */
2670                                 ima->name[0] = '\0';
2671                         }
2672
2673 #if 0
2674                         /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
2675                         if (ima->type != IMA_TYPE_MULTILAYER)
2676                                 BKE_image_free_buffers(ima);
2677 #else
2678                         /* image buffers for non-sequence multilayer will share buffers with RenderResult,
2679                          * however sequence multilayer will own buffers. Such logic makes switching from
2680                          * single multilayer file to sequence completely unstable
2681                          * since changes in nodes seems this workaround isn't needed anymore, all sockets
2682                          * are nicely detecting anyway, but freeing buffers always here makes multilayer
2683                          * sequences behave stable
2684                          */
2685                         BKE_image_free_buffers(ima);
2686 #endif
2687
2688                         ima->ok = 1;
2689                         if (iuser)
2690                                 iuser->ok = 1;
2691
2692                         BKE_image_walk_all_users(bmain, ima, image_tag_frame_recalc);
2693
2694                         break;
2695
2696                 case IMA_SIGNAL_RELOAD:
2697                         /* try to repack file */
2698                         if (BKE_image_has_packedfile(ima)) {
2699                                 const int totfiles = image_num_files(ima);
2700
2701                                 if (totfiles != BLI_listbase_count_at_most(&ima->packedfiles, totfiles + 1)) {
2702                                         /* in case there are new available files to be loaded */
2703                                         image_free_packedfiles(ima);
2704                                         BKE_image_packfiles(NULL, ima, ID_BLEND_PATH(bmain, &ima->id));
2705                                 }
2706                                 else {
2707                                         ImagePackedFile *imapf;
2708                                         for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next) {
2709                                                 PackedFile *pf;
2710                                                 pf = newPackedFile(NULL, imapf->filepath, ID_BLEND_PATH(bmain, &ima->id));
2711                                                 if (pf) {
2712                                                         freePackedFile(imapf->packedfile);
2713                                                         imapf->packedfile = pf;
2714                                                 }
2715                                                 else {
2716                                                         printf("ERROR: Image \"%s\" not available. Keeping packed image\n", imapf->filepath);
2717                                                 }
2718                                         }
2719                                 }
2720
2721                                 if (BKE_image_has_packedfile(ima))
2722                                         BKE_image_free_buffers(ima);
2723                         }
2724                         else
2725                                 BKE_image_free_buffers(ima);
2726
2727                         if (iuser) {
2728                                 iuser->ok = 1;
2729                                 if (iuser->scene) {
2730                                         image_update_views_format(ima, iuser);
2731                                 }
2732                         }
2733
2734                         break;
2735                 case IMA_SIGNAL_USER_NEW_IMAGE:
2736                         if (iuser) {
2737                                 iuser->ok = 1;
2738                                 if (ima->source == IMA_SRC_FILE || ima->source == IMA_SRC_SEQUENCE) {
2739                                         if (ima->type == IMA_TYPE_MULTILAYER) {
2740                                                 image_init_imageuser(ima, iuser);
2741                                         }
2742                                 }
2743                         }
2744                         break;
2745                 case IMA_SIGNAL_COLORMANAGE:
2746                         BKE_image_free_buffers(ima);
2747
2748                         ima->ok = 1;
2749
2750                         if (iuser)
2751                                 iuser->ok = 1;
2752
2753                         break;
2754         }
2755
2756         BLI_spin_unlock(&image_spin);
2757
2758         /* don't use notifiers because they are not 100% sure to succeeded
2759          * this also makes sure all scenes are accounted for. */
2760         {
2761                 Scene *scene;
2762                 for (scene = bmain->scene.first; scene; scene = scene->id.next) {
2763                         if (scene->nodetree) {
2764                                 nodeUpdateID(scene->nodetree, &ima->id);
2765                         }
2766                 }
2767         }
2768 }
2769
2770 /* return renderpass for a given pass index and active view */
2771 /* fallback to available if there are missing passes for active view */
2772 static RenderPass *image_render_pass_get(RenderLayer *rl, const int pass, const int view, int *r_passindex)
2773 {
2774         RenderPass *rpass_ret = NULL;
2775         RenderPass *rpass;
2776
2777         int rp_index = 0;
2778         const char *rp_name = "";
2779
2780         for (rpass = rl->passes.first; rpass; rpass = rpass->next, rp_index++) {
2781                 if (rp_index == pass) {
2782                         rpass_ret = rpass;
2783                         if (view == 0) {
2784                                 /* no multiview or left eye */
2785                                 break;
2786                         }
2787                         else {
2788                                 rp_name = rpass->name;
2789                         }
2790                 }
2791                 /* multiview */
2792                 else if (rp_name[0] &&
2793                          STREQ(rpass->name, rp_name) &&
2794                          (rpass->view_id == view))
2795                 {
2796                         rpass_ret = rpass;
2797                         break;
2798                 }
2799         }
2800
2801         /* fallback to the first pass in the layer */
2802         if (rpass_ret == NULL) {
2803                 rp_index = 0;
2804                 rpass_ret = rl->passes.first;
2805         }
2806
2807         if (r_passindex) {
2808                 *r_passindex = (rpass == rpass_ret ? rp_index : pass);
2809         }
2810
2811         return rpass_ret;
2812 }
2813
2814 /* if layer or pass changes, we need an index for the imbufs list */
2815 /* note it is called for rendered results, but it doesn't use the index! */
2816 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
2817 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
2818 {
2819         RenderLayer *rl;
2820         RenderPass *rpass = NULL;
2821
2822         if (rr == NULL)
2823                 return NULL;
2824
2825         if (iuser) {
2826                 short index = 0, rv_index, rl_index = 0;
2827                 bool is_stereo = (iuser->flag & IMA_SHOW_STEREO) && RE_RenderResult_is_stereo(rr);
2828
2829                 rv_index = is_stereo ? iuser->multiview_eye : iuser->view;
2830                 if (RE_HasCombinedLayer(rr)) rl_index += 1;
2831
2832                 for (rl = rr->layers.first; rl; rl = rl->next, rl_index++) {
2833                         if (iuser->layer == rl_index) {
2834                                 int rp_index;
2835                                 rpass = image_render_pass_get(rl, iuser->pass, rv_index, &rp_index);
2836                                 iuser->multi_index = index + rp_index;
2837                                 break;
2838                         }
2839                         else {
2840                                 index += BLI_listbase_count(&rl->passes);
2841                         }
2842                 }
2843         }
2844
2845         return rpass;
2846 }
2847
2848 void BKE_image_multiview_index(Image *ima, ImageUser *iuser)
2849 {
2850         if (iuser) {
2851                 bool is_stereo = BKE_image_is_stereo(ima) && (iuser->flag & IMA_SHOW_STEREO);
2852                 if (is_stereo) {
2853                         iuser->multi_index = iuser->multiview_eye;
2854                 }
2855                 else {
2856                         if ((iuser->view < 0) || (iuser->view >= BLI_listbase_count_at_most(&ima->views, iuser->view + 1))) {
2857                                 iuser->multi_index = iuser->view = 0;
2858                         }
2859                         else {
2860                                 iuser->multi_index = iuser->view;
2861                         }
2862                 }
2863         }
2864 }
2865
2866 /* if layer or pass changes, we need an index for the imbufs list */
2867 /* note it is called for rendered results, but it doesn't use the index! */
2868 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
2869 bool BKE_image_is_multilayer(Image *ima)
2870 {
2871         if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE)) {
2872                 if (ima->type == IMA_TYPE_MULTILAYER) {
2873                         return true;
2874                 }
2875         }
2876         else if (ima->source == IMA_SRC_VIEWER) {
2877                 if (ima->type == IMA_TYPE_R_RESULT) {
2878                         return true;
2879                 }
2880         }
2881         return false;
2882 }
2883
2884 bool BKE_image_is_multiview(Image *ima)
2885 {
2886         ImageView *view = ima->views.first;
2887         return (view && (view->next || view->name[0]));
2888 }
2889
2890 bool BKE_image_is_stereo(Image *ima)
2891 {
2892         return BKE_image_is_multiview(ima) &&
2893                (BLI_findstring(&ima->views, STEREO_LEFT_NAME, offsetof(ImageView, name)) &&
2894                 BLI_findstring(&ima->views, STEREO_RIGHT_NAME, offsetof(ImageView, name)));
2895 }
2896
2897 static void image_init_multilayer_multiview(Image *ima, RenderResult *rr)
2898 {
2899         /* update image views from render views, but only if they actually changed,
2900          * to avoid invalid memory access during render. ideally these should always
2901          * be acquired with a mutex along with the render result, but there are still
2902          * some places with just an image pointer that need to access views */
2903         if (rr && BLI_listbase_count(&ima->views) == BLI_listbase_count(&rr->views)) {
2904                 ImageView *iv = ima->views.first;
2905                 RenderView *rv = rr->views.first;
2906                 bool modified = false;
2907                 for (; rv; rv = rv->next, iv = iv->next) {
2908                         modified |= !STREQ(rv->name, iv->name);
2909                 }
2910                 if (!modified)
2911                         return;
2912         }
2913
2914         BKE_image_free_views(ima);
2915
2916         if (rr) {
2917                 for (RenderView *rv = rr->views.first; rv; rv = rv->next) {
2918                         ImageView *iv = MEM_callocN(sizeof(ImageView), "Viewer Image View");
2919                         STRNCPY(iv->name, rv->name);
2920                         BLI_addtail(&ima->views, iv);
2921                 }
2922         }
2923 }
2924
2925
2926 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
2927 {
2928         RenderResult *rr = NULL;
2929         if (ima->rr) {
2930                 rr = ima->rr;
2931         }
2932         else if (ima->type == IMA_TYPE_R_RESULT) {
2933                 if (ima->render_slot == ima->last_render_slot)
2934                         rr = RE_AcquireResultRead(RE_GetSceneRender(scene));
2935                 else
2936                         rr = BKE_image_get_renderslot(ima, ima->render_slot)->render;
2937
2938                 /* set proper views */
2939                 image_init_multilayer_multiview(ima, rr);
2940         }
2941
2942         return rr;
2943 }
2944
2945 void BKE_image_release_renderresult(Scene *scene, Image *ima)
2946 {
2947         if (ima->rr) {
2948                 /* pass */
2949         }
2950         else if (ima->type == IMA_TYPE_R_RESULT) {
2951                 if (ima->render_slot == ima->last_render_slot)
2952                         RE_ReleaseResult(RE_GetSceneRender(scene));
2953         }
2954 }
2955
2956 bool BKE_image_is_openexr(struct Image *ima)
2957 {
2958 #ifdef WITH_OPENEXR
2959         if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE)) {
2960                 return BLI_path_extension_check(ima->name, ".exr");
2961         }
2962 #else
2963         UNUSED_VARS(ima);
2964 #endif
2965         return false;
2966 }
2967
2968 void BKE_image_backup_render(Scene *scene, Image *ima, bool free_current_slot)
2969 {
2970         /* called right before rendering, ima->renderslots contains render
2971          * result pointers for everything but the current render */
2972         Render *re = RE_GetSceneRender(scene);
2973
2974         /* Ensure we always have a valid render slot. */
2975         if (!ima->renderslots.first) {
2976                 BKE_image_add_renderslot(ima, NULL);
2977                 ima->render_slot = 0;
2978                 ima->last_render_slot = 0;
2979         }
2980         else if (ima->render_slot >= BLI_listbase_count(&ima->renderslots)) {
2981                 ima->render_slot = 0;
2982                 ima->last_render_slot = 0;
2983         }
2984
2985         RenderSlot *last_slot = BKE_image_get_renderslot(ima, ima->last_render_slot);
2986         RenderSlot *cur_slot = BKE_image_get_renderslot(ima, ima->render_slot);
2987
2988         if (last_slot && ima->render_slot != ima->last_render_slot) {
2989                 last_slot->render = NULL;
2990                 RE_SwapResult(re, &last_slot->render);
2991
2992                 if (cur_slot->render) {
2993                         if (free_current_slot) {
2994                                 BKE_image_clear_renderslot(ima, NULL, ima->render_slot);
2995                         }
2996                         else {
2997                                 RE_SwapResult(re, &cur_slot->render);
2998                         }
2999                 }
3000         }
3001
3002         ima->last_render_slot = ima->render_slot;
3003 }
3004
3005 /**************************** multiview load openexr *********************************/
3006
3007 static void image_add_view(Image *ima, const char *viewname, const char *filepath)
3008 {
3009         ImageView *iv;
3010
3011         iv = MEM_mallocN(sizeof(ImageView), "Viewer Image View");
3012         STRNCPY(iv->name, viewname);
3013         STRNCPY(iv->filepath, filepath);
3014
3015         /* For stereo drawing we need to ensure:
3016          * STEREO_LEFT_NAME  == STEREO_LEFT_ID and
3017          * STEREO_RIGHT_NAME == STEREO_RIGHT_ID */
3018
3019         if (STREQ(viewname, STEREO_LEFT_NAME)) {
3020                 BLI_addhead(&ima->views, iv);
3021         }
3022         else if (STREQ(viewname, STEREO_RIGHT_NAME)) {
3023                 ImageView *left_iv = BLI_findstring(&ima->views, STEREO_LEFT_NAME, offsetof(ImageView, name));
3024
3025                 if (left_iv == NULL) {
3026                         BLI_addhead(&ima->views, iv);
3027                 }
3028                 else {
3029                         BLI_insertlinkafter(&ima->views, left_iv, iv);
3030                 }
3031         }
3032         else {
3033                 BLI_addtail(&ima->views, iv);
3034         }
3035 }
3036
3037 /* after imbuf load, openexr type can return with a exrhandle open */
3038 /* in that case we have to build a render-result */
3039 #ifdef WITH_OPENEXR
3040 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
3041 {
3042         const char *colorspace = ima->colorspace_settings.name;
3043         bool predivide = (ima->alpha_mode == IMA_ALPHA_PREMUL);
3044
3045         /* only load rr once for multiview */
3046         if (!ima->rr)
3047                 ima->rr = RE_MultilayerConvert(ibuf->userdata, colorspace, predivide, ibuf->x, ibuf->y);
3048
3049         IMB_exr_close(ibuf->userdata);
3050
3051         ibuf->userdata = NULL;
3052         if (ima->rr)
3053                 ima->rr->framenr = framenr;
3054
3055         /* set proper views */
3056         image_init_multilayer_multiview(ima, ima->rr);
3057 }
3058 #endif  /* WITH_OPENEXR */
3059
3060 /* common stuff to do with images after loading */
3061 static void image_initialize_after_load(Image *ima, ImBuf *UNUSED(ibuf))
3062 {
3063         /* Preview is NULL when it has never been used as an icon before.
3064          * Never handle previews/icons outside of main thread. */
3065         if (G.background == 0 && ima->preview == NULL && BLI_thread_is_main()) {
3066                 BKE_icon_changed(BKE_icon_id_ensure(&ima->id));
3067         }
3068
3069         /* timer */
3070         BKE_image_tag_time(ima);
3071
3072         ima->ok = IMA_OK_LOADED;
3073
3074 }
3075
3076 static int imbuf_alpha_flags_for_image(Image *ima)
3077 {
3078         int flag = 0;
3079
3080         if (ima->flag & IMA_IGNORE_ALPHA)
3081                 flag |= IB_ignore_alpha;
3082         else if (ima->alpha_mode == IMA_ALPHA_PREMUL)
3083                 flag |= IB_alphamode_premul;
3084
3085         return flag;
3086 }
3087
3088 /* the number of files will vary according to the stereo format */
3089 static int image_num_files(Image *ima)
3090 {
3091         const bool is_multiview = BKE_image_is_multiview(ima);
3092
3093         if (!is_multiview) {
3094                 return 1;
3095         }
3096         else if (ima->views_format == R_IMF_VIEWS_STEREO_3D) {
3097                 return 1;
3098         }
3099         /* R_IMF_VIEWS_INDIVIDUAL */
3100         else {
3101                 return BLI_listbase_count(&ima->views);
3102         }
3103 }
3104
3105 static ImBuf *load_sequence_single(Image *ima, ImageUser *iuser, int frame, const int view_id, bool *r_assign)
3106 {
3107         struct ImBuf *ibuf;
3108         char name[FILE_MAX];
3109         int flag;
3110         ImageUser iuser_t = {0};
3111
3112         /* XXX temp stuff? */
3113         if (ima->lastframe != frame)
3114                 ima->tpageflag |= IMA_TPAGE_REFRESH;
3115
3116         ima->lastframe = frame;
3117
3118         if (iuser) {
3119                 iuser_t = *iuser;
3120         }
3121         else {
3122                 /* TODO(sergey): Do we need to initialize something here? */
3123         }
3124
3125         iuser_t.view = view_id;
3126         BKE_image_user_file_path(&iuser_t, ima, name);
3127
3128         flag = IB_rect | IB_multilayer;
3129         flag |= imbuf_alpha_flags_for_image(ima);
3130
3131         /* read ibuf */
3132         ibuf = IMB_loadiffname(name, flag, ima->colorspace_settings.name);
3133
3134 #if 0
3135         if (ibuf) {
3136                 printf(AT " loaded %s\n", name);
3137         }
3138         else {
3139                 printf(AT " missed %s\n", name);
3140         }
3141 #endif
3142
3143         if (ibuf) {
3144 #ifdef WITH_OPENEXR
3145                 if (ibuf->ftype == IMB_FTYPE_OPENEXR && ibuf->userdata) {
3146                         /* Handle multilayer and multiview cases, don't assign ibuf here.
3147                          * will be set layer in BKE_image_acquire_ibuf from ima->rr. */
3148                         if (IMB_exr_has_multilayer(ibuf->userdata)) {
3149                                 image_create_multilayer(ima, ibuf, frame);
3150                                 ima->type = IMA_TYPE_MULTILAYER;
3151                                 IMB_freeImBuf(ibuf);
3152                                 ibuf = NULL;
3153                         }
3154                 }
3155                 else {
3156                         image_initialize_after_load(ima, ibuf);
3157                         *r_assign = true;
3158                 }
3159 #else
3160                 image_initialize_after_load(ima, ibuf);
3161                 *r_assign = true;
3162 #endif
3163         }
3164
3165         return ibuf;
3166 }
3167
3168 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
3169 {
3170         struct ImBuf *ibuf = NULL;
3171         const bool is_multiview = BKE_image_is_multiview(ima);
3172         const int totfiles = image_num_files(ima);
3173         bool assign = false;
3174
3175         if (!is_multiview) {
3176                 ibuf = load_sequence_single(ima, iuser, frame, 0, &assign);
3177                 if (assign) {
3178                         image_assign_ibuf(ima, ibuf, 0, frame);
3179                 }
3180         }
3181         else {
3182                 const int totviews = BLI_listbase_count(&ima->views);
3183                 int i;
3184                 struct ImBuf **ibuf_arr;
3185
3186                 ibuf_arr = MEM_mallocN(sizeof(ImBuf *) * totviews, "Image Views Imbufs");
3187
3188                 for (i = 0; i < totfiles; i++)
3189                         ibuf_arr[i] = load_sequence_single(ima, iuser, frame, i, &assign);
3190
3191                 if (BKE_image_is_stereo(ima) && ima->views_format == R_IMF_VIEWS_STEREO_3D)
3192                         IMB_ImBufFromStereo3d(ima->stereo3d_format, ibuf_arr[0], &ibuf_arr[0], &ibuf_arr[1]);
3193
3194                 /* return the original requested ImBuf */
3195                 ibuf = ibuf_arr[(iuser ? iuser->multi_index : 0)];
3196
3197                 if (assign) {
3198                         for (i = 0; i < totviews; i++) {
3199                                 image_assign_ibuf(ima, ibuf_arr[i], i, frame);
3200                         }
3201                 }
3202
3203                 /* "remove" the others (decrease their refcount) */
3204                 for (i = 0; i < totviews; i++) {
3205                         if (ibuf_arr[i] != ibuf) {
3206                                 IMB_freeImBuf(ibuf_arr[i]);
3207                         }
3208                 }
3209
3210                 /* cleanup */
3211                 MEM_freeN(ibuf_arr);
3212         }
3213
3214         return ibuf;
3215 }
3216
3217 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
3218 {
3219         struct ImBuf *ibuf = NULL;
3220
3221         /* either we load from RenderResult, or we have to load a new one */
3222
3223         /* check for new RenderResult */
3224         if (ima->rr == NULL || frame != ima->rr->framenr) {
3225                 if (ima->rr) {
3226                         /* Cached image buffers shares pointers with render result,
3227                          * need to ensure there's no image buffers are hanging around
3228                          * with dead links after freeing the render result.
3229                          */
3230                         image_free_cached_frames(ima);
3231                         RE_FreeRenderResult(ima->rr);
3232                         ima->rr = NULL;
3233                 }
3234
3235                 ibuf = image_load_sequence_file(ima, iuser, frame);
3236
3237                 if (ibuf) { /* actually an error */
3238                         ima->type = IMA_TYPE_IMAGE;
3239                         printf("error, multi is normal image\n");
3240                 }
3241         }
3242         if (ima->rr) {
3243                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
3244
3245                 if (rpass) {
3246                         // printf("load from pass %s\n", rpass->name);
3247                         /* since we free  render results, we copy the rect */
3248                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
3249                         ibuf->rect_float = MEM_dupallocN(rpass->rect);
3250                         ibuf->flags |= IB_rectfloat;
3251                         ibuf->mall = IB_rectfloat;
3252                         ibuf->channels = rpass->channels;
3253
3254                         image_initialize_after_load(ima, ibuf);
3255                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : 0, frame);
3256
3257                 }
3258                 // else printf("pass not found\n");
3259         }
3260         else
3261                 ima->ok = 0;
3262
3263         if (iuser)
3264                 iuser->ok = ima->ok;
3265
3266         return ibuf;
3267 }
3268
3269 static ImBuf *load_movie_single(Image *ima, ImageUser *iuser, int frame, const int view_id)
3270 {
3271         struct ImBuf *ibuf = NULL;
3272         ImageAnim *ia;
3273
3274         ia = BLI_findlink(&ima->anims, view_id);
3275
3276         if (ia->anim == NULL) {
3277                 char str[FILE_MAX];
3278                 int flags = IB_rect;
3279                 ImageUser iuser_t;
3280
3281                 if (ima->flag & IMA_DEINTERLACE) {
3282                         flags |= IB_animdeinterlace;
3283                 }
3284
3285                 if (iuser)
3286                         iuser_t = *iuser;
3287
3288                 iuser_t.view = view_id;
3289
3290                 BKE_image_user_file_path(&iuser_t, ima, str);
3291
3292                 /* FIXME: make several stream accessible in image editor, too*/
3293                 ia->anim = openanim(str, flags, 0, ima->colorspace_settings.name);
3294
3295                 /* let's initialize this user */
3296                 if (ia->anim && iuser && iuser->frames == 0)
3297                         iuser->frames = IMB_anim_get_duration(ia->anim,
3298                                                               IMB_TC_RECORD_RUN);
3299         }
3300
3301         if (ia->anim) {
3302                 int dur = IMB_anim_get_duration(ia->anim,
3303                                                 IMB_TC_RECORD_RUN);
3304                 int fra = frame - 1;
3305
3306                 if (fra < 0) fra = 0;
3307                 if (fra > (dur - 1)) fra = dur - 1;
3308                 ibuf = IMB_makeSingleUser(
3309                     IMB_anim_absolute(ia->anim, fra,
3310                                       IMB_TC_RECORD_RUN,
3311                                       IMB_PROXY_NONE));
3312
3313                 if (ibuf) {
3314                         image_initialize_after_load(ima, ibuf);
3315                 }
3316                 else
3317                         ima->ok = 0;
3318         }
3319         else
3320                 ima->ok = 0;
3321
3322         return ibuf;
3323 }
3324
3325 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
3326 {
3327         struct ImBuf *ibuf = NULL;
3328         const bool is_multiview = BKE_image_is_multiview(ima);
3329         const int totfiles = image_num_files(ima);
3330         int i;
3331
3332         if (totfiles != BLI_listbase_count_at_most(&ima->anims, totfiles + 1)) {
3333                 image_free_anims(ima);