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