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