A bit alternative fix for bug mentioned in rev50826
[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         else {
624                 ibuf = IMB_allocImBuf(width, height, depth, IB_rect);
625                 rect = (unsigned char *)ibuf->rect;
626
627                 if (colorspace_settings->name[0] == '\0') {
628                         const char *colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_BYTE);
629
630                         BLI_strncpy(colorspace_settings->name, colorspace, sizeof(colorspace_settings->name));
631                 }
632
633                 IMB_colormanagement_assign_rect_colorspace(ibuf, colorspace_settings->name);
634         }
635
636         BLI_strncpy(ibuf->name, name, sizeof(ibuf->name));
637         ibuf->userflags |= IB_BITMAPDIRTY;
638
639         switch (gen_type) {
640                 case IMA_GENTYPE_GRID:
641                         BKE_image_buf_fill_checker(rect, rect_float, width, height);
642                         break;
643                 case IMA_GENTYPE_GRID_COLOR:
644                         BKE_image_buf_fill_checker_color(rect, rect_float, width, height);
645                         break;
646                 default:
647                         BKE_image_buf_fill_color(rect, rect_float, width, height, color);
648         }
649
650         return ibuf;
651 }
652
653 /* adds new image block, creates ImBuf and initializes color */
654 Image *BKE_image_add_generated(unsigned int width, unsigned int height, const char *name, int depth, int floatbuf, short gen_type, float color[4])
655 {
656         /* on save, type is changed to FILE in editsima.c */
657         Image *ima = image_alloc(name, IMA_SRC_GENERATED, IMA_TYPE_UV_TEST);
658
659         if (ima) {
660                 ImBuf *ibuf;
661
662                 /* BLI_strncpy(ima->name, name, FILE_MAX); */ /* don't do this, this writes in ain invalid filepath! */
663                 ima->gen_x = width;
664                 ima->gen_y = height;
665                 ima->gen_type = gen_type;
666                 ima->gen_flag |= (floatbuf ? IMA_GEN_FLOAT : 0);
667
668                 ibuf = add_ibuf_size(width, height, ima->name, depth, floatbuf, gen_type, color, &ima->colorspace_settings);
669                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
670
671                 ima->ok = IMA_OK_LOADED;
672         }
673
674         return ima;
675 }
676
677 /* creates an image image owns the imbuf passed */
678 Image *BKE_image_add_from_imbuf(ImBuf *ibuf)
679 {
680         /* on save, type is changed to FILE in editsima.c */
681         Image *ima;
682
683         ima = image_alloc(BLI_path_basename(ibuf->name), IMA_SRC_FILE, IMA_TYPE_IMAGE);
684
685         if (ima) {
686                 BLI_strncpy(ima->name, ibuf->name, FILE_MAX);
687                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
688                 ima->ok = IMA_OK_LOADED;
689         }
690
691         return ima;
692 }
693
694 /* packs rect from memory as PNG */
695 void BKE_image_memorypack(Image *ima)
696 {
697         ImBuf *ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
698
699         if (ibuf == NULL)
700                 return;
701         if (ima->packedfile) {
702                 freePackedFile(ima->packedfile);
703                 ima->packedfile = NULL;
704         }
705
706         ibuf->ftype = PNG;
707         ibuf->planes = R_IMF_PLANES_RGBA;
708
709         IMB_saveiff(ibuf, ibuf->name, IB_rect | IB_mem);
710         if (ibuf->encodedbuffer == NULL) {
711                 printf("memory save for pack error\n");
712         }
713         else {
714                 PackedFile *pf = MEM_callocN(sizeof(*pf), "PackedFile");
715
716                 pf->data = ibuf->encodedbuffer;
717                 pf->size = ibuf->encodedsize;
718                 ima->packedfile = pf;
719                 ibuf->encodedbuffer = NULL;
720                 ibuf->encodedsize = 0;
721                 ibuf->userflags &= ~IB_BITMAPDIRTY;
722
723                 if (ima->source == IMA_SRC_GENERATED) {
724                         ima->source = IMA_SRC_FILE;
725                         ima->type = IMA_TYPE_IMAGE;
726                 }
727         }
728 }
729
730 void BKE_image_tag_time(Image *ima)
731 {
732         if (ima)
733                 ima->lastused = (int)PIL_check_seconds_timer();
734 }
735
736 #if 0
737 static void tag_all_images_time()
738 {
739         Image *ima;
740         int ctime = (int)PIL_check_seconds_timer();
741
742         ima = G.main->image.first;
743         while (ima) {
744                 if (ima->bindcode || ima->repbind || ima->ibufs.first) {
745                         ima->lastused = ctime;
746                 }
747         }
748 }
749 #endif
750
751 void free_old_images(void)
752 {
753         Image *ima;
754         static int lasttime = 0;
755         int ctime = (int)PIL_check_seconds_timer();
756
757         /*
758          * Run garbage collector once for every collecting period of time
759          * if textimeout is 0, that's the option to NOT run the collector
760          */
761         if (U.textimeout == 0 || ctime % U.texcollectrate || ctime == lasttime)
762                 return;
763
764         /* of course not! */
765         if (G.is_rendering)
766                 return;
767
768         lasttime = ctime;
769
770         ima = G.main->image.first;
771         while (ima) {
772                 if ((ima->flag & IMA_NOCOLLECT) == 0 && ctime - ima->lastused > U.textimeout) {
773                         /* If it's in GL memory, deallocate and set time tag to current time
774                          * This gives textures a "second chance" to be used before dying. */
775                         if (ima->bindcode || ima->repbind) {
776                                 GPU_free_image(ima);
777                                 ima->lastused = ctime;
778                         }
779                         /* Otherwise, just kill the buffers */
780                         else if (ima->ibufs.first) {
781                                 image_free_buffers(ima);
782                         }
783                 }
784                 ima = ima->id.next;
785         }
786 }
787
788 static uintptr_t image_mem_size(Image *ima)
789 {
790         ImBuf *ibuf, *ibufm;
791         int level;
792         uintptr_t size = 0;
793
794         size = 0;
795
796         /* viewers have memory depending on other rules, has no valid rect pointer */
797         if (ima->source == IMA_SRC_VIEWER)
798                 return 0;
799
800         for (ibuf = ima->ibufs.first; ibuf; ibuf = ibuf->next) {
801                 if (ibuf->rect) size += MEM_allocN_len(ibuf->rect);
802                 else if (ibuf->rect_float) size += MEM_allocN_len(ibuf->rect_float);
803
804                 for (level = 0; level < IB_MIPMAP_LEVELS; level++) {
805                         ibufm = ibuf->mipmap[level];
806                         if (ibufm) {
807                                 if (ibufm->rect) size += MEM_allocN_len(ibufm->rect);
808                                 else if (ibufm->rect_float) size += MEM_allocN_len(ibufm->rect_float);
809                         }
810                 }
811         }
812
813         return size;
814 }
815
816 void BKE_image_print_memlist(void)
817 {
818         Image *ima;
819         uintptr_t size, totsize = 0;
820
821         for (ima = G.main->image.first; ima; ima = ima->id.next)
822                 totsize += image_mem_size(ima);
823
824         printf("\ntotal image memory len: %.3f MB\n", (double)totsize / (double)(1024 * 1024));
825
826         for (ima = G.main->image.first; ima; ima = ima->id.next) {
827                 size = image_mem_size(ima);
828
829                 if (size)
830                         printf("%s len: %.3f MB\n", ima->id.name + 2, (double)size / (double)(1024 * 1024));
831         }
832 }
833
834 void BKE_image_free_all_textures(void)
835 {
836         Tex *tex;
837         Image *ima;
838         /* unsigned int totsize = 0; */
839
840         for (ima = G.main->image.first; ima; ima = ima->id.next)
841                 ima->id.flag &= ~LIB_DOIT;
842
843         for (tex = G.main->tex.first; tex; tex = tex->id.next)
844                 if (tex->ima)
845                         tex->ima->id.flag |= LIB_DOIT;
846
847         for (ima = G.main->image.first; ima; ima = ima->id.next) {
848                 if (ima->ibufs.first && (ima->id.flag & LIB_DOIT)) {
849                         ImBuf *ibuf;
850
851                         for (ibuf = ima->ibufs.first; ibuf; ibuf = ibuf->next) {
852                                 /* escape when image is painted on */
853                                 if (ibuf->userflags & IB_BITMAPDIRTY)
854                                         break;
855
856 #if 0
857                                 if (ibuf->mipmap[0])
858                                         totsize += 1.33 * ibuf->x * ibuf->y * 4;
859                                 else
860                                         totsize += ibuf->x * ibuf->y * 4;
861 #endif
862                         }
863                         if (ibuf == NULL)
864                                 image_free_buffers(ima);
865                 }
866         }
867         /* printf("freed total %d MB\n", totsize/(1024*1024)); */
868 }
869
870 /* except_frame is weak, only works for seqs without offset... */
871 void BKE_image_free_anim_ibufs(Image *ima, int except_frame)
872 {
873         ImBuf *ibuf, *nbuf;
874
875         for (ibuf = ima->ibufs.first; ibuf; ibuf = nbuf) {
876                 nbuf = ibuf->next;
877                 if (ibuf->userflags & IB_BITMAPDIRTY)
878                         continue;
879                 if (ibuf->index == IMA_NO_INDEX)
880                         continue;
881                 if (except_frame != IMA_INDEX_FRAME(ibuf->index)) {
882                         BLI_remlink(&ima->ibufs, ibuf);
883
884                         if (ibuf->userdata) {
885                                 MEM_freeN(ibuf->userdata);
886                                 ibuf->userdata = NULL;
887                         }
888                         IMB_freeImBuf(ibuf);
889                 }
890         }
891 }
892
893 void BKE_image_all_free_anim_ibufs(int cfra)
894 {
895         Image *ima;
896
897         for (ima = G.main->image.first; ima; ima = ima->id.next)
898                 if (ELEM(ima->source, IMA_SRC_SEQUENCE, IMA_SRC_MOVIE))
899                         BKE_image_free_anim_ibufs(ima, cfra);
900 }
901
902
903 /* *********** READ AND WRITE ************** */
904
905 int BKE_imtype_to_ftype(const char imtype)
906 {
907         if (imtype == R_IMF_IMTYPE_TARGA)
908                 return TGA;
909         else if (imtype == R_IMF_IMTYPE_RAWTGA)
910                 return RAWTGA;
911         else if (imtype == R_IMF_IMTYPE_IRIS)
912                 return IMAGIC;
913 #ifdef WITH_HDR
914         else if (imtype == R_IMF_IMTYPE_RADHDR)
915                 return RADHDR;
916 #endif
917         else if (imtype == R_IMF_IMTYPE_PNG)
918                 return PNG;
919 #ifdef WITH_DDS
920         else if (imtype == R_IMF_IMTYPE_DDS)
921                 return DDS;
922 #endif
923         else if (imtype == R_IMF_IMTYPE_BMP)
924                 return BMP;
925 #ifdef WITH_TIFF
926         else if (imtype == R_IMF_IMTYPE_TIFF)
927                 return TIF;
928 #endif
929         else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER)
930                 return OPENEXR;
931 #ifdef WITH_CINEON
932         else if (imtype == R_IMF_IMTYPE_CINEON)
933                 return CINEON;
934         else if (imtype == R_IMF_IMTYPE_DPX)
935                 return DPX;
936 #endif
937 #ifdef WITH_OPENJPEG
938         else if (imtype == R_IMF_IMTYPE_JP2)
939                 return JP2;
940 #endif
941         else
942                 return JPG | 90;
943 }
944
945 char BKE_ftype_to_imtype(const int ftype)
946 {
947         if (ftype == 0)
948                 return R_IMF_IMTYPE_TARGA;
949         else if (ftype == IMAGIC)
950                 return R_IMF_IMTYPE_IRIS;
951 #ifdef WITH_HDR
952         else if (ftype & RADHDR)
953                 return R_IMF_IMTYPE_RADHDR;
954 #endif
955         else if (ftype & PNG)
956                 return R_IMF_IMTYPE_PNG;
957 #ifdef WITH_DDS
958         else if (ftype & DDS)
959                 return R_IMF_IMTYPE_DDS;
960 #endif
961         else if (ftype & BMP)
962                 return R_IMF_IMTYPE_BMP;
963 #ifdef WITH_TIFF
964         else if (ftype & TIF)
965                 return R_IMF_IMTYPE_TIFF;
966 #endif
967         else if (ftype & OPENEXR)
968                 return R_IMF_IMTYPE_OPENEXR;
969 #ifdef WITH_CINEON
970         else if (ftype & CINEON)
971                 return R_IMF_IMTYPE_CINEON;
972         else if (ftype & DPX)
973                 return R_IMF_IMTYPE_DPX;
974 #endif
975         else if (ftype & TGA)
976                 return R_IMF_IMTYPE_TARGA;
977         else if (ftype & RAWTGA)
978                 return R_IMF_IMTYPE_RAWTGA;
979 #ifdef WITH_OPENJPEG
980         else if (ftype & JP2)
981                 return R_IMF_IMTYPE_JP2;
982 #endif
983         else
984                 return R_IMF_IMTYPE_JPEG90;
985 }
986
987
988 int BKE_imtype_is_movie(const char imtype)
989 {
990         switch (imtype) {
991                 case R_IMF_IMTYPE_AVIRAW:
992                 case R_IMF_IMTYPE_AVIJPEG:
993                 case R_IMF_IMTYPE_QUICKTIME:
994                 case R_IMF_IMTYPE_FFMPEG:
995                 case R_IMF_IMTYPE_H264:
996                 case R_IMF_IMTYPE_THEORA:
997                 case R_IMF_IMTYPE_XVID:
998                 case R_IMF_IMTYPE_FRAMESERVER:
999                         return 1;
1000         }
1001         return 0;
1002 }
1003
1004 int BKE_imtype_supports_zbuf(const char imtype)
1005 {
1006         switch (imtype) {
1007                 case R_IMF_IMTYPE_IRIZ:
1008                 case R_IMF_IMTYPE_OPENEXR: /* but not R_IMF_IMTYPE_MULTILAYER */
1009                         return 1;
1010         }
1011         return 0;
1012 }
1013
1014 int BKE_imtype_supports_compress(const char imtype)
1015 {
1016         switch (imtype) {
1017                 case R_IMF_IMTYPE_PNG:
1018                         return 1;
1019         }
1020         return 0;
1021 }
1022
1023 int BKE_imtype_supports_quality(const char imtype)
1024 {
1025         switch (imtype) {
1026                 case R_IMF_IMTYPE_JPEG90:
1027                 case R_IMF_IMTYPE_JP2:
1028                 case R_IMF_IMTYPE_AVIJPEG:
1029                         return 1;
1030         }
1031         return 0;
1032 }
1033
1034 int BKE_imtype_supports_float(const char imtype)
1035 {
1036         switch (imtype) {
1037                 case R_IMF_IMTYPE_CINEON:
1038                 case R_IMF_IMTYPE_DPX:
1039                 case R_IMF_IMTYPE_RADHDR:
1040                 case R_IMF_IMTYPE_OPENEXR:
1041                 case R_IMF_IMTYPE_MULTILAYER:
1042                         return TRUE;
1043         }
1044         return 0;
1045 }
1046
1047 char BKE_imtype_valid_channels(const char imtype)
1048 {
1049         char chan_flag = IMA_CHAN_FLAG_RGB; /* assume all support rgb */
1050
1051         /* alpha */
1052         switch (imtype) {
1053                 case R_IMF_IMTYPE_TARGA:
1054                 case R_IMF_IMTYPE_IRIS:
1055                 case R_IMF_IMTYPE_PNG:
1056                 /* case R_IMF_IMTYPE_BMP: */ /* read but not write */
1057                 case R_IMF_IMTYPE_RADHDR:
1058                 case R_IMF_IMTYPE_TIFF:
1059                 case R_IMF_IMTYPE_OPENEXR:
1060                 case R_IMF_IMTYPE_MULTILAYER:
1061                 case R_IMF_IMTYPE_DDS:
1062                 case R_IMF_IMTYPE_JP2:
1063                 case R_IMF_IMTYPE_QUICKTIME:
1064                         chan_flag |= IMA_CHAN_FLAG_ALPHA;
1065         }
1066
1067         /* bw */
1068         switch (imtype) {
1069                 case R_IMF_IMTYPE_PNG:
1070                 case R_IMF_IMTYPE_JPEG90:
1071                 case R_IMF_IMTYPE_TARGA:
1072                 case R_IMF_IMTYPE_RAWTGA:
1073                 case R_IMF_IMTYPE_TIFF:
1074                 case R_IMF_IMTYPE_IRIS:
1075                         chan_flag |= IMA_CHAN_FLAG_BW;
1076         }
1077
1078         return chan_flag;
1079 }
1080
1081 char BKE_imtype_valid_depths(const char imtype)
1082 {
1083         switch (imtype) {
1084                 case R_IMF_IMTYPE_RADHDR:
1085                         return R_IMF_CHAN_DEPTH_32;
1086                 case R_IMF_IMTYPE_TIFF:
1087                         return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_16;
1088                 case R_IMF_IMTYPE_OPENEXR:
1089                         return R_IMF_CHAN_DEPTH_16 | R_IMF_CHAN_DEPTH_32;
1090                 case R_IMF_IMTYPE_MULTILAYER:
1091                         return R_IMF_CHAN_DEPTH_32;
1092                 /* eeh, cineone does some strange 10bits per channel */
1093                 case R_IMF_IMTYPE_DPX:
1094                 case R_IMF_IMTYPE_CINEON:
1095                         return R_IMF_CHAN_DEPTH_12;
1096                 case R_IMF_IMTYPE_JP2:
1097                         return R_IMF_CHAN_DEPTH_8 | R_IMF_CHAN_DEPTH_12 | R_IMF_CHAN_DEPTH_16;
1098                 /* most formats are 8bit only */
1099                 default:
1100                         return R_IMF_CHAN_DEPTH_8;
1101         }
1102 }
1103
1104
1105 /* string is from command line --render-format arg, keep in sync with
1106  * creator.c help info */
1107 char BKE_imtype_from_arg(const char *imtype_arg)
1108 {
1109         if      (!strcmp(imtype_arg, "TGA")) return R_IMF_IMTYPE_TARGA;
1110         else if (!strcmp(imtype_arg, "IRIS")) return R_IMF_IMTYPE_IRIS;
1111 #ifdef WITH_DDS
1112         else if (!strcmp(imtype_arg, "DDS")) return R_IMF_IMTYPE_DDS;
1113 #endif
1114         else if (!strcmp(imtype_arg, "JPEG")) return R_IMF_IMTYPE_JPEG90;
1115         else if (!strcmp(imtype_arg, "IRIZ")) return R_IMF_IMTYPE_IRIZ;
1116         else if (!strcmp(imtype_arg, "RAWTGA")) return R_IMF_IMTYPE_RAWTGA;
1117         else if (!strcmp(imtype_arg, "AVIRAW")) return R_IMF_IMTYPE_AVIRAW;
1118         else if (!strcmp(imtype_arg, "AVIJPEG")) return R_IMF_IMTYPE_AVIJPEG;
1119         else if (!strcmp(imtype_arg, "PNG")) return R_IMF_IMTYPE_PNG;
1120         else if (!strcmp(imtype_arg, "QUICKTIME")) return R_IMF_IMTYPE_QUICKTIME;
1121         else if (!strcmp(imtype_arg, "BMP")) return R_IMF_IMTYPE_BMP;
1122 #ifdef WITH_HDR
1123         else if (!strcmp(imtype_arg, "HDR")) return R_IMF_IMTYPE_RADHDR;
1124 #endif
1125 #ifdef WITH_TIFF
1126         else if (!strcmp(imtype_arg, "TIFF")) return R_IMF_IMTYPE_TIFF;
1127 #endif
1128 #ifdef WITH_OPENEXR
1129         else if (!strcmp(imtype_arg, "EXR")) return R_IMF_IMTYPE_OPENEXR;
1130         else if (!strcmp(imtype_arg, "MULTILAYER")) return R_IMF_IMTYPE_MULTILAYER;
1131 #endif
1132         else if (!strcmp(imtype_arg, "MPEG")) return R_IMF_IMTYPE_FFMPEG;
1133         else if (!strcmp(imtype_arg, "FRAMESERVER")) return R_IMF_IMTYPE_FRAMESERVER;
1134 #ifdef WITH_CINEON
1135         else if (!strcmp(imtype_arg, "CINEON")) return R_IMF_IMTYPE_CINEON;
1136         else if (!strcmp(imtype_arg, "DPX")) return R_IMF_IMTYPE_DPX;
1137 #endif
1138 #ifdef WITH_OPENJPEG
1139         else if (!strcmp(imtype_arg, "JP2")) return R_IMF_IMTYPE_JP2;
1140 #endif
1141         else return R_IMF_IMTYPE_INVALID;
1142 }
1143
1144 int BKE_add_image_extension(char *string, const char imtype)
1145 {
1146         const char *extension = NULL;
1147
1148         if (imtype == R_IMF_IMTYPE_IRIS) {
1149                 if (!BLI_testextensie(string, ".rgb"))
1150                         extension = ".rgb";
1151         }
1152         else if (imtype == R_IMF_IMTYPE_IRIZ) {
1153                 if (!BLI_testextensie(string, ".rgb"))
1154                         extension = ".rgb";
1155         }
1156 #ifdef WITH_HDR
1157         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1158                 if (!BLI_testextensie(string, ".hdr"))
1159                         extension = ".hdr";
1160         }
1161 #endif
1162         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1163                 if (!BLI_testextensie(string, ".png"))
1164                         extension = ".png";
1165         }
1166 #ifdef WITH_DDS
1167         else if (imtype == R_IMF_IMTYPE_DDS) {
1168                 if (!BLI_testextensie(string, ".dds"))
1169                         extension = ".dds";
1170         }
1171 #endif
1172         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
1173                 if (!BLI_testextensie(string, ".tga"))
1174                         extension = ".tga";
1175         }
1176         else if (imtype == R_IMF_IMTYPE_BMP) {
1177                 if (!BLI_testextensie(string, ".bmp"))
1178                         extension = ".bmp";
1179         }
1180 #ifdef WITH_TIFF
1181         else if (imtype == R_IMF_IMTYPE_TIFF) {
1182                 if (!BLI_testextensie(string, ".tif") &&
1183                     !BLI_testextensie(string, ".tiff"))
1184                 {
1185                         extension = ".tif";
1186                 }
1187         }
1188 #endif
1189 #ifdef WITH_OPENEXR
1190         else if (ELEM(imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
1191                 if (!BLI_testextensie(string, ".exr"))
1192                         extension = ".exr";
1193         }
1194 #endif
1195 #ifdef WITH_CINEON
1196         else if (imtype == R_IMF_IMTYPE_CINEON) {
1197                 if (!BLI_testextensie(string, ".cin"))
1198                         extension = ".cin";
1199         }
1200         else if (imtype == R_IMF_IMTYPE_DPX) {
1201                 if (!BLI_testextensie(string, ".dpx"))
1202                         extension = ".dpx";
1203         }
1204 #endif
1205         else if (imtype == R_IMF_IMTYPE_TARGA) {
1206                 if (!BLI_testextensie(string, ".tga"))
1207                         extension = ".tga";
1208         }
1209 #ifdef WITH_OPENJPEG
1210         else if (imtype == R_IMF_IMTYPE_JP2) {
1211                 if (!BLI_testextensie(string, ".jp2"))
1212                         extension = ".jp2";
1213         }
1214 #endif
1215         else { //   R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90, R_IMF_IMTYPE_QUICKTIME etc
1216                 if (!(BLI_testextensie(string, ".jpg") || BLI_testextensie(string, ".jpeg")))
1217                         extension = ".jpg";
1218         }
1219
1220         if (extension) {
1221                 /* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */
1222                 /* remove any other known image extension */
1223                 if (BLI_testextensie_array(string, imb_ext_image) ||
1224                     (G.have_quicktime && BLI_testextensie_array(string, imb_ext_image_qt)))
1225                 {
1226                         return BLI_replace_extension(string, FILE_MAX, extension);
1227                 }
1228                 else {
1229                         return BLI_ensure_extension(string, FILE_MAX, extension);
1230                 }
1231
1232         }
1233         else {
1234                 return FALSE;
1235         }
1236 }
1237
1238 void BKE_imformat_defaults(ImageFormatData *im_format)
1239 {
1240         memset(im_format, 0, sizeof(*im_format));
1241         im_format->planes = R_IMF_PLANES_RGB;
1242         im_format->imtype = R_IMF_IMTYPE_PNG;
1243         im_format->quality = 90;
1244         im_format->compress = 90;
1245
1246         BKE_color_managed_display_settings_init(&im_format->display_settings);
1247         BKE_color_managed_view_settings_init(&im_format->view_settings);
1248 }
1249
1250 void BKE_imbuf_to_image_format(struct ImageFormatData *im_format, const ImBuf *imbuf)
1251 {
1252         int ftype        = imbuf->ftype & ~IB_CUSTOM_FLAGS_MASK;
1253         int custom_flags = imbuf->ftype & IB_CUSTOM_FLAGS_MASK;
1254
1255         BKE_imformat_defaults(im_format);
1256
1257         /* file type */
1258
1259         if (ftype == IMAGIC)
1260                 im_format->imtype = R_IMF_IMTYPE_IRIS;
1261
1262 #ifdef WITH_HDR
1263         else if (ftype == RADHDR)
1264                 im_format->imtype = R_IMF_IMTYPE_RADHDR;
1265 #endif
1266
1267         else if (ftype == PNG)
1268                 im_format->imtype = R_IMF_IMTYPE_PNG;
1269
1270 #ifdef WITH_DDS
1271         else if (ftype == DDS)
1272                 im_format->imtype = R_IMF_IMTYPE_DDS;
1273 #endif
1274
1275         else if (ftype == BMP)
1276                 im_format->imtype = R_IMF_IMTYPE_BMP;
1277
1278 #ifdef WITH_TIFF
1279         else if (ftype == TIF) {
1280                 im_format->imtype = R_IMF_IMTYPE_TIFF;
1281                 if (custom_flags & TIF_16BIT)
1282                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1283         }
1284 #endif
1285
1286 #ifdef WITH_OPENEXR
1287         else if (ftype == OPENEXR) {
1288                 im_format->imtype = R_IMF_IMTYPE_OPENEXR;
1289                 if (custom_flags & OPENEXR_HALF)
1290                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1291                 if (custom_flags & OPENEXR_COMPRESS)
1292                         im_format->exr_codec = R_IMF_EXR_CODEC_ZIP;  // Can't determine compression
1293                 if (imbuf->zbuf_float)
1294                         im_format->flag |= R_IMF_FLAG_ZBUF;
1295         }
1296 #endif
1297
1298 #ifdef WITH_CINEON
1299         else if (ftype == CINEON)
1300                 im_format->imtype = R_IMF_IMTYPE_CINEON;
1301         else if (ftype == DPX)
1302                 im_format->imtype = R_IMF_IMTYPE_DPX;
1303 #endif
1304
1305         else if (ftype == TGA) {
1306                 im_format->imtype = R_IMF_IMTYPE_TARGA;
1307         }
1308         else if (ftype == RAWTGA) {
1309                 im_format->imtype = R_IMF_IMTYPE_RAWTGA;
1310         }
1311
1312 #ifdef WITH_OPENJPEG
1313         else if (ftype & JP2) {
1314                 im_format->imtype = R_IMF_IMTYPE_JP2;
1315                 im_format->quality = custom_flags & ~JPG_MSK;
1316
1317                 if (ftype & JP2_16BIT)
1318                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1319                 else if (ftype & JP2_12BIT)
1320                         im_format->depth = R_IMF_CHAN_DEPTH_12;
1321
1322                 if (ftype & JP2_YCC)
1323                         im_format->jp2_flag |= R_IMF_JP2_FLAG_YCC;
1324
1325                 if (ftype & JP2_CINE) {
1326                         im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_PRESET;
1327                         if (ftype & JP2_CINE_48FPS)
1328                                 im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_48;
1329                 }
1330         }
1331 #endif
1332
1333         else {
1334                 im_format->imtype = R_IMF_IMTYPE_JPEG90;
1335                 im_format->quality = custom_flags & ~JPG_MSK;
1336         }
1337
1338         /* planes */
1339         switch (imbuf->channels) {
1340                 case 0:
1341                 case 4: im_format->planes = R_IMF_PLANES_RGBA;
1342                         break;
1343                 case 3: im_format->planes = R_IMF_PLANES_RGB;
1344                         break;
1345                 case 1: im_format->planes = R_IMF_PLANES_BW;
1346                         break;
1347                 default: im_format->planes = R_IMF_PLANES_RGB;
1348                         break;
1349         }
1350
1351 }
1352
1353 static void timecode_simple_string(char *text, size_t text_size, const int cfra, int const frs_sec)
1354 {
1355         int f = (int)(cfra % frs_sec);
1356         int s = (int)(cfra / frs_sec);
1357         int h = 0;
1358         int m = 0;
1359
1360         if (s) {
1361                 m = (int)(s / 60);
1362                 s %= 60;
1363
1364                 if (m) {
1365                         h = (int)(m / 60);
1366                         m %= 60;
1367                 }
1368         }
1369
1370         if (frs_sec < 100) {
1371                 BLI_snprintf(text, text_size, "%02d:%02d:%02d.%02d", h, m, s, f);
1372         }
1373         else {
1374                 BLI_snprintf(text, text_size, "%02d:%02d:%02d.%03d", h, m, s, f);
1375         }
1376 }
1377
1378 /* could allow access externally - 512 is for long names, 64 is for id names */
1379 typedef struct StampData {
1380         char file[512];
1381         char note[512];
1382         char date[512];
1383         char marker[512];
1384         char time[512];
1385         char frame[512];
1386         char camera[64];
1387         char cameralens[64];
1388         char scene[64];
1389         char strip[64];
1390         char rendertime[64];
1391 } StampData;
1392
1393 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix)
1394 {
1395         char text[256];
1396         struct tm *tl;
1397         time_t t;
1398
1399         if (scene->r.stamp & R_STAMP_FILENAME) {
1400                 BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), do_prefix ? "File %s" : "%s", G.relbase_valid ? G.main->name : "<untitled>");
1401         }
1402         else {
1403                 stamp_data->file[0] = '\0';
1404         }
1405
1406         if (scene->r.stamp & R_STAMP_NOTE) {
1407                 /* Never do prefix for Note */
1408                 BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", scene->r.stamp_udata);
1409         }
1410         else {
1411                 stamp_data->note[0] = '\0';
1412         }
1413
1414         if (scene->r.stamp & R_STAMP_DATE) {
1415                 t = time(NULL);
1416                 tl = localtime(&t);
1417                 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);
1418                 BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), do_prefix ? "Date %s" : "%s", text);
1419         }
1420         else {
1421                 stamp_data->date[0] = '\0';
1422         }
1423
1424         if (scene->r.stamp & R_STAMP_MARKER) {
1425                 char *name = BKE_scene_find_last_marker_name(scene, CFRA);
1426
1427                 if (name) BLI_strncpy(text, name, sizeof(text));
1428                 else BLI_strncpy(text, "<none>", sizeof(text));
1429
1430                 BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), do_prefix ? "Marker %s" : "%s", text);
1431         }
1432         else {
1433                 stamp_data->marker[0] = '\0';
1434         }
1435
1436         if (scene->r.stamp & R_STAMP_TIME) {
1437                 timecode_simple_string(text, sizeof(text), scene->r.cfra, scene->r.frs_sec);
1438                 BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), do_prefix ? "Time %s" : "%s", text);
1439         }
1440         else {
1441                 stamp_data->time[0] = '\0';
1442         }
1443
1444         if (scene->r.stamp & R_STAMP_FRAME) {
1445                 char fmtstr[32];
1446                 int digits = 1;
1447
1448                 if (scene->r.efra > 9)
1449                         digits = 1 + (int) log10(scene->r.efra);
1450
1451                 BLI_snprintf(fmtstr, sizeof(fmtstr), do_prefix ? "Frame %%0%di" : "%%0%di", digits);
1452                 BLI_snprintf(stamp_data->frame, sizeof(stamp_data->frame), fmtstr, scene->r.cfra);
1453         }
1454         else {
1455                 stamp_data->frame[0] = '\0';
1456         }
1457
1458         if (scene->r.stamp & R_STAMP_CAMERA) {
1459                 BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), do_prefix ? "Camera %s" : "%s", camera ? camera->id.name + 2 : "<none>");
1460         }
1461         else {
1462                 stamp_data->camera[0] = '\0';
1463         }
1464
1465         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1466                 if (camera && camera->type == OB_CAMERA) {
1467                         BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)camera->data)->lens);
1468                 }
1469                 else BLI_strncpy(text, "<none>", sizeof(text));
1470
1471                 BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), do_prefix ? "Lens %s" : "%s", text);
1472         }
1473         else {
1474                 stamp_data->cameralens[0] = '\0';
1475         }
1476
1477         if (scene->r.stamp & R_STAMP_SCENE) {
1478                 BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), do_prefix ? "Scene %s" : "%s", scene->id.name + 2);
1479         }
1480         else {
1481                 stamp_data->scene[0] = '\0';
1482         }
1483
1484         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1485                 Sequence *seq = BKE_sequencer_foreground_frame_get(scene, scene->r.cfra);
1486
1487                 if (seq) BLI_strncpy(text, seq->name + 2, sizeof(text));
1488                 else BLI_strncpy(text, "<none>", sizeof(text));
1489
1490                 BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), do_prefix ? "Strip %s" : "%s", text);
1491         }
1492         else {
1493                 stamp_data->strip[0] = '\0';
1494         }
1495
1496         {
1497                 Render *re = RE_GetRender(scene->id.name);
1498                 RenderStats *stats = re ? RE_GetStats(re) : NULL;
1499
1500                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1501                         BLI_timestr(stats->lastframetime, text);
1502
1503                         BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), do_prefix ? "RenderTime %s" : "%s", text);
1504                 }
1505                 else {
1506                         stamp_data->rendertime[0] = '\0';
1507                 }
1508         }
1509 }
1510
1511 void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rectf, int width, int height, int channels)
1512 {
1513         struct StampData stamp_data;
1514         float w, h, pad;
1515         int x, y, y_ofs;
1516         float h_fixed;
1517         const int mono = blf_mono_font_render; // XXX
1518         struct ColorManagedDisplay *display;
1519         const char *display_device;
1520
1521         /* this could be an argument if we want to operate on non linear float imbuf's
1522          * for now though this is only used for renders which use scene settings */
1523
1524 #define BUFF_MARGIN_X 2
1525 #define BUFF_MARGIN_Y 1
1526
1527         if (!rect && !rectf)
1528                 return;
1529
1530         display_device = scene->display_settings.display_device;
1531         display = IMB_colormanagement_display_get_named(display_device);
1532
1533         stampdata(scene, camera, &stamp_data, 1);
1534
1535         /* TODO, do_versions */
1536         if (scene->r.stamp_font_id < 8)
1537                 scene->r.stamp_font_id = 12;
1538
1539         /* set before return */
1540         BLF_size(mono, scene->r.stamp_font_id, 72);
1541
1542         BLF_buffer(mono, rectf, rect, width, height, channels, display);
1543         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1544         pad = BLF_width_max(mono);
1545
1546         /* use 'h_fixed' rather than 'h', aligns better */
1547         h_fixed = BLF_height_max(mono);
1548         y_ofs = -BLF_descender(mono);
1549
1550         x = 0;
1551         y = height;
1552
1553         if (stamp_data.file[0]) {
1554                 /* Top left corner */
1555                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h = h_fixed;
1556                 y -= h;
1557
1558                 /* also a little of space to the background. */
1559                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1560                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1561
1562                 /* and draw the text. */
1563                 BLF_position(mono, x, y + y_ofs, 0.0);
1564                 BLF_draw_buffer(mono, stamp_data.file);
1565
1566                 /* the extra pixel for background. */
1567                 y -= BUFF_MARGIN_Y * 2;
1568         }
1569
1570         /* Top left corner, below File */
1571         if (stamp_data.note[0]) {
1572                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h = h_fixed;
1573                 y -= h;
1574
1575                 /* and space for background. */
1576                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1577                                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1578
1579                 BLF_position(mono, x, y + y_ofs, 0.0);
1580                 BLF_draw_buffer(mono, stamp_data.note);
1581
1582                 /* the extra pixel for background. */
1583                 y -= BUFF_MARGIN_Y * 2;
1584         }
1585
1586         /* Top left corner, below File (or Note) */
1587         if (stamp_data.date[0]) {
1588                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h = h_fixed;
1589                 y -= h;
1590
1591                 /* and space for background. */
1592                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1593                                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1594
1595                 BLF_position(mono, x, y + y_ofs, 0.0);
1596                 BLF_draw_buffer(mono, stamp_data.date);
1597
1598                 /* the extra pixel for background. */
1599                 y -= BUFF_MARGIN_Y * 2;
1600         }
1601
1602         /* Top left corner, below File, Date or Note */
1603         if (stamp_data.rendertime[0]) {
1604                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h = h_fixed;
1605                 y -= h;
1606
1607                 /* and space for background. */
1608                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1609                                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1610
1611                 BLF_position(mono, x, y + y_ofs, 0.0);
1612                 BLF_draw_buffer(mono, stamp_data.rendertime);
1613         }
1614
1615         x = 0;
1616         y = 0;
1617
1618         /* Bottom left corner, leaving space for timing */
1619         if (stamp_data.marker[0]) {
1620                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h = h_fixed;
1621
1622                 /* extra space for background. */
1623                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp,  display,
1624                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1625
1626                 /* and pad the text. */
1627                 BLF_position(mono, x, y + y_ofs, 0.0);
1628                 BLF_draw_buffer(mono, stamp_data.marker);
1629
1630                 /* space width. */
1631                 x += w + pad;
1632         }
1633
1634         /* Left bottom corner */
1635         if (stamp_data.time[0]) {
1636                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h = h_fixed;
1637
1638                 /* extra space for background */
1639                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1640                                                   x - BUFF_MARGIN_X, y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1641
1642                 /* and pad the text. */
1643                 BLF_position(mono, x, y + y_ofs, 0.0);
1644                 BLF_draw_buffer(mono, stamp_data.time);
1645
1646                 /* space width. */
1647                 x += w + pad;
1648         }
1649
1650         if (stamp_data.frame[0]) {
1651                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h = h_fixed;
1652
1653                 /* extra space for background. */
1654                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1655                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1656
1657                 /* and pad the text. */
1658                 BLF_position(mono, x, y + y_ofs, 0.0);
1659                 BLF_draw_buffer(mono, stamp_data.frame);
1660
1661                 /* space width. */
1662                 x += w + pad;
1663         }
1664
1665         if (stamp_data.camera[0]) {
1666                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h = h_fixed;
1667
1668                 /* extra space for background. */
1669                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1670                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1671                 BLF_position(mono, x, y + y_ofs, 0.0);
1672                 BLF_draw_buffer(mono, stamp_data.camera);
1673
1674                 /* space width. */
1675                 x += w + pad;
1676         }
1677
1678         if (stamp_data.cameralens[0]) {
1679                 BLF_width_and_height(mono, stamp_data.cameralens, &w, &h); h = h_fixed;
1680
1681                 /* extra space for background. */
1682                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1683                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1684                 BLF_position(mono, x, y + y_ofs, 0.0);
1685                 BLF_draw_buffer(mono, stamp_data.cameralens);
1686         }
1687
1688         if (stamp_data.scene[0]) {
1689                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h = h_fixed;
1690
1691                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1692                 x = width - w - 2;
1693
1694                 /* extra space for background. */
1695                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1696                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1697
1698                 /* and pad the text. */
1699                 BLF_position(mono, x, y + y_ofs, 0.0);
1700                 BLF_draw_buffer(mono, stamp_data.scene);
1701         }
1702
1703         if (stamp_data.strip[0]) {
1704                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h = h_fixed;
1705
1706                 /* Top right corner, with an extra space because blenfont is too strict! */
1707                 x = width - w - pad;
1708                 y = height - h;
1709
1710                 /* extra space for background. */
1711                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1712                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1713
1714                 BLF_position(mono, x, y + y_ofs, 0.0);
1715                 BLF_draw_buffer(mono, stamp_data.strip);
1716         }
1717
1718         /* cleanup the buffer. */
1719         BLF_buffer(mono, NULL, NULL, 0, 0, 0, FALSE);
1720
1721 #undef BUFF_MARGIN_X
1722 #undef BUFF_MARGIN_Y
1723 }
1724
1725 void BKE_imbuf_stamp_info(Scene *scene, Object *camera, struct ImBuf *ibuf)
1726 {
1727         struct StampData stamp_data;
1728
1729         if (!ibuf) return;
1730
1731         /* fill all the data values, no prefix */
1732         stampdata(scene, camera, &stamp_data, 0);
1733
1734         if (stamp_data.file[0]) IMB_metadata_change_field(ibuf, "File",        stamp_data.file);
1735         if (stamp_data.note[0]) IMB_metadata_change_field(ibuf, "Note",        stamp_data.note);
1736         if (stamp_data.date[0]) IMB_metadata_change_field(ibuf, "Date",        stamp_data.date);
1737         if (stamp_data.marker[0]) IMB_metadata_change_field(ibuf, "Marker",    stamp_data.marker);
1738         if (stamp_data.time[0]) IMB_metadata_change_field(ibuf, "Time",        stamp_data.time);
1739         if (stamp_data.frame[0]) IMB_metadata_change_field(ibuf, "Frame",      stamp_data.frame);
1740         if (stamp_data.camera[0]) IMB_metadata_change_field(ibuf, "Camera",    stamp_data.camera);
1741         if (stamp_data.cameralens[0]) IMB_metadata_change_field(ibuf, "Lens",  stamp_data.cameralens);
1742         if (stamp_data.scene[0]) IMB_metadata_change_field(ibuf, "Scene",      stamp_data.scene);
1743         if (stamp_data.strip[0]) IMB_metadata_change_field(ibuf, "Strip",      stamp_data.strip);
1744         if (stamp_data.rendertime[0]) IMB_metadata_change_field(ibuf, "RenderTime", stamp_data.rendertime);
1745 }
1746
1747 int BKE_imbuf_alpha_test(ImBuf *ibuf)
1748 {
1749         int tot;
1750         if (ibuf->rect_float) {
1751                 float *buf = ibuf->rect_float;
1752                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1753                         if (buf[3] < 1.0f) {
1754                                 return TRUE;
1755                         }
1756                 }
1757         }
1758         else if (ibuf->rect) {
1759                 unsigned char *buf = (unsigned char *)ibuf->rect;
1760                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1761                         if (buf[3] != 255) {
1762                                 return TRUE;
1763                         }
1764                 }
1765         }
1766
1767         return FALSE;
1768 }
1769
1770 /* note: imf->planes is ignored here, its assumed the image channels
1771  * are already set */
1772 int BKE_imbuf_write(ImBuf *ibuf, const char *name, ImageFormatData *imf)
1773 {
1774         char imtype = imf->imtype;
1775         char compress = imf->compress;
1776         char quality = imf->quality;
1777
1778         int ok;
1779
1780         if (imtype == R_IMF_IMTYPE_IRIS) {
1781                 ibuf->ftype = IMAGIC;
1782         }
1783 #ifdef WITH_HDR
1784         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1785                 ibuf->ftype = RADHDR;
1786         }
1787 #endif
1788         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1789                 ibuf->ftype = PNG;
1790
1791                 if (imtype == R_IMF_IMTYPE_PNG)
1792                         ibuf->ftype |= compress;
1793
1794         }
1795 #ifdef WITH_DDS
1796         else if (imtype == R_IMF_IMTYPE_DDS) {
1797                 ibuf->ftype = DDS;
1798         }
1799 #endif
1800         else if (imtype == R_IMF_IMTYPE_BMP) {
1801                 ibuf->ftype = BMP;
1802         }
1803 #ifdef WITH_TIFF
1804         else if (imtype == R_IMF_IMTYPE_TIFF) {
1805                 ibuf->ftype = TIF;
1806
1807                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1808                         ibuf->ftype |= TIF_16BIT;
1809         }
1810 #endif
1811 #ifdef WITH_OPENEXR
1812         else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER) {
1813                 ibuf->ftype = OPENEXR;
1814                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1815                         ibuf->ftype |= OPENEXR_HALF;
1816                 ibuf->ftype |= (imf->exr_codec & OPENEXR_COMPRESS);
1817
1818                 if (!(imf->flag & R_IMF_FLAG_ZBUF))
1819                         ibuf->zbuf_float = NULL;    /* signal for exr saving */
1820
1821         }
1822 #endif
1823 #ifdef WITH_CINEON
1824         else if (imtype == R_IMF_IMTYPE_CINEON) {
1825                 ibuf->ftype = CINEON;
1826         }
1827         else if (imtype == R_IMF_IMTYPE_DPX) {
1828                 ibuf->ftype = DPX;
1829         }
1830 #endif
1831         else if (imtype == R_IMF_IMTYPE_TARGA) {
1832                 ibuf->ftype = TGA;
1833         }
1834         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
1835                 ibuf->ftype = RAWTGA;
1836         }
1837 #ifdef WITH_OPENJPEG
1838         else if (imtype == R_IMF_IMTYPE_JP2) {
1839                 if (quality < 10) quality = 90;
1840                 ibuf->ftype = JP2 | quality;
1841
1842                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1843                         ibuf->ftype |= JP2_16BIT;
1844                 }
1845                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1846                         ibuf->ftype |= JP2_12BIT;
1847                 }
1848
1849                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
1850                         ibuf->ftype |= JP2_YCC;
1851                 }
1852
1853                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
1854                         ibuf->ftype |= JP2_CINE;
1855                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
1856                                 ibuf->ftype |= JP2_CINE_48FPS;
1857                 }
1858         }
1859 #endif
1860         else {
1861                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
1862                 if (quality < 10) quality = 90;
1863                 ibuf->ftype = JPG | quality;
1864         }
1865
1866         BLI_make_existing_file(name);
1867
1868         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1869         if (ok == 0) {
1870                 perror(name);
1871         }
1872
1873         return(ok);
1874 }
1875
1876 /* same as BKE_imbuf_write() but crappy workaround not to perminantly modify
1877  * _some_, values in the imbuf */
1878 int BKE_imbuf_write_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
1879                        const short save_copy)
1880 {
1881         ImBuf ibuf_back = *ibuf;
1882         int ok;
1883
1884         /* all data is rgba anyway,
1885          * this just controls how to save for some formats */
1886         ibuf->planes = imf->planes;
1887
1888         ok = BKE_imbuf_write(ibuf, name, imf);
1889
1890         if (save_copy) {
1891                 /* note that we are not restoring _all_ settings */
1892                 ibuf->planes = ibuf_back.planes;
1893                 ibuf->ftype =  ibuf_back.ftype;
1894         }
1895
1896         return ok;
1897 }
1898
1899 int BKE_imbuf_write_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, struct ImageFormatData *imf)
1900 {
1901         if (scene && scene->r.stamp & R_STAMP_ALL)
1902                 BKE_imbuf_stamp_info(scene, camera, ibuf);
1903
1904         return BKE_imbuf_write(ibuf, name, imf);
1905 }
1906
1907
1908 void BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, const char imtype, const short use_ext, const short use_frames)
1909 {
1910         if (string == NULL) return;
1911         BLI_strncpy(string, base, FILE_MAX - 10);   /* weak assumption */
1912         BLI_path_abs(string, relbase);
1913
1914         if (use_frames)
1915                 BLI_path_frame(string, frame, 4);
1916
1917         if (use_ext)
1918                 BKE_add_image_extension(string, imtype);
1919
1920 }
1921
1922 /* used by sequencer too */
1923 struct anim *openanim(const char *name, int flags, int streamindex, char colorspace[IMA_MAX_SPACE])
1924 {
1925         struct anim *anim;
1926         struct ImBuf *ibuf;
1927
1928         anim = IMB_open_anim(name, flags, streamindex, colorspace);
1929         if (anim == NULL) return NULL;
1930
1931         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
1932         if (ibuf == NULL) {
1933                 if (BLI_exists(name))
1934                         printf("not an anim: %s\n", name);
1935                 else
1936                         printf("anim file doesn't exist: %s\n", name);
1937                 IMB_free_anim(anim);
1938                 return NULL;
1939         }
1940         IMB_freeImBuf(ibuf);
1941
1942         return(anim);
1943 }
1944
1945 /* ************************* New Image API *************** */
1946
1947
1948 /* Notes about Image storage
1949  * - packedfile
1950  *   -> written in .blend
1951  * - filename
1952  *   -> written in .blend
1953  * - movie
1954  *   -> comes from packedfile or filename
1955  * - renderresult
1956  *   -> comes from packedfile or filename
1957  * - listbase
1958  *   -> ibufs from exrhandle
1959  * - flipbook array
1960  *   -> ibufs come from movie, temporary renderresult or sequence
1961  * - ibuf
1962  *   -> comes from packedfile or filename or generated
1963  */
1964
1965
1966 /* forces existence of 1 Image for renderout or nodes, returns Image */
1967 /* name is only for default, when making new one */
1968 Image *BKE_image_verify_viewer(int type, const char *name)
1969 {
1970         Image *ima;
1971
1972         for (ima = G.main->image.first; ima; ima = ima->id.next)
1973                 if (ima->source == IMA_SRC_VIEWER)
1974                         if (ima->type == type)
1975                                 break;
1976
1977         if (ima == NULL)
1978                 ima = image_alloc(name, IMA_SRC_VIEWER, type);
1979
1980         /* happens on reload, imagewindow cannot be image user when hidden*/
1981         if (ima->id.us == 0)
1982                 id_us_plus(&ima->id);
1983
1984         return ima;
1985 }
1986
1987 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1988 {
1989         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1990 }
1991
1992 void BKE_image_walk_all_users(const Main *mainp, void *customdata,
1993                               void callback(Image *ima, ImageUser *iuser, void *customdata))
1994 {
1995         wmWindowManager *wm;
1996         wmWindow *win;
1997         Tex *tex;
1998
1999         /* texture users */
2000         for (tex = mainp->tex.first; tex; tex = tex->id.next) {
2001                 if (tex->type == TEX_IMAGE && tex->ima) {
2002                         if (ELEM(tex->ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
2003                                 callback(tex->ima, &tex->iuser, customdata);
2004                         }
2005                 }
2006         }
2007
2008         /* image window, compo node users */
2009         for (wm = mainp->wm.first; wm; wm = wm->id.next) { /* only 1 wm */
2010                 for (win = wm->windows.first; win; win = win->next) {
2011                         ScrArea *sa;
2012                         for (sa = win->screen->areabase.first; sa; sa = sa->next) {
2013                                 if (sa->spacetype == SPACE_VIEW3D) {
2014                                         View3D *v3d = sa->spacedata.first;
2015                                         BGpic *bgpic;
2016                                         for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
2017                                                 callback(bgpic->ima, &bgpic->iuser, customdata);
2018                                         }
2019                                 }
2020                                 else if (sa->spacetype == SPACE_IMAGE) {
2021                                         SpaceImage *sima = sa->spacedata.first;
2022                                         callback(sima->image, &sima->iuser, customdata);
2023                                 }
2024                                 else if (sa->spacetype == SPACE_NODE) {
2025                                         SpaceNode *snode = sa->spacedata.first;
2026                                         if ((snode->treetype == NTREE_COMPOSIT) && (snode->nodetree)) {
2027                                                 bNode *node;
2028                                                 for (node = snode->nodetree->nodes.first; node; node = node->next) {
2029                                                         if (node->id && node->type == CMP_NODE_IMAGE) {
2030                                                                 Image *ima = (Image *)node->id;
2031                                                                 ImageUser *iuser = node->storage;
2032                                                                 callback(ima, iuser, customdata);
2033                                                         }
2034                                                 }
2035                                         }
2036                                 }
2037                         }
2038                 }
2039         }
2040 }
2041
2042 static void image_tag_frame_recalc(Image *ima, ImageUser *iuser, void *customdata)
2043 {
2044         Image *changed_image = customdata;
2045
2046         if (ima == changed_image) {
2047                 iuser->flag |= IMA_NEED_FRAME_RECALC;
2048         }
2049 }
2050
2051 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
2052 {
2053         if (ima == NULL)
2054                 return;
2055
2056         switch (signal) {
2057                 case IMA_SIGNAL_FREE:
2058                         image_free_buffers(ima);
2059                         if (iuser)
2060                                 iuser->ok = 1;
2061                         break;
2062                 case IMA_SIGNAL_SRC_CHANGE:
2063                         if (ima->type == IMA_TYPE_UV_TEST)
2064                                 if (ima->source != IMA_SRC_GENERATED)
2065                                         ima->type = IMA_TYPE_IMAGE;
2066
2067                         if (ima->source == IMA_SRC_GENERATED) {
2068                                 if (ima->gen_x == 0 || ima->gen_y == 0) {
2069                                         ImBuf *ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2070                                         if (ibuf) {
2071                                                 ima->gen_x = ibuf->x;
2072                                                 ima->gen_y = ibuf->y;
2073                                         }
2074                                 }
2075                         }
2076
2077                         /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
2078                         if (ima->type != IMA_TYPE_MULTILAYER)
2079                                 image_free_buffers(ima);
2080
2081                         ima->ok = 1;
2082                         if (iuser)
2083                                 iuser->ok = 1;
2084
2085                         BKE_image_walk_all_users(G.main, ima, image_tag_frame_recalc);
2086
2087                         break;
2088
2089                 case IMA_SIGNAL_RELOAD:
2090                         /* try to repack file */
2091                         if (ima->packedfile) {
2092                                 PackedFile *pf;
2093                                 pf = newPackedFile(NULL, ima->name, ID_BLEND_PATH(G.main, &ima->id));
2094                                 if (pf) {
2095                                         freePackedFile(ima->packedfile);
2096                                         ima->packedfile = pf;
2097                                         image_free_buffers(ima);
2098                                 }
2099                                 else {
2100                                         printf("ERROR: Image not available. Keeping packed image\n");
2101                                 }
2102                         }
2103                         else
2104                                 image_free_buffers(ima);
2105
2106                         if (iuser)
2107                                 iuser->ok = 1;
2108
2109                         break;
2110                 case IMA_SIGNAL_USER_NEW_IMAGE:
2111                         if (iuser) {
2112                                 iuser->ok = 1;
2113                                 if (ima->source == IMA_SRC_FILE || ima->source == IMA_SRC_SEQUENCE) {
2114                                         if (ima->type == IMA_TYPE_MULTILAYER) {
2115                                                 iuser->multi_index = 0;
2116                                                 iuser->layer = iuser->pass = 0;
2117                                         }
2118                                 }
2119                         }
2120                         break;
2121         }
2122
2123         /* don't use notifiers because they are not 100% sure to succeeded
2124          * this also makes sure all scenes are accounted for. */
2125         {
2126                 Scene *scene;
2127                 for (scene = G.main->scene.first; scene; scene = scene->id.next) {
2128                         if (scene->nodetree) {
2129                                 nodeUpdateID(scene->nodetree, &ima->id);
2130                         }
2131                 }
2132         }
2133 }
2134
2135 /* if layer or pass changes, we need an index for the imbufs list */
2136 /* note it is called for rendered results, but it doesnt use the index! */
2137 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
2138 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
2139 {
2140         RenderLayer *rl;
2141         RenderPass *rpass = NULL;
2142
2143         if (rr == NULL)
2144                 return NULL;
2145
2146         if (iuser) {
2147                 short index = 0, rl_index = 0, rp_index;
2148
2149                 for (rl = rr->layers.first; rl; rl = rl->next, rl_index++) {
2150                         rp_index = 0;
2151                         for (rpass = rl->passes.first; rpass; rpass = rpass->next, index++, rp_index++)
2152                                 if (iuser->layer == rl_index && iuser->pass == rp_index)
2153                                         break;
2154                         if (rpass)
2155                                 break;
2156                 }
2157
2158                 if (rpass)
2159                         iuser->multi_index = index;
2160                 else
2161                         iuser->multi_index = 0;
2162         }
2163         if (rpass == NULL) {
2164                 rl = rr->layers.first;
2165                 if (rl)
2166                         rpass = rl->passes.first;
2167         }
2168
2169         return rpass;
2170 }
2171
2172 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
2173 {
2174         if (ima->rr) {
2175                 return ima->rr;
2176         }
2177         else if (ima->type == IMA_TYPE_R_RESULT) {
2178                 if (ima->render_slot == ima->last_render_slot)
2179                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
2180                 else
2181                         return ima->renders[ima->render_slot];
2182         }
2183         else
2184                 return NULL;
2185 }
2186
2187 void BKE_image_release_renderresult(Scene *scene, Image *ima)
2188 {
2189         if (ima->rr) {
2190                 /* pass */
2191         }
2192         else if (ima->type == IMA_TYPE_R_RESULT) {
2193                 if (ima->render_slot == ima->last_render_slot)
2194                         RE_ReleaseResult(RE_GetRender(scene->id.name));
2195         }
2196 }
2197
2198 void BKE_image_backup_render(Scene *scene, Image *ima)
2199 {
2200         /* called right before rendering, ima->renders contains render
2201          * result pointers for everything but the current render */
2202         Render *re = RE_GetRender(scene->id.name);
2203         int slot = ima->render_slot, last = ima->last_render_slot;
2204
2205         if (slot != last) {
2206                 if (ima->renders[slot]) {
2207                         RE_FreeRenderResult(ima->renders[slot]);
2208                         ima->renders[slot] = NULL;
2209                 }
2210
2211                 ima->renders[last] = NULL;
2212                 RE_SwapResult(re, &ima->renders[last]);
2213         }
2214
2215         ima->last_render_slot = slot;
2216 }
2217
2218 /* after imbuf load, openexr type can return with a exrhandle open */
2219 /* in that case we have to build a render-result */
2220 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
2221 {
2222         const char *colorspace = ima->colorspace_settings.name;
2223         int predivide = ima->flag & IMA_CM_PREDIVIDE;
2224
2225         ima->rr = RE_MultilayerConvert(ibuf->userdata, colorspace, predivide, ibuf->x, ibuf->y);
2226
2227 #ifdef WITH_OPENEXR
2228         IMB_exr_close(ibuf->userdata);
2229 #endif
2230
2231         ibuf->userdata = NULL;
2232         if (ima->rr)
2233                 ima->rr->framenr = framenr;
2234 }
2235
2236 /* common stuff to do with images after loading */
2237 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
2238 {
2239         /* preview is NULL when it has never been used as an icon before */
2240         if (G.background == 0 && ima->preview == NULL)
2241                 BKE_icon_changed(BKE_icon_getid(&ima->id));
2242
2243         /* fields */
2244         if (ima->flag & IMA_FIELDS) {
2245                 if (ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
2246                 else de_interlace_ng(ibuf);
2247         }
2248         /* timer */
2249         ima->lastused = clock() / CLOCKS_PER_SEC;
2250
2251         ima->ok = IMA_OK_LOADED;
2252
2253 }
2254
2255 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
2256 {
2257         struct ImBuf *ibuf;
2258         char name[FILE_MAX];
2259         int flag;
2260
2261         /* XXX temp stuff? */
2262         if (ima->lastframe != frame)
2263                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2264
2265         ima->lastframe = frame;
2266         BKE_image_user_file_path(iuser, ima, name);
2267
2268         flag = IB_rect | IB_multilayer;
2269         if (ima->flag & IMA_DO_PREMUL)
2270                 flag |= IB_premul;
2271
2272         /* read ibuf */
2273         ibuf = IMB_loadiffname(name, flag, ima->colorspace_settings.name);
2274
2275 #if 0
2276         if (ibuf) {
2277                 printf(AT " loaded %s\n", name);
2278         }
2279         else {
2280                 printf(AT " missed %s\n", name);
2281         }
2282 #endif
2283
2284         if (ibuf) {
2285 #ifdef WITH_OPENEXR
2286                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2287                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2288                         image_create_multilayer(ima, ibuf, frame);
2289                         ima->type = IMA_TYPE_MULTILAYER;
2290                         IMB_freeImBuf(ibuf);
2291                         ibuf = NULL;
2292                 }
2293                 else {
2294                         image_initialize_after_load(ima, ibuf);
2295                         image_assign_ibuf(ima, ibuf, 0, frame);
2296                 }
2297 #else
2298                 image_initialize_after_load(ima, ibuf);
2299                 image_assign_ibuf(ima, ibuf, 0, frame);
2300 #endif
2301         }
2302         else
2303                 ima->ok = 0;
2304
2305         if (iuser)
2306                 iuser->ok = ima->ok;
2307
2308         return ibuf;
2309 }
2310
2311 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
2312 {
2313         struct ImBuf *ibuf = NULL;
2314
2315         /* either we load from RenderResult, or we have to load a new one */
2316
2317         /* check for new RenderResult */
2318         if (ima->rr == NULL || frame != ima->rr->framenr) {
2319                 /* copy to survive not found multilayer image */
2320                 RenderResult *oldrr = ima->rr;
2321
2322                 ima->rr = NULL;
2323                 ibuf = image_load_sequence_file(ima, iuser, frame);
2324
2325                 if (ibuf) { /* actually an error */
2326                         ima->type = IMA_TYPE_IMAGE;
2327                         printf("error, multi is normal image\n");
2328                 }
2329                 // printf("loaded new result %p\n", ima->rr);
2330                 /* free result if new one found */
2331                 if (ima->rr) {
2332                         // if (oldrr) printf("freed previous result %p\n", oldrr);
2333                         if (oldrr) RE_FreeRenderResult(oldrr);
2334                 }
2335                 else {
2336                         ima->rr = oldrr;
2337                 }
2338
2339         }
2340         if (ima->rr) {
2341                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2342
2343                 if (rpass) {
2344                         // printf("load from pass %s\n", rpass->name);
2345                         /* since we free  render results, we copy the rect */
2346                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2347                         ibuf->rect_float = MEM_dupallocN(rpass->rect);
2348                         ibuf->flags |= IB_rectfloat;
2349                         ibuf->mall = IB_rectfloat;
2350                         ibuf->channels = rpass->channels;
2351
2352                         image_initialize_after_load(ima, ibuf);
2353                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : 0, frame);
2354
2355                 }
2356                 // else printf("pass not found\n");
2357         }
2358         else
2359                 ima->ok = 0;
2360
2361         if (iuser)
2362                 iuser->ok = ima->ok;
2363
2364         return ibuf;
2365 }
2366
2367
2368 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
2369 {
2370         struct ImBuf *ibuf = NULL;
2371
2372         ima->lastframe = frame;
2373
2374         if (ima->anim == NULL) {
2375                 char str[FILE_MAX];
2376
2377                 BKE_image_user_file_path(iuser, ima, str);
2378
2379                 /* FIXME: make several stream accessible in image editor, too*/
2380                 ima->anim = openanim(str, IB_rect, 0, ima->colorspace_settings.name);
2381
2382                 /* let's initialize this user */
2383                 if (ima->anim && iuser && iuser->frames == 0)
2384                         iuser->frames = IMB_anim_get_duration(ima->anim,
2385                                                               IMB_TC_RECORD_RUN);
2386         }
2387
2388         if (ima->anim) {
2389                 int dur = IMB_anim_get_duration(ima->anim,
2390                                                 IMB_TC_RECORD_RUN);
2391                 int fra = frame - 1;
2392
2393                 if (fra < 0) fra = 0;
2394                 if (fra > (dur - 1)) fra = dur - 1;
2395                 ibuf = IMB_makeSingleUser(
2396                     IMB_anim_absolute(ima->anim, fra,
2397                                       IMB_TC_RECORD_RUN,
2398                                       IMB_PROXY_NONE));
2399
2400                 if (ibuf) {
2401                         image_initialize_after_load(ima, ibuf);
2402                         image_assign_ibuf(ima, ibuf, 0, frame);
2403                 }
2404                 else
2405                         ima->ok = 0;
2406         }
2407         else
2408                 ima->ok = 0;
2409
2410         if (iuser)
2411                 iuser->ok = ima->ok;
2412
2413         return ibuf;
2414 }
2415
2416 /* warning, 'iuser' can be NULL */
2417 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
2418 {
2419         struct ImBuf *ibuf;
2420         char str[FILE_MAX];
2421         int assign = 0, flag;
2422
2423         /* always ensure clean ima */
2424         image_free_buffers(ima);
2425
2426         /* is there a PackedFile with this image ? */
2427         if (ima->packedfile) {
2428                 flag = IB_rect | IB_multilayer;
2429                 if (ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
2430
2431                 ibuf = IMB_ibImageFromMemory((unsigned char *)ima->packedfile->data, ima->packedfile->size, flag,
2432                                              ima->colorspace_settings.name, "<packed data>");
2433         }
2434         else {
2435                 flag = IB_rect | IB_multilayer | IB_metadata;
2436                 if (ima->flag & IMA_DO_PREMUL)
2437                         flag |= IB_premul;
2438
2439                 /* get the right string */
2440                 BKE_image_user_frame_calc(iuser, cfra, 0);
2441                 BKE_image_user_file_path(iuser, ima, str);
2442
2443                 /* read ibuf */
2444                 ibuf = IMB_loadiffname(str, flag, ima->colorspace_settings.name);
2445         }
2446
2447         if (ibuf) {
2448                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2449                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2450                         image_create_multilayer(ima, ibuf, cfra);
2451                         ima->type = IMA_TYPE_MULTILAYER;
2452                         IMB_freeImBuf(ibuf);
2453                         ibuf = NULL;
2454                 }
2455                 else {
2456                         image_initialize_after_load(ima, ibuf);
2457                         assign = 1;
2458
2459                         /* check if the image is a font image... */
2460                         detectBitmapFont(ibuf);
2461
2462                         /* make packed file for autopack */
2463                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
2464                                 ima->packedfile = newPackedFile(NULL, str, ID_BLEND_PATH(G.main, &ima->id));
2465                 }
2466         }
2467         else
2468                 ima->ok = 0;
2469
2470         if (assign)
2471                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2472
2473         if (iuser)
2474                 iuser->ok = ima->ok;
2475
2476         return ibuf;
2477 }
2478
2479 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
2480 {
2481         ImBuf *ibuf = NULL;
2482
2483         if (ima->rr == NULL) {
2484                 ibuf = image_load_image_file(ima, iuser, 0);
2485                 if (ibuf) { /* actually an error */
2486                         ima->type = IMA_TYPE_IMAGE;
2487                         return ibuf;
2488                 }
2489         }
2490         if (ima->rr) {
2491                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2492
2493                 if (rpass) {
2494                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2495
2496                         image_initialize_after_load(ima, ibuf);
2497
2498                         ibuf->rect_float = rpass->rect;
2499                         ibuf->flags |= IB_rectfloat;
2500                         ibuf->channels = rpass->channels;
2501
2502                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2503                 }
2504         }
2505
2506         if (ibuf == NULL)
2507                 ima->ok = 0;
2508         if (iuser)
2509                 iuser->ok = ima->ok;
2510
2511         return ibuf;
2512 }
2513
2514
2515 /* showing RGBA result itself (from compo/sequence) or
2516  * like exr, using layers etc */
2517 /* always returns a single ibuf, also during render progress */
2518 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
2519 {
2520         Render *re;
2521         RenderResult rres;
2522         float *rectf, *rectz;
2523         unsigned int *rect;
2524         float dither;
2525         int channels, layer, pass;
2526         ImBuf *ibuf;
2527         int from_render = (ima->render_slot == ima->last_render_slot);
2528
2529         if (!(iuser && iuser->scene))
2530                 return NULL;
2531
2532         /* if we the caller is not going to release the lock, don't give the image */
2533         if (!lock_r)
2534                 return NULL;
2535
2536         re = RE_GetRender(iuser->scene->id.name);
2537
2538         channels = 4;
2539         layer = (iuser) ? iuser->layer : 0;
2540         pass = (iuser) ? iuser->pass : 0;
2541
2542         if (from_render) {
2543                 RE_AcquireResultImage(re, &rres);
2544         }
2545         else if (ima->renders[ima->render_slot]) {
2546                 rres = *(ima->renders[ima->render_slot]);
2547                 rres.have_combined = rres.rectf != NULL;
2548         }
2549         else
2550                 memset(&rres, 0, sizeof(RenderResult));
2551
2552         if (!(rres.rectx > 0 && rres.recty > 0)) {
2553                 if (from_render)
2554                         RE_ReleaseResultImage(re);
2555                 return NULL;
2556         }
2557
2558         /* release is done in BKE_image_release_ibuf using lock_r */
2559         if (from_render) {
2560                 BLI_lock_thread(LOCK_VIEWER);
2561                 *lock_r = re;
2562         }
2563
2564         /* this gives active layer, composite or seqence result */
2565         rect = (unsigned int *)rres.rect32;
2566         rectf = rres.rectf;
2567         rectz = rres.rectz;
2568         dither = iuser->scene->r.dither_intensity;
2569
2570         /* combined layer gets added as first layer */
2571         if (rres.have_combined && layer == 0) {
2572                 /* pass */
2573         }
2574         else if (rres.layers.first) {
2575                 RenderLayer *rl = BLI_findlink(&rres.layers, layer - (rres.have_combined ? 1 : 0));
2576                 if (rl) {
2577                         RenderPass *rpass;
2578
2579                         /* there's no combined pass, is in renderlayer itself */
2580                         if (pass == 0) {
2581                                 rectf = rl->rectf;
2582                         }
2583                         else {
2584                                 rpass = BLI_findlink(&rl->passes, pass - 1);
2585                                 if (rpass) {
2586                                         channels = rpass->channels;
2587                                         rectf = rpass->rect;
2588                                         dither = 0.0f; /* don't dither passes */
2589                                 }
2590                         }
2591
2592                         for (rpass = rl->passes.first; rpass; rpass = rpass->next)
2593                                 if (rpass->passtype == SCE_PASS_Z)
2594                                         rectz = rpass->rect;
2595                 }
2596         }
2597
2598         ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2599
2600         /* make ibuf if needed, and initialize it */
2601         if (ibuf == NULL) {
2602                 ibuf = IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
2603                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2604         }
2605
2606         /* invalidate color managed buffers if render result changed */
2607         BLI_lock_thread(LOCK_COLORMANAGE);
2608         if (ibuf->x != rres.rectx || ibuf->y != rres.recty || ibuf->rect_float != rectf)
2609         {
2610                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
2611         }
2612
2613         ibuf->x = rres.rectx;
2614         ibuf->y = rres.recty;
2615
2616         /* free rect buffer if float buffer changes, so it can be recreated with
2617          * the updated result, and also in case we got byte buffer from sequencer,
2618          * so we don't keep reference to freed buffer */
2619         if (ibuf->rect_float != rectf || rect || !rectf)
2620                 imb_freerectImBuf(ibuf);
2621
2622         if (rect)
2623                 ibuf->rect = rect;
2624
2625         if (rectf) {
2626                 ibuf->rect_float = rectf;
2627                 ibuf->flags |= IB_rectfloat;
2628                 ibuf->channels = channels;
2629         }
2630         else {
2631                 ibuf->rect_float = NULL;
2632                 ibuf->flags &= ~IB_rectfloat;
2633         }
2634
2635         if (rectz) {
2636                 ibuf->zbuf_float = rectz;
2637                 ibuf->flags |= IB_zbuffloat;
2638         }
2639         else {
2640                 ibuf->zbuf_float = NULL;
2641                 ibuf->flags &= ~IB_zbuffloat;
2642         }
2643
2644         BLI_unlock_thread(LOCK_COLORMANAGE);
2645
2646         ibuf->dither = dither;
2647
2648         if (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT_PREDIVIDE) {
2649                 ibuf->flags |= IB_cm_predivide;
2650                 ima->flag |= IMA_CM_PREDIVIDE;
2651         }
2652         else {
2653                 ibuf->flags &= ~IB_cm_predivide;
2654                 ima->flag &= ~IMA_CM_PREDIVIDE;
2655         }
2656
2657         ima->ok = IMA_OK_LOADED;
2658
2659         return ibuf;
2660 }
2661
2662 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2663 {
2664         ImBuf *ibuf = NULL;
2665         int frame = 0, index = 0;
2666
2667         /* see if we already have an appropriate ibuf, with image source and type */
2668         if (ima->source == IMA_SRC_MOVIE) {
2669                 frame = iuser ? iuser->framenr : ima->lastframe;
2670                 ibuf = image_get_ibuf(ima, 0, frame);
2671                 /* XXX temp stuff? */
2672                 if (ima->lastframe != frame)
2673                         ima->tpageflag |= IMA_TPAGE_REFRESH;
2674                 ima->lastframe = frame;
2675         }
2676         else if (ima->source == IMA_SRC_SEQUENCE) {
2677                 if (ima->type == IMA_TYPE_IMAGE) {
2678                         frame = iuser ? iuser->framenr : ima->lastframe;
2679                         ibuf = image_get_ibuf(ima, 0, frame);
2680
2681                         /* XXX temp stuff? */
2682                         if (ima->lastframe != frame) {
2683                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2684                         }
2685                         ima->lastframe = frame;
2686                 }
2687                 else if (ima->type == IMA_TYPE_MULTILAYER) {
2688                         frame = iuser ? iuser->framenr : ima->lastframe;
2689                         index = iuser ? iuser->multi_index : IMA_NO_INDEX;
2690                         ibuf = image_get_ibuf(ima, index, frame);
2691                 }
2692         }
2693         else if (ima->source == IMA_SRC_FILE) {
2694                 if (ima->type == IMA_TYPE_IMAGE)
2695                         ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2696                 else if (ima->type == IMA_TYPE_MULTILAYER)
2697                         ibuf = image_get_ibuf(ima, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2698         }
2699         else if (ima->source == IMA_SRC_GENERATED) {
2700                 ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2701         }
2702         else if (ima->source == IMA_SRC_VIEWER) {
2703                 /* always verify entirely, not that this shouldn't happen
2704                  * as part of texture sampling in rendering anyway, so not
2705                  * a big bottleneck */
2706         }
2707
2708         *frame_r = frame;
2709         *index_r = index;
2710
2711         return ibuf;
2712 }
2713
2714 /* Checks optional ImageUser and verifies/creates ImBuf. */
2715 /* use this one if you want to get a render result in progress,
2716  * if not, use BKE_image_get_ibuf which doesn't require a release */
2717 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2718 {
2719         ImBuf *ibuf = NULL;
2720         float color[] = {0, 0, 0, 1};
2721         int frame = 0, index = 0;
2722
2723         /* This function is intended to be thread-safe. It postpones the mutex lock
2724          * until it needs to load the image, if the image is already there it
2725          * should just get the pointer and return. The reason is that a lot of mutex
2726          * locks appears to be very slow on certain multicore macs, causing a render
2727          * with image textures to actually slow down as more threads are used.
2728          *
2729          * Note that all the image loading functions should also make sure they do
2730          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2731          * That means, the last two steps must be, 1) add the ibuf to the list and
2732          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2733
2734         if (lock_r)
2735                 *lock_r = NULL;
2736
2737         /* quick reject tests */
2738         if (ima == NULL)
2739                 return NULL;
2740         if (iuser) {
2741                 if (iuser->ok == 0)
2742                         return NULL;
2743         }
2744         else if (ima->ok == 0)
2745                 return NULL;
2746
2747         /* try to get the ibuf without locking */
2748         ibuf = image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2749
2750         if (ibuf == NULL) {
2751                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2752                  * load the image */
2753                 BLI_lock_thread(LOCK_IMAGE);
2754
2755                 /* need to check ok flag and loading ibuf again, because the situation
2756                  * might have changed in the meantime */
2757                 if (iuser) {
2758                         if (iuser->ok == 0) {
2759                                 BLI_unlock_thread(LOCK_IMAGE);
2760                                 return NULL;
2761                         }
2762                 }
2763                 else if (ima->ok == 0) {
2764                         BLI_unlock_thread(LOCK_IMAGE);
2765                         return NULL;
2766                 }
2767
2768                 ibuf = image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2769
2770                 if (ibuf == NULL) {
2771                         /* we are sure we have to load the ibuf, using source and type */
2772                         if (ima->source == IMA_SRC_MOVIE) {
2773                                 /* source is from single file, use flipbook to store ibuf */
2774                                 ibuf = image_load_movie_file(ima, iuser, frame);
2775                         }
2776                         else if (ima->source == IMA_SRC_SEQUENCE) {
2777                                 if (ima->type == IMA_TYPE_IMAGE) {
2778                                         /* regular files, ibufs in flipbook, allows saving */
2779                                         ibuf = image_load_sequence_file(ima, iuser, frame);
2780                                 }
2781                                 /* no else; on load the ima type can change */
2782                                 if (ima->type == IMA_TYPE_MULTILAYER) {
2783                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2784                                         ibuf = image_load_sequence_multilayer(ima, iuser, frame);
2785                                 }
2786                         }
2787                         else if (ima->source == IMA_SRC_FILE) {
2788
2789                                 if (ima->type == IMA_TYPE_IMAGE)
2790                                         ibuf = image_load_image_file(ima, iuser, frame);  /* cfra only for '#', this global is OK */
2791                                 /* no else; on load the ima type can change */
2792                                 if (ima->type == IMA_TYPE_MULTILAYER)
2793                                         /* keeps render result, stores ibufs in listbase, allows saving */
2794                                         ibuf = image_get_ibuf_multilayer(ima, iuser);
2795
2796                         }
2797                         else if (ima->source == IMA_SRC_GENERATED) {
2798                                 /* generated is: ibuf is allocated dynamically */
2799                                 /* UV testgrid or black or solid etc */
2800                                 if (ima->gen_x == 0) ima->gen_x = 1024;
2801                                 if (ima->gen_y == 0) ima->gen_y = 1024;
2802                                 ibuf = add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, (ima->gen_flag & IMA_GEN_FLOAT) != 0, ima->gen_type,
2803                                                      color, &ima->colorspace_settings);
2804                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2805                                 ima->ok = IMA_OK_LOADED;
2806                         }
2807                         else if (ima->source == IMA_SRC_VIEWER) {
2808                                 if (ima->type == IMA_TYPE_R_RESULT) {
2809                                         /* always verify entirely, and potentially
2810                                          * returns pointer to release later */
2811                                         ibuf = image_get_render_result(ima, iuser, lock_r);
2812                                 }
2813                                 else if (ima->type == IMA_TYPE_COMPOSITE) {
2814                                         /* requires lock/unlock, otherwise don't return image */
2815                                         if (lock_r) {
2816                                                 /* unlock in BKE_image_release_ibuf */
2817                                                 BLI_lock_thread(LOCK_VIEWER);
2818                                                 *lock_r = ima;
2819
2820                                                 /* XXX anim play for viewer nodes not yet supported */
2821                                                 frame = 0; // XXX iuser?iuser->framenr:0;
2822                                                 ibuf = image_get_ibuf(ima, 0, frame);
2823
2824                                                 if (!ibuf) {
2825                                                         /* Composite Viewer, all handled in compositor */
2826                                                         /* fake ibuf, will be filled in compositor */
2827                                                         ibuf = IMB_allocImBuf(256, 256, 32, IB_rect);
2828                                                         image_assign_ibuf(ima, ibuf, 0, frame);
2829                                                 }
2830                                         }
2831                                 }
2832                         }
2833                 }
2834
2835                 BLI_unlock_thread(LOCK_IMAGE);
2836         }
2837
2838         BKE_image_tag_time(ima);
2839
2840         return ibuf;
2841 }
2842
2843 void BKE_image_release_ibuf(Image *ima, void *lock)
2844 {
2845         /* for getting image during threaded render / compositing, need to release */
2846         if (lock == ima) {
2847                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2848         }
2849         else if (lock) {
2850                 RE_ReleaseResultImage(lock); /* render result */
2851                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2852         }
2853 }
2854
2855 /* warning, this can allocate generated images */
2856 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2857 {
2858         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2859         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2860 }
2861
2862 int BKE_image_user_frame_get(const ImageUser *iuser, int cfra, int fieldnr, short *r_is_in_range)
2863 {
2864         const int len = (iuser->fie_ima * iuser->frames) / 2;
2865
2866         if (r_is_in_range) {
2867                 *r_is_in_range = FALSE;
2868         }
2869
2870         if (len == 0) {
2871                 return 0;
2872         }
2873         else {
2874                 int framenr;
2875                 cfra = cfra - iuser->sfra + 1;
2876
2877                 /* cyclic */
2878                 if (iuser->cycl) {
2879                         cfra = ((cfra) % len);
2880                         if (cfra < 0) cfra += len;
2881                         if (cfra == 0) cfra = len;
2882
2883                         if (r_is_in_range) {
2884                                 *r_is_in_range = TRUE;
2885                         }
2886                 }
2887
2888                 if (cfra < 0) {
2889                         cfra = 0;
2890                 }
2891                 else if (cfra > len) {
2892                         cfra = len;
2893                 }
2894                 else {
2895                         if (r_is_in_range) {
2896                                 *r_is_in_range = TRUE;
2897                         }
2898                 }
2899
2900                 /* convert current frame to current field */
2901                 cfra = 2 * (cfra);
2902                 if (fieldnr) cfra++;
2903
2904                 /* transform to images space */
2905                 framenr = (cfra + iuser->fie_ima - 2) / iuser->fie_ima;
2906                 if (framenr > iuser->frames) framenr = iuser->frames;
2907
2908                 if (iuser->cycl) {
2909                         framenr = ((framenr) % len);
2910                         while (framenr < 0) framenr += len;
2911                         if (framenr == 0) framenr = len;
2912                 }
2913
2914                 /* important to apply after else we cant loop on frames 100 - 110 for eg. */
2915                 framenr += iuser->offset;
2916
2917                 return framenr;
2918         }
2919 }
2920
2921 void BKE_image_user_frame_calc(ImageUser *iuser, int cfra, int fieldnr)
2922 {
2923         if (iuser) {
2924                 short is_in_range;
2925                 const int framenr = BKE_image_user_frame_get(iuser, cfra, fieldnr, &is_in_range);
2926
2927                 if (is_in_range) {
2928                         iuser->flag |= IMA_USER_FRAME_IN_RANGE;
2929                 }
2930                 else {
2931                         iuser->flag &= ~IMA_USER_FRAME_IN_RANGE;
2932                 }
2933
2934                 /* allows image users to handle redraws */
2935                 if (iuser->flag & IMA_ANIM_ALWAYS)
2936                         if (framenr != iuser->framenr)
2937                                 iuser->flag |= IMA_ANIM_REFRESHED;
2938
2939                 iuser->framenr = framenr;
2940                 if (iuser->ok == 0) iuser->ok = 1;
2941         }
2942 }
2943
2944 void BKE_image_user_check_frame_calc(ImageUser *iuser, int cfra, int fieldnr)
2945 {
2946         if ((iuser->flag & IMA_ANIM_ALWAYS) || (iuser->flag & IMA_NEED_FRAME_RECALC)) {
2947                 BKE_image_user_frame_calc(iuser, cfra, fieldnr);
2948
2949                 iuser->flag &= ~IMA_NEED_FRAME_RECALC;
2950         }
2951 }
2952
2953 void BKE_image_user_file_path(ImageUser *iuser, Image *ima, char *filepath)
2954 {
2955         BLI_strncpy(filepath, ima->name, FILE_MAX);
2956
2957         if (ima->source == IMA_SRC_SEQUENCE) {
2958                 char head[FILE_MAX], tail[FILE_MAX];
2959                 unsigned short numlen;
2960                 int frame = iuser ? iuser->framenr : ima->lastframe;
2961
2962                 BLI_stringdec(filepath, head, tail, &numlen);
2963                 BLI_stringenc(filepath, head, tail, numlen, frame);
2964         }
2965
2966         BLI_path_abs(filepath, ID_BLEND_PATH(G.main, &ima->id));
2967 }
2968
2969 int BKE_image_has_alpha(struct Image *image)
2970 {
2971         ImBuf *ibuf;
2972         void *lock;
2973         int planes;
2974
2975         ibuf = BKE_image_acquire_ibuf(image, NULL, &lock);
2976         planes = (ibuf ? ibuf->planes : 0);
2977         BKE_image_release_ibuf(image, lock);
2978
2979         if (planes == 32)
2980                 return 1;
2981         else
2982                 return 0;
2983 }
2984
2985 void BKE_image_get_size(Image *image, ImageUser *iuser, int *width, int *height)
2986 {
2987         ImBuf *ibuf = NULL;
2988         void *lock;
2989
2990         ibuf = BKE_image_acquire_ibuf(image, iuser, &lock);
2991
2992         if (ibuf && ibuf->x > 0 && ibuf->y > 0) {
2993                 *width = ibuf->x;
2994                 *height = ibuf->y;
2995         }
2996         else {
2997                 *width  = IMG_SIZE_FALLBACK;
2998                 *height = IMG_SIZE_FALLBACK;
2999         }
3000
3001         BKE_image_release_ibuf(image, lock);
3002 }
3003
3004 void BKE_image_get_size_fl(Image *image, ImageUser *iuser, float size[2])
3005 {
3006         int width, height;
3007         BKE_image_get_size(image, iuser, &width, &height);
3008
3009         size[0] = (float)width;
3010         size[1] = (float)height;
3011
3012 }
3013
3014 void BKE_image_get_aspect(Image *image, float *aspx, float *aspy)
3015 {
3016         *aspx = 1.0;
3017
3018         /* x is always 1 */
3019         if (image)
3020                 *aspy = image->aspy / image->aspx;
3021         else
3022                 *aspy = 1.0f;
3023 }