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