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