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