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