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