Blender V5.3
openexr_api.cpp
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2005 `Gernot Ziegler <gz@lysator.liu.se>`. All rights reserved.
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "IMB_filetype.hh"
10
11#include <algorithm>
12#include <cctype>
13#include <cerrno>
14#include <cstddef>
15#include <cstdio>
16#include <cstdlib>
17#include <fcntl.h>
18#include <fstream>
19#include <iostream>
20#include <set>
21#include <string>
22
23/* The OpenEXR version can reliably be found in this header file from OpenEXR,
24 * for both 2.x and 3.x:
25 */
26#include <OpenEXR/OpenEXRConfig.h>
27#define COMBINED_OPENEXR_VERSION \
28 ((10000 * OPENEXR_VERSION_MAJOR) + (100 * OPENEXR_VERSION_MINOR) + OPENEXR_VERSION_PATCH)
29
30#if COMBINED_OPENEXR_VERSION >= 20599
31/* >=2.5.99 -> OpenEXR >=3.0 */
32# include <Imath/half.h>
33# include <OpenEXR/ImfFrameBuffer.h>
34# define exr_file_offset_t uint64_t
35#else
36/* OpenEXR 2.x, use the old locations. */
37# include <OpenEXR/half.h>
38# define exr_file_offset_t Int64
39#endif
40
41#include <OpenEXR/Iex.h>
42#include <OpenEXR/ImfArray.h>
43#include <OpenEXR/ImfAttribute.h>
44#include <OpenEXR/ImfChannelList.h>
45#include <OpenEXR/ImfChromaticities.h>
46#include <OpenEXR/ImfCompression.h>
47#include <OpenEXR/ImfCompressionAttribute.h>
48#include <OpenEXR/ImfIO.h>
49#include <OpenEXR/ImfInputFile.h>
50#include <OpenEXR/ImfIntAttribute.h>
51#include <OpenEXR/ImfOutputFile.h>
52#include <OpenEXR/ImfPixelType.h>
53#include <OpenEXR/ImfPreviewImage.h>
54#include <OpenEXR/ImfRgbaFile.h>
55#include <OpenEXR/ImfStandardAttributes.h>
56#include <OpenEXR/ImfStringAttribute.h>
57#include <OpenEXR/ImfVersion.h>
58
59/* multiview/multipart */
60#include <OpenEXR/ImfInputPart.h>
61#include <OpenEXR/ImfMultiPartInputFile.h>
62#include <OpenEXR/ImfMultiPartOutputFile.h>
63#include <OpenEXR/ImfMultiView.h>
64#include <OpenEXR/ImfOutputPart.h>
65#include <OpenEXR/ImfPartHelper.h>
66#include <OpenEXR/ImfPartType.h>
67#include <OpenEXR/ImfTiledOutputPart.h>
68
69#include "DNA_scene_types.h" /* For OpenEXR compression constants */
70
71#include <openexr_api.h>
72
73#if defined(WIN32)
74# include "utfconv.hh"
75# include <io.h>
76#else
77# include <unistd.h>
78#endif
79
80#include "MEM_guardedalloc.h"
81
82#include "BLI_fileops.hh"
83#include "BLI_math_base.hh"
84#include "BLI_math_color_c.hh"
85#include "BLI_math_half.hh"
86#include "BLI_mmap.hh"
87#include "BLI_string.hh"
88#include "BLI_string_ref.hh"
89#include "BLI_string_utf8.hh"
90#include "BLI_task.hh"
91#include "BLI_threads.hh"
92
93#include "BKE_blender_version.h"
94#include "BKE_idprop.hh"
95#include "BKE_image.hh"
96
97#include "CLG_log.h"
98
100#include "IMB_imbuf.hh"
101#include "IMB_imbuf_types.hh"
102#include "IMB_metadata.hh"
103#include "IMB_openexr.hh"
104
105namespace blender {
106
107const char *imb_file_extensions_openexr[] = {".exr", nullptr};
108
109static CLG_LogRef LOG = {"image.openexr"};
110
111using namespace Imf;
112using namespace Imath;
113
114/* prototype */
115static bool exr_has_multiview(MultiPartInputFile &file);
116static bool exr_has_multipart_file(MultiPartInputFile &file);
117static bool exr_has_alpha(MultiPartInputFile &file);
118static bool exr_has_channels(MultiPartInputFile &file);
119static bool imb_exr_is_multi(MultiPartInputFile &file);
120static const ColorSpace *imb_exr_part_colorspace(const Header &header);
121static const Header &imb_exr_colorspace_header(const MultiPartInputFile &file);
122
123/* XYZ with Illuminant E */
124static Imf::Chromaticities CHROMATICITIES_XYZ_E{
125 {1.0f, 0.0f}, {0.0f, 1.0f}, {0.0f, 0.0f}, {1.0f / 3.0f, 1.0f / 3.0f}};
126/* Values matching ChromaticitiesForACES in https://github.com/ampas/aces_container */
127static Imf::Chromaticities CHROMATICITIES_ACES_2065_1{
128 {0.7347f, 0.2653f}, {0.0f, 1.0f}, {0.0001f, -0.077f}, {0.32168f, 0.33767f}};
129
130/* Memory Input Stream */
131
132class IMemStream : public Imf::IStream {
133 public:
134 IMemStream(uchar *exrbuf, size_t exrsize) : IStream("<memory>"), _exrpos(0), _exrsize(exrsize)
135 {
136 _exrbuf = exrbuf;
137 }
138
139 bool read(char c[], int n) override
140 {
141 if (n + _exrpos <= _exrsize) {
142 memcpy(c, (void *)(&_exrbuf[_exrpos]), n);
143 _exrpos += n;
144 return true;
145 }
146
147 return false;
148 }
149
151 {
152 return _exrpos;
153 }
154
155 void seekg(exr_file_offset_t pos) override
156 {
157 _exrpos = pos;
158 }
159
160 void clear() override {}
161
162 private:
163 exr_file_offset_t _exrpos;
164 exr_file_offset_t _exrsize;
165 uchar *_exrbuf;
166};
167
168/* Memory-Mapped Input Stream */
169
170class IMMapStream : public Imf::IStream {
171 public:
172 IMMapStream(const char *filepath) : IStream(filepath)
173 {
174 const int file = BLI_open(filepath, O_BINARY | O_RDONLY, 0);
175 if (file < 0) {
176 throw IEX_NAMESPACE::InputExc("file not found");
177 }
178 _exrpos = 0;
179 _mmap_file = BLI_mmap_open(file);
180 close(file);
181 if (_mmap_file == nullptr) {
182 throw IEX_NAMESPACE::InputExc("BLI_mmap_open failed");
183 }
184 _exrsize = BLI_mmap_get_length(_mmap_file);
185 }
186
187 ~IMMapStream() override
188 {
189 BLI_mmap_free(_mmap_file);
190 }
191
196 bool read(char c[], int n) override
197 {
198 if (_exrpos + n > _exrsize) {
199 throw Iex::InputExc("Unexpected end of file.");
200 }
201
202 if (!BLI_mmap_read(_mmap_file, c, _exrpos, n)) {
203 throw Iex::InputExc("Error reading file.");
204 }
205
206 _exrpos += n;
207
208 return _exrpos < _exrsize;
209 }
210
212 {
213 return _exrpos;
214 }
215
216 void seekg(exr_file_offset_t pos) override
217 {
218 _exrpos = pos;
219 }
220
221 private:
222 BLI_mmap_file *_mmap_file;
223 exr_file_offset_t _exrpos;
224 exr_file_offset_t _exrsize;
225};
226
227/* File Input Stream */
228
229class IFileStream : public Imf::IStream {
230 public:
231 IFileStream(const char *filepath) : IStream(filepath)
232 {
233 /* UTF8 file path support on windows. */
234#if defined(WIN32)
235 wchar_t *wfilepath = alloc_utf16_from_8(filepath, 0);
236 ifs.open(wfilepath, std::ios_base::binary);
237 free(wfilepath);
238#else
239 ifs.open(filepath, std::ios_base::binary);
240#endif
241
242 if (!ifs) {
243 Iex::throwErrnoExc();
244 }
245 }
246
247 bool read(char c[], int n) override
248 {
249 if (!ifs) {
250 throw Iex::InputExc("Unexpected end of file.");
251 }
252
253 errno = 0;
254 ifs.read(c, n);
255 return check_error();
256 }
257
259 {
260 return std::streamoff(ifs.tellg());
261 }
262
263 void seekg(exr_file_offset_t pos) override
264 {
265 ifs.seekg(pos);
266 check_error();
267 }
268
269 void clear() override
270 {
271 ifs.clear();
272 }
273
274 private:
275 bool check_error()
276 {
277 if (!ifs) {
278 if (errno) {
279 Iex::throwErrnoExc();
280 }
281
282 return false;
283 }
284
285 return true;
286 }
287
288 std::ifstream ifs;
289};
290
291/* Memory Output Stream */
292
293struct OMemStream : public OStream {
294 OMemStream() : OStream("<memory>"), offset(0)
295 {
296 buffer.reserve(80 * 1024);
297 }
298
299 void write(const char c[], int n) override
300 {
301 ensure_size(offset + n);
302 memcpy(buffer.data() + offset, c, n);
303 offset += n;
304 }
305
307 {
308 return offset;
309 }
310
311 void seekp(exr_file_offset_t pos) override
312 {
313 offset = pos;
315 }
316
318 {
319 if (size > buffer.size()) {
320 buffer.resize(size);
321 }
322 }
323
326};
327
328/* File Output Stream */
329
330class OFileStream : public OStream {
331 public:
332 OFileStream(const char *filepath) : OStream(filepath)
333 {
334 /* UTF8 file path support on windows. */
335#if defined(WIN32)
336 wchar_t *wfilepath = alloc_utf16_from_8(filepath, 0);
337 ofs.open(wfilepath, std::ios_base::binary);
338 free(wfilepath);
339#else
340 ofs.open(filepath, std::ios_base::binary);
341#endif
342
343 if (!ofs) {
344 Iex::throwErrnoExc();
345 }
346 }
347
348 void write(const char c[], int n) override
349 {
350 errno = 0;
351 ofs.write(c, n);
352 check_error();
353 }
354
356 {
357 return std::streamoff(ofs.tellp());
358 }
359
360 void seekp(exr_file_offset_t pos) override
361 {
362 ofs.seekp(pos);
363 check_error();
364 }
365
366 private:
367 void check_error()
368 {
369 if (!ofs) {
370 if (errno) {
371 Iex::throwErrnoExc();
372 }
373
374 throw Iex::ErrnoExc("File output failed.");
375 }
376 }
377
378 std::ofstream ofs;
379};
380
381bool imb_is_a_openexr(const uchar *mem, const size_t size)
382{
383 /* No define is exposed for this size. */
384 if (size < 4) {
385 return false;
386 }
387 return Imf::isImfMagic((const char *)mem);
388}
389
391{
392 q = math::clamp(q, 0, 100);
393
394 /* Map default JPG quality of 90 to default DWA level of 45,
395 * "lossless" JPG quality of 100 to DWA level of 0, and everything else
396 * linearly based on those. */
397 constexpr int x0 = 100, y0 = 0;
398 constexpr int x1 = 90, y1 = 45;
399 q = y0 + (q - x0) * (y1 - y0) / (x1 - x0);
400 return q;
401}
402
403static float compression_half_max(const int compression, const int quality)
404{
406 /* Empirically determined margin to prevent DWAA/DWAB lossy compression
407 * from overshooting to infinity. The DWA compression uses log2-luminance
408 * DCT, and overshoot increases with the compression level.
409 *
410 * Tested with randomized pixel patterns across various compression levels
411 * to find a tight bound. */
412 const int level = openexr_jpg_like_quality_to_dwa_compression_level(quality);
413 const float margin = (level <= 50) ? (2048.0f + 32.0f * level) :
414 (3624.0f + 128.0f * (level - 50));
415 return HALF_MAX - margin;
416 }
417
418 return HALF_MAX;
419}
420
421static int openexr_compression_for_data_colorspace(const int compression)
422{
423 /* Still write data passes lossless when using lossy compression. */
425 return R_IMF_EXR_CODEC_ZIP;
426 }
427 return compression;
428}
429
430static void openexr_header_compression(Header *header, int compression, int quality)
431{
432 switch (compression) {
434 header->compression() = NO_COMPRESSION;
435 break;
437 header->compression() = PXR24_COMPRESSION;
438 break;
440 header->compression() = ZIP_COMPRESSION;
441 break;
443 header->compression() = PIZ_COMPRESSION;
444 break;
446 header->compression() = RLE_COMPRESSION;
447 break;
449 header->compression() = ZIPS_COMPRESSION;
450 break;
452 header->compression() = B44_COMPRESSION;
453 break;
455 header->compression() = B44A_COMPRESSION;
456 break;
457#if OPENEXR_VERSION_MAJOR > 2 || (OPENEXR_VERSION_MAJOR >= 2 && OPENEXR_VERSION_MINOR >= 2)
459 header->compression() = DWAA_COMPRESSION;
460 header->dwaCompressionLevel() = openexr_jpg_like_quality_to_dwa_compression_level(quality);
461 break;
463 header->compression() = DWAB_COMPRESSION;
464 header->dwaCompressionLevel() = openexr_jpg_like_quality_to_dwa_compression_level(quality);
465 break;
466#endif
467#if COMBINED_OPENEXR_VERSION >= 30400
468 /* Always writing 32 scan-lines for now, could add an option for 256 scan-lines
469 * for slightly smaller files if there is demand for it. */
471 header->compression() = HTJ2K32_COMPRESSION;
472 break;
473#endif
474 default:
475 header->compression() = ZIP_COMPRESSION;
476 break;
477 }
478}
479
480static int openexr_header_get_compression(const Header &header)
481{
482 switch (header.compression()) {
483 case NO_COMPRESSION:
485 case RLE_COMPRESSION:
486 return R_IMF_EXR_CODEC_RLE;
487 case ZIPS_COMPRESSION:
489 case ZIP_COMPRESSION:
490 return R_IMF_EXR_CODEC_ZIP;
491 case PIZ_COMPRESSION:
492 return R_IMF_EXR_CODEC_PIZ;
493 case PXR24_COMPRESSION:
495 case B44_COMPRESSION:
496 return R_IMF_EXR_CODEC_B44;
497 case B44A_COMPRESSION:
499 case DWAA_COMPRESSION:
501 case DWAB_COMPRESSION:
503#if COMBINED_OPENEXR_VERSION >= 30400
504 case HTJ2K256_COMPRESSION:
505 case HTJ2K32_COMPRESSION:
507#endif
508#if COMBINED_OPENEXR_VERSION >= 30500
509 case LJ2K_COMPRESSION:
511 case ZSTD_COMPRESSION:
512 return R_IMF_EXR_CODEC_ZIP;
513#endif
514 case NUM_COMPRESSION_METHODS:
516 }
518}
519
520static bool openexr_metadata_skip_read(const char *name, const bool is_multi)
521{
522 /* For multi-layer reads, the part name and view are used for the view, layer, pass
523 * names. The metadata from the first part is used as shared metadata for all passes,
524 * as OpenEXR has no global metadata. So this would be wrong for all but the first pass.
525 *
526 * For single layer images we keep it, as in that case writing out the image again
527 * would otherwise lose the metadata. */
528 return is_multi && STR_ELEM(name, "name", "view");
529}
530
531static bool openexr_metadata_skip_write(const char *name, const bool is_multi)
532{
533 /* Do not blindly pass along compression or colorInteropID, as they might have changed
534 * and will already be written when appropriate. Same for metadata about the software
535 * that wrote the file and the type (scanline, tiled, deep).
536 *
537 * Multi-layer name and view are skipped, see #openexr_metadata_skip_read. */
538 return STR_ELEM(
539 name, "compression", "colorInteropID", "Software", "BlenderMultiChannel", "type") ||
540 (is_multi && STR_ELEM(name, "name", "view"));
541}
542
544{
545 header->insert(
546 "Software",
547 TypedAttribute<std::string>(std::string("Blender ") + BKE_blender_version_string()));
548
549 if (metadata) {
550 for (IDProperty &prop : metadata->data.group) {
551 if ((prop.type == IDP_STRING) && !openexr_metadata_skip_write(prop.name, false)) {
552 header->insert(prop.name, StringAttribute(IDP_string_get(&prop)));
553 }
554 }
555 }
556}
557
558static void openexr_header_metadata_pixelinfo(Header *header, const double ppm[2])
559{
560 if (ppm[0] > 0.0 && ppm[1] > 0.0) {
561 /* Convert meters to inches. */
562 addXDensity(*header, ppm[0] * 0.0254);
563 header->pixelAspectRatio() = math::safe_divide(ppm[1], ppm[0]);
564 }
565}
566
568{
569 if (colorspace == nullptr) {
570 return;
571 }
572
573 const char *aces_colorspace = IMB_colormanagement_role_colorspace_name_get(
575 const char *ibuf_colorspace = IMB_colormanagement_colorspace_get_name(colorspace);
576
577 /* Write chromaticities for ACES-2065-1, as required by ACES container format. */
578 if (aces_colorspace && STREQ(aces_colorspace, ibuf_colorspace)) {
579 header->insert("chromaticities", TypedAttribute<Chromaticities>(CHROMATICITIES_ACES_2065_1));
580 header->insert("adoptedNeutral", TypedAttribute<V2f>(CHROMATICITIES_ACES_2065_1.white));
581 }
582
583 /* Write interop ID if available. */
585 if (!interop_id.is_empty()) {
586 header->insert("colorInteropID", TypedAttribute<std::string>(interop_id));
587 }
588}
589
590static void openexr_header_metadata_colorspace(Header *header, const ImBuf *ibuf)
591{
592 /* Get colorspace from image buffer. */
593 const ColorSpace *colorspace = nullptr;
594 if (ibuf->float_data()) {
596 if (colorspace == nullptr) {
599 }
600 }
601 else if (ibuf->byte_data()) {
603 }
604
606}
607
614
615static void convert_input_to_half_rgba(const ImBuf *ibuf, RGBAHalf *dst)
616{
617 const int channels = ibuf->channels;
618 const bool is_alpha = (channels >= 4) && (ibuf->can_contain_alpha());
619 const int width = ibuf->x;
620 const int height = ibuf->y;
621
622 if (ibuf->float_data()) {
623 const float *float_data = ibuf->float_data();
624
625 const int compression = ibuf->foptions.flag & OPENEXR_CODEC_MASK;
626 const float half_max_val = compression_half_max(compression, ibuf->foptions.quality);
627 const int comp_r = 0;
628 const int comp_g = channels >= 2 ? 1 : 0;
629 const int comp_b = channels >= 3 ? 2 : 0;
630 const int comp_a = channels >= 4 ? 3 : 0;
631
633 Array<float4> row_buffer(width);
634 RGBAHalf *to_row = dst + y * width;
635
636 const float *from = float_data + int64_t(channels) * (ibuf->y - 1 - y) * width;
637 for (int x = 0; x < ibuf->x; x++) {
638 row_buffer[x] = float4(from[comp_r], from[comp_g], from[comp_b], from[comp_a]);
639 from += channels;
640 }
642 &row_buffer.data()->x, &to_row->r, 4 * width, -half_max_val, half_max_val);
643 });
644 }
645 else {
646 uint16_t color_to_half[256];
647 uint16_t alpha_to_half[256];
648 for (int v = 0; v < 256; v++) {
650 alpha_to_half[v] = math::float_to_half(float(v) / 255.0f);
651 }
652
653 const uchar *byte_data = ibuf->byte_data();
654
655 for (int i = ibuf->y - 1; i >= 0; i--) {
656 const uchar *from = byte_data + int64_t(4) * i * width;
657
658 for (int j = ibuf->x; j > 0; j--) {
659 dst->r = color_to_half[from[0]];
660 dst->g = color_to_half[from[1]];
661 dst->b = color_to_half[from[2]];
662 dst->a = is_alpha ? alpha_to_half[from[3]] : 0x3c00; /* 0x3c00 = FP16 1.0 */
663 dst++;
664 from += 4;
665 }
666 }
667 }
668}
669
670static void save_setup_header(const ImBuf *ibuf,
671 bool half_precision,
672 bool is_alpha,
673 Header &header)
674{
675 const int compression = ibuf->foptions.flag & OPENEXR_CODEC_MASK;
676 openexr_header_compression(&header, compression, ibuf->foptions.quality);
680
681 /* create channels */
682 Channel channel(half_precision ? HALF : FLOAT);
683 header.channels().insert("R", channel);
684 header.channels().insert("G", channel);
685 header.channels().insert("B", channel);
686 if (is_alpha) {
687 header.channels().insert("A", channel);
688 }
689}
690
691static void save_setup_framebuffer(const ImBuf *ibuf,
692 bool half_precision,
693 bool is_alpha,
694 Vector<RGBAHalf> &half_pixels,
695 FrameBuffer &frameBuffer)
696{
697 const int width = ibuf->x;
698 const int height = ibuf->y;
699 const int channels = ibuf->channels;
700
701 if (half_precision) {
702 half_pixels.resize(int64_t(height) * width);
703 RGBAHalf *to = half_pixels.data();
704 int xstride = sizeof(RGBAHalf);
705 int ystride = xstride * width;
706 frameBuffer.insert("R", Slice(HALF, (char *)&to->r, xstride, ystride));
707 frameBuffer.insert("G", Slice(HALF, (char *)&to->g, xstride, ystride));
708 frameBuffer.insert("B", Slice(HALF, (char *)&to->b, xstride, ystride));
709 if (is_alpha) {
710 frameBuffer.insert("A", Slice(HALF, (char *)&to->a, xstride, ystride));
711 }
712
713 convert_input_to_half_rgba(ibuf, half_pixels.data());
714 }
715 else {
716 int xstride = sizeof(float) * channels;
717 int ystride = -xstride * width;
718
719 /* Last scan-line, stride negative. */
720 const float *src_data = ibuf->float_data() + int64_t(channels) * (height - 1) * width;
721 frameBuffer.insert("R", Slice(FLOAT, (char *)src_data, xstride, ystride));
722 frameBuffer.insert(
723 "G", Slice(FLOAT, (char *)(src_data + (channels >= 2 ? 1 : 0)), xstride, ystride));
724 frameBuffer.insert(
725 "B", Slice(FLOAT, (char *)(src_data + (channels >= 3 ? 2 : 0)), xstride, ystride));
726 if (is_alpha) {
727 frameBuffer.insert("A", Slice(FLOAT, (char *)(src_data + 3), xstride, ystride));
728 }
729 }
730}
731
732bool imb_save_openexr(ImBuf *ibuf, const char *filepath, ImBufFlags /*flags*/)
733{
734 /* Use half precision when asked for it, or if source is a
735 * byte image (half precision is always enough for that case). */
736 const bool half_precision = (ibuf->foptions.flag & OPENEXR_HALF) ||
737 ibuf->float_data() == nullptr;
738 const bool is_alpha = (ibuf->channels >= 4) && (ibuf->can_contain_alpha());
739 try {
740 Header header(ibuf->x, ibuf->y);
741 save_setup_header(ibuf, half_precision, is_alpha, header);
742
743 OFileStream file_stream(filepath);
744 OutputFile file(file_stream, header);
745
746 FrameBuffer frameBuffer;
747 Vector<RGBAHalf> half_pixels;
748 save_setup_framebuffer(ibuf, half_precision, is_alpha, half_pixels, frameBuffer);
749 file.setFrameBuffer(frameBuffer);
750 file.writePixels(ibuf->y);
751 return true;
752 }
753 catch (const std::exception &exc) {
754 CLOG_ERROR(&LOG, "%s: %s", __func__, exc.what());
755 return false;
756 }
757 catch (...) { /* Catch-all for RTTI or symbol visibility mismatches. */
758 CLOG_ERROR(&LOG, "Unknown error in %s", __func__);
759 return false;
760 }
761}
762
764{
765 /* Use half precision when asked for it, or if source is a
766 * byte image (half precision is always enough for that case). */
767 const bool half_precision = (ibuf->foptions.flag & OPENEXR_HALF) ||
768 ibuf->float_data() == nullptr;
769
770 const bool is_alpha = (ibuf->channels >= 4) && (ibuf->can_contain_alpha());
771 try {
772 Header header(ibuf->x, ibuf->y);
773 save_setup_header(ibuf, half_precision, is_alpha, header);
774
775 OMemStream mem_stream;
776 OutputFile file(mem_stream, header);
777
778 FrameBuffer frameBuffer;
779 Vector<RGBAHalf> half_pixels;
780 save_setup_framebuffer(ibuf, half_precision, is_alpha, half_pixels, frameBuffer);
781 file.setFrameBuffer(frameBuffer);
782 file.writePixels(ibuf->y);
783 return std::move(mem_stream.buffer);
784 }
785 catch (const std::exception &exc) {
786 CLOG_ERROR(&LOG, "%s: %s", __func__, exc.what());
787 }
788 catch (...) { /* Catch-all for RTTI or symbol visibility mismatches. */
789 CLOG_ERROR(&LOG, "Unknown error in %s", __func__);
790 }
791 return {};
792}
793
794/* ******* Nicer API, MultiLayer and with Tile file support ************************************ */
795
796/* naming rules:
797 * - parse name from right to left
798 * - last character is channel ID, 1 char like 'A' 'R' 'G' 'B' 'X' 'Y' 'Z' 'W' 'U' 'V'
799 * - separated with a dot; the Pass name (like "Depth", "Color", "Diffuse" or "Combined")
800 * - separated with a dot: the Layer name (like "Light1" or "Walls" or "Characters")
801 */
802
806 std::string part_name;
807 int part_number = 0;
808
810 std::string name;
812 std::string internal_name;
814 std::string view;
815
818
820 int xstride = 0;
822 int ystride = 0;
824 int offset = 0;
826 float *rect = nullptr;
828 char chan_id = 0;
830 bool use_half_float = false;
831};
832
834struct ExrPass {
835 std::string name;
836 int totchan = 0;
838 /* Extra byte for null termination of string. */
839 char chan_id[EXR_PASS_MAXCHAN + 1] = {};
840
842 std::string internal_name;
843 std::string view;
844};
845
846struct ExrLayer {
847 std::string name;
849};
850
852 IStream *ifile_stream = nullptr;
853 MultiPartInputFile *ifile = nullptr;
854
855 int width = 0, height = 0;
856
857 StringVector views;
858
867 bool channels_parsed = false;
868};
869
872 MultiPartOutputFile *mpofile = nullptr;
873 OutputFile *ofile = nullptr;
874
875 bool write_multipart = false;
877 float half_max_val = HALF_MAX;
878
879 int width = 0, height = 0;
880
881 StringVector views;
882
885};
886
888static Vector<ExrChannel> exr_channels_in_multi_part_file(const MultiPartInputFile &file);
889static void imb_exr_write_channels(ExrWriteHandle *handle);
890
891/* ********************** */
892
893ExrWriteHandle *IMB_exr_write_begin(const bool write_multipart)
894{
895 ExrWriteHandle *handle = MEM_new<ExrWriteHandle>("ExrWriteHandle");
896 handle->write_multipart = write_multipart;
897 return handle;
898}
899
900/* multiview functions */
901
902void IMB_exr_write_view(ExrWriteHandle *handle, const char *viewname)
903{
904 handle->views.emplace_back(viewname);
905}
906
907static int imb_exr_get_multiView_id(StringVector &views, const std::string &name)
908{
909 int count = 0;
910 for (StringVector::const_iterator i = views.begin(); count < views.size(); ++i) {
911 if (name == *i) {
912 return count;
913 }
914
915 count++;
916 }
917
918 /* no views or wrong name */
919 return -1;
920}
921
922static StringVector imb_exr_get_views(MultiPartInputFile &file)
923{
924 StringVector views;
925
926 for (int p = 0; p < file.parts(); p++) {
927 /* Views stored in separate parts. */
928 if (file.header(p).hasView()) {
929 const std::string &view = file.header(p).view();
930 if (imb_exr_get_multiView_id(views, view) == -1) {
931 views.push_back(view);
932 }
933 }
934
935 /* Part containing multiple views. */
936 if (hasMultiView(file.header(p))) {
937 StringVector multiview = multiView(file.header(p));
938 for (const std::string &view : multiview) {
939 if (imb_exr_get_multiView_id(views, view) == -1) {
940 views.push_back(view);
941 }
942 }
943 }
944 }
945
946 return views;
947}
948
950 StringRefNull layerpassname,
951 StringRefNull channelnames,
952 StringRefNull viewname,
954 size_t xstride,
955 size_t ystride,
956 const float *rect,
957 bool use_half_float)
958{
959 /* For multipart, part name includes view since part names must be unique. */
960 std::string part_name;
961 if (handle->write_multipart) {
962 part_name = layerpassname;
963 if (!viewname.is_empty()) {
964 if (part_name.empty()) {
965 part_name = viewname;
966 }
967 else {
968 part_name = part_name + "-" + viewname;
969 }
970 }
971 }
972
973 /* If there are layer and pass names, we will write Blender multichannel metadata. */
974 if (!layerpassname.is_empty()) {
975 handle->has_layer_pass_names = true;
976 }
977
978 for (size_t channel = 0; channel < channelnames.size(); channel++) {
979 /* Full channel name including view (when not using multipart) and channel. */
980 std::string full_name = layerpassname;
981 if (!handle->write_multipart && !viewname.is_empty()) {
982 if (full_name.empty()) {
983 full_name = viewname;
984 }
985 else {
986 full_name = full_name + "." + viewname;
987 }
988 }
989 if (full_name.empty()) {
990 full_name = channelnames[channel];
991 }
992 else {
993 full_name = full_name + "." + channelnames[channel];
994 }
995
996 handle->channels.append_as();
997 ExrChannel &echan = handle->channels.last();
998
999 echan.name = full_name;
1000 echan.internal_name = full_name;
1001 echan.part_name = part_name;
1002 echan.view = viewname;
1004
1005 echan.xstride = xstride;
1006 echan.ystride = ystride;
1007 /* This is used for writing, the data should not be modified. ????????? */
1008 echan.rect = const_cast<float *>(rect + channel);
1009 echan.use_half_float = use_half_float && !IMB_colormanagement_space_is_data(echan.colorspace);
1010 }
1011
1012 CLOG_DEBUG(&LOG, "Added pass %s %s", layerpassname.c_str(), channelnames.c_str());
1013}
1014
1016 Header &header,
1017 const StampData *stamp)
1018{
1019 openexr_header_metadata_global(&header, nullptr);
1020 if (handle->has_layer_pass_names) {
1021 header.insert("BlenderMultiChannel", StringAttribute("Blender V2.55.1 and newer"));
1022 }
1023 if (!handle->write_multipart && !handle->views.empty() && !handle->views[0].empty()) {
1024 addMultiView(header, handle->views);
1025 }
1027 &header,
1028 const_cast<StampData *>(stamp),
1029 [](void *data, const char *propname, char *prop, int /*len*/) {
1030 if (!openexr_metadata_skip_write(propname, true)) {
1031 Header *header = (Header *)data;
1032 header->insert(propname, StringAttribute(prop));
1033 }
1034 },
1035 false);
1036}
1037
1039 const char *filepath,
1040 int width,
1041 int height,
1042 const double ppm[2],
1043 int compress,
1044 int quality,
1045 const StampData *stamp)
1046{
1047 if (handle->channels.is_empty()) {
1048 CLOG_ERROR(&LOG, "Attempt to save MultiLayer without layers.");
1049 MEM_delete(handle);
1050 return false;
1051 }
1052
1053 bool ok = true;
1054
1055 try {
1056 Header header(width, height);
1057
1058 handle->width = width;
1059 handle->height = height;
1060
1061 openexr_header_compression(&header, compress, quality);
1062 handle->half_max_val = compression_half_max(compress, quality);
1063
1065
1066 if (!handle->write_multipart) {
1067 /* If we're writing single part, we can only add one colorspace even if there are
1068 * multiple passes with potentially different spaces. Prefer to write non-data
1069 * colorspace in that case, since readers can detect data passes based on
1070 * channels names being e.g. XYZ instead of RGB. */
1071 bool found = false;
1072 for (const ExrChannel &echan : handle->channels) {
1075 found = true;
1076 break;
1077 }
1078 }
1079 if (!found) {
1080 if (const ColorSpace *colorspace = handle->channels[0].colorspace) {
1082 }
1083 }
1084 }
1085
1086 Vector<Header> part_headers;
1087
1088 StringRefNull last_part_name;
1089
1090 for (const ExrChannel &echan : handle->channels) {
1091 if (part_headers.is_empty() || last_part_name != echan.part_name) {
1092 Header part_header = header;
1093
1094 /* Store global metadata in the first header only. Large metadata like cryptomatte would
1095 * be bad to duplicate many times. */
1096 if (part_headers.is_empty()) {
1097 openexr_header_metadata_multi(handle, part_header, stamp);
1098 }
1099
1100 /* When writing multipart, set name, view, type and colorspace in each part.
1101 *
1102 * Note we do this after openexr_header_metadata_multi to replace any attributes with the
1103 * same name, because e.g. the part header name is really just a "name" attribute. */
1104 if (handle->write_multipart) {
1105 part_header.setName(echan.part_name);
1106 if (!echan.view.empty()) {
1107 part_header.insert("view", StringAttribute(echan.view));
1108 }
1109 part_header.insert("type", StringAttribute(SCANLINEIMAGE));
1111
1114 &part_header, openexr_compression_for_data_colorspace(compress), quality);
1115 }
1116 }
1117
1118 part_headers.append(std::move(part_header));
1119 last_part_name = echan.part_name;
1120 }
1121
1122 part_headers.last().channels().insert(
1123 echan.name, Channel(echan.use_half_float ? Imf::HALF : Imf::FLOAT));
1124 }
1125
1126 BLI_assert(!(handle->write_multipart == false && part_headers.size() > 1));
1127
1128 /* Manually create `ofstream`, so we can handle UTF8 file-paths on windows. */
1129 handle->ofile_stream = new OFileStream(filepath);
1130 if (handle->write_multipart) {
1131 handle->mpofile = new MultiPartOutputFile(
1132 *(handle->ofile_stream), part_headers.data(), part_headers.size());
1133 }
1134 else {
1135 handle->ofile = new OutputFile(*(handle->ofile_stream), part_headers[0]);
1136 }
1137
1138 imb_exr_write_channels(handle);
1139 }
1140 catch (const std::exception &exc) {
1141 CLOG_ERROR(&LOG, "%s: %s", __func__, exc.what());
1142 ok = false;
1143 }
1144 catch (...) { /* Catch-all for RTTI or symbol visibility mismatches. */
1145 CLOG_ERROR(&LOG, "Unknown error in %s", __func__);
1146 ok = false;
1147 }
1148
1149 delete handle->ofile;
1150 delete handle->mpofile;
1151 delete handle->ofile_stream;
1152
1153 MEM_delete(handle);
1154
1155 return ok;
1156}
1157
1158ExrReadHandle *IMB_exr_open(const char *filepath)
1159{
1160 /* 32 is arbitrary, but zero length files crashes exr. */
1161 if (!(BLI_exists(filepath) && BLI_file_size(filepath) > 32)) {
1162 return nullptr;
1163 }
1164
1165 ExrReadHandle *handle = MEM_new<ExrReadHandle>("ExrReadHandle");
1166 bool ok = true;
1167
1168 /* avoid crash/abort when we don't have permission to write here */
1169 try {
1170 handle->ifile_stream = new IFileStream(filepath);
1171 handle->ifile = new MultiPartInputFile(*(handle->ifile_stream));
1172
1173 const Box2i dw = handle->ifile->header(0).dataWindow();
1174 handle->width = dw.max.x - dw.min.x + 1;
1175 handle->height = dw.max.y - dw.min.y + 1;
1176 }
1177 catch (const std::exception &exc) {
1178 CLOG_ERROR(&LOG, "%s: %s", __func__, exc.what());
1179 ok = false;
1180 }
1181 catch (...) { /* Catch-all for RTTI or symbol visibility mismatches. */
1182 CLOG_ERROR(&LOG, "Unknown error in %s", __func__);
1183 ok = false;
1184 }
1185
1186 if (!ok) {
1187 delete handle->ifile;
1188 delete handle->ifile_stream;
1189
1190 handle->ifile = nullptr;
1191 handle->ifile_stream = nullptr;
1192
1193 IMB_exr_close(handle);
1194 return nullptr;
1195 }
1196
1197 return handle;
1198}
1199
1201{
1202 if (handle->channels.is_empty()) {
1203 CLOG_ERROR(&LOG, "Attempt to save MultiLayer without layers.");
1204 return;
1205 }
1206
1207 const size_t num_pixels = size_t(handle->width) * handle->height;
1208 const size_t num_parts = (handle->mpofile) ? handle->mpofile->parts() : 1;
1209
1210 for (size_t part_num = 0; part_num < num_parts; part_num++) {
1211 const std::string &part_id = (handle->mpofile) ? handle->mpofile->header(part_num).name() : "";
1212 /* We allocate temporary storage for half pixels for all the channels at once. */
1213 int num_half_channels = 0;
1214 for (const ExrChannel &echan : handle->channels) {
1215 if (echan.part_name == part_id && echan.use_half_float) {
1216 num_half_channels++;
1217 }
1218 }
1219
1220 Vector<uint16_t> rect_half;
1221 uint16_t *current_rect_half = nullptr;
1222 if (num_half_channels > 0) {
1223 rect_half.resize(size_t(num_half_channels) * num_pixels);
1224 current_rect_half = rect_half.data();
1225 }
1226
1227 FrameBuffer frameBuffer;
1228
1229 for (const ExrChannel &echan : handle->channels) {
1230 /* Writing starts from last scan-line, stride negative. */
1231 if (echan.part_name != part_id) {
1232 continue;
1233 }
1234
1235 if (echan.use_half_float) {
1236 const float *src_float = echan.rect;
1237 /* Convert & clamp input floats to half-floats. */
1238 threading::parallel_for(IndexRange(num_pixels), 16 * 1024, [&](IndexRange range) {
1239 Array<float> gathered_floats(range.size());
1240 int64_t i = 0;
1241 for (int64_t index : range) {
1242 gathered_floats[i++] = src_float[index * echan.xstride];
1243 }
1244 math::float_to_half_clamp_array(gathered_floats.data(),
1245 current_rect_half + range.first(),
1246 range.size(),
1247 -handle->half_max_val,
1248 handle->half_max_val);
1249 });
1250
1251 uint16_t *rect_to_write = current_rect_half + (handle->height - 1L) * handle->width;
1252 frameBuffer.insert(
1253 echan.name,
1254 Slice(Imf::HALF, (char *)rect_to_write, sizeof(half), -handle->width * sizeof(half)));
1255 current_rect_half += num_pixels;
1256 }
1257 else {
1258 float *rect = echan.rect + echan.xstride * (handle->height - 1L) * handle->width;
1259 frameBuffer.insert(echan.name,
1260 Slice(Imf::FLOAT,
1261 (char *)rect,
1262 echan.xstride * sizeof(float),
1263 -echan.ystride * sizeof(float)));
1264 }
1265 }
1266
1267 try {
1268 if (handle->mpofile) {
1269 OutputPart part(*handle->mpofile, part_num);
1270 part.setFrameBuffer(frameBuffer);
1271 part.writePixels(handle->height);
1272 }
1273 else {
1274 handle->ofile->setFrameBuffer(frameBuffer);
1275 handle->ofile->writePixels(handle->height);
1276 }
1277 }
1278 catch (const std::exception &exc) {
1279 CLOG_ERROR(&LOG, "%s: %s", __func__, exc.what());
1280 }
1281 catch (...) { /* Catch-all for RTTI or symbol visibility mismatches. */
1282 CLOG_ERROR(&LOG, "Unknown error in %s", __func__);
1283 }
1284 }
1285}
1286
1289{
1290 try {
1291 int numparts = handle->ifile->parts();
1292
1293 /* Check if EXR was saved with previous versions of blender which flipped images. */
1294 const StringAttribute *ta = handle->ifile->header(0).findTypedAttribute<StringAttribute>(
1295 "BlenderMultiChannel");
1296
1297 /* 'previous multilayer attribute, flipped. */
1298 short flip = (ta && STRPREFIX(ta->value().c_str(), "Blender V2.43"));
1299
1300 CLOG_DEBUG(&LOG,
1301 "\nIMB_exr_read_channels\n%s %-6s %-22s "
1302 "\"%s\"\n---------------------------------------------------------------------",
1303 "p",
1304 "view",
1305 "name",
1306 "internal_name");
1307
1308 for (int i = 0; i < numparts; i++) {
1309 /* Skip parts from which we don't need any channel. */
1310 bool part_has_buffer = false;
1311 for (const ExrChannel &echan : handle->channels) {
1312 if (echan.part_number == i && echan.rect) {
1313 part_has_buffer = true;
1314 break;
1315 }
1316 }
1317 if (!part_has_buffer) {
1318 continue;
1319 }
1320
1321 try {
1322 /* Read part header. */
1323 InputPart in(*handle->ifile, i);
1324 Header header = in.header();
1325 Box2i dw = header.dataWindow();
1326
1327 /* Insert all matching channel into frame-buffer. */
1328 FrameBuffer frameBuffer;
1329
1330 for (const ExrChannel &echan : handle->channels) {
1331 if (echan.part_number != i) {
1332 continue;
1333 }
1334
1335 CLOG_DEBUG(&LOG,
1336 "%d %-6s %-22s \"%s\"\n",
1337 echan.part_number,
1338 echan.view.c_str(),
1339 echan.name.c_str(),
1340 echan.internal_name.c_str());
1341
1342 if (echan.rect) {
1343 float *rect = echan.rect;
1344 size_t xstride = echan.xstride * sizeof(float);
1345 size_t ystride = echan.ystride * sizeof(float);
1346
1347 if (!flip) {
1348 /* Inverse correct first pixel for data-window coordinates. */
1349 rect -= echan.xstride * (dw.min.x - dw.min.y * handle->width);
1350 /* Move to last scan-line to flip to Blender convention. */
1351 rect += echan.xstride * (handle->height - 1) * handle->width;
1352 ystride = -ystride;
1353 }
1354 else {
1355 /* Inverse correct first pixel for data-window coordinates. */
1356 rect -= echan.xstride * (dw.min.x + dw.min.y * handle->width);
1357 }
1358
1359 frameBuffer.insert(echan.internal_name,
1360 Slice(Imf::FLOAT, (char *)rect, xstride, ystride));
1361 }
1362 }
1363
1364 /* Read pixels. */
1365 in.setFrameBuffer(frameBuffer);
1366 CLOG_DEBUG(&LOG, "readPixels:readPixels[%d]: min.y: %d, max.y: %d", i, dw.min.y, dw.max.y);
1367 in.readPixels(dw.min.y, dw.max.y);
1368 }
1369 catch (const std::exception &exc) {
1370 CLOG_ERROR(&LOG, "%s: %s", __func__, exc.what());
1371 break;
1372 }
1373 catch (...) { /* Catch-all for RTTI or symbol visibility mismatches. */
1374 CLOG_ERROR(&LOG, "Unknown error in %s", __func__);
1375 break;
1376 }
1377 }
1378 }
1379 catch (const std::exception &exc) {
1380 CLOG_ERROR(&LOG, "%s: %s", __func__, exc.what());
1381 }
1382 catch (...) { /* Catch-all for RTTI or symbol visibility mismatches. */
1383 CLOG_ERROR(&LOG, "Unknown error in %s", __func__);
1384 }
1385}
1386
1388{
1389 return int2(handle->width, handle->height);
1390}
1391
1392/* Stamp ppm + display window from the EXR file header onto the ImBuf. */
1393static void imb_exr_set_ibuf_display_window(MultiPartInputFile &file, ImBuf *ibuf);
1394
1396{
1399 for (ExrLayer &lay : handle->layers) {
1400 for (ExrPass &pass : lay.passes) {
1401 if (pass.totchan == 0) {
1402 continue;
1403 }
1404 out.append({.layer = lay.name,
1405 .pass = pass.internal_name,
1406 .view = pass.view,
1407 .chan_id = StringRefNull(pass.chan_id, strnlen(pass.chan_id, EXR_PASS_MAXCHAN)),
1408 .channels = pass.totchan});
1409 }
1410 }
1411 return out;
1412}
1413
1415{
1418 for (const std::string &view : handle->views) {
1419 out.append(view);
1420 }
1421 return out;
1422}
1423
1426 const char *src_colorspace,
1427 const bool predivide)
1428{
1429 if (handle == nullptr || entries.is_empty()) {
1430 return;
1431 }
1432
1434
1435 const int width = handle->width;
1436 const int height = handle->height;
1437
1438 /* Find matching layer and pass for every pass info to read. */
1439 for (ExrPassInfo &entry : entries) {
1440 bool found = false;
1441 for (ExrLayer &lay : handle->layers) {
1442 if (lay.name != entry.layer) {
1443 continue;
1444 }
1445 for (ExrPass &pass : lay.passes) {
1446 if (pass.internal_name != entry.pass || pass.view != entry.view) {
1447 continue;
1448 }
1449
1450 /* Allocate a destination ImBuf if the caller didn't provide one. */
1451 if (entry.ibuf == nullptr) {
1452 entry.ibuf = IMB_allocImBuf(width, height, ImBufFlags::Zero);
1453 if (entry.ibuf == nullptr) {
1454 break;
1455 }
1456 entry.ibuf->color_mode = IMB_color_mode_from_channels(pass.totchan);
1457 if (!IMB_alloc_float_pixels(entry.ibuf, pass.totchan)) {
1458 IMB_freeImBuf(entry.ibuf);
1459 entry.ibuf = nullptr;
1460 found = true;
1461 break;
1462 }
1463 }
1464 else {
1465 BLI_assert(entry.ibuf->x == width && entry.ibuf->y == height);
1466 }
1467
1468 /* Populate per channel pixel pointers.
1469 *
1470 * This allows different number of source and destination channels for th
1471 * RenderResult.load_from_file API, which has historically supported this. */
1472 float *data = entry.ibuf->float_data_for_write();
1473 for (int a = 0; a < pass.totchan; a++) {
1474 ExrChannel &echan = *pass.chan[a];
1475 if (echan.offset >= entry.ibuf->channels) {
1476 continue;
1477 }
1478 echan.xstride = entry.ibuf->channels;
1479 echan.ystride = width * entry.ibuf->channels;
1480 echan.rect = data + echan.offset;
1481 }
1482 found = true;
1483 break;
1484 }
1485 if (found) {
1486 break;
1487 }
1488 }
1489 }
1490
1491 /* Read the requested channels. */
1492 imb_exr_read_channels(handle);
1493
1494 /* Clear per channel pixel pointers again. */
1495 for (ExrLayer &lay : handle->layers) {
1496 for (ExrPass &pass : lay.passes) {
1497 for (int a = 0; a < pass.totchan; a++) {
1498 pass.chan[a]->rect = nullptr;
1499 }
1500 }
1501 }
1502
1503 for (ExrPassInfo &entry : entries) {
1504 if (entry.ibuf == nullptr) {
1505 continue;
1506 }
1507
1508 /* Add metadata. */
1509 imb_exr_set_ibuf_display_window(*handle->ifile, entry.ibuf);
1510
1511 /* Convert and assign colorspace. */
1512 if (src_colorspace) {
1513 if (IMB_chan_id_is_color(entry.chan_id)) {
1514 const char *to_colorspace = IMB_colormanagement_role_colorspace_name_get(
1516 IMB_colormanagement_transform_float(entry.ibuf->float_data_for_write(),
1517 entry.ibuf->x,
1518 entry.ibuf->y,
1519 entry.ibuf->channels,
1520 src_colorspace,
1521 to_colorspace,
1522 predivide);
1523 }
1524 else {
1525 const char *data_colorspace = IMB_colormanagement_role_colorspace_name_get(
1527 IMB_colormanagement_assign_float_colorspace(entry.ibuf, data_colorspace);
1528 }
1529 }
1530 }
1531}
1532
1534{
1535 Vector<ExrPassInfo> passes = IMB_exr_get_passes(handle);
1536 if (passes.is_empty()) {
1537 return false;
1538 }
1539
1540 /* Prefer the combined pass, then any other RGB(A) pass, then the first pass. */
1541 ExrPassInfo *combined = nullptr;
1542 ExrPassInfo *rgb = nullptr;
1543 for (ExrPassInfo &info : passes) {
1544 if (info.pass == RE_PASSNAME_COMBINED) {
1545 combined = &info;
1546 break;
1547 }
1548 if (rgb == nullptr && ELEM(info.chan_id, "RGBA", "RGB")) {
1549 rgb = &info;
1550 }
1551 }
1552 ExrPassInfo *chosen = combined ? combined : rgb ? rgb : &passes.first();
1553
1554 /* Read pixels, as 1, 3 or 4 channels. */
1555 const int channels = ELEM(chosen->channels, 1, 3, 4) ? chosen->channels : 3;
1556 if (!IMB_alloc_float_pixels(ibuf, channels)) {
1557 return false;
1558 }
1559 ibuf->color_mode = IMB_color_mode_from_channels(channels);
1560 chosen->ibuf = ibuf;
1561
1562 MutableSpan<ExrPassInfo> single(chosen, 1);
1563 IMB_exr_read_passes(handle, single, nullptr, false);
1564 return true;
1565}
1566
1568{
1569 delete handle->ifile;
1570 delete handle->ifile_stream;
1571
1572 MEM_delete(handle);
1573}
1574
1575/* ********* */
1576
1578static int imb_exr_split_token(const char *str, const char *end, const char **token)
1579{
1580 const char delims[] = {'.', '\0'};
1581 const char *sep;
1582
1583 BLI_str_partition_ex(str, end, delims, &sep, token, true);
1584
1585 if (!sep) {
1586 *token = str;
1587 }
1588
1589 return int(end - *token);
1590}
1591
1592static void imb_exr_pass_name_from_channel(char *passname,
1593 const ExrChannel &echan,
1594 const char *channelname,
1595 const bool has_xyz_channels)
1596{
1597 const int passname_maxncpy = EXR_TOT_MAXNAME;
1598
1599 if (echan.chan_id == 'Z' && (!has_xyz_channels || BLI_strcaseeq(channelname, "depth"))) {
1600 BLI_strncpy_utf8(passname, "Depth", passname_maxncpy);
1601 }
1602 else if (echan.chan_id == 'Y' && !has_xyz_channels) {
1603 BLI_strncpy_utf8(passname, channelname, passname_maxncpy);
1604 }
1605 else if (ELEM(echan.chan_id, 'R', 'G', 'B', 'A', 'V', 'X', 'Y', 'Z')) {
1606 BLI_strncpy_utf8(passname, "Combined", passname_maxncpy);
1607 }
1608 else {
1609 BLI_strncpy_utf8(passname, channelname, passname_maxncpy);
1610 }
1611}
1612
1613static void imb_exr_pass_name_from_channel_name(char *passname,
1614 const ExrChannel & /*echan*/,
1615 const char *channelname,
1616 const bool /*has_xyz_channels*/)
1617{
1618 const int passname_maxncpy = EXR_TOT_MAXNAME;
1619
1620 /* TODO: Are special tricks similar to imb_exr_pass_name_from_channel() needed here?
1621 * Note that unknown passes are default to chan_id='X'. The place where this function is called
1622 * is when the channel name is more than 1 character, so perhaps using just channel ID is not
1623 * fully correct here. */
1624
1625 BLI_strncpy_utf8(passname, channelname, passname_maxncpy);
1626}
1627
1629 char *layname,
1630 char *passname,
1631 bool has_xyz_channels)
1632{
1633 const int layname_maxncpy = EXR_TOT_MAXNAME;
1634 const int passname_maxncpy = EXR_TOT_MAXNAME;
1635 const char *name = echan.name.c_str();
1636 const char *end = name + strlen(name);
1637 const char *token;
1638
1639 /* Some multi-layers have the combined buffer with names V, RGBA, or XYZ saved. Additionally, the
1640 * Z channel can be interpreted as a Depth channel, but we only detect it as such if no X and Y
1641 * channels exists, since the Z in this case is part of XYZ. The same goes for the Y channel,
1642 * which can be detected as a luminance channel with the same name. */
1643 if (name[1] == 0) {
1644 /* Notice that we will be comparing with this upper-case version of the channel name, so the
1645 * below comparisons are effectively not case sensitive, and would also consider lowercase
1646 * versions of the listed channels. */
1647 echan.chan_id = BLI_toupper_ascii(name[0]);
1648 layname[0] = '\0';
1649 imb_exr_pass_name_from_channel(passname, echan, name, has_xyz_channels);
1650 return 1;
1651 }
1652
1653 /* last token is channel identifier */
1654 size_t len = imb_exr_split_token(name, end, &token);
1655 if (len == 0) {
1656 CLOG_ERROR(&LOG, "Multilayer read: bad channel name: %s", name);
1657 return 0;
1658 }
1659
1660 char channelname[EXR_TOT_MAXNAME];
1661 BLI_strncpy_utf8(channelname, token, std::min(len + 1, sizeof(channelname)));
1662
1663 if (len == 1) {
1664 echan.chan_id = BLI_toupper_ascii(channelname[0]);
1665 }
1666 else {
1667 BLI_assert(len > 1); /* Checks above ensure. */
1668 if (len == 2) {
1669 /* Some multi-layers are using two-letter channels name,
1670 * like, MX or NZ, which is basically has structure of
1671 * <pass_prefix><component>
1672 *
1673 * This is a bit silly, but see file from #35658.
1674 *
1675 * Here we do some magic to distinguish such cases.
1676 */
1677 const char chan_id = BLI_toupper_ascii(channelname[1]);
1678 if (ELEM(chan_id, 'X', 'Y', 'Z', 'R', 'G', 'B', 'U', 'V', 'A')) {
1679 echan.chan_id = chan_id;
1680 }
1681 else {
1682 echan.chan_id = 'X'; /* Default to X if unknown. */
1683 }
1684 }
1685 else if (BLI_strcaseeq(channelname, "red")) {
1686 echan.chan_id = 'R';
1687 }
1688 else if (BLI_strcaseeq(channelname, "green")) {
1689 echan.chan_id = 'G';
1690 }
1691 else if (BLI_strcaseeq(channelname, "blue")) {
1692 echan.chan_id = 'B';
1693 }
1694 else if (BLI_strcaseeq(channelname, "alpha")) {
1695 echan.chan_id = 'A';
1696 }
1697 else if (BLI_strcaseeq(channelname, "depth")) {
1698 echan.chan_id = 'Z';
1699 }
1700 else {
1701 echan.chan_id = 'X'; /* Default to X if unknown. */
1702 }
1703 }
1704 end -= len + 1; /* +1 to skip '.' separator */
1705
1706 if (end > name) {
1707 /* second token is pass name */
1708 len = imb_exr_split_token(name, end, &token);
1709 if (len == 0) {
1710 CLOG_ERROR(&LOG, "Multilayer read: bad channel name: %s", name);
1711 return 0;
1712 }
1713 BLI_strncpy_utf8(passname, token, std::min(passname_maxncpy, int(len) + 1));
1714 end -= len + 1; /* +1 to skip '.' separator */
1715 }
1716 else {
1717 /* Single token, determine pass name from channel name. */
1718 imb_exr_pass_name_from_channel_name(passname, echan, channelname, has_xyz_channels);
1719 }
1720
1721 /* all preceding tokens combined as layer name */
1722 if (end > name) {
1723 BLI_strncpy_utf8(layname, name, std::min(layname_maxncpy, int(end - name) + 1));
1724 }
1725 else {
1726 layname[0] = '\0';
1727 }
1728
1729 return 1;
1730}
1731
1732static ExrLayer *imb_exr_get_layer(ExrReadHandle *handle, const char *layname)
1733{
1734 for (ExrLayer &lay : handle->layers) {
1735 if (lay.name == layname) {
1736 return &lay;
1737 }
1738 }
1739
1740 handle->layers.append_as();
1741 ExrLayer &lay = handle->layers.last();
1742 lay.name = layname;
1743 return &lay;
1744}
1745
1746static ExrPass *imb_exr_get_pass(ExrLayer &lay, const char *passname)
1747{
1748 for (ExrPass &pass : lay.passes) {
1749 if (pass.name == passname) {
1750 return &pass;
1751 }
1752 }
1753
1754 ExrPass pass;
1755 pass.name = passname;
1756
1757 if (STREQ(passname, "Combined")) {
1758 lay.passes.prepend(std::move(pass));
1759 return &lay.passes.first();
1760 }
1761
1762 lay.passes.append(std::move(pass));
1763 return &lay.passes.last();
1764}
1765
1766static bool exr_has_xyz_channels(ExrReadHandle *exr_handle)
1767{
1768 bool x_found = false;
1769 bool y_found = false;
1770 bool z_found = false;
1771 for (const ExrChannel &echan : exr_handle->channels) {
1772 if (ELEM(echan.name, "X", "x")) {
1773 x_found = true;
1774 }
1775 if (ELEM(echan.name, "Y", "y")) {
1776 y_found = true;
1777 }
1778 if (ELEM(echan.name, "Z", "z")) {
1779 z_found = true;
1780 }
1781 }
1782
1783 return x_found && y_found && z_found;
1784}
1785
1790static Vector<ExrChannel> exr_channels_in_multi_part_file(const MultiPartInputFile &file)
1791{
1792 Vector<ExrChannel> channels;
1793 const ColorSpace *global_colorspace = imb_exr_part_colorspace(imb_exr_colorspace_header(file));
1794
1795 /* Get channels from each part. */
1796 for (int p = 0; p < file.parts(); p++) {
1797 const ChannelList &c = file.header(p).channels();
1798
1799 /* Parse color-space. Per part color-spaces are not currently used, but
1800 * might as well populate them for consistency with writing. */
1801 const ColorSpace *colorspace = imb_exr_part_colorspace(file.header(p));
1802 if (colorspace == nullptr) {
1803 colorspace = global_colorspace;
1804 }
1805
1806 /* There are two ways of storing multi-view EXRs:
1807 * - Multiple views in part with multiView attribute.
1808 * - Each view in its own part with view attribute. */
1809 const bool has_multiple_views_in_part = hasMultiView(file.header(p));
1810 StringVector views_in_part;
1811 if (has_multiple_views_in_part) {
1812 views_in_part = multiView(file.header(p));
1813 }
1814 StringRef part_view;
1815 if (file.header(p).hasView()) {
1816 part_view = file.header(p).view();
1817 }
1818
1819 /* Parse part name. */
1820 StringRef part_name;
1821 if (file.header(p).hasName()) {
1822 part_name = file.header(p).name();
1823
1824 /* Strip view name suffix if views are stored in separate parts.
1825 * They need to be included to make the part names unique. */
1826 if (!has_multiple_views_in_part) {
1827 if (part_name.endswith("." + part_view)) {
1828 part_name = part_name.drop_known_suffix("." + part_view);
1829 }
1830 else if (part_name.endswith("-" + part_view)) {
1831 part_name = part_name.drop_known_suffix("-" + part_view);
1832 }
1833 }
1834 }
1835
1836 /* Parse channels. */
1837 for (ChannelList::ConstIterator i = c.begin(); i != c.end(); i++) {
1838 ExrChannel echan;
1839 echan.name = std::string(i.name());
1840 echan.internal_name = echan.name;
1841
1842 if (has_multiple_views_in_part) {
1843 echan.view = viewFromChannelName(echan.name, views_in_part);
1844 echan.name = removeViewName(echan.internal_name, echan.view);
1845 }
1846 else {
1847 echan.view = part_view;
1848 }
1849
1850 /* Prepend part name as potential layer or pass name. According to OpenEXR docs
1851 * this should not be needed, but Houdini writes files like this. */
1852 if (!part_name.is_empty() && !StringRef(echan.name).startswith(part_name + ".")) {
1853 echan.name = part_name + "." + echan.name;
1854 }
1855
1856 echan.part_number = p;
1857 echan.colorspace = colorspace;
1858 channels.append(std::move(echan));
1859 }
1860 }
1861
1862 return channels;
1863}
1864
1866{
1867 if (handle->channels_parsed) {
1868 return !handle->layers.is_empty();
1869 }
1870 handle->channels_parsed = true;
1871
1872 try {
1873 handle->views = imb_exr_get_views(*handle->ifile);
1875 }
1876 catch (const std::exception &exc) {
1877 CLOG_ERROR(&LOG, "%s: %s", __func__, exc.what());
1878 handle->views.clear();
1879 handle->channels.clear();
1880 return false;
1881 }
1882 catch (...) { /* Catch-all for RTTI or symbol visibility mismatches. */
1883 CLOG_ERROR(&LOG, "Unknown error in %s", __func__);
1884 handle->views.clear();
1885 handle->channels.clear();
1886 return false;
1887 }
1888
1889 const bool has_xyz_channels = exr_has_xyz_channels(handle);
1890
1891 /* now try to sort out how to assign memory to the channels */
1892 /* first build hierarchical layer list */
1893 for (ExrChannel &echan : handle->channels) {
1894 char layname[EXR_TOT_MAXNAME], passname[EXR_TOT_MAXNAME];
1895 if (imb_exr_split_channel_name(echan, layname, passname, has_xyz_channels)) {
1896 const char *view = echan.view.c_str();
1897 std::string internal_name = passname;
1898
1899 if (view[0] != '\0') {
1900 char tmp_pass[EXR_PASS_MAXNAME];
1901 SNPRINTF_UTF8(tmp_pass, "%s.%s", passname, view);
1902 STRNCPY_UTF8(passname, tmp_pass);
1903 }
1904
1905 ExrLayer *lay = imb_exr_get_layer(handle, layname);
1906 ExrPass *pass = imb_exr_get_pass(*lay, passname);
1907
1908 pass->chan[pass->totchan] = &echan;
1909 pass->totchan++;
1910 pass->view = view;
1911 pass->internal_name = internal_name;
1912
1913 if (pass->totchan >= EXR_PASS_MAXCHAN) {
1914 CLOG_ERROR(&LOG, "Too many channels in one pass: %s", echan.name.c_str());
1915 return false;
1916 }
1917 }
1918 }
1919
1920 /* With some heuristics, try to merge the channels into logical layers and passes. */
1921 for (ExrLayer &lay : handle->layers) {
1922 for (ExrPass &pass : lay.passes) {
1923 if (pass.totchan == 0) {
1924 continue;
1925 }
1926 if (pass.totchan == 1) {
1927 ExrChannel &echan = *pass.chan[0];
1928 echan.offset = 0;
1929 echan.xstride = 1;
1930 echan.ystride = handle->width;
1931 pass.chan_id[0] = echan.chan_id;
1932 }
1933 else {
1934 char lookup[256];
1935
1936 memset(lookup, 0, sizeof(lookup));
1937
1938 bool known_channel_layout = false;
1939
1940 /* we can have RGB(A), XYZ(W), UVA */
1941 if (ELEM(pass.totchan, 3, 4)) {
1942 known_channel_layout = true;
1943 if (pass.chan[0]->chan_id == 'B' || pass.chan[1]->chan_id == 'B' ||
1944 pass.chan[2]->chan_id == 'B')
1945 {
1946 lookup[uint('R')] = 0;
1947 lookup[uint('G')] = 1;
1948 lookup[uint('B')] = 2;
1949 lookup[uint('A')] = 3;
1950 }
1951 else if (pass.chan[0]->chan_id == 'Y' || pass.chan[1]->chan_id == 'Y' ||
1952 pass.chan[2]->chan_id == 'Y')
1953 {
1954 lookup[uint('X')] = 0;
1955 lookup[uint('Y')] = 1;
1956 lookup[uint('Z')] = 2;
1957 lookup[uint('W')] = 3;
1958 }
1959 else {
1960 lookup[uint('U')] = 0;
1961 lookup[uint('V')] = 1;
1962 lookup[uint('A')] = 2;
1963 }
1964 }
1965
1966 for (int a = 0; a < pass.totchan; a++) {
1967 ExrChannel &echan = *pass.chan[a];
1968 const int offset = known_channel_layout ? lookup[uint(echan.chan_id)] : a;
1969 echan.offset = offset;
1970 echan.xstride = pass.totchan;
1971 echan.ystride = handle->width * pass.totchan;
1972 pass.chan_id[offset] = echan.chan_id;
1973 }
1974 }
1975 }
1976 }
1977
1978 return true;
1979}
1980
1981/* ********************************************************* */
1982
1983static void exr_print_filecontents(MultiPartInputFile &file)
1984{
1985 int numparts = file.parts();
1986 if (numparts == 1 && hasMultiView(file.header(0))) {
1987 const StringVector views = multiView(file.header(0));
1988 CLOG_DEBUG(&LOG, "MultiView file");
1989 CLOG_DEBUG(&LOG, "Default view: %s", defaultViewName(views).c_str());
1990 for (const std::string &view : views) {
1991 CLOG_DEBUG(&LOG, "Found view %s", view.c_str());
1992 }
1993 }
1994 else if (numparts > 1) {
1995 CLOG_DEBUG(&LOG, "MultiPart file");
1996 for (int i = 0; i < numparts; i++) {
1997 if (file.header(i).hasView()) {
1998 CLOG_DEBUG(&LOG, "Part %d: view = \"%s\"", i, file.header(i).view().c_str());
1999 }
2000 }
2001 }
2002
2003 for (int j = 0; j < numparts; j++) {
2004 const ChannelList &channels = file.header(j).channels();
2005 for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i) {
2006 const Channel &channel = i.channel();
2007 CLOG_DEBUG(&LOG, "Found channel %s of type %d", i.name(), channel.type);
2008 }
2009 }
2010}
2011
2013static const char *exr_rgba_channelname(MultiPartInputFile &file, const char *chan)
2014{
2015 const ChannelList &channels = file.header(0).channels();
2016
2017 for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i) {
2018 // const Channel &channel = i.channel(); /* Not used yet. */
2019 const char *str = i.name();
2020 int len = strlen(str);
2021 if (len) {
2022 if (BLI_strcasecmp(chan, str + len - 1) == 0) {
2023 return str;
2024 }
2025 }
2026 }
2027 return chan;
2028}
2029
2030static int exr_has_rgb(MultiPartInputFile &file, const char *rgb_channels[3])
2031{
2032 /* Common names for RGB-like channels in order. The V channel name is used by convention for BW
2033 * images, which will be broadcast to RGB channel at the end. */
2034 static const char *channel_names[] = {
2035 "V", "R", "Red", "G", "Green", "B", "Blue", "AR", "RA", "AG", "GA", "AB", "BA", nullptr};
2036
2037 const Header &header = file.header(0);
2038 int num_channels = 0;
2039
2040 for (int i = 0; channel_names[i]; i++) {
2041 /* Also try to match lower case variant of the channel names. */
2042 std::string lower_case_name = std::string(channel_names[i]);
2043 std::transform(lower_case_name.begin(),
2044 lower_case_name.end(),
2045 lower_case_name.begin(),
2046 [](uchar c) { return std::tolower(c); });
2047
2048 if (header.channels().findChannel(channel_names[i]) ||
2049 header.channels().findChannel(lower_case_name))
2050 {
2051 rgb_channels[num_channels++] = channel_names[i];
2052 if (num_channels == 3) {
2053 break;
2054 }
2055 }
2056 }
2057
2058 return num_channels;
2059}
2060
2061static bool exr_has_luma(MultiPartInputFile &file)
2062{
2063 /* Y channel is the luma and should always present fir luma space images,
2064 * optionally it could be also channels for chromas called BY and RY.
2065 */
2066 const Header &header = file.header(0);
2067 return header.channels().findChannel("Y") != nullptr;
2068}
2069
2070static bool exr_has_chroma(MultiPartInputFile &file)
2071{
2072 const Header &header = file.header(0);
2073 return header.channels().findChannel("BY") != nullptr &&
2074 header.channels().findChannel("RY") != nullptr;
2075}
2076
2077static bool exr_has_alpha(MultiPartInputFile &file)
2078{
2079 const Header &header = file.header(0);
2080 return !(header.channels().findChannel("A") == nullptr);
2081}
2082
2083static bool exr_has_xyz(MultiPartInputFile &file)
2084{
2085 const Header &header = file.header(0);
2086 return (header.channels().findChannel("X") != nullptr ||
2087 header.channels().findChannel("x") != nullptr) &&
2088 (header.channels().findChannel("Y") != nullptr ||
2089 header.channels().findChannel("y") != nullptr) &&
2090 (header.channels().findChannel("Z") != nullptr ||
2091 header.channels().findChannel("z") != nullptr);
2092}
2093
2094static bool exr_has_channels(MultiPartInputFile &file)
2095{
2096 const Header &header = file.header(0);
2097 return header.channels().begin() != header.channels().end();
2098}
2099
2100static const char *exr_unknown_channel_name(MultiPartInputFile &file)
2101{
2102 const Header &header = file.header(0);
2103 return header.channels().begin().name();
2104}
2105
2106static bool exr_is_half_float(const Header &header)
2107{
2108 const ChannelList &channels = header.channels();
2109 for (ChannelList::ConstIterator i = channels.begin(); i != channels.end(); ++i) {
2110 const Channel &channel = i.channel();
2111 if (channel.type != HALF) {
2112 return false;
2113 }
2114 }
2115 return true;
2116}
2117
2118static bool imb_exr_is_multilayer_file(MultiPartInputFile &file)
2119{
2120 const ChannelList &channels = file.header(0).channels();
2121 std::set<std::string> layerNames;
2122
2123 /* This will not include empty layer names, so files with just R/G/B/A
2124 * channels without a layer name will be single layer. */
2125 channels.layers(layerNames);
2126
2127 return !layerNames.empty();
2128}
2129
2130static bool exr_has_multiview(MultiPartInputFile &file)
2131{
2132 for (int p = 0; p < file.parts(); p++) {
2133 if (hasMultiView(file.header(p))) {
2134 return true;
2135 }
2136 }
2137
2138 return false;
2139}
2140
2141static bool exr_has_multipart_file(MultiPartInputFile &file)
2142{
2143 return file.parts() > 1;
2144}
2145
2147static bool imb_exr_is_multi(MultiPartInputFile &file)
2148{
2149 try {
2150 /* Multipart files are treated as multilayer in blender -
2151 * even if they are single layer openexr with multiview. */
2152 if (exr_has_multipart_file(file)) {
2153 return true;
2154 }
2155
2156 if (exr_has_multiview(file)) {
2157 return true;
2158 }
2159
2160 if (imb_exr_is_multilayer_file(file)) {
2161 return true;
2162 }
2163 }
2164 catch (const std::exception &exc) {
2165 CLOG_ERROR(&LOG, "%s: %s", __func__, exc.what());
2166 }
2167 catch (...) { /* Catch-all for RTTI or symbol visibility mismatches. */
2168 CLOG_ERROR(&LOG, "Unknown error in %s", __func__);
2169 }
2170
2171 return false;
2172}
2173
2174static bool imb_check_chromaticity_val(float test_v, float ref_v)
2175{
2176 const float tolerance_v = 0.000001f;
2177 return (test_v < (ref_v + tolerance_v)) && (test_v > (ref_v - tolerance_v));
2178}
2179
2180/* https://openexr.com/en/latest/TechnicalIntroduction.html#recommendations */
2181static bool imb_check_chromaticity_matches(const Imf::Chromaticities &a,
2182 const Imf::Chromaticities &b)
2183{
2184 return imb_check_chromaticity_val(a.red.x, b.red.x) &&
2185 imb_check_chromaticity_val(a.red.y, b.red.y) &&
2186 imb_check_chromaticity_val(a.green.x, b.green.x) &&
2187 imb_check_chromaticity_val(a.green.y, b.green.y) &&
2188 imb_check_chromaticity_val(a.blue.x, b.blue.x) &&
2189 imb_check_chromaticity_val(a.blue.y, b.blue.y) &&
2190 imb_check_chromaticity_val(a.white.x, b.white.x) &&
2191 imb_check_chromaticity_val(a.white.y, b.white.y);
2192}
2193
2194static void imb_exr_set_known_colorspace(const Header &header, ImFileColorSpace &r_colorspace)
2195{
2196 r_colorspace.is_hdr_float = true;
2197
2198 /* Read ACES container format metadata. */
2199 const IntAttribute *header_aces_container = header.findTypedAttribute<IntAttribute>(
2200 "acesImageContainerFlag");
2201 const ChromaticitiesAttribute *header_chromaticities =
2202 header.findTypedAttribute<ChromaticitiesAttribute>("chromaticities");
2203
2204 if ((header_aces_container && header_aces_container->value() == 1) ||
2205 (header_chromaticities &&
2206 imb_check_chromaticity_matches(header_chromaticities->value(), CHROMATICITIES_ACES_2065_1)))
2207 {
2208 const char *known_colorspace = IMB_colormanagement_role_colorspace_name_get(
2210 if (known_colorspace) {
2211 STRNCPY_UTF8(r_colorspace.metadata_colorspace, known_colorspace);
2212 }
2213 return;
2214 }
2215
2216 const StringAttribute *header_interop_id = header.findTypedAttribute<StringAttribute>(
2217 "colorInteropID");
2218
2219 /* Next try interop ID. */
2220 if (header_interop_id && !header_interop_id->value().empty()) {
2222 header_interop_id->value());
2223 if (colorspace) {
2224 STRNCPY_UTF8(r_colorspace.metadata_colorspace,
2226 return;
2227 }
2228 }
2229
2230 /* Try chromaticities. */
2231 if (header_chromaticities &&
2232 imb_check_chromaticity_matches(header_chromaticities->value(), CHROMATICITIES_XYZ_E))
2233 {
2234 /* Only works for the Blender default configuration due to fixed name. */
2235 STRNCPY_UTF8(r_colorspace.metadata_colorspace, "Linear CIE-XYZ E");
2236 }
2237}
2238
2239static const ColorSpace *imb_exr_part_colorspace(const Header &header)
2240{
2243 return IMB_colormanagement_space_get_named(colorspace.metadata_colorspace);
2244}
2245
2246static const Header &imb_exr_colorspace_header(const MultiPartInputFile &file)
2247{
2248 /* For multi-part files, find the first header with a non-data colorspace,
2249 * and use that as the colorspace for all color passes.
2250 *
2251 * The color interop forum recommendation say the colorInteropID of later
2252 * parts should not be different than the first part, except if it's missing
2253 * or set to data. This fits for Blender image datablocks, which also have
2254 * one colorspace but individual passes may be marked as data. */
2255 for (int p = 0; p < file.parts(); p++) {
2256 const ColorSpace *colorspace = imb_exr_part_colorspace(file.header(p));
2258 return file.header(p);
2259 }
2260 }
2261
2262 /* No representative colorspace found, fall back to the first header. */
2263 return file.header(0);
2264}
2265
2266static bool exr_get_ppm(MultiPartInputFile &file, double ppm[2])
2267{
2268 try {
2269 const Header &header = file.header(0);
2270 if (!hasXDensity(header)) {
2271 return false;
2272 }
2273 ppm[0] = double(xDensity(header)) / 0.0254;
2274 ppm[1] = ppm[0] * double(header.pixelAspectRatio());
2275 return true;
2276 }
2277 catch (const std::exception &exc) {
2278 CLOG_ERROR(&LOG, "%s: %s", __func__, exc.what());
2279 return false;
2280 }
2281 catch (...) { /* Catch-all for RTTI or symbol visibility mismatches. */
2282 CLOG_ERROR(&LOG, "Unknown error in %s", __func__);
2283 return false;
2284 }
2285}
2286
2287bool IMB_exr_get_ppm(ExrReadHandle *handle, double ppm[2])
2288{
2289 return exr_get_ppm(*handle->ifile, ppm);
2290}
2291
2292static void get_exr_display_window(const MultiPartInputFile &file,
2293 int display_size[2],
2294 int display_offset[2],
2295 int data_offset[2])
2296{
2297 try {
2298 const Header &header = file.header(0);
2299 const Box2i data_window = header.dataWindow();
2300 const Box2i display_window = header.displayWindow();
2301 display_size[0] = display_window.size()[0] + 1;
2302 display_size[1] = display_window.size()[1] + 1;
2303 display_offset[0] = display_window.min[0];
2304 display_offset[1] = display_window.min[1];
2305 data_offset[0] = data_window.min[0] - display_window.min[0];
2306 data_offset[1] = data_window.min[1] - display_window.min[1];
2307 return;
2308 }
2309 catch (const std::exception &exc) {
2310 CLOG_ERROR(&LOG, "%s: %s", __func__, exc.what());
2311 }
2312 catch (...) { /* Catch-all for RTTI or symbol visibility mismatches. */
2313 CLOG_ERROR(&LOG, "Unknown error in %s", __func__);
2314 }
2315
2316 display_size[0] = display_size[1] = 0;
2317 display_offset[0] = display_offset[1] = 0;
2318 data_offset[0] = data_offset[1] = 0;
2319}
2320
2322 int display_size[2],
2323 int display_offset[2],
2324 int data_offset[2])
2325{
2326 get_exr_display_window(*handle->ifile, display_size, display_offset, data_offset);
2327}
2328
2329static void imb_exr_set_ibuf_display_window(MultiPartInputFile &file, ImBuf *ibuf)
2330{
2333 exr_get_ppm(file, ibuf->ppm);
2334}
2335
2337{
2338 ExrReadHandle *handle = IMB_exr_open(filepath);
2339 if (handle == nullptr) {
2340 return nullptr;
2341 }
2342 if (!imb_exr_is_multi(*handle->ifile)) {
2343 IMB_exr_close(handle);
2344 return nullptr;
2345 }
2346 return handle;
2347}
2348
2350{
2351 IMemStream *membuf = nullptr;
2352 MultiPartInputFile *file = nullptr;
2353
2354 try {
2355 membuf = new IMemStream(const_cast<uchar *>(mem), size);
2356 file = new MultiPartInputFile(*membuf);
2357
2358 if (!imb_exr_is_multi(*file)) {
2359 delete file;
2360 delete membuf;
2361 return nullptr;
2362 }
2363
2364 const Box2i dw = file->header(0).dataWindow();
2365
2366 ExrReadHandle *handle = MEM_new<ExrReadHandle>("ExrReadHandle");
2367 handle->ifile_stream = membuf;
2368 handle->ifile = file;
2369 handle->width = dw.max.x - dw.min.x + 1;
2370 handle->height = dw.max.y - dw.min.y + 1;
2371 return handle;
2372 }
2373 catch (const std::exception &exc) {
2374 CLOG_ERROR(&LOG, "%s: %s", __func__, exc.what());
2375 }
2376 catch (...) { /* Catch-all for RTTI or symbol visibility mismatches. */
2377 CLOG_ERROR(&LOG, "Unknown error in %s", __func__);
2378 }
2379
2380 delete file;
2381 delete membuf;
2382 return nullptr;
2383}
2384
2386 size_t size,
2387 ImBufFlags flags,
2388 ImFileColorSpace &r_colorspace)
2389{
2390 ImBuf *ibuf = nullptr;
2391 IMemStream *membuf = nullptr;
2392 MultiPartInputFile *file = nullptr;
2393
2394 if (imb_is_a_openexr(mem, size) == 0) {
2395 return nullptr;
2396 }
2397
2398 try {
2399 membuf = new IMemStream(const_cast<uchar *>(mem), size);
2400 file = new MultiPartInputFile(*membuf);
2401
2402 const Header &file_header = file->header(0);
2403 Box2i dw = file_header.dataWindow();
2404 const size_t width = dw.max.x - dw.min.x + 1;
2405 const size_t height = dw.max.y - dw.min.y + 1;
2406
2407 CLOG_DEBUG(&LOG, "Image data window %d %d %d %d", dw.min.x, dw.min.y, dw.max.x, dw.max.y);
2408
2411 }
2412
2413 {
2414 const bool is_alpha = exr_has_alpha(*file);
2415 const Header &colorspace_header = imb_exr_colorspace_header(*file);
2416
2417 ibuf = IMB_allocImBuf(width, height, ImBufFlags::Zero);
2418 ibuf->color_mode = is_alpha ? ImColorMode::RGBA : ImColorMode::RGB;
2419 ibuf->foptions.flag |= exr_is_half_float(colorspace_header) ? OPENEXR_HALF : 0;
2420 ibuf->foptions.flag |= openexr_header_get_compression(colorspace_header);
2421
2423
2424 imb_exr_set_known_colorspace(colorspace_header, r_colorspace);
2425
2426 ibuf->ftype = IMB_FTYPE_OPENEXR;
2427
2428 /* Tell caller they have to read multilayer themselves, if they specified they
2429 * are capable of handling multilayer. */
2430 const bool is_multi = imb_exr_is_multi(*file);
2431 const bool defer_multilayer = is_multi && flag_is_set(flags, ImBufFlags::MultiLayer);
2432 if (defer_multilayer) {
2434 }
2435
2436 if (!flag_is_set(flags, ImBufFlags::Test)) {
2437
2438 if (flag_is_set(flags, ImBufFlags::Metadata)) {
2439 Header::ConstIterator iter;
2440
2442 for (iter = file_header.begin(); iter != file_header.end(); iter++) {
2443 if (openexr_metadata_skip_read(iter.name(), is_multi)) {
2444 continue;
2445 }
2446
2447 const StringAttribute *attr = file_header.findTypedAttribute<StringAttribute>(
2448 iter.name());
2449
2450 /* not all attributes are string attributes so we might get some NULLs here */
2451 if (attr) {
2452 IMB_metadata_set_field(metadata, iter.name(), attr->value().c_str());
2453 ibuf->flags |= ImBufFlags::Metadata;
2454 }
2455 }
2456 }
2457
2458 if (!defer_multilayer && is_multi) {
2459 /* Multilayer but caller can not handle it, read a single pass. */
2460 ExrReadHandle *handle = MEM_new<ExrReadHandle>("ExrReadHandle");
2461 handle->ifile = file;
2462 handle->ifile_stream = membuf;
2463 handle->width = int(width);
2464 handle->height = int(height);
2465 const bool ok = imb_exr_multi_read_single_pass(handle, ibuf);
2466 IMB_exr_close(handle);
2467 file = nullptr;
2468 membuf = nullptr;
2469 if (!ok) {
2470 IMB_freeImBuf(ibuf);
2471 return nullptr;
2472 }
2473 }
2474 else if (!defer_multilayer) {
2475 /* Read single layer EXR. */
2476 const char *rgb_channels[3];
2477 const int num_rgb_channels = exr_has_rgb(*file, rgb_channels);
2478 const int has_channels = exr_has_channels(*file);
2479 const bool has_luma = exr_has_luma(*file);
2480 const bool has_xyz = exr_has_xyz(*file);
2481 FrameBuffer frameBuffer;
2482 float *first;
2483 size_t xstride = sizeof(float[4]);
2484 size_t ystride = -xstride * width;
2485
2486 /* No need to clear image memory, it will be fully written below. */
2487 IMB_alloc_float_pixels(ibuf, 4, false);
2488
2489 /* Inverse correct first pixel for data-window
2490 * coordinates (- dw.min.y because of y flip). */
2491 first = ibuf->float_data_for_write() - 4 * (dw.min.x - dw.min.y * width);
2492 /* But, since we read y-flipped (negative y stride) we move to last scan-line. */
2493 first += 4 * (height - 1) * width;
2494
2495 if (num_rgb_channels > 0) {
2496 for (int i = 0; i < num_rgb_channels; i++) {
2497 frameBuffer.insert(exr_rgba_channelname(*file, rgb_channels[i]),
2498 Slice(Imf::FLOAT, (char *)(first + i), xstride, ystride));
2499 }
2500 }
2501 else if (has_xyz) {
2502 frameBuffer.insert(exr_rgba_channelname(*file, "X"),
2503 Slice(Imf::FLOAT, (char *)first, xstride, ystride));
2504 frameBuffer.insert(exr_rgba_channelname(*file, "Y"),
2505 Slice(Imf::FLOAT, (char *)(first + 1), xstride, ystride));
2506 frameBuffer.insert(exr_rgba_channelname(*file, "Z"),
2507 Slice(Imf::FLOAT, (char *)(first + 2), xstride, ystride));
2508 }
2509 else if (has_luma) {
2510 frameBuffer.insert(exr_rgba_channelname(*file, "Y"),
2511 Slice(Imf::FLOAT, (char *)first, xstride, ystride));
2512 frameBuffer.insert(
2513 exr_rgba_channelname(*file, "BY"),
2514 Slice(Imf::FLOAT, (char *)(first + 1), xstride, ystride, 1, 1, 0.5f));
2515 frameBuffer.insert(
2516 exr_rgba_channelname(*file, "RY"),
2517 Slice(Imf::FLOAT, (char *)(first + 2), xstride, ystride, 1, 1, 0.5f));
2518 }
2519 else if (has_channels) {
2520 frameBuffer.insert(exr_unknown_channel_name(*file),
2521 Slice(Imf::FLOAT, (char *)first, xstride, ystride, 1, 1));
2522 }
2523
2524 /* 1.0 is fill value, this still needs to be assigned even when (is_alpha == 0) */
2525 frameBuffer.insert(exr_rgba_channelname(*file, "A"),
2526 Slice(Imf::FLOAT, (char *)(first + 3), xstride, ystride, 1, 1, 1.0f));
2527
2528 InputPart in(*file, 0);
2529 in.setFrameBuffer(frameBuffer);
2530 in.readPixels(dw.min.y, dw.max.y);
2531
2532 /* XXX, ImBuf has no nice way to deal with this.
2533 * ideally IM_rect would be used when the caller wants a rect BUT
2534 * at the moment all functions use IM_rect.
2535 * Disabling this is ok because all functions should check
2536 * if a rect exists and create one on demand.
2537 *
2538 * Disabling this because the sequencer frees immediate. */
2539#if 0
2540 if (flag & IM_rect) {
2541 IMB_byte_from_float(ibuf);
2542 }
2543#endif
2544
2545 float *float_data = ibuf->float_data_for_write();
2546 if (num_rgb_channels == 0 && has_luma && exr_has_chroma(*file)) {
2547 for (size_t a = 0; a < size_t(ibuf->x) * ibuf->y; a++) {
2548 float *color = float_data + a * 4;
2549 ycc_to_rgb(color[0] * 255.0f,
2550 color[1] * 255.0f,
2551 color[2] * 255.0f,
2552 &color[0],
2553 &color[1],
2554 &color[2],
2556 }
2557 }
2558 else if (!has_xyz && num_rgb_channels <= 1) {
2559 /* Convert 1 to 3 channels. */
2560 for (size_t a = 0; a < size_t(ibuf->x) * ibuf->y; a++) {
2561 float *color = float_data + a * 4;
2562 color[1] = color[0];
2563 color[2] = color[0];
2564 }
2565 }
2566 }
2567 }
2568
2569 /* file is no longer needed */
2570 delete membuf;
2571 delete file;
2572
2573 if (flag_is_set(flags, ImBufFlags::AlphaDetect)) {
2575 }
2576 }
2577 return ibuf;
2578 }
2579 catch (const std::exception &exc) {
2580 CLOG_ERROR(&LOG, "%s: %s", __func__, exc.what());
2581 }
2582 catch (...) { /* Catch-all for RTTI or symbol visibility mismatches. */
2583 CLOG_ERROR(&LOG, "Unknown error in %s", __func__);
2584 }
2585
2586 if (ibuf) {
2587 IMB_freeImBuf(ibuf);
2588 }
2589 delete file;
2590 delete membuf;
2591
2592 return nullptr;
2593}
2594
2596 const ImBufFlags /*flags*/,
2597 const size_t max_thumb_size,
2598 ImFileColorSpace &r_colorspace,
2599 size_t *r_width,
2600 size_t *r_height)
2601{
2602 ImBuf *ibuf = nullptr;
2603 IStream *stream = nullptr;
2604 Imf::RgbaInputFile *file = nullptr;
2605
2606 /* OpenExr uses exceptions for error-handling. */
2607 try {
2608
2609 /* The memory-mapped stream is faster, but don't use for huge files as it requires contiguous
2610 * address space and we are processing multiple files at once (typically one per processor
2611 * core). The 100 MB limit here is arbitrary, but seems reasonable and conservative. */
2612 if (BLI_file_size(filepath) < 100 * 1024 * 1024) {
2613 stream = new IMMapStream(filepath);
2614 }
2615 else {
2616 stream = new IFileStream(filepath);
2617 }
2618
2619 /* imb_initopenexr() creates a global pool of worker threads. But we thumbnail multiple images
2620 * at once, and by default each file will attempt to use the entire pool for itself, stalling
2621 * the others. So each thumbnail should use a single thread of the pool. */
2622 file = new RgbaInputFile(*stream, 1);
2623
2624 if (!file->isComplete()) {
2625 delete file;
2626 delete stream;
2627 return nullptr;
2628 }
2629
2630 Imath::Box2i dw = file->dataWindow();
2631 int source_w = dw.max.x - dw.min.x + 1;
2632 int source_h = dw.max.y - dw.min.y + 1;
2633 *r_width = source_w;
2634 *r_height = source_h;
2635
2636 const Header &file_header = file->header();
2637
2638 /* If there is an embedded thumbnail, return that instead of making a new one. */
2639 if (file_header.hasPreviewImage()) {
2640 const Imf::PreviewImage &preview = file->header().previewImage();
2641 ImBuf *ibuf = IMB_allocFromBuffer(
2642 (uint8_t *)preview.pixels(), nullptr, preview.width(), preview.height(), 4);
2643 delete file;
2644 delete stream;
2645 IMB_flipy(ibuf);
2646 return ibuf;
2647 }
2648
2649 /* No effect yet for thumbnails, but will work once it is supported. */
2650 imb_exr_set_known_colorspace(file_header, r_colorspace);
2651
2652 /* Create a new thumbnail. */
2653 float scale_factor = std::min(float(max_thumb_size) / float(source_w),
2654 float(max_thumb_size) / float(source_h));
2655 int dest_w = std::max(int(source_w * scale_factor), 1);
2656 int dest_h = std::max(int(source_h * scale_factor), 1);
2657
2658 ibuf = IMB_allocImBuf(dest_w, dest_h, ImBufFlags::FloatData);
2659
2660 /* A single row of source pixels. */
2661 Imf::Array<Imf::Rgba> pixels(source_w);
2662
2663 /* Loop through destination thumbnail rows. */
2664 float *float_data = ibuf->float_data_for_write();
2665 for (int h = 0; h < dest_h; h++) {
2666
2667 /* Load the single source row that corresponds with destination row. */
2668 int source_y = int(float(h) / scale_factor) + dw.min.y;
2669 file->setFrameBuffer(&pixels[0] - dw.min.x - source_y * source_w, 1, source_w);
2670 file->readPixels(source_y);
2671
2672 for (int w = 0; w < dest_w; w++) {
2673 /* For each destination pixel find single corresponding source pixel. */
2674 int source_x = int(std::min<int>((w / scale_factor), dw.max.x - 1));
2675 float *dest_px = &float_data[(h * dest_w + w) * 4];
2676 dest_px[0] = pixels[source_x].r;
2677 dest_px[1] = pixels[source_x].g;
2678 dest_px[2] = pixels[source_x].b;
2679 dest_px[3] = pixels[source_x].a;
2680 }
2681 }
2682
2683 if (file->lineOrder() == INCREASING_Y) {
2684 IMB_flipy(ibuf);
2685 }
2686
2687 delete file;
2688 delete stream;
2689
2690 return ibuf;
2691 }
2692
2693 catch (const std::exception &exc) {
2694 CLOG_ERROR(&LOG, "%s: %s", __func__, exc.what());
2695 }
2696 catch (...) { /* Catch-all for RTTI or symbol visibility mismatches. */
2697 CLOG_ERROR(&LOG, "Unknown error in %s", __func__);
2698 }
2699
2700 if (ibuf) {
2701 IMB_freeImBuf(ibuf);
2702 }
2703
2704 delete file;
2705 delete stream;
2706 return nullptr;
2707}
2708
2710{
2711 /* In a multithreaded program, staticInitialize() must be called once during startup, before the
2712 * program accesses any other functions or classes in the IlmImf library. */
2713 Imf::staticInitialize();
2714 Imf::setGlobalThreadCount(BLI_system_thread_count());
2715}
2716
2718{
2719 /* Tells OpenEXR to free thread pool, also ensures there is no running tasks. */
2720 Imf::setGlobalThreadCount(0);
2721}
2722
2723} // namespace blender
#define IDP_string_get(prop)
File and directory operations.
#define O_BINARY
#define BLI_YCC_ITU_BT709
#define STR_ELEM(...)
#define SNPRINTF_UTF8(dst, format,...)
#define STRNCPY_UTF8(dst, src)
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:188
#define CLOG_DEBUG(clg_ref,...)
Definition CLG_log.h:191
#define CLOG_CHECK(clg_ref, verbose_level,...)
Definition CLG_log.h:147
@ CLG_LEVEL_DEBUG
Definition CLG_log.h:62
#define RE_PASSNAME_COMBINED
#define OPENEXR_CODEC_MASK
#define EXR_PASS_MAXNAME
#define EXR_TOT_MAXNAME
#define EXR_PASS_MAXCHAN
Read Blender memory allocation and freeing.
#define STRPREFIX(a, b)
#define ELEM(...)
#define STREQ(a, b)
SIMD_FORCE_INLINE const btScalar & w() const
Return the w value.
Definition btQuadWord.h:119
const T * data() const
Definition BLI_array.hh:323
IFileStream(const char *filepath)
void seekg(exr_file_offset_t pos) override
bool read(char c[], int n) override
void clear() override
exr_file_offset_t tellg() override
bool read(char c[], int n) override
exr_file_offset_t tellg() override
IMMapStream(const char *filepath)
void seekg(exr_file_offset_t pos) override
bool read(char c[], int n) override
exr_file_offset_t tellg() override
void seekg(exr_file_offset_t pos) override
void clear() override
IMemStream(uchar *exrbuf, size_t exrsize)
constexpr int64_t size() const
constexpr IndexRange()=default
constexpr bool is_empty() const
Definition BLI_span.hh:515
void write(const char c[], int n) override
exr_file_offset_t tellp() override
void seekp(exr_file_offset_t pos) override
OFileStream(const char *filepath)
constexpr const char * c_str() const
constexpr StringRefNull()
constexpr StringRef drop_known_suffix(StringRef suffix) const
int64_t size() const
void append(const T &value)
const T & last(const int64_t n=0) const
bool is_empty() const
void resize(const int64_t new_size)
const T & first() const
constexpr bool startswith(StringRef prefix) const
constexpr bool is_empty() const
constexpr int64_t size() const
constexpr bool endswith(StringRef suffix) const
Definition half.h:29
#define str(s)
#define OPENEXR_HALF
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
Definition math_dual.h:263
void free(Subdiv *subdiv)
Definition subdiv.cc:192
uint16_t float_to_half(float v)
Definition math_half.cc:32
T clamp(const T &a, const T &min, const T &max)
T safe_divide(const T &a, const T &b)
void float_to_half_clamp_array(const float *src, uint16_t *dst, size_t length, float min_value, float max_value)
Definition math_half.cc:292
void parallel_for_each(Range &&range, const Function &function)
Definition BLI_task.hh:31
void parallel_for(const IndexRange range, const int64_t grain_size, const Function &function, const TaskSizeHints &size_hints=detail::TaskSizeHints_Static(1))
Definition BLI_task.hh:69
BMesh Iterators.
void IMB_colormanagement_assign_float_colorspace(ImBuf *ibuf, const char *name)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
int char char int BLI_strcasecmp(const char *s1, const char *s2) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1
Vector< uint8_t > imb_save_buffer_openexr(ImBuf *ibuf, ImBufFlags)
static ExrLayer * imb_exr_get_layer(ExrReadHandle *handle, const char *layname)
static bool exr_has_xyz_channels(ExrReadHandle *exr_handle)
__int64 int64_t
Definition BKE_text.h:90
static bool exr_has_chroma(MultiPartInputFile &file)
static StringVector imb_exr_get_views(MultiPartInputFile &file)
static int exr_has_rgb(MultiPartInputFile &file, const char *rgb_channels[3])
static const ColorSpace * imb_exr_part_colorspace(const Header &header)
static bool imb_exr_is_multilayer_file(MultiPartInputFile &file)
static void openexr_header_metadata_colorspace(Header *header, const ColorSpace *colorspace)
static const char * exr_rgba_channelname(MultiPartInputFile &file, const char *chan)
unsigned int uint
Definition BKE_text.h:55
static void save_setup_framebuffer(const ImBuf *ibuf, bool half_precision, bool is_alpha, Vector< RGBAHalf > &half_pixels, FrameBuffer &frameBuffer)
int2 IMB_exr_get_size(ExrReadHandle *handle)
ExrReadHandle * IMB_exr_open(const char *filepath)
size_t BLI_mmap_get_length(const BLI_mmap_file *file) ATTR_WARN_UNUSED_RESULT
Definition BLI_mmap.cc:484
bool IMB_chan_id_is_color(StringRef chan_id)
BLI_mmap_file * BLI_mmap_open(int fd) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT
Definition BLI_mmap.cc:369
void ycc_to_rgb(float y, float cb, float cr, float *r_r, float *r_g, float *r_b, int colorspace)
static void openexr_header_metadata_pixelinfo(Header *header, const double ppm[2])
bool BLI_exists(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition storage.cc:404
void IMB_exr_write_pass(ExrWriteHandle *handle, StringRefNull layerpassname, StringRefNull channelnames, StringRefNull viewname, StringRefNull colorspace, size_t xstride, size_t ystride, const float *rect, bool use_half_float)
static int imb_exr_get_multiView_id(StringVector &views, const std::string &name)
static void exr_print_filecontents(MultiPartInputFile &file)
static void openexr_header_metadata_multi(ExrWriteHandle *handle, Header &header, const StampData *stamp)
static void save_setup_header(const ImBuf *ibuf, bool half_precision, bool is_alpha, Header &header)
static bool exr_has_multipart_file(MultiPartInputFile &file)
char * BLI_strncpy_utf8(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
bool IMB_exr_write_end(ExrWriteHandle *handle, const char *filepath, int width, int height, const double ppm[2], int compress, int quality, const StampData *stamp)
static bool openexr_metadata_skip_read(const char *name, const bool is_multi)
ATTR_WARN_UNUSED_RESULT const BMVert * v
bool imb_save_openexr(ImBuf *ibuf, const char *filepath, ImBufFlags)
static bool exr_has_xyz(MultiPartInputFile &file)
static int imb_exr_split_channel_name(ExrChannel &echan, char *layname, char *passname, bool has_xyz_channels)
static const Header & imb_exr_colorspace_header(const MultiPartInputFile &file)
ExrReadHandle * IMB_exr_open_multilayer(const char *filepath)
int BLI_open(const char *filepath, int oflag, int pmode) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
static int openexr_header_get_compression(const Header &header)
ImBuf * imb_load_openexr(const uchar *mem, size_t size, ImBufFlags flags, ImFileColorSpace &r_colorspace)
char BLI_toupper_ascii(const char c) ATTR_WARN_UNUSED_RESULT
void BLI_mmap_free(BLI_mmap_file *file) ATTR_NONNULL(1)
Definition BLI_mmap.cc:494
static bool exr_has_multiview(MultiPartInputFile &file)
static void imb_exr_pass_name_from_channel(char *passname, const ExrChannel &echan, const char *channelname, const bool has_xyz_channels)
void IMB_exr_get_display_window(ExrReadHandle *handle, int display_size[2], int display_offset[2], int data_offset[2])
static int openexr_compression_for_data_colorspace(const int compression)
VecBase< float, 4 > float4
unsigned short uint16_t
Definition BKE_text.h:80
float BLI_color_from_srgb_table[256]
int BLI_system_thread_count()
Definition threads.cc:258
static float compression_half_max(const int compression, const int quality)
static void openexr_header_metadata_global(Header *header, const IDProperty *metadata)
static int imb_exr_split_token(const char *str, const char *end, const char **token)
void imb_initopenexr()
void IMB_freeImBuf(ImBuf *ibuf)
VecBase< int32_t, 2 > int2
const char * imb_file_extensions_openexr[]
unsigned char uchar
Definition BKE_text.h:58
ImColorMode IMB_color_mode_from_channels(int channels)
void IMB_exr_write_view(ExrWriteHandle *handle, const char *viewname)
const char * IMB_colormanagement_role_colorspace_name_get(int role)
BMesh const char void * data
Vector< StringRefNull > IMB_exr_get_views(ExrReadHandle *handle)
static bool imb_exr_multilayer_ensure_channels_parsed(ExrReadHandle *handle)
static Imf::Chromaticities CHROMATICITIES_XYZ_E
unsigned char uint8_t
Definition BKE_text.h:79
void IMB_flipy(ImBuf *ibuf)
const char * IMB_colormanagement_colorspace_get_name(const ColorSpace *colorspace)
bool IMB_exr_get_ppm(ExrReadHandle *handle, double ppm[2])
static bool imb_exr_multi_read_single_pass(ExrReadHandle *handle, ImBuf *ibuf)
bool BLI_mmap_read(BLI_mmap_file *file, void *dest, size_t offset, size_t length) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition BLI_mmap.cc:466
static void imb_exr_read_channels(ExrReadHandle *handle)
@ R_IMF_EXR_CODEC_PXR24
@ R_IMF_EXR_CODEC_HTJ2K
ExrWriteHandle * IMB_exr_write_begin(bool write_multipart=false)
void IMB_exr_close(ExrReadHandle *handle)
static void convert_input_to_half_rgba(const ImBuf *ibuf, RGBAHalf *dst)
ImBuf * IMB_allocImBuf(unsigned int x, unsigned int y, ImBufFlags flags)
size_t BLI_file_size(const char *path) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition storage.cc:228
static bool exr_has_channels(MultiPartInputFile &file)
static bool imb_check_chromaticity_matches(const Imf::Chromaticities &a, const Imf::Chromaticities &b)
const ColorSpace * IMB_colormanagement_space_from_interop_id(StringRefNull interop_id)
static void imb_exr_pass_name_from_channel_name(char *passname, const ExrChannel &, const char *channelname, const bool)
bool IMB_colormanagement_space_is_data(const ColorSpace *colorspace)
void BKE_stamp_info_callback(void *data, StampData *stamp_data, StampCallback callback, bool noskip)
StringRefNull IMB_colormanagement_space_get_interop_id(const ColorSpace *colorspace)
static const char * exr_unknown_channel_name(MultiPartInputFile &file)
static int openexr_jpg_like_quality_to_dwa_compression_level(int q)
static Vector< ExrChannel > exr_channels_in_multi_part_file(const MultiPartInputFile &file)
static void get_exr_display_window(const MultiPartInputFile &file, int display_size[2], int display_offset[2], int data_offset[2])
void IMB_byte_from_float(ImBuf *ibuf)
const ColorSpace * IMB_colormanagement_space_get_named(const char *name)
ExrReadHandle * IMB_exr_open_multilayer_from_memory(const uchar *mem, size_t size)
ImBuf * IMB_allocFromBuffer(const uint8_t *byte_buffer, const float *float_buffer, unsigned int w, unsigned int h, unsigned int channels)
bool imb_is_a_openexr(const uchar *mem, const size_t size)
ImBuf * imb_load_filepath_thumbnail_openexr(const char *filepath, const ImBufFlags, const size_t max_thumb_size, ImFileColorSpace &r_colorspace, size_t *r_width, size_t *r_height)
static bool imb_check_chromaticity_val(float test_v, float ref_v)
static CLG_LogRef LOG
int bool bool bool size_t size_t size_t BLI_str_partition_ex(const char *str, const char *end, const char delim[], const char **sep, const char **suf, bool from_right) ATTR_NONNULL(1
static void imb_exr_write_channels(ExrWriteHandle *handle)
static bool imb_exr_is_multi(MultiPartInputFile &file)
bool IMB_alloc_float_pixels(ImBuf *ibuf, unsigned int channels, bool initialize_pixels=true)
void imb_exitopenexr()
static Imf::Chromaticities CHROMATICITIES_ACES_2065_1
static bool exr_has_luma(MultiPartInputFile &file)
int BLI_strcaseeq(const char *a, const char *b) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1
void IMB_colormanagement_transform_float(float *buffer, int width, int height, int channels, const char *from_colorspace, const char *to_colorspace, bool predivide)
static void imb_exr_set_ibuf_display_window(MultiPartInputFile &file, ImBuf *ibuf)
static bool exr_is_half_float(const Header &header)
static ExrPass * imb_exr_get_pass(ExrLayer &lay, const char *passname)
Vector< ExrPassInfo > IMB_exr_get_passes(ExrReadHandle *handle)
static bool exr_get_ppm(MultiPartInputFile &file, double ppm[2])
static void openexr_header_compression(Header *header, int compression, int quality)
static bool exr_has_alpha(MultiPartInputFile &file)
const char * BKE_blender_version_string()
Definition blender.cc:147
void IMB_exr_read_passes(ExrReadHandle *handle, MutableSpan< ExrPassInfo > entries, const char *src_colorspace=nullptr, bool predivide=false)
void IMB_metadata_set_field(IDProperty *metadata, const char *key, const char *value)
ocio::ColorSpace ColorSpace
Definition BLF_api.hh:42
static bool openexr_metadata_skip_write(const char *name, const bool is_multi)
static void imb_exr_set_known_colorspace(const Header &header, ImFileColorSpace &r_colorspace)
#define exr_file_offset_t
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
std::string internal_name
const ColorSpace * colorspace
Vector< ExrPass > passes
std::string internal_name
ExrChannel * chan[EXR_PASS_MAXCHAN]
char chan_id[EXR_PASS_MAXCHAN+1]
Vector< ExrLayer > layers
MultiPartInputFile * ifile
Vector< ExrChannel > channels
MultiPartOutputFile * mpofile
Vector< ExrChannel > channels
eIDPropertyType type
Definition DNA_ID.h:145
const ColorSpace * colorspace
const ColorSpace * colorspace
ImbFormatOptions foptions
ImBufFloatBuffer float_buffer
ImBufByteBuffer byte_buffer
const uint8_t * byte_data() const
IDProperty * metadata_for_write()
const IDProperty * metadata() const
const float * float_data() const
ImColorMode color_mode
eImbFileType ftype
float * float_data_for_write()
Definition allocimbuf.cc:79
bool can_contain_alpha() const
char metadata_colorspace[IM_MAX_SPACE]
void ensure_size(exr_file_offset_t size)
exr_file_offset_t tellp() override
void seekp(exr_file_offset_t pos) override
Vector< uint8_t > buffer
void write(const char c[], int n) override
exr_file_offset_t offset
int size() const
Definition vector.hh:130
void reserve(int new_size)
Definition vector.hh:78
void resize(int new_size)
Definition vector.hh:94
wchar_t * alloc_utf16_from_8(const char *in8, size_t add)
Definition utfconv.cc:294