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