move pbvh into BKE, it used many BKE bad level includes.
[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;
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 int BKE_add_image_extension(char *string, const char imtype)
1169 {
1170         const char *extension = NULL;
1171
1172         if (imtype == R_IMF_IMTYPE_IRIS) {
1173                 if (!BLI_testextensie(string, ".rgb"))
1174                         extension = ".rgb";
1175         }
1176         else if (imtype == R_IMF_IMTYPE_IRIZ) {
1177                 if (!BLI_testextensie(string, ".rgb"))
1178                         extension = ".rgb";
1179         }
1180 #ifdef WITH_HDR
1181         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1182                 if (!BLI_testextensie(string, ".hdr"))
1183                         extension = ".hdr";
1184         }
1185 #endif
1186         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1187                 if (!BLI_testextensie(string, ".png"))
1188                         extension = ".png";
1189         }
1190 #ifdef WITH_DDS
1191         else if (imtype == R_IMF_IMTYPE_DDS) {
1192                 if (!BLI_testextensie(string, ".dds"))
1193                         extension = ".dds";
1194         }
1195 #endif
1196         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
1197                 if (!BLI_testextensie(string, ".tga"))
1198                         extension = ".tga";
1199         }
1200         else if (imtype == R_IMF_IMTYPE_BMP) {
1201                 if (!BLI_testextensie(string, ".bmp"))
1202                         extension = ".bmp";
1203         }
1204 #ifdef WITH_TIFF
1205         else if (imtype == R_IMF_IMTYPE_TIFF) {
1206                 if (!BLI_testextensie(string, ".tif") &&
1207                     !BLI_testextensie(string, ".tiff"))
1208                 {
1209                         extension = ".tif";
1210                 }
1211         }
1212 #endif
1213 #ifdef WITH_OPENEXR
1214         else if (ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
1215                 if (!BLI_testextensie(string, ".exr"))
1216                         extension = ".exr";
1217         }
1218 #endif
1219 #ifdef WITH_CINEON
1220         else if (imtype == R_IMF_IMTYPE_CINEON) {
1221                 if (!BLI_testextensie(string, ".cin"))
1222                         extension = ".cin";
1223         }
1224         else if (imtype == R_IMF_IMTYPE_DPX) {
1225                 if (!BLI_testextensie(string, ".dpx"))
1226                         extension = ".dpx";
1227         }
1228 #endif
1229         else if (imtype == R_IMF_IMTYPE_TARGA) {
1230                 if (!BLI_testextensie(string, ".tga"))
1231                         extension = ".tga";
1232         }
1233 #ifdef WITH_OPENJPEG
1234         else if (imtype == R_IMF_IMTYPE_JP2) {
1235                 if (!BLI_testextensie(string, ".jp2"))
1236                         extension = ".jp2";
1237         }
1238 #endif
1239         else { //   R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90, R_IMF_IMTYPE_QUICKTIME etc
1240                 if (!(BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
1241                         extension = ".jpg";
1242         }
1243
1244         if (extension) {
1245                 /* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */
1246                 /* remove any other known image extension */
1247                 if (BLI_testextensie_array(string, imb_ext_image) ||
1248                     (G.have_quicktime && BLI_testextensie_array(string, imb_ext_image_qt)))
1249                 {
1250                         return BLI_replace_extension(string, FILE_MAX, extension);
1251                 }
1252                 else {
1253                         return BLI_ensure_extension(string, FILE_MAX, extension);
1254                 }
1255
1256         }
1257         else {
1258                 return FALSE;
1259         }
1260 }
1261
1262 void BKE_imformat_defaults(ImageFormatData *im_format)
1263 {
1264         memset(im_format, 0, sizeof(*im_format));
1265         im_format->planes = R_IMF_PLANES_RGB;
1266         im_format->imtype = R_IMF_IMTYPE_PNG;
1267         im_format->quality = 90;
1268         im_format->compress = 90;
1269
1270         BKE_color_managed_display_settings_init(&im_format->display_settings);
1271         BKE_color_managed_view_settings_init(&im_format->view_settings);
1272 }
1273
1274 void BKE_imbuf_to_image_format(struct ImageFormatData *im_format, const ImBuf *imbuf)
1275 {
1276         int ftype        = imbuf->ftype & ~IB_CUSTOM_FLAGS_MASK;
1277         int custom_flags = imbuf->ftype & IB_CUSTOM_FLAGS_MASK;
1278
1279         BKE_imformat_defaults(im_format);
1280
1281         /* file type */
1282
1283         if (ftype == IMAGIC)
1284                 im_format->imtype = R_IMF_IMTYPE_IRIS;
1285
1286 #ifdef WITH_HDR
1287         else if (ftype == RADHDR)
1288                 im_format->imtype = R_IMF_IMTYPE_RADHDR;
1289 #endif
1290
1291         else if (ftype == PNG)
1292                 im_format->imtype = R_IMF_IMTYPE_PNG;
1293
1294 #ifdef WITH_DDS
1295         else if (ftype == DDS)
1296                 im_format->imtype = R_IMF_IMTYPE_DDS;
1297 #endif
1298
1299         else if (ftype == BMP)
1300                 im_format->imtype = R_IMF_IMTYPE_BMP;
1301
1302 #ifdef WITH_TIFF
1303         else if (ftype == TIF) {
1304                 im_format->imtype = R_IMF_IMTYPE_TIFF;
1305                 if (custom_flags & TIF_16BIT)
1306                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1307         }
1308 #endif
1309
1310 #ifdef WITH_OPENEXR
1311         else if (ftype == OPENEXR) {
1312                 im_format->imtype = R_IMF_IMTYPE_OPENEXR;
1313                 if (custom_flags & OPENEXR_HALF)
1314                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1315                 if (custom_flags & OPENEXR_COMPRESS)
1316                         im_format->exr_codec = R_IMF_EXR_CODEC_ZIP;  // Can't determine compression
1317                 if (imbuf->zbuf_float)
1318                         im_format->flag |= R_IMF_FLAG_ZBUF;
1319         }
1320 #endif
1321
1322 #ifdef WITH_CINEON
1323         else if (ftype == CINEON)
1324                 im_format->imtype = R_IMF_IMTYPE_CINEON;
1325         else if (ftype == DPX)
1326                 im_format->imtype = R_IMF_IMTYPE_DPX;
1327 #endif
1328
1329         else if (ftype == TGA) {
1330                 im_format->imtype = R_IMF_IMTYPE_TARGA;
1331         }
1332         else if (ftype == RAWTGA) {
1333                 im_format->imtype = R_IMF_IMTYPE_RAWTGA;
1334         }
1335
1336 #ifdef WITH_OPENJPEG
1337         else if (ftype & JP2) {
1338                 im_format->imtype = R_IMF_IMTYPE_JP2;
1339                 im_format->quality = custom_flags & ~JPG_MSK;
1340
1341                 if (ftype & JP2_16BIT)
1342                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1343                 else if (ftype & JP2_12BIT)
1344                         im_format->depth = R_IMF_CHAN_DEPTH_12;
1345
1346                 if (ftype & JP2_YCC)
1347                         im_format->jp2_flag |= R_IMF_JP2_FLAG_YCC;
1348
1349                 if (ftype & JP2_CINE) {
1350                         im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_PRESET;
1351                         if (ftype & JP2_CINE_48FPS)
1352                                 im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_48;
1353                 }
1354         }
1355 #endif
1356
1357         else {
1358                 im_format->imtype = R_IMF_IMTYPE_JPEG90;
1359                 im_format->quality = custom_flags & ~JPG_MSK;
1360         }
1361
1362         /* planes */
1363         switch (imbuf->channels) {
1364                 case 0:
1365                 case 4: im_format->planes = R_IMF_PLANES_RGBA;
1366                         break;
1367                 case 3: im_format->planes = R_IMF_PLANES_RGB;
1368                         break;
1369                 case 1: im_format->planes = R_IMF_PLANES_BW;
1370                         break;
1371                 default: im_format->planes = R_IMF_PLANES_RGB;
1372                         break;
1373         }
1374
1375 }
1376
1377 static void timecode_simple_string(char *text, size_t text_size, const int cfra, int const frs_sec)
1378 {
1379         int f = (int)(cfra % frs_sec);
1380         int s = (int)(cfra / frs_sec);
1381         int h = 0;
1382         int m = 0;
1383
1384         if (s) {
1385                 m = (int)(s / 60);
1386                 s %= 60;
1387
1388                 if (m) {
1389                         h = (int)(m / 60);
1390                         m %= 60;
1391                 }
1392         }
1393
1394         if (frs_sec < 100) {
1395                 BLI_snprintf(text, text_size, "%02d:%02d:%02d.%02d", h, m, s, f);
1396         }
1397         else {
1398                 BLI_snprintf(text, text_size, "%02d:%02d:%02d.%03d", h, m, s, f);
1399         }
1400 }
1401
1402 #define STAMP_NAME_SIZE ((MAX_ID_NAME - 2) + 16)
1403 /* could allow access externally - 512 is for long names,
1404  * STAMP_NAME_SIZE is for id names, allowing them some room for description */
1405 typedef struct StampData {
1406         char file[512];
1407         char note[512];
1408         char date[512];
1409         char marker[512];
1410         char time[512];
1411         char frame[512];
1412         char camera[STAMP_NAME_SIZE];
1413         char cameralens[STAMP_NAME_SIZE];
1414         char scene[STAMP_NAME_SIZE];
1415         char strip[STAMP_NAME_SIZE];
1416         char rendertime[STAMP_NAME_SIZE];
1417 } StampData;
1418 #undef STAMP_NAME_SIZE
1419
1420 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix)
1421 {
1422         char text[256];
1423         struct tm *tl;
1424         time_t t;
1425
1426         if (scene->r.stamp & R_STAMP_FILENAME) {
1427                 BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), do_prefix ? "File %s" : "%s", G.relbase_valid ? G.main->name : "<untitled>");
1428         }
1429         else {
1430                 stamp_data->file[0] = '\0';
1431         }
1432
1433         if (scene->r.stamp & R_STAMP_NOTE) {
1434                 /* Never do prefix for Note */
1435                 BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", scene->r.stamp_udata);
1436         }
1437         else {
1438                 stamp_data->note[0] = '\0';
1439         }
1440
1441         if (scene->r.stamp & R_STAMP_DATE) {
1442                 t = time(NULL);
1443                 tl = localtime(&t);
1444                 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);
1445                 BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), do_prefix ? "Date %s" : "%s", text);
1446         }
1447         else {
1448                 stamp_data->date[0] = '\0';
1449         }
1450
1451         if (scene->r.stamp & R_STAMP_MARKER) {
1452                 char *name = BKE_scene_find_last_marker_name(scene, CFRA);
1453
1454                 if (name) BLI_strncpy(text, name, sizeof(text));
1455                 else BLI_strncpy(text, "<none>", sizeof(text));
1456
1457                 BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), do_prefix ? "Marker %s" : "%s", text);
1458         }
1459         else {
1460                 stamp_data->marker[0] = '\0';
1461         }
1462
1463         if (scene->r.stamp & R_STAMP_TIME) {
1464                 timecode_simple_string(text, sizeof(text), scene->r.cfra, scene->r.frs_sec);
1465                 BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), do_prefix ? "Time %s" : "%s", text);
1466         }
1467         else {
1468                 stamp_data->time[0] = '\0';
1469         }
1470
1471         if (scene->r.stamp & R_STAMP_FRAME) {
1472                 char fmtstr[32];
1473                 int digits = 1;
1474
1475                 if (scene->r.efra > 9)
1476                         digits = 1 + (int) log10(scene->r.efra);
1477
1478                 BLI_snprintf(fmtstr, sizeof(fmtstr), do_prefix ? "Frame %%0%di" : "%%0%di", digits);
1479                 BLI_snprintf(stamp_data->frame, sizeof(stamp_data->frame), fmtstr, scene->r.cfra);
1480         }
1481         else {
1482                 stamp_data->frame[0] = '\0';
1483         }
1484
1485         if (scene->r.stamp & R_STAMP_CAMERA) {
1486                 BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), do_prefix ? "Camera %s" : "%s", camera ? camera->id.name + 2 : "<none>");
1487         }
1488         else {
1489                 stamp_data->camera[0] = '\0';
1490         }
1491
1492         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1493                 if (camera && camera->type == OB_CAMERA) {
1494                         BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)camera->data)->lens);
1495                 }
1496                 else BLI_strncpy(text, "<none>", sizeof(text));
1497
1498                 BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), do_prefix ? "Lens %s" : "%s", text);
1499         }
1500         else {
1501                 stamp_data->cameralens[0] = '\0';
1502         }
1503
1504         if (scene->r.stamp & R_STAMP_SCENE) {
1505                 BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), do_prefix ? "Scene %s" : "%s", scene->id.name + 2);
1506         }
1507         else {
1508                 stamp_data->scene[0] = '\0';
1509         }
1510
1511         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1512                 Sequence *seq = BKE_sequencer_foreground_frame_get(scene, scene->r.cfra);
1513
1514                 if (seq) BLI_strncpy(text, seq->name + 2, sizeof(text));
1515                 else BLI_strncpy(text, "<none>", sizeof(text));
1516
1517                 BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), do_prefix ? "Strip %s" : "%s", text);
1518         }
1519         else {
1520                 stamp_data->strip[0] = '\0';
1521         }
1522
1523         {
1524                 Render *re = RE_GetRender(scene->id.name);
1525                 RenderStats *stats = re ? RE_GetStats(re) : NULL;
1526
1527                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1528                         BLI_timestr(stats->lastframetime, text);
1529
1530                         BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), do_prefix ? "RenderTime %s" : "%s", text);
1531                 }
1532                 else {
1533                         stamp_data->rendertime[0] = '\0';
1534                 }
1535         }
1536 }
1537
1538 void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rectf, int width, int height, int channels)
1539 {
1540         struct StampData stamp_data;
1541         float w, h, pad;
1542         int x, y, y_ofs;
1543         float h_fixed;
1544         const int mono = blf_mono_font_render; // XXX
1545         struct ColorManagedDisplay *display;
1546         const char *display_device;
1547
1548         /* this could be an argument if we want to operate on non linear float imbuf's
1549          * for now though this is only used for renders which use scene settings */
1550
1551 #define BUFF_MARGIN_X 2
1552 #define BUFF_MARGIN_Y 1
1553
1554         if (!rect && !rectf)
1555                 return;
1556
1557         display_device = scene->display_settings.display_device;
1558         display = IMB_colormanagement_display_get_named(display_device);
1559
1560         stampdata(scene, camera, &stamp_data, 1);
1561
1562         /* TODO, do_versions */
1563         if (scene->r.stamp_font_id < 8)
1564                 scene->r.stamp_font_id = 12;
1565
1566         /* set before return */
1567         BLF_size(mono, scene->r.stamp_font_id, 72);
1568
1569         BLF_buffer(mono, rectf, rect, width, height, channels, display);
1570         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1571         pad = BLF_width_max(mono);
1572
1573         /* use 'h_fixed' rather than 'h', aligns better */
1574         h_fixed = BLF_height_max(mono);
1575         y_ofs = -BLF_descender(mono);
1576
1577         x = 0;
1578         y = height;
1579
1580         if (stamp_data.file[0]) {
1581                 /* Top left corner */
1582                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h = h_fixed;
1583                 y -= h;
1584
1585                 /* also a little of space to the background. */
1586                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1587                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1588
1589                 /* and draw the text. */
1590                 BLF_position(mono, x, y + y_ofs, 0.0);
1591                 BLF_draw_buffer(mono, stamp_data.file);
1592
1593                 /* the extra pixel for background. */
1594                 y -= BUFF_MARGIN_Y * 2;
1595         }
1596
1597         /* Top left corner, below File */
1598         if (stamp_data.note[0]) {
1599                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h = h_fixed;
1600                 y -= h;
1601
1602                 /* and space for background. */
1603                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1604                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1605
1606                 BLF_position(mono, x, y + y_ofs, 0.0);
1607                 BLF_draw_buffer(mono, stamp_data.note);
1608
1609                 /* the extra pixel for background. */
1610                 y -= BUFF_MARGIN_Y * 2;
1611         }
1612
1613         /* Top left corner, below File (or Note) */
1614         if (stamp_data.date[0]) {
1615                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h = h_fixed;
1616                 y -= h;
1617
1618                 /* and space for background. */
1619                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1620                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1621
1622                 BLF_position(mono, x, y + y_ofs, 0.0);
1623                 BLF_draw_buffer(mono, stamp_data.date);
1624
1625                 /* the extra pixel for background. */
1626                 y -= BUFF_MARGIN_Y * 2;
1627         }
1628
1629         /* Top left corner, below File, Date or Note */
1630         if (stamp_data.rendertime[0]) {
1631                 BLF_width_and_height(mono, stamp_data.rendertime, &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.rendertime);
1640         }
1641
1642         x = 0;
1643         y = 0;
1644
1645         /* Bottom left corner, leaving space for timing */
1646         if (stamp_data.marker[0]) {
1647                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h = h_fixed;
1648
1649                 /* extra space for background. */
1650                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp,  display,
1651                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1652
1653                 /* and pad the text. */
1654                 BLF_position(mono, x, y + y_ofs, 0.0);
1655                 BLF_draw_buffer(mono, stamp_data.marker);
1656
1657                 /* space width. */
1658                 x += w + pad;
1659         }
1660
1661         /* Left bottom corner */
1662         if (stamp_data.time[0]) {
1663                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h = h_fixed;
1664
1665                 /* extra space for background */
1666                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1667                                   x - BUFF_MARGIN_X, y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1668
1669                 /* and pad the text. */
1670                 BLF_position(mono, x, y + y_ofs, 0.0);
1671                 BLF_draw_buffer(mono, stamp_data.time);
1672
1673                 /* space width. */
1674                 x += w + pad;
1675         }
1676
1677         if (stamp_data.frame[0]) {
1678                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h = h_fixed;
1679
1680                 /* extra space for background. */
1681                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1682                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1683
1684                 /* and pad the text. */
1685                 BLF_position(mono, x, y + y_ofs, 0.0);
1686                 BLF_draw_buffer(mono, stamp_data.frame);
1687
1688                 /* space width. */
1689                 x += w + pad;
1690         }
1691
1692         if (stamp_data.camera[0]) {
1693                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h = h_fixed;
1694
1695                 /* extra space for background. */
1696                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1697                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1698                 BLF_position(mono, x, y + y_ofs, 0.0);
1699                 BLF_draw_buffer(mono, stamp_data.camera);
1700
1701                 /* space width. */
1702                 x += w + pad;
1703         }
1704
1705         if (stamp_data.cameralens[0]) {
1706                 BLF_width_and_height(mono, stamp_data.cameralens, &w, &h); h = h_fixed;
1707
1708                 /* extra space for background. */
1709                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1710                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1711                 BLF_position(mono, x, y + y_ofs, 0.0);
1712                 BLF_draw_buffer(mono, stamp_data.cameralens);
1713         }
1714
1715         if (stamp_data.scene[0]) {
1716                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h = h_fixed;
1717
1718                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1719                 x = width - w - 2;
1720
1721                 /* extra space for background. */
1722                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1723                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1724
1725                 /* and pad the text. */
1726                 BLF_position(mono, x, y + y_ofs, 0.0);
1727                 BLF_draw_buffer(mono, stamp_data.scene);
1728         }
1729
1730         if (stamp_data.strip[0]) {
1731                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h = h_fixed;
1732
1733                 /* Top right corner, with an extra space because blenfont is too strict! */
1734                 x = width - w - pad;
1735                 y = height - h;
1736
1737                 /* extra space for background. */
1738                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1739                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1740
1741                 BLF_position(mono, x, y + y_ofs, 0.0);
1742                 BLF_draw_buffer(mono, stamp_data.strip);
1743         }
1744
1745         /* cleanup the buffer. */
1746         BLF_buffer(mono, NULL, NULL, 0, 0, 0, FALSE);
1747
1748 #undef BUFF_MARGIN_X
1749 #undef BUFF_MARGIN_Y
1750 }
1751
1752 void BKE_imbuf_stamp_info(Scene *scene, Object *camera, struct ImBuf *ibuf)
1753 {
1754         struct StampData stamp_data;
1755
1756         if (!ibuf) return;
1757
1758         /* fill all the data values, no prefix */
1759         stampdata(scene, camera, &stamp_data, 0);
1760
1761         if (stamp_data.file[0]) IMB_metadata_change_field(ibuf, "File",        stamp_data.file);
1762         if (stamp_data.note[0]) IMB_metadata_change_field(ibuf, "Note",        stamp_data.note);
1763         if (stamp_data.date[0]) IMB_metadata_change_field(ibuf, "Date",        stamp_data.date);
1764         if (stamp_data.marker[0]) IMB_metadata_change_field(ibuf, "Marker",    stamp_data.marker);
1765         if (stamp_data.time[0]) IMB_metadata_change_field(ibuf, "Time",        stamp_data.time);
1766         if (stamp_data.frame[0]) IMB_metadata_change_field(ibuf, "Frame",      stamp_data.frame);
1767         if (stamp_data.camera[0]) IMB_metadata_change_field(ibuf, "Camera",    stamp_data.camera);
1768         if (stamp_data.cameralens[0]) IMB_metadata_change_field(ibuf, "Lens",  stamp_data.cameralens);
1769         if (stamp_data.scene[0]) IMB_metadata_change_field(ibuf, "Scene",      stamp_data.scene);
1770         if (stamp_data.strip[0]) IMB_metadata_change_field(ibuf, "Strip",      stamp_data.strip);
1771         if (stamp_data.rendertime[0]) IMB_metadata_change_field(ibuf, "RenderTime", stamp_data.rendertime);
1772 }
1773
1774 int BKE_imbuf_alpha_test(ImBuf *ibuf)
1775 {
1776         int tot;
1777         if (ibuf->rect_float) {
1778                 float *buf = ibuf->rect_float;
1779                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1780                         if (buf[3] < 1.0f) {
1781                                 return TRUE;
1782                         }
1783                 }
1784         }
1785         else if (ibuf->rect) {
1786                 unsigned char *buf = (unsigned char *)ibuf->rect;
1787                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1788                         if (buf[3] != 255) {
1789                                 return TRUE;
1790                         }
1791                 }
1792         }
1793
1794         return FALSE;
1795 }
1796
1797 /* note: imf->planes is ignored here, its assumed the image channels
1798  * are already set */
1799 int BKE_imbuf_write(ImBuf *ibuf, const char *name, ImageFormatData *imf)
1800 {
1801         char imtype = imf->imtype;
1802         char compress = imf->compress;
1803         char quality = imf->quality;
1804
1805         int ok;
1806
1807         if (imtype == R_IMF_IMTYPE_IRIS) {
1808                 ibuf->ftype = IMAGIC;
1809         }
1810 #ifdef WITH_HDR
1811         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1812                 ibuf->ftype = RADHDR;
1813         }
1814 #endif
1815         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1816                 ibuf->ftype = PNG;
1817
1818                 if (imtype == R_IMF_IMTYPE_PNG)
1819                         ibuf->ftype |= compress;
1820
1821         }
1822 #ifdef WITH_DDS
1823         else if (imtype == R_IMF_IMTYPE_DDS) {
1824                 ibuf->ftype = DDS;
1825         }
1826 #endif
1827         else if (imtype == R_IMF_IMTYPE_BMP) {
1828                 ibuf->ftype = BMP;
1829         }
1830 #ifdef WITH_TIFF
1831         else if (imtype == R_IMF_IMTYPE_TIFF) {
1832                 ibuf->ftype = TIF;
1833
1834                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1835                         ibuf->ftype |= TIF_16BIT;
1836         }
1837 #endif
1838 #ifdef WITH_OPENEXR
1839         else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER) {
1840                 ibuf->ftype = OPENEXR;
1841                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1842                         ibuf->ftype |= OPENEXR_HALF;
1843                 ibuf->ftype |= (imf->exr_codec & OPENEXR_COMPRESS);
1844
1845                 if (!(imf->flag & R_IMF_FLAG_ZBUF))
1846                         ibuf->zbuf_float = NULL;    /* signal for exr saving */
1847
1848         }
1849 #endif
1850 #ifdef WITH_CINEON
1851         else if (imtype == R_IMF_IMTYPE_CINEON) {
1852                 ibuf->ftype = CINEON;
1853                 if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
1854                         ibuf->ftype |= CINEON_LOG;
1855                 }
1856                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1857                         ibuf->ftype |= CINEON_16BIT;
1858                 }
1859                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1860                         ibuf->ftype |= CINEON_12BIT;
1861                 }
1862                 else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
1863                         ibuf->ftype |= CINEON_10BIT;
1864                 }
1865         }
1866         else if (imtype == R_IMF_IMTYPE_DPX) {
1867                 ibuf->ftype = DPX;
1868                 if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
1869                   ibuf->ftype |= CINEON_LOG;
1870                 }
1871                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1872                         ibuf->ftype |= CINEON_16BIT;
1873                 }
1874                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1875                         ibuf->ftype |= CINEON_12BIT;
1876                 }
1877                 else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
1878                         ibuf->ftype |= CINEON_10BIT;
1879                 }
1880         }
1881 #endif
1882         else if (imtype == R_IMF_IMTYPE_TARGA) {
1883                 ibuf->ftype = TGA;
1884         }
1885         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
1886                 ibuf->ftype = RAWTGA;
1887         }
1888 #ifdef WITH_OPENJPEG
1889         else if (imtype == R_IMF_IMTYPE_JP2) {
1890                 if (quality < 10) quality = 90;
1891                 ibuf->ftype = JP2 | quality;
1892
1893                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1894                         ibuf->ftype |= JP2_16BIT;
1895                 }
1896                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1897                         ibuf->ftype |= JP2_12BIT;
1898                 }
1899
1900                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
1901                         ibuf->ftype |= JP2_YCC;
1902                 }
1903
1904                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
1905                         ibuf->ftype |= JP2_CINE;
1906                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
1907                                 ibuf->ftype |= JP2_CINE_48FPS;
1908                 }
1909         }
1910 #endif
1911         else {
1912                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
1913                 if (quality < 10) quality = 90;
1914                 ibuf->ftype = JPG | quality;
1915         }
1916
1917         BLI_make_existing_file(name);
1918
1919         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1920         if (ok == 0) {
1921                 perror(name);
1922         }
1923
1924         return(ok);
1925 }
1926
1927 /* same as BKE_imbuf_write() but crappy workaround not to perminantly modify
1928  * _some_, values in the imbuf */
1929 int BKE_imbuf_write_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
1930                        const short save_copy)
1931 {
1932         ImBuf ibuf_back = *ibuf;
1933         int ok;
1934
1935         /* all data is rgba anyway,
1936          * this just controls how to save for some formats */
1937         ibuf->planes = imf->planes;
1938
1939         ok = BKE_imbuf_write(ibuf, name, imf);
1940
1941         if (save_copy) {
1942                 /* note that we are not restoring _all_ settings */
1943                 ibuf->planes = ibuf_back.planes;
1944                 ibuf->ftype =  ibuf_back.ftype;
1945         }
1946
1947         return ok;
1948 }
1949
1950 int BKE_imbuf_write_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, struct ImageFormatData *imf)
1951 {
1952         if (scene && scene->r.stamp & R_STAMP_ALL)
1953                 BKE_imbuf_stamp_info(scene, camera, ibuf);
1954
1955         return BKE_imbuf_write(ibuf, name, imf);
1956 }
1957
1958
1959 void BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, const char imtype, const short use_ext, const short use_frames)
1960 {
1961         if (string == NULL) return;
1962         BLI_strncpy(string, base, FILE_MAX - 10);   /* weak assumption */
1963         BLI_path_abs(string, relbase);
1964
1965         if (use_frames)
1966                 BLI_path_frame(string, frame, 4);
1967
1968         if (use_ext)
1969                 BKE_add_image_extension(string, imtype);
1970
1971 }
1972
1973 /* used by sequencer too */
1974 struct anim *openanim(const char *name, int flags, int streamindex, char colorspace[IMA_MAX_SPACE])
1975 {
1976         struct anim *anim;
1977         struct ImBuf *ibuf;
1978
1979         anim = IMB_open_anim(name, flags, streamindex, colorspace);
1980         if (anim == NULL) return NULL;
1981
1982         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
1983         if (ibuf == NULL) {
1984                 if (BLI_exists(name))
1985                         printf("not an anim: %s\n", name);
1986                 else
1987                         printf("anim file doesn't exist: %s\n", name);
1988                 IMB_free_anim(anim);
1989                 return NULL;
1990         }
1991         IMB_freeImBuf(ibuf);
1992
1993         return(anim);
1994 }
1995
1996 /* ************************* New Image API *************** */
1997
1998
1999 /* Notes about Image storage
2000  * - packedfile
2001  *   -> written in .blend
2002  * - filename
2003  *   -> written in .blend
2004  * - movie
2005  *   -> comes from packedfile or filename
2006  * - renderresult
2007  *   -> comes from packedfile or filename
2008  * - listbase
2009  *   -> ibufs from exrhandle
2010  * - flipbook array
2011  *   -> ibufs come from movie, temporary renderresult or sequence
2012  * - ibuf
2013  *   -> comes from packedfile or filename or generated
2014  */
2015
2016
2017 /* forces existence of 1 Image for renderout or nodes, returns Image */
2018 /* name is only for default, when making new one */
2019 Image *BKE_image_verify_viewer(int type, const char *name)
2020 {
2021         Image *ima;
2022
2023         for (ima = G.main->image.first; ima; ima = ima->id.next)
2024                 if (ima->source == IMA_SRC_VIEWER)
2025                         if (ima->type == type)
2026                                 break;
2027
2028         if (ima == NULL)
2029                 ima = image_alloc(name, IMA_SRC_VIEWER, type);
2030
2031         /* happens on reload, imagewindow cannot be image user when hidden*/
2032         if (ima->id.us == 0)
2033                 id_us_plus(&ima->id);
2034
2035         return ima;
2036 }
2037
2038 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
2039 {
2040         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2041 }
2042
2043 void BKE_image_walk_all_users(const Main *mainp, void *customdata,
2044                               void callback(Image *ima, ImageUser *iuser, void *customdata))
2045 {
2046         wmWindowManager *wm;
2047         wmWindow *win;
2048         Tex *tex;
2049
2050         /* texture users */
2051         for (tex = mainp->tex.first; tex; tex = tex->id.next) {
2052                 if (tex->type == TEX_IMAGE && tex->ima) {
2053                         if (ELEM(tex->ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
2054                                 callback(tex->ima, &tex->iuser, customdata);
2055                         }
2056                 }
2057         }
2058
2059         /* image window, compo node users */
2060         for (wm = mainp->wm.first; wm; wm = wm->id.next) { /* only 1 wm */
2061                 for (win = wm->windows.first; win; win = win->next) {
2062                         ScrArea *sa;
2063                         for (sa = win->screen->areabase.first; sa; sa = sa->next) {
2064                                 if (sa->spacetype == SPACE_VIEW3D) {
2065                                         View3D *v3d = sa->spacedata.first;
2066                                         BGpic *bgpic;
2067                                         for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
2068                                                 callback(bgpic->ima, &bgpic->iuser, customdata);
2069                                         }
2070                                 }
2071                                 else if (sa->spacetype == SPACE_IMAGE) {
2072                                         SpaceImage *sima = sa->spacedata.first;
2073                                         callback(sima->image, &sima->iuser, customdata);
2074                                 }
2075                                 else if (sa->spacetype == SPACE_NODE) {
2076                                         SpaceNode *snode = sa->spacedata.first;
2077                                         if ((snode->treetype == NTREE_COMPOSIT) && (snode->nodetree)) {
2078                                                 bNode *node;
2079                                                 for (node = snode->nodetree->nodes.first; node; node = node->next) {
2080                                                         if (node->id && node->type == CMP_NODE_IMAGE) {
2081                                                                 Image *ima = (Image *)node->id;
2082                                                                 ImageUser *iuser = node->storage;
2083                                                                 callback(ima, iuser, customdata);
2084                                                         }
2085                                                 }
2086                                         }
2087                                 }
2088                         }
2089                 }
2090         }
2091 }
2092
2093 static void image_tag_frame_recalc(Image *ima, ImageUser *iuser, void *customdata)
2094 {
2095         Image *changed_image = customdata;
2096
2097         if (ima == changed_image) {
2098                 iuser->flag |= IMA_NEED_FRAME_RECALC;
2099         }
2100 }
2101
2102 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
2103 {
2104         if (ima == NULL)
2105                 return;
2106
2107         BLI_spin_lock(&image_spin);
2108
2109         switch (signal) {
2110                 case IMA_SIGNAL_FREE:
2111                         image_free_buffers(ima);
2112                         if (iuser)
2113                                 iuser->ok = 1;
2114                         break;
2115                 case IMA_SIGNAL_SRC_CHANGE:
2116                         if (ima->type == IMA_TYPE_UV_TEST)
2117                                 if (ima->source != IMA_SRC_GENERATED)
2118                                         ima->type = IMA_TYPE_IMAGE;
2119
2120                         if (ima->source == IMA_SRC_GENERATED) {
2121                                 if (ima->gen_x == 0 || ima->gen_y == 0) {
2122                                         ImBuf *ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2123                                         if (ibuf) {
2124                                                 ima->gen_x = ibuf->x;
2125                                                 ima->gen_y = ibuf->y;
2126                                         }
2127                                 }
2128                         }
2129
2130                         /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
2131                         if (ima->type != IMA_TYPE_MULTILAYER)
2132                                 image_free_buffers(ima);
2133
2134                         ima->ok = 1;
2135                         if (iuser)
2136                                 iuser->ok = 1;
2137
2138                         BKE_image_walk_all_users(G.main, ima, image_tag_frame_recalc);
2139
2140                         break;
2141
2142                 case IMA_SIGNAL_RELOAD:
2143                         /* try to repack file */
2144                         if (ima->packedfile) {
2145                                 PackedFile *pf;
2146                                 pf = newPackedFile(NULL, ima->name, ID_BLEND_PATH(G.main, &ima->id));
2147                                 if (pf) {
2148                                         freePackedFile(ima->packedfile);
2149                                         ima->packedfile = pf;
2150                                         image_free_buffers(ima);
2151                                 }
2152                                 else {
2153                                         printf("ERROR: Image not available. Keeping packed image\n");
2154                                 }
2155                         }
2156                         else
2157                                 image_free_buffers(ima);
2158
2159                         if (iuser)
2160                                 iuser->ok = 1;
2161
2162                         break;
2163                 case IMA_SIGNAL_USER_NEW_IMAGE:
2164                         if (iuser) {
2165                                 iuser->ok = 1;
2166                                 if (ima->source == IMA_SRC_FILE || ima->source == IMA_SRC_SEQUENCE) {
2167                                         if (ima->type == IMA_TYPE_MULTILAYER) {
2168                                                 iuser->multi_index = 0;
2169                                                 iuser->layer = iuser->pass = 0;
2170                                         }
2171                                 }
2172                         }
2173                         break;
2174                 case IMA_SIGNAL_COLORMANAGE:
2175                         image_free_buffers(ima);
2176
2177                         ima->ok = 1;
2178
2179                         if (iuser)
2180                                 iuser->ok = 1;
2181
2182                         break;
2183         }
2184
2185         BLI_spin_unlock(&image_spin);
2186
2187         /* don't use notifiers because they are not 100% sure to succeeded
2188          * this also makes sure all scenes are accounted for. */
2189         {
2190                 Scene *scene;
2191                 for (scene = G.main->scene.first; scene; scene = scene->id.next) {
2192                         if (scene->nodetree) {
2193                                 nodeUpdateID(scene->nodetree, &ima->id);
2194                         }
2195                 }
2196         }
2197 }
2198
2199 /* if layer or pass changes, we need an index for the imbufs list */
2200 /* note it is called for rendered results, but it doesnt use the index! */
2201 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
2202 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
2203 {
2204         RenderLayer *rl;
2205         RenderPass *rpass = NULL;
2206
2207         if (rr == NULL)
2208                 return NULL;
2209
2210         if (iuser) {
2211                 short index = 0, rl_index = 0, rp_index;
2212
2213                 for (rl = rr->layers.first; rl; rl = rl->next, rl_index++) {
2214                         rp_index = 0;
2215                         for (rpass = rl->passes.first; rpass; rpass = rpass->next, index++, rp_index++)
2216                                 if (iuser->layer == rl_index && iuser->pass == rp_index)
2217                                         break;
2218                         if (rpass)
2219                                 break;
2220                 }
2221
2222                 if (rpass)
2223                         iuser->multi_index = index;
2224                 else
2225                         iuser->multi_index = 0;
2226         }
2227         if (rpass == NULL) {
2228                 rl = rr->layers.first;
2229                 if (rl)
2230                         rpass = rl->passes.first;
2231         }
2232
2233         return rpass;
2234 }
2235
2236 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
2237 {
2238         if (ima->rr) {
2239                 return ima->rr;
2240         }
2241         else if (ima->type == IMA_TYPE_R_RESULT) {
2242                 if (ima->render_slot == ima->last_render_slot)
2243                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
2244                 else
2245                         return ima->renders[ima->render_slot];
2246         }
2247         else
2248                 return NULL;
2249 }
2250
2251 void BKE_image_release_renderresult(Scene *scene, Image *ima)
2252 {
2253         if (ima->rr) {
2254                 /* pass */
2255         }
2256         else if (ima->type == IMA_TYPE_R_RESULT) {
2257                 if (ima->render_slot == ima->last_render_slot)
2258                         RE_ReleaseResult(RE_GetRender(scene->id.name));
2259         }
2260 }
2261
2262 void BKE_image_backup_render(Scene *scene, Image *ima)
2263 {
2264         /* called right before rendering, ima->renders contains render
2265          * result pointers for everything but the current render */
2266         Render *re = RE_GetRender(scene->id.name);
2267         int slot = ima->render_slot, last = ima->last_render_slot;
2268
2269         if (slot != last) {
2270                 if (ima->renders[slot]) {
2271                         RE_FreeRenderResult(ima->renders[slot]);
2272                         ima->renders[slot] = NULL;
2273                 }
2274
2275                 ima->renders[last] = NULL;
2276                 RE_SwapResult(re, &ima->renders[last]);
2277         }
2278
2279         ima->last_render_slot = slot;
2280 }
2281
2282 /* after imbuf load, openexr type can return with a exrhandle open */
2283 /* in that case we have to build a render-result */
2284 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
2285 {
2286         const char *colorspace = ima->colorspace_settings.name;
2287         int predivide = ima->flag & IMA_CM_PREDIVIDE;
2288
2289         ima->rr = RE_MultilayerConvert(ibuf->userdata, colorspace, predivide, ibuf->x, ibuf->y);
2290
2291 #ifdef WITH_OPENEXR
2292         IMB_exr_close(ibuf->userdata);
2293 #endif
2294
2295         ibuf->userdata = NULL;
2296         if (ima->rr)
2297                 ima->rr->framenr = framenr;
2298 }
2299
2300 /* common stuff to do with images after loading */
2301 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
2302 {
2303         /* preview is NULL when it has never been used as an icon before */
2304         if (G.background == 0 && ima->preview == NULL)
2305                 BKE_icon_changed(BKE_icon_getid(&ima->id));
2306
2307         /* fields */
2308         if (ima->flag & IMA_FIELDS) {
2309                 if (ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
2310                 else de_interlace_ng(ibuf);
2311         }
2312         /* timer */
2313         ima->lastused = clock() / CLOCKS_PER_SEC;
2314
2315         ima->ok = IMA_OK_LOADED;
2316
2317 }
2318
2319 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
2320 {
2321         struct ImBuf *ibuf;
2322         char name[FILE_MAX];
2323         int flag;
2324
2325         /* XXX temp stuff? */
2326         if (ima->lastframe != frame)
2327                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2328
2329         ima->lastframe = frame;
2330         BKE_image_user_file_path(iuser, ima, name);
2331
2332         flag = IB_rect | IB_multilayer;
2333         if (ima->flag & IMA_DO_PREMUL)
2334                 flag |= IB_premul;
2335
2336         /* read ibuf */
2337         ibuf = IMB_loadiffname(name, flag, ima->colorspace_settings.name);
2338
2339 #if 0
2340         if (ibuf) {
2341                 printf(AT " loaded %s\n", name);
2342         }
2343         else {
2344                 printf(AT " missed %s\n", name);
2345         }
2346 #endif
2347
2348         if (ibuf) {
2349 #ifdef WITH_OPENEXR
2350                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_acquire_ibuf */
2351                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2352                         image_create_multilayer(ima, ibuf, frame);
2353                         ima->type = IMA_TYPE_MULTILAYER;
2354                         IMB_freeImBuf(ibuf);
2355                         ibuf = NULL;
2356                 }
2357                 else {
2358                         image_initialize_after_load(ima, ibuf);
2359                         image_assign_ibuf(ima, ibuf, 0, frame);
2360                 }
2361 #else
2362                 image_initialize_after_load(ima, ibuf);
2363                 image_assign_ibuf(ima, ibuf, 0, frame);
2364 #endif
2365         }
2366         else
2367                 ima->ok = 0;
2368
2369         if (iuser)
2370                 iuser->ok = ima->ok;
2371
2372         return ibuf;
2373 }
2374
2375 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
2376 {
2377         struct ImBuf *ibuf = NULL;
2378
2379         /* either we load from RenderResult, or we have to load a new one */
2380
2381         /* check for new RenderResult */
2382         if (ima->rr == NULL || frame != ima->rr->framenr) {
2383                 /* copy to survive not found multilayer image */
2384                 RenderResult *oldrr = ima->rr;
2385
2386                 ima->rr = NULL;
2387                 ibuf = image_load_sequence_file(ima, iuser, frame);
2388
2389                 if (ibuf) { /* actually an error */
2390                         ima->type = IMA_TYPE_IMAGE;
2391                         printf("error, multi is normal image\n");
2392                 }
2393                 // printf("loaded new result %p\n", ima->rr);
2394                 /* free result if new one found */
2395                 if (ima->rr) {
2396                         // if (oldrr) printf("freed previous result %p\n", oldrr);
2397                         if (oldrr) RE_FreeRenderResult(oldrr);
2398                 }
2399                 else {
2400                         ima->rr = oldrr;
2401                 }
2402
2403         }
2404         if (ima->rr) {
2405                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2406
2407                 if (rpass) {
2408                         // printf("load from pass %s\n", rpass->name);
2409                         /* since we free  render results, we copy the rect */
2410                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2411                         ibuf->rect_float = MEM_dupallocN(rpass->rect);
2412                         ibuf->flags |= IB_rectfloat;
2413                         ibuf->mall = IB_rectfloat;
2414                         ibuf->channels = rpass->channels;
2415
2416                         image_initialize_after_load(ima, ibuf);
2417                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : 0, frame);
2418
2419                 }
2420                 // else printf("pass not found\n");
2421         }
2422         else
2423                 ima->ok = 0;
2424
2425         if (iuser)
2426                 iuser->ok = ima->ok;
2427
2428         return ibuf;
2429 }
2430
2431
2432 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
2433 {
2434         struct ImBuf *ibuf = NULL;
2435
2436         ima->lastframe = frame;
2437
2438         if (ima->anim == NULL) {
2439                 char str[FILE_MAX];
2440
2441                 BKE_image_user_file_path(iuser, ima, str);
2442
2443                 /* FIXME: make several stream accessible in image editor, too*/
2444                 ima->anim = openanim(str, IB_rect, 0, ima->colorspace_settings.name);
2445
2446                 /* let's initialize this user */
2447                 if (ima->anim && iuser && iuser->frames == 0)
2448                         iuser->frames = IMB_anim_get_duration(ima->anim,
2449                                                               IMB_TC_RECORD_RUN);
2450         }
2451
2452         if (ima->anim) {
2453                 int dur = IMB_anim_get_duration(ima->anim,
2454                                                 IMB_TC_RECORD_RUN);
2455                 int fra = frame - 1;
2456
2457                 if (fra < 0) fra = 0;
2458                 if (fra > (dur - 1)) fra = dur - 1;
2459                 ibuf = IMB_makeSingleUser(
2460                     IMB_anim_absolute(ima->anim, fra,
2461                                       IMB_TC_RECORD_RUN,
2462                                       IMB_PROXY_NONE));
2463
2464                 if (ibuf) {
2465                         image_initialize_after_load(ima, ibuf);
2466                         image_assign_ibuf(ima, ibuf, 0, frame);
2467                 }
2468                 else
2469                         ima->ok = 0;
2470         }
2471         else
2472                 ima->ok = 0;
2473
2474         if (iuser)
2475                 iuser->ok = ima->ok;
2476
2477         return ibuf;
2478 }
2479
2480 /* warning, 'iuser' can be NULL */
2481 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
2482 {
2483         struct ImBuf *ibuf;
2484         char str[FILE_MAX];
2485         int assign = 0, flag;
2486
2487         /* always ensure clean ima */
2488         image_free_buffers(ima);
2489
2490         /* is there a PackedFile with this image ? */
2491         if (ima->packedfile) {
2492                 flag = IB_rect | IB_multilayer;
2493                 if (ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
2494
2495                 ibuf = IMB_ibImageFromMemory((unsigned char *)ima->packedfile->data, ima->packedfile->size, flag,
2496                                              ima->colorspace_settings.name, "<packed data>");
2497         }
2498         else {
2499                 flag = IB_rect | IB_multilayer | IB_metadata;
2500                 if (ima->flag & IMA_DO_PREMUL)
2501                         flag |= IB_premul;
2502
2503                 /* get the right string */
2504                 BKE_image_user_frame_calc(iuser, cfra, 0);
2505                 BKE_image_user_file_path(iuser, ima, str);
2506
2507                 /* read ibuf */
2508                 ibuf = IMB_loadiffname(str, flag, ima->colorspace_settings.name);
2509         }
2510
2511         if (ibuf) {
2512                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_acquire_ibuf */
2513                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2514                         image_create_multilayer(ima, ibuf, cfra);
2515                         ima->type = IMA_TYPE_MULTILAYER;
2516                         IMB_freeImBuf(ibuf);
2517                         ibuf = NULL;
2518                 }
2519                 else {
2520                         image_initialize_after_load(ima, ibuf);
2521                         assign = 1;
2522
2523                         /* check if the image is a font image... */
2524                         detectBitmapFont(ibuf);
2525
2526                         /* make packed file for autopack */
2527                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
2528                                 ima->packedfile = newPackedFile(NULL, str, ID_BLEND_PATH(G.main, &ima->id));
2529                 }
2530         }
2531         else
2532                 ima->ok = 0;
2533
2534         if (assign)
2535                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2536
2537         if (iuser)
2538                 iuser->ok = ima->ok;
2539
2540         return ibuf;
2541 }
2542
2543 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
2544 {
2545         ImBuf *ibuf = NULL;
2546
2547         if (ima->rr == NULL) {
2548                 ibuf = image_load_image_file(ima, iuser, 0);
2549                 if (ibuf) { /* actually an error */
2550                         ima->type = IMA_TYPE_IMAGE;
2551                         return ibuf;
2552                 }
2553         }
2554         if (ima->rr) {
2555                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2556
2557                 if (rpass) {
2558                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2559
2560                         image_initialize_after_load(ima, ibuf);
2561
2562                         ibuf->rect_float = rpass->rect;
2563                         ibuf->flags |= IB_rectfloat;
2564                         ibuf->channels = rpass->channels;
2565
2566                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2567                 }
2568         }
2569
2570         if (ibuf == NULL)
2571                 ima->ok = 0;
2572         if (iuser)
2573                 iuser->ok = ima->ok;
2574
2575         return ibuf;
2576 }
2577
2578
2579 /* showing RGBA result itself (from compo/sequence) or
2580  * like exr, using layers etc */
2581 /* always returns a single ibuf, also during render progress */
2582 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
2583 {
2584         Render *re;
2585         RenderResult rres;
2586         float *rectf, *rectz;
2587         unsigned int *rect;
2588         float dither;
2589         int channels, layer, pass;
2590         ImBuf *ibuf;
2591         int from_render = (ima->render_slot == ima->last_render_slot);
2592
2593         if (!(iuser && iuser->scene))
2594                 return NULL;
2595
2596         /* if we the caller is not going to release the lock, don't give the image */
2597         if (!lock_r)
2598                 return NULL;
2599
2600         re = RE_GetRender(iuser->scene->id.name);
2601
2602         channels = 4;
2603         layer = (iuser) ? iuser->layer : 0;
2604         pass = (iuser) ? iuser->pass : 0;
2605
2606         if (from_render) {
2607                 RE_AcquireResultImage(re, &rres);
2608         }
2609         else if (ima->renders[ima->render_slot]) {
2610                 rres = *(ima->renders[ima->render_slot]);
2611                 rres.have_combined = rres.rectf != NULL;
2612         }
2613         else
2614                 memset(&rres, 0, sizeof(RenderResult));
2615
2616         if (!(rres.rectx > 0 && rres.recty > 0)) {
2617                 if (from_render)
2618                         RE_ReleaseResultImage(re);
2619                 return NULL;
2620         }
2621
2622         /* release is done in BKE_image_release_ibuf using lock_r */
2623         if (from_render) {
2624                 BLI_lock_thread(LOCK_VIEWER);
2625                 *lock_r = re;
2626         }
2627
2628         /* this gives active layer, composite or sequence result */
2629         rect = (unsigned int *)rres.rect32;
2630         rectf = rres.rectf;
2631         rectz = rres.rectz;
2632         dither = iuser->scene->r.dither_intensity;
2633
2634         /* combined layer gets added as first layer */
2635         if (rres.have_combined && layer == 0) {
2636                 /* pass */
2637         }
2638         else if (rres.layers.first) {
2639                 RenderLayer *rl = BLI_findlink(&rres.layers, layer - (rres.have_combined ? 1 : 0));
2640                 if (rl) {
2641                         RenderPass *rpass;
2642
2643                         /* there's no combined pass, is in renderlayer itself */
2644                         if (pass == 0) {
2645                                 rectf = rl->rectf;
2646                         }
2647                         else {
2648                                 rpass = BLI_findlink(&rl->passes, pass - 1);
2649                                 if (rpass) {
2650                                         channels = rpass->channels;
2651                                         rectf = rpass->rect;
2652                                         dither = 0.0f; /* don't dither passes */
2653                                 }
2654                         }
2655
2656                         for (rpass = rl->passes.first; rpass; rpass = rpass->next)
2657                                 if (rpass->passtype == SCE_PASS_Z)
2658                                         rectz = rpass->rect;
2659                 }
2660         }
2661
2662         ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2663
2664         /* make ibuf if needed, and initialize it */
2665         if (ibuf == NULL) {
2666                 ibuf = IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
2667                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2668         }
2669
2670         /* invalidate color managed buffers if render result changed */
2671         BLI_lock_thread(LOCK_COLORMANAGE);
2672         if (ibuf->x != rres.rectx || ibuf->y != rres.recty || ibuf->rect_float != rectf) {
2673                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
2674         }
2675
2676         ibuf->x = rres.rectx;
2677         ibuf->y = rres.recty;
2678
2679         /* free rect buffer if float buffer changes, so it can be recreated with
2680          * the updated result, and also in case we got byte buffer from sequencer,
2681          * so we don't keep reference to freed buffer */
2682         if (ibuf->rect_float != rectf || rect)
2683                 imb_freerectImBuf(ibuf);
2684
2685         if (rect) {
2686                 ibuf->rect = rect;
2687         }
2688         else {
2689                 /* byte buffer of render result has been freed, make sure image buffers
2690                  * does not reference to this buffer anymore
2691                  * need check for whether byte buffer was allocated and owned by image itself
2692                  * or if it's reusing buffer from render result
2693                  */
2694                 if ((ibuf->mall & IB_rect) == 0)
2695                         ibuf->rect = NULL;
2696         }
2697
2698         if (rectf) {
2699                 ibuf->rect_float = rectf;
2700                 ibuf->flags |= IB_rectfloat;
2701                 ibuf->channels = channels;
2702         }
2703         else {
2704                 ibuf->rect_float = NULL;
2705                 ibuf->flags &= ~IB_rectfloat;
2706         }
2707
2708         if (rectz) {
2709                 ibuf->zbuf_float = rectz;
2710                 ibuf->flags |= IB_zbuffloat;
2711         }
2712         else {
2713                 ibuf->zbuf_float = NULL;
2714                 ibuf->flags &= ~IB_zbuffloat;
2715         }
2716
2717         BLI_unlock_thread(LOCK_COLORMANAGE);
2718
2719         ibuf->dither = dither;
2720
2721         if (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT_PREDIVIDE) {
2722                 ibuf->flags |= IB_cm_predivide;
2723                 ima->flag |= IMA_CM_PREDIVIDE;
2724         }
2725         else {
2726                 ibuf->flags &= ~IB_cm_predivide;
2727                 ima->flag &= ~IMA_CM_PREDIVIDE;
2728         }
2729
2730         ima->ok = IMA_OK_LOADED;
2731
2732         return ibuf;
2733 }
2734
2735 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2736 {
2737         ImBuf *ibuf = NULL;
2738         int frame = 0, index = 0;
2739
2740         /* see if we already have an appropriate ibuf, with image source and type */
2741         if (ima->source == IMA_SRC_MOVIE) {
2742                 frame = iuser ? iuser->framenr : ima->lastframe;
2743                 ibuf = image_get_ibuf(ima, 0, frame);
2744                 /* XXX temp stuff? */
2745                 if (ima->lastframe != frame)
2746                         ima->tpageflag |= IMA_TPAGE_REFRESH;
2747                 ima->lastframe = frame;
2748         }
2749         else if (ima->source == IMA_SRC_SEQUENCE) {
2750                 if (ima->type == IMA_TYPE_IMAGE) {
2751                         frame = iuser ? iuser->framenr : ima->lastframe;
2752                         ibuf = image_get_ibuf(ima, 0, frame);
2753
2754                         /* XXX temp stuff? */
2755                         if (ima->lastframe != frame) {
2756                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2757                         }
2758                         ima->lastframe = frame;
2759                 }
2760                 else if (ima->type == IMA_TYPE_MULTILAYER) {
2761                         frame = iuser ? iuser->framenr : ima->lastframe;
2762                         index = iuser ? iuser->multi_index : IMA_NO_INDEX;
2763                         ibuf = image_get_ibuf(ima, index, frame);
2764                 }
2765         }
2766         else if (ima->source == IMA_SRC_FILE) {
2767                 if (ima->type == IMA_TYPE_IMAGE)
2768                         ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2769                 else if (ima->type == IMA_TYPE_MULTILAYER)
2770                         ibuf = image_get_ibuf(ima, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2771         }
2772         else if (ima->source == IMA_SRC_GENERATED) {
2773                 ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2774         }
2775         else if (ima->source == IMA_SRC_VIEWER) {
2776                 /* always verify entirely, not that this shouldn't happen
2777                  * as part of texture sampling in rendering anyway, so not
2778                  * a big bottleneck */
2779         }
2780
2781         if (frame_r)
2782                 *frame_r = frame;
2783
2784         if (index_r)
2785                 *index_r = index;
2786
2787         return ibuf;
2788 }
2789
2790 /* Checks optional ImageUser and verifies/creates ImBuf.
2791  *
2792  * not thread-safe, so callee should worry about thread locks
2793  */
2794 static ImBuf *image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2795 {
2796         ImBuf *ibuf = NULL;
2797         float color[] = {0, 0, 0, 1};
2798         int frame = 0, index = 0;
2799
2800         if (lock_r)
2801                 *lock_r = NULL;
2802
2803         /* quick reject tests */
2804         if (ima == NULL)
2805                 return NULL;
2806
2807         if (iuser) {
2808                 if (iuser->ok == 0)
2809                         return NULL;
2810         }
2811         else if (ima->ok == 0)
2812                 return NULL;
2813
2814         ibuf = image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2815
2816         if (ibuf == NULL) {
2817                 /* we are sure we have to load the ibuf, using source and type */
2818                 if (ima->source == IMA_SRC_MOVIE) {
2819                         /* source is from single file, use flipbook to store ibuf */
2820                         ibuf = image_load_movie_file(ima, iuser, frame);
2821                 }
2822                 else if (ima->source == IMA_SRC_SEQUENCE) {
2823                         if (ima->type == IMA_TYPE_IMAGE) {
2824                                 /* regular files, ibufs in flipbook, allows saving */
2825                                 ibuf = image_load_sequence_file(ima, iuser, frame);
2826                         }
2827                         /* no else; on load the ima type can change */
2828                         if (ima->type == IMA_TYPE_MULTILAYER) {
2829                                 /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2830                                 ibuf = image_load_sequence_multilayer(ima, iuser, frame);
2831                         }
2832                 }
2833                 else if (ima->source == IMA_SRC_FILE) {
2834
2835                         if (ima->type == IMA_TYPE_IMAGE)
2836                                 ibuf = image_load_image_file(ima, iuser, frame);  /* cfra only for '#', this global is OK */
2837                         /* no else; on load the ima type can change */
2838                         if (ima->type == IMA_TYPE_MULTILAYER)
2839                                 /* keeps render result, stores ibufs in listbase, allows saving */
2840                                 ibuf = image_get_ibuf_multilayer(ima, iuser);
2841
2842                 }
2843                 else if (ima->source == IMA_SRC_GENERATED) {
2844                         /* generated is: ibuf is allocated dynamically */
2845                         /* UV testgrid or black or solid etc */
2846                         if (ima->gen_x == 0) ima->gen_x = 1024;
2847                         if (ima->gen_y == 0) ima->gen_y = 1024;
2848                         ibuf = add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, (ima->gen_flag & IMA_GEN_FLOAT) != 0, ima->gen_type,
2849                                              color, &ima->colorspace_settings);
2850                         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2851                         ima->ok = IMA_OK_LOADED;
2852                 }
2853                 else if (ima->source == IMA_SRC_VIEWER) {
2854                         if (ima->type == IMA_TYPE_R_RESULT) {
2855                                 /* always verify entirely, and potentially
2856                                  * returns pointer to release later */
2857                                 ibuf = image_get_render_result(ima, iuser, lock_r);
2858                         }
2859                         else if (ima->type == IMA_TYPE_COMPOSITE) {
2860                                 /* requires lock/unlock, otherwise don't return image */
2861                                 if (lock_r) {
2862                                         /* unlock in BKE_image_release_ibuf */
2863                                         BLI_lock_thread(LOCK_VIEWER);
2864                                         *lock_r = ima;
2865
2866                                         /* XXX anim play for viewer nodes not yet supported */
2867                                         frame = 0; // XXX iuser?iuser->framenr:0;
2868                                         ibuf = image_get_ibuf(ima, 0, frame);
2869
2870                                         if (!ibuf) {
2871                                                 /* Composite Viewer, all handled in compositor */
2872                                                 /* fake ibuf, will be filled in compositor */
2873                                                 ibuf = IMB_allocImBuf(256, 256, 32, IB_rect);
2874                                                 image_assign_ibuf(ima, ibuf, 0, frame);
2875                                         }
2876                                 }
2877                         }
2878                 }
2879         }
2880
2881         BKE_image_tag_time(ima);
2882
2883         return ibuf;
2884 }
2885
2886 /* return image buffer for given image and user
2887  *
2888  * - will lock render result if image type is render result and lock is not NULL
2889  * - will return NULL if image type if render or composite result and lock is NULL
2890  *
2891  * references the result, BKE_image_release_ibuf should be used to de-reference
2892  */
2893 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2894 {
2895         ImBuf *ibuf;
2896
2897         BLI_spin_lock(&image_spin);
2898
2899         ibuf = image_acquire_ibuf(ima, iuser, lock_r);
2900
2901         if (ibuf)
2902                 IMB_refImBuf(ibuf);
2903
2904         BLI_spin_unlock(&image_spin);
2905
2906         return ibuf;
2907 }
2908
2909 void BKE_image_release_ibuf(Image *ima, ImBuf *ibuf, void *lock)
2910 {
2911         if (lock) {
2912                 /* for getting image during threaded render / compositing, need to release */
2913                 if (lock == ima) {
2914                         BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2915                 }
2916                 else if (lock) {
2917                         RE_ReleaseResultImage(lock); /* render result */
2918                         BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2919                 }
2920         }
2921
2922         if (ibuf) {
2923                 BLI_spin_lock(&image_spin);
2924                 IMB_freeImBuf(ibuf);
2925                 BLI_spin_unlock(&image_spin);
2926         }
2927 }
2928
2929 /* checks whether there's an image buffer for given image and user */
2930 int BKE_image_has_ibuf(Image *ima, ImageUser *iuser)
2931 {
2932         ImBuf *ibuf;
2933
2934         /* quick reject tests */
2935         if (ima == NULL)
2936                 return FALSE;
2937
2938         if (iuser) {
2939                 if (iuser->ok == 0)
2940                         return FALSE;
2941         }
2942         else if (ima->ok == 0)
2943                 return FALSE;
2944
2945         ibuf = image_get_ibuf_threadsafe(ima, iuser, NULL, NULL);
2946
2947         if (!ibuf) {
2948                 BLI_spin_lock(&image_spin);
2949
2950                 ibuf = image_get_ibuf_threadsafe(ima, iuser, NULL, NULL);
2951
2952                 if (!ibuf)
2953                         ibuf = image_acquire_ibuf(ima, iuser, NULL);
2954
2955                 BLI_spin_unlock(&image_spin);
2956         }
2957
2958         return ibuf != NULL;
2959 }
2960
2961 int BKE_image_user_frame_get(const ImageUser *iuser, int cfra, int fieldnr, short *r_is_in_range)
2962 {
2963         const int len = (iuser->fie_ima * iuser->frames) / 2;
2964
2965         if (r_is_in_range) {
2966                 *r_is_in_range = FALSE;
2967         }
2968
2969         if (len == 0) {
2970                 return 0;
2971         }
2972         else {
2973                 int framenr;
2974                 cfra = cfra - iuser->sfra + 1;
2975
2976                 /* cyclic */
2977                 if (iuser->cycl) {
2978                         cfra = ((cfra) % len);
2979                         if (cfra < 0) cfra += len;
2980                         if (cfra == 0) cfra = len;
2981
2982                         if (r_is_in_range) {
2983                                 *r_is_in_range = TRUE;
2984                         }
2985                 }
2986
2987                 if (cfra < 0) {
2988                         cfra = 0;
2989                 }
2990                 else if (cfra > len) {
2991                         cfra = len;
2992                 }
2993                 else {
2994                         if (r_is_in_range) {
2995                                 *r_is_in_range = TRUE;
2996                         }
2997                 }
2998
2999                 /* convert current frame to current field */
3000                 cfra = 2 * (cfra);
3001                 if (fieldnr) cfra++;
3002
3003                 /* transform to images space */
3004                 framenr = (cfra + iuser->fie_ima - 2) / iuser->fie_ima;
3005                 if (framenr > iuser->frames) framenr = iuser->frames;
3006
3007                 if (iuser->cycl) {
3008                         framenr = ((framenr) % len);
3009                         while (framenr < 0) framenr += len;
3010                         if (framenr == 0) framenr = len;
3011                 }
3012
3013                 /* important to apply after else we cant loop on frames 100 - 110 for eg. */
3014                 framenr += iuser->offset;
3015
3016                 return framenr;
3017         }
3018 }
3019
3020 void BKE_image_user_frame_calc(ImageUser *iuser, int cfra, int fieldnr)
3021 {
3022         if (iuser) {
3023                 short is_in_range;
3024                 const int framenr = BKE_image_user_frame_get(iuser, cfra, fieldnr, &is_in_range);
3025
3026                 if (is_in_range) {
3027                         iuser->flag |= IMA_USER_FRAME_IN_RANGE;
3028                 }
3029                 else {
3030                         iuser->flag &= ~IMA_USER_FRAME_IN_RANGE;
3031                 }
3032
3033                 /* allows image users to handle redraws */
3034                 if (iuser->flag & IMA_ANIM_ALWAYS)
3035                         if (framenr != iuser->framenr)
3036                                 iuser->flag |= IMA_ANIM_REFRESHED;
3037
3038                 iuser->framenr = framenr;
3039                 if (iuser->ok == 0) iuser->ok = 1;
3040         }
3041 }
3042
3043 void BKE_image_user_check_frame_calc(ImageUser *iuser, int cfra, int fieldnr)
3044 {
3045         if ((iuser->flag & IMA_ANIM_ALWAYS) || (iuser->flag & IMA_NEED_FRAME_RECALC)) {
3046                 BKE_image_user_frame_calc(iuser, cfra, fieldnr);
3047
3048                 iuser->flag &= ~IMA_NEED_FRAME_RECALC;
3049         }
3050 }
3051
3052 void BKE_image_user_file_path(ImageUser *iuser, Image *ima, char *filepath)
3053 {
3054         BLI_strncpy(filepath, ima->name, FILE_MAX);
3055
3056         if (ima->source == IMA_SRC_SEQUENCE) {
3057                 char head[FILE_MAX], tail[FILE_MAX];
3058                 unsigned short numlen;
3059                 int frame = iuser ? iuser->framenr : ima->lastframe;
3060
3061                 BLI_stringdec(filepath, head, tail, &numlen);
3062                 BLI_stringenc(filepath, head, tail, numlen, frame);
3063         }
3064
3065         BLI_path_abs(filepath, ID_BLEND_PATH(G.main, &ima->id));
3066 }
3067
3068 int BKE_image_has_alpha(struct Image *image)
3069 {
3070         ImBuf *ibuf;
3071         void *lock;
3072         int planes;
3073
3074         ibuf = BKE_image_acquire_ibuf(image, NULL, &lock);
3075         planes = (ibuf ? ibuf->planes : 0);
3076         BKE_image_release_ibuf(image, ibuf, lock);
3077
3078         if (planes == 32)
3079                 return 1;
3080         else
3081                 return 0;
3082 }
3083
3084 void BKE_image_get_size(Image *image, ImageUser *iuser, int *width, int *height)
3085 {
3086         ImBuf *ibuf = NULL;
3087         void *lock;
3088
3089         ibuf = BKE_image_acquire_ibuf(image, iuser, &lock);
3090
3091         if (ibuf && ibuf->x > 0 && ibuf->y > 0) {
3092                 *width = ibuf->x;
3093                 *height = ibuf->y;
3094         }
3095         else {
3096                 *width  = IMG_SIZE_FALLBACK;
3097                 *height = IMG_SIZE_FALLBACK;
3098         }
3099
3100         BKE_image_release_ibuf(image, ibuf, lock);
3101 }
3102
3103 void BKE_image_get_size_fl(Image *image, ImageUser *iuser, float size[2])
3104 {
3105         int width, height;
3106         BKE_image_get_size(image, iuser, &width, &height);
3107
3108         size[0] = (float)width;
3109         size[1] = (float)height;
3110
3111 }
3112
3113 void BKE_image_get_aspect(Image *image, float *aspx, float *aspy)
3114 {
3115         *aspx = 1.0;
3116
3117         /* x is always 1 */
3118         if (image)
3119                 *aspy = image->aspy / image->aspx;
3120         else
3121                 *aspy = 1.0f;
3122 }