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