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