Code cleanup: Typo fix for image function, patch by kgeogeo.
[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 BUFF_MARGIN_X 2
1640 #define BUFF_MARGIN_Y 1
1641
1642         if (!rect && !rectf)
1643                 return;
1644
1645         display_device = scene->display_settings.display_device;
1646         display = IMB_colormanagement_display_get_named(display_device);
1647
1648         stampdata(scene, camera, &stamp_data, 1);
1649
1650         /* TODO, do_versions */
1651         if (scene->r.stamp_font_id < 8)
1652                 scene->r.stamp_font_id = 12;
1653
1654         /* set before return */
1655         BLF_size(mono, scene->r.stamp_font_id, 72);
1656
1657         BLF_buffer(mono, rectf, rect, width, height, channels, display);
1658         BLF_buffer_col(mono, scene->r.fg_stamp[0], scene->r.fg_stamp[1], scene->r.fg_stamp[2], 1.0);
1659         pad = BLF_width_max(mono);
1660
1661         /* use 'h_fixed' rather than 'h', aligns better */
1662         h_fixed = BLF_height_max(mono);
1663         y_ofs = -BLF_descender(mono);
1664
1665         x = 0;
1666         y = height;
1667
1668         if (stamp_data.file[0]) {
1669                 /* Top left corner */
1670                 BLF_width_and_height(mono, stamp_data.file, &w, &h); h = h_fixed;
1671                 y -= h;
1672
1673                 /* also a little of space to the background. */
1674                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1675                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1676
1677                 /* and draw the text. */
1678                 BLF_position(mono, x, y + y_ofs, 0.0);
1679                 BLF_draw_buffer(mono, stamp_data.file);
1680
1681                 /* the extra pixel for background. */
1682                 y -= BUFF_MARGIN_Y * 2;
1683         }
1684
1685         /* Top left corner, below File */
1686         if (stamp_data.note[0]) {
1687                 BLF_width_and_height(mono, stamp_data.note, &w, &h); h = h_fixed;
1688                 y -= h;
1689
1690                 /* and space for background. */
1691                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1692                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1693
1694                 BLF_position(mono, x, y + y_ofs, 0.0);
1695                 BLF_draw_buffer(mono, stamp_data.note);
1696
1697                 /* the extra pixel for background. */
1698                 y -= BUFF_MARGIN_Y * 2;
1699         }
1700
1701         /* Top left corner, below File (or Note) */
1702         if (stamp_data.date[0]) {
1703                 BLF_width_and_height(mono, stamp_data.date, &w, &h); h = h_fixed;
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 (stamp_data.rendertime[0]) {
1719                 BLF_width_and_height(mono, stamp_data.rendertime, &w, &h); h = h_fixed;
1720                 y -= h;
1721
1722                 /* and space for background. */
1723                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1724                                   0, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1725
1726                 BLF_position(mono, x, y + y_ofs, 0.0);
1727                 BLF_draw_buffer(mono, stamp_data.rendertime);
1728         }
1729
1730         x = 0;
1731         y = 0;
1732
1733         /* Bottom left corner, leaving space for timing */
1734         if (stamp_data.marker[0]) {
1735                 BLF_width_and_height(mono, stamp_data.marker, &w, &h); h = h_fixed;
1736
1737                 /* extra space for background. */
1738                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp,  display,
1739                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1740
1741                 /* and pad the text. */
1742                 BLF_position(mono, x, y + y_ofs, 0.0);
1743                 BLF_draw_buffer(mono, stamp_data.marker);
1744
1745                 /* space width. */
1746                 x += w + pad;
1747         }
1748
1749         /* Left bottom corner */
1750         if (stamp_data.time[0]) {
1751                 BLF_width_and_height(mono, stamp_data.time, &w, &h); h = h_fixed;
1752
1753                 /* extra space for background */
1754                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1755                                   x - BUFF_MARGIN_X, y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1756
1757                 /* and pad the text. */
1758                 BLF_position(mono, x, y + y_ofs, 0.0);
1759                 BLF_draw_buffer(mono, stamp_data.time);
1760
1761                 /* space width. */
1762                 x += w + pad;
1763         }
1764
1765         if (stamp_data.frame[0]) {
1766                 BLF_width_and_height(mono, stamp_data.frame, &w, &h); h = h_fixed;
1767
1768                 /* extra space for background. */
1769                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1770                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1771
1772                 /* and pad the text. */
1773                 BLF_position(mono, x, y + y_ofs, 0.0);
1774                 BLF_draw_buffer(mono, stamp_data.frame);
1775
1776                 /* space width. */
1777                 x += w + pad;
1778         }
1779
1780         if (stamp_data.camera[0]) {
1781                 BLF_width_and_height(mono, stamp_data.camera, &w, &h); h = h_fixed;
1782
1783                 /* extra space for background. */
1784                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1785                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1786                 BLF_position(mono, x, y + y_ofs, 0.0);
1787                 BLF_draw_buffer(mono, stamp_data.camera);
1788
1789                 /* space width. */
1790                 x += w + pad;
1791         }
1792
1793         if (stamp_data.cameralens[0]) {
1794                 BLF_width_and_height(mono, stamp_data.cameralens, &w, &h); h = h_fixed;
1795
1796                 /* extra space for background. */
1797                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1798                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1799                 BLF_position(mono, x, y + y_ofs, 0.0);
1800                 BLF_draw_buffer(mono, stamp_data.cameralens);
1801         }
1802
1803         if (stamp_data.scene[0]) {
1804                 BLF_width_and_height(mono, stamp_data.scene, &w, &h); h = h_fixed;
1805
1806                 /* Bottom right corner, with an extra space because blenfont is too strict! */
1807                 x = width - w - 2;
1808
1809                 /* extra space for background. */
1810                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1811                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1812
1813                 /* and pad the text. */
1814                 BLF_position(mono, x, y + y_ofs, 0.0);
1815                 BLF_draw_buffer(mono, stamp_data.scene);
1816         }
1817
1818         if (stamp_data.strip[0]) {
1819                 BLF_width_and_height(mono, stamp_data.strip, &w, &h); h = h_fixed;
1820
1821                 /* Top right corner, with an extra space because blenfont is too strict! */
1822                 x = width - w - pad;
1823                 y = height - h;
1824
1825                 /* extra space for background. */
1826                 buf_rectfill_area(rect, rectf, width, height, scene->r.bg_stamp, display,
1827                                   x - BUFF_MARGIN_X, y - BUFF_MARGIN_Y, x + w + BUFF_MARGIN_X, y + h + BUFF_MARGIN_Y);
1828
1829                 BLF_position(mono, x, y + y_ofs, 0.0);
1830                 BLF_draw_buffer(mono, stamp_data.strip);
1831         }
1832
1833         /* cleanup the buffer. */
1834         BLF_buffer(mono, NULL, NULL, 0, 0, 0, NULL);
1835
1836 #undef BUFF_MARGIN_X
1837 #undef BUFF_MARGIN_Y
1838 }
1839
1840 void BKE_imbuf_stamp_info(Scene *scene, Object *camera, struct ImBuf *ibuf)
1841 {
1842         struct StampData stamp_data;
1843
1844         if (!ibuf) return;
1845
1846         /* fill all the data values, no prefix */
1847         stampdata(scene, camera, &stamp_data, 0);
1848
1849         if (stamp_data.file[0]) IMB_metadata_change_field(ibuf, "File",        stamp_data.file);
1850         if (stamp_data.note[0]) IMB_metadata_change_field(ibuf, "Note",        stamp_data.note);
1851         if (stamp_data.date[0]) IMB_metadata_change_field(ibuf, "Date",        stamp_data.date);
1852         if (stamp_data.marker[0]) IMB_metadata_change_field(ibuf, "Marker",    stamp_data.marker);
1853         if (stamp_data.time[0]) IMB_metadata_change_field(ibuf, "Time",        stamp_data.time);
1854         if (stamp_data.frame[0]) IMB_metadata_change_field(ibuf, "Frame",      stamp_data.frame);
1855         if (stamp_data.camera[0]) IMB_metadata_change_field(ibuf, "Camera",    stamp_data.camera);
1856         if (stamp_data.cameralens[0]) IMB_metadata_change_field(ibuf, "Lens",  stamp_data.cameralens);
1857         if (stamp_data.scene[0]) IMB_metadata_change_field(ibuf, "Scene",      stamp_data.scene);
1858         if (stamp_data.strip[0]) IMB_metadata_change_field(ibuf, "Strip",      stamp_data.strip);
1859         if (stamp_data.rendertime[0]) IMB_metadata_change_field(ibuf, "RenderTime", stamp_data.rendertime);
1860 }
1861
1862 int BKE_imbuf_alpha_test(ImBuf *ibuf)
1863 {
1864         int tot;
1865         if (ibuf->rect_float) {
1866                 float *buf = ibuf->rect_float;
1867                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1868                         if (buf[3] < 1.0f) {
1869                                 return TRUE;
1870                         }
1871                 }
1872         }
1873         else if (ibuf->rect) {
1874                 unsigned char *buf = (unsigned char *)ibuf->rect;
1875                 for (tot = ibuf->x * ibuf->y; tot--; buf += 4) {
1876                         if (buf[3] != 255) {
1877                                 return TRUE;
1878                         }
1879                 }
1880         }
1881
1882         return FALSE;
1883 }
1884
1885 /* note: imf->planes is ignored here, its assumed the image channels
1886  * are already set */
1887 int BKE_imbuf_write(ImBuf *ibuf, const char *name, ImageFormatData *imf)
1888 {
1889         char imtype = imf->imtype;
1890         char compress = imf->compress;
1891         char quality = imf->quality;
1892
1893         int ok;
1894
1895         if (imtype == R_IMF_IMTYPE_IRIS) {
1896                 ibuf->ftype = IMAGIC;
1897         }
1898 #ifdef WITH_HDR
1899         else if (imtype == R_IMF_IMTYPE_RADHDR) {
1900                 ibuf->ftype = RADHDR;
1901         }
1902 #endif
1903         else if (ELEM5(imtype, R_IMF_IMTYPE_PNG, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_THEORA, R_IMF_IMTYPE_XVID)) {
1904                 ibuf->ftype = PNG;
1905
1906                 if (imtype == R_IMF_IMTYPE_PNG) {
1907                         if (imf->depth == R_IMF_CHAN_DEPTH_16)
1908                                 ibuf->ftype |= PNG_16BIT;
1909
1910                         ibuf->ftype |= compress;
1911                 }
1912
1913         }
1914 #ifdef WITH_DDS
1915         else if (imtype == R_IMF_IMTYPE_DDS) {
1916                 ibuf->ftype = DDS;
1917         }
1918 #endif
1919         else if (imtype == R_IMF_IMTYPE_BMP) {
1920                 ibuf->ftype = BMP;
1921         }
1922 #ifdef WITH_TIFF
1923         else if (imtype == R_IMF_IMTYPE_TIFF) {
1924                 ibuf->ftype = TIF;
1925
1926                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1927                         ibuf->ftype |= TIF_16BIT;
1928         }
1929 #endif
1930 #ifdef WITH_OPENEXR
1931         else if (imtype == R_IMF_IMTYPE_OPENEXR || imtype == R_IMF_IMTYPE_MULTILAYER) {
1932                 ibuf->ftype = OPENEXR;
1933                 if (imf->depth == R_IMF_CHAN_DEPTH_16)
1934                         ibuf->ftype |= OPENEXR_HALF;
1935                 ibuf->ftype |= (imf->exr_codec & OPENEXR_COMPRESS);
1936
1937                 if (!(imf->flag & R_IMF_FLAG_ZBUF))
1938                         ibuf->zbuf_float = NULL;    /* signal for exr saving */
1939
1940         }
1941 #endif
1942 #ifdef WITH_CINEON
1943         else if (imtype == R_IMF_IMTYPE_CINEON) {
1944                 ibuf->ftype = CINEON;
1945                 if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
1946                         ibuf->ftype |= CINEON_LOG;
1947                 }
1948                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1949                         ibuf->ftype |= CINEON_16BIT;
1950                 }
1951                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1952                         ibuf->ftype |= CINEON_12BIT;
1953                 }
1954                 else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
1955                         ibuf->ftype |= CINEON_10BIT;
1956                 }
1957         }
1958         else if (imtype == R_IMF_IMTYPE_DPX) {
1959                 ibuf->ftype = DPX;
1960                 if (imf->cineon_flag & R_IMF_CINEON_FLAG_LOG) {
1961                         ibuf->ftype |= CINEON_LOG;
1962                 }
1963                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1964                         ibuf->ftype |= CINEON_16BIT;
1965                 }
1966                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1967                         ibuf->ftype |= CINEON_12BIT;
1968                 }
1969                 else if (imf->depth == R_IMF_CHAN_DEPTH_10) {
1970                         ibuf->ftype |= CINEON_10BIT;
1971                 }
1972         }
1973 #endif
1974         else if (imtype == R_IMF_IMTYPE_TARGA) {
1975                 ibuf->ftype = TGA;
1976         }
1977         else if (imtype == R_IMF_IMTYPE_RAWTGA) {
1978                 ibuf->ftype = RAWTGA;
1979         }
1980 #ifdef WITH_OPENJPEG
1981         else if (imtype == R_IMF_IMTYPE_JP2) {
1982                 if (quality < 10) quality = 90;
1983                 ibuf->ftype = JP2 | quality;
1984
1985                 if (imf->depth == R_IMF_CHAN_DEPTH_16) {
1986                         ibuf->ftype |= JP2_16BIT;
1987                 }
1988                 else if (imf->depth == R_IMF_CHAN_DEPTH_12) {
1989                         ibuf->ftype |= JP2_12BIT;
1990                 }
1991
1992                 if (imf->jp2_flag & R_IMF_JP2_FLAG_YCC) {
1993                         ibuf->ftype |= JP2_YCC;
1994                 }
1995
1996                 if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_PRESET) {
1997                         ibuf->ftype |= JP2_CINE;
1998                         if (imf->jp2_flag & R_IMF_JP2_FLAG_CINE_48)
1999                                 ibuf->ftype |= JP2_CINE_48FPS;
2000                 }
2001
2002                 if (imf->jp2_codec == R_IMF_JP2_CODEC_JP2)
2003                         ibuf->ftype |= JP2_JP2;
2004                 else if (imf->jp2_codec == R_IMF_JP2_CODEC_J2K)
2005                         ibuf->ftype |= JP2_J2K;
2006                 else
2007                         BLI_assert(!"Unsupported jp2 codec was specified in im_format->jp2_codec");
2008         }
2009 #endif
2010         else {
2011                 /* R_IMF_IMTYPE_JPEG90, etc. default we save jpegs */
2012                 if (quality < 10) quality = 90;
2013                 ibuf->ftype = JPG | quality;
2014         }
2015
2016         BLI_make_existing_file(name);
2017
2018         ok = IMB_saveiff(ibuf, name, IB_rect | IB_zbuf | IB_zbuffloat);
2019         if (ok == 0) {
2020                 perror(name);
2021         }
2022
2023         return(ok);
2024 }
2025
2026 /* same as BKE_imbuf_write() but crappy workaround not to perminantly modify
2027  * _some_, values in the imbuf */
2028 int BKE_imbuf_write_as(ImBuf *ibuf, const char *name, ImageFormatData *imf,
2029                        const short save_copy)
2030 {
2031         ImBuf ibuf_back = *ibuf;
2032         int ok;
2033
2034         /* all data is rgba anyway,
2035          * this just controls how to save for some formats */
2036         ibuf->planes = imf->planes;
2037
2038         ok = BKE_imbuf_write(ibuf, name, imf);
2039
2040         if (save_copy) {
2041                 /* note that we are not restoring _all_ settings */
2042                 ibuf->planes = ibuf_back.planes;
2043                 ibuf->ftype =  ibuf_back.ftype;
2044         }
2045
2046         return ok;
2047 }
2048
2049 int BKE_imbuf_write_stamp(Scene *scene, struct Object *camera, ImBuf *ibuf, const char *name, struct ImageFormatData *imf)
2050 {
2051         if (scene && scene->r.stamp & R_STAMP_ALL)
2052                 BKE_imbuf_stamp_info(scene, camera, ibuf);
2053
2054         return BKE_imbuf_write(ibuf, name, imf);
2055 }
2056
2057
2058 static void do_makepicstring(char *string, const char *base, const char *relbase, int frame, const char imtype,
2059                              const ImageFormatData *im_format, const short use_ext, const short use_frames)
2060 {
2061         if (string == NULL) return;
2062         BLI_strncpy(string, base, FILE_MAX - 10);   /* weak assumption */
2063         BLI_path_abs(string, relbase);
2064
2065         if (use_frames)
2066                 BLI_path_frame(string, frame, 4);
2067
2068         if (use_ext)
2069                 do_add_image_extension(string, imtype, im_format);
2070 }
2071
2072 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)
2073 {
2074         do_makepicstring(string, base, relbase, frame, im_format->imtype, im_format, use_ext, use_frames);
2075 }
2076
2077 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)
2078 {
2079         do_makepicstring(string, base, relbase, frame, imtype, NULL, use_ext, use_frames);
2080 }
2081
2082 /* used by sequencer too */
2083 struct anim *openanim(const char *name, int flags, int streamindex, char colorspace[IMA_MAX_SPACE])
2084 {
2085         struct anim *anim;
2086         struct ImBuf *ibuf;
2087
2088         anim = IMB_open_anim(name, flags, streamindex, colorspace);
2089         if (anim == NULL) return NULL;
2090
2091         ibuf = IMB_anim_absolute(anim, 0, IMB_TC_NONE, IMB_PROXY_NONE);
2092         if (ibuf == NULL) {
2093                 if (BLI_exists(name))
2094                         printf("not an anim: %s\n", name);
2095                 else
2096                         printf("anim file doesn't exist: %s\n", name);
2097                 IMB_free_anim(anim);
2098                 return NULL;
2099         }
2100         IMB_freeImBuf(ibuf);
2101
2102         return(anim);
2103 }
2104
2105 /* ************************* New Image API *************** */
2106
2107
2108 /* Notes about Image storage
2109  * - packedfile
2110  *   -> written in .blend
2111  * - filename
2112  *   -> written in .blend
2113  * - movie
2114  *   -> comes from packedfile or filename
2115  * - renderresult
2116  *   -> comes from packedfile or filename
2117  * - listbase
2118  *   -> ibufs from exrhandle
2119  * - flipbook array
2120  *   -> ibufs come from movie, temporary renderresult or sequence
2121  * - ibuf
2122  *   -> comes from packedfile or filename or generated
2123  */
2124
2125
2126 /* forces existence of 1 Image for renderout or nodes, returns Image */
2127 /* name is only for default, when making new one */
2128 Image *BKE_image_verify_viewer(int type, const char *name)
2129 {
2130         Image *ima;
2131
2132         for (ima = G.main->image.first; ima; ima = ima->id.next)
2133                 if (ima->source == IMA_SRC_VIEWER)
2134                         if (ima->type == type)
2135                                 break;
2136
2137         if (ima == NULL)
2138                 ima = image_alloc(G.main, name, IMA_SRC_VIEWER, type);
2139
2140         /* happens on reload, imagewindow cannot be image user when hidden*/
2141         if (ima->id.us == 0)
2142                 id_us_plus(&ima->id);
2143
2144         return ima;
2145 }
2146
2147 void BKE_image_assign_ibuf(Image *ima, ImBuf *ibuf)
2148 {
2149         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2150 }
2151
2152 void BKE_image_walk_all_users(const Main *mainp, void *customdata,
2153                               void callback(Image *ima, ImageUser *iuser, void *customdata))
2154 {
2155         wmWindowManager *wm;
2156         wmWindow *win;
2157         Tex *tex;
2158
2159         /* texture users */
2160         for (tex = mainp->tex.first; tex; tex = tex->id.next) {
2161                 if (tex->type == TEX_IMAGE && tex->ima) {
2162                         callback(tex->ima, &tex->iuser, customdata);
2163                 }
2164         }
2165
2166         /* image window, compo node users */
2167         for (wm = mainp->wm.first; wm; wm = wm->id.next) { /* only 1 wm */
2168                 for (win = wm->windows.first; win; win = win->next) {
2169                         ScrArea *sa;
2170                         for (sa = win->screen->areabase.first; sa; sa = sa->next) {
2171                                 if (sa->spacetype == SPACE_VIEW3D) {
2172                                         View3D *v3d = sa->spacedata.first;
2173                                         BGpic *bgpic;
2174                                         for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
2175                                                 callback(bgpic->ima, &bgpic->iuser, customdata);
2176                                         }
2177                                 }
2178                                 else if (sa->spacetype == SPACE_IMAGE) {
2179                                         SpaceImage *sima = sa->spacedata.first;
2180                                         callback(sima->image, &sima->iuser, customdata);
2181                                 }
2182                                 else if (sa->spacetype == SPACE_NODE) {
2183                                         SpaceNode *snode = sa->spacedata.first;
2184                                         if (snode->nodetree && snode->nodetree->type == NTREE_COMPOSIT) {
2185                                                 bNode *node;
2186                                                 for (node = snode->nodetree->nodes.first; node; node = node->next) {
2187                                                         if (node->id && node->type == CMP_NODE_IMAGE) {
2188                                                                 Image *ima = (Image *)node->id;
2189                                                                 ImageUser *iuser = node->storage;
2190                                                                 callback(ima, iuser, customdata);
2191                                                         }
2192                                                 }
2193                                         }
2194                                 }
2195                         }
2196                 }
2197         }
2198 }
2199
2200 static void image_tag_frame_recalc(Image *ima, ImageUser *iuser, void *customdata)
2201 {
2202         Image *changed_image = customdata;
2203
2204         if (ima == changed_image && ELEM(ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
2205                 iuser->flag |= IMA_NEED_FRAME_RECALC;
2206         }
2207 }
2208
2209 void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
2210 {
2211         if (ima == NULL)
2212                 return;
2213
2214         BLI_spin_lock(&image_spin);
2215
2216         switch (signal) {
2217                 case IMA_SIGNAL_FREE:
2218                         image_free_buffers(ima);
2219                         if (iuser)
2220                                 iuser->ok = 1;
2221                         break;
2222                 case IMA_SIGNAL_SRC_CHANGE:
2223                         if (ima->type == IMA_TYPE_UV_TEST)
2224                                 if (ima->source != IMA_SRC_GENERATED)
2225                                         ima->type = IMA_TYPE_IMAGE;
2226
2227                         if (ima->source == IMA_SRC_GENERATED) {
2228                                 if (ima->gen_x == 0 || ima->gen_y == 0) {
2229                                         ImBuf *ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2230                                         if (ibuf) {
2231                                                 ima->gen_x = ibuf->x;
2232                                                 ima->gen_y = ibuf->y;
2233                                         }
2234                                 }
2235                         }
2236
2237 #if 0
2238                         /* force reload on first use, but not for multilayer, that makes nodes and buttons in ui drawing fail */
2239                         if (ima->type != IMA_TYPE_MULTILAYER)
2240                                 image_free_buffers(ima);
2241 #else
2242                         /* image buffers for non-sequence multilayer will share buffers with RenderResult,
2243                          * however sequence multilayer will own buffers. Such logic makes switching from
2244                          * single multilayer file to sequence completely unstable
2245                          * since changes in nodes seems this workaround isn't needed anymore, all sockets
2246                          * are nicely detecting anyway, but freeing buffers always here makes multilayer
2247                          * sequences behave stable
2248                          */
2249                         image_free_buffers(ima);
2250 #endif
2251
2252                         ima->ok = 1;
2253                         if (iuser)
2254                                 iuser->ok = 1;
2255
2256                         BKE_image_walk_all_users(G.main, ima, image_tag_frame_recalc);
2257
2258                         break;
2259
2260                 case IMA_SIGNAL_RELOAD:
2261                         /* try to repack file */
2262                         if (ima->packedfile) {
2263                                 PackedFile *pf;
2264                                 pf = newPackedFile(NULL, ima->name, ID_BLEND_PATH(G.main, &ima->id));
2265                                 if (pf) {
2266                                         freePackedFile(ima->packedfile);
2267                                         ima->packedfile = pf;
2268                                         image_free_buffers(ima);
2269                                 }
2270                                 else {
2271                                         printf("ERROR: Image not available. Keeping packed image\n");
2272                                 }
2273                         }
2274                         else
2275                                 image_free_buffers(ima);
2276
2277                         if (iuser)
2278                                 iuser->ok = 1;
2279
2280                         break;
2281                 case IMA_SIGNAL_USER_NEW_IMAGE:
2282                         if (iuser) {
2283                                 iuser->ok = 1;
2284                                 if (ima->source == IMA_SRC_FILE || ima->source == IMA_SRC_SEQUENCE) {
2285                                         if (ima->type == IMA_TYPE_MULTILAYER) {
2286                                                 iuser->multi_index = 0;
2287                                                 iuser->layer = iuser->pass = 0;
2288                                         }
2289                                 }
2290                         }
2291                         break;
2292                 case IMA_SIGNAL_COLORMANAGE:
2293                         image_free_buffers(ima);
2294
2295                         ima->ok = 1;
2296
2297                         if (iuser)
2298                                 iuser->ok = 1;
2299
2300                         break;
2301         }
2302
2303         BLI_spin_unlock(&image_spin);
2304
2305         /* don't use notifiers because they are not 100% sure to succeeded
2306          * this also makes sure all scenes are accounted for. */
2307         {
2308                 Scene *scene;
2309                 for (scene = G.main->scene.first; scene; scene = scene->id.next) {
2310                         if (scene->nodetree) {
2311                                 nodeUpdateID(scene->nodetree, &ima->id);
2312                         }
2313                 }
2314         }
2315 }
2316
2317 /* if layer or pass changes, we need an index for the imbufs list */
2318 /* note it is called for rendered results, but it doesnt use the index! */
2319 /* and because rendered results use fake layer/passes, don't correct for wrong indices here */
2320 RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
2321 {
2322         RenderLayer *rl;
2323         RenderPass *rpass = NULL;
2324
2325         if (rr == NULL)
2326                 return NULL;
2327
2328         if (iuser) {
2329                 short index = 0, rl_index = 0, rp_index;
2330
2331                 for (rl = rr->layers.first; rl; rl = rl->next, rl_index++) {
2332                         rp_index = 0;
2333                         for (rpass = rl->passes.first; rpass; rpass = rpass->next, index++, rp_index++)
2334                                 if (iuser->layer == rl_index && iuser->pass == rp_index)
2335                                         break;
2336                         if (rpass)
2337                                 break;
2338                 }
2339
2340                 if (rpass)
2341                         iuser->multi_index = index;
2342                 else
2343                         iuser->multi_index = 0;
2344         }
2345         if (rpass == NULL) {
2346                 rl = rr->layers.first;
2347                 if (rl)
2348                         rpass = rl->passes.first;
2349         }
2350
2351         return rpass;
2352 }
2353
2354 RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
2355 {
2356         if (ima->rr) {
2357                 return ima->rr;
2358         }
2359         else if (ima->type == IMA_TYPE_R_RESULT) {
2360                 if (ima->render_slot == ima->last_render_slot)
2361                         return RE_AcquireResultRead(RE_GetRender(scene->id.name));
2362                 else
2363                         return ima->renders[ima->render_slot];
2364         }
2365         else
2366                 return NULL;
2367 }
2368
2369 void BKE_image_release_renderresult(Scene *scene, Image *ima)
2370 {
2371         if (ima->rr) {
2372                 /* pass */
2373         }
2374         else if (ima->type == IMA_TYPE_R_RESULT) {
2375                 if (ima->render_slot == ima->last_render_slot)
2376                         RE_ReleaseResult(RE_GetRender(scene->id.name));
2377         }
2378 }
2379
2380 void BKE_image_backup_render(Scene *scene, Image *ima)
2381 {
2382         /* called right before rendering, ima->renders contains render
2383          * result pointers for everything but the current render */
2384         Render *re = RE_GetRender(scene->id.name);
2385         int slot = ima->render_slot, last = ima->last_render_slot;
2386
2387         if (slot != last) {
2388                 if (ima->renders[slot]) {
2389                         RE_FreeRenderResult(ima->renders[slot]);
2390                         ima->renders[slot] = NULL;
2391                 }
2392
2393                 ima->renders[last] = NULL;
2394                 RE_SwapResult(re, &ima->renders[last]);
2395         }
2396
2397         ima->last_render_slot = slot;
2398 }
2399
2400 /* after imbuf load, openexr type can return with a exrhandle open */
2401 /* in that case we have to build a render-result */
2402 static void image_create_multilayer(Image *ima, ImBuf *ibuf, int framenr)
2403 {
2404         const char *colorspace = ima->colorspace_settings.name;
2405         int predivide = ima->alpha_mode == IMA_ALPHA_PREMUL;
2406
2407         ima->rr = RE_MultilayerConvert(ibuf->userdata, colorspace, predivide, ibuf->x, ibuf->y);
2408
2409 #ifdef WITH_OPENEXR
2410         IMB_exr_close(ibuf->userdata);
2411 #endif
2412
2413         ibuf->userdata = NULL;
2414         if (ima->rr)
2415                 ima->rr->framenr = framenr;
2416 }
2417
2418 /* common stuff to do with images after loading */
2419 static void image_initialize_after_load(Image *ima, ImBuf *ibuf)
2420 {
2421         /* preview is NULL when it has never been used as an icon before */
2422         if (G.background == 0 && ima->preview == NULL)
2423                 BKE_icon_changed(BKE_icon_getid(&ima->id));
2424
2425         /* fields */
2426         if (ima->flag & IMA_FIELDS) {
2427                 if (ima->flag & IMA_STD_FIELD) de_interlace_st(ibuf);
2428                 else de_interlace_ng(ibuf);
2429         }
2430         /* timer */
2431         ima->lastused = clock() / CLOCKS_PER_SEC;
2432
2433         ima->ok = IMA_OK_LOADED;
2434
2435 }
2436
2437 static int imbuf_alpha_flags_for_image(Image *ima)
2438 {
2439         int flag = 0;
2440
2441         if (ima->flag & IMA_IGNORE_ALPHA)
2442                 flag |= IB_ignore_alpha;
2443         else if (ima->alpha_mode == IMA_ALPHA_PREMUL)
2444                 flag |= IB_alphamode_premul;
2445
2446         return flag;
2447 }
2448
2449 static ImBuf *image_load_sequence_file(Image *ima, ImageUser *iuser, int frame)
2450 {
2451         struct ImBuf *ibuf;
2452         char name[FILE_MAX];
2453         int flag;
2454
2455         /* XXX temp stuff? */
2456         if (ima->lastframe != frame)
2457                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2458
2459         ima->lastframe = frame;
2460         BKE_image_user_file_path(iuser, ima, name);
2461
2462         flag = IB_rect | IB_multilayer;
2463         flag |= imbuf_alpha_flags_for_image(ima);
2464
2465         /* read ibuf */
2466         ibuf = IMB_loadiffname(name, flag, ima->colorspace_settings.name);
2467
2468 #if 0
2469         if (ibuf) {
2470                 printf(AT " loaded %s\n", name);
2471         }
2472         else {
2473                 printf(AT " missed %s\n", name);
2474         }
2475 #endif
2476
2477         if (ibuf) {
2478 #ifdef WITH_OPENEXR
2479                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_acquire_ibuf */
2480                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2481                         image_create_multilayer(ima, ibuf, frame);
2482                         ima->type = IMA_TYPE_MULTILAYER;
2483                         IMB_freeImBuf(ibuf);
2484                         ibuf = NULL;
2485                 }
2486                 else {
2487                         image_initialize_after_load(ima, ibuf);
2488                         image_assign_ibuf(ima, ibuf, 0, frame);
2489                 }
2490 #else
2491                 image_initialize_after_load(ima, ibuf);
2492                 image_assign_ibuf(ima, ibuf, 0, frame);
2493 #endif
2494         }
2495         else
2496                 ima->ok = 0;
2497
2498         if (iuser)
2499                 iuser->ok = ima->ok;
2500
2501         return ibuf;
2502 }
2503
2504 static ImBuf *image_load_sequence_multilayer(Image *ima, ImageUser *iuser, int frame)
2505 {
2506         struct ImBuf *ibuf = NULL;
2507
2508         /* either we load from RenderResult, or we have to load a new one */
2509
2510         /* check for new RenderResult */
2511         if (ima->rr == NULL || frame != ima->rr->framenr) {
2512                 if (ima->rr) {
2513                         /* Cached image buffers shares pointers with render result,
2514                          * need to ensure there's no image buffers are hanging around
2515                          * with dead links after freeing the render result.
2516                          */
2517                         image_free_cahced_frames(ima);
2518                         RE_FreeRenderResult(ima->rr);
2519                         ima->rr = NULL;
2520                 }
2521
2522                 ibuf = image_load_sequence_file(ima, iuser, frame);
2523
2524                 if (ibuf) { /* actually an error */
2525                         ima->type = IMA_TYPE_IMAGE;
2526                         printf("error, multi is normal image\n");
2527                 }
2528         }
2529         if (ima->rr) {
2530                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2531
2532                 if (rpass) {
2533                         // printf("load from pass %s\n", rpass->name);
2534                         /* since we free  render results, we copy the rect */
2535                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2536                         ibuf->rect_float = MEM_dupallocN(rpass->rect);
2537                         ibuf->flags |= IB_rectfloat;
2538                         ibuf->mall = IB_rectfloat;
2539                         ibuf->channels = rpass->channels;
2540
2541                         image_initialize_after_load(ima, ibuf);
2542                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : 0, frame);
2543
2544                 }
2545                 // else printf("pass not found\n");
2546         }
2547         else
2548                 ima->ok = 0;
2549
2550         if (iuser)
2551                 iuser->ok = ima->ok;
2552
2553         return ibuf;
2554 }
2555
2556
2557 static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
2558 {
2559         struct ImBuf *ibuf = NULL;
2560
2561         ima->lastframe = frame;
2562
2563         if (ima->anim == NULL) {
2564                 char str[FILE_MAX];
2565
2566                 BKE_image_user_file_path(iuser, ima, str);
2567
2568                 /* FIXME: make several stream accessible in image editor, too*/
2569                 ima->anim = openanim(str, IB_rect, 0, ima->colorspace_settings.name);
2570
2571                 /* let's initialize this user */
2572                 if (ima->anim && iuser && iuser->frames == 0)
2573                         iuser->frames = IMB_anim_get_duration(ima->anim,
2574                                                               IMB_TC_RECORD_RUN);
2575         }
2576
2577         if (ima->anim) {
2578                 int dur = IMB_anim_get_duration(ima->anim,
2579                                                 IMB_TC_RECORD_RUN);
2580                 int fra = frame - 1;
2581
2582                 if (fra < 0) fra = 0;
2583                 if (fra > (dur - 1)) fra = dur - 1;
2584                 ibuf = IMB_makeSingleUser(
2585                     IMB_anim_absolute(ima->anim, fra,
2586                                       IMB_TC_RECORD_RUN,
2587                                       IMB_PROXY_NONE));
2588
2589                 if (ibuf) {
2590                         image_initialize_after_load(ima, ibuf);
2591                         image_assign_ibuf(ima, ibuf, 0, frame);
2592                 }
2593                 else
2594                         ima->ok = 0;
2595         }
2596         else
2597                 ima->ok = 0;
2598
2599         if (iuser)
2600                 iuser->ok = ima->ok;
2601
2602         return ibuf;
2603 }
2604
2605 /* warning, 'iuser' can be NULL */
2606 static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
2607 {
2608         struct ImBuf *ibuf;
2609         char str[FILE_MAX];
2610         int assign = 0, flag;
2611
2612         /* always ensure clean ima */
2613         image_free_buffers(ima);
2614
2615         /* is there a PackedFile with this image ? */
2616         if (ima->packedfile) {
2617                 flag = IB_rect | IB_multilayer;
2618                 flag |= imbuf_alpha_flags_for_image(ima);
2619
2620                 ibuf = IMB_ibImageFromMemory((unsigned char *)ima->packedfile->data, ima->packedfile->size, flag,
2621                                              ima->colorspace_settings.name, "<packed data>");
2622         }
2623         else {
2624                 flag = IB_rect | IB_multilayer | IB_metadata;
2625                 flag |= imbuf_alpha_flags_for_image(ima);
2626
2627                 /* get the right string */
2628                 BKE_image_user_frame_calc(iuser, cfra, 0);
2629                 BKE_image_user_file_path(iuser, ima, str);
2630
2631                 /* read ibuf */
2632                 ibuf = IMB_loadiffname(str, flag, ima->colorspace_settings.name);
2633         }
2634
2635         if (ibuf) {
2636                 /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_acquire_ibuf */
2637                 if (ibuf->ftype == OPENEXR && ibuf->userdata) {
2638                         image_create_multilayer(ima, ibuf, cfra);
2639                         ima->type = IMA_TYPE_MULTILAYER;
2640                         IMB_freeImBuf(ibuf);
2641                         ibuf = NULL;
2642                 }
2643                 else {
2644                         image_initialize_after_load(ima, ibuf);
2645                         assign = 1;
2646
2647                         /* check if the image is a font image... */
2648                         detectBitmapFont(ibuf);
2649
2650                         /* make packed file for autopack */
2651                         if ((ima->packedfile == NULL) && (G.fileflags & G_AUTOPACK))
2652                                 ima->packedfile = newPackedFile(NULL, str, ID_BLEND_PATH(G.main, &ima->id));
2653                 }
2654         }
2655         else
2656                 ima->ok = 0;
2657
2658         if (assign)
2659                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2660
2661         if (iuser)
2662                 iuser->ok = ima->ok;
2663
2664         return ibuf;
2665 }
2666
2667 static ImBuf *image_get_ibuf_multilayer(Image *ima, ImageUser *iuser)
2668 {
2669         ImBuf *ibuf = NULL;
2670
2671         if (ima->rr == NULL) {
2672                 ibuf = image_load_image_file(ima, iuser, 0);
2673                 if (ibuf) { /* actually an error */
2674                         ima->type = IMA_TYPE_IMAGE;
2675                         return ibuf;
2676                 }
2677         }
2678         if (ima->rr) {
2679                 RenderPass *rpass = BKE_image_multilayer_index(ima->rr, iuser);
2680
2681                 if (rpass) {
2682                         ibuf = IMB_allocImBuf(ima->rr->rectx, ima->rr->recty, 32, 0);
2683
2684                         image_initialize_after_load(ima, ibuf);
2685
2686                         ibuf->rect_float = rpass->rect;
2687                         ibuf->flags |= IB_rectfloat;
2688                         ibuf->channels = rpass->channels;
2689
2690                         image_assign_ibuf(ima, ibuf, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2691                 }
2692         }
2693
2694         if (ibuf == NULL)
2695                 ima->ok = 0;
2696         if (iuser)
2697                 iuser->ok = ima->ok;
2698
2699         return ibuf;
2700 }
2701
2702
2703 /* showing RGBA result itself (from compo/sequence) or
2704  * like exr, using layers etc */
2705 /* always returns a single ibuf, also during render progress */
2706 static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **lock_r)
2707 {
2708         Render *re;
2709         RenderResult rres;
2710         float *rectf, *rectz;
2711         unsigned int *rect;
2712         float dither;
2713         int channels, layer, pass;
2714         ImBuf *ibuf;
2715         int from_render = (ima->render_slot == ima->last_render_slot);
2716
2717         if (!(iuser && iuser->scene))
2718                 return NULL;
2719
2720         /* if we the caller is not going to release the lock, don't give the image */
2721         if (!lock_r)
2722                 return NULL;
2723
2724         re = RE_GetRender(iuser->scene->id.name);
2725
2726         channels = 4;
2727         layer = iuser->layer;
2728         pass = iuser->pass;
2729
2730         if (from_render) {
2731                 RE_AcquireResultImage(re, &rres);
2732         }
2733         else if (ima->renders[ima->render_slot]) {
2734                 rres = *(ima->renders[ima->render_slot]);
2735                 rres.have_combined = rres.rectf != NULL;
2736         }
2737         else
2738                 memset(&rres, 0, sizeof(RenderResult));
2739
2740         if (!(rres.rectx > 0 && rres.recty > 0)) {
2741                 if (from_render)
2742                         RE_ReleaseResultImage(re);
2743                 return NULL;
2744         }
2745
2746         /* release is done in BKE_image_release_ibuf using lock_r */
2747         if (from_render) {
2748                 BLI_lock_thread(LOCK_VIEWER);
2749                 *lock_r = re;
2750         }
2751
2752         /* this gives active layer, composite or sequence result */
2753         rect = (unsigned int *)rres.rect32;
2754         rectf = rres.rectf;
2755         rectz = rres.rectz;
2756         dither = iuser->scene->r.dither_intensity;
2757
2758         /* combined layer gets added as first layer */
2759         if (rres.have_combined && layer == 0) {
2760                 /* pass */
2761         }
2762         else if (rect && layer == 0) {
2763                 /* rect32 is set when there's a Sequence pass, this pass seems
2764                  * to have layer=0 (this is from image_buttons.c)
2765                  * in this case we ignore float buffer, because it could have
2766                  * hung from previous pass which was float
2767                  */
2768                 rectf = NULL;
2769         }
2770         else if (rres.layers.first) {
2771                 RenderLayer *rl = BLI_findlink(&rres.layers, layer - (rres.have_combined ? 1 : 0));
2772                 if (rl) {
2773                         RenderPass *rpass;
2774
2775                         /* there's no combined pass, is in renderlayer itself */
2776                         if (pass == 0) {
2777                                 rectf = rl->rectf;
2778                         }
2779                         else {
2780                                 rpass = BLI_findlink(&rl->passes, pass - 1);
2781                                 if (rpass) {
2782                                         channels = rpass->channels;
2783                                         rectf = rpass->rect;
2784                                         dither = 0.0f; /* don't dither passes */
2785                                 }
2786                         }
2787
2788                         for (rpass = rl->passes.first; rpass; rpass = rpass->next)
2789                                 if (rpass->passtype == SCE_PASS_Z)
2790                                         rectz = rpass->rect;
2791                 }
2792         }
2793
2794         ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2795
2796         /* make ibuf if needed, and initialize it */
2797         if (ibuf == NULL) {
2798                 ibuf = IMB_allocImBuf(rres.rectx, rres.recty, 32, 0);
2799                 image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
2800         }
2801
2802         /* invalidate color managed buffers if render result changed */
2803         BLI_lock_thread(LOCK_COLORMANAGE);
2804         if (ibuf->x != rres.rectx || ibuf->y != rres.recty || ibuf->rect_float != rectf) {
2805                 ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
2806         }
2807
2808         ibuf->x = rres.rectx;
2809         ibuf->y = rres.recty;
2810
2811         /* free rect buffer if float buffer changes, so it can be recreated with
2812          * the updated result, and also in case we got byte buffer from sequencer,
2813          * so we don't keep reference to freed buffer */
2814         if (ibuf->rect_float != rectf || rect)
2815                 imb_freerectImBuf(ibuf);
2816
2817         if (rect) {
2818                 ibuf->rect = rect;
2819         }
2820         else {
2821                 /* byte buffer of render result has been freed, make sure image buffers
2822                  * does not reference to this buffer anymore
2823                  * need check for whether byte buffer was allocated and owned by image itself
2824                  * or if it's reusing buffer from render result
2825                  */
2826                 if ((ibuf->mall & IB_rect) == 0)
2827                         ibuf->rect = NULL;
2828         }
2829
2830         if (rectf) {
2831                 ibuf->rect_float = rectf;
2832                 ibuf->flags |= IB_rectfloat;
2833                 ibuf->channels = channels;
2834         }
2835         else {
2836                 ibuf->rect_float = NULL;
2837                 ibuf->flags &= ~IB_rectfloat;
2838         }
2839
2840         if (rectz) {
2841                 ibuf->zbuf_float = rectz;
2842                 ibuf->flags |= IB_zbuffloat;
2843         }
2844         else {
2845                 ibuf->zbuf_float = NULL;
2846                 ibuf->flags &= ~IB_zbuffloat;
2847         }
2848
2849         BLI_unlock_thread(LOCK_COLORMANAGE);
2850
2851         ibuf->dither = dither;
2852
2853         ima->ok = IMA_OK_LOADED;
2854
2855         return ibuf;
2856 }
2857
2858 static void image_get_frame_and_index(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2859 {
2860         int frame = 0, index = 0;
2861
2862         /* see if we already have an appropriate ibuf, with image source and type */
2863         if (ima->source == IMA_SRC_MOVIE) {
2864                 frame = iuser ? iuser->framenr : ima->lastframe;
2865         }
2866         else if (ima->source == IMA_SRC_SEQUENCE) {
2867                 if (ima->type == IMA_TYPE_IMAGE) {
2868                         frame = iuser ? iuser->framenr : ima->lastframe;
2869                 }
2870                 else if (ima->type == IMA_TYPE_MULTILAYER) {
2871                         frame = iuser ? iuser->framenr : ima->lastframe;
2872                         index = iuser ? iuser->multi_index : IMA_NO_INDEX;
2873                 }
2874         }
2875
2876         *frame_r = frame;
2877         *index_r = index;
2878 }
2879
2880 static ImBuf *image_get_ibuf_threadsafe(Image *ima, ImageUser *iuser, int *frame_r, int *index_r)
2881 {
2882         ImBuf *ibuf = NULL;
2883         int frame = 0, index = 0;
2884
2885         /* see if we already have an appropriate ibuf, with image source and type */
2886         if (ima->source == IMA_SRC_MOVIE) {
2887                 frame = iuser ? iuser->framenr : ima->lastframe;
2888                 ibuf = image_get_ibuf(ima, 0, frame);
2889                 /* XXX temp stuff? */
2890                 if (ima->lastframe != frame)
2891                         ima->tpageflag |= IMA_TPAGE_REFRESH;
2892                 ima->lastframe = frame;
2893         }
2894         else if (ima->source == IMA_SRC_SEQUENCE) {
2895                 if (ima->type == IMA_TYPE_IMAGE) {
2896                         frame = iuser ? iuser->framenr : ima->lastframe;
2897                         ibuf = image_get_ibuf(ima, 0, frame);
2898
2899                         /* XXX temp stuff? */
2900                         if (ima->lastframe != frame) {
2901                                 ima->tpageflag |= IMA_TPAGE_REFRESH;
2902                         }
2903                         ima->lastframe = frame;
2904                 }
2905                 else if (ima->type == IMA_TYPE_MULTILAYER) {
2906                         frame = iuser ? iuser->framenr : ima->lastframe;
2907                         index = iuser ? iuser->multi_index : IMA_NO_INDEX;
2908                         ibuf = image_get_ibuf(ima, index, frame);
2909                 }
2910         }
2911         else if (ima->source == IMA_SRC_FILE) {
2912                 if (ima->type == IMA_TYPE_IMAGE)
2913                         ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2914                 else if (ima->type == IMA_TYPE_MULTILAYER)
2915                         ibuf = image_get_ibuf(ima, iuser ? iuser->multi_index : IMA_NO_INDEX, 0);
2916         }
2917         else if (ima->source == IMA_SRC_GENERATED) {
2918                 ibuf = image_get_ibuf(ima, IMA_NO_INDEX, 0);
2919         }
2920         else if (ima->source == IMA_SRC_VIEWER) {
2921                 /* always verify entirely, not that this shouldn't happen
2922                  * as part of texture sampling in rendering anyway, so not
2923                  * a big bottleneck */
2924         }
2925
2926         if (frame_r)
2927                 *frame_r = frame;
2928
2929         if (index_r)
2930                 *index_r = index;
2931
2932         return ibuf;
2933 }
2934
2935 BLI_INLINE int image_quick_test(Image *ima, ImageUser *iuser)
2936 {
2937         if (ima == NULL)
2938                 return FALSE;
2939
2940         if (iuser) {
2941                 if (iuser->ok == 0)
2942                         return FALSE;
2943         }
2944         else if (ima->ok == 0)
2945                 return FALSE;
2946
2947         return TRUE;
2948 }
2949
2950 /* Checks optional ImageUser and verifies/creates ImBuf.
2951  *
2952  * not thread-safe, so callee should worry about thread locks
2953  */
2954 static ImBuf *image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
2955 {
2956         ImBuf *ibuf = NULL;
2957         float color[] = {0, 0, 0, 1};
2958         int frame = 0, index = 0;
2959
2960         if (lock_r)
2961                 *lock_r = NULL;
2962
2963         /* quick reject tests */
2964         if (!image_quick_test(ima, iuser))
2965                 return NULL;
2966
2967         ibuf = image_get_ibuf_threadsafe(ima, iuser, &frame, &index);
2968
2969         if (ibuf == NULL) {
2970                 /* we are sure we have to load the ibuf, using source and type */
2971                 if (ima->source == IMA_SRC_MOVIE) {
2972                         /* source is from single file, use flipbook to store ibuf */
2973                         ibuf = image_load_movie_file(ima, iuser, frame);
2974                 }
2975                 else if (ima->source == IMA_SRC_SEQUENCE) {
2976                         if (ima->type == IMA_TYPE_IMAGE) {
2977                                 /* regular files, ibufs in flipbook, allows saving */
2978                                 ibuf = image_load_sequence_file(ima, iuser, frame);
2979                         }
2980                         /* no else; on load the ima type can change */
2981                         if (ima->type == IMA_TYPE_MULTILAYER) {
2982                                 /* only 1 layer/pass stored in imbufs, no exrhandle anim storage, no saving */
2983                                 ibuf = image_load_sequence_multilayer(ima, iuser, frame);
2984                         }
2985                 }
2986                 else if (ima->source == IMA_SRC_FILE) {
2987
2988                         if (ima->type == IMA_TYPE_IMAGE)
2989                                 ibuf = image_load_image_file(ima, iuser, frame);  /* cfra only for '#', this global is OK */
2990                         /* no else; on load the ima type can change */
2991                         if (ima->type == IMA_TYPE_MULTILAYER)
2992                                 /* keeps render result, stores ibufs in listbase, allows saving */
2993                                 ibuf = image_get_ibuf_multilayer(ima, iuser);
2994
2995                 }
2996                 else if (ima->source == IMA_SRC_GENERATED) {
2997                         /* generated is: ibuf is allocated dynamically */
2998                         /* UV testgrid or black or solid etc */
2999                         if (ima->gen_x == 0) ima->gen_x = 1024;
3000                         if (ima->gen_y == 0) ima->gen_y = 1024;
3001                         if (ima->gen_depth == 0) ima->gen_depth = 24;
3002                         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,
3003                                              color, &ima->colorspace_settings);
3004                         image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
3005                         ima->ok = IMA_OK_LOADED;
3006                 }
3007                 else if (ima->source == IMA_SRC_VIEWER) {
3008                         if (ima->type == IMA_TYPE_R_RESULT) {
3009                                 /* always verify entirely, and potentially
3010                                  * returns pointer to release later */
3011                                 ibuf = image_get_render_result(ima, iuser, lock_r);
3012                         }
3013                         else if (ima->type == IMA_TYPE_COMPOSITE) {
3014                                 /* requires lock/unlock, otherwise don't return image */
3015                                 if (lock_r) {
3016                                         /* unlock in BKE_image_release_ibuf */
3017                                         BLI_lock_thread(LOCK_VIEWER);
3018                                         *lock_r = ima;
3019
3020                                         /* XXX anim play for viewer nodes not yet supported */
3021                                         frame = 0; // XXX iuser ? iuser->framenr : 0;
3022                                         ibuf = image_get_ibuf(ima, 0, frame);
3023
3024                                         if (!ibuf) {
3025                                                 /* Composite Viewer, all handled in compositor */
3026                                                 /* fake ibuf, will be filled in compositor */
3027                                                 ibuf = IMB_allocImBuf(256, 256, 32, IB_rect);
3028                                                 image_assign_ibuf(ima, ibuf, 0, frame);
3029                                         }
3030                                 }
3031                         }
3032                 }
3033         }
3034
3035         BKE_image_tag_time(ima);
3036
3037         return ibuf;
3038 }
3039
3040 /* return image buffer for given image and user
3041  *
3042  * - will lock render result if image type is render result and lock is not NULL
3043  * - will return NULL if image type if render or composite result and lock is NULL
3044  *
3045  * references the result, BKE_image_release_ibuf should be used to de-reference
3046  */
3047 ImBuf *BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **lock_r)
3048 {
3049         ImBuf *ibuf;
3050
3051         BLI_spin_lock(&image_spin);
3052
3053         ibuf = image_acquire_ibuf(ima, iuser, lock_r);
3054
3055         if (ibuf)
3056                 IMB_refImBuf(ibuf);
3057
3058         BLI_spin_unlock(&image_spin);
3059
3060         return ibuf;
3061 }
3062
3063 void BKE_image_release_ibuf(Image *ima, ImBuf *ibuf, void *lock)
3064 {
3065         if (lock) {
3066                 /* for getting image during threaded render / compositing, need to release */
3067                 if (lock == ima) {
3068                         BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
3069                 }
3070                 else if (lock) {
3071                         RE_ReleaseResultImage(lock); /* render result */
3072                         BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
3073                 }
3074         }
3075
3076         if (ibuf) {
3077                 BLI_spin_lock(&image_spin);
3078                 IMB_freeImBuf(ibuf);
3079                 BLI_spin_unlock(&image_spin);
3080         }
3081 }
3082
3083 /* checks whether there's an image buffer for given image and user */
3084 int BKE_image_has_ibuf(Image *ima, ImageUser *iuser)
3085 {
3086         ImBuf *ibuf;
3087
3088         /* quick reject tests */
3089         if (!image_quick_test(ima, iuser))
3090                 return FALSE;
3091
3092         ibuf = image_get_ibuf_threadsafe(ima, iuser, NULL, NULL);
3093
3094         if (!ibuf) {
3095                 BLI_spin_lock(&image_spin);
3096
3097                 ibuf = image_get_ibuf_threadsafe(ima, iuser, NULL, NULL);
3098
3099                 if (!ibuf)
3100                         ibuf = image_acquire_ibuf(ima, iuser, NULL);
3101
3102                 BLI_spin_unlock(&image_spin);
3103         }
3104
3105         return ibuf != NULL;
3106 }
3107
3108 /* ******** Pool for image buffers ********  */
3109
3110 typedef struct ImagePoolEntry {
3111         struct ImagePoolEntry *next, *prev;
3112         Image *image;
3113         ImBuf *ibuf;
3114         int index;
3115         int frame;
3116 } ImagePoolEntry;
3117
3118 typedef struct ImagePool {
3119         ListBase image_buffers;
3120 } ImagePool;
3121
3122 ImagePool *BKE_image_pool_new(void)
3123 {
3124         ImagePool *pool = MEM_callocN(sizeof(ImagePool), "Image Pool");
3125
3126         return pool;
3127 }
3128
3129 void BKE_image_pool_free(ImagePool *pool)
3130 {
3131         ImagePoolEntry *entry, *next_entry;
3132
3133         /* use single lock to dereference all the image buffers */
3134         BLI_spin_lock(&image_spin);
3135
3136         for (entry = pool->image_buffers.first; entry; entry = next_entry) {
3137                 next_entry = entry->next;
3138
3139                 if (entry->ibuf)
3140                         IMB_freeImBuf(entry->ibuf);
3141
3142                 MEM_freeN(entry);
3143         }
3144
3145         BLI_spin_unlock(&image_spin);
3146
3147         MEM_freeN(pool);
3148 }
3149
3150 BLI_INLINE ImBuf *image_pool_find_entry(ImagePool *pool, Image *image, int frame, int index, int *found)
3151 {
3152         ImagePoolEntry *entry;
3153
3154         *found = FALSE;
3155
3156         for (entry = pool->image_buffers.first; entry; entry = entry->next) {
3157                 if (entry->image == image && entry->frame == frame && entry->index == index) {
3158                         *found = TRUE;
3159                         return entry->ibuf;
3160                 }
3161         }
3162
3163         return NULL;
3164 }
3165
3166 ImBuf *BKE_image_pool_acquire_ibuf(Image *ima, ImageUser *iuser, ImagePool *pool)
3167 {
3168         ImBuf *ibuf;
3169         int index, frame, found;
3170
3171         if (!image_quick_test(ima, iuser))
3172                 return NULL;
3173
3174         if (pool == NULL) {
3175                 /* pool could be NULL, in this case use general acquire function */
3176                 return BKE_image_acquire_ibuf(ima, iuser, NULL);
3177         }
3178
3179         image_get_frame_and_index(ima, iuser, &frame, &index);
3180
3181         ibuf = image_pool_find_entry(pool, ima, frame, index, &found);
3182         if (found)
3183                 return ibuf;
3184
3185         BLI_spin_lock(&image_spin);
3186
3187         ibuf = image_pool_find_entry(pool, ima, frame, index, &found);
3188
3189         /* will also create entry even in cases image buffer failed to load,
3190          * prevents trying to load the same buggy file multiple times
3191          */
3192         if (!found) {
3193                 ImagePoolEntry *entry;
3194
3195                 ibuf = image_acquire_ibuf(ima, iuser, NULL);
3196
3197                 if (ibuf)
3198                         IMB_refImBuf(ibuf);
3199
3200                 entry = MEM_callocN(sizeof(ImagePoolEntry), "Image Pool Entry");
3201                 entry->image = ima;
3202                 entry->frame = frame;
3203                 entry->index = index;
3204                 entry->ibuf = ibuf;
3205
3206                 BLI_addtail(&pool->image_buffers, entry);
3207         }
3208
3209         BLI_spin_unlock(&image_spin);
3210
3211         return ibuf;
3212 }
3213
3214 void BKE_image_pool_release_ibuf(Image *ima, ImBuf *ibuf, ImagePool *pool)
3215 {
3216         /* if pool wasn't actually used, use general release stuff,
3217          * for pools image buffers will be dereferenced on pool free
3218          */
3219         if (pool == NULL) {
3220                 BKE_image_release_ibuf(ima, ibuf, NULL);
3221         }
3222 }
3223
3224 int BKE_image_user_frame_get(const ImageUser *iuser, int cfra, int fieldnr, short *r_is_in_range)
3225 {
3226         const int len = (iuser->fie_ima * iuser->frames) / 2;
3227
3228         if (r_is_in_range) {
3229                 *r_is_in_range = FALSE;
3230         }
3231
3232         if (len == 0) {
3233                 return 0;
3234         }
3235         else {
3236                 int framenr;
3237                 cfra = cfra - iuser->sfra + 1;
3238
3239                 /* cyclic */
3240                 if (iuser->cycl) {
3241                         cfra = ((cfra) % len);
3242                         if (cfra < 0) cfra += len;
3243                         if (cfra == 0) cfra = len;
3244
3245                         if (r_is_in_range) {
3246                                 *r_is_in_range = TRUE;
3247                         }
3248                 }
3249
3250                 if (cfra < 0) {
3251                         cfra = 0;
3252                 }
3253                 else if (cfra > len) {
3254                         cfra = len;
3255                 }
3256                 else {
3257                         if (r_is_in_range) {
3258                                 *r_is_in_range = TRUE;
3259                         }
3260                 }
3261
3262                 /* convert current frame to current field */
3263                 cfra = 2 * (cfra);
3264                 if (fieldnr) cfra++;
3265
3266                 /* transform to images space */
3267                 framenr = (cfra + iuser->fie_ima - 2) / iuser->fie_ima;
3268                 if (framenr > iuser->frames) framenr = iuser->frames;
3269
3270                 if (iuser->cycl) {
3271                         framenr = ((framenr) % len);
3272                         while (framenr < 0) framenr += len;
3273                         if (framenr == 0) framenr = len;
3274                 }
3275
3276                 /* important to apply after else we cant loop on frames 100 - 110 for eg. */
3277                 framenr += iuser->offset;