-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
hdf5dataset.cpp
1752 lines (1571 loc) · 60.6 KB
/
hdf5dataset.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
/******************************************************************************
*
* Project: Hierarchical Data Format Release 5 (HDF5)
* Purpose: HDF5 Datasets. Open HDF5 file, fetch metadata and list of
* subdatasets.
* This driver initially based on code supplied by Markus Neteler
* Author: Denis Nadeau <[email protected]>
*
******************************************************************************
* Copyright (c) 2005, Frank Warmerdam <[email protected]>
* Copyright (c) 2008-2018, Even Rouault <even.rouault at spatialys.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "cpl_port.h"
#include "hdf5_api.h"
#include "hdf5dataset.h"
#include "hdf5vfl.h"
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <string>
#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_string.h"
#include "gdal.h"
#include "gdal_frmts.h"
#include "gdal_priv.h"
constexpr size_t MAX_METADATA_LEN = 32768;
#ifdef ENABLE_HDF5_GLOBAL_LOCK
/************************************************************************/
/* GetHDF5GlobalMutex() */
/************************************************************************/
std::recursive_mutex &GetHDF5GlobalMutex()
{
static std::recursive_mutex oMutex;
return oMutex;
}
#endif
/************************************************************************/
/* HDF5GetFileDriver() */
/************************************************************************/
hid_t HDF5GetFileDriver()
{
return HDF5VFLGetFileDriver();
}
/************************************************************************/
/* HDF5UnloadFileDriver() */
/************************************************************************/
void HDF5UnloadFileDriver()
{
HDF5VFLUnloadFileDriver();
}
/************************************************************************/
/* HDF5DatasetDriverUnload() */
/************************************************************************/
static void HDF5DatasetDriverUnload(GDALDriver *)
{
HDF5UnloadFileDriver();
}
/************************************************************************/
/* ==================================================================== */
/* HDF5Dataset */
/* ==================================================================== */
/************************************************************************/
/************************************************************************/
/* GDALRegister_HDF5() */
/************************************************************************/
void GDALRegister_HDF5()
{
if (GDALGetDriverByName("HDF5") != nullptr)
return;
GDALDriver *poDriver = new GDALDriver();
poDriver->SetDescription("HDF5");
poDriver->SetMetadataItem(GDAL_DCAP_RASTER, "YES");
poDriver->SetMetadataItem(GDAL_DMD_LONGNAME,
"Hierarchical Data Format Release 5");
poDriver->SetMetadataItem(GDAL_DMD_HELPTOPIC, "drivers/raster/hdf5.html");
poDriver->SetMetadataItem(GDAL_DMD_EXTENSIONS, "h5 hdf5");
poDriver->SetMetadataItem(GDAL_DMD_SUBDATASETS, "YES");
poDriver->SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");
poDriver->SetMetadataItem(GDAL_DCAP_MULTIDIM_RASTER, "YES");
poDriver->pfnOpen = HDF5Dataset::Open;
poDriver->pfnIdentify = HDF5Dataset::Identify;
poDriver->pfnUnloadDriver = HDF5DatasetDriverUnload;
GetGDALDriverManager()->RegisterDriver(poDriver);
#ifdef HDF5_PLUGIN
GDALRegister_HDF5Image();
GDALRegister_BAG();
#endif
}
/************************************************************************/
/* HDF5Dataset() */
/************************************************************************/
HDF5Dataset::HDF5Dataset()
: hGroupID(-1), papszSubDatasets(nullptr), nDatasetType(-1),
nSubDataCount(0), poH5RootGroup(nullptr)
{
}
/************************************************************************/
/* ~HDF5Dataset() */
/************************************************************************/
HDF5Dataset::~HDF5Dataset()
{
HDF5_GLOBAL_LOCK();
if (hGroupID > 0)
H5Gclose(hGroupID);
if (m_hHDF5 > 0)
H5Fclose(m_hHDF5);
CSLDestroy(papszSubDatasets);
if (poH5RootGroup != nullptr)
{
DestroyH5Objects(poH5RootGroup);
CPLFree(poH5RootGroup->pszName);
CPLFree(poH5RootGroup->pszPath);
CPLFree(poH5RootGroup->pszUnderscorePath);
CPLFree(poH5RootGroup->poHchild);
CPLFree(poH5RootGroup);
}
}
/************************************************************************/
/* GetDataType() */
/* */
/* Transform HDF5 datatype to GDAL datatype */
/************************************************************************/
GDALDataType HDF5Dataset::GetDataType(hid_t TypeID)
{
// Check for native types first
if (H5Tget_class(TypeID) != H5T_COMPOUND)
{
if (H5Tequal(H5T_NATIVE_SCHAR, TypeID))
return GDT_Int8;
else if (H5Tequal(H5T_NATIVE_CHAR, TypeID) ||
H5Tequal(H5T_NATIVE_UCHAR, TypeID))
return GDT_Byte;
else if (H5Tequal(H5T_NATIVE_SHORT, TypeID))
return GDT_Int16;
else if (H5Tequal(H5T_NATIVE_USHORT, TypeID))
return GDT_UInt16;
else if (H5Tequal(H5T_NATIVE_INT, TypeID))
return GDT_Int32;
else if (H5Tequal(H5T_NATIVE_UINT, TypeID))
return GDT_UInt32;
else if (H5Tequal(H5T_NATIVE_INT64, TypeID))
return GDT_Int64;
else if (H5Tequal(H5T_NATIVE_UINT64, TypeID))
return GDT_UInt64;
else if (H5Tequal(H5T_NATIVE_LONG, TypeID))
{
#if SIZEOF_UNSIGNED_LONG == 4
return GDT_Int32;
#else
return GDT_Unknown;
#endif
}
else if (H5Tequal(H5T_NATIVE_ULONG, TypeID))
{
#if SIZEOF_UNSIGNED_LONG == 4
return GDT_UInt32;
#else
return GDT_Unknown;
#endif
}
else if (H5Tequal(H5T_NATIVE_FLOAT, TypeID))
return GDT_Float32;
else if (H5Tequal(H5T_NATIVE_DOUBLE, TypeID))
return GDT_Float64;
else if (H5Tequal(H5T_NATIVE_LLONG, TypeID))
return GDT_Unknown;
else if (H5Tequal(H5T_NATIVE_ULLONG, TypeID))
return GDT_Unknown;
}
else // Parse compound type to determine if data is complex
{
// For complex the compound type must contain 2 elements
if (H5Tget_nmembers(TypeID) != 2)
return GDT_Unknown;
// For complex the native types of both elements should be the same
hid_t ElemTypeID = H5Tget_member_type(TypeID, 0);
hid_t Elem2TypeID = H5Tget_member_type(TypeID, 1);
const bool bTypeEqual = H5Tequal(ElemTypeID, Elem2TypeID) > 0;
H5Tclose(Elem2TypeID);
if (!bTypeEqual)
{
H5Tclose(ElemTypeID);
return GDT_Unknown;
}
char *pszName1 = H5Tget_member_name(TypeID, 0);
const bool bIsReal =
pszName1 && (pszName1[0] == 'r' || pszName1[0] == 'R');
H5free_memory(pszName1);
char *pszName2 = H5Tget_member_name(TypeID, 1);
const bool bIsImaginary =
pszName2 && (pszName2[0] == 'i' || pszName2[0] == 'I');
H5free_memory(pszName2);
if (!bIsReal || !bIsImaginary)
{
H5Tclose(ElemTypeID);
return GDT_Unknown;
}
// Check the native types to determine CInt16, CFloat32 or CFloat64
GDALDataType eDataType = GDT_Unknown;
if (H5Tequal(H5T_NATIVE_SHORT, ElemTypeID))
eDataType = GDT_CInt16;
else if (H5Tequal(H5T_NATIVE_INT, ElemTypeID))
eDataType = GDT_CInt32;
else if (H5Tequal(H5T_NATIVE_LONG, ElemTypeID))
{
#if SIZEOF_UNSIGNED_LONG == 4
eDataType = GDT_CInt32;
#else
eDataType = GDT_Unknown;
#endif
}
else if (H5Tequal(H5T_NATIVE_FLOAT, ElemTypeID))
eDataType = GDT_CFloat32;
else if (H5Tequal(H5T_NATIVE_DOUBLE, ElemTypeID))
eDataType = GDT_CFloat64;
// Close the data type
H5Tclose(ElemTypeID);
return eDataType;
}
return GDT_Unknown;
}
/************************************************************************/
/* GetDataTypeName() */
/* */
/* Return the human readable name of data type */
/************************************************************************/
const char *HDF5Dataset::GetDataTypeName(hid_t TypeID)
{
// Check for native types first
if (H5Tget_class(TypeID) != H5T_COMPOUND)
{
if (H5Tequal(H5T_NATIVE_CHAR, TypeID))
return "8-bit character";
else if (H5Tequal(H5T_NATIVE_SCHAR, TypeID))
return "8-bit signed character";
else if (H5Tequal(H5T_NATIVE_UCHAR, TypeID))
return "8-bit unsigned character";
else if (H5Tequal(H5T_NATIVE_SHORT, TypeID))
return "16-bit integer";
else if (H5Tequal(H5T_NATIVE_USHORT, TypeID))
return "16-bit unsigned integer";
else if (H5Tequal(H5T_NATIVE_INT, TypeID))
return "32-bit integer";
else if (H5Tequal(H5T_NATIVE_UINT, TypeID))
return "32-bit unsigned integer";
else if (H5Tequal(H5T_NATIVE_INT64, TypeID))
return "64-bit integer";
else if (H5Tequal(H5T_NATIVE_UINT64, TypeID))
return "64-bit unsigned integer";
else if (H5Tequal(H5T_NATIVE_LONG, TypeID))
return "32/64-bit integer";
else if (H5Tequal(H5T_NATIVE_ULONG, TypeID))
return "32/64-bit unsigned integer";
else if (H5Tequal(H5T_NATIVE_FLOAT, TypeID))
return "32-bit floating-point";
else if (H5Tequal(H5T_NATIVE_DOUBLE, TypeID))
return "64-bit floating-point";
else if (H5Tequal(H5T_NATIVE_LLONG, TypeID))
return "64-bit integer";
else if (H5Tequal(H5T_NATIVE_ULLONG, TypeID))
return "64-bit unsigned integer";
else if (H5Tequal(H5T_NATIVE_DOUBLE, TypeID))
return "64-bit floating-point";
}
else
{
// For complex the compound type must contain 2 elements
if (H5Tget_nmembers(TypeID) != 2)
return "Unknown";
// For complex the native types of both elements should be the same
hid_t ElemTypeID = H5Tget_member_type(TypeID, 0);
hid_t Elem2TypeID = H5Tget_member_type(TypeID, 1);
const bool bTypeEqual = H5Tequal(ElemTypeID, Elem2TypeID) > 0;
H5Tclose(Elem2TypeID);
if (!bTypeEqual)
{
H5Tclose(ElemTypeID);
return "Unknown";
}
// Check the native types to determine CInt16, CFloat32 or CFloat64
if (H5Tequal(H5T_NATIVE_SHORT, ElemTypeID))
{
H5Tclose(ElemTypeID);
return "complex, 16-bit integer";
}
else if (H5Tequal(H5T_NATIVE_INT, ElemTypeID))
{
H5Tclose(ElemTypeID);
return "complex, 32-bit integer";
}
else if (H5Tequal(H5T_NATIVE_LONG, ElemTypeID))
{
H5Tclose(ElemTypeID);
return "complex, 32/64-bit integer";
}
else if (H5Tequal(H5T_NATIVE_FLOAT, ElemTypeID))
{
H5Tclose(ElemTypeID);
return "complex, 32-bit floating-point";
}
else if (H5Tequal(H5T_NATIVE_DOUBLE, ElemTypeID))
{
H5Tclose(ElemTypeID);
return "complex, 64-bit floating-point";
}
}
return "Unknown";
}
/************************************************************************/
/* Identify() */
/************************************************************************/
int HDF5Dataset::Identify(GDALOpenInfo *poOpenInfo)
{
if ((poOpenInfo->nOpenFlags & GDAL_OF_MULTIDIM_RASTER) &&
STARTS_WITH(poOpenInfo->pszFilename, "HDF5:"))
{
return TRUE;
}
// Is it an HDF5 file?
constexpr char achSignature[] = "\211HDF\r\n\032\n";
if (!poOpenInfo->pabyHeader)
return FALSE;
const CPLString osExt(CPLGetExtension(poOpenInfo->pszFilename));
const auto IsRecognizedByNetCDFDriver = [&osExt, poOpenInfo]()
{
if ((EQUAL(osExt, "NC") || EQUAL(osExt, "CDF") || EQUAL(osExt, "NC4") ||
EQUAL(osExt, "gmac")) &&
GDALGetDriverByName("netCDF") != nullptr)
{
const char *const apszAllowedDriver[] = {"netCDF", nullptr};
CPLPushErrorHandler(CPLQuietErrorHandler);
GDALDatasetH hDS = GDALOpenEx(
poOpenInfo->pszFilename,
GDAL_OF_RASTER | GDAL_OF_MULTIDIM_RASTER | GDAL_OF_VECTOR,
apszAllowedDriver, nullptr, nullptr);
CPLPopErrorHandler();
if (hDS)
{
GDALClose(hDS);
return true;
}
}
return false;
};
if (memcmp(poOpenInfo->pabyHeader, achSignature, 8) == 0 ||
(poOpenInfo->nHeaderBytes > 512 + 8 &&
memcmp(poOpenInfo->pabyHeader + 512, achSignature, 8) == 0))
{
// The tests to avoid opening KEA and BAG drivers are not
// necessary when drivers are built in the core lib, as they
// are registered after HDF5, but in the case of plugins, we
// cannot do assumptions about the registration order.
// Avoid opening kea files if the kea driver is available.
if (EQUAL(osExt, "KEA") && GDALGetDriverByName("KEA") != nullptr)
{
return FALSE;
}
// Avoid opening BAG files if the bag driver is available.
if (EQUAL(osExt, "BAG") && GDALGetDriverByName("BAG") != nullptr)
{
return FALSE;
}
// Avoid opening NC files if the netCDF driver is available and
// they are recognized by it.
if (IsRecognizedByNetCDFDriver())
{
return FALSE;
}
return TRUE;
}
if (memcmp(poOpenInfo->pabyHeader, "<HDF_UserBlock>", 15) == 0)
{
if (H5Fis_hdf5(poOpenInfo->pszFilename))
return TRUE;
}
// The HDF5 signature can be at offsets 512, 1024, 2048, etc.
if (poOpenInfo->fpL != nullptr &&
(EQUAL(osExt, "h5") || EQUAL(osExt, "hdf5") || EQUAL(osExt, "nc") ||
EQUAL(osExt, "cdf") || EQUAL(osExt, "nc4")))
{
vsi_l_offset nOffset = 512;
for (int i = 0; i < 64; i++)
{
GByte abyBuf[8];
if (VSIFSeekL(poOpenInfo->fpL, nOffset, SEEK_SET) != 0 ||
VSIFReadL(abyBuf, 1, 8, poOpenInfo->fpL) != 8)
{
break;
}
if (memcmp(abyBuf, achSignature, 8) == 0)
{
// Avoid opening NC files if the netCDF driver is available and
// they are recognized by it.
if (IsRecognizedByNetCDFDriver())
{
return FALSE;
}
return TRUE;
}
nOffset *= 2;
}
}
return FALSE;
}
/************************************************************************/
/* GDAL_HDF5Open() */
/************************************************************************/
hid_t GDAL_HDF5Open(const std::string &osFilename)
{
hid_t hHDF5;
// Heuristics to able datasets split over several files, using the 'family'
// driver. If passed the first file, and it contains a single 0, or
// ends up with 0.h5 or 0.hdf5, replace the 0 with %d and try the family
// driver.
if (std::count(osFilename.begin(), osFilename.end(), '0') == 1 ||
osFilename.find("0.h5") != std::string::npos ||
osFilename.find("0.hdf5") != std::string::npos)
{
const auto zero_pos = osFilename.rfind('0');
const auto osNewName = osFilename.substr(0, zero_pos) + "%d" +
osFilename.substr(zero_pos + 1);
hid_t fapl = H5Pcreate(H5P_FILE_ACCESS);
H5Pset_fapl_family(fapl, H5F_FAMILY_DEFAULT, H5P_DEFAULT);
#ifdef HAVE_GCC_WARNING_ZERO_AS_NULL_POINTER_CONSTANT
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
#endif
H5E_BEGIN_TRY
{
hHDF5 = H5Fopen(osNewName.c_str(), H5F_ACC_RDONLY, fapl);
}
H5E_END_TRY;
#ifdef HAVE_GCC_WARNING_ZERO_AS_NULL_POINTER_CONSTANT
#pragma GCC diagnostic pop
#endif
H5Pclose(fapl);
if (hHDF5 >= 0)
{
CPLDebug("HDF5", "Actually opening %s with 'family' driver",
osNewName.c_str());
return hHDF5;
}
}
hid_t fapl = H5Pcreate(H5P_FILE_ACCESS);
H5Pset_driver(fapl, HDF5GetFileDriver(), nullptr);
hHDF5 = H5Fopen(osFilename.c_str(), H5F_ACC_RDONLY, fapl);
H5Pclose(fapl);
return hHDF5;
}
/************************************************************************/
/* Open() */
/************************************************************************/
GDALDataset *HDF5Dataset::Open(GDALOpenInfo *poOpenInfo)
{
if (!Identify(poOpenInfo))
return nullptr;
HDF5_GLOBAL_LOCK();
if (poOpenInfo->nOpenFlags & GDAL_OF_MULTIDIM_RASTER)
{
return OpenMultiDim(poOpenInfo);
}
// Create datasource.
HDF5Dataset *const poDS = new HDF5Dataset();
poDS->SetDescription(poOpenInfo->pszFilename);
// Try opening the dataset.
poDS->m_hHDF5 = GDAL_HDF5Open(poOpenInfo->pszFilename);
if (poDS->m_hHDF5 < 0)
{
delete poDS;
return nullptr;
}
poDS->hGroupID = H5Gopen(poDS->m_hHDF5, "/");
if (poDS->hGroupID < 0)
{
delete poDS;
return nullptr;
}
if (HDF5EOSParser::HasHDFEOS(poDS->hGroupID))
{
if (poDS->m_oHDFEOSParser.Parse(poDS->hGroupID))
{
CPLDebug("HDF5", "Successfully parsed HDFEOS metadata");
}
}
poDS->ReadGlobalAttributes(true);
poDS->SetMetadata(poDS->m_aosMetadata.List());
if (STARTS_WITH(poDS->m_aosMetadata.FetchNameValueDef("mission_name", ""),
"Sentinel 3") &&
EQUAL(
poDS->m_aosMetadata.FetchNameValueDef("altimeter_sensor_name", ""),
"SRAL") &&
EQUAL(
poDS->m_aosMetadata.FetchNameValueDef("radiometer_sensor_name", ""),
"MWR") &&
GDALGetDriverByName("netCDF") != nullptr)
{
delete poDS;
return nullptr;
}
if (CSLCount(poDS->papszSubDatasets) / 2 >= 1)
poDS->SetMetadata(poDS->papszSubDatasets, "SUBDATASETS");
// Make sure we don't try to do any pam stuff with this dataset.
poDS->nPamFlags |= GPF_NOSAVE;
// If we have single subdataset only, open it immediately.
int nSubDatasets = CSLCount(poDS->papszSubDatasets) / 2;
if (nSubDatasets == 1)
{
CPLString osDSName =
CSLFetchNameValue(poDS->papszSubDatasets, "SUBDATASET_1_NAME");
delete poDS;
return GDALDataset::Open(osDSName, poOpenInfo->nOpenFlags, nullptr,
poOpenInfo->papszOpenOptions, nullptr);
}
else
{
// Confirm the requested access is supported.
if (poOpenInfo->eAccess == GA_Update)
{
delete poDS;
CPLError(CE_Failure, CPLE_NotSupported,
"The HDF5 driver does not support update access to "
"existing datasets.");
return nullptr;
}
}
return poDS;
}
/************************************************************************/
/* DestroyH5Objects() */
/* */
/* Erase all objects */
/************************************************************************/
void HDF5Dataset::DestroyH5Objects(HDF5GroupObjects *poH5Object)
{
// Visit all objects.
for (unsigned i = 0; i < poH5Object->nbObjs; i++)
DestroyH5Objects(poH5Object->poHchild + i);
if (poH5Object->poHparent == nullptr)
return;
// Erase some data.
CPLFree(poH5Object->paDims);
poH5Object->paDims = nullptr;
CPLFree(poH5Object->pszPath);
poH5Object->pszPath = nullptr;
CPLFree(poH5Object->pszName);
poH5Object->pszName = nullptr;
CPLFree(poH5Object->pszUnderscorePath);
poH5Object->pszUnderscorePath = nullptr;
if (poH5Object->native > 0)
H5Tclose(poH5Object->native);
poH5Object->native = 0;
// All Children are visited and can be deleted.
if (poH5Object->nbObjs != 0)
{
CPLFree(poH5Object->poHchild);
poH5Object->poHchild = nullptr;
}
}
/************************************************************************/
/* CreatePath() */
/* */
/* Find Dataset path for HDopen */
/************************************************************************/
static void CreatePath(HDF5GroupObjects *poH5Object)
{
// Recurse to the root path.
CPLString osPath;
if (poH5Object->poHparent != nullptr)
{
CreatePath(poH5Object->poHparent);
osPath = poH5Object->poHparent->pszPath;
}
// Add name to the path.
if (!EQUAL(poH5Object->pszName, "/"))
{
osPath.append("/");
osPath.append(poH5Object->pszName);
}
// Fill up path for each object.
CPLString osUnderscoreSpaceInName;
if (poH5Object->pszPath == nullptr)
{
// This is completely useless but needed if we want to keep
// subdataset names as they have "always" been formatted,
// with double slash at the beginning
if (osPath.empty())
osPath = "/";
// Change space for underscore.
char **papszPath =
CSLTokenizeString2(osPath.c_str(), " ", CSLT_HONOURSTRINGS);
for (int i = 0; papszPath[i] != nullptr; i++)
{
if (i > 0)
osUnderscoreSpaceInName.append("_");
osUnderscoreSpaceInName.append(papszPath[i]);
}
CSLDestroy(papszPath);
// -1 to give room for NUL in C strings.
constexpr size_t MAX_PATH = 8192 - 1;
// TODO(schwehr): Is it an issue if the results are longer than 8192?
// It appears that the output can never be longer than the source.
if (osUnderscoreSpaceInName.size() > MAX_PATH)
CPLError(CE_Fatal, CPLE_AppDefined,
"osUnderscoreSpaceInName longer than MAX_PATH: "
"%u > %u",
static_cast<unsigned int>(osUnderscoreSpaceInName.size()),
static_cast<unsigned int>(MAX_PATH));
if (osPath.size() > MAX_PATH)
CPLError(CE_Fatal, CPLE_AppDefined,
"osPath longer than MAX_PATH: %u > %u",
static_cast<unsigned int>(osPath.size()),
static_cast<unsigned int>(MAX_PATH));
poH5Object->pszUnderscorePath =
CPLStrdup(osUnderscoreSpaceInName.c_str());
poH5Object->pszPath = CPLStrdup(osPath.c_str());
}
}
/************************************************************************/
/* HDF5GroupCheckDuplicate() */
/* */
/* Returns TRUE if an ancestor has the same objno[] as passed */
/* in - used to avoid looping in files with "links up" #(3218). */
/************************************************************************/
static int HDF5GroupCheckDuplicate(HDF5GroupObjects *poHparent,
unsigned long *objno)
{
while (poHparent != nullptr)
{
if (poHparent->objno[0] == objno[0] && poHparent->objno[1] == objno[1])
return TRUE;
poHparent = poHparent->poHparent;
}
return FALSE;
}
/************************************************************************/
/* HDF5CreateGroupObjs() */
/* */
/* Create HDF5 hierarchy into a linked list */
/************************************************************************/
herr_t HDF5CreateGroupObjs(hid_t hHDF5, const char *pszObjName,
void *poHObjParent)
{
HDF5GroupObjects *const poHparent =
static_cast<HDF5GroupObjects *>(poHObjParent);
HDF5GroupObjects *poHchild = poHparent->poHchild;
H5G_stat_t oStatbuf;
if (H5Gget_objinfo(hHDF5, pszObjName, FALSE, &oStatbuf) < 0)
return -1;
// Look for next child.
unsigned idx = 0; // idx is used after the for loop.
for (; idx < poHparent->nbObjs; idx++)
{
if (poHchild->pszName == nullptr)
break;
poHchild++;
}
if (idx == poHparent->nbObjs)
return -1; // All children parsed.
// Save child information.
poHchild->pszName = CPLStrdup(pszObjName);
poHchild->nType = oStatbuf.type;
poHchild->nIndex = idx;
poHchild->poHparent = poHparent;
poHchild->nRank = 0;
poHchild->paDims = nullptr;
poHchild->HDatatype = 0;
poHchild->objno[0] = oStatbuf.objno[0];
poHchild->objno[1] = oStatbuf.objno[1];
if (poHchild->pszPath == nullptr)
{
CreatePath(poHchild);
}
if (poHparent->pszPath == nullptr)
{
CreatePath(poHparent);
}
switch (oStatbuf.type)
{
case H5G_LINK:
{
poHchild->nbAttrs = 0;
poHchild->nbObjs = 0;
poHchild->poHchild = nullptr;
poHchild->nRank = 0;
poHchild->paDims = nullptr;
poHchild->HDatatype = 0;
break;
}
case H5G_GROUP:
{
hid_t hGroupID = H5I_INVALID_HID; // Identifier of group.
if ((hGroupID = H5Gopen(hHDF5, pszObjName)) == -1)
{
CPLError(CE_Failure, CPLE_AppDefined,
"unable to access \"%s\" group.", pszObjName);
return -1;
}
// Number of attributes in object.
const int nbAttrs = H5Aget_num_attrs(hGroupID);
hsize_t nbObjs = 0; // Number of objects in a group.
H5Gget_num_objs(hGroupID, &nbObjs);
poHchild->nbAttrs = nbAttrs;
poHchild->nbObjs = static_cast<int>(nbObjs);
poHchild->nRank = 0;
poHchild->paDims = nullptr;
poHchild->HDatatype = 0;
if (nbObjs > 0)
{
poHchild->poHchild = static_cast<HDF5GroupObjects *>(CPLCalloc(
static_cast<int>(nbObjs), sizeof(HDF5GroupObjects)));
memset(poHchild->poHchild, 0,
static_cast<size_t>(sizeof(HDF5GroupObjects) * nbObjs));
}
else
{
poHchild->poHchild = nullptr;
}
if (!HDF5GroupCheckDuplicate(poHparent, oStatbuf.objno))
H5Giterate(hHDF5, pszObjName, nullptr, HDF5CreateGroupObjs,
poHchild);
else
CPLDebug("HDF5", "avoiding link looping on node '%s'.",
pszObjName);
H5Gclose(hGroupID);
break;
}
case H5G_DATASET:
{
hid_t hDatasetID = H5I_INVALID_HID; // Identifier of dataset.
if ((hDatasetID = H5Dopen(hHDF5, pszObjName)) == -1)
{
CPLError(CE_Failure, CPLE_AppDefined,
"unable to access \"%s\" dataset.", pszObjName);
return -1;
}
const int nbAttrs = H5Aget_num_attrs(hDatasetID);
const hid_t datatype = H5Dget_type(hDatasetID);
const hid_t dataspace = H5Dget_space(hDatasetID);
const int n_dims = H5Sget_simple_extent_ndims(dataspace);
const hid_t native = H5Tget_native_type(datatype, H5T_DIR_ASCEND);
hsize_t *maxdims = nullptr;
hsize_t *dims = nullptr;
if (n_dims > 0)
{
dims =
static_cast<hsize_t *>(CPLCalloc(n_dims, sizeof(hsize_t)));
maxdims =
static_cast<hsize_t *>(CPLCalloc(n_dims, sizeof(hsize_t)));
}
H5Sget_simple_extent_dims(dataspace, dims, maxdims);
if (maxdims != nullptr)
CPLFree(maxdims);
if (n_dims > 0)
{
poHchild->nRank = n_dims; // rank of the array
poHchild->paDims = dims; // dimension of the array.
poHchild->HDatatype = datatype; // HDF5 datatype
}
else
{
poHchild->nRank = -1;
poHchild->paDims = nullptr;
poHchild->HDatatype = 0;
}
poHchild->nbAttrs = nbAttrs;
poHchild->nbObjs = 0;
poHchild->poHchild = nullptr;
poHchild->native = native;
H5Tclose(datatype);
H5Sclose(dataspace);
H5Dclose(hDatasetID);
break;
}
case H5G_TYPE:
{
poHchild->nbAttrs = 0;
poHchild->nbObjs = 0;
poHchild->poHchild = nullptr;
poHchild->nRank = 0;
poHchild->paDims = nullptr;
poHchild->HDatatype = 0;
break;
}
default:
break;
}
return 0;
}
/************************************************************************/
/* HDF5DatasetCreateMetadataContext */
/************************************************************************/
struct HDF5DatasetCreateMetadataContext
{
std::string m_osKey{};
CPLStringList &m_aosMetadata;
// Work variables
std::string m_osValue{};
explicit HDF5DatasetCreateMetadataContext(CPLStringList &aosMetadata)
: m_aosMetadata(aosMetadata)
{
}
};
/************************************************************************/
/* HDF5AttrIterate() */
/************************************************************************/
static herr_t HDF5AttrIterate(hid_t hH5ObjID, const char *pszAttrName,
void *pContext)
{
HDF5DatasetCreateMetadataContext *const psContext =
static_cast<HDF5DatasetCreateMetadataContext *>(pContext);
psContext->m_osValue.clear();
std::string osKey(psContext->m_osKey);
// Convert whitespaces into "_" for the attribute name component
const CPLStringList aosTokens(CSLTokenizeString2(
pszAttrName, " ", CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES));
for (int i = 0; i < aosTokens.size(); ++i)
{
if (!osKey.empty())
osKey += '_';
osKey += aosTokens[i];
}
const hid_t hAttrID = H5Aopen_name(hH5ObjID, pszAttrName);
const hid_t hAttrTypeID = H5Aget_type(hAttrID);
const hid_t hAttrNativeType =
H5Tget_native_type(hAttrTypeID, H5T_DIR_DEFAULT);
const hid_t hAttrSpace = H5Aget_space(hAttrID);
if (H5Tget_class(hAttrNativeType) == H5T_VLEN)
{
H5Sclose(hAttrSpace);
H5Tclose(hAttrNativeType);
H5Tclose(hAttrTypeID);
H5Aclose(hAttrID);
return 0;
}
hsize_t nSize[64] = {};
const unsigned int nAttrDims =
H5Sget_simple_extent_dims(hAttrSpace, nSize, nullptr);
unsigned int nAttrElmts = 1;
for (hsize_t i = 0; i < nAttrDims; i++)
{
nAttrElmts *= static_cast<int>(nSize[i]);
}
if (H5Tget_class(hAttrNativeType) == H5T_STRING)
{
if (H5Tis_variable_str(hAttrNativeType))
{
char **papszStrings =
static_cast<char **>(CPLMalloc(nAttrElmts * sizeof(char *)));
// Read the values.
H5Aread(hAttrID, hAttrNativeType, papszStrings);
// Concatenate all values as one string separated by a space.
psContext->m_osValue = papszStrings[0] ? papszStrings[0] : "{NULL}";
for (hsize_t i = 1; i < nAttrElmts; i++)
{
psContext->m_osValue += " ";
psContext->m_osValue +=
papszStrings[i] ? papszStrings[i] : "{NULL}";
}