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