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