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