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