/
exroutput.cpp
1823 lines (1648 loc) · 70.8 KB
/
exroutput.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright Contributors to the OpenImageIO project.
// SPDX-License-Identifier: Apache-2.0
// https://github.com/AcademySoftwareFoundation/OpenImageIO
#include <cerrno>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <numeric>
#include <OpenImageIO/Imath.h>
#include <OpenImageIO/platform.h>
#include <OpenEXR/IlmThreadPool.h>
#include <OpenEXR/ImfChannelList.h>
#include <OpenEXR/ImfEnvmap.h>
#include <OpenEXR/ImfOutputFile.h>
#include <OpenEXR/ImfTiledOutputFile.h>
#include "exr_pvt.h"
#define OPENEXR_CODED_VERSION \
(OPENEXR_VERSION_MAJOR * 10000 + OPENEXR_VERSION_MINOR * 100 \
+ OPENEXR_VERSION_PATCH)
// The way that OpenEXR uses dynamic casting for attributes requires
// temporarily suspending "hidden" symbol visibility mode.
OIIO_PRAGMA_VISIBILITY_PUSH
OIIO_PRAGMA_WARNING_PUSH
OIIO_GCC_PRAGMA(GCC diagnostic ignored "-Wunused-parameter")
#include <OpenEXR/IexBaseExc.h>
#include <OpenEXR/ImfBoxAttribute.h>
#include <OpenEXR/ImfCRgbaFile.h> // JUST to get symbols to figure out version!
#include <OpenEXR/ImfChromaticitiesAttribute.h>
#include <OpenEXR/ImfCompressionAttribute.h>
#include <OpenEXR/ImfEnvmapAttribute.h>
#include <OpenEXR/ImfFloatAttribute.h>
#include <OpenEXR/ImfFloatVectorAttribute.h>
#include <OpenEXR/ImfHeader.h>
#include <OpenEXR/ImfIntAttribute.h>
#include <OpenEXR/ImfKeyCodeAttribute.h>
#include <OpenEXR/ImfMatrixAttribute.h>
#include <OpenEXR/ImfRationalAttribute.h>
#include <OpenEXR/ImfStringAttribute.h>
#include <OpenEXR/ImfTimeCodeAttribute.h>
#include <OpenEXR/ImfVecAttribute.h>
#include <OpenEXR/ImfDeepFrameBuffer.h>
#include <OpenEXR/ImfDeepScanLineOutputPart.h>
#include <OpenEXR/ImfDeepTiledOutputPart.h>
#include <OpenEXR/ImfDoubleAttribute.h>
#include <OpenEXR/ImfMultiPartOutputFile.h>
#include <OpenEXR/ImfOutputPart.h>
#include <OpenEXR/ImfPartType.h>
#include <OpenEXR/ImfStringVectorAttribute.h>
#include <OpenEXR/ImfTiledOutputPart.h>
OIIO_PRAGMA_WARNING_POP
OIIO_PRAGMA_VISIBILITY_POP
#include <OpenImageIO/dassert.h>
#include <OpenImageIO/deepdata.h>
#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/fmath.h>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/strutil.h>
#include <OpenImageIO/sysutil.h>
#include <OpenImageIO/thread.h>
OIIO_PLUGIN_NAMESPACE_BEGIN
// Custom file output stream that uses IOProxy for output.
class OpenEXROutputStream final : public Imf::OStream {
public:
OpenEXROutputStream(const char* filename, Filesystem::IOProxy* io)
: Imf::OStream(filename)
, m_io(io)
{
if (!io || io->mode() != Filesystem::IOProxy::Write)
throw Iex::IoExc("File output failed.");
}
void write(const char c[], int n) override
{
if (m_io->write(c, n) != size_t(n))
throw Iex::IoExc("File output failed.");
}
uint64_t tellp() override { return m_io->tell(); }
void seekp(uint64_t pos) override
{
if (!m_io->seek(pos))
throw Iex::IoExc("File output failed.");
}
private:
Filesystem::IOProxy* m_io = nullptr;
};
class OpenEXROutput final : public ImageOutput {
public:
OpenEXROutput();
~OpenEXROutput() override;
const char* format_name(void) const override { return "openexr"; }
int supports(string_view feature) const override;
bool open(const std::string& name, const ImageSpec& spec,
OpenMode mode = Create) override;
bool open(const std::string& name, int subimages,
const ImageSpec* specs) override;
bool close() override;
bool copy_image(ImageInput* in) override;
bool write_scanline(int y, int z, TypeDesc format, const void* data,
stride_t xstride) override;
bool write_scanlines(int ybegin, int yend, int z, TypeDesc format,
const void* data, stride_t xstride,
stride_t ystride) override;
bool write_tile(int x, int y, int z, TypeDesc format, const void* data,
stride_t xstride, stride_t ystride,
stride_t zstride) override;
bool write_tiles(int xbegin, int xend, int ybegin, int yend, int zbegin,
int zend, TypeDesc format, const void* data,
stride_t xstride, stride_t ystride,
stride_t zstride) override;
bool write_deep_scanlines(int ybegin, int yend, int z,
const DeepData& deepdata) override;
bool write_deep_tiles(int xbegin, int xend, int ybegin, int yend,
int zbegin, int zend,
const DeepData& deepdata) override;
bool set_ioproxy(Filesystem::IOProxy* ioproxy) override
{
m_io = ioproxy;
return true;
}
private:
std::unique_ptr<OpenEXROutputStream>
m_output_stream; ///< Stream for output file
std::unique_ptr<Imf::OutputFile>
m_output_scanline; ///< Input for scanline files
std::unique_ptr<Imf::TiledOutputFile>
m_output_tiled; ///< Input for tiled files
std::unique_ptr<Imf::MultiPartOutputFile> m_output_multipart;
std::unique_ptr<Imf::OutputPart> m_scanline_output_part;
std::unique_ptr<Imf::TiledOutputPart> m_tiled_output_part;
std::unique_ptr<Imf::DeepScanLineOutputPart> m_deep_scanline_output_part;
std::unique_ptr<Imf::DeepTiledOutputPart> m_deep_tiled_output_part;
int m_levelmode; ///< The level mode of the file
int m_roundingmode; ///< Rounding mode of the file
int m_subimage; ///< What subimage we're writing now
int m_nsubimages; ///< How many subimages are there?
int m_miplevel; ///< What miplevel we're writing now
int m_nmiplevels; ///< How many mip levels are there?
std::vector<Imf::PixelType> m_pixeltype; ///< Imf pixel type for each
///< channel of current subimage
std::vector<unsigned char> m_scratch; ///< Scratch space for us to use
std::vector<ImageSpec> m_subimagespecs; ///< Saved subimage specs
std::vector<Imf::Header> m_headers;
Filesystem::IOProxy* m_io = nullptr;
std::unique_ptr<Filesystem::IOProxy> m_local_io;
// Initialize private members to pre-opened state
void init(void)
{
m_output_stream = NULL;
m_output_scanline = NULL;
m_output_tiled = NULL;
m_output_multipart.reset();
m_scanline_output_part.reset();
m_tiled_output_part.reset();
m_deep_scanline_output_part.reset();
m_deep_tiled_output_part.reset();
m_levelmode = Imf::ONE_LEVEL;
m_subimage = -1;
m_miplevel = -1;
m_subimagespecs.clear();
m_subimagespecs.shrink_to_fit();
m_headers.clear();
m_headers.shrink_to_fit();
m_io = nullptr;
m_local_io.reset();
}
// Set up the header based on the given spec. Also may doctor the
// spec a bit.
bool spec_to_header(ImageSpec& spec, int subimage, Imf::Header& header);
// Compute an OpenEXR PixelType from an OIIO TypeDesc
Imf::PixelType imfpixeltype(TypeDesc type);
// Fill in m_pixeltype based on the spec
void compute_pixeltypes(const ImageSpec& spec);
// Add a parameter to the output
bool put_parameter(const std::string& name, TypeDesc type, const void* data,
Imf::Header& header);
// Decode the IlmImf MIP parameters from the spec.
static void figure_mip(const ImageSpec& spec, int& nmiplevels,
int& levelmode, int& roundingmode);
// Helper: if the channel names are nonsensical, fix them to keep the
// app from shooting itself in the foot.
void sanity_check_channelnames();
bool copy_and_check_spec(const ImageSpec& srcspec, ImageSpec& dstspec)
{
// Arbitrarily limit res to 1M x 1M and 4k channels, assuming anything
// beyond that is more likely to be a mistake than a legit request. We
// may have to come back to this if these assumptions are wrong.
if (!check_open(Create, srcspec,
{ 0, 1 << 20, 0, 1 << 20, 0, 1, 0, 1 << 12 }))
return false;
if (&dstspec != &m_spec)
dstspec = m_spec;
return true;
}
};
// Obligatory material to make this a recognizable imageio plugin:
OIIO_PLUGIN_EXPORTS_BEGIN
OIIO_EXPORT ImageOutput*
openexr_output_imageio_create()
{
return new OpenEXROutput;
}
OIIO_EXPORT int openexr_imageio_version = OIIO_PLUGIN_VERSION;
OIIO_EXPORT const char*
openexr_imageio_library_version()
{
return "OpenEXR " OPENEXR_VERSION_STRING;
}
OIIO_EXPORT const char* openexr_output_extensions[] = { "exr", "sxr", "mxr",
nullptr };
OIIO_PLUGIN_EXPORTS_END
namespace pvt {
void
set_exr_threads()
{
static int exr_threads = 0; // lives in exrinput.cpp
static spin_mutex exr_threads_mutex;
int oiio_threads = 1;
OIIO::getattribute("exr_threads", oiio_threads);
// 0 means all threads in OIIO, but single-threaded in OpenEXR
// -1 means single-threaded in OIIO
if (oiio_threads == 0) {
oiio_threads = Sysutil::hardware_concurrency();
} else if (oiio_threads == -1) {
oiio_threads = 0;
}
spin_lock lock(exr_threads_mutex);
if (exr_threads != oiio_threads) {
exr_threads = oiio_threads;
Imf::setGlobalThreadCount(exr_threads);
}
#if OPENEXR_CODED_VERSION < 30108 && defined(_WIN32)
// If we're ever in this function, which we would be any time we use
// openexr threads, also proactively ensure that we exit the application,
// we force the OpenEXR threadpool to shut down because their destruction
// might cause us to hang on Windows when it tries to communicate with
// threads that would have already been terminated without releasing any
// held mutexes.
// Addendum: But only for OpenEXR < 3.1.8 (beyond that we think it's
// fixed on the OpenEXR side), and also only on Windows (the only platform
// where we've seen this be symptomatic).
static std::once_flag set_atexit_once;
std::call_once(set_atexit_once, []() {
std::atexit([]() {
// print("EXITING and setting ilmthreads = 0\n");
IlmThread::ThreadPool::globalThreadPool().setNumThreads(0);
});
});
#endif
}
} // namespace pvt
OpenEXROutput::OpenEXROutput()
{
pvt::set_exr_threads();
init();
}
OpenEXROutput::~OpenEXROutput()
{
// Close, if not already done.
close();
m_output_scanline.reset();
m_output_tiled.reset();
m_scanline_output_part.reset();
m_tiled_output_part.reset();
m_deep_scanline_output_part.reset();
m_deep_tiled_output_part.reset();
m_output_multipart.reset();
m_output_stream.reset();
}
int
OpenEXROutput::supports(string_view feature) const
{
if (feature == "tiles")
return true;
if (feature == "mipmap")
return true;
if (feature == "alpha")
return true;
if (feature == "nchannels")
return true;
if (feature == "channelformats")
return true;
if (feature == "displaywindow")
return true;
if (feature == "origin")
return true;
if (feature == "negativeorigin")
return true;
if (feature == "arbitrary_metadata")
return true;
if (feature == "exif") // Because of arbitrary_metadata
return true;
if (feature == "iptc") // Because of arbitrary_metadata
return true;
if (feature == "multiimage")
return true; // N.B. But OpenEXR does not support "appendsubimage"
if (feature == "deepdata")
return true;
if (feature == "ioproxy")
return true;
// EXR supports random write order iff lineOrder is set to 'random Y'
// and it's a tiled file.
if (feature == "random_access" && m_spec.tile_width != 0) {
const ParamValue* param = m_spec.find_attribute("openexr:lineOrder");
const char* lineorder = param ? *(char**)param->data() : NULL;
return (lineorder && Strutil::iequals(lineorder, "randomY"));
}
// FIXME: we could support "empty"
// Everything else, we either don't support or don't know about
return false;
}
bool
OpenEXROutput::open(const std::string& name, const ImageSpec& userspec,
OpenMode mode)
{
if (mode == Create) {
if (userspec.deep) // Fall back on multi-part OpenEXR for deep files
return open(name, 1, &userspec);
m_nsubimages = 1;
m_subimage = 0;
m_nmiplevels = 1;
m_miplevel = 0;
m_headers.resize(1);
copy_and_check_spec(userspec, m_spec);
sanity_check_channelnames();
const ParamValue* param = m_spec.find_attribute("oiio:ioproxy",
TypeDesc::PTR);
if (param)
m_io = param->get<Filesystem::IOProxy*>();
if (!spec_to_header(m_spec, m_subimage, m_headers[m_subimage]))
return false;
try {
if (!m_io) {
m_io = new Filesystem::IOFile(name, Filesystem::IOProxy::Write);
m_local_io.reset(m_io);
}
OIIO_ASSERT(m_io);
if (m_io->mode() != Filesystem::IOProxy::Write) {
// If the proxy couldn't be opened in write mode, try to
// return an error.
std::string e = m_io->error();
errorfmt("Could not open \"{}\" ({})", name,
e.size() ? e : std::string("unknown error"));
return false;
}
m_output_stream.reset(new OpenEXROutputStream(name.c_str(), m_io));
if (m_spec.tile_width) {
m_output_tiled.reset(
new Imf::TiledOutputFile(*m_output_stream,
m_headers[m_subimage]));
} else {
m_output_scanline.reset(
new Imf::OutputFile(*m_output_stream,
m_headers[m_subimage]));
}
} catch (const std::exception& e) {
errorfmt("Could not open \"{}\" ({})", name, e.what());
m_output_scanline = NULL;
m_output_tiled = NULL;
return false;
} catch (...) { // catch-all for edge cases or compiler bugs
errorfmt("Could not open \"{}\" (unknown exception)", name);
m_output_scanline = NULL;
m_output_tiled = NULL;
return false;
}
if (!m_output_scanline && !m_output_tiled) {
errorfmt("Unknown error opening EXR file");
return false;
}
return true;
}
if (mode == AppendSubimage) {
// OpenEXR 2.x supports subimages, but we only allow it to use the
// open(name,subimages,specs[]) variety.
if (m_subimagespecs.size() == 0 || !m_output_multipart) {
errorfmt("{} not opened properly for subimages", format_name());
return false;
}
// Move on to next subimage
++m_subimage;
if (m_subimage >= m_nsubimages) {
errorfmt("More subimages than originally declared.");
return false;
}
// Close the current subimage, open the next one
try {
if (m_tiled_output_part) {
m_tiled_output_part.reset(
new Imf::TiledOutputPart(*m_output_multipart, m_subimage));
} else if (m_scanline_output_part) {
m_scanline_output_part.reset(
new Imf::OutputPart(*m_output_multipart, m_subimage));
} else if (m_deep_tiled_output_part) {
m_deep_tiled_output_part.reset(
new Imf::DeepTiledOutputPart(*m_output_multipart,
m_subimage));
} else if (m_deep_scanline_output_part) {
m_deep_scanline_output_part.reset(
new Imf::DeepScanLineOutputPart(*m_output_multipart,
m_subimage));
} else {
errorfmt(
"Called open with AppendSubimage mode, but no appropriate part is found. Application bug?");
return false;
}
} catch (const std::exception& e) {
errorfmt("OpenEXR exception: {}", e.what());
m_scanline_output_part.reset();
m_tiled_output_part.reset();
m_deep_scanline_output_part.reset();
m_deep_tiled_output_part.reset();
return false;
} catch (...) { // catch-all for edge cases or compiler bugs
errorfmt("OpenEXR exception: unknown exception");
m_scanline_output_part.reset();
m_tiled_output_part.reset();
m_deep_scanline_output_part.reset();
m_deep_tiled_output_part.reset();
return false;
}
m_spec = m_subimagespecs[m_subimage];
sanity_check_channelnames();
compute_pixeltypes(m_spec);
return true;
}
if (mode == AppendMIPLevel) {
if (!m_output_scanline && !m_output_tiled) {
errorfmt("Cannot append a MIP level if no file has been opened");
return false;
}
if (m_spec.tile_width && m_levelmode != Imf::ONE_LEVEL) {
// OpenEXR does not support differing tile sizes on different
// MIP-map levels. Reject the open() if not using the original
// tile sizes.
if (userspec.tile_width != m_spec.tile_width
|| userspec.tile_height != m_spec.tile_height) {
errorfmt(
"OpenEXR tiles must have the same size on all MIPmap levels");
return false;
}
// Copy the new mip level size. Keep everything else from the
// original level.
m_spec.width = userspec.width;
m_spec.height = userspec.height;
// N.B. do we need to copy anything else from userspec?
++m_miplevel;
return true;
} else {
errorfmt("Cannot add MIP level to a non-MIPmapped file");
return false;
}
}
errorfmt("Unknown open mode {}", int(mode));
return false;
}
bool
OpenEXROutput::open(const std::string& name, int subimages,
const ImageSpec* specs)
{
if (subimages < 1) {
errorfmt("OpenEXR does not support {} subimages.", subimages);
return false;
}
// Only one part and not deep? Write an OpenEXR 1.x file
if (subimages == 1 && !specs[0].deep)
return open(name, specs[0], Create);
// Copy the passed-in subimages and turn into OpenEXR headers
m_nsubimages = subimages;
m_subimage = 0;
m_nmiplevels = 1;
m_miplevel = 0;
m_subimagespecs.resize(subimages);
for (int i = 0; i < subimages; ++i)
if (!copy_and_check_spec(specs[i], m_subimagespecs[i]))
return false;
m_headers.resize(subimages);
std::string filetype;
if (specs[0].deep)
filetype = specs[0].tile_width ? "tiledimage" : "deepscanlineimage";
else
filetype = specs[0].tile_width ? "tiledimage" : "scanlineimage";
bool deep = false;
for (int s = 0; s < subimages; ++s) {
if (!spec_to_header(m_subimagespecs[s], s, m_headers[s]))
return false;
deep |= m_subimagespecs[s].deep;
if (m_subimagespecs[s].deep != m_subimagespecs[0].deep) {
errorfmt(
"OpenEXR does not support mixed deep/nondeep multi-part image files");
return false;
}
if (subimages > 1 || deep) {
bool tiled = m_subimagespecs[s].tile_width;
m_headers[s].setType(
deep ? (tiled ? Imf::DEEPTILE : Imf::DEEPSCANLINE)
: (tiled ? Imf::TILEDIMAGE : Imf::SCANLINEIMAGE));
}
}
m_spec = m_subimagespecs[0];
sanity_check_channelnames();
compute_pixeltypes(m_spec);
// Create an ImfMultiPartOutputFile
try {
// m_output_stream.reset (new OpenEXROutputStream (name.c_str())();
// m_output_multipart.reset (new Imf::MultiPartOutputFile (*m_output_stream,
// &m_headers[0], subimages)();
// FIXME: Oops, looks like OpenEXR 2.0 currently lacks a
// MultiPartOutputFile ctr that takes an OStream, so we can't
// do this quite yet.
m_output_multipart.reset(new Imf::MultiPartOutputFile(name.c_str(),
&m_headers[0],
subimages));
} catch (const std::exception& e) {
m_output_stream.reset();
errorfmt("OpenEXR exception: {}", e.what());
return false;
} catch (...) { // catch-all for edge cases or compiler bugs
m_output_stream.reset();
errorfmt("OpenEXR exception: unknown exception");
return false;
}
try {
if (deep) {
if (m_spec.tile_width) {
m_deep_tiled_output_part.reset(
new Imf::DeepTiledOutputPart(*m_output_multipart, 0));
} else {
m_deep_scanline_output_part.reset(
new Imf::DeepScanLineOutputPart(*m_output_multipart, 0));
}
} else {
if (m_spec.tile_width) {
m_tiled_output_part.reset(
new Imf::TiledOutputPart(*m_output_multipart, 0));
} else {
m_scanline_output_part.reset(
new Imf::OutputPart(*m_output_multipart, 0));
}
}
} catch (const std::exception& e) {
errorfmt("OpenEXR exception: {}", e.what());
m_output_stream.reset();
m_scanline_output_part.reset();
m_tiled_output_part.reset();
m_deep_scanline_output_part.reset();
m_deep_tiled_output_part.reset();
return false;
} catch (...) { // catch-all for edge cases or compiler bugs
errorfmt("OpenEXR exception: unknown exception");
m_output_stream.reset();
m_scanline_output_part.reset();
m_tiled_output_part.reset();
m_deep_scanline_output_part.reset();
m_deep_tiled_output_part.reset();
return false;
}
return true;
}
Imf::PixelType
OpenEXROutput::imfpixeltype(TypeDesc type)
{
Imf::PixelType ptype;
switch (type.basetype) {
case TypeDesc::UINT: ptype = Imf::UINT; break;
case TypeDesc::FLOAT:
case TypeDesc::DOUBLE: ptype = Imf::FLOAT; break;
default:
// Everything else defaults to half
ptype = Imf::HALF;
break;
}
return ptype;
}
void
OpenEXROutput::compute_pixeltypes(const ImageSpec& spec)
{
m_pixeltype.clear();
m_pixeltype.reserve(spec.nchannels);
for (int c = 0; c < spec.nchannels; ++c) {
m_pixeltype.push_back(imfpixeltype(spec.channelformat(c)));
}
OIIO_ASSERT(m_pixeltype.size() == size_t(spec.nchannels));
}
bool
OpenEXROutput::spec_to_header(ImageSpec& spec, int subimage,
Imf::Header& header)
{
// Force use of one of the three data types that OpenEXR supports
switch (spec.format.basetype) {
case TypeDesc::UINT: spec.format = TypeDesc::UINT; break;
case TypeDesc::FLOAT:
case TypeDesc::DOUBLE: spec.format = TypeDesc::FLOAT; break;
default:
// Everything else defaults to half
spec.format = TypeDesc::HALF;
}
Imath::Box2i dataWindow(Imath::V2i(spec.x, spec.y),
Imath::V2i(spec.width + spec.x - 1,
spec.height + spec.y - 1));
Imath::Box2i displayWindow(Imath::V2i(spec.full_x, spec.full_y),
Imath::V2i(spec.full_width + spec.full_x - 1,
spec.full_height + spec.full_y - 1));
header = Imf::Header(displayWindow, dataWindow);
// Insert channels into the header. Also give the channels names if
// the user botched it.
compute_pixeltypes(spec);
static const char* default_chan_names[] = { "R", "G", "B", "A" };
spec.channelnames.resize(spec.nchannels);
for (int c = 0; c < spec.nchannels; ++c) {
if (spec.channelnames[c].empty())
spec.channelnames[c] = (c < 4)
? default_chan_names[c]
: Strutil::fmt::format("unknown {}", c);
// Hint to lossy compression methods that indicates whether
// human perception of the quantity represented by this channel
// is closer to linear or closer to logarithmic. Compression
// methods may optimize image quality by adjusting pixel data
// quantization according to this hint.
// Note: This is not the same as data having come from a linear
// colorspace. It is meant for data that is perceived by humans
// in a linear fashion.
// e.g Cb & Cr components in YCbCr images
// a* & b* components in L*a*b* images
// H & S components in HLS images
// We ignore this for now, but we should fix it if we ever commonly
// work with non-perceptual/non-color image data.
bool pLinear = false;
header.channels().insert(spec.channelnames[c].c_str(),
Imf::Channel(m_pixeltype[c], 1, 1, pLinear));
}
string_view comp;
int qual;
std::tie(comp, qual) = spec.decode_compression_metadata("zip", -1);
// It seems that zips is the only compression that can reliably work
// on deep files (but allow "none" as well)
if (spec.deep && comp != "none")
comp = "zips";
// For single channel tiled images, dwaa/b compression only seems to work
// reliably when tile size > 16 and size is a power of two.
if (spec.nchannels == 1 && spec.tile_width > 0
&& Strutil::istarts_with(comp, "dwa")
&& ((spec.tile_width < 16 && spec.tile_height < 16)
|| !ispow2(spec.tile_width) || !ispow2(spec.tile_height))) {
comp = "zip";
}
if (Strutil::istarts_with(comp, "dwa")) {
spec.attribute("openexr:dwaCompressionLevel",
qual > 0 ? float(qual) : 45.0f);
}
spec.attribute("compression", comp);
#if OPENEXR_CODED_VERSION >= 30103
if (Strutil::istarts_with(comp, "zip")) {
header.zipCompressionLevel() = (qual >= 1 && qual <= 9) ? qual : 4;
}
#endif
// Default to increasingY line order
if (!spec.find_attribute("openexr:lineOrder"))
spec.attribute("openexr:lineOrder", "increasingY");
// Automatically set date field if the client didn't supply it.
if (!spec.find_attribute("DateTime")) {
time_t now;
time(&now);
struct tm mytm;
Sysutil::get_local_time(&now, &mytm);
std::string date
= Strutil::fmt::format("{:4d}:{:02d}:{:02d} {:02d}:{:02d}:{:02d}",
mytm.tm_year + 1900, mytm.tm_mon + 1,
mytm.tm_mday, mytm.tm_hour, mytm.tm_min,
mytm.tm_sec);
spec.attribute("DateTime", date);
}
figure_mip(spec, m_nmiplevels, m_levelmode, m_roundingmode);
std::string textureformat = spec.get_string_attribute("textureformat", "");
if (Strutil::iequals(textureformat, "CubeFace Environment")) {
header.insert("envmap", Imf::EnvmapAttribute(Imf::ENVMAP_CUBE));
} else if (Strutil::iequals(textureformat, "LatLong Environment")) {
header.insert("envmap", Imf::EnvmapAttribute(Imf::ENVMAP_LATLONG));
}
// Fix up density and aspect to be consistent
float aspect = spec.get_float_attribute("PixelAspectRatio", 0.0f);
float xdensity = spec.get_float_attribute("XResolution", 0.0f);
float ydensity = spec.get_float_attribute("YResolution", 0.0f);
if (!aspect && xdensity && ydensity) {
// No aspect ratio. Compute it from density, if supplied.
spec.attribute("PixelAspectRatio", xdensity / ydensity);
}
if (xdensity && ydensity
&& spec.get_string_attribute("ResolutionUnit") == "cm") {
// OpenEXR only supports pixels per inch, so fix the values if they
// came to us in cm.
spec.attribute("XResolution", xdensity / 2.54f);
spec.attribute("YResolution", ydensity / 2.54f);
}
// We must setTileDescription here before the put_parameter calls below,
// since put_parameter will check the header to ensure this is a tiled
// image before setting lineOrder to randomY.
if (spec.tile_width)
header.setTileDescription(
Imf::TileDescription(spec.tile_width, spec.tile_height,
Imf::LevelMode(m_levelmode),
Imf::LevelRoundingMode(m_roundingmode)));
// Deal with all other params
for (const auto& p : spec.extra_attribs)
put_parameter(p.name().string(), p.type(), p.data(), header);
// Multi-part EXR files required to have a name. Make one up if not
// supplied.
if (m_nsubimages > 1 && !header.hasName()) {
std::string n = Strutil::fmt::format("subimage{:02d}", subimage);
header.insert("name", Imf::StringAttribute(n));
}
return true;
}
void
OpenEXROutput::figure_mip(const ImageSpec& spec, int& nmiplevels,
int& levelmode, int& roundingmode)
{
nmiplevels = 1;
levelmode = Imf::ONE_LEVEL; // Default to no MIP-mapping
roundingmode = spec.get_int_attribute("openexr:roundingmode",
Imf::ROUND_DOWN);
std::string textureformat = spec.get_string_attribute("textureformat", "");
if (Strutil::iequals(textureformat, "Plain Texture")) {
levelmode = spec.get_int_attribute("openexr:levelmode",
Imf::MIPMAP_LEVELS);
} else if (Strutil::iequals(textureformat, "CubeFace Environment")) {
levelmode = spec.get_int_attribute("openexr:levelmode",
Imf::MIPMAP_LEVELS);
} else if (Strutil::iequals(textureformat, "LatLong Environment")) {
levelmode = spec.get_int_attribute("openexr:levelmode",
Imf::MIPMAP_LEVELS);
} else if (Strutil::iequals(textureformat, "Shadow")) {
levelmode = Imf::ONE_LEVEL; // Force one level for shadow maps
}
if (levelmode == Imf::MIPMAP_LEVELS) {
// Compute how many mip levels there will be
int w = spec.width;
int h = spec.height;
while (w > 1 && h > 1) {
if (roundingmode == Imf::ROUND_DOWN) {
w = w / 2;
h = h / 2;
} else {
w = (w + 1) / 2;
h = (h + 1) / 2;
}
w = std::max(1, w);
h = std::max(1, h);
++nmiplevels;
}
}
}
struct ExrMeta {
const char *oiioname, *exrname;
TypeDesc exrtype;
ExrMeta(const char* oiioname = NULL, const char* exrname = NULL,
TypeDesc exrtype = TypeDesc::UNKNOWN)
: oiioname(oiioname)
, exrname(exrname)
, exrtype(exrtype)
{
}
};
static ExrMeta exr_meta_translation[] = {
// Translate OIIO standard metadata names to OpenEXR standard names
ExrMeta("worldtocamera", "worldToCamera", TypeMatrix),
ExrMeta("worldtoNDC", "worldToNDC", TypeMatrix),
ExrMeta("worldtoscreen", "worldToScreen", TypeMatrix),
ExrMeta("DateTime", "capDate", TypeString),
ExrMeta("ImageDescription", "comments", TypeString),
ExrMeta("description", "comments", TypeString),
ExrMeta("Copyright", "owner", TypeString),
ExrMeta("PixelAspectRatio", "pixelAspectRatio", TypeFloat),
ExrMeta("XResolution", "xDensity", TypeFloat),
ExrMeta("ExposureTime", "expTime", TypeFloat),
ExrMeta("FNumber", "aperture", TypeFloat),
ExrMeta("oiio:subimagename", "name", TypeString),
ExrMeta("openexr:dwaCompressionLevel", "dwaCompressionLevel", TypeFloat),
ExrMeta("smpte:TimeCode", "timeCode", TypeTimeCode),
ExrMeta("smpte:KeyCode", "keyCode", TypeKeyCode),
// Empty exrname means that we silently drop this metadata.
// Often this is because they have particular meaning to OpenEXR and we
// don't want to mess it up by inadvertently copying it wrong from the
// user or from a file we read.
ExrMeta("YResolution"), ExrMeta("planarconfig"), ExrMeta("type"),
ExrMeta("tiles"), ExrMeta("chunkCount"), ExrMeta("maxSamplesPerPixel"),
ExrMeta("openexr:roundingmode")
};
bool
OpenEXROutput::put_parameter(const std::string& name, TypeDesc type,
const void* data, Imf::Header& header)
{
// Translate
if (name.empty())
return false;
if (!data)
return false;
std::string xname = name;
TypeDesc exrtype = TypeUnknown;
for (const auto& e : exr_meta_translation) {
if (Strutil::iequals(xname, e.oiioname)
|| (e.exrname && Strutil::iequals(xname, e.exrname))) {
xname = std::string(e.exrname ? e.exrname : "");
exrtype = e.exrtype;
// std::cerr << "exr put '" << name << "' -> '" << xname << "'\n";
break;
}
}
// Special cases
if (Strutil::iequals(xname, "Compression") && type == TypeString) {
const char* str = *(char**)data;
header.compression() = Imf::ZIP_COMPRESSION; // Default
if (str) {
if (Strutil::iequals(str, "none"))
header.compression() = Imf::NO_COMPRESSION;
else if (Strutil::iequals(str, "deflate")
|| Strutil::iequals(str, "zip"))
header.compression() = Imf::ZIP_COMPRESSION;
else if (Strutil::iequals(str, "rle"))
header.compression() = Imf::RLE_COMPRESSION;
else if (Strutil::iequals(str, "zips"))
header.compression() = Imf::ZIPS_COMPRESSION;
else if (Strutil::iequals(str, "piz"))
header.compression() = Imf::PIZ_COMPRESSION;
else if (Strutil::iequals(str, "pxr24"))
header.compression() = Imf::PXR24_COMPRESSION;
else if (Strutil::iequals(str, "b44"))
header.compression() = Imf::B44_COMPRESSION;
else if (Strutil::iequals(str, "b44a"))
header.compression() = Imf::B44A_COMPRESSION;
else if (Strutil::iequals(str, "dwaa"))
header.compression() = Imf::DWAA_COMPRESSION;
else if (Strutil::iequals(str, "dwab"))
header.compression() = Imf::DWAB_COMPRESSION;
}
return true;
}
if (Strutil::iequals(xname, "openexr:lineOrder") && type == TypeString) {
const char* str = *(char**)data;
header.lineOrder() = Imf::INCREASING_Y; // Default
if (str) {
if (Strutil::iequals(str, "randomY")
&& header
.hasTileDescription() /* randomY is only for tiled files */)
header.lineOrder() = Imf::RANDOM_Y;
else if (Strutil::iequals(str, "decreasingY"))
header.lineOrder() = Imf::DECREASING_Y;
}
return true;
}
// Special handling of any remaining "oiio:*" metadata.
if (Strutil::istarts_with(xname, "oiio:")) {
if (Strutil::iequals(xname, "oiio:ConstantColor")
|| Strutil::iequals(xname, "oiio:AverageColor")
|| Strutil::iequals(xname, "oiio:SHA-1")) {
// let these fall through and get stored as metadata
} else {
// Other than the listed exceptions, suppress any other custom
// oiio: directives.
return false;
}
}
// Before handling general named metadata, suppress format-specific
// metadata meant for other formats.
if (const char* colon = strchr(xname.c_str(), ':')) {
std::string prefix(xname.c_str(), colon);
Strutil::to_lower(prefix);
if (prefix != format_name() && is_imageio_format_name(prefix))
return false;
}
// The main "ICCProfile" byte array should translate, but the individual
// "ICCProfile:*" attributes are suppressed because they merely duplicate
// what's in the byte array.
if (Strutil::istarts_with(xname, "ICCProfile:")) {
return false;
}
if (!xname.length())
return false; // Skip suppressed names
// Handle some cases where the user passed a type different than what
// OpenEXR expects, and we can make a good guess about how to translate.
float tmpfloat;
int tmpint;
if (exrtype == TypeFloat && type == TypeInt) {
tmpfloat = float(*(const int*)data);
data = &tmpfloat;
type = TypeFloat;