Merge branch 'master' into blender2.8
[blender.git] / source / blender / blenkernel / intern / image.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, 2006, full recode
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/image.c
27  *  \ingroup bke
28  */
29
30
31 #include <stdio.h>
32 #include <string.h>
33 #include <fcntl.h>
34 #include <math.h>
35 #ifndef WIN32
36 #  include <unistd.h>
37 #else
38 #  include <io.h>
39 #endif
40
41 #include <time.h>
42
43 #include "MEM_guardedalloc.h"
44
45 #include "IMB_colormanagement.h"
46 #include "IMB_imbuf_types.h"
47 #include "IMB_imbuf.h"
48 #include "IMB_moviecache.h"
49
50 #ifdef WITH_OPENEXR
51 #  include "intern/openexr/openexr_multi.h"
52 #endif
53
54 #include "DNA_packedFile_types.h"
55 #include "DNA_scene_types.h"
56 #include "DNA_object_types.h"
57 #include "DNA_camera_types.h"
58 #include "DNA_sequence_types.h"
59 #include "DNA_brush_types.h"
60 #include "DNA_mesh_types.h"
61 #include "DNA_meshdata_types.h"
62
63 #include "BLI_blenlib.h"
64 #include "BLI_math_vector.h"
65 #include "BLI_mempool.h"
66 #include "BLI_threads.h"
67 #include "BLI_timecode.h"  /* for stamp timecode format */
68 #include "BLI_utildefines.h"
69
70 #include "BKE_bmfont.h"
71 #include "BKE_colortools.h"
72 #include "BKE_global.h"
73 #include "BKE_icons.h"
74 #include "BKE_image.h"
75 #include "BKE_library.h"
76 #include "BKE_library_query.h"
77 #include "BKE_library_remap.h"
78 #include "BKE_main.h"
79 #include "BKE_packedFile.h"
80 #include "BKE_report.h"
81 #include "BKE_scene.h"
82 #include "BKE_node.h"
83 #include "BKE_sequencer.h" /* seq_foreground_frame_get() */
84 #include "BKE_workspace.h"
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                 // BLI_snprintf(cache_name, sizeof(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                 BLI_strncpy(imapf_dst->filepath, imapf_src->filepath, sizeof(imapf_dst->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(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(G.main, 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         BLI_strncpy(str, filepath, sizeof(str));
597         BLI_path_abs(str, bmain->name);
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         BLI_strncpy(ima->name, filepath, sizeof(ima->name));
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(const char *filepath, bool *r_exists)
621 {
622         Image *ima;
623         char str[FILE_MAX], strtest[FILE_MAX];
624
625         BLI_strncpy(str, filepath, sizeof(str));
626         BLI_path_abs(str, G.main->name);
627
628         /* first search an identical filepath */
629         for (ima = G.main->image.first; ima; ima = ima->id.next) {
630                 if (ima->source != IMA_SRC_VIEWER && ima->source != IMA_SRC_GENERATED) {
631                         BLI_strncpy(strtest, ima->name, sizeof(ima->name));
632                         BLI_path_abs(strtest, ID_BLEND_PATH(G.main, &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(G.main, filepath);
652 }
653
654 Image *BKE_image_load_exists(const char *filepath)
655 {
656         return BKE_image_load_exists_ex(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                         BLI_strncpy(colorspace_settings->name, colorspace, sizeof(colorspace_settings->name));
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                         BLI_strncpy(colorspace_settings->name, colorspace, sizeof(colorspace_settings->name));
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         BLI_strncpy(ibuf->name, name, sizeof(ibuf->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                 /* BLI_strncpy(ima->name, name, FILE_MAX); */ /* 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(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(G.main, name, IMA_SRC_FILE, IMA_TYPE_IMAGE);
768
769         if (ima) {
770                 BLI_strncpy(ima->name, ibuf->name, FILE_MAX);
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                         BLI_strncpy(imapf->filepath, iv->filepath, sizeof(imapf->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                 BLI_strncpy(imapf->filepath, ima->name, sizeof(imapf->filepath));
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                         BLI_strncpy(imapf->filepath, ima->name, sizeof(imapf->filepath));
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                                 BLI_strncpy(imapf->filepath, iv->filepath, sizeof(imapf->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                 BLI_strncpy(imapf->filepath, ima->name, sizeof(imapf->filepath));
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()
937 {
938         Image *ima;
939         int ctime = PIL_check_seconds_timer_i();
940
941         ima = G.main->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(void)
996 {
997         Image *ima;
998         uintptr_t size, totsize = 0;
999
1000         for (ima = G.main->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 = G.main->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(void)
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 = G.main->image.first; ima; ima = ima->id.next)
1029                 ima->id.tag &= ~LIB_TAG_DOIT;
1030
1031         for (tex = G.main->tex.first; tex; tex = tex->id.next)
1032                 if (tex->ima)
1033                         tex->ima->id.tag |= LIB_TAG_DOIT;
1034
1035         for (ima = G.main->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(int cfra)
1072 {
1073         Image *ima;
1074
1075         for (ima = G.main->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 camera[STAMP_NAME_SIZE];
1627         char cameralens[STAMP_NAME_SIZE];
1628         char scene[STAMP_NAME_SIZE];
1629         char strip[STAMP_NAME_SIZE];
1630         char rendertime[STAMP_NAME_SIZE];
1631         char memory[STAMP_NAME_SIZE];
1632
1633         /* Custom fields are used to put extra meta information header from render
1634          * engine to the result image.
1635          *
1636          * NOTE: This fields are not stamped onto the image. At least for now.
1637          */
1638         ListBase custom_fields;
1639 } StampData;
1640 #undef STAMP_NAME_SIZE
1641
1642 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix)
1643 {
1644         char text[256];
1645         struct tm *tl;
1646         time_t t;
1647
1648         if (scene->r.stamp & R_STAMP_FILENAME) {
1649                 BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), do_prefix ? "File %s" : "%s", G.relbase_valid ? G.main->name : "<untitled>");
1650         }
1651         else {
1652                 stamp_data->file[0] = '\0';
1653         }
1654
1655         if (scene->r.stamp & R_STAMP_NOTE) {
1656                 /* Never do prefix for Note */
1657                 BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", scene->r.stamp_udata);
1658         }
1659         else {
1660                 stamp_data->note[0] = '\0';
1661         }
1662
1663         if (scene->r.stamp & R_STAMP_DATE) {
1664                 t = time(NULL);
1665                 tl = localtime(&t);
1666                 BLI_snprintf(text, sizeof(text), "%04d/%02d/%02d %02d:%02d:%02d", tl->tm_year + 1900, tl->tm_mon + 1, tl->tm_mday, tl->tm_hour, tl->tm_min, tl->tm_sec);
1667                 BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), do_prefix ? "Date %s" : "%s", text);
1668         }
1669         else {
1670                 stamp_data->date[0] = '\0';
1671         }
1672
1673         if (scene->r.stamp & R_STAMP_MARKER) {
1674                 const char *name = BKE_scene_find_last_marker_name(scene, CFRA);
1675
1676                 if (name) BLI_strncpy(text, name, sizeof(text));
1677                 else BLI_strncpy(text, "<none>", sizeof(text));
1678
1679                 BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), do_prefix ? "Marker %s" : "%s", text);
1680         }
1681         else {
1682                 stamp_data->marker[0] = '\0';
1683         }
1684
1685         if (scene->r.stamp & R_STAMP_TIME) {
1686                 const short timecode_style = USER_TIMECODE_SMPTE_FULL;
1687                 BLI_timecode_string_from_time(text, sizeof(text), 0, FRA2TIME(scene->r.cfra), FPS, timecode_style);
1688                 BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), do_prefix ? "Timecode %s" : "%s", text);
1689         }
1690         else {
1691                 stamp_data->time[0] = '\0';
1692         }
1693
1694         if (scene->r.stamp & R_STAMP_FRAME) {
1695                 char fmtstr[32];
1696                 int digits = 1;
1697
1698                 if (scene->r.efra > 9)
1699                         digits = integer_digits_i(scene->r.efra);
1700
1701                 BLI_snprintf(fmtstr, sizeof(fmtstr), do_prefix ? "Frame %%0%di" : "%%0%di", digits);
1702                 BLI_snprintf(stamp_data->frame, sizeof(stamp_data->frame), fmtstr, scene->r.cfra);
1703         }
1704         else {
1705                 stamp_data->frame[0] = '\0';
1706         }
1707
1708         if (scene->r.stamp & R_STAMP_CAMERA) {
1709                 BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), do_prefix ? "Camera %s" : "%s", camera ? camera->id.name + 2 : "<none>");
1710         }
1711         else {
1712                 stamp_data->camera[0] = '\0';
1713         }
1714
1715         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1716                 if (camera && camera->type == OB_CAMERA) {
1717                         BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)camera->data)->lens);
1718                 }
1719                 else {
1720                         BLI_strncpy(text, "<none>", sizeof(text));
1721                 }
1722
1723                 BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), do_prefix ? "Lens %s" : "%s", text);
1724         }
1725         else {
1726                 stamp_data->cameralens[0] = '\0';
1727         }
1728
1729         if (scene->r.stamp & R_STAMP_SCENE) {
1730                 BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), do_prefix ? "Scene %s" : "%s", scene->id.name + 2);
1731         }
1732         else {
1733                 stamp_data->scene[0] = '\0';
1734         }
1735
1736         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1737                 Sequence *seq = BKE_sequencer_foreground_frame_get(scene, scene->r.cfra);
1738
1739                 if (seq) BLI_strncpy(text, seq->name + 2, sizeof(text));
1740                 else BLI_strncpy(text, "<none>", sizeof(text));
1741
1742                 BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), do_prefix ? "Strip %s" : "%s", text);
1743         }
1744         else {
1745                 stamp_data->strip[0] = '\0';
1746         }
1747
1748         {
1749                 Render *re = RE_GetSceneRender(scene);
1750                 RenderStats *stats = re ? RE_GetStats(re) : NULL;
1751
1752                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1753                         BLI_timecode_string_from_time_simple(text, sizeof(text), stats->lastframetime);
1754
1755                         BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), do_prefix ? "RenderTime %s" : "%s", text);
1756                 }
1757                 else {
1758                         stamp_data->rendertime[0] = '\0';
1759                 }
1760
1761                 if (stats && (scene->r.stamp & R_STAMP_MEMORY)) {
1762                         BLI_snprintf(stamp_data->memory, sizeof(stamp_data->memory), do_prefix ? "Peak Memory %.2fM" : "%.2fM", stats->mem_peak);
1763                 }
1764                 else {
1765                         stamp_data->memory[0] = '\0';
1766                 }
1767         }
1768 }
1769
1770 /* Will always add prefix. */
1771 static void stampdata_from_template(StampData *stamp_data,
1772                                     const Scene *scene,
1773                                     const StampData *stamp_data_template)
1774 {
1775         if (scene->r.stamp & R_STAMP_FILENAME) {
1776                 BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), "File %s", stamp_data_template->file);
1777         }
1778         else {
1779                 stamp_data->file[0] = '\0';
1780         }
1781         if (scene->r.stamp & R_STAMP_NOTE) {
1782                 BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", stamp_data_template->note);
1783         }
1784         else {
1785                 stamp_data->note[0] = '\0';
1786         }
1787         if (scene->r.stamp & R_STAMP_DATE) {
1788                 BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), "Date %s", stamp_data_template->date);
1789         }
1790         else {
1791                 stamp_data->date[0] = '\0';
1792         }
1793         if (scene->r.stamp & R_STAMP_MARKER) {
1794                 BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), "Marker %s", stamp_data_template->marker);
1795         }
1796         else {
1797                 stamp_data->marker[0] = '\0';
1798         }
1799         if (scene->r.stamp & R_STAMP_TIME) {
1800                 BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), "Timecode %s", stamp_data_template->time);
1801         }
1802         else {
1803                 stamp_data->time[0] = '\0';
1804         }
1805         if (scene->r.stamp & R_STAMP_FRAME) {
1806                 BLI_snprintf(stamp_data->frame, sizeof(stamp_data->frame), "Frame %s", stamp_data_template->frame);
1807         }
1808         else {
1809                 stamp_data->frame[0] = '\0';
1810         }
1811         if (scene->r.stamp & R_STAMP_CAMERA) {
1812                 BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), "Camera %s", stamp_data_template->camera);
1813         }
1814         else {
1815                 stamp_data->camera[0] = '\0';
1816         }
1817         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1818                 BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), "Lens %s", stamp_data_template->cameralens);
1819         }
1820         else {
1821                 stamp_data->cameralens[0] = '\0';
1822         }
1823         if (scene->r.stamp & R_STAMP_SCENE) {
1824                 BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), "Scene %s", stamp_data_template->scene);
1825         }
1826         else {
1827                 stamp_data->scene[0] = '\0';
1828         }
1829         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1830                 BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), "Strip %s", stamp_data_template->strip);
1831         }
1832         else {
1833                 stamp_data->strip[0] = '\0';
1834         }
1835         if (scene->r.stamp & R_STAMP_RENDERTIME) {
1836                 BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), "RenderTime %s", stamp_data_template->rendertime);
1837         }
1838         else {
1839                 stamp_data->rendertime[0] = '\0';
1840         }
1841         if (scene->r.stamp & R_STAMP_MEMORY) {
1842                 BLI_snprintf(stamp_data->memory, sizeof(stamp_data->memory), "Peak Memory %s", stamp_data_template->memory);
1843         }
1844         else {
1845                 stamp_data->memory[0] = '\0';
1846         }
1847 }
1848
1849 void BKE_image_stamp_buf(
1850         Scene *scene, Object *camera, const StampData *stamp_data_template,
1851         unsigned char *rect, float *rectf, int width, int height, int channels)
1852 {
1853         struct StampData stamp_data;
1854         float w, h, pad;
1855         int x, y, y_ofs;
1856         float h_fixed;
1857         const int mono = blf_mono_font_render; // XXX
1858         struct ColorManagedDisplay *display;
1859         const char *display_device;
1860
1861         /* vars for calculating wordwrap */
1862         struct {
1863                 struct ResultBLF info;
1864                 rctf rect;
1865         } wrap;
1866
1867         /* this could be an argument if we want to operate on non linear float imbuf's
1868          * for now though this is only used for renders which use scene settings */
1869
1870 #define TEXT_SIZE_CHECK(str, w, h) \
1871         ((str[0]) && ((void)(h = h_fixed), (w = BLF_width(mono, str, sizeof(str)))))
1872
1873         /* must enable BLF_WORD_WRAP before using */
1874 #define TEXT_SIZE_CHECK_WORD_WRAP(str, w, h) \
1875         ((str[0]) && (BLF_boundbox_ex(mono, str, sizeof(str), &wrap.rect, &wrap.info), \
1876          (void)(h = h_fixed * wrap.info.lines), (w = BLI_rctf_size_x(&wrap.rect))))
1877
1878 #define BUFF_MARGIN_X 2
1879 #define BUFF_MARGIN_Y 1
1880
1881         if (!rect && !rectf)
1882                 return;
1883
1884         display_device = scene->display_settings.display_device;
1885         display = IMB_colormanagement_display_get_named(display_device);
1886
1887         if (stamp_data_template == NULL) {
1888                 stampdata(scene, camera, &stamp_data, (scene->r.stamp & R_STAMP_HIDE_LABELS) == 0);
1889         }
1890         else {
1891                 stampdata_from_template(&stamp_data, scene, stamp_data_template);
1892         }
1893
1894         /* TODO, do_versions */
1895         if (scene->r.stamp_font_id < 8)
1896                 scene->r.stamp_font_id = 12;
1897
1898         /* set before return */
1899         BLF_size(mono, scene->r.stamp_font_id, 72);
1900         BLF_wordwrap(mono, width - (BUFF_MARGIN_X * 2));
1901
1902         BLF_buffer(mono, rectf, rect, width, height, channels, display);
1903         BLF_buffer_col(mono, scene->r.fg_stamp);
1904         pad = BLF_width_max(mono);
1905
1906         /* use 'h_fixed' rather than 'h', aligns better */
1907         h_fixed = BLF_height_max(mono);
1908         y_ofs = -BLF_descender(mono);
1909
1910         x = 0;
1911         y = height;
1912
1913         if (TEXT_SIZE_CHECK(stamp_data.file, w, h)) {
1914                 /* Top left corner */
1915                 y -= h;
1916
1917                 /* also a little of space to the background. */
1918                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1919                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1920
1921                 /* and draw the text. */
1922                 BLF_position(mono, x, y + y_ofs, 0.0);
1923                 BLF_draw_buffer(mono, stamp_data.file, BLF_DRAW_STR_DUMMY_MAX);
1924
1925                 /* the extra pixel for background. */
1926                 y -= BUFF_MARGIN_Y * 2;
1927         }
1928
1929         /* Top left corner, below File */
1930         if (TEXT_SIZE_CHECK(stamp_data.date, w, h)) {
1931                 y -= h;
1932
1933                 /* and space for background. */
1934                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1935                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1936
1937                 BLF_position(mono, x, y + y_ofs, 0.0);
1938                 BLF_draw_buffer(mono, stamp_data.date, BLF_DRAW_STR_DUMMY_MAX);
1939
1940                 /* the extra pixel for background. */
1941                 y -= BUFF_MARGIN_Y * 2;
1942         }
1943
1944         /* Top left corner, below File, Date */
1945         if (TEXT_SIZE_CHECK(stamp_data.rendertime, w, h)) {
1946                 y -= h;
1947
1948                 /* and space for background. */
1949                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1950                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1951
1952                 BLF_position(mono, x, y + y_ofs, 0.0);
1953                 BLF_draw_buffer(mono, stamp_data.rendertime, BLF_DRAW_STR_DUMMY_MAX);
1954
1955                 /* the extra pixel for background. */
1956                 y -= BUFF_MARGIN_Y * 2;
1957         }
1958
1959         /* Top left corner, below File, Date, Rendertime */
1960         if (TEXT_SIZE_CHECK(stamp_data.memory, w, h)) {
1961                 y -= h;
1962
1963                 /* and space for background. */
1964                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1965                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1966
1967                 BLF_position(mono, x, y + y_ofs, 0.0);
1968                 BLF_draw_buffer(mono, stamp_data.memory, BLF_DRAW_STR_DUMMY_MAX);
1969
1970                 /* the extra pixel for background. */
1971                 y -= BUFF_MARGIN_Y * 2;
1972         }
1973
1974         /* Top left corner, below File, Date, Memory, Rendertime */
1975         BLF_enable(mono, BLF_WORD_WRAP);
1976         if (TEXT_SIZE_CHECK_WORD_WRAP(stamp_data.note, w, h)) {
1977                 y -= h;
1978
1979                 /* and space for background. */
1980                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1981                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1982
1983                 BLF_position(mono, x, y + y_ofs + (h - h_fixed), 0.0);
1984                 BLF_draw_buffer(mono, stamp_data.note, BLF_DRAW_STR_DUMMY_MAX);
1985         }
1986         BLF_disable(mono, BLF_WORD_WRAP);
1987
1988         x = 0;
1989         y = 0;
1990
1991         /* Bottom left corner, leaving space for timing */
1992         if (TEXT_SIZE_CHECK(stamp_data.marker, w, h)) {
1993
1994                 /* extra space for background. */
1995                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp,  display,
1996                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1997
1998                 /* and pad the text. */
1999                 BLF_position(mono, x, y + y_ofs, 0.0);
2000                 BLF_draw_buffer(mono, stamp_data.marker, BLF_DRAW_STR_DUMMY_MAX);
2001
2002                 /* space width. */
2003                 x += w + pad;
2004         }
2005
2006         /* Left bottom corner */
2007         if (TEXT_SIZE_CHECK(stamp_data.time, w, h)) {
2008
2009                 /* extra space for background */
2010                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
2011                                   x - BUFF_MARGIN_X, y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2012
2013                 /* and pad the text. */
2014                 BLF_position(mono, x, y + y_ofs, 0.0);
2015                 BLF_draw_buffer(mono, stamp_data.time, BLF_DRAW_STR_DUMMY_MAX);
2016
2017                 /* space width. */
2018                 x += w + pad;
2019         }
2020
2021         if (TEXT_SIZE_CHECK(stamp_data.frame, w, h)) {
2022
2023                 /* extra space for background. */
2024                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
2025                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2026
2027                 /* and pad the text. */
2028                 BLF_position(mono, x, y + y_ofs, 0.0);
2029                 BLF_draw_buffer(mono, stamp_data.frame, BLF_DRAW_STR_DUMMY_MAX);
2030
2031                 /* space width. */
2032                 x += w + pad;
2033         }
2034
2035         if (TEXT_SIZE_CHECK(stamp_data.camera, w, h)) {
2036
2037                 /* extra space for background. */
2038                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
2039                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2040                 BLF_position(mono, x, y + y_ofs, 0.0);
2041                 BLF_draw_buffer(mono, stamp_data.camera, BLF_DRAW_STR_DUMMY_MAX);
2042
2043                 /* space width. */
2044                 x += w + pad;
2045         }
2046
2047         if (TEXT_SIZE_CHECK(stamp_data.cameralens, w, h)) {
2048
2049                 /* extra space for background. */
2050                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
2051                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2052                 BLF_position(mono, x, y + y_ofs, 0.0);
2053                 BLF_draw_buffer(mono, stamp_data.cameralens, BLF_DRAW_STR_DUMMY_MAX);
2054         }
2055
2056         if (TEXT_SIZE_CHECK(stamp_data.scene, w, h)) {
2057
2058                 /* Bottom right corner, with an extra space because blenfont is too strict! */
2059                 x = width - w - 2;
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
2065                 /* and pad the text. */
2066                 BLF_position(mono, x, y + y_ofs, 0.0);
2067                 BLF_draw_buffer(mono, stamp_data.scene, BLF_DRAW_STR_DUMMY_MAX);
2068         }
2069
2070         if (TEXT_SIZE_CHECK(stamp_data.strip, w, h)) {
2071
2072                 /* Top right corner, with an extra space because blenfont is too strict! */
2073                 x = width - w - pad;
2074                 y = height - h;
2075
2076                 /* extra space for background. */
2077                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
2078                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
2079
2080                 BLF_position(mono, x, y + y_ofs, 0.0);
2081                 BLF_draw_buffer(mono, stamp_data.strip, BLF_DRAW_STR_DUMMY_MAX);
2082         }
2083
2084         /* cleanup the buffer. */
2085         BLF_buffer(mono, NULL, NULL, 0, 0, 0, NULL);
2086         BLF_wordwrap(mono, 0);
2087
2088 #undef TEXT_SIZE_CHECK
2089 #undef TEXT_SIZE_CHECK_WORD_WRAP
2090 #undef BUFF_MARGIN_X
2091 #undef BUFF_MARGIN_Y
2092 }
2093
2094 void BKE_render_result_stamp_info(Scene *scene, Object *camera, struct RenderResult *rr, bool allocate_only)
2095 {
2096         struct StampData *stamp_data;
2097
2098         if (!(scene && (scene->r.stamp & R_STAMP_ALL)) && !allocate_only)
2099                 return;
2100
2101         if (!rr->stamp_data) {
2102                 stamp_data = MEM_callocN(sizeof(StampData), "RenderResult.stamp_data");
2103         }
2104         else {
2105                 stamp_data = rr->stamp_data;
2106         }
2107
2108         if (!allocate_only)
2109                 stampdata(scene, camera, stamp_data, 0);
2110
2111         if (!rr->stamp_data) {
2112                 rr->stamp_data = stamp_data;
2113         }
2114 }
2115
2116 void BKE_stamp_info_callback(void *data, struct StampData *stamp_data, StampCallback callback, bool noskip)
2117 {
2118         if ((callback == NULL) || (stamp_data == NULL)) {
2119                 return;
2120         }
2121
2122 #define CALL(member, value_str) \
2123         if (noskip || stamp_data->member[0]) { \
2124                 callback(data, value_str, stamp_data->member, sizeof(stamp_data->member)); \
2125         } ((void)0)
2126
2127         CALL(file, "File");
2128         CALL(note, "Note");
2129         CALL(date, "Date");
2130         CALL(marker, "Marker");
2131         CALL(time, "Time");
2132         CALL(frame, "Frame");
2133         CALL(camera, "Camera");
2134         CALL(cameralens, "Lens");
2135         CALL(scene, "Scene");
2136         CALL(strip, "Strip");
2137         CALL(rendertime, "RenderTime");
2138         CALL(memory, "Memory");
2139
2140         for (StampDataCustomField *custom_field = stamp_data->custom_fields.first;
2141              custom_field != NULL;
2142              custom_field = custom_field->next)
2143         {
2144                 if (noskip || custom_field->value[0]) {
2145                         callback(data, custom_field->key, custom_field->value, sizeof(custom_field->value));
2146                 }
2147         }
2148
2149 #undef CALL
2150 }
2151
2152 void BKE_render_result_stamp_data(RenderResult *rr, const char *key, const char *value)
2153 {
2154         StampData *stamp_data;
2155         if (rr->stamp_data == NULL) {
2156                 rr->stamp_data = MEM_callocN(sizeof(StampData), "RenderResult.stamp_data");
2157         }
2158         stamp_data = rr->stamp_data;
2159         StampDataCustomField *field = MEM_mallocN(sizeof(StampDataCustomField),
2160                                                   "StampData Custom Field");
2161         BLI_strncpy(field->key, key, sizeof(field->key));
2162         BLI_strncpy(field->value, value, sizeof(field->value));
2163         BLI_addtail(&stamp_data->custom_fields, field);
2164 }
2165
2166 void BKE_stamp_data_free(struct StampData *stamp_data)
2167 {
2168         if (stamp_data == NULL) {
2169                 return;
2170         }
2171         BLI_freelistN(&stamp_data->custom_fields);
2172         MEM_freeN(stamp_data);
2173 }
2174
2175 /* wrap for callback only */
2176 static void metadata_change_field(void *data, const char *propname, char *propvalue, int UNUSED(len))
2177 {
2178         IMB_metadata_change_field(data, propname, propvalue);
2179 }
2180
2181 static void metadata_get_field(void *data, const char *propname, char *propvalue, int len)
2182 {
2183         IMB_metadata_get_field(data, propname, propvalue, len);
2184 }
2185
2186 void BKE_imbuf_stamp_info(RenderResult *rr, struct ImBuf *ibuf)
2187 {
2188         struct StampData *stamp_data = rr->stamp_data;
2189
2190         BKE_stamp_info_callback(ibuf, stamp_data, metadata_change_field, false);
2191 }
2192
2193 void BKE_stamp_info_from_imbuf(RenderResult *rr, struct ImBuf *ibuf)
2194 {
2195         struct StampData *stamp_data = rr->stamp_data;
2196
2197         BKE_stamp_info_callback(ibuf, stamp_data, metadata_get_field, true);
2198 }
2199
2200 bool BKE_imbuf_alpha_test(ImBuf *ibuf)
2201 {
2202         int tot;
2203         if (ibuf->rect_float) {
2204                 const float *buf = ibuf->rect_float;
2205                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
2206                         if (buf[3] < 1.0f) {
2207                                 return true;
2208                         }
2209                 }
2210         }
2211         else if (ibuf->rect) {
2212                 unsigned char *buf = (unsigned char *)ibuf->rect;
2213                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
2214                         if (buf[3] != 255) {
2215                                 return true;
2216                         }
2217                 }
2218         }
2219
2220         return false;
2221 }
2222
2223 /* note: imf->planes is ignored here, its assumed the image channels
2224  * are already set */
2225 void BKE_imbuf_write_prepare(ImBuf *ibuf, const ImageFormatData *imf)
2226 {
2227         char imtype = imf->imtype;
2228         char compress = imf->compress;
2229         char quality = imf->quality;
2230
2231         /* initialize all from image format */
2232         ibuf->foptions.flag = 0;
2233
2234         if (imtype == R_IMF_IMTYPE_IRIS) {
2235                 ibuf->ftype = IMB_FTYPE_IMAGIC;
2236         }
2237 #ifdef WITH_HDR
2238         else if (imtype == R_IMF_IMTYPE_RADHDR) {
2239                 ibuf->ftype = IMB_FTYPE_RADHDR;
2240         }
2241 #endif
2242         else if (ELEM(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
2243                 ibuf->ftype = IMB_FTYPE_PNG;
2244
2245                 if (imtype == R_IMF_IMTYPE_PNG) {
2246                         if (imf->depth == R_IMF_CHAN_DEPTH_16)
2247                                 ibuf->foptions.flag |= PNG_16BIT;
2248
2249                         ibuf->foptions.quality = compress;
2250                 }
2251
2252         }
2253 #ifdef WITH_DDS
2254         else if (imtype == R_IMF_IMTYPE_DDS) {
2255                 ibuf->ftype = IMB_FTYPE_DDS;
2256         }
2257 #endif
2258         else if (imtype == R_IMF_IMTYPE_BMP) {
2259                 ibuf->ftype = IMB_FTYPE_BMP;
2260         }
2261 #ifdef WITH_TIFF
2262         else if (imtype == R_IMF_IMTYPE_TIFF) {
2263                 ibuf->ftype = IMB_FTYPE_TIF;
2264
2265                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2266                         ibuf->foptions.flag |= TIF_16BIT;
2267                 }
2268                 if (imf->tiff_codec == R_IMF_TIFF_CODEC_NONE) {
2269                         ibuf->foptions.flag |= TIF_COMPRESS_NONE;
2270                 }
2271                 else if (imf->tiff_codec == R_IMF_TIFF_CODEC_DEFLATE) {
2272                         ibuf->foptions.flag |= TIF_COMPRESS_DEFLATE;
2273                 }
2274                 else if (imf->tiff_codec == R_IMF_TIFF_CODEC_LZW) {
2275                         ibuf->foptions.flag |= TIF_COMPRESS_LZW;
2276                 }
2277                 else if (imf->tiff_codec == R_IMF_TIFF_CODEC_PACKBITS) {
2278                         ibuf->foptions.flag |= TIF_COMPRESS_PACKBITS;
2279                 }
2280         }
2281 #endif
2282 #ifdef WITH_OPENEXR
2283         else if (ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
2284                 ibuf->ftype = IMB_FTYPE_OPENEXR;
2285                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
2286                         ibuf->foptions.flag |= OPENEXR_HALF;
2287                 ibuf->foptions.flag |= (imf->exr_codec & OPENEXR_COMPRESS);
2288
2289                 if (!(imf->flag & R_IMF_FLAG_ZBUF)) {
2290                         /* Signal for exr saving. */
2291                         IMB_freezbuffloatImBuf(ibuf);
2292                 }
2293
2294         }
2295 #endif
2296 #ifdef WITH_CINEON
2297         else if (imtype == R_IMF_IMTYPE_CINEON) {
2298                 ibuf->ftype = IMB_FTYPE_CINEON;
2299                 if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
2300                         ibuf->foptions.flag |= CINEON_LOG;
2301                 }
2302                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2303                         ibuf->foptions.flag |= CINEON_16BIT;
2304                 }
2305                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
2306                         ibuf->foptions.flag |= CINEON_12BIT;
2307                 }
2308                 else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
2309                         ibuf->foptions.flag |= CINEON_10BIT;
2310                 }
2311         }
2312         else if (imtype == R_IMF_IMTYPE_DPX) {
2313                 ibuf->ftype = IMB_FTYPE_DPX;
2314                 if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
2315                         ibuf->foptions.flag |= CINEON_LOG;
2316                 }
2317                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2318                         ibuf->foptions.flag |= CINEON_16BIT;
2319                 }
2320                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
2321                         ibuf->foptions.flag |= CINEON_12BIT;
2322                 }
2323                 else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
2324                         ibuf->foptions.flag |= CINEON_10BIT;
2325                 }
2326         }
2327 #endif
2328         else if (imtype == R_IMF_IMTYPE_TARGA) {
2329                 ibuf->ftype = IMB_FTYPE_TGA;
2330         }
2331         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
2332                 ibuf->ftype = IMB_FTYPE_TGA;
2333                 ibuf->foptions.flag = RAWTGA;
2334         }
2335 #ifdef WITH_OPENJPEG
2336         else if (imtype == R_IMF_IMTYPE_JP2) {
2337                 if (quality < 10) quality = 90;
2338                 ibuf->ftype = IMB_FTYPE_JP2;
2339                 ibuf->foptions.quality = quality;
2340
2341                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
2342                         ibuf->foptions.flag |= JP2_16BIT;
2343                 }
2344                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
2345                         ibuf->foptions.flag |= JP2_12BIT;
2346                 }
2347
2348                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
2349                         ibuf->foptions.flag |= JP2_YCC;
2350                 }
2351
2352                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
2353                         ibuf->foptions.flag |= JP2_CINE;
2354                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
2355                                 ibuf->foptions.flag |= JP2_CINE_48FPS;
2356                 }
2357
2358                 if (imf->jp2_codec == R_IMF_JP2_CODEC_JP2)
2359                         ibuf->foptions.flag |= JP2_JP2;
2360                 else if (imf->jp2_codec == R_IMF_JP2_CODEC_J2K)
2361                         ibuf->foptions.flag |= JP2_J2K;
2362                 else
2363                         BLI_assert(!"Unsupported jp2 codec was specified in im_format->jp2_codec");
2364         }
2365 #endif
2366         else {
2367                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
2368                 if (quality < 10) quality = 90;
2369                 ibuf->ftype = IMB_FTYPE_JPG;
2370                 ibuf->foptions.quality = quality;
2371         }
2372 }
2373
2374 int BKE_imbuf_write(ImBuf *ibuf, const char *name, const ImageFormatData *imf)
2375 {
2376         int ok;
2377
2378         BKE_imbuf_write_prepare(ibuf, imf);
2379
2380         BLI_make_existing_file(name);
2381
2382         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
2383         if (ok == 0) {
2384                 perror(name);
2385         }
2386
2387         return(ok);
2388 }
2389
2390 /* same as BKE_imbuf_write() but crappy workaround not to permanently modify
2391  * _some_, values in the imbuf */
2392 int BKE_imbuf_write_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
2393                        const bool save_copy)
2394 {
2395         ImBuf ibuf_back = *ibuf;
2396         int ok;
2397
2398         /* all data is rgba anyway,
2399          * this just controls how to save for some formats */
2400         ibuf->planes = imf->planes;
2401
2402         ok = BKE_imbuf_write(ibuf, name, imf);
2403
2404         if (save_copy) {
2405                 /* note that we are not restoring _all_ settings */
2406                 ibuf->planes = ibuf_back.planes;
2407                 ibuf->ftype =  ibuf_back.ftype;
2408                 ibuf->foptions =  ibuf_back.foptions;
2409         }
2410
2411         return ok;
2412 }
2413
2414 int BKE_imbuf_write_stamp(
2415         Scene *scene, struct RenderResult *rr, ImBuf *ibuf, const char *name,
2416         const struct ImageFormatData *imf)
2417 {
2418         if (scene && scene->r.stamp & R_STAMP_ALL)
2419                 BKE_imbuf_stamp_info(rr, ibuf);
2420
2421         return BKE_imbuf_write(ibuf, name, imf);
2422 }
2423
2424 static void do_makepicstring(
2425         char *string, const char *base, const char *relbase, int frame, const char imtype,
2426         const ImageFormatData *im_format, const short use_ext, const short use_frames,
2427         const char *suffix)
2428 {
2429         if (string == NULL) return;
2430         BLI_strncpy(string, base, FILE_MAX - 10);   /* weak assumption */
2431         BLI_path_abs(string, relbase);
2432
2433         if (use_frames)
2434                 BLI_path_frame(string, frame, 4);
2435
2436         if (suffix)
2437                 BLI_path_suffix(string, FILE_MAX, suffix, "");
2438
2439         if (use_ext)
2440                 do_add_image_extension(string, imtype, im_format);
2441 }
2442
2443 void BKE_image_path_from_imformat(
2444         char *string, const char *base, const char *relbase, int frame,
2445         const ImageFormatData *im_format, const bool use_ext, const bool use_frames, const char *suffix)
2446 {
2447         do_makepicstring(string, base, relbase, frame, im_format->imtype, im_format, use_ext, use_frames, suffix);
2448 }
2449
2450 void BKE_image_path_from_imtype(
2451         char *string, const char *base, const char *relbase, int frame,
2452         const char imtype, const bool use_ext, const bool use_frames, const char *view)
2453 {
2454         do_makepicstring(string, base, relbase, frame, imtype, NULL, use_ext, use_frames, view);
2455 }
2456
2457 struct anim *openanim_noload(const char *name, int flags, int streamindex, char colorspace[IMA_MAX_SPACE])
2458 {
2459         struct anim *anim;
2460
2461         anim = IMB_open_anim(name, flags, streamindex, colorspace);
2462         return anim;
2463 }
2464
2465 /* used by sequencer too */
2466 struct anim *openanim(const char *name, int flags, int streamindex, char colorspace[IMA_MAX_SPACE])
2467 {
2468         struct anim *anim;
2469         struct ImBuf *ibuf;
2470
2471         anim = IMB_open_anim(name, flags, streamindex, colorspace);
2472         if (anim == NULL) return NULL;
2473
2474         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
2475         if (ibuf == NULL) {
2476                 if (BLI_exists(name))
2477                         printf("not an anim: %s\n", name);
2478                 else
2479                         printf("anim file doesn't exist: %s\n", name);
2480                 IMB_free_anim(anim);
2481                 return NULL;
2482         }
2483         IMB_freeImBuf(ibuf);
2484
2485         return(anim);
2486 }
2487
2488 /* ************************* New Image API *************** */
2489
2490
2491 /* Notes about Image storage
2492  * - packedfile
2493  *   -> written in .blend
2494  * - filename
2495  *   -> written in .blend
2496  * - movie
2497  *   -> comes from packedfile or filename
2498  * - renderresult
2499  *   -> comes from packedfile or filename
2500  * - listbase
2501  *   -> ibufs from exrhandle
2502  * - flipbook array
2503  *   -> ibufs come from movie, temporary renderresult or sequence
2504  * - ibuf
2505  *   -> comes from packedfile or filename or generated
2506  */
2507
2508
2509 /* forces existence of 1 Image for renderout or nodes, returns Image */
2510 /* name is only for default, when making new one */
2511 Image *BKE_image_verify_viewer(int type, const char *name)
2512 {
2513         Image *ima;
2514
2515         for (ima = G.main->image.first; ima; ima = ima->id.next)
2516                 if (ima->source == IMA_SRC_VIEWER)
2517                         if (ima->type == type)
2518                                 break;
2519
2520         if (ima == NULL)
2521                 ima = image_alloc(G.main, name, IMA_SRC_VIEWER, type);
2522
2523         /* happens on reload, imagewindow cannot be image user when hidden*/
2524         if (ima->id.us == 0)
2525                 id_us_plus(&ima->id);
2526
2527         return ima;
2528 }
2529
2530 static void image_viewer_create_views(const RenderData *rd, Image *ima)
2531 {
2532         if ((rd->scemode & R_MULTIVIEW) == 0) {
2533                 image_add_view(ima, "", "");
2534         }
2535         else {
2536                 SceneRenderView *srv;
2537                 for (srv = rd->views.first; srv; srv = srv->next) {
2538                         if (BKE_scene_multiview_is_render_view_active(rd, srv) == false)
2539                                 continue;
2540                         image_add_view(ima, srv->name, "");
2541                 }
2542         }
2543 }
2544
2545 /* Reset the image cache and views when the Viewer Nodes views don't match the scene views */
2546 void BKE_image_verify_viewer_views(const RenderData *rd, Image *ima, ImageUser *iuser)
2547 {
2548         bool do_reset;
2549         const bool is_multiview = (rd->scemode & R_MULTIVIEW) != 0;
2550
2551         BLI_thread_lock(LOCK_DRAW_IMAGE);
2552
2553         if (!BKE_scene_multiview_is_stereo3d(rd))
2554                 iuser->flag &= ~IMA_SHOW_STEREO;
2555
2556         /* see if all scene render views are in the image view list */
2557         do_reset = (BKE_scene_multiview_num_views_get(rd) != BLI_listbase_count(&ima->views));
2558
2559         /* multiview also needs to be sure all the views are synced */
2560         if (is_multiview && !do_reset) {
2561                 SceneRenderView *srv;
2562                 ImageView *iv;
2563
2564                 for (iv = ima->views.first; iv; iv = iv->next) {
2565                         srv = BLI_findstring(&rd->views, iv->name, offsetof(SceneRenderView, name));
2566                         if ((srv == NULL) || (BKE_scene_multiview_is_render_view_active(rd, srv) == false)) {
2567                                 do_reset = true;
2568                                 break;
2569                         }
2570                 }
2571         }
2572
2573         if (do_reset) {
2574                 BLI_spin_lock(&image_spin);
2575
2576                 image_free_cached_frames(ima);
2577                 BKE_image_free_views(ima);
2578
2579                 /* add new views */
2580                 image_viewer_create_views(rd, ima);
2581
2582                 BLI_spin_unlock(&image_spin);
2583         }
2584
2585         BLI_thread_unlock(LOCK_DRAW_IMAGE);
2586 }
2587
2588 void BKE_image_walk_all_users(const Main *mainp, void *customdata,
2589                               void callback(Image *ima, ImageUser *iuser, void *customdata))
2590 {
2591         wmWindowManager *wm;
2592         wmWindow *win;
2593         Tex *tex;
2594
2595         /* texture users */
2596         for (tex = mainp->tex.first; tex; tex = tex->id.next) {
2597                 if (tex->type == TEX_IMAGE && tex->ima) {
2598                         callback(tex->ima, &tex->iuser, customdata);
2599                 }
2600
2601                 if (tex->nodetree) {
2602                         bNode *node;
2603                         for (node = tex->nodetree->nodes.first; node; node = node->next) {
2604                                 if (node->id && node->type == TEX_NODE_IMAGE) {
2605                                         Image *ima = (Image *)node->id;
2606                                         ImageUser *iuser = node->storage;
2607                                         callback(ima, iuser, customdata);
2608                                 }
2609                         }
2610                 }
2611         }
2612
2613         for (Camera *cam = mainp->camera.first; cam; cam = cam->id.next) {
2614                 for (CameraBGImage *bgpic = cam->bg_images.first; bgpic; bgpic = bgpic->next) {
2615                         callback(bgpic->ima, &bgpic->iuser, customdata);
2616                 }
2617         }
2618
2619         /* image window, compo node users */
2620         for (wm = mainp->wm.first; wm; wm = wm->id.next) { /* only 1 wm */
2621                 for (win = wm->windows.first; win; win = win->next) {
2622                         const bScreen *screen = BKE_workspace_active_screen_get(win->workspace_hook);
2623
2624                         for (ScrArea *sa = screen->areabase.first; sa; sa = sa->next) {
2625                                 if (sa->spacetype == SPACE_IMAGE) {
2626                                         SpaceImage *sima = sa->spacedata.first;
2627                                         callback(sima->image, &sima->iuser, customdata);
2628                                 }
2629                                 else if (sa->spacetype == SPACE_NODE) {
2630                                         SpaceNode *snode = sa->spacedata.first;
2631                                         if (snode->nodetree && snode->nodetree->type == NTREE_COMPOSIT) {
2632                                                 bNode *node;
2633                                                 for (node = snode->nodetree->nodes.first; node; node = node->next) {
2634                                                         if (node->id && node->type == CMP_NODE_IMAGE) {
2635                                                                 Image *ima = (Image *)node->id;
2636                                                                 ImageUser *iuser = node->storage;
2637                                                                 callback(ima, iuser, customdata);
2638                                                         }
2639                                                 }
2640                                         }
2641                                 }
2642                         }
2643                 }
2644         }
2645 }
2646
2647 static void image_tag_frame_recalc(Image *ima, ImageUser *iuser, void *customdata)
2648 {
2649         Image *changed_image = customdata;
2650
2651         if (ima == changed_image && BKE_image_is_animated(ima)) {
2652                 iuser->flag |= IMA_NEED_FRAME_RECALC;
2653         }
2654 }
2655
2656 static void image_init_imageuser(Image *ima, ImageUser *iuser)
2657 {
2658         RenderResult *rr = ima->rr;
2659
2660         iuser->multi_index = 0;
2661         iuser->layer = iuser->pass = iuser->view = 0;
2662
2663         if (rr)
2664                 BKE_image_multilayer_index(rr, iuser);
2665 }
2666
2667 void BKE_image_init_imageuser(Image *ima, ImageUser *iuser)
2668 {
2669         image_init_imageuser(ima, iuser);
2670 }
2671
2672 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
2673 {
2674         if (ima == NULL)
2675                 return;
2676
2677         BLI_spin_lock(&image_spin);
2678
2679         switch (signal) {
2680                 case IMA_SIGNAL_FREE:
2681                         BKE_image_free_buffers(ima);
2682
2683                         if (iuser) {
2684                                 iuser->ok = 1;
2685                                 if (iuser->scene) {
2686                                         image_update_views_format(ima, iuser);
2687                                 }
2688                         }
2689                         break;
2690                 case IMA_SIGNAL_SRC_CHANGE:
2691                         if (ima->type == IMA_TYPE_UV_TEST)
2692                                 if (ima->source != IMA_SRC_GENERATED)
2693                                         ima->type = IMA_TYPE_IMAGE;
2694
2695                         if (ima->source == IMA_SRC_GENERATED) {
2696                                 if (ima->gen_x == 0 || ima->gen_y == 0) {
2697                                         ImBuf *ibuf = image_get_cached_ibuf_for_index_frame(ima, IMA_NO_INDEX, 0);
2698                                         if (ibuf) {
2699                                                 ima->gen_x = ibuf->x;
2700                                                 ima->gen_y = ibuf->y;
2701                                                 IMB_freeImBuf(ibuf);
2702                                         }
2703                                 }
2704
2705                                 /* Changing source type to generated will likely change file format
2706                                  * used by generated image buffer. Saving different file format to
2707                                  * the old name might confuse other applications.
2708                                  *
2709                                  * Here we ensure original image path wouldn't be used when saving
2710                                  * generated image.
2711                                  */
2712                                 ima->name[0] = '\0';
2713                         }
2714
2715 #if 0
2716                         /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
2717                         if (ima->type != IMA_TYPE_MULTILAYER)
2718                                 BKE_image_free_buffers(ima);
2719 #else
2720                         /* image buffers for non-sequence multilayer will share buffers with RenderResult,
2721                          * however sequence multilayer will own buffers. Such logic makes switching from
2722                          * single multilayer file to sequence completely unstable
2723                          * since changes in nodes seems this workaround isn't needed anymore, all sockets
2724                          * are nicely detecting anyway, but freeing buffers always here makes multilayer
2725                          * sequences behave stable
2726                          */
2727                         BKE_image_free_buffers(ima);
2728 #endif
2729
2730                         ima->ok = 1;
2731                         if (iuser)
2732                                 iuser->ok = 1;
2733
2734                         BKE_image_walk_all_users(G.main, ima, image_tag_frame_recalc);
2735
2736                         break;
2737
2738                 case IMA_SIGNAL_RELOAD:
2739                         /* try to repack file */
2740                         if (BKE_image_has_packedfile(ima)) {
2741                                 const int totfiles = image_num_files(ima);
2742
2743                                 if (totfiles != BLI_listbase_count_ex(&ima->packedfiles, totfiles + 1)) {
2744                                         /* in case there are new available files to be loaded */
2745                                         image_free_packedfiles(ima);
2746                                         BKE_image_packfiles(NULL, ima, ID_BLEND_PATH(G.main, &ima->id));
2747                                 }
2748                                 else {
2749                                         ImagePackedFile *imapf;
2750                                         for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next) {
2751                                                 PackedFile *pf;
2752                                                 pf = newPackedFile(NULL, imapf->filepath, ID_BLEND_PATH(G.main, &ima->id));
2753                                                 if (pf) {
2754                                                         freePackedFile(imapf->packedfile);
2755                                                         imapf->packedfile = pf;
2756                                                 }
2757                                                 else {
2758                                                         printf("ERROR: Image \"%s\" not available. Keeping packed image\n", imapf->filepath);
2759                                                 }
2760                                         }
2761                                 }
2762
2763                                 if (BKE_image_has_packedfile(ima))
2764                                         BKE_image_free_buffers(ima);
2765                         }
2766                         else
2767                                 BKE_image_free_buffers(ima);
2768
2769                         if (iuser) {
2770                                 iuser->ok = 1;
2771                                 if (iuser->scene) {
2772                                         image_update_views_format(ima, iuser);
2773                                 }
2774                         }
2775
2776                         break;
2777                 case IMA_SIGNAL_USER_NEW_IMAGE:
2778                         if (iuser) {
2779                                 iuser->ok = 1;
2780                                 if (ima->source == IMA_SRC_FILE || ima->source == IMA_SRC_SEQUENCE) {
2781                                         if (ima->type == IMA_TYPE_MULTILAYER) {
2782                                                 image_init_imageuser(ima, iuser);
2783                                         }
2784                                 }
2785                         }
2786                         break;
2787                 case IMA_SIGNAL_COLORMANAGE:
2788                         BKE_image_free_buffers(ima);
2789
2790                         ima->ok = 1;
2791
2792                         if (iuser)
2793                                 iuser->ok = 1;
2794
2795                         break;
2796         }
2797
2798         BLI_spin_unlock(&image_spin);
2799
2800         /* don't use notifiers because they are not 100% sure to succeeded
2801          * this also makes sure all scenes are accounted for. */
2802         {
2803                 Scene *scene;
2804                 for (scene = G.main->scene.first; scene; scene = scene->id.next) {
2805                         if (scene->nodetree) {
2806                                 nodeUpdateID(scene->nodetree, &ima->id);
2807                         }
2808                 }
2809         }
2810 }
2811
2812 /* return renderpass for a given pass index and active view */
2813 /* fallback to available if there are missing passes for active view */
2814 static RenderPass *image_render_pass_get(RenderLayer *rl, const int pass, const int view, int *r_passindex)
2815 {
2816         RenderPass *rpass_ret = NULL;
2817         RenderPass *rpass;
2818
2819         int rp_index = 0;
2820         const char *rp_name = "";
2821
2822         for (rpass = rl->passes.first; rpass; rpass = rpass->next, rp_index++) {
2823                 if (rp_index == pass) {
2824                         rpass_ret = rpass;
2825                         if (view == 0) {
2826                                 /* no multiview or left eye */
2827                                 break;
2828                         }
2829                         else {
2830                                 rp_name = rpass->name;
2831                         }
2832                 }
2833                 /* multiview */
2834                 else if (rp_name[0] &&
2835                          STREQ(rpass->name, rp_name) &&
2836                          (rpass->view_id == view))
2837                 {
2838                         rpass_ret = rpass;
2839                         break;
2840                 }
2841         }
2842
2843         /* fallback to the first pass in the layer */
2844         if (rpass_ret == NULL) {
2845                 rp_index = 0;
2846                 rpass_ret = rl->passes.first;
2847         }
2848
2849         if (r_passindex) {
2850                 *r_passindex = (rpass == rpass_ret ? rp_index : pass);
2851         }
2852
2853         return rpass_ret;
2854 }
2855
2856 /* if layer or pass changes, we need an index for the imbufs list */
2857 /* note it is called for rendered results, but it doesnt use the index! */
2858 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
2859 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
2860 {
2861         RenderLayer *rl;
2862         RenderPass *rpass = NULL;
2863
2864         if (rr == NULL)
2865                 return NULL;
2866
2867         if (iuser) {
2868                 short index = 0, rv_index, rl_index = 0;
2869                 bool is_stereo = (iuser->flag & IMA_SHOW_STEREO) && RE_RenderResult_is_stereo(rr);
2870
2871                 rv_index = is_stereo ? iuser->multiview_eye : iuser->view;
2872                 if (RE_HasCombinedLayer(rr)) rl_index += 1;
2873
2874                 for (rl = rr->layers.first; rl; rl = rl->next, rl_index++) {
2875                         if (iuser->layer == rl_index) {
2876                                 int rp_index;
2877                                 rpass = image_render_pass_get(rl, iuser->pass, rv_index, &rp_index);
2878                                 iuser->multi_index = index + rp_index;
2879                                 break;
2880                         }
2881                         else {
2882                                 index += BLI_listbase_count(&rl->passes);
2883                         }
2884                 }
2885         }
2886
2887         return rpass;
2888 }
2889
2890 void BKE_image_multiview_index(Image *ima, ImageUser *iuser)
2891 {
2892         if (iuser) {
2893                 bool is_stereo = BKE_image_is_stereo(ima) && (iuser->flag & IMA_SHOW_STEREO);
2894                 if (is_stereo) {
2895                         iuser->multi_index = iuser->multiview_eye;
2896                 }
2897                 else {
2898                         if ((iuser->view < 0) || (iuser->view >= BLI_listbase_count_ex(&ima->views, iuser->view + 1))) {
2899                                 iuser->multi_index = iuser->view = 0;
2900                         }
2901                         else {
2902                                 iuser->multi_index = iuser->view;
2903                         }
2904                 }
2905         }
2906 }
2907
2908 /* if layer or pass changes, we need an index for the imbufs list */
2909 /* note it is called for rendered results, but it doesnt use the index! */
2910 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
2911 bool BKE_image_is_multilayer(Image *ima)
2912 {
2913         if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE)) {
2914                 if (ima->type == IMA_TYPE_MULTILAYER) {
2915                         return true;
2916                 }
2917         }
2918         else if (ima->source == IMA_SRC_VIEWER) {
2919                 if (ima->type == IMA_TYPE_R_RESULT) {
2920                         return true;
2921                 }
2922         }
2923         return false;
2924 }
2925
2926 bool BKE_image_is_multiview(Image *ima)
2927 {
2928         ImageView *view = ima->views.first;
2929         return (view && (view->next || view->name[0]));
2930 }
2931
2932 bool BKE_image_is_stereo(Image *ima)
2933 {
2934         return BKE_image_is_multiview(ima) &&
2935                (BLI_findstring(&ima->views, STEREO_LEFT_NAME, offsetof(ImageView, name)) &&
2936                 BLI_findstring(&ima->views, STEREO_RIGHT_NAME, offsetof(ImageView, name)));
2937 }
2938
2939 static void image_init_multilayer_multiview(Image *ima, RenderResult *rr)
2940 {
2941         /* update image views from render views, but only if they actually changed,
2942          * to avoid invalid memory access during render. ideally these should always
2943          * be acquired with a mutex along with the render result, but there are still
2944          * some places with just an image pointer that need to access views */
2945         if (rr && BLI_listbase_count(&ima->views) == BLI_listbase_count(&rr->views)) {
2946                 ImageView *iv = ima->views.first;
2947                 RenderView *rv = rr->views.first;
2948                 bool modified = false;
2949                 for (; rv; rv = rv->next, iv = iv->next) {
2950                         modified |= !STREQ(rv->name, iv->name);
2951                 }
2952                 if (!modified)
2953                         return;
2954         }
2955
2956         BKE_image_free_views(ima);
2957
2958         if (rr) {
2959                 for (RenderView *rv = rr->views.first; rv; rv = rv->next) {
2960                         ImageView *iv = MEM_callocN(sizeof(ImageView), "Viewer Image View");
2961                         BLI_strncpy(iv->name, rv->name, sizeof(iv->name));
2962                         BLI_addtail(&ima->views, iv);
2963                 }
2964         }
2965 }
2966
2967
2968 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
2969 {
2970         RenderResult *rr = NULL;
2971         if (ima->rr) {
2972                 rr = ima->rr;
2973         }
2974         else if (ima->type == IMA_TYPE_R_RESULT) {
2975                 if (ima->render_slot == ima->last_render_slot)
2976                         rr = RE_AcquireResultRead(RE_GetSceneRender(scene));
2977                 else
2978                         rr = ima->renders[ima->render_slot];
2979
2980                 /* set proper views */
2981                 image_init_multilayer_multiview(ima, rr);
2982         }
2983
2984         return rr;
2985 }
2986
2987 void BKE_image_release_renderresult(Scene *scene, Image *ima)
2988 {
2989         if (ima->rr) {
2990                 /* pass */
2991         }
2992         else if (ima->type == IMA_TYPE_R_RESULT) {
2993                 if (ima->render_slot == ima->last_render_slot)
2994                         RE_ReleaseResult(RE_GetSceneRender(scene));
2995         }
2996 }
2997
2998 bool BKE_image_is_openexr(struct Image *ima)
2999 {
3000 #ifdef WITH_OPENEXR
3001         if (ELEM(ima->source, IMA_SRC_FILE, IMA_SRC_SEQUENCE)) {
3002                 return BLI_testextensie(ima->name, ".exr");
3003         }
3004 #else
3005         UNUSED_VARS(ima);
3006 #endif
3007         return false;
3008 }
3009
3010 void BKE_image_backup_render(Scene *scene, Image *ima, bool free_current_slot)
3011 {
3012         /* called right before rendering, ima->renders contains render
3013          * result pointers for everything but the current render */
3014         Render *re = RE_GetSceneRender(scene);
3015         int slot = ima->render_slot, last = ima->last_render_slot;
3016
3017         if (slot != last) {
3018                 ima->renders[last] = NULL;
3019                 RE_SwapResult(re, &ima->renders[last]);
3020
3021                 if (ima->renders[slot]) {
3022                         if (free_current_slot) {
3023                                 RE_FreeRenderResult(ima->renders[slot]);
3024                                 ima->renders[slot] = NULL;
3025                         }
3026                         else {
3027                                 RE_SwapResult(re, &ima->renders[slot]);
3028                         }
3029                 }
3030         }
3031
3032         ima->last_render_slot = slot;
3033 }
3034
3035 /**************************** multiview load openexr *********************************/
3036
3037 static void image_add_view(Image *ima, const char *viewname, const char *filepath)
3038 {
3039         ImageView *iv;
3040
3041         iv = MEM_mallocN(sizeof(ImageView), "Viewer Image View");
3042         BLI_strncpy(iv->name, viewname, sizeof(iv->name));
3043         BLI_strncpy(iv->filepath, filepath, sizeof(iv->filepath));
3044
3045         /* For stereo drawing we need to ensure:
3046          * STEREO_LEFT_NAME  == STEREO_LEFT_ID and
3047          * STEREO_RIGHT_NAME == STEREO_RIGHT_ID */
3048
3049         if (STREQ(viewname, STEREO_LEFT_NAME)) {
3050                 BLI_addhead(&ima->views, iv);
3051         }
3052         else if (STREQ(viewname, STEREO_RIGHT_NAME)) {
3053                 ImageView *left_iv = BLI_findstring(&ima->views, STEREO_LEFT_NAME, offsetof(ImageView, name));
3054
3055                 if (left_iv == NULL) {
3056                         BLI_addhead(&ima->views, iv);
3057                 }
3058                 else {
3059                         BLI_insertlinkafter(&ima->views, left_iv, iv);
3060                 }
3061         }
3062         else {
3063                 BLI_addtail(&ima->views, iv);
3064         }
3065 }
3066
3067 /* after imbuf load, openexr type can return with a exrhandle open */
3068 /* in that case we have to build a render-result */
3069 #ifdef WITH_OPENEXR
3070 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
3071 {
3072         const char *colorspace = ima->colorspace_settings.name;
3073         bool predivide = (ima->alpha_mode == IMA_ALPHA_PREMUL);
3074
3075         /* only load rr once for multiview */
3076         if (!ima->rr)
3077                 ima->rr = RE_MultilayerConvert(ibuf->userdata, colorspace, predivide, ibuf->x, ibuf->y);
3078
3079         IMB_exr_close(ibuf->userdata);
3080
3081         ibuf->userdata = NULL;
3082         if (ima->rr)
3083                 ima->rr->framenr = framenr;
3084
3085         /* set proper views */
3086         image_init_multilayer_multiview(ima, ima->rr);
3087 }
3088 #endif  /* WITH_OPENEXR */
3089
3090 /* common stuff to do with images after loading */
3091 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
3092 {
3093         /* preview is NULL when it has never been used as an icon before */
3094         if (G.background == 0 && ima->preview == NULL)
3095                 BKE_icon_changed(BKE_icon_id_ensure(&ima->id));
3096
3097         /* fields */
3098         if (ima->flag & IMA_FIELDS) {
3099                 if (ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
3100                 else de_interlace_ng(ibuf);
3101         }
3102         /* timer */
3103         BKE_image_tag_time(ima);
3104
3105         ima->ok = IMA_OK_LOADED;
3106
3107 }
3108
3109 static int imbuf_alpha_flags_for_image(Image *ima)
3110 {
3111         int flag = 0;
3112
3113         if (ima->flag & IMA_IGNORE_ALPHA)
3114                 flag |= IB_ignore_alpha;
3115         else if (ima->alpha_mode == IMA_ALPHA_PREMUL)
3116                 flag |= IB_alphamode_premul;
3117
3118         return flag;
3119 }
3120
3121 /* the number of files will vary according to the stereo format */
3122 static int image_num_files(Image *ima)
3123 {
3124         const bool is_multiview = BKE_image_is_multiview(ima);
3125
3126         if (!is_multiview) {
3127                 return 1;
3128         }
3129         else if (ima->views_format == R_IMF_VIEWS_STEREO_3D) {
3130                 return 1;
3131         }
3132         /* R_IMF_VIEWS_INDIVIDUAL */
3133         else {
3134                 return BLI_listbase_count(&ima->views);
3135         }
3136 }
3137
3138 static ImBuf *load_sequence_single(Image *ima, ImageUser *iuser, int frame, const int view_id, bool *r_assign)
3139 {
3140         struct ImBuf *ibuf;
3141         char name[FILE_MAX];
3142         int flag;
3143         ImageUser iuser_t = {0};
3144
3145         /* XXX temp stuff? */
3146         if (ima->lastframe != frame)
3147                 ima->tpageflag |= IMA_TPAGE_REFRESH;
3148
3149         ima->lastframe = frame;
3150
3151         if (iuser) {
3152                 iuser_t = *iuser;
3153         }
3154         else {
3155                 /* TODO(sergey): Do we need to initialize something here? */
3156         }
3157
3158         iuser_t.view = view_id;
3159         BKE_image_user_file_path(&iuser_t, ima, name);
3160
3161         flag = IB_rect | IB_multilayer;
3162         flag |= imbuf_alpha_flags_for_image(ima);
3163
3164         /* read ibuf */
3165         ibuf = IMB_loadiffname(name, flag, ima->colorspace_settings.name);
3166
3167 #if 0
3168         if (ibuf) {
3169                 printf(AT " loaded %s\n", name);
3170         }
3171         else {
3172                 printf(AT " missed %s\n", name);
3173         }
3174 #endif
3175
3176         if (ibuf) {
3177 #ifdef WITH_OPENEXR
3178                 if (ibuf->ftype == IMB_FTYPE_OPENEXR && ibuf->userdata) {
3179                         /* Handle multilayer and multiview cases, don't assign ibuf here.
3180                          * will be set layer in BKE_image_acquire_ibuf from ima->rr. */
3181                         if (IMB_exr_has_multilayer(ibuf->userdata)) {
3182                                 image_create_multilayer(ima, ibuf, frame);
3183                                 ima->type = IMA_TYPE_MULTILAYER;
3184                                 IMB_freeImBuf(ibuf);
3185                                 ibuf = NULL;
3186                         }
3187                 }
3188                 else {
3189                         image_initialize_after_load(ima, ibuf);
3190                         *r_assign = true;
3191                 }
3192 #else
3193                 image_initialize_after_load(ima, ibuf);
3194                 *r_assign = true;
3195 #endif
3196         }
3197
3198         return ibuf;
3199 }
3200
3201 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
3202 {
3203         struct ImBuf *ibuf = NULL;
3204         const bool is_multiview = BKE_image_is_multiview(ima);
3205         const int totfiles = image_num_files(ima);
3206         bool assign = false;
3207
3208         if (!is_multiview) {
3209                 ibuf = load_sequence_single(ima, iuser, frame, 0, &assign);
3210                 if (assign) {
3211                         image_assign_ibuf(ima, ibuf, 0, frame);
3212                 }
3213         }
3214         else {
3215                 const int totviews = BLI_listbase_count(&ima->views);
3216                 int i;
3217                 struct ImBuf **ibuf_arr;
3218
3219                 ibuf_arr = MEM_mallocN(sizeof(ImBuf *) * totviews, "Image Views Imbufs");
3220
3221                 for (i = 0; i < totfiles; i++)
3222                         ibuf_arr[i] = load_sequence_single(ima, iuser, frame, i, &assign);
3223
3224                 if (BKE_image_is_stereo(ima) && ima->views_format == R_IMF_VIEWS_STEREO_3D)
3225                         IMB_ImBufFromStereo3d(ima->stereo3d_format, ibuf_arr[0], &ibuf_arr[0], &ibuf_arr[1]);
3226
3227                 /* return the original requested ImBuf */
3228                 ibuf = ibuf_arr[(iuser ? iuser->multi_index : 0)];
3229
3230                 if (assign) {
3231                         for (i = 0; i < totviews; i++) {
3232                                 image_assign_ibuf(ima, ibuf_arr[i], i, frame);
3233                         }
3234                 }
3235
3236                 /* "remove" the others (decrease their refcount) */
3237                 for (i = 0; i < totviews; i++) {
3238                         if (ibuf_arr[i] != ibuf) {
3239                                 IMB_freeImBuf(ibuf_arr[i]);
3240                         }
3241                 }
3242
3243                 /* cleanup */
3244                 MEM_freeN(ibuf_arr);
3245         }
3246
3247         return ibuf;
3248 }
3249
3250 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
3251 {
3252         struct ImBuf *ibuf = NULL;
3253
3254         /* either we load from RenderResult, or we have to load a new one */
3255
3256         /* check for new RenderResult */
3257         if (ima->rr == NULL || frame != ima->rr->framenr) {
3258                 if (ima->rr) {
3259                         /* Cached image buffers shares pointers with render result,
3260                          * need to ensure there's no image buffers are hanging around
3261                          * with dead links after freeing the render result.
3262                          */
3263                         image_free_cached_frames(ima);
3264                         RE_FreeRenderResult(ima->rr);
3265                         ima->rr = NULL;
3266                 }
3267
3268                 ibuf = image_load_sequence_file(ima, iuser, frame);
3269
3270                 if (ibuf) { /* actually an error */
3271                         ima->type = IMA_TYPE_IMAGE;
3272                         printf("error, multi is normal image\n");
3273                 }
3274         }
3275         if (ima->rr) {
3276                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
3277
3278                 if (rpass) {
3279                         // printf("load from pass %s\n", rpass->name);
3280                         /* since we free  render results, we copy the rect */
3281                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
3282                         ibuf->rect_float = MEM_dupallocN(rpass->rect);
3283                         ibuf->flags |= IB_rectfloat;
3284                         ibuf->mall = IB_rectfloat;
3285                         ibuf->channels = rpass->channels;
3286
3287                         image_initialize_after_load(ima, ibuf);
3288                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : 0, frame);
3289
3290                 }
3291                 // else printf("pass not found\n");
3292         }
3293         else
3294                 ima->ok = 0;
3295
3296         if (iuser)
3297                 iuser->ok = ima->ok;
3298
3299         return ibuf;
3300 }
3301
3302 static ImBuf *load_movie_single(Image *ima, ImageUser *iuser, int frame, const int view_id)
3303 {
3304         struct ImBuf *ibuf = NULL;
3305         ImageAnim *ia;
3306
3307         ia = BLI_findlink(&ima->anims, view_id);
3308
3309         if (ia->anim == NULL) {
3310                 char str[FILE_MAX];
3311                 int flags = IB_rect;
3312                 ImageUser iuser_t;
3313
3314                 if (ima->flag & IMA_DEINTERLACE) {
3315                         flags |= IB_animdeinterlace;
3316                 }
3317
3318                 if (iuser)
3319                         iuser_t = *iuser;
3320
3321                 iuser_t.view = view_id;
3322
3323                 BKE_image_user_file_path(&iuser_t, ima, str);
3324
3325                 /* FIXME: make several stream accessible in image editor, too*/
3326                 ia->anim = openanim(str, flags, 0, ima->colorspace_settings.name);
3327
3328                 /* let's initialize this user */
3329                 if (ia->anim && iuser && iuser->frames == 0)
3330                         iuser->frames = IMB_anim_get_duration(ia->anim,
3331                                                               IMB_TC_RECORD_RUN);
3332         }
3333
3334         if (ia->anim) {
3335                 int dur = IMB_anim_get_duration(ia->anim,
3336                                                 IMB_TC_RECORD_RUN);
3337                 int fra = frame - 1;
3338
3339                 if (fra < 0) fra = 0;
3340                 if (fra > (dur - 1)) fra = dur - 1;
3341                 ibuf&