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