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