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