-
Notifications
You must be signed in to change notification settings - Fork 667
Expand file tree
/
Copy pathexrinput.cpp
More file actions
1701 lines (1507 loc) · 62.3 KB
/
exrinput.cpp
File metadata and controls
1701 lines (1507 loc) · 62.3 KB
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 <map>
#include <memory>
#include <numeric>
#include <OpenImageIO/Imath.h>
#include <OpenImageIO/platform.h>
#include <OpenEXR/ImfArray.h>
#include <OpenEXR/ImfChannelList.h>
#include <OpenEXR/ImfEnvmap.h>
#include <OpenEXR/ImfInputFile.h>
#include <OpenEXR/ImfRgba.h>
#include <OpenEXR/ImfTestFile.h>
#include <OpenEXR/ImfTiledInputFile.h>
#include "exr_pvt.h"
#include "imageio_pvt.h"
// 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/IexThrowErrnoExc.h>
#include <OpenEXR/ImfBoxAttribute.h>
#include <OpenEXR/ImfChromaticitiesAttribute.h>
#include <OpenEXR/ImfCompressionAttribute.h>
#include <OpenEXR/ImfDeepFrameBuffer.h>
#include <OpenEXR/ImfDeepScanLineInputPart.h>
#include <OpenEXR/ImfDeepTiledInputPart.h>
#include <OpenEXR/ImfDoubleAttribute.h>
#include <OpenEXR/ImfEnvmapAttribute.h>
#include <OpenEXR/ImfFloatAttribute.h>
#include <OpenEXR/ImfHeader.h>
#if OPENEXR_HAS_FLOATVECTOR
# include <OpenEXR/ImfFloatVectorAttribute.h>
#endif
#include <OpenEXR/ImfInputPart.h>
#include <OpenEXR/ImfIntAttribute.h>
#include <OpenEXR/ImfKeyCodeAttribute.h>
#include <OpenEXR/ImfLineOrderAttribute.h>
#include <OpenEXR/ImfMatrixAttribute.h>
#include <OpenEXR/ImfMultiPartInputFile.h>
#include <OpenEXR/ImfPartType.h>
#include <OpenEXR/ImfRationalAttribute.h>
#include <OpenEXR/ImfStringAttribute.h>
#include <OpenEXR/ImfStringVectorAttribute.h>
#include <OpenEXR/ImfTiledInputPart.h>
#include <OpenEXR/ImfTimeCodeAttribute.h>
#include <OpenEXR/ImfVecAttribute.h>
OIIO_PRAGMA_WARNING_POP
OIIO_PRAGMA_VISIBILITY_POP
#include <OpenEXR/ImfCRgbaFile.h>
#if OPENEXR_CODED_VERSION >= 30100 && defined(OIIO_USE_EXR_C_API)
# define USE_OPENEXR_CORE
#endif
#include "imageio_pvt.h"
#include <OpenImageIO/dassert.h>
#include <OpenImageIO/deepdata.h>
#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/imagebufalgo_util.h>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/strutil.h>
#include <OpenImageIO/sysutil.h>
#include <OpenImageIO/thread.h>
OIIO_PLUGIN_NAMESPACE_BEGIN
// Obligatory material to make this a recognizable imageio plugin:
OIIO_PLUGIN_EXPORTS_BEGIN
OIIO_EXPORT ImageInput*
openexr_input_imageio_create()
{
#ifdef USE_OPENEXR_CORE
if (pvt::openexr_core) {
// Strutil::print("selecting core\n");
extern ImageInput* openexrcore_input_imageio_create();
return openexrcore_input_imageio_create();
}
#endif
return new OpenEXRInput;
}
// OIIO_EXPORT int openexr_imageio_version = OIIO_PLUGIN_VERSION; // it's in exroutput.cpp
OIIO_EXPORT const char* openexr_input_extensions[] = { "exr", "sxr", "mxr",
nullptr };
OIIO_PLUGIN_EXPORTS_END
static std::map<std::string, std::string> exr_tag_to_oiio_std {
// Ones whose name we change to our convention
{ "cameraTransform", "worldtocamera" },
{ "capDate", "DateTime" },
{ "comments", "ImageDescription" },
{ "owner", "Copyright" },
{ "pixelAspectRatio", "PixelAspectRatio" },
{ "xDensity", "XResolution" },
{ "expTime", "ExposureTime" },
// Ones we don't rename -- OpenEXR convention matches ours
{ "wrapmodes", "wrapmodes" },
{ "aperture", "FNumber" },
// Ones to prefix with openexr:
{ "chunkCount", "openexr:chunkCount" },
{ "maxSamplesPerPixel", "openexr:maxSamplesPerPixel" },
{ "dwaCompressionLevel", "openexr:dwaCompressionLevel" },
// Ones to skip because we handle specially or consider them irrelevant
{ "channels", "" },
{ "compression", "" },
{ "dataWindow", "" },
{ "displayWindow", "" },
{ "envmap", "" },
{ "tiledesc", "" },
{ "tiles", "" },
{ "type", "" },
// FIXME: Things to consider in the future:
// preview
// screenWindowCenter
// adoptedNeutral
// renderingTransform, lookModTransform
// utcOffset
// longitude latitude altitude
// focus isoSpeed
};
namespace pvt {
void
set_exr_threads();
// Split a full channel name into layer and suffix.
void
split_name(string_view fullname, string_view& layer, string_view& suffix)
{
size_t dot = fullname.find_last_of('.');
if (dot == string_view::npos) {
suffix = fullname;
layer = string_view();
} else {
layer = string_view(fullname.data(), dot + 1);
suffix = string_view(fullname.data() + dot + 1,
fullname.size() - dot - 1);
}
}
inline bool
str_equal_either(string_view str, string_view a, string_view b)
{
return Strutil::iequals(str, a) || Strutil::iequals(str, b);
}
// Do the channels appear to be R, G, B (or known common aliases)?
bool
channels_are_rgb(const ImageSpec& spec)
{
return spec.nchannels >= 3
&& str_equal_either(spec.channel_name(0), "R", "Red")
&& str_equal_either(spec.channel_name(1), "G", "Green")
&& str_equal_either(spec.channel_name(2), "B", "Blue");
}
} // namespace pvt
OpenEXRInput::OpenEXRInput() { init(); }
bool
OpenEXRInput::valid_file(Filesystem::IOProxy* ioproxy) const
{
if (!ioproxy || ioproxy->mode() != Filesystem::IOProxy::Mode::Read)
return false;
try {
OpenEXRInputStream IStream("", ioproxy);
return Imf::isOpenExrFile(IStream);
} catch (const std::exception& e) {
return false;
}
}
bool
OpenEXRInput::open(const std::string& name, ImageSpec& newspec,
const ImageSpec& config)
{
// First thing's first. See if we're been given an IOProxy. We have to
// do this before the check for non-exr files, that's why it's here and
// not where the rest of the configuration hints are handled.
const ParamValue* param = config.find_attribute("oiio:ioproxy",
TypeDesc::PTR);
if (param)
m_io = param->get<Filesystem::IOProxy*>();
// Quick check to immediately reject nonexistent or non-exr files.
if (!m_io && !Filesystem::is_regular(name)) {
errorfmt("Could not open file \"{}\"", name);
return false;
}
// If we weren't given an IOProxy, create one now that just reads from
// the file.
if (!m_io) {
m_io = new Filesystem::IOFile(name, Filesystem::IOProxy::Read);
m_local_io.reset(m_io);
}
OIIO_ASSERT(m_io);
if (!valid_file(m_io)) {
errorfmt("\"{}\" is not an OpenEXR file", name);
return false;
}
// Check any other configuration hints
m_filename = name;
// "missingcolor" gives fill color for missing scanlines or tiles.
if (const ParamValue* m = config.find_attribute("oiio:missingcolor")) {
if (m->type().basetype == TypeDesc::STRING) {
// missingcolor as string
m_missingcolor = Strutil::extract_from_list_string<float>(
m->get_string());
} else {
// missingcolor as numeric array
int n = m->type().basevalues();
m_missingcolor.clear();
m_missingcolor.resize(n);
for (int i = 0; i < n; ++i)
m_missingcolor[i] = m->get_float(i);
}
} else {
// If not passed explicit, is there a global setting?
std::string mc = OIIO::get_string_attribute("missingcolor");
if (mc.size())
m_missingcolor = Strutil::extract_from_list_string<float>(mc);
}
// Before engaging further with OpenEXR, make sure it is using the right
// number of threads.
pvt::set_exr_threads();
// Clear the spec with default constructor
m_spec = ImageSpec();
// Establish an input stream.
try {
if (m_io->mode() != Filesystem::IOProxy::Read) {
// 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_io->seek(0);
m_input_stream = new OpenEXRInputStream(name.c_str(), m_io);
} catch (const std::exception& e) {
m_input_stream = NULL;
errorfmt("OpenEXR exception: {}", e.what());
return false;
} catch (...) { // catch-all for edge cases or compiler bugs
m_input_stream = NULL;
errorfmt("OpenEXR exception: unknown");
return false;
}
// Read the header by constructing a MultiPartInputFile from the input
// stream.
try {
m_input_multipart = new Imf::MultiPartInputFile(*m_input_stream);
} catch (const std::exception& e) {
delete m_input_stream;
m_input_stream = NULL;
errorfmt("OpenEXR exception: {}", e.what());
return false;
} catch (...) { // catch-all for edge cases or compiler bugs
m_input_stream = NULL;
errorfmt("OpenEXR exception: unknown");
return false;
}
m_nsubimages = m_input_multipart->parts();
m_parts.resize(m_nsubimages);
m_subimage = -1;
m_miplevel = -1;
// Set up for the first subimage ("part"). This will trigger reading
// information about all the parts.
bool ok = seek_subimage(0, 0);
if (ok)
newspec = m_spec;
else
close();
return ok;
}
// Count number of MIPmap levels
inline int
numlevels(int width, int roundingmode)
{
int nlevels = 1;
for (; width > 1; ++nlevels) {
if (roundingmode == Imf::ROUND_DOWN)
width = width / 2;
else
width = (width + 1) / 2;
}
return nlevels;
}
bool
OpenEXRInput::PartInfo::parse_header(OpenEXRInput* in,
const Imf::Header* header)
{
bool ok = true;
if (initialized)
return ok;
ImageInput::lock_guard lock(*in);
OIIO_DASSERT(header);
spec = ImageSpec();
top_datawindow = header->dataWindow();
top_displaywindow = header->displayWindow();
spec.x = top_datawindow.min.x;
spec.y = top_datawindow.min.y;
spec.z = 0;
spec.width = top_datawindow.max.x - top_datawindow.min.x + 1;
spec.height = top_datawindow.max.y - top_datawindow.min.y + 1;
spec.depth = 1;
topwidth = spec.width; // Save top-level mipmap dimensions
topheight = spec.height;
spec.full_x = top_displaywindow.min.x;
spec.full_y = top_displaywindow.min.y;
spec.full_z = 0;
spec.full_width = top_displaywindow.max.x - top_displaywindow.min.x + 1;
spec.full_height = top_displaywindow.max.y - top_displaywindow.min.y + 1;
spec.full_depth = 1;
spec.tile_depth = 1;
if (header->hasTileDescription()
&& Strutil::icontains(header->type(), "tile")) {
const Imf::TileDescription& td(header->tileDescription());
spec.tile_width = td.xSize;
spec.tile_height = td.ySize;
levelmode = td.mode;
roundingmode = td.roundingMode;
if (levelmode == Imf::MIPMAP_LEVELS)
nmiplevels = numlevels(std::max(topwidth, topheight), roundingmode);
else if (levelmode == Imf::RIPMAP_LEVELS)
nmiplevels = numlevels(std::max(topwidth, topheight), roundingmode);
else
nmiplevels = 1;
} else {
spec.tile_width = 0;
spec.tile_height = 0;
levelmode = Imf::ONE_LEVEL;
nmiplevels = 1;
}
if (!query_channels(in, header)) // also sets format
return false;
spec.deep = Strutil::istarts_with(header->type(), "deep");
if (levelmode != Imf::ONE_LEVEL)
spec.attribute("openexr:roundingmode", roundingmode);
const Imf::EnvmapAttribute* envmap;
envmap = header->findTypedAttribute<Imf::EnvmapAttribute>("envmap");
if (envmap) {
cubeface = (envmap->value() == Imf::ENVMAP_CUBE);
spec.attribute("textureformat", cubeface ? "CubeFace Environment"
: "LatLong Environment");
// OpenEXR conventions for env maps
if (!cubeface)
spec.attribute("oiio:updirection", "y");
spec.attribute("oiio:sampleborder", 1);
// FIXME - detect CubeFace Shadow?
} else {
cubeface = false;
if (spec.tile_width && levelmode == Imf::MIPMAP_LEVELS)
spec.attribute("textureformat", "Plain Texture");
// FIXME - detect Shadow
}
const Imf::CompressionAttribute* compressattr;
compressattr = header->findTypedAttribute<Imf::CompressionAttribute>(
"compression");
if (compressattr) {
const char* comp = NULL;
switch (compressattr->value()) {
case Imf::NO_COMPRESSION: comp = "none"; break;
case Imf::RLE_COMPRESSION: comp = "rle"; break;
case Imf::ZIPS_COMPRESSION: comp = "zips"; break;
case Imf::ZIP_COMPRESSION: comp = "zip"; break;
case Imf::PIZ_COMPRESSION: comp = "piz"; break;
case Imf::PXR24_COMPRESSION: comp = "pxr24"; break;
case Imf::B44_COMPRESSION: comp = "b44"; break;
case Imf::B44A_COMPRESSION: comp = "b44a"; break;
case Imf::DWAA_COMPRESSION: comp = "dwaa"; break;
case Imf::DWAB_COMPRESSION: comp = "dwab"; break;
#ifdef IMF_HTJ2K_COMPRESSION
case Imf::HTJ2K_COMPRESSION: comp = "htj2k"; break;
#endif
#ifdef IMF_ZSTD_COMPRESSION
case Imf::ZSTD_COMPRESSION: comp = "zstd"; break;
#endif
default: break;
}
if (comp)
spec.attribute("compression", comp);
}
for (auto hit = header->begin(); hit != header->end(); ++hit) {
const Imf::IntAttribute* iattr;
const Imf::FloatAttribute* fattr;
const Imf::StringAttribute* sattr;
const Imf::M33fAttribute* m33fattr;
const Imf::M44fAttribute* m44fattr;
const Imf::V3fAttribute* v3fattr;
const Imf::V3iAttribute* v3iattr;
const Imf::V2fAttribute* v2fattr;
const Imf::V2iAttribute* v2iattr;
const Imf::Box2iAttribute* b2iattr;
const Imf::Box2fAttribute* b2fattr;
const Imf::TimeCodeAttribute* tattr;
const Imf::KeyCodeAttribute* kcattr;
const Imf::ChromaticitiesAttribute* crattr;
const Imf::RationalAttribute* rattr;
#if OPENEXR_HAS_FLOATVECTOR
const Imf::FloatVectorAttribute* fvattr;
#endif
const Imf::StringVectorAttribute* svattr;
const Imf::DoubleAttribute* dattr;
const Imf::V2dAttribute* v2dattr;
const Imf::V3dAttribute* v3dattr;
const Imf::M33dAttribute* m33dattr;
const Imf::M44dAttribute* m44dattr;
const Imf::LineOrderAttribute* lattr;
const char* name = hit.name();
auto found = exr_tag_to_oiio_std.find(name);
std::string oname(found != exr_tag_to_oiio_std.end() ? found->second
: name);
if (oname.empty()) // Empty string means skip this attrib
continue;
// if (oname == name)
// oname = std::string(format_name()) + "_" + oname;
const Imf::Attribute& attrib = hit.attribute();
std::string type = attrib.typeName();
if (type == "string"
&& (sattr = header->findTypedAttribute<Imf::StringAttribute>(
name))) {
if (sattr->value().size())
spec.attribute(oname, sattr->value().c_str());
} else if (type == "int"
&& (iattr = header->findTypedAttribute<Imf::IntAttribute>(
name)))
spec.attribute(oname, iattr->value());
else if (type == "float"
&& (fattr = header->findTypedAttribute<Imf::FloatAttribute>(
name)))
spec.attribute(oname, fattr->value());
else if (type == "m33f"
&& (m33fattr = header->findTypedAttribute<Imf::M33fAttribute>(
name)))
spec.attribute(oname, TypeMatrix33, &(m33fattr->value()));
else if (type == "m44f"
&& (m44fattr = header->findTypedAttribute<Imf::M44fAttribute>(
name)))
spec.attribute(oname, TypeMatrix44, &(m44fattr->value()));
else if (type == "v3f"
&& (v3fattr = header->findTypedAttribute<Imf::V3fAttribute>(
name)))
spec.attribute(oname, TypeVector, &(v3fattr->value()));
else if (type == "v3i"
&& (v3iattr = header->findTypedAttribute<Imf::V3iAttribute>(
name))) {
TypeDesc v3(TypeDesc::INT, TypeDesc::VEC3, TypeDesc::VECTOR);
spec.attribute(oname, v3, &(v3iattr->value()));
} else if (type == "v2f"
&& (v2fattr = header->findTypedAttribute<Imf::V2fAttribute>(
name))) {
TypeDesc v2(TypeDesc::FLOAT, TypeDesc::VEC2);
spec.attribute(oname, v2, &(v2fattr->value()));
} else if (type == "v2i"
&& (v2iattr = header->findTypedAttribute<Imf::V2iAttribute>(
name))) {
TypeDesc v2(TypeDesc::INT, TypeDesc::VEC2);
spec.attribute(oname, v2, &(v2iattr->value()));
} else if (type == "stringvector"
&& (svattr
= header->findTypedAttribute<Imf::StringVectorAttribute>(
name))) {
std::vector<std::string> strvec = svattr->value();
std::vector<ustring> ustrvec(strvec.size());
for (size_t i = 0, e = strvec.size(); i < e; ++i)
ustrvec[i] = strvec[i];
TypeDesc sv(TypeDesc::STRING, ustrvec.size());
spec.attribute(oname, sv, &ustrvec[0]);
#if OPENEXR_HAS_FLOATVECTOR
} else if (type == "floatvector"
&& (fvattr
= header->findTypedAttribute<Imf::FloatVectorAttribute>(
name))) {
std::vector<float> fvec = fvattr->value();
TypeDesc fv(TypeDesc::FLOAT, fvec.size());
spec.attribute(oname, fv, &fvec[0]);
#endif
} else if (type == "double"
&& (dattr = header->findTypedAttribute<Imf::DoubleAttribute>(
name))) {
TypeDesc d(TypeDesc::DOUBLE);
spec.attribute(oname, d, &(dattr->value()));
} else if (type == "v2d"
&& (v2dattr = header->findTypedAttribute<Imf::V2dAttribute>(
name))) {
TypeDesc v2(TypeDesc::DOUBLE, TypeDesc::VEC2);
spec.attribute(oname, v2, &(v2dattr->value()));
} else if (type == "v3d"
&& (v3dattr = header->findTypedAttribute<Imf::V3dAttribute>(
name))) {
TypeDesc v3(TypeDesc::DOUBLE, TypeDesc::VEC3, TypeDesc::VECTOR);
spec.attribute(oname, v3, &(v3dattr->value()));
} else if (type == "m33d"
&& (m33dattr = header->findTypedAttribute<Imf::M33dAttribute>(
name))) {
TypeDesc m33(TypeDesc::DOUBLE, TypeDesc::MATRIX33);
spec.attribute(oname, m33, &(m33dattr->value()));
} else if (type == "m44d"
&& (m44dattr = header->findTypedAttribute<Imf::M44dAttribute>(
name))) {
TypeDesc m44(TypeDesc::DOUBLE, TypeDesc::MATRIX44);
spec.attribute(oname, m44, &(m44dattr->value()));
} else if (type == "box2i"
&& (b2iattr = header->findTypedAttribute<Imf::Box2iAttribute>(
name))) {
TypeDesc bx(TypeDesc::INT, TypeDesc::VEC2, 2);
spec.attribute(oname, bx, &b2iattr->value());
} else if (type == "box2f"
&& (b2fattr = header->findTypedAttribute<Imf::Box2fAttribute>(
name))) {
TypeDesc bx(TypeDesc::FLOAT, TypeDesc::VEC2, 2);
spec.attribute(oname, bx, &b2fattr->value());
} else if (type == "timecode"
&& (tattr
= header->findTypedAttribute<Imf::TimeCodeAttribute>(
name))) {
unsigned int timecode[2];
timecode[0] = tattr->value().timeAndFlags(
Imf::TimeCode::TV60_PACKING); //TV60 returns unchanged _time
timecode[1] = tattr->value().userData();
// Elevate "timeCode" to smpte:TimeCode
if (oname == "timeCode")
oname = "smpte:TimeCode";
spec.attribute(oname, TypeTimeCode, timecode);
} else if (type == "keycode"
&& (kcattr
= header->findTypedAttribute<Imf::KeyCodeAttribute>(
name))) {
const Imf::KeyCode* k = &kcattr->value();
unsigned int keycode[7];
keycode[0] = k->filmMfcCode();
keycode[1] = k->filmType();
keycode[2] = k->prefix();
keycode[3] = k->count();
keycode[4] = k->perfOffset();
keycode[5] = k->perfsPerFrame();
keycode[6] = k->perfsPerCount();
// Elevate "keyCode" to smpte:KeyCode
if (oname == "keyCode")
oname = "smpte:KeyCode";
spec.attribute(oname, TypeKeyCode, keycode);
} else if (type == "chromaticities"
&& (crattr = header->findTypedAttribute<
Imf::ChromaticitiesAttribute>(name))) {
const Imf::Chromaticities* chroma = &crattr->value();
spec.attribute(oname, TypeDesc(TypeDesc::FLOAT, 8),
(const float*)chroma);
} else if (type == "rational"
&& (rattr
= header->findTypedAttribute<Imf::RationalAttribute>(
name))) {
const Imf::Rational* rational = &rattr->value();
int n = rational->n;
unsigned int d = rational->d;
if (d < (1UL << 31)) {
int r[2];
r[0] = n;
r[1] = static_cast<int>(d);
spec.attribute(oname, TypeRational, r);
} else {
int f = static_cast<int>(std::gcd(int64_t(n), int64_t(d)));
if (f > 1) {
int r[2];
r[0] = n / f;
r[1] = static_cast<int>(d / f);
spec.attribute(oname, TypeRational, r);
} else {
// TODO: find a way to allow the client to accept "close" rational values
OIIO::debugfmt(
"Don't know what to do with OpenEXR Rational attribute {} with value {} / {} that we cannot represent exactly",
oname, n, d);
}
}
} else if (type == "lineOrder"
&& (lattr
= header->findTypedAttribute<Imf::LineOrderAttribute>(
name))) {
const char* lineOrder = "increasingY";
switch (lattr->value()) {
case Imf::INCREASING_Y: lineOrder = "increasingY"; break;
case Imf::DECREASING_Y: lineOrder = "decreasingY"; break;
case Imf::RANDOM_Y: lineOrder = "randomY"; break;
default: break;
}
spec.attribute("openexr:lineOrder", lineOrder);
} else {
#if 0
print(std::cerr, " unknown attribute '{}' name '{}'\n",
type, name);
#endif
}
}
float aspect = spec.get_float_attribute("PixelAspectRatio", 0.0f);
float xdensity = spec.get_float_attribute("XResolution", 0.0f);
if (xdensity) {
// If XResolution is found, supply the YResolution and unit.
spec.attribute("YResolution", xdensity * (aspect ? aspect : 1.0f));
spec.attribute("ResolutionUnit", "in"); // EXR is always pixels/inch
}
// EXR "name" also gets passed along as "oiio:subimagename".
if (header->hasName())
spec.attribute("oiio:subimagename", header->name());
spec.attribute("oiio:subimages", in->m_nsubimages);
// Try to figure out the color space for some unambiguous cases
if (spec.get_int_attribute("acesImageContainerFlag") == 1) {
spec.set_colorspace("lin_ap0_scene");
} else if (auto c = spec.find_attribute("colorInteropID", TypeString)) {
spec.set_colorspace(c->get_ustring());
}
// Squash some problematic texture metadata if we suspect it's wrong
pvt::check_texture_metadata_sanity(spec);
initialized = true;
return ok;
}
namespace {
static TypeDesc
TypeDesc_from_ImfPixelType(Imf::PixelType ptype)
{
switch (ptype) {
case Imf::UINT: return TypeDesc::UINT; break;
case Imf::HALF: return TypeDesc::HALF; break;
case Imf::FLOAT: return TypeDesc::FLOAT; break;
default:
OIIO_ASSERT_MSG(0, "Unknown Imf::PixelType %d", int(ptype));
return TypeUnknown;
}
}
// Used to hold channel information for sorting into canonical order
struct ChanNameHolder {
string_view fullname; // layer.suffix
string_view layer; // just layer
string_view suffix; // just suffix (or the fillname, if no layer)
int exr_channel_number; // channel index in the exr (sorted by name)
int special_index; // sort order for special reserved names
Imf::PixelType exr_data_type;
TypeDesc datatype;
int xSampling;
int ySampling;
ChanNameHolder(string_view fullname, int n, const Imf::Channel& exrchan)
: fullname(fullname)
, exr_channel_number(n)
, special_index(10000)
, exr_data_type(exrchan.type)
, datatype(TypeDesc_from_ImfPixelType(exrchan.type))
, xSampling(exrchan.xSampling)
, ySampling(exrchan.ySampling)
{
pvt::split_name(fullname, layer, suffix);
}
// Compute canoninical channel list sort priority
void compute_special_index()
{
static const char* special[]
= { "R", "Red", "G", "Green", "B", "Blue", "Y",
"real", "imag", "A", "Alpha", "AR", "RA", "AG",
"GA", "AB", "BA", "Z", "Depth", "Zback", nullptr };
for (int i = 0; special[i]; ++i)
if (Strutil::iequals(suffix, special[i])) {
special_index = i;
return;
}
}
// Compute alternate channel sort priority for layers that contain
// x,y,z.
void compute_special_index_xyz()
{
static const char* special[]
= { "R", "Red", "G", "Green", "B", "Blue", /* "Y", */
"X", "Y", "Z", "real", "imag", "A", "Alpha", "AR",
"RA", "AG", "GA", "AB", "BA", "Depth", "Zback", nullptr };
for (int i = 0; special[i]; ++i)
if (Strutil::iequals(suffix, special[i])) {
special_index = i;
return;
}
}
// Partial sort on layer only
static bool compare_layer(const ChanNameHolder& a, const ChanNameHolder& b)
{
return (a.layer < b.layer);
}
// Full sort on layer name, special index, suffix
static bool compare_cnh(const ChanNameHolder& a, const ChanNameHolder& b)
{
if (a.layer < b.layer)
return true;
if (a.layer > b.layer)
return false;
// Within the same layer
if (a.special_index < b.special_index)
return true;
if (a.special_index > b.special_index)
return false;
return a.suffix < b.suffix;
}
};
// Is the channel name (suffix only) in the list?
static bool
suffixfound(string_view name, span<ChanNameHolder> chans)
{
for (auto& c : chans)
if (Strutil::iequals(name, c.suffix))
return true;
return false;
}
// Returns the index of that channel name (suffix only) in the list, or -1 in case of failure.
static int
get_index_of_suffix(string_view name, span<ChanNameHolder> chans)
{
for (size_t i = 0, n = chans.size(); i < n; ++i)
if (Strutil::iequals(name, chans[i].suffix))
return static_cast<int>(i);
return -1;
}
// Is this a luminance-chroma image, i.e., Y/BY/RY or Y/BY/RY/A or Y/BY/RY/Alpha?
//
// Note that extra channels are not supported.
static bool
is_luminance_chroma(span<ChanNameHolder> chans)
{
if (chans.size() < 3 || chans.size() > 4)
return false;
if (!suffixfound("Y", chans))
return false;
if (!suffixfound("BY", chans))
return false;
if (!suffixfound("RY", chans))
return false;
if (chans.size() == 4 && !suffixfound("A", chans)
&& !suffixfound("Alpha", chans))
return false;
return true;
}
} // namespace
bool
OpenEXRInput::PartInfo::query_channels(OpenEXRInput* in,
const Imf::Header* header)
{
OIIO_DASSERT(!initialized);
bool ok = true;
const Imf::ChannelList& channels(header->channels());
std::vector<ChanNameHolder> cnh;
int c = 0;
for (auto ci = channels.begin(); ci != channels.end(); ++c, ++ci)
cnh.emplace_back(ci.name(), c, ci.channel());
spec.nchannels = int(cnh.size());
if (!spec.nchannels) {
in->errorfmt("No channels found");
return false;
}
// First, do a partial sort by layername. EXR should already be in that
// order, but take no chances.
std::sort(cnh.begin(), cnh.end(), ChanNameHolder::compare_layer);
// Now, within each layer, sort by channel name
for (auto layerbegin = cnh.begin(); layerbegin != cnh.end();) {
// Identify the subrange that comprises a layer
auto layerend = layerbegin + 1;
while (layerend != cnh.end() && layerbegin->layer == layerend->layer)
++layerend;
span<ChanNameHolder> layerspan(&(*layerbegin), layerend - layerbegin);
// Strutil::printf("layerspan:\n");
// for (auto& c : layerspan)
// Strutil::print(" {} = {} . {}\n", c.fullname, c.layer, c.suffix);
if (suffixfound("X", layerspan)
&& (suffixfound("Y", layerspan) || suffixfound("Z", layerspan))) {
// If "X", and at least one of "Y" and "Z", are found among the
// channel names of this layer, it must encode some kind of
// position or normal. The usual sort order will give a weird
// result. Choose a different sort order to reflect this.
for (auto& ch : layerspan)
ch.compute_special_index_xyz();
} else {
// Use the usual sort order.
for (auto& ch : layerspan)
ch.compute_special_index();
}
std::sort(layerbegin, layerend, ChanNameHolder::compare_cnh);
layerbegin = layerend; // next set of layers
}
// Now we should have cnh sorted into the order that we want to present
// to the OIIO client.
// Limitations for luminance-chroma images: no tiling, no deep samples, no
// miplevels/subimages, no extra channels.
luminance_chroma = is_luminance_chroma(cnh);
if (luminance_chroma) {
spec.attribute("openexr:luminancechroma", 1);
spec.format = TypeDesc::HALF;
spec.nchannels = cnh.size();
if (spec.nchannels == 3) {
spec.channelnames = { "R", "G", "B" };
spec.alpha_channel = -1;
spec.z_channel = -1;
} else {
OIIO_ASSERT(spec.nchannels == 4);
int index_a = get_index_of_suffix("A", cnh);
if (index_a != -1) {
spec.channelnames = { "R", "G", "B", "A" };
spec.alpha_channel = index_a;
} else {
spec.channelnames = { "R", "G", "B", "Alpha" };
spec.alpha_channel = get_index_of_suffix("Alpha", cnh);
OIIO_ASSERT(spec.alpha_channel != -1);
}
spec.z_channel = -1;
}
spec.channelformats.clear();
return true;
}
spec.format = TypeDesc::UNKNOWN;
bool all_one_format = true;
for (int c = 0; c < spec.nchannels; ++c) {
spec.channelnames.push_back(cnh[c].fullname);
spec.channelformats.push_back(cnh[c].datatype);
spec.format = TypeDesc::basetype_merge(spec.format, cnh[c].datatype);
pixeltype.push_back(cnh[c].exr_data_type);
chanbytes.push_back(cnh[c].datatype.size());
all_one_format &= (cnh[c].datatype == cnh[0].datatype);
if (spec.alpha_channel < 0
&& (Strutil::iequals(cnh[c].suffix, "A")
|| Strutil::iequals(cnh[c].suffix, "Alpha")))
spec.alpha_channel = c;
if (spec.z_channel < 0
&& (Strutil::iequals(cnh[c].suffix, "Z")
|| Strutil::iequals(cnh[c].suffix, "Depth")))
spec.z_channel = c;
if (cnh[c].xSampling != 1 || cnh[c].ySampling != 1) {
ok = false;
in->errorfmt(
"Subsampled channels are not supported (channel \"{}\" has sampling {},{}).",
cnh[c].fullname, cnh[c].xSampling, cnh[c].ySampling);
// FIXME: Some day, we should handle channel subsampling (beyond the luminance chroma
// special case, possibly replacing it).
}
}
OIIO_DASSERT((int)spec.channelnames.size() == spec.nchannels);
OIIO_DASSERT(spec.format != TypeDesc::UNKNOWN);
if (all_one_format)
spec.channelformats.clear();
return ok;
}
void
OpenEXRInput::PartInfo::compute_mipres(int miplevel, ImageSpec& spec) const
{
// Compute the resolution of the requested mip level, and also adjust
// the "full" size appropriately (based on the exr display window).
if (levelmode == Imf::ONE_LEVEL)
return; // spec is already correct
int w = topwidth;
int h = topheight;
if (levelmode == Imf::MIPMAP_LEVELS) {
for (int m = miplevel; m; --m) {
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);
}
} else if (levelmode == Imf::RIPMAP_LEVELS) {
// FIXME
} else {
OIIO_ASSERT_MSG(0, "Unknown levelmode %d", int(levelmode));
}
spec.width = w;
spec.height = h;
// N.B. OpenEXR doesn't support data and display windows per MIPmap
// level. So always take from the top level.
Imath::Box2i datawindow = top_datawindow;
Imath::Box2i displaywindow = top_displaywindow;
spec.x = datawindow.min.x;
spec.y = datawindow.min.y;
if (miplevel == 0) {
spec.full_x = displaywindow.min.x;
spec.full_y = displaywindow.min.y;
spec.full_width = displaywindow.max.x - displaywindow.min.x + 1;
spec.full_height = displaywindow.max.y - displaywindow.min.y + 1;
} else {
spec.full_x = spec.x;
spec.full_y = spec.y;
spec.full_width = spec.width;
spec.full_height = spec.height;
}
if (cubeface) {
spec.full_width = w;
spec.full_height = w;
}
}