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