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