-
Notifications
You must be signed in to change notification settings - Fork 667
Expand file tree
/
Copy pathexrinput_c.cpp
More file actions
2018 lines (1781 loc) · 74.3 KB
/
exrinput_c.cpp
File metadata and controls
2018 lines (1781 loc) · 74.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 2021-present 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 "exr_pvt.h"
#include <OpenEXR/openexr.h>
#include "imageio_pvt.h"
#include <OpenImageIO/color.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
struct oiioexr_filebuf_struct {
ImageInput* m_img = nullptr;
Filesystem::IOProxy* m_io = nullptr;
};
static void
oiio_exr_error_handler(exr_const_context_t ctxt, exr_result_t code,
const char* msg = nullptr)
{
void* userdata;
if (EXR_ERR_SUCCESS == exr_get_user_data(ctxt, &userdata)) {
if (userdata) {
oiioexr_filebuf_struct* fb = static_cast<oiioexr_filebuf_struct*>(
userdata);
if (fb->m_img) {
fb->m_img->errorfmt("EXR Error ({}): {} {}",
(fb->m_io ? fb->m_io->filename().c_str()
: "<unknown>"),
exr_get_error_code_as_string(code),
msg ? msg
: exr_get_default_error_message(code));
return;
}
}
}
// this should only happen from valid_file check, do we care?
// print(std::cerr, "EXR error with no valid context ({}): {}\n",
// exr_get_error_code_as_string(code), msg);
}
static int64_t
oiio_exr_query_size_func(exr_const_context_t ctxt, void* userdata)
{
oiioexr_filebuf_struct* fb = static_cast<oiioexr_filebuf_struct*>(userdata);
if (fb)
return static_cast<int64_t>(fb->m_io->tell());
return -1;
}
static int64_t
oiio_exr_read_func(exr_const_context_t ctxt, void* userdata, void* buffer,
uint64_t sz, uint64_t offset,
exr_stream_error_func_ptr_t error_cb)
{
oiioexr_filebuf_struct* fb = static_cast<oiioexr_filebuf_struct*>(userdata);
int64_t nread = -1;
if (fb) {
Filesystem::IOProxy* io = fb->m_io;
if (io) {
size_t retval = io->pread(buffer, sz, offset);
if (retval != size_t(-1)) {
nread = static_cast<int64_t>(retval);
} else {
std::string err = io->error();
error_cb(ctxt, EXR_ERR_READ_IO,
"Could not read from file: \"%s\" (%s)",
io->filename().c_str(),
err.empty() ? "<unknown error>" : err.c_str());
}
}
}
return nread;
}
class OpenEXRCoreInput final : public ImageInput {
public:
OpenEXRCoreInput();
~OpenEXRCoreInput() override { close(); }
const char* format_name(void) const override { return "openexr"; }
int supports(string_view feature) const override
{
return (feature == "arbitrary_metadata"
|| feature == "exif" // Because of arbitrary_metadata
|| feature == "ioproxy"
|| feature == "iptc" // Because of arbitrary_metadata
|| feature == "multiimage" || feature == "mipmap");
}
bool valid_file(const std::string& filename) const override;
bool open(const std::string& name, ImageSpec& newspec,
const ImageSpec& config) override;
bool open(const std::string& name, ImageSpec& newspec) override
{
return open(name, newspec, ImageSpec());
}
bool close() override;
int current_subimage(void) const override { return m_subimage; }
int current_miplevel(void) const override { return m_miplevel; }
bool seek_subimage(int subimage, int miplevel) override;
ImageSpec spec(int subimage, int miplevel) override;
ImageSpec spec_dimensions(int subimage, int miplevel) override;
bool read_native_scanline(int subimage, int miplevel, int y, int z,
void* data) override;
bool read_native_scanlines(int subimage, int miplevel, int ybegin, int yend,
int z, void* data) override;
bool read_native_scanlines(int subimage, int miplevel, int ybegin, int yend,
int z, int chbegin, int chend,
void* data) override;
bool read_native_tile(int subimage, int miplevel, int x, int y, int z,
void* data) override;
bool read_native_tiles(int subimage, int miplevel, int xbegin, int xend,
int ybegin, int yend, int zbegin, int zend,
void* data) override;
bool read_native_tiles(int subimage, int miplevel, int xbegin, int xend,
int ybegin, int yend, int zbegin, int zend,
int chbegin, int chend, void* data) override;
bool read_native_deep_scanlines(int subimage, int miplevel, int ybegin,
int yend, int z, int chbegin, int chend,
DeepData& deepdata) override;
bool read_native_deep_tiles(int subimage, int miplevel, int xbegin,
int xend, int ybegin, int yend, int zbegin,
int zend, int chbegin, int chend,
DeepData& deepdata) override;
bool set_ioproxy(Filesystem::IOProxy* ioproxy) override
{
OIIO_ASSERT(!m_exr_context);
m_userdata.m_io = ioproxy;
return true;
}
private:
const ImageSpec& init_part(int subimage, int miplevel);
struct PartInfo {
std::atomic_bool initialized;
ImageSpec spec;
int topwidth; ///< Width of top mip level
int topheight; ///< Height of top mip level
exr_tile_level_mode_t levelmode; ///< The level mode
exr_tile_round_mode_t roundingmode; ///< Rounding mode
bool cubeface; ///< It's a cubeface environment map
int32_t nmiplevels; ///< How many MIP levels are there?
exr_attr_box2i_t top_datawindow;
exr_attr_box2i_t top_displaywindow;
std::vector<exr_pixel_type_t> pixeltype; ///< Imf pixel type for each chan
std::vector<int> chanbytes; ///< Size (in bytes) of each channel
PartInfo()
: initialized(false)
{
}
PartInfo(const PartInfo& p)
: initialized((bool)p.initialized)
, spec(p.spec)
, topwidth(p.topwidth)
, topheight(p.topheight)
, levelmode(p.levelmode)
, roundingmode(p.roundingmode)
, cubeface(p.cubeface)
, nmiplevels(p.nmiplevels)
, top_datawindow(p.top_datawindow)
, top_displaywindow(p.top_displaywindow)
, pixeltype(p.pixeltype)
, chanbytes(p.chanbytes)
{
}
~PartInfo() {}
bool parse_header(OpenEXRCoreInput* in, exr_context_t ctxt,
int subimage, int miplevel);
bool query_channels(OpenEXRCoreInput* in, exr_context_t ctxt,
int subimage);
void compute_mipres(int miplevel, ImageSpec& spec) const;
};
friend struct PartInfo;
// cache of the parsed data
std::vector<PartInfo> m_parts; ///< Image parts
// these are only needed to preserve the concept that you have
// state of seeking in the file
int m_subimage;
int m_miplevel;
exr_context_t m_exr_context = nullptr;
oiioexr_filebuf_struct m_userdata;
std::unique_ptr<Filesystem::IOProxy> m_local_io;
int m_nsubimages; ///< How many subimages are there?
std::vector<float> m_missingcolor; ///< Color for missing tile/scanline
std::string m_filename; // filename, if known
void init()
{
m_exr_context = nullptr;
m_userdata.m_img = this;
m_userdata.m_io = nullptr;
m_local_io.reset();
m_missingcolor.clear();
m_filename.clear();
}
bool valid_file(const std::string& filename, Filesystem::IOProxy* io) const;
// Fill in with 'missing' color/pattern.
bool check_fill_missing(int xbegin, int xend, int ybegin, int yend,
int zbegin, int zend, int chbegin, int chend,
void* data, stride_t xstride, stride_t ystride);
// Helper struct to destroy decoder upon scope exit
class DecoderDestroyer {
public:
DecoderDestroyer(exr_const_context_t ctx,
exr_decode_pipeline_t* decoder)
: ctx(ctx)
, decoder(decoder) {};
~DecoderDestroyer() { exr_decoding_destroy(ctx, decoder); }
private:
exr_const_context_t ctx;
exr_decode_pipeline_t* decoder;
};
friend class DecoderDestroyer;
};
OIIO_EXPORT ImageInput*
openexrcore_input_imageio_create()
{
return new OpenEXRCoreInput;
}
static std::map<std::string, std::string> cexr_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
};
OpenEXRCoreInput::OpenEXRCoreInput() { init(); }
bool
OpenEXRCoreInput::valid_file(const std::string& filename) const
{
return valid_file(filename, nullptr);
}
bool
OpenEXRCoreInput::valid_file(const std::string& filename,
Filesystem::IOProxy* io) const
{
oiioexr_filebuf_struct udata;
exr_context_initializer_t cinit = EXR_DEFAULT_CONTEXT_INITIALIZER;
cinit.error_handler_fn = &oiio_exr_error_handler;
// do we always want this?
std::unique_ptr<Filesystem::IOProxy> localio;
if (!io) {
localio.reset(
new Filesystem::IOFile(filename, Filesystem::IOProxy::Read));
io = localio.get();
}
if (io) {
udata.m_img
= nullptr; // this will silence the errors in the error handler above
udata.m_io = io;
cinit.user_data = &udata;
cinit.read_fn = &oiio_exr_read_func;
cinit.size_fn = &oiio_exr_query_size_func;
}
exr_result_t rv = exr_test_file_header(filename.c_str(), &cinit);
return (rv == EXR_ERR_SUCCESS);
}
bool
OpenEXRCoreInput::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_userdata.m_io = param->get<Filesystem::IOProxy*>();
// Quick check to immediately reject nonexistent or non-exr files.
//KDTDISABLE quick checks are still file iOPs, let the file open handle this
//KDTDISABLE if (!m_io && !Filesystem::is_regular(name)) {
//KDTDISABLE errorfmt("Could not open file \"{}\"", name);
//KDTDISABLE return false;
//KDTDISABLE }
//KDTDISABLE if (!valid_file(name, m_io)) {
//KDTDISABLE errorfmt("\"{}\" is not an OpenEXR file", name);
//KDTDISABLE return false;
//KDTDISABLE }
// 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);
}
// Clear the spec with default constructor
m_spec = ImageSpec();
// Establish an input stream. If we weren't given an IOProxy, create one
// now that just reads from the file.
if (!m_userdata.m_io) {
m_userdata.m_io = new Filesystem::IOFile(name,
Filesystem::IOProxy::Read);
m_local_io.reset(m_userdata.m_io);
}
if (m_userdata.m_io->mode() != Filesystem::IOProxy::Read) {
// If the proxy couldn't be opened in read mode, try to
// return an error.
std::string e = m_userdata.m_io->error();
errorfmt("Could not open \"{}\" ({})", name,
e.size() ? e : std::string("unknown error"));
return false;
}
m_userdata.m_io->seek(0);
m_userdata.m_img = this;
exr_context_initializer_t cinit = EXR_DEFAULT_CONTEXT_INITIALIZER;
cinit.error_handler_fn = &oiio_exr_error_handler;
cinit.user_data = &m_userdata;
if (m_userdata.m_io) {
cinit.read_fn = &oiio_exr_read_func;
cinit.size_fn = &oiio_exr_query_size_func;
}
exr_result_t rv = exr_start_read(&m_exr_context, name.c_str(), &cinit);
if (rv != EXR_ERR_SUCCESS) {
// the error handler would have already reported the error into us
m_local_io.reset();
m_userdata.m_io = nullptr;
return false;
}
#if ENABLE_EXR_DEBUG_PRINTS || !defined(NDEBUG) /* allow debugging */
if (exrdebug)
exr_print_context_info(m_exr_context, 1);
#endif
rv = exr_get_count(m_exr_context, &m_nsubimages);
if (rv != EXR_ERR_SUCCESS) {
m_local_io.reset();
m_userdata.m_io = nullptr;
return false;
}
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;
}
const ImageSpec&
OpenEXRCoreInput::init_part(int subimage, int miplevel)
{
const PartInfo& part(m_parts[subimage]);
if (!part.initialized) {
// Only if this subimage hasn't yet been inventoried do we need
// to lock and seek, but that is only so we don't have to re-look values up
lock_guard lock(*this);
if (!part.initialized) {
if (!seek_subimage(subimage, miplevel)) {
errorfmt("Unable to initialize part");
return part.spec;
}
}
}
return part.spec;
}
bool
OpenEXRCoreInput::PartInfo::parse_header(OpenEXRCoreInput* in,
exr_context_t ctxt, int subimage,
int miplevel)
{
bool ok = true;
if (initialized)
return ok;
ImageInput::lock_guard lock(*in);
spec = ImageSpec();
exr_result_t rv = exr_get_data_window(ctxt, subimage, &top_datawindow);
if (rv != EXR_ERR_SUCCESS)
return false;
rv = exr_get_display_window(ctxt, subimage, &top_displaywindow);
if (rv != EXR_ERR_SUCCESS)
return false;
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;
exr_storage_t storage;
rv = exr_get_storage(ctxt, subimage, &storage);
if (rv != EXR_ERR_SUCCESS)
return false;
uint32_t txsz, tysz;
if ((storage == EXR_STORAGE_TILED || storage == EXR_STORAGE_DEEP_TILED)
&& EXR_ERR_SUCCESS
== exr_get_tile_descriptor(ctxt, subimage, &txsz, &tysz,
&levelmode, &roundingmode)) {
spec.tile_width = txsz;
spec.tile_height = tysz;
int32_t levelsx, levelsy;
rv = exr_get_tile_levels(ctxt, subimage, &levelsx, &levelsy);
if (rv != EXR_ERR_SUCCESS)
return false;
nmiplevels = std::max(levelsx, levelsy);
} else {
spec.tile_width = 0;
spec.tile_height = 0;
levelmode = EXR_TILE_ONE_LEVEL;
nmiplevels = 1;
}
if (!query_channels(in, ctxt, subimage)) // also sets format
return false;
spec.deep = (storage == EXR_STORAGE_DEEP_TILED
|| storage == EXR_STORAGE_DEEP_SCANLINE);
if (levelmode != EXR_TILE_ONE_LEVEL)
spec.attribute("openexr:roundingmode", (int)roundingmode);
exr_envmap_t envmap;
rv = exr_attr_get_envmap(ctxt, subimage, "envmap", &envmap);
if (rv == EXR_ERR_SUCCESS) {
cubeface = (envmap == EXR_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 == EXR_TILE_MIPMAP_LEVELS)
spec.attribute("textureformat", "Plain Texture");
// FIXME - detect Shadow
}
exr_compression_t comptype;
rv = exr_get_compression(ctxt, subimage, &comptype);
if (rv == EXR_ERR_SUCCESS) {
const char* comp = NULL;
switch (comptype) {
case EXR_COMPRESSION_NONE: comp = "none"; break;
case EXR_COMPRESSION_RLE: comp = "rle"; break;
case EXR_COMPRESSION_ZIPS: comp = "zips"; break;
case EXR_COMPRESSION_ZIP: comp = "zip"; break;
case EXR_COMPRESSION_PIZ: comp = "piz"; break;
case EXR_COMPRESSION_PXR24: comp = "pxr24"; break;
case EXR_COMPRESSION_B44: comp = "b44"; break;
case EXR_COMPRESSION_B44A: comp = "b44a"; break;
case EXR_COMPRESSION_DWAA: comp = "dwaa"; break;
case EXR_COMPRESSION_DWAB: comp = "dwab"; break;
#ifdef IMF_HTJ2K_COMPRESSION
case EXR_COMPRESSION_HTJ2K: comp = "htj2k"; break;
#endif
#ifdef IMF_ZSTD_COMPRESSION
case EXR_COMPRESSION_ZSTD: comp = "zstd"; break;
#endif
default: break;
}
if (comp)
spec.attribute("compression", comp);
}
int32_t attrcount = 0;
rv = exr_get_attribute_count(ctxt, subimage, &attrcount);
if (rv != EXR_ERR_SUCCESS)
return false;
for (int32_t i = 0; i < attrcount; ++i) {
const exr_attribute_t* attr;
rv = exr_get_attribute_by_index(ctxt, subimage,
EXR_ATTR_LIST_FILE_ORDER, i, &attr);
if (rv != EXR_ERR_SUCCESS)
return false;
auto found = cexr_tag_to_oiio_std.find(attr->name);
const char* oname = (found != cexr_tag_to_oiio_std.end())
? found->second.c_str()
: attr->name;
// empty name means skip;
if (!oname || oname[0] == '\0')
continue;
switch (attr->type) {
case EXR_ATTR_BOX2I: {
TypeDesc bx(TypeDesc::INT, TypeDesc::VEC2, 2);
spec.attribute(oname, bx, attr->box2i);
break;
}
case EXR_ATTR_BOX2F: {
TypeDesc bx(TypeDesc::FLOAT, TypeDesc::VEC2, 2);
spec.attribute(oname, bx, attr->box2f);
break;
}
case EXR_ATTR_CHROMATICITIES: {
spec.attribute(oname, TypeDesc(TypeDesc::FLOAT, 8),
(const float*)attr->chromaticities);
break;
}
case EXR_ATTR_DOUBLE: {
TypeDesc d(TypeDesc::DOUBLE);
spec.attribute(oname, d, &(attr->d));
break;
}
case EXR_ATTR_FLOAT: spec.attribute(oname, attr->f); break;
case EXR_ATTR_FLOAT_VECTOR: {
TypeDesc fv(TypeDesc::FLOAT, (size_t)attr->floatvector->length);
spec.attribute(oname, fv, attr->floatvector->arr);
break;
}
case EXR_ATTR_INT: spec.attribute(oname, attr->i); break;
case EXR_ATTR_KEYCODE:
// Elevate "keyCode" to smpte:KeyCode
if (!strcmp(oname, "keyCode"))
oname = "smpte:KeyCode";
spec.attribute(oname, TypeKeyCode, attr->keycode);
break;
case EXR_ATTR_M33F:
spec.attribute(oname, TypeMatrix33, attr->m33f);
break;
case EXR_ATTR_M33D: {
TypeDesc m33(TypeDesc::DOUBLE, TypeDesc::MATRIX33);
spec.attribute(oname, m33, attr->m33d);
break;
}
case EXR_ATTR_M44F:
spec.attribute(oname, TypeMatrix44, attr->m44f);
break;
case EXR_ATTR_M44D: {
TypeDesc m44(TypeDesc::DOUBLE, TypeDesc::MATRIX44);
spec.attribute(oname, m44, attr->m44d);
break;
}
case EXR_ATTR_RATIONAL: {
int32_t n = attr->rational->num;
uint32_t d = attr->rational->denom;
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);
}
}
break;
}
case EXR_ATTR_STRING:
if (attr->string && attr->string->str && attr->string->str[0])
spec.attribute(oname, attr->string->str);
break;
case EXR_ATTR_STRING_VECTOR: {
std::vector<ustring> ustrvec(attr->stringvector->n_strings);
for (int32_t i = 0, e = attr->stringvector->n_strings; i < e; ++i)
ustrvec[i] = attr->stringvector->strings[i].str;
TypeDesc sv(TypeDesc::STRING, ustrvec.size());
spec.attribute(oname, sv, &ustrvec[0]);
break;
}
case EXR_ATTR_TIMECODE:
// Elevate "timeCode" to smpte:TimeCode
if (!strcmp(oname, "timeCode"))
oname = "smpte:TimeCode";
spec.attribute(oname, TypeTimeCode, attr->timecode);
break;
case EXR_ATTR_V2I: {
TypeDesc v2(TypeDesc::INT, TypeDesc::VEC2);
spec.attribute(oname, v2, attr->v2i);
break;
}
case EXR_ATTR_V2F: {
TypeDesc v2(TypeDesc::FLOAT, TypeDesc::VEC2);
spec.attribute(oname, v2, attr->v2f);
break;
}
case EXR_ATTR_V2D: {
TypeDesc v2(TypeDesc::DOUBLE, TypeDesc::VEC2);
spec.attribute(oname, v2, attr->v2d);
break;
}
case EXR_ATTR_V3I: {
TypeDesc v3(TypeDesc::INT, TypeDesc::VEC3, TypeDesc::VECTOR);
spec.attribute(oname, v3, attr->v3i);
break;
}
case EXR_ATTR_V3F: spec.attribute(oname, TypeVector, attr->v3f); break;
case EXR_ATTR_V3D: {
TypeDesc v3(TypeDesc::DOUBLE, TypeDesc::VEC3, TypeDesc::VECTOR);
spec.attribute(oname, v3, attr->v3d);
break;
}
case EXR_ATTR_LINEORDER: {
std::string lineOrder = "increasingY";
switch (attr->uc) {
case EXR_LINEORDER_INCREASING_Y: lineOrder = "increasingY"; break;
case EXR_LINEORDER_DECREASING_Y: lineOrder = "decreasingY"; break;
case EXR_LINEORDER_RANDOM_Y: lineOrder = "randomY"; break;
default: break;
}
spec.attribute("openexr:lineOrder", lineOrder);
break;
}
case EXR_ATTR_PREVIEW:
case EXR_ATTR_OPAQUE:
case EXR_ATTR_ENVMAP:
case EXR_ATTR_COMPRESSION:
case EXR_ATTR_CHLIST:
case EXR_ATTR_TILEDESC:
default:
#if 0
print(std::cerr, " unknown attribute type '{}' in name '{}'\n",
attr->type_name, attr->name);
#endif
break;
}
}
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".
const char* partname;
if (exr_get_name(ctxt, subimage, &partname) == EXR_ERR_SUCCESS) {
if (partname)
spec.attribute("oiio:subimagename", partname);
}
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(exr_pixel_type_t ptype)
{
switch (ptype) {
case EXR_PIXEL_UINT: return TypeDesc::UINT; break;
case EXR_PIXEL_HALF: return TypeDesc::HALF; break;
case EXR_PIXEL_FLOAT: return TypeDesc::FLOAT; break;
default:
OIIO_ASSERT_MSG(0, "Unknown EXR exr_pixel_type_t %d", int(ptype));
return TypeUnknown;
}
}
// Used to hold channel information for sorting into canonical order
struct CChanNameHolder {
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
exr_pixel_type_t exr_data_type;
TypeDesc datatype;
int xSampling;
int ySampling;
CChanNameHolder(int n, const exr_attr_chlist_entry_t& exrchan)
: fullname(exrchan.name.str)
, exr_channel_number(n)
, special_index(10000)
, exr_data_type(exrchan.pixel_type)
, datatype(TypeDesc_from_ImfPixelType(exrchan.pixel_type))
, xSampling(exrchan.x_sampling)
, ySampling(exrchan.y_sampling)
{
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 CChanNameHolder& a,
const CChanNameHolder& b)
{
return (a.layer < b.layer);
}
// Full sort on layer name, special index, suffix
static bool compare_cnh(const CChanNameHolder& a, const CChanNameHolder& 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<CChanNameHolder> chans)
{
for (auto& c : chans)
if (Strutil::iequals(name, c.suffix))
return true;
return false;
}
} // namespace
bool
OpenEXRCoreInput::PartInfo::query_channels(OpenEXRCoreInput* in,
exr_context_t ctxt, int subimage)
{
OIIO_DASSERT(!initialized);
bool ok = true;
spec.nchannels = 0;
const exr_attr_chlist_t* chlist;
exr_result_t rv = exr_get_channels(ctxt, subimage, &chlist);
if (rv != EXR_ERR_SUCCESS) {
in->errorfmt("exr_get_channels failed");
return false;
}
std::vector<CChanNameHolder> cnh;
int c = 0;
for (; c < chlist->num_channels; ++c) {
const exr_attr_chlist_entry_t& chan = chlist->entries[c];
cnh.emplace_back(c, chan);
}
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(), CChanNameHolder::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<CChanNameHolder> 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, CChanNameHolder::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.
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.
}
}
OIIO_DASSERT((int)spec.channelnames.size() == spec.nchannels);
OIIO_DASSERT(spec.format != TypeDesc::UNKNOWN);
if (all_one_format)
spec.channelformats.clear();
return ok;
}