svn merge ^/trunk/blender -r49854:49867
[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         BKE_imformat_defaults(im_format);
1236
1237         /* file type */
1238
1239         if (imbuf->ftype == IMAGIC)
1240                 im_format->imtype = R_IMF_IMTYPE_IRIS;
1241
1242 #ifdef WITH_HDR
1243         else if (imbuf->ftype == RADHDR)
1244                 im_format->imtype = R_IMF_IMTYPE_RADHDR;
1245 #endif
1246
1247         else if (imbuf->ftype == PNG)
1248                 im_format->imtype = R_IMF_IMTYPE_PNG;
1249
1250 #ifdef WITH_DDS
1251         else if (imbuf->ftype == DDS)
1252                 im_format->imtype = R_IMF_IMTYPE_DDS;
1253 #endif
1254
1255         else if (imbuf->ftype == BMP)
1256                 im_format->imtype = R_IMF_IMTYPE_BMP;
1257
1258 #ifdef WITH_TIFF
1259         else if (imbuf->ftype & TIF) {
1260                 im_format->imtype = R_IMF_IMTYPE_TIFF;
1261                 if (imbuf->ftype & TIF_16BIT)
1262                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1263         }
1264 #endif
1265
1266 #ifdef WITH_OPENEXR
1267         else if (imbuf->ftype & OPENEXR) {
1268                 im_format->imtype = R_IMF_IMTYPE_OPENEXR;
1269                 if (imbuf->ftype & OPENEXR_HALF)
1270                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1271                 if (imbuf->ftype & OPENEXR_COMPRESS)
1272                         im_format->exr_codec = R_IMF_EXR_CODEC_ZIP;  // Can't determine compression
1273                 if (imbuf->zbuf_float)
1274                         im_format->flag |= R_IMF_FLAG_ZBUF;
1275         }
1276 #endif
1277
1278 #ifdef WITH_CINEON
1279         else if (imbuf->ftype == CINEON)
1280                 im_format->imtype = R_IMF_IMTYPE_CINEON;
1281         else if (imbuf->ftype == DPX)
1282                 im_format->imtype = R_IMF_IMTYPE_DPX;
1283 #endif
1284
1285         else if (imbuf->ftype == TGA) {
1286                 im_format->imtype = R_IMF_IMTYPE_TARGA;
1287         }
1288         else if (imbuf->ftype == RAWTGA) {
1289                 im_format->imtype = R_IMF_IMTYPE_RAWTGA;
1290         }
1291
1292 #ifdef WITH_OPENJPEG
1293         else if (imbuf->ftype & JP2) {
1294                 im_format->imtype = R_IMF_IMTYPE_JP2;
1295                 im_format->quality = imbuf->ftype & ~JPG_MSK;
1296
1297                 if (imbuf->ftype & JP2_16BIT)
1298                         im_format->depth = R_IMF_CHAN_DEPTH_16;
1299                 else if (imbuf->ftype & JP2_12BIT)
1300                         im_format->depth = R_IMF_CHAN_DEPTH_12;
1301
1302                 if (imbuf->ftype & JP2_YCC)
1303                         im_format->jp2_flag |= R_IMF_JP2_FLAG_YCC;
1304
1305                 if (imbuf->ftype & JP2_CINE) {
1306                         im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_PRESET;
1307                         if (imbuf->ftype & JP2_CINE_48FPS)
1308                                 im_format->jp2_flag |= R_IMF_JP2_FLAG_CINE_48;
1309                 }
1310         }
1311 #endif
1312
1313         else {
1314                 im_format->imtype = R_IMF_IMTYPE_JPEG90;
1315                 im_format->quality = imbuf->ftype & ~JPG_MSK;
1316         }
1317
1318         /* planes */
1319         switch (imbuf->channels) {
1320                 case 0:
1321                 case 4: im_format->planes = R_IMF_PLANES_RGBA;
1322                         break;
1323                 case 3: im_format->planes = R_IMF_PLANES_RGB;
1324                         break;
1325                 case 1: im_format->planes = R_IMF_PLANES_BW;
1326                         break;
1327                 default: im_format->planes = R_IMF_PLANES_RGB;
1328                         break;
1329         }
1330
1331 }
1332
1333 static void timecode_simple_string(char *text, size_t text_size, const int cfra, int const frs_sec)
1334 {
1335         int f = (int)(cfra % frs_sec);
1336         int s = (int)(cfra / frs_sec);
1337         int h = 0;
1338         int m = 0;
1339
1340         if (s) {
1341                 m = (int)(s / 60);
1342                 s %= 60;
1343
1344                 if (m) {
1345                         h = (int)(m / 60);
1346                         m %= 60;
1347                 }
1348         }
1349
1350         if (frs_sec < 100) {
1351                 BLI_snprintf(text, text_size, "%02d:%02d:%02d.%02d", h, m, s, f);
1352         }
1353         else {
1354                 BLI_snprintf(text, text_size, "%02d:%02d:%02d.%03d", h, m, s, f);
1355         }
1356 }
1357
1358 /* could allow access externally - 512 is for long names, 64 is for id names */
1359 typedef struct StampData {
1360         char file[512];
1361         char note[512];
1362         char date[512];
1363         char marker[512];
1364         char time[512];
1365         char frame[512];
1366         char camera[64];
1367         char cameralens[64];
1368         char scene[64];
1369         char strip[64];
1370         char rendertime[64];
1371 } StampData;
1372
1373 static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix)
1374 {
1375         char text[256];
1376         struct tm *tl;
1377         time_t t;
1378
1379         if (scene->r.stamp & R_STAMP_FILENAME) {
1380                 BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), do_prefix ? "File %s" : "%s", G.relbase_valid ? G.main->name : "<untitled>");
1381         }
1382         else {
1383                 stamp_data->file[0] = '\0';
1384         }
1385
1386         if (scene->r.stamp & R_STAMP_NOTE) {
1387                 /* Never do prefix for Note */
1388                 BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", scene->r.stamp_udata);
1389         }
1390         else {
1391                 stamp_data->note[0] = '\0';
1392         }
1393
1394         if (scene->r.stamp & R_STAMP_DATE) {
1395                 t = time(NULL);
1396                 tl = localtime(&t);
1397                 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);
1398                 BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), do_prefix ? "Date %s" : "%s", text);
1399         }
1400         else {
1401                 stamp_data->date[0] = '\0';
1402         }
1403
1404         if (scene->r.stamp & R_STAMP_MARKER) {
1405                 char *name = BKE_scene_find_last_marker_name(scene, CFRA);
1406
1407                 if (name) BLI_strncpy(text, name, sizeof(text));
1408                 else BLI_strncpy(text, "<none>", sizeof(text));
1409
1410                 BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), do_prefix ? "Marker %s" : "%s", text);
1411         }
1412         else {
1413                 stamp_data->marker[0] = '\0';
1414         }
1415
1416         if (scene->r.stamp & R_STAMP_TIME) {
1417                 timecode_simple_string(text, sizeof(text), scene->r.cfra, scene->r.frs_sec);
1418                 BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), do_prefix ? "Time %s" : "%s", text);
1419         }
1420         else {
1421                 stamp_data->time[0] = '\0';
1422         }
1423
1424         if (scene->r.stamp & R_STAMP_FRAME) {
1425                 char fmtstr[32];
1426                 int digits = 1;
1427
1428                 if (scene->r.efra > 9)
1429                         digits = 1 + (int) log10(scene->r.efra);
1430
1431                 BLI_snprintf(fmtstr, sizeof(fmtstr), do_prefix ? "Frame %%0%di" : "%%0%di", digits);
1432                 BLI_snprintf(stamp_data->frame, sizeof(stamp_data->frame), fmtstr, scene->r.cfra);
1433         }
1434         else {
1435                 stamp_data->frame[0] = '\0';
1436         }
1437
1438         if (scene->r.stamp & R_STAMP_CAMERA) {
1439                 BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), do_prefix ? "Camera %s" : "%s", camera ? camera->id.name + 2 : "<none>");
1440         }
1441         else {
1442                 stamp_data->camera[0] = '\0';
1443         }
1444
1445         if (scene->r.stamp & R_STAMP_CAMERALENS) {
1446                 if (camera && camera->type == OB_CAMERA) {
1447                         BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)camera->data)->lens);
1448                 }
1449                 else BLI_strncpy(text, "<none>", sizeof(text));
1450
1451                 BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), do_prefix ? "Lens %s" : "%s", text);
1452         }
1453         else {
1454                 stamp_data->cameralens[0] = '\0';
1455         }
1456
1457         if (scene->r.stamp & R_STAMP_SCENE) {
1458                 BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), do_prefix ? "Scene %s" : "%s", scene->id.name + 2);
1459         }
1460         else {
1461                 stamp_data->scene[0] = '\0';
1462         }
1463
1464         if (scene->r.stamp & R_STAMP_SEQSTRIP) {
1465                 Sequence *seq = BKE_sequencer_foreground_frame_get(scene, scene->r.cfra);
1466
1467                 if (seq) BLI_strncpy(text, seq->name + 2, sizeof(text));
1468                 else BLI_strncpy(text, "<none>", sizeof(text));
1469
1470                 BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), do_prefix ? "Strip %s" : "%s", text);
1471         }
1472         else {
1473                 stamp_data->strip[0] = '\0';
1474         }
1475
1476         {
1477                 Render *re = RE_GetRender(scene->id.name);
1478                 RenderStats *stats = re ? RE_GetStats(re) : NULL;
1479
1480                 if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
1481                         BLI_timestr(stats->lastframetime, text);
1482
1483                         BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), do_prefix ? "RenderTime %s" : "%s", text);
1484                 }
1485                 else {
1486                         stamp_data->rendertime[0] = '\0';
1487                 }
1488         }
1489 }
1490
1491 void BKE_stamp_buf(Scene *scene, Object *camera, unsigned char *rect, float *rectf, int width, int height, int channels)
1492 {
1493         struct StampData stamp_data;
1494         float w, h, pad;
1495         int x, y, y_ofs;
1496         float h_fixed;
1497         const int mono = blf_mono_font_render; // XXX
1498
1499         /* this could be an argument if we want to operate on non linear float imbuf's
1500          * for now though this is only used for renders which use scene settings */
1501         const int do_color_management = (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) != 0;
1502
1503 #define BUFF_MARGIN_X 2
1504 #define BUFF_MARGIN_Y 1
1505
1506         if (!rect && !rectf)
1507                 return;
1508
1509         stampdata(scene, camera, &stamp_data, 1);
1510
1511         /* TODO, do_versions */
1512         if (scene->r.stamp_font_id < 8)
1513                 scene->r.stamp_font_id = 12;
1514
1515         /* set before return */
1516         BLF_size(mono, scene->r.stamp_font_id, 72);
1517
1518         BLF_buffer(mono, rectf, rect, width, height, channels, do_color_management);
1519         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1520         pad = BLF_width_max(mono);
1521
1522         /* use 'h_fixed' rather than 'h', aligns better */
1523         h_fixed = BLF_height_max(mono);
1524         y_ofs = -BLF_descender(mono);
1525
1526         x = 0;
1527         y = height;
1528
1529         if (stamp_data.file[0]) {
1530                 /* Top left corner */
1531                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h = h_fixed;
1532                 y -= h;
1533
1534                 /* also a little of space to the background. */
1535                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1536                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1537
1538                 /* and draw the text. */
1539                 BLF_position(mono, x, y + y_ofs, 0.0);
1540                 BLF_draw_buffer(mono, stamp_data.file);
1541
1542                 /* the extra pixel for background. */
1543                 y -= BUFF_MARGIN_Y * 2;
1544         }
1545
1546         /* Top left corner, below File */
1547         if (stamp_data.note[0]) {
1548                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h = h_fixed;
1549                 y -= h;
1550
1551                 /* and space for background. */
1552                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1553                                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1554
1555                 BLF_position(mono, x, y + y_ofs, 0.0);
1556                 BLF_draw_buffer(mono, stamp_data.note);
1557
1558                 /* the extra pixel for background. */
1559                 y -= BUFF_MARGIN_Y * 2;
1560         }
1561
1562         /* Top left corner, below File (or Note) */
1563         if (stamp_data.date[0]) {
1564                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h = h_fixed;
1565                 y -= h;
1566
1567                 /* and space for background. */
1568                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1569                                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1570
1571                 BLF_position(mono, x, y + y_ofs, 0.0);
1572                 BLF_draw_buffer(mono, stamp_data.date);
1573
1574                 /* the extra pixel for background. */
1575                 y -= BUFF_MARGIN_Y * 2;
1576         }
1577
1578         /* Top left corner, below File, Date or Note */
1579         if (stamp_data.rendertime[0]) {
1580                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h = h_fixed;
1581                 y -= h;
1582
1583                 /* and space for background. */
1584                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1585                                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1586
1587                 BLF_position(mono, x, y + y_ofs, 0.0);
1588                 BLF_draw_buffer(mono, stamp_data.rendertime);
1589         }
1590
1591         x = 0;
1592         y = 0;
1593
1594         /* Bottom left corner, leaving space for timing */
1595         if (stamp_data.marker[0]) {
1596                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h = h_fixed;
1597
1598                 /* extra space for background. */
1599                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp,  do_color_management,
1600                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1601
1602                 /* and pad the text. */
1603                 BLF_position(mono, x, y + y_ofs, 0.0);
1604                 BLF_draw_buffer(mono, stamp_data.marker);
1605
1606                 /* space width. */
1607                 x += w + pad;
1608         }
1609
1610         /* Left bottom corner */
1611         if (stamp_data.time[0]) {
1612                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h = h_fixed;
1613
1614                 /* extra space for background */
1615                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1616                                                   x - BUFF_MARGIN_X, y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1617
1618                 /* and pad the text. */
1619                 BLF_position(mono, x, y + y_ofs, 0.0);
1620                 BLF_draw_buffer(mono, stamp_data.time);
1621
1622                 /* space width. */
1623                 x += w + pad;
1624         }
1625
1626         if (stamp_data.frame[0]) {
1627                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h = h_fixed;
1628
1629                 /* extra space for background. */
1630                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1631                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1632
1633                 /* and pad the text. */
1634                 BLF_position(mono, x, y + y_ofs, 0.0);
1635                 BLF_draw_buffer(mono, stamp_data.frame);
1636
1637                 /* space width. */
1638                 x += w + pad;
1639         }
1640
1641         if (stamp_data.camera[0]) {
1642                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h = h_fixed;
1643
1644                 /* extra space for background. */
1645                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1646                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1647                 BLF_position(mono, x, y + y_ofs, 0.0);
1648                 BLF_draw_buffer(mono, stamp_data.camera);
1649
1650                 /* space width. */
1651                 x += w + pad;
1652         }
1653
1654         if (stamp_data.cameralens[0]) {
1655                 BLF_width_and_height(mono, stamp_data.cameralens, &w, &h); h = h_fixed;
1656
1657                 /* extra space for background. */
1658                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1659                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1660                 BLF_position(mono, x, y + y_ofs, 0.0);
1661                 BLF_draw_buffer(mono, stamp_data.cameralens);
1662         }
1663
1664         if (stamp_data.scene[0]) {
1665                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h = h_fixed;
1666
1667                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1668                 x = width - w - 2;
1669
1670                 /* extra space for background. */
1671                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1672                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1673
1674                 /* and pad the text. */
1675                 BLF_position(mono, x, y + y_ofs, 0.0);
1676                 BLF_draw_buffer(mono, stamp_data.scene);
1677         }
1678
1679         if (stamp_data.strip[0]) {
1680                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h = h_fixed;
1681
1682                 /* Top right corner, with an extra space because blenfont is too strict! */
1683                 x = width - w - pad;
1684                 y = height - h;
1685
1686                 /* extra space for background. */
1687                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, do_color_management,
1688                                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1689
1690                 BLF_position(mono, x, y + y_ofs, 0.0);
1691                 BLF_draw_buffer(mono, stamp_data.strip);
1692         }
1693
1694         /* cleanup the buffer. */
1695         BLF_buffer(mono, NULL, NULL, 0, 0, 0, FALSE);
1696
1697 #undef BUFF_MARGIN_X
1698 #undef BUFF_MARGIN_Y
1699 }
1700
1701 void BKE_imbuf_stamp_info(Scene *scene, Object *camera, struct ImBuf *ibuf)
1702 {
1703         struct StampData stamp_data;
1704
1705         if (!ibuf) return;
1706
1707         /* fill all the data values, no prefix */
1708         stampdata(scene, camera, &stamp_data, 0);
1709
1710         if (stamp_data.file[0]) IMB_metadata_change_field(ibuf, "File",        stamp_data.file);
1711         if (stamp_data.note[0]) IMB_metadata_change_field(ibuf, "Note",        stamp_data.note);
1712         if (stamp_data.date[0]) IMB_metadata_change_field(ibuf, "Date",        stamp_data.date);
1713         if (stamp_data.marker[0]) IMB_metadata_change_field(ibuf, "Marker",    stamp_data.marker);
1714         if (stamp_data.time[0]) IMB_metadata_change_field(ibuf, "Time",        stamp_data.time);
1715         if (stamp_data.frame[0]) IMB_metadata_change_field(ibuf, "Frame",      stamp_data.frame);
1716         if (stamp_data.camera[0]) IMB_metadata_change_field(ibuf, "Camera",    stamp_data.camera);
1717         if (stamp_data.cameralens[0]) IMB_metadata_change_field(ibuf, "Lens",  stamp_data.cameralens);
1718         if (stamp_data.scene[0]) IMB_metadata_change_field(ibuf, "Scene",      stamp_data.scene);
1719         if (stamp_data.strip[0]) IMB_metadata_change_field(ibuf, "Strip",      stamp_data.strip);
1720         if (stamp_data.rendertime[0]) IMB_metadata_change_field(ibuf, "RenderTime", stamp_data.rendertime);
1721 }
1722
1723 int BKE_imbuf_alpha_test(ImBuf *ibuf)
1724 {
1725         int tot;
1726         if (ibuf->rect_float) {
1727                 float *buf = ibuf->rect_float;
1728                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1729                         if (buf[3] < 1.0f) {
1730                                 return TRUE;
1731                         }
1732                 }
1733         }
1734         else if (ibuf->rect) {
1735                 unsigned char *buf = (unsigned char *)ibuf->rect;
1736                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1737                         if (buf[3] != 255) {
1738                                 return TRUE;
1739                         }
1740                 }
1741         }
1742
1743         return FALSE;
1744 }
1745
1746 /* note: imf->planes is ignored here, its assumed the image channels
1747  * are already set */
1748 int BKE_imbuf_write(ImBuf *ibuf, const char *name, ImageFormatData *imf)
1749 {
1750         char imtype = imf->imtype;
1751         char compress = imf->compress;
1752         char quality = imf->quality;
1753
1754         int ok;
1755
1756         if (imtype == R_IMF_IMTYPE_IRIS) {
1757                 ibuf->ftype = IMAGIC;
1758         }
1759 #ifdef WITH_HDR
1760         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1761                 ibuf->ftype = RADHDR;
1762         }
1763 #endif
1764         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1765                 ibuf->ftype = PNG;
1766
1767                 if (imtype == R_IMF_IMTYPE_PNG)
1768                         ibuf->ftype |= compress;
1769
1770         }
1771 #ifdef WITH_DDS
1772         else if (imtype == R_IMF_IMTYPE_DDS) {
1773                 ibuf->ftype = DDS;
1774         }
1775 #endif
1776         else if (imtype == R_IMF_IMTYPE_BMP) {
1777                 ibuf->ftype = BMP;
1778         }
1779 #ifdef WITH_TIFF
1780         else if (imtype == R_IMF_IMTYPE_TIFF) {
1781                 ibuf->ftype = TIF;
1782
1783                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1784                         ibuf->ftype |= TIF_16BIT;
1785         }
1786 #endif
1787 #ifdef WITH_OPENEXR
1788         else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER) {
1789                 ibuf->ftype = OPENEXR;
1790                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1791                         ibuf->ftype |= OPENEXR_HALF;
1792                 ibuf->ftype |= (imf->exr_codec & OPENEXR_COMPRESS);
1793
1794                 if (!(imf->flag & R_IMF_FLAG_ZBUF))
1795                         ibuf->zbuf_float = NULL;    /* signal for exr saving */
1796
1797         }
1798 #endif
1799 #ifdef WITH_CINEON
1800         else if (imtype == R_IMF_IMTYPE_CINEON) {
1801                 ibuf->ftype = CINEON;
1802         }
1803         else if (imtype == R_IMF_IMTYPE_DPX) {
1804                 ibuf->ftype = DPX;
1805         }
1806 #endif
1807         else if (imtype == R_IMF_IMTYPE_TARGA) {
1808                 ibuf->ftype = TGA;
1809         }
1810         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
1811                 ibuf->ftype = RAWTGA;
1812         }
1813 #ifdef WITH_OPENJPEG
1814         else if (imtype == R_IMF_IMTYPE_JP2) {
1815                 if (quality < 10) quality = 90;
1816                 ibuf->ftype = JP2 | quality;
1817
1818                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1819                         ibuf->ftype |= JP2_16BIT;
1820                 }
1821                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1822                         ibuf->ftype |= JP2_12BIT;
1823                 }
1824
1825                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
1826                         ibuf->ftype |= JP2_YCC;
1827                 }
1828
1829                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
1830                         ibuf->ftype |= JP2_CINE;
1831                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
1832                                 ibuf->ftype |= JP2_CINE_48FPS;
1833                 }
1834         }
1835 #endif
1836         else {
1837                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
1838                 if (quality < 10) quality = 90;
1839                 ibuf->ftype = JPG | quality;
1840         }
1841
1842         BLI_make_existing_file(name);
1843
1844         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
1845         if (ok == 0) {
1846                 perror(name);
1847         }
1848
1849         return(ok);
1850 }
1851
1852 /* same as BKE_imbuf_write() but crappy workaround not to perminantly modify
1853  * _some_, values in the imbuf */
1854 int BKE_imbuf_write_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
1855                        const short save_copy)
1856 {
1857         ImBuf ibuf_back = *ibuf;
1858         int ok;
1859
1860         /* all data is rgba anyway,
1861          * this just controls how to save for some formats */
1862         ibuf->planes = imf->planes;
1863
1864         ok = BKE_imbuf_write(ibuf, name, imf);
1865
1866         if (save_copy) {
1867                 /* note that we are not restoring _all_ settings */
1868                 ibuf->planes = ibuf_back.planes;
1869                 ibuf->ftype =  ibuf_back.ftype;
1870         }
1871
1872         return ok;
1873 }
1874
1875 int BKE_imbuf_write_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, struct ImageFormatData *imf)
1876 {
1877         if (scene && scene->r.stamp & R_STAMP_ALL)
1878                 BKE_imbuf_stamp_info(scene, camera, ibuf);
1879
1880         return BKE_imbuf_write(ibuf, name, imf);
1881 }
1882
1883
1884 void BKE_makepicstring(char *string, const char *base, const char *relbase, int frame, const char imtype, const short use_ext, const short use_frames)
1885 {
1886         if (string == NULL) return;
1887         BLI_strncpy(string, base, FILE_MAX - 10);   /* weak assumption */
1888         BLI_path_abs(string, relbase);
1889
1890         if (use_frames)
1891                 BLI_path_frame(string, frame, 4);
1892
1893         if (use_ext)
1894                 BKE_add_image_extension(string, imtype);
1895
1896 }
1897
1898 /* used by sequencer too */
1899 struct anim *openanim(const char *name, int flags, int streamindex)
1900 {
1901         struct anim *anim;
1902         struct ImBuf *ibuf;
1903
1904         anim = IMB_open_anim(name, flags, streamindex);
1905         if (anim == NULL) return NULL;
1906
1907         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
1908         if (ibuf == NULL) {
1909                 if (BLI_exists(name))
1910                         printf("not an anim: %s\n", name);
1911                 else
1912                         printf("anim file doesn't exist: %s\n", name);
1913                 IMB_free_anim(anim);
1914                 return NULL;
1915         }
1916         IMB_freeImBuf(ibuf);
1917
1918         return(anim);
1919 }
1920
1921 /* ************************* New Image API *************** */
1922
1923
1924 /* Notes about Image storage
1925  * - packedfile
1926  *   -> written in .blend
1927  * - filename
1928  *   -> written in .blend
1929  * - movie
1930  *   -> comes from packedfile or filename
1931  * - renderresult
1932  *   -> comes from packedfile or filename
1933  * - listbase
1934  *   -> ibufs from exrhandle
1935  * - flipbook array
1936  *   -> ibufs come from movie, temporary renderresult or sequence
1937  * - ibuf
1938  *   -> comes from packedfile or filename or generated
1939  */
1940
1941
1942 /* forces existence of 1 Image for renderout or nodes, returns Image */
1943 /* name is only for default, when making new one */
1944 Image *BKE_image_verify_viewer(int type, const char *name)
1945 {
1946         Image *ima;
1947
1948         for (ima = G.main->image.first; ima; ima = ima->id.next)
1949                 if (ima->source == IMA_SRC_VIEWER)
1950                         if (ima->type == type)
1951                                 break;
1952
1953         if (ima == NULL)
1954                 ima = image_alloc(name, IMA_SRC_VIEWER, type);
1955
1956         /* happens on reload, imagewindow cannot be image user when hidden*/
1957         if (ima->id.us == 0)
1958                 id_us_plus(&ima->id);
1959
1960         return ima;
1961 }
1962
1963 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
1964 {
1965         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
1966 }
1967
1968 void BKE_image_walk_all_users(const Main *mainp, void *customdata,
1969                               void callback(Image *ima, ImageUser *iuser, void *customdata))
1970 {
1971         wmWindowManager *wm;
1972         wmWindow *win;
1973         Tex *tex;
1974
1975         /* texture users */
1976         for (tex = mainp->tex.first; tex; tex = tex->id.next) {
1977                 if (tex->type == TEX_IMAGE && tex->ima) {
1978                         if (ELEM(tex->ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
1979                                 callback(tex->ima, &tex->iuser, customdata);
1980                         }
1981                 }
1982         }
1983
1984         /* image window, compo node users */
1985         for (wm = mainp->wm.first; wm; wm = wm->id.next) { /* only 1 wm */
1986                 for (win = wm->windows.first; win; win = win->next) {
1987                         ScrArea *sa;
1988                         for (sa = win->screen->areabase.first; sa; sa = sa->next) {
1989                                 if (sa->spacetype == SPACE_VIEW3D) {
1990                                         View3D *v3d = sa->spacedata.first;
1991                                         BGpic *bgpic;
1992                                         for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
1993                                                 callback(bgpic->ima, &bgpic->iuser, customdata);
1994                                         }
1995                                 }
1996                                 else if (sa->spacetype == SPACE_IMAGE) {
1997                                         SpaceImage *sima = sa->spacedata.first;
1998                                         callback(sima->image, &sima->iuser, customdata);
1999                                 }
2000                                 else if (sa->spacetype == SPACE_NODE) {
2001                                         SpaceNode *snode = sa->spacedata.first;
2002                                         if ((snode->treetype == NTREE_COMPOSIT) && (snode->nodetree)) {
2003                                                 bNode *node;
2004                                                 for (node = snode->nodetree->nodes.first; node; node = node->next) {
2005                                                         if (node->id && node->type == CMP_NODE_IMAGE) {
2006                                                                 Image *ima = (Image *)node->id;
2007                                                                 ImageUser *iuser = node->storage;
2008                                                                 callback(ima, iuser, customdata);
2009                                                         }
2010                                                 }
2011                                         }
2012                                 }
2013                         }
2014                 }
2015         }
2016 }
2017
2018 static void image_tag_frame_recalc(Image *ima, ImageUser *iuser, void *customdata)
2019 {
2020         Image *changed_image = customdata;
2021
2022         if (ima == changed_image) {
2023                 iuser->flag |= IMA_NEED_FRAME_RECALC;
2024         }
2025 }
2026
2027 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
2028 {
2029         if (ima == NULL)
2030                 return;
2031
2032         switch (signal) {
2033                 case IMA_SIGNAL_FREE:
2034                         image_free_buffers(ima);
2035                         if (iuser)
2036                                 iuser->ok = 1;
2037                         break;
2038                 case IMA_SIGNAL_SRC_CHANGE:
2039                         if (ima->type == IMA_TYPE_UV_TEST)
2040                                 if (ima->source != IMA_SRC_GENERATED)
2041                                         ima->type = IMA_TYPE_IMAGE;
2042
2043                         if (ima->source == IMA_SRC_GENERATED) {
2044                                 if (ima->gen_x == 0 || ima->gen_y == 0) {
2045                                         ImBuf *ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2046                                         if (ibuf) {
2047                                                 ima->gen_x = ibuf->x;
2048                                                 ima->gen_y = ibuf->y;
2049                                         }
2050                                 }
2051                         }
2052
2053                         /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
2054                         if (ima->type != IMA_TYPE_MULTILAYER)
2055                                 image_free_buffers(ima);
2056
2057                         ima->ok = 1;
2058                         if (iuser)
2059                                 iuser->ok = 1;
2060
2061                         BKE_image_walk_all_users(G.main, ima, image_tag_frame_recalc);
2062
2063                         break;
2064
2065                 case IMA_SIGNAL_RELOAD:
2066                         /* try to repack file */
2067                         if (ima->packedfile) {
2068                                 PackedFile *pf;
2069                                 pf = newPackedFile(NULL, ima->name, ID_BLEND_PATH(G.main, &ima->id));
2070                                 if (pf) {
2071                                         freePackedFile(ima->packedfile);
2072                                         ima->packedfile = pf;
2073                                         image_free_buffers(ima);
2074                                 }
2075                                 else {
2076                                         printf("ERROR: Image not available. Keeping packed image\n");
2077                                 }
2078                         }
2079                         else
2080                                 image_free_buffers(ima);
2081
2082                         if (iuser)
2083                                 iuser->ok = 1;
2084
2085                         break;
2086                 case IMA_SIGNAL_USER_NEW_IMAGE:
2087                         if (iuser) {
2088                                 iuser->ok = 1;
2089                                 if (ima->source == IMA_SRC_FILE || ima->source == IMA_SRC_SEQUENCE) {
2090                                         if (ima->type == IMA_TYPE_MULTILAYER) {
2091                                                 iuser->multi_index = 0;
2092                                                 iuser->layer = iuser->pass = 0;
2093                                         }
2094                                 }
2095                         }
2096                         break;
2097         }
2098
2099         /* don't use notifiers because they are not 100% sure to succeeded
2100          * this also makes sure all scenes are accounted for. */
2101         {
2102                 Scene *scene;
2103                 for (scene = G.main->scene.first; scene; scene = scene->id.next) {
2104                         if (scene->nodetree) {
2105                                 nodeUpdateID(scene->nodetree, &ima->id);
2106                         }
2107                 }
2108         }
2109 }
2110
2111 /* if layer or pass changes, we need an index for the imbufs list */
2112 /* note it is called for rendered results, but it doesnt use the index! */
2113 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
2114 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
2115 {
2116         RenderLayer *rl;
2117         RenderPass *rpass = NULL;
2118
2119         if (rr == NULL)
2120                 return NULL;
2121
2122         if (iuser) {
2123                 short index = 0, rl_index = 0, rp_index;
2124
2125                 for (rl = rr->layers.first; rl; rl = rl->next, rl_index++) {
2126                         rp_index = 0;
2127                         for (rpass = rl->passes.first; rpass; rpass = rpass->next, index++, rp_index++)
2128                                 if (iuser->layer == rl_index && iuser->pass == rp_index)
2129                                         break;
2130                         if (rpass)
2131                                 break;
2132                 }
2133
2134                 if (rpass)
2135                         iuser->multi_index = index;
2136                 else
2137                         iuser->multi_index = 0;
2138         }
2139         if (rpass == NULL) {
2140                 rl = rr->layers.first;
2141                 if (rl)
2142                         rpass = rl->passes.first;
2143         }
2144
2145         return rpass;
2146 }
2147
2148 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
2149 {
2150         if (ima->rr) {
2151                 return ima->rr;
2152         }
2153         else if (ima->type == IMA_TYPE_R_RESULT) {
2154                 if (ima->render_slot == ima->last_render_slot)
2155                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
2156                 else
2157                         return ima->renders[ima->render_slot];
2158         }
2159         else
2160                 return NULL;
2161 }
2162
2163 void BKE_image_release_renderresult(Scene *scene, Image *ima)
2164 {
2165         if (ima->rr) ;
2166         else if (ima->type == IMA_TYPE_R_RESULT) {
2167                 if (ima->render_slot == ima->last_render_slot)
2168                         RE_ReleaseResult(RE_GetRender(scene->id.name));
2169         }
2170 }
2171
2172 void BKE_image_backup_render(Scene *scene, Image *ima)
2173 {
2174         /* called right before rendering, ima->renders contains render
2175          * result pointers for everything but the current render */
2176         Render *re = RE_GetRender(scene->id.name);
2177         int slot = ima->render_slot, last = ima->last_render_slot;
2178
2179         if (slot != last) {
2180                 if (ima->renders[slot]) {
2181                         RE_FreeRenderResult(ima->renders[slot]);
2182                         ima->renders[slot] = NULL;
2183                 }
2184
2185                 ima->renders[last] = NULL;
2186                 RE_SwapResult(re, &ima->renders[last]);
2187         }
2188
2189         ima->last_render_slot = slot;
2190 }
2191
2192 /* after imbuf load, openexr type can return with a exrhandle open */
2193 /* in that case we have to build a render-result */
2194 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
2195 {
2196
2197         ima->rr = RE_MultilayerConvert(ibuf->userdata, ibuf->x, ibuf->y);
2198
2199 #ifdef WITH_OPENEXR
2200         IMB_exr_close(ibuf->userdata);
2201 #endif
2202
2203         ibuf->userdata = NULL;
2204         if (ima->rr)
2205                 ima->rr->framenr = framenr;
2206 }
2207
2208 /* common stuff to do with images after loading */
2209 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
2210 {
2211         /* make float buffer stored in ImBuf scene linear space */
2212         IMB_colormanagement_imbuf_make_scene_linear(ibuf, &ima->colorspace_settings);
2213
2214         /* preview is NULL when it has never been used as an icon before */
2215         if (G.background == 0 && ima->preview == NULL)
2216                 BKE_icon_changed(BKE_icon_getid(&ima->id));
2217
2218         /* fields */
2219         if (ima->flag & IMA_FIELDS) {
2220                 if (ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
2221                 else de_interlace_ng(ibuf);
2222         }
2223         /* timer */
2224         ima->lastused = clock() / CLOCKS_PER_SEC;
2225
2226         ima->ok = IMA_OK_LOADED;
2227
2228 }
2229
2230 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
2231 {
2232         struct ImBuf *ibuf;
2233         char name[FILE_MAX];
2234         int flag;
2235
2236         /* XXX temp stuff? */
2237         if (ima->lastframe != frame)
2238                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2239
2240         ima->lastframe = frame;
2241         BKE_image_user_file_path(iuser, ima, name);
2242
2243         flag = IB_rect | IB_multilayer;
2244         if (ima->flag & IMA_DO_PREMUL)
2245                 flag |= IB_premul;
2246
2247         /* read ibuf */
2248         ibuf = IMB_loadiffname(name, flag);
2249
2250 #if 0
2251         if (ibuf) {
2252                 printf(AT " loaded %s\n", name);
2253         }
2254         else {
2255                 printf(AT " missed %s\n", name);
2256         }
2257 #endif
2258
2259         if (ibuf) {
2260 #ifdef WITH_OPENEXR
2261                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2262                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2263                         image_create_multilayer(ima, ibuf, frame);
2264                         ima->type = IMA_TYPE_MULTILAYER;
2265                         IMB_freeImBuf(ibuf);
2266                         ibuf = NULL;
2267                 }
2268                 else {
2269                         image_initialize_after_load(ima, ibuf);
2270                         image_assign_ibuf(ima, ibuf, 0, frame);
2271                 }
2272 #else
2273                 image_initialize_after_load(ima, ibuf);
2274                 image_assign_ibuf(ima, ibuf, 0, frame);
2275 #endif
2276         }
2277         else
2278                 ima->ok = 0;
2279
2280         if (iuser)
2281                 iuser->ok = ima->ok;
2282
2283         return ibuf;
2284 }
2285
2286 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
2287 {
2288         struct ImBuf *ibuf = NULL;
2289
2290         /* either we load from RenderResult, or we have to load a new one */
2291
2292         /* check for new RenderResult */
2293         if (ima->rr == NULL || frame != ima->rr->framenr) {
2294                 /* copy to survive not found multilayer image */
2295                 RenderResult *oldrr = ima->rr;
2296
2297                 ima->rr = NULL;
2298                 ibuf = image_load_sequence_file(ima, iuser, frame);
2299
2300                 if (ibuf) { /* actually an error */
2301                         ima->type = IMA_TYPE_IMAGE;
2302                         printf("error, multi is normal image\n");
2303                 }
2304                 // printf("loaded new result %p\n", ima->rr);
2305                 /* free result if new one found */
2306                 if (ima->rr) {
2307                         // if (oldrr) printf("freed previous result %p\n", oldrr);
2308                         if (oldrr) RE_FreeRenderResult(oldrr);
2309                 }
2310                 else {
2311                         ima->rr = oldrr;
2312                 }
2313
2314         }
2315         if (ima->rr) {
2316                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2317
2318                 if (rpass) {
2319                         // printf("load from pass %s\n", rpass->name);
2320                         /* since we free  render results, we copy the rect */
2321                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2322                         ibuf->rect_float = MEM_dupallocN(rpass->rect);
2323                         ibuf->flags |= IB_rectfloat;
2324                         ibuf->mall = IB_rectfloat;
2325                         ibuf->channels = rpass->channels;
2326                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2327
2328                         image_initialize_after_load(ima, ibuf);
2329                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : 0, frame);
2330
2331                 }
2332                 // else printf("pass not found\n");
2333         }
2334         else
2335                 ima->ok = 0;
2336
2337         if (iuser)
2338                 iuser->ok = ima->ok;
2339
2340         return ibuf;
2341 }
2342
2343
2344 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
2345 {
2346         struct ImBuf *ibuf = NULL;
2347
2348         ima->lastframe = frame;
2349
2350         if (ima->anim == NULL) {
2351                 char str[FILE_MAX];
2352
2353                 BKE_image_user_file_path(iuser, ima, str);
2354
2355                 /* FIXME: make several stream accessible in image editor, too*/
2356                 ima->anim = openanim(str, IB_rect, 0);
2357
2358                 /* let's initialize this user */
2359                 if (ima->anim && iuser && iuser->frames == 0)
2360                         iuser->frames = IMB_anim_get_duration(ima->anim,
2361                                                               IMB_TC_RECORD_RUN);
2362         }
2363
2364         if (ima->anim) {
2365                 int dur = IMB_anim_get_duration(ima->anim,
2366                                                 IMB_TC_RECORD_RUN);
2367                 int fra = frame - 1;
2368
2369                 if (fra < 0) fra = 0;
2370                 if (fra > (dur - 1)) fra = dur - 1;
2371                 ibuf = IMB_makeSingleUser(
2372                     IMB_anim_absolute(ima->anim, fra,
2373                                       IMB_TC_RECORD_RUN,
2374                                       IMB_PROXY_NONE));
2375
2376                 if (ibuf) {
2377                         image_initialize_after_load(ima, ibuf);
2378                         image_assign_ibuf(ima, ibuf, 0, frame);
2379                 }
2380                 else
2381                         ima->ok = 0;
2382         }
2383         else
2384                 ima->ok = 0;
2385
2386         if (iuser)
2387                 iuser->ok = ima->ok;
2388
2389         return ibuf;
2390 }
2391
2392 /* warning, 'iuser' can be NULL */
2393 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
2394 {
2395         struct ImBuf *ibuf;
2396         char str[FILE_MAX];
2397         int assign = 0, flag;
2398
2399         /* always ensure clean ima */
2400         image_free_buffers(ima);
2401
2402         /* is there a PackedFile with this image ? */
2403         if (ima->packedfile) {
2404                 flag = IB_rect | IB_multilayer;
2405                 if (ima->flag & IMA_DO_PREMUL) flag |= IB_premul;
2406
2407                 ibuf = IMB_ibImageFromMemory((unsigned char *)ima->packedfile->data,
2408                                              ima->packedfile->size, flag, "<packed data>");
2409         }
2410         else {
2411                 flag = IB_rect | IB_multilayer | IB_metadata;
2412                 if (ima->flag & IMA_DO_PREMUL)
2413                         flag |= IB_premul;
2414
2415                 /* get the right string */
2416                 BKE_image_user_frame_calc(iuser, cfra, 0);
2417                 BKE_image_user_file_path(iuser, ima, str);
2418
2419                 /* read ibuf */
2420                 ibuf = IMB_loadiffname(str, flag);
2421         }
2422
2423         if (ibuf) {
2424                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_get_ibuf */
2425                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2426                         image_create_multilayer(ima, ibuf, cfra);
2427                         ima->type = IMA_TYPE_MULTILAYER;
2428                         IMB_freeImBuf(ibuf);
2429                         ibuf = NULL;
2430                 }
2431                 else {
2432                         image_initialize_after_load(ima, ibuf);
2433                         assign = 1;
2434
2435                         /* check if the image is a font image... */
2436                         detectBitmapFont(ibuf);
2437
2438                         /* make packed file for autopack */
2439                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
2440                                 ima->packedfile = newPackedFile(NULL, str, ID_BLEND_PATH(G.main, &ima->id));
2441                 }
2442         }
2443         else
2444                 ima->ok = 0;
2445
2446         if (assign)
2447                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2448
2449         if (iuser)
2450                 iuser->ok = ima->ok;
2451
2452         return ibuf;
2453 }
2454
2455 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
2456 {
2457         ImBuf *ibuf = NULL;
2458
2459         if (ima->rr == NULL) {
2460                 ibuf = image_load_image_file(ima, iuser, 0);
2461                 if (ibuf) { /* actually an error */
2462                         ima->type = IMA_TYPE_IMAGE;
2463                         return ibuf;
2464                 }
2465         }
2466         if (ima->rr) {
2467                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2468
2469                 if (rpass) {
2470                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2471
2472                         image_initialize_after_load(ima, ibuf);
2473
2474                         ibuf->rect_float = rpass->rect;
2475                         ibuf->flags |= IB_rectfloat;
2476                         ibuf->channels = rpass->channels;
2477                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
2478
2479                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2480                 }
2481         }
2482
2483         if (ibuf == NULL)
2484                 ima->ok = 0;
2485         if (iuser)
2486                 iuser->ok = ima->ok;
2487
2488         return ibuf;
2489 }
2490
2491
2492 /* showing RGBA result itself (from compo/sequence) or
2493  * like exr, using layers etc */
2494 /* always returns a single ibuf, also during render progress */
2495 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
2496 {
2497         Render *re;
2498         RenderResult rres;
2499         float *rectf, *rectz;
2500         unsigned int *rect;
2501         float dither;
2502         int channels, layer, pass;
2503         ImBuf *ibuf;
2504         int from_render = (ima->render_slot == ima->last_render_slot);
2505
2506         if (!(iuser && iuser->scene))
2507                 return NULL;
2508
2509         /* if we the caller is not going to release the lock, don't give the image */
2510         if (!lock_r)
2511                 return NULL;
2512
2513         re = RE_GetRender(iuser->scene->id.name);
2514
2515         channels = 4;
2516         layer = (iuser) ? iuser->layer : 0;
2517         pass = (iuser) ? iuser->pass : 0;
2518
2519         if (from_render) {
2520                 RE_AcquireResultImage(re, &rres);
2521         }
2522         else if (ima->renders[ima->render_slot]) {
2523                 rres = *(ima->renders[ima->render_slot]);
2524                 rres.have_combined = rres.rectf != NULL;
2525         }
2526         else
2527                 memset(&rres, 0, sizeof(RenderResult));
2528
2529         if (!(rres.rectx > 0 && rres.recty > 0)) {
2530                 if (from_render)
2531                         RE_ReleaseResultImage(re);
2532                 return NULL;
2533         }
2534
2535         /* release is done in BKE_image_release_ibuf using lock_r */
2536         if (from_render) {
2537                 BLI_lock_thread(LOCK_VIEWER);
2538                 *lock_r = re;
2539         }
2540
2541         /* this gives active layer, composite or seqence result */
2542         rect = (unsigned int *)rres.rect32;
2543         rectf = rres.rectf;
2544         rectz = rres.rectz;
2545         dither = iuser->scene->r.dither_intensity;
2546
2547         /* combined layer gets added as first layer */
2548         if (rres.have_combined && layer == 0) ;
2549         else if (rres.layers.first) {
2550                 RenderLayer *rl = BLI_findlink(&rres.layers, layer - (rres.have_combined ? 1 : 0));
2551                 if (rl) {
2552                         RenderPass *rpass;
2553
2554                         /* there's no combined pass, is in renderlayer itself */
2555                         if (pass == 0) {
2556                                 rectf = rl->rectf;
2557                         }
2558                         else {
2559                                 rpass = BLI_findlink(&rl->passes, pass - 1);
2560                                 if (rpass) {
2561                                         channels = rpass->channels;
2562                                         rectf = rpass->rect;
2563                                         dither = 0.0f; /* don't dither passes */
2564                                 }
2565                         }
2566
2567                         for (rpass = rl->passes.first; rpass; rpass = rpass->next)
2568                                 if (rpass->passtype == SCE_PASS_Z)
2569                                         rectz = rpass->rect;
2570                 }
2571         }
2572
2573         ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2574
2575         /* make ibuf if needed, and initialize it */
2576         if (ibuf == NULL) {
2577                 ibuf = IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
2578                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2579         }
2580
2581         /* invalidate color managed buffers if render result changed */
2582         BLI_lock_thread(LOCK_COLORMANAGE);
2583         if (ibuf->x != rres.rectx || ibuf->y != rres.recty || ibuf->rect_float != rectf) {
2584                 IMB_display_buffer_invalidate(ibuf);
2585         }
2586
2587         ibuf->x = rres.rectx;
2588         ibuf->y = rres.recty;
2589
2590         /* free rect buffer if float buffer changes, so it can be recreated with
2591          * the updated result, and also in case we got byte buffer from sequencer,
2592          * so we don't keep reference to freed buffer */
2593         
2594         /* todo: this fix breaks save buffers render progress 
2595            if (ibuf->rect_float != rectf || rect || !rectf) */
2596
2597         if (ibuf->rect_float != rectf || rect)
2598                 imb_freerectImBuf(ibuf);
2599
2600         if (rect)
2601                 ibuf->rect = rect;
2602
2603         if (rectf) {
2604                 ibuf->rect_float = rectf;
2605                 ibuf->flags |= IB_rectfloat;
2606                 ibuf->channels = channels;
2607         }
2608         else {
2609                 ibuf->rect_float = NULL;
2610                 ibuf->flags &= ~IB_rectfloat;
2611         }
2612
2613         if (rectz) {
2614                 ibuf->zbuf_float = rectz;
2615                 ibuf->flags |= IB_zbuffloat;
2616         }
2617         else {
2618                 ibuf->zbuf_float = NULL;
2619                 ibuf->flags &= ~IB_zbuffloat;
2620         }
2621
2622         BLI_unlock_thread(LOCK_COLORMANAGE);
2623
2624         /* since its possible to access the buffer from the image directly, set the profile [#25073] */
2625         ibuf->profile = (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT) ? IB_PROFILE_LINEAR_RGB : IB_PROFILE_NONE;
2626         ibuf->dither = dither;
2627
2628         if (iuser->scene->r.color_mgt_flag & R_COLOR_MANAGEMENT_PREDIVIDE) {
2629                 ibuf->flags |= IB_cm_predivide;
2630                 ima->flag |= IMA_CM_PREDIVIDE;
2631         }
2632         else {
2633                 ibuf->flags &= ~IB_cm_predivide;
2634                 ima->flag &= ~IMA_CM_PREDIVIDE;
2635         }
2636
2637         ima->ok = IMA_OK_LOADED;
2638
2639         return ibuf;
2640 }
2641
2642 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2643 {
2644         ImBuf *ibuf = NULL;
2645         int frame = 0, index = 0;
2646
2647         /* see if we already have an appropriate ibuf, with image source and type */
2648         if (ima->source == IMA_SRC_MOVIE) {
2649                 frame = iuser ? iuser->framenr : ima->lastframe;
2650                 ibuf = image_get_ibuf(ima, 0, frame);
2651                 /* XXX temp stuff? */
2652                 if (ima->lastframe != frame)
2653                         ima->tpageflag |= IMA_TPAGE_REFRESH;
2654                 ima->lastframe = frame;
2655         }
2656         else if (ima->source == IMA_SRC_SEQUENCE) {
2657                 if (ima->type == IMA_TYPE_IMAGE) {
2658                         frame = iuser ? iuser->framenr : ima->lastframe;
2659                         ibuf = image_get_ibuf(ima, 0, frame);
2660
2661                         /* XXX temp stuff? */
2662                         if (ima->lastframe != frame) {
2663                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2664                         }
2665                         ima->lastframe = frame;
2666                 }
2667                 else if (ima->type == IMA_TYPE_MULTILAYER) {
2668                         frame = iuser ? iuser->framenr : ima->lastframe;
2669                         index = iuser ? iuser->multi_index : IMA_NO_INDEX;
2670                         ibuf = image_get_ibuf(ima, index, frame);
2671                 }
2672         }
2673         else if (ima->source == IMA_SRC_FILE) {
2674                 if (ima->type == IMA_TYPE_IMAGE)
2675                         ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2676                 else if (ima->type == IMA_TYPE_MULTILAYER)
2677                         ibuf = image_get_ibuf(ima, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2678         }
2679         else if (ima->source == IMA_SRC_GENERATED) {
2680                 ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2681         }
2682         else if (ima->source == IMA_SRC_VIEWER) {
2683                 /* always verify entirely, not that this shouldn't happen
2684                  * as part of texture sampling in rendering anyway, so not
2685                  * a big bottleneck */
2686         }
2687
2688         *frame_r = frame;
2689         *index_r = index;
2690
2691         return ibuf;
2692 }
2693
2694 /* Checks optional ImageUser and verifies/creates ImBuf. */
2695 /* use this one if you want to get a render result in progress,
2696  * if not, use BKE_image_get_ibuf which doesn't require a release */
2697 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2698 {
2699         ImBuf *ibuf = NULL;
2700         float color[] = {0, 0, 0, 1};
2701         int frame = 0, index = 0;
2702
2703         /* This function is intended to be thread-safe. It postpones the mutex lock
2704          * until it needs to load the image, if the image is already there it
2705          * should just get the pointer and return. The reason is that a lot of mutex
2706          * locks appears to be very slow on certain multicore macs, causing a render
2707          * with image textures to actually slow down as more threads are used.
2708          *
2709          * Note that all the image loading functions should also make sure they do
2710          * things in a threadsafe way for image_get_ibuf_threadsafe to work correct.
2711          * That means, the last two steps must be, 1) add the ibuf to the list and
2712          * 2) set ima/iuser->ok to 0 to IMA_OK_LOADED */
2713
2714         if (lock_r)
2715                 *lock_r = NULL;
2716
2717         /* quick reject tests */
2718         if (ima == NULL)
2719                 return NULL;
2720         if (iuser) {
2721                 if (iuser->ok == 0)
2722                         return NULL;
2723         }
2724         else if (ima->ok == 0)
2725                 return NULL;
2726
2727         /* try to get the ibuf without locking */
2728         ibuf = image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2729
2730         if (ibuf == NULL) {
2731                 /* couldn't get ibuf and image is not ok, so let's lock and try to
2732                  * load the image */
2733                 BLI_lock_thread(LOCK_IMAGE);
2734
2735                 /* need to check ok flag and loading ibuf again, because the situation
2736                  * might have changed in the meantime */
2737                 if (iuser) {
2738                         if (iuser->ok == 0) {
2739                                 BLI_unlock_thread(LOCK_IMAGE);
2740                                 return NULL;
2741                         }
2742                 }
2743                 else if (ima->ok == 0) {
2744                         BLI_unlock_thread(LOCK_IMAGE);
2745                         return NULL;
2746                 }
2747
2748                 ibuf = image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2749
2750                 if (ibuf == NULL) {
2751                         /* we are sure we have to load the ibuf, using source and type */
2752                         if (ima->source == IMA_SRC_MOVIE) {
2753                                 /* source is from single file, use flipbook to store ibuf */
2754                                 ibuf = image_load_movie_file(ima, iuser, frame);
2755                         }
2756                         else if (ima->source == IMA_SRC_SEQUENCE) {
2757                                 if (ima->type == IMA_TYPE_IMAGE) {
2758                                         /* regular files, ibufs in flipbook, allows saving */
2759                                         ibuf = image_load_sequence_file(ima, iuser, frame);
2760                                 }
2761                                 /* no else; on load the ima type can change */
2762                                 if (ima->type == IMA_TYPE_MULTILAYER) {
2763                                         /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2764                                         ibuf = image_load_sequence_multilayer(ima, iuser, frame);
2765                                 }
2766                         }
2767                         else if (ima->source == IMA_SRC_FILE) {
2768
2769                                 if (ima->type == IMA_TYPE_IMAGE)
2770                                         ibuf = image_load_image_file(ima, iuser, frame);  /* cfra only for '#', this global is OK */
2771                                 /* no else; on load the ima type can change */
2772                                 if (ima->type == IMA_TYPE_MULTILAYER)
2773                                         /* keeps render result, stores ibufs in listbase, allows saving */
2774                                         ibuf = image_get_ibuf_multilayer(ima, iuser);
2775
2776                         }
2777                         else if (ima->source == IMA_SRC_GENERATED) {
2778                                 /* generated is: ibuf is allocated dynamically */
2779                                 /* UV testgrid or black or solid etc */
2780                                 if (ima->gen_x == 0) ima->gen_x = 1024;
2781                                 if (ima->gen_y == 0) ima->gen_y = 1024;
2782                                 ibuf = add_ibuf_size(ima->gen_x, ima->gen_y, ima->name, 24, (ima->gen_flag & IMA_GEN_FLOAT) != 0, ima->gen_type, color);
2783                                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2784                                 ima->ok = IMA_OK_LOADED;
2785                         }
2786                         else if (ima->source == IMA_SRC_VIEWER) {
2787                                 if (ima->type == IMA_TYPE_R_RESULT) {
2788                                         /* always verify entirely, and potentially
2789                                          * returns pointer to release later */
2790                                         ibuf = image_get_render_result(ima, iuser, lock_r);
2791                                 }
2792                                 else if (ima->type == IMA_TYPE_COMPOSITE) {
2793                                         /* requires lock/unlock, otherwise don't return image */
2794                                         if (lock_r) {
2795                                                 /* unlock in BKE_image_release_ibuf */
2796                                                 BLI_lock_thread(LOCK_VIEWER);
2797                                                 *lock_r = ima;
2798
2799                                                 /* XXX anim play for viewer nodes not yet supported */
2800                                                 frame = 0; // XXX iuser?iuser->framenr:0;
2801                                                 ibuf = image_get_ibuf(ima, 0, frame);
2802
2803                                                 if (!ibuf) {
2804                                                         /* Composite Viewer, all handled in compositor */
2805                                                         /* fake ibuf, will be filled in compositor */
2806                                                         ibuf = IMB_allocImBuf(256, 256, 32, IB_rect);
2807                                                         image_assign_ibuf(ima, ibuf, 0, frame);
2808                                                 }
2809                                         }
2810                                 }
2811                         }
2812                 }
2813
2814                 BLI_unlock_thread(LOCK_IMAGE);
2815         }
2816
2817         BKE_image_tag_time(ima);
2818
2819         return ibuf;
2820 }
2821
2822 void BKE_image_release_ibuf(Image *ima, void *lock)
2823 {
2824         /* for getting image during threaded render / compositing, need to release */
2825         if (lock == ima) {
2826                 BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
2827         }
2828         else if (lock) {
2829                 RE_ReleaseResultImage(lock); /* render result */
2830                 BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
2831         }
2832 }
2833
2834 /* warning, this can allocate generated images */
2835 ImBuf *BKE_image_get_ibuf(Image *ima, ImageUser *iuser)
2836 {
2837         /* here (+fie_ima/2-1) makes sure that division happens correctly */
2838         return BKE_image_acquire_ibuf(ima, iuser, NULL);
2839 }
2840
2841 int BKE_image_user_frame_get(const ImageUser *iuser, int cfra, int fieldnr, short *r_is_in_range)
2842 {
2843         const int len = (iuser->fie_ima * iuser->frames) / 2;
2844
2845         if (r_is_in_range) {
2846                 *r_is_in_range = FALSE;
2847         }
2848
2849         if (len == 0) {
2850                 return 0;
2851         }
2852         else {
2853                 int framenr;
2854                 cfra = cfra - iuser->sfra + 1;
2855
2856                 /* cyclic */
2857                 if (iuser->cycl) {
2858                         cfra = ((cfra) % len);
2859                         if (cfra < 0) cfra += len;
2860                         if (cfra == 0) cfra = len;
2861
2862                         if (r_is_in_range) {
2863                                 *r_is_in_range = TRUE;
2864                         }
2865                 }
2866
2867                 if (cfra < 0) {
2868                         cfra = 0;
2869                 }
2870                 else if (cfra > len) {
2871                         cfra = len;
2872                 }
2873                 else {
2874                         if (r_is_in_range) {
2875                                 *r_is_in_range = TRUE;
2876                         }
2877                 }
2878
2879                 /* convert current frame to current field */
2880                 cfra = 2 * (cfra);
2881                 if (fieldnr) cfra++;
2882
2883                 /* transform to images space */
2884                 framenr = (cfra + iuser->fie_ima - 2) / iuser->fie_ima;
2885                 if (framenr > iuser->frames) framenr = iuser->frames;
2886
2887                 if (iuser->cycl) {
2888                         framenr = ((framenr) % len);
2889                         while (framenr < 0) framenr += len;
2890                         if (framenr == 0) framenr = len;
2891                 }
2892
2893                 /* important to apply after else we cant loop on frames 100 - 110 for eg. */
2894                 framenr += iuser->offset;
2895
2896                 return framenr;
2897         }
2898 }
2899
2900 void BKE_image_user_frame_calc(ImageUser *iuser, int cfra, int fieldnr)
2901 {
2902         if (iuser) {
2903                 short is_in_range;
2904                 const int framenr = BKE_image_user_frame_get(iuser, cfra, fieldnr, &is_in_range);
2905
2906                 if (is_in_range) {
2907                         iuser->flag |= IMA_USER_FRAME_IN_RANGE;
2908                 }
2909                 else {
2910                         iuser->flag &= ~IMA_USER_FRAME_IN_RANGE;
2911                 }
2912
2913                 /* allows image users to handle redraws */
2914                 if (iuser->flag & IMA_ANIM_ALWAYS)
2915                         if (framenr != iuser->framenr)
2916                                 iuser->flag |= IMA_ANIM_REFRESHED;
2917
2918                 iuser->framenr = framenr;
2919                 if (iuser->ok == 0) iuser->ok = 1;
2920         }
2921 }
2922
2923 void BKE_image_user_check_frame_calc(ImageUser *iuser, int cfra, int fieldnr)
2924 {
2925         if ((iuser->flag & IMA_ANIM_ALWAYS) || (iuser->flag & IMA_NEED_FRAME_RECALC)) {
2926                 BKE_image_user_frame_calc(iuser, cfra, fieldnr);
2927
2928                 iuser->flag &= ~IMA_NEED_FRAME_RECALC;
2929         }
2930 }
2931
2932 void BKE_image_user_file_path(ImageUser *iuser, Image *ima, char *filepath)
2933 {
2934         BLI_strncpy(filepath, ima->name, FILE_MAX);
2935
2936         if (ima->source == IMA_SRC_SEQUENCE) {
2937                 char head[FILE_MAX], tail[FILE_MAX];
2938                 unsigned short numlen;
2939                 int frame = iuser ? iuser->framenr : ima->lastframe;
2940
2941                 BLI_stringdec(filepath, head, tail, &numlen);
2942                 BLI_stringenc(filepath, head, tail, numlen, frame);
2943         }
2944
2945         BLI_path_abs(filepath, ID_BLEND_PATH(G.main, &ima->id));
2946 }
2947
2948 int BKE_image_has_alpha(struct Image *image)
2949 {
2950         ImBuf *ibuf;
2951         void *lock;
2952         int planes;
2953
2954         ibuf = BKE_image_acquire_ibuf(image, NULL, &lock);
2955         planes = (ibuf ? ibuf->planes : 0);
2956         BKE_image_release_ibuf(image, lock);
2957
2958         if (planes == 32)
2959                 return 1;
2960         else
2961                 return 0;
2962 }