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