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