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