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