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