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