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