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