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