Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: Hierarchical Data Format Release 5 (HDF5)
4 : * Purpose: Read subdatasets of HDF5 file.
5 : * Author: Denis Nadeau <denis.nadeau@gmail.com>
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 2005, Frank Warmerdam <warmerdam@pobox.com>
9 : * Copyright (c) 2007-2013, Even Rouault <even dot rouault at spatialys.com>
10 : *
11 : * SPDX-License-Identifier: MIT
12 : ****************************************************************************/
13 :
14 : #include "hdf5_api.h"
15 :
16 : #include "cpl_float.h"
17 : #include "cpl_string.h"
18 : #include "gdal_frmts.h"
19 : #include "gdal_pam.h"
20 : #include "gdal_priv.h"
21 : #include "gh5_convenience.h"
22 : #include "hdf5dataset.h"
23 : #include "hdf5drivercore.h"
24 : #include "ogr_spatialref.h"
25 : #include "memdataset.h"
26 :
27 : #include <algorithm>
28 : #include <limits>
29 :
30 : class HDF5ImageDataset final : public HDF5Dataset
31 : {
32 : typedef enum
33 : {
34 : UNKNOWN_PRODUCT = 0,
35 : CSK_PRODUCT
36 : } Hdf5ProductType;
37 :
38 : typedef enum
39 : {
40 : PROD_UNKNOWN = 0,
41 : PROD_CSK_L0,
42 : PROD_CSK_L1A,
43 : PROD_CSK_L1B,
44 : PROD_CSK_L1C,
45 : PROD_CSK_L1D
46 : } HDF5CSKProductEnum;
47 :
48 : friend class HDF5ImageRasterBand;
49 :
50 : OGRSpatialReference m_oSRS{};
51 : OGRSpatialReference m_oGCPSRS{};
52 : std::vector<gdal::GCP> m_aoGCPs{};
53 :
54 : hsize_t *dims;
55 : hsize_t *maxdims;
56 : HDF5GroupObjects *poH5Objects;
57 : int ndims;
58 : int dimensions;
59 : hid_t dataset_id;
60 : hid_t dataspace_id;
61 : hid_t native;
62 : #ifdef HDF5_HAVE_FLOAT16
63 : bool m_bConvertFromFloat16 = false;
64 : #endif
65 : Hdf5ProductType iSubdatasetType;
66 : HDF5CSKProductEnum iCSKProductType;
67 : double adfGeoTransform[6];
68 : bool bHasGeoTransform;
69 : int m_nXIndex = -1;
70 : int m_nYIndex = -1;
71 : int m_nOtherDimIndex = -1;
72 :
73 : int m_nBlockXSize = 0;
74 : int m_nBlockYSize = 0;
75 : int m_nBandChunkSize = 1; //! Number of bands in a chunk
76 :
77 : enum WholeBandChunkOptim
78 : {
79 : WBC_DETECTION_IN_PROGRESS,
80 : WBC_DISABLED,
81 : WBC_ENABLED,
82 : };
83 :
84 : //! Flag to detect if the read pattern of HDF5ImageRasterBand::IRasterIO()
85 : // is whole band after whole band.
86 : WholeBandChunkOptim m_eWholeBandChunkOptim = WBC_DETECTION_IN_PROGRESS;
87 : //! Value of nBand during last HDF5ImageRasterBand::IRasterIO() call
88 : int m_nLastRasterIOBand = -1;
89 : //! Value of nXOff during last HDF5ImageRasterBand::IRasterIO() call
90 : int m_nLastRasterIOXOff = -1;
91 : //! Value of nYOff during last HDF5ImageRasterBand::IRasterIO() call
92 : int m_nLastRasterIOYOff = -1;
93 : //! Value of nXSize during last HDF5ImageRasterBand::IRasterIO() call
94 : int m_nLastRasterIOXSize = -1;
95 : //! Value of nYSize during last HDF5ImageRasterBand::IRasterIO() call
96 : int m_nLastRasterIOYSize = -1;
97 : //! Value such that m_abyBandChunk represent band data in the range
98 : // [m_iCurrentBandChunk * m_nBandChunkSize, (m_iCurrentBandChunk+1) * m_nBandChunkSize[
99 : int m_iCurrentBandChunk = -1;
100 : //! Cached values (in native data type) for bands in the range
101 : // [m_iCurrentBandChunk * m_nBandChunkSize, (m_iCurrentBandChunk+1) * m_nBandChunkSize[
102 : std::vector<GByte> m_abyBandChunk{};
103 :
104 : CPLErr CreateODIMH5Projection();
105 :
106 : public:
107 : HDF5ImageDataset();
108 : virtual ~HDF5ImageDataset();
109 :
110 : CPLErr CreateProjections();
111 : static GDALDataset *Open(GDALOpenInfo *);
112 : static int Identify(GDALOpenInfo *);
113 :
114 : const OGRSpatialReference *GetSpatialRef() const override;
115 : virtual int GetGCPCount() override;
116 : const OGRSpatialReference *GetGCPSpatialRef() const override;
117 : virtual const GDAL_GCP *GetGCPs() override;
118 : virtual CPLErr GetGeoTransform(double *padfTransform) override;
119 :
120 : CPLErr IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize,
121 : int nYSize, void *pData, int nBufXSize, int nBufYSize,
122 : GDALDataType eBufType, int nBandCount,
123 : BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
124 : GSpacing nLineSpace, GSpacing nBandSpace,
125 : GDALRasterIOExtraArg *psExtraArg) override;
126 :
127 : const char *GetMetadataItem(const char *pszName,
128 : const char *pszDomain = "") override;
129 :
130 171 : Hdf5ProductType GetSubdatasetType() const
131 : {
132 171 : return iSubdatasetType;
133 : }
134 :
135 6 : HDF5CSKProductEnum GetCSKProductType() const
136 : {
137 6 : return iCSKProductType;
138 : }
139 :
140 171 : int IsComplexCSKL1A() const
141 : {
142 177 : return GetSubdatasetType() == CSK_PRODUCT &&
143 177 : GetCSKProductType() == PROD_CSK_L1A && ndims == 3;
144 : }
145 :
146 640 : int GetYIndex() const
147 : {
148 640 : return m_nYIndex;
149 : }
150 :
151 776 : int GetXIndex() const
152 : {
153 776 : return m_nXIndex;
154 : }
155 :
156 : /**
157 : * Identify if the subdataset has a known product format
158 : * It stores a product identifier in iSubdatasetType,
159 : * UNKNOWN_PRODUCT, if it isn't a recognizable format.
160 : */
161 : void IdentifyProductType();
162 :
163 : /**
164 : * Captures Geolocation information from a COSMO-SKYMED
165 : * file.
166 : * The geoid will always be WGS84
167 : * The projection type may be UTM or UPS, depending on the
168 : * latitude from the center of the image.
169 : * @param iProductType type of HDF5 subproduct, see HDF5CSKProduct
170 : */
171 : void CaptureCSKGeolocation(int iProductType);
172 :
173 : /**
174 : * Get Geotransform information for COSMO-SKYMED files
175 : * In case of success it stores the transformation
176 : * in adfGeoTransform. In case of failure it doesn't
177 : * modify adfGeoTransform
178 : * @param iProductType type of HDF5 subproduct, see HDF5CSKProduct
179 : */
180 : void CaptureCSKGeoTransform(int iProductType);
181 :
182 : /**
183 : * @param iProductType type of HDF5 subproduct, see HDF5CSKProduct
184 : */
185 : void CaptureCSKGCPs(int iProductType);
186 : };
187 :
188 : /************************************************************************/
189 : /* ==================================================================== */
190 : /* HDF5ImageDataset */
191 : /* ==================================================================== */
192 : /************************************************************************/
193 :
194 : /************************************************************************/
195 : /* HDF5ImageDataset() */
196 : /************************************************************************/
197 58 : HDF5ImageDataset::HDF5ImageDataset()
198 : : dims(nullptr), maxdims(nullptr), poH5Objects(nullptr), ndims(0),
199 : dimensions(0), dataset_id(-1), dataspace_id(-1), native(-1),
200 : iSubdatasetType(UNKNOWN_PRODUCT), iCSKProductType(PROD_UNKNOWN),
201 58 : bHasGeoTransform(false)
202 : {
203 58 : m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
204 58 : m_oGCPSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
205 58 : adfGeoTransform[0] = 0.0;
206 58 : adfGeoTransform[1] = 1.0;
207 58 : adfGeoTransform[2] = 0.0;
208 58 : adfGeoTransform[3] = 0.0;
209 58 : adfGeoTransform[4] = 0.0;
210 58 : adfGeoTransform[5] = 1.0;
211 58 : }
212 :
213 : /************************************************************************/
214 : /* ~HDF5ImageDataset() */
215 : /************************************************************************/
216 116 : HDF5ImageDataset::~HDF5ImageDataset()
217 : {
218 : HDF5_GLOBAL_LOCK();
219 :
220 58 : FlushCache(true);
221 :
222 58 : if (dataset_id > 0)
223 58 : H5Dclose(dataset_id);
224 58 : if (dataspace_id > 0)
225 58 : H5Sclose(dataspace_id);
226 58 : if (native > 0)
227 57 : H5Tclose(native);
228 :
229 58 : CPLFree(dims);
230 58 : CPLFree(maxdims);
231 116 : }
232 :
233 : /************************************************************************/
234 : /* ==================================================================== */
235 : /* Hdf5imagerasterband */
236 : /* ==================================================================== */
237 : /************************************************************************/
238 : class HDF5ImageRasterBand final : public GDALPamRasterBand
239 : {
240 : friend class HDF5ImageDataset;
241 :
242 : bool bNoDataSet = false;
243 : double dfNoDataValue = -9999.0;
244 : bool m_bHasOffset = false;
245 : double m_dfOffset = 0.0;
246 : bool m_bHasScale = false;
247 : double m_dfScale = 1.0;
248 : int m_nIRasterIORecCounter = 0;
249 :
250 : public:
251 : HDF5ImageRasterBand(HDF5ImageDataset *, int, GDALDataType);
252 : virtual ~HDF5ImageRasterBand();
253 :
254 : virtual CPLErr IReadBlock(int, int, void *) override;
255 : virtual double GetNoDataValue(int *) override;
256 : virtual double GetOffset(int *) override;
257 : virtual double GetScale(int *) override;
258 : // virtual CPLErr IWriteBlock( int, int, void * );
259 :
260 : CPLErr IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize,
261 : int nYSize, void *pData, int nBufXSize, int nBufYSize,
262 : GDALDataType eBufType, GSpacing nPixelSpace,
263 : GSpacing nLineSpace,
264 : GDALRasterIOExtraArg *psExtraArg) override;
265 : };
266 :
267 : /************************************************************************/
268 : /* ~HDF5ImageRasterBand() */
269 : /************************************************************************/
270 :
271 246 : HDF5ImageRasterBand::~HDF5ImageRasterBand()
272 : {
273 246 : }
274 :
275 : /************************************************************************/
276 : /* HDF5ImageRasterBand() */
277 : /************************************************************************/
278 123 : HDF5ImageRasterBand::HDF5ImageRasterBand(HDF5ImageDataset *poDSIn, int nBandIn,
279 123 : GDALDataType eType)
280 : {
281 123 : poDS = poDSIn;
282 123 : nBand = nBandIn;
283 123 : eDataType = eType;
284 123 : nBlockXSize = poDSIn->m_nBlockXSize;
285 123 : nBlockYSize = poDSIn->m_nBlockYSize;
286 :
287 : // netCDF convention for nodata
288 123 : bNoDataSet =
289 123 : GH5_FetchAttribute(poDSIn->dataset_id, "_FillValue", dfNoDataValue);
290 123 : if (!bNoDataSet)
291 114 : dfNoDataValue = -9999.0;
292 :
293 : // netCDF conventions for scale and offset
294 123 : m_bHasOffset =
295 123 : GH5_FetchAttribute(poDSIn->dataset_id, "add_offset", m_dfOffset);
296 123 : if (!m_bHasOffset)
297 122 : m_dfOffset = 0.0;
298 123 : m_bHasScale =
299 123 : GH5_FetchAttribute(poDSIn->dataset_id, "scale_factor", m_dfScale);
300 123 : if (!m_bHasScale)
301 122 : m_dfScale = 1.0;
302 123 : }
303 :
304 : /************************************************************************/
305 : /* GetNoDataValue() */
306 : /************************************************************************/
307 48 : double HDF5ImageRasterBand::GetNoDataValue(int *pbSuccess)
308 :
309 : {
310 48 : if (bNoDataSet)
311 : {
312 3 : if (pbSuccess)
313 3 : *pbSuccess = bNoDataSet;
314 :
315 3 : return dfNoDataValue;
316 : }
317 :
318 45 : return GDALPamRasterBand::GetNoDataValue(pbSuccess);
319 : }
320 :
321 : /************************************************************************/
322 : /* GetOffset() */
323 : /************************************************************************/
324 :
325 22 : double HDF5ImageRasterBand::GetOffset(int *pbSuccess)
326 :
327 : {
328 22 : if (m_bHasOffset)
329 : {
330 1 : if (pbSuccess)
331 1 : *pbSuccess = m_bHasOffset;
332 :
333 1 : return m_dfOffset;
334 : }
335 :
336 21 : return GDALPamRasterBand::GetOffset(pbSuccess);
337 : }
338 :
339 : /************************************************************************/
340 : /* GetScale() */
341 : /************************************************************************/
342 :
343 22 : double HDF5ImageRasterBand::GetScale(int *pbSuccess)
344 :
345 : {
346 22 : if (m_bHasScale)
347 : {
348 1 : if (pbSuccess)
349 1 : *pbSuccess = m_bHasScale;
350 :
351 1 : return m_dfScale;
352 : }
353 :
354 21 : return GDALPamRasterBand::GetScale(pbSuccess);
355 : }
356 :
357 : /************************************************************************/
358 : /* IReadBlock() */
359 : /************************************************************************/
360 103 : CPLErr HDF5ImageRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff,
361 : void *pImage)
362 : {
363 103 : HDF5ImageDataset *poGDS = static_cast<HDF5ImageDataset *>(poDS);
364 :
365 103 : memset(pImage, 0,
366 103 : static_cast<size_t>(nBlockXSize) * nBlockYSize *
367 103 : GDALGetDataTypeSizeBytes(eDataType));
368 :
369 103 : if (poGDS->eAccess == GA_Update)
370 : {
371 0 : return CE_None;
372 : }
373 :
374 103 : const int nXOff = nBlockXOff * nBlockXSize;
375 103 : const int nYOff = nBlockYOff * nBlockYSize;
376 103 : const int nXSize = std::min(nBlockXSize, nRasterXSize - nXOff);
377 103 : const int nYSize = std::min(nBlockYSize, nRasterYSize - nYOff);
378 103 : if (poGDS->m_eWholeBandChunkOptim == HDF5ImageDataset::WBC_ENABLED)
379 : {
380 : const bool bIsBandInterleavedData =
381 2 : poGDS->ndims == 3 && poGDS->m_nOtherDimIndex == 0 &&
382 3 : poGDS->GetYIndex() == 1 && poGDS->GetXIndex() == 2;
383 1 : if (poGDS->nBands == 1 || bIsBandInterleavedData)
384 : {
385 : GDALRasterIOExtraArg sExtraArg;
386 1 : INIT_RASTERIO_EXTRA_ARG(sExtraArg);
387 1 : const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
388 2 : return IRasterIO(GF_Read, nXOff, nYOff, nXSize, nYSize, pImage,
389 : nXSize, nYSize, eDataType, nDTSize,
390 1 : static_cast<GSpacing>(nDTSize) * nBlockXSize,
391 1 : &sExtraArg);
392 : }
393 : }
394 :
395 : HDF5_GLOBAL_LOCK();
396 :
397 102 : hsize_t count[3] = {0, 0, 0};
398 102 : H5OFFSET_TYPE offset[3] = {0, 0, 0};
399 102 : hsize_t col_dims[3] = {0, 0, 0};
400 102 : hsize_t rank = std::min(poGDS->ndims, 2);
401 :
402 102 : if (poGDS->ndims == 3)
403 : {
404 1 : rank = 3;
405 1 : offset[poGDS->m_nOtherDimIndex] = nBand - 1;
406 1 : count[poGDS->m_nOtherDimIndex] = 1;
407 1 : col_dims[poGDS->m_nOtherDimIndex] = 1;
408 : }
409 :
410 102 : const int nYIndex = poGDS->GetYIndex();
411 : // Blocksize may not be a multiple of imagesize.
412 102 : if (nYIndex >= 0)
413 : {
414 101 : offset[nYIndex] = nYOff;
415 101 : count[nYIndex] = nYSize;
416 : }
417 102 : offset[poGDS->GetXIndex()] = nXOff;
418 102 : count[poGDS->GetXIndex()] = nXSize;
419 :
420 : // Select block from file space.
421 102 : herr_t status = H5Sselect_hyperslab(poGDS->dataspace_id, H5S_SELECT_SET,
422 : offset, nullptr, count, nullptr);
423 102 : if (status < 0)
424 0 : return CE_Failure;
425 :
426 : // Create memory space to receive the data.
427 102 : if (nYIndex >= 0)
428 101 : col_dims[nYIndex] = nBlockYSize;
429 102 : col_dims[poGDS->GetXIndex()] = nBlockXSize;
430 :
431 : const hid_t memspace =
432 102 : H5Screate_simple(static_cast<int>(rank), col_dims, nullptr);
433 102 : H5OFFSET_TYPE mem_offset[3] = {0, 0, 0};
434 102 : status = H5Sselect_hyperslab(memspace, H5S_SELECT_SET, mem_offset, nullptr,
435 : count, nullptr);
436 102 : if (status < 0)
437 : {
438 0 : H5Sclose(memspace);
439 0 : return CE_Failure;
440 : }
441 :
442 102 : status = H5Dread(poGDS->dataset_id, poGDS->native, memspace,
443 : poGDS->dataspace_id, H5P_DEFAULT, pImage);
444 :
445 102 : H5Sclose(memspace);
446 :
447 102 : if (status < 0)
448 : {
449 0 : CPLError(CE_Failure, CPLE_AppDefined, "H5Dread() failed for block.");
450 0 : return CE_Failure;
451 : }
452 :
453 : #ifdef HDF5_HAVE_FLOAT16
454 : if (eDataType == GDT_Float32 && poGDS->m_bConvertFromFloat16)
455 : {
456 : for (size_t i = static_cast<size_t>(nBlockXSize) * nBlockYSize; i > 0;
457 : /* do nothing */)
458 : {
459 : --i;
460 : uint16_t nVal16;
461 : memcpy(&nVal16, static_cast<uint16_t *>(pImage) + i,
462 : sizeof(nVal16));
463 : const uint32_t nVal32 = CPLHalfToFloat(nVal16);
464 : float fVal;
465 : memcpy(&fVal, &nVal32, sizeof(fVal));
466 : *(static_cast<float *>(pImage) + i) = fVal;
467 : }
468 : }
469 : else if (eDataType == GDT_CFloat32 && poGDS->m_bConvertFromFloat16)
470 : {
471 : for (size_t i = static_cast<size_t>(nBlockXSize) * nBlockYSize; i > 0;
472 : /* do nothing */)
473 : {
474 : --i;
475 : for (int j = 1; j >= 0; --j)
476 : {
477 : uint16_t nVal16;
478 : memcpy(&nVal16, static_cast<uint16_t *>(pImage) + 2 * i + j,
479 : sizeof(nVal16));
480 : const uint32_t nVal32 = CPLHalfToFloat(nVal16);
481 : float fVal;
482 : memcpy(&fVal, &nVal32, sizeof(fVal));
483 : *(static_cast<float *>(pImage) + 2 * i + j) = fVal;
484 : }
485 : }
486 : }
487 : #endif
488 :
489 102 : return CE_None;
490 : }
491 :
492 : /************************************************************************/
493 : /* IRasterIO() */
494 : /************************************************************************/
495 :
496 311 : CPLErr HDF5ImageRasterBand::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
497 : int nXSize, int nYSize, void *pData,
498 : int nBufXSize, int nBufYSize,
499 : GDALDataType eBufType,
500 : GSpacing nPixelSpace, GSpacing nLineSpace,
501 : GDALRasterIOExtraArg *psExtraArg)
502 :
503 : {
504 311 : HDF5ImageDataset *poGDS = static_cast<HDF5ImageDataset *>(poDS);
505 :
506 : #ifdef HDF5_HAVE_FLOAT16
507 : if (poGDS->m_bConvertFromFloat16)
508 : {
509 : return GDALPamRasterBand::IRasterIO(
510 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
511 : eBufType, nPixelSpace, nLineSpace, psExtraArg);
512 : }
513 : #endif
514 :
515 : const bool bIsBandInterleavedData =
516 450 : poGDS->ndims == 3 && poGDS->m_nOtherDimIndex == 0 &&
517 761 : poGDS->GetYIndex() == 1 && poGDS->GetXIndex() == 2;
518 :
519 311 : const int nDTSize = GDALGetDataTypeSizeBytes(eDataType);
520 :
521 : // Try to detect if we read whole bands by chunks of whole lines
522 : // If so, then read and cache whole band (or group of m_nBandChunkSize bands)
523 : // to save HDF5 decompression.
524 311 : if (m_nIRasterIORecCounter == 0)
525 : {
526 263 : bool bInvalidateWholeBandChunkOptim = false;
527 263 : if (!(nXSize == nBufXSize && nYSize == nBufYSize))
528 : {
529 1 : bInvalidateWholeBandChunkOptim = true;
530 : }
531 : // Is the first request on band 1, line 0 and one or several full lines?
532 262 : else if (poGDS->m_eWholeBandChunkOptim !=
533 70 : HDF5ImageDataset::WBC_ENABLED &&
534 70 : nBand == 1 && nXOff == 0 && nYOff == 0 &&
535 20 : nXSize == nRasterXSize)
536 : {
537 19 : poGDS->m_eWholeBandChunkOptim =
538 : HDF5ImageDataset::WBC_DETECTION_IN_PROGRESS;
539 19 : poGDS->m_nLastRasterIOBand = 1;
540 19 : poGDS->m_nLastRasterIOXOff = nXOff;
541 19 : poGDS->m_nLastRasterIOYOff = nYOff;
542 19 : poGDS->m_nLastRasterIOXSize = nXSize;
543 19 : poGDS->m_nLastRasterIOYSize = nYSize;
544 : }
545 243 : else if (poGDS->m_eWholeBandChunkOptim ==
546 : HDF5ImageDataset::WBC_DETECTION_IN_PROGRESS)
547 : {
548 50 : if (poGDS->m_nLastRasterIOBand == 1 && nBand == 1)
549 : {
550 : // Is this request a continuation of the previous one?
551 44 : if (nXOff == 0 && poGDS->m_nLastRasterIOXOff == 0 &&
552 44 : nYOff == poGDS->m_nLastRasterIOYOff +
553 44 : poGDS->m_nLastRasterIOYSize &&
554 43 : poGDS->m_nLastRasterIOXSize == nRasterXSize &&
555 43 : nXSize == nRasterXSize)
556 : {
557 43 : poGDS->m_nLastRasterIOXOff = nXOff;
558 43 : poGDS->m_nLastRasterIOYOff = nYOff;
559 43 : poGDS->m_nLastRasterIOXSize = nXSize;
560 43 : poGDS->m_nLastRasterIOYSize = nYSize;
561 : }
562 : else
563 : {
564 1 : bInvalidateWholeBandChunkOptim = true;
565 : }
566 : }
567 6 : else if (poGDS->m_nLastRasterIOBand == 1 && nBand == 2)
568 : {
569 : // Are we switching to band 2 while having fully read band 1?
570 5 : if (nXOff == 0 && nYOff == 0 && nXSize == nRasterXSize &&
571 5 : poGDS->m_nLastRasterIOXOff == 0 &&
572 5 : poGDS->m_nLastRasterIOXSize == nRasterXSize &&
573 5 : poGDS->m_nLastRasterIOYOff + poGDS->m_nLastRasterIOYSize ==
574 5 : nRasterYSize)
575 : {
576 11 : if ((poGDS->m_nBandChunkSize > 1 ||
577 5 : nBufYSize < nRasterYSize) &&
578 1 : static_cast<int64_t>(poGDS->m_nBandChunkSize) *
579 1 : nRasterXSize * nRasterYSize * nDTSize <
580 1 : CPLGetUsablePhysicalRAM() / 10)
581 : {
582 1 : poGDS->m_eWholeBandChunkOptim =
583 : HDF5ImageDataset::WBC_ENABLED;
584 : }
585 : else
586 : {
587 3 : bInvalidateWholeBandChunkOptim = true;
588 : }
589 : }
590 : else
591 : {
592 1 : bInvalidateWholeBandChunkOptim = true;
593 : }
594 : }
595 : else
596 : {
597 1 : bInvalidateWholeBandChunkOptim = true;
598 : }
599 : }
600 263 : if (bInvalidateWholeBandChunkOptim)
601 : {
602 7 : poGDS->m_eWholeBandChunkOptim = HDF5ImageDataset::WBC_DISABLED;
603 7 : poGDS->m_nLastRasterIOBand = -1;
604 7 : poGDS->m_nLastRasterIOXOff = -1;
605 7 : poGDS->m_nLastRasterIOYOff = -1;
606 7 : poGDS->m_nLastRasterIOXSize = -1;
607 7 : poGDS->m_nLastRasterIOYSize = -1;
608 : }
609 : }
610 :
611 311 : if (poGDS->m_eWholeBandChunkOptim == HDF5ImageDataset::WBC_ENABLED &&
612 193 : nXSize == nBufXSize && nYSize == nBufYSize)
613 : {
614 193 : if (poGDS->nBands == 1 || bIsBandInterleavedData)
615 : {
616 193 : if (poGDS->m_iCurrentBandChunk < 0)
617 1 : CPLDebug("HDF5", "Using whole band chunk caching");
618 193 : const int iBandChunk = (nBand - 1) / poGDS->m_nBandChunkSize;
619 193 : if (iBandChunk != poGDS->m_iCurrentBandChunk)
620 : {
621 15 : poGDS->m_abyBandChunk.resize(
622 15 : static_cast<size_t>(poGDS->m_nBandChunkSize) *
623 15 : nRasterXSize * nRasterYSize * nDTSize);
624 :
625 : HDF5_GLOBAL_LOCK();
626 :
627 : hsize_t count[3] = {
628 30 : std::min(static_cast<hsize_t>(poGDS->nBands),
629 30 : static_cast<hsize_t>(iBandChunk + 1) *
630 15 : poGDS->m_nBandChunkSize) -
631 15 : static_cast<hsize_t>(iBandChunk) *
632 15 : poGDS->m_nBandChunkSize,
633 15 : static_cast<hsize_t>(nRasterYSize),
634 15 : static_cast<hsize_t>(nRasterXSize)};
635 15 : H5OFFSET_TYPE offset[3] = {
636 15 : static_cast<H5OFFSET_TYPE>(iBandChunk) *
637 15 : poGDS->m_nBandChunkSize,
638 : static_cast<H5OFFSET_TYPE>(0),
639 15 : static_cast<H5OFFSET_TYPE>(0)};
640 : herr_t status =
641 15 : H5Sselect_hyperslab(poGDS->dataspace_id, H5S_SELECT_SET,
642 : offset, nullptr, count, nullptr);
643 15 : if (status < 0)
644 0 : return CE_Failure;
645 :
646 : const hid_t memspace =
647 15 : H5Screate_simple(poGDS->ndims, count, nullptr);
648 15 : H5OFFSET_TYPE mem_offset[3] = {0, 0, 0};
649 : status =
650 15 : H5Sselect_hyperslab(memspace, H5S_SELECT_SET, mem_offset,
651 : nullptr, count, nullptr);
652 15 : if (status < 0)
653 : {
654 0 : H5Sclose(memspace);
655 0 : return CE_Failure;
656 : }
657 :
658 15 : status = H5Dread(poGDS->dataset_id, poGDS->native, memspace,
659 : poGDS->dataspace_id, H5P_DEFAULT,
660 15 : poGDS->m_abyBandChunk.data());
661 :
662 15 : H5Sclose(memspace);
663 :
664 15 : if (status < 0)
665 : {
666 0 : CPLError(
667 : CE_Failure, CPLE_AppDefined,
668 : "HDF5ImageRasterBand::IRasterIO(): H5Dread() failed");
669 0 : return CE_Failure;
670 : }
671 :
672 15 : poGDS->m_iCurrentBandChunk = iBandChunk;
673 : }
674 :
675 1447 : for (int iY = 0; iY < nYSize; ++iY)
676 : {
677 2508 : GDALCopyWords(poGDS->m_abyBandChunk.data() +
678 1254 : static_cast<size_t>((nBand - 1) %
679 1254 : poGDS->m_nBandChunkSize) *
680 1254 : nRasterYSize * nRasterXSize * nDTSize +
681 1254 : static_cast<size_t>(nYOff + iY) *
682 1254 : nRasterXSize * nDTSize +
683 1254 : nXOff * nDTSize,
684 : eDataType, nDTSize,
685 : static_cast<GByte *>(pData) +
686 1254 : static_cast<size_t>(iY) * nLineSpace,
687 : eBufType, static_cast<int>(nPixelSpace), nXSize);
688 : }
689 193 : return CE_None;
690 : }
691 : }
692 :
693 : const bool bIsExpectedLayout =
694 204 : (bIsBandInterleavedData ||
695 171 : (poGDS->ndims == 2 && poGDS->GetYIndex() == 0 &&
696 85 : poGDS->GetXIndex() == 1));
697 118 : if (eRWFlag == GF_Read && bIsExpectedLayout && nXSize == nBufXSize &&
698 116 : nYSize == nBufYSize && eBufType == eDataType &&
699 68 : nPixelSpace == nDTSize && nLineSpace == nXSize * nPixelSpace)
700 : {
701 : HDF5_GLOBAL_LOCK();
702 :
703 68 : hsize_t count[3] = {1, static_cast<hsize_t>(nYSize),
704 68 : static_cast<hsize_t>(nXSize)};
705 68 : H5OFFSET_TYPE offset[3] = {static_cast<H5OFFSET_TYPE>(nBand - 1),
706 68 : static_cast<H5OFFSET_TYPE>(nYOff),
707 68 : static_cast<H5OFFSET_TYPE>(nXOff)};
708 68 : if (poGDS->ndims == 2)
709 : {
710 47 : count[0] = count[1];
711 47 : count[1] = count[2];
712 :
713 47 : offset[0] = offset[1];
714 47 : offset[1] = offset[2];
715 : }
716 68 : herr_t status = H5Sselect_hyperslab(poGDS->dataspace_id, H5S_SELECT_SET,
717 : offset, nullptr, count, nullptr);
718 68 : if (status < 0)
719 0 : return CE_Failure;
720 :
721 68 : const hid_t memspace = H5Screate_simple(poGDS->ndims, count, nullptr);
722 68 : H5OFFSET_TYPE mem_offset[3] = {0, 0, 0};
723 68 : status = H5Sselect_hyperslab(memspace, H5S_SELECT_SET, mem_offset,
724 : nullptr, count, nullptr);
725 68 : if (status < 0)
726 : {
727 0 : H5Sclose(memspace);
728 0 : return CE_Failure;
729 : }
730 :
731 68 : status = H5Dread(poGDS->dataset_id, poGDS->native, memspace,
732 : poGDS->dataspace_id, H5P_DEFAULT, pData);
733 :
734 68 : H5Sclose(memspace);
735 :
736 68 : if (status < 0)
737 : {
738 0 : CPLError(CE_Failure, CPLE_AppDefined,
739 : "HDF5ImageRasterBand::IRasterIO(): H5Dread() failed");
740 0 : return CE_Failure;
741 : }
742 :
743 68 : return CE_None;
744 : }
745 :
746 : // If the request is still small enough, try to read from libhdf5 with
747 : // the natural interleaving into a temporary MEMDataset, and then read
748 : // from it with the requested interleaving and data type.
749 50 : if (eRWFlag == GF_Read && bIsExpectedLayout && nXSize == nBufXSize &&
750 100 : nYSize == nBufYSize &&
751 48 : static_cast<GIntBig>(nXSize) * nYSize < CPLGetUsablePhysicalRAM() / 10)
752 : {
753 : auto poMemDS = std::unique_ptr<GDALDataset>(
754 48 : MEMDataset::Create("", nXSize, nYSize, 1, eDataType, nullptr));
755 48 : if (poMemDS)
756 : {
757 48 : void *pMemData = poMemDS->GetInternalHandle("MEMORY1");
758 48 : CPLAssert(pMemData);
759 : // Read from HDF5 into the temporary MEMDataset using the
760 : // natural interleaving of the HDF5 dataset
761 48 : ++m_nIRasterIORecCounter;
762 : CPLErr eErr =
763 96 : IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize, pMemData,
764 : nXSize, nYSize, eDataType, nDTSize,
765 48 : static_cast<GSpacing>(nXSize) * nDTSize, psExtraArg);
766 48 : --m_nIRasterIORecCounter;
767 48 : if (eErr != CE_None)
768 : {
769 0 : return CE_Failure;
770 : }
771 : // Copy to the final buffer using requested data type and spacings.
772 48 : return poMemDS->GetRasterBand(1)->RasterIO(
773 : GF_Read, 0, 0, nXSize, nYSize, pData, nXSize, nYSize, eBufType,
774 48 : nPixelSpace, nLineSpace, nullptr);
775 : }
776 : }
777 :
778 2 : return GDALPamRasterBand::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
779 : pData, nBufXSize, nBufYSize, eBufType,
780 2 : nPixelSpace, nLineSpace, psExtraArg);
781 : }
782 :
783 : /************************************************************************/
784 : /* IRasterIO() */
785 : /************************************************************************/
786 :
787 90 : CPLErr HDF5ImageDataset::IRasterIO(
788 : GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize,
789 : void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType,
790 : int nBandCount, BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
791 : GSpacing nLineSpace, GSpacing nBandSpace, GDALRasterIOExtraArg *psExtraArg)
792 :
793 : {
794 : #ifdef HDF5_HAVE_FLOAT16
795 : if (m_bConvertFromFloat16)
796 : {
797 : return HDF5Dataset::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
798 : pData, nBufXSize, nBufYSize, eBufType,
799 : nBandCount, panBandMap, nPixelSpace,
800 : nLineSpace, nBandSpace, psExtraArg);
801 : }
802 : #endif
803 :
804 134 : const auto IsConsecutiveBands = [](const int *panVals, int nCount)
805 : {
806 151 : for (int i = 1; i < nCount; ++i)
807 : {
808 19 : if (panVals[i] != panVals[i - 1] + 1)
809 2 : return false;
810 : }
811 132 : return true;
812 : };
813 :
814 90 : const auto eDT = GetRasterBand(1)->GetRasterDataType();
815 90 : const int nDTSize = GDALGetDataTypeSizeBytes(eDT);
816 :
817 : // Band-interleaved data and request
818 176 : const bool bIsBandInterleavedData = ndims == 3 && m_nOtherDimIndex == 0 &&
819 266 : GetYIndex() == 1 && GetXIndex() == 2;
820 90 : if (eRWFlag == GF_Read && bIsBandInterleavedData && nXSize == nBufXSize &&
821 86 : nYSize == nBufYSize && IsConsecutiveBands(panBandMap, nBandCount) &&
822 84 : eBufType == eDT && nPixelSpace == nDTSize &&
823 180 : nLineSpace == nXSize * nPixelSpace && nBandSpace == nYSize * nLineSpace)
824 : {
825 : HDF5_GLOBAL_LOCK();
826 :
827 43 : hsize_t count[3] = {static_cast<hsize_t>(nBandCount),
828 43 : static_cast<hsize_t>(nYSize),
829 43 : static_cast<hsize_t>(nXSize)};
830 : H5OFFSET_TYPE offset[3] = {
831 43 : static_cast<H5OFFSET_TYPE>(panBandMap[0] - 1),
832 43 : static_cast<H5OFFSET_TYPE>(nYOff),
833 43 : static_cast<H5OFFSET_TYPE>(nXOff)};
834 43 : herr_t status = H5Sselect_hyperslab(dataspace_id, H5S_SELECT_SET,
835 : offset, nullptr, count, nullptr);
836 43 : if (status < 0)
837 0 : return CE_Failure;
838 :
839 43 : const hid_t memspace = H5Screate_simple(ndims, count, nullptr);
840 43 : H5OFFSET_TYPE mem_offset[3] = {0, 0, 0};
841 43 : status = H5Sselect_hyperslab(memspace, H5S_SELECT_SET, mem_offset,
842 : nullptr, count, nullptr);
843 43 : if (status < 0)
844 : {
845 0 : H5Sclose(memspace);
846 0 : return CE_Failure;
847 : }
848 :
849 43 : status = H5Dread(dataset_id, native, memspace, dataspace_id,
850 : H5P_DEFAULT, pData);
851 :
852 43 : H5Sclose(memspace);
853 :
854 43 : if (status < 0)
855 : {
856 0 : CPLError(CE_Failure, CPLE_AppDefined,
857 : "HDF5ImageDataset::IRasterIO(): H5Dread() failed");
858 0 : return CE_Failure;
859 : }
860 :
861 43 : return CE_None;
862 : }
863 :
864 : // Pixel-interleaved data and request
865 :
866 51 : const bool bIsPixelInterleaveData = ndims == 3 && m_nOtherDimIndex == 2 &&
867 98 : GetYIndex() == 0 && GetXIndex() == 1;
868 47 : if (eRWFlag == GF_Read && bIsPixelInterleaveData && nXSize == nBufXSize &&
869 4 : nYSize == nBufYSize && IsConsecutiveBands(panBandMap, nBandCount) &&
870 4 : eBufType == eDT && nBandSpace == nDTSize &&
871 97 : nPixelSpace == nBandCount * nBandSpace &&
872 3 : nLineSpace == nXSize * nPixelSpace)
873 : {
874 : HDF5_GLOBAL_LOCK();
875 :
876 3 : hsize_t count[3] = {static_cast<hsize_t>(nYSize),
877 3 : static_cast<hsize_t>(nXSize),
878 3 : static_cast<hsize_t>(nBandCount)};
879 : H5OFFSET_TYPE offset[3] = {
880 3 : static_cast<H5OFFSET_TYPE>(nYOff),
881 3 : static_cast<H5OFFSET_TYPE>(nXOff),
882 3 : static_cast<H5OFFSET_TYPE>(panBandMap[0] - 1)};
883 3 : herr_t status = H5Sselect_hyperslab(dataspace_id, H5S_SELECT_SET,
884 : offset, nullptr, count, nullptr);
885 3 : if (status < 0)
886 0 : return CE_Failure;
887 :
888 3 : const hid_t memspace = H5Screate_simple(ndims, count, nullptr);
889 3 : H5OFFSET_TYPE mem_offset[3] = {0, 0, 0};
890 3 : status = H5Sselect_hyperslab(memspace, H5S_SELECT_SET, mem_offset,
891 : nullptr, count, nullptr);
892 3 : if (status < 0)
893 : {
894 0 : H5Sclose(memspace);
895 0 : return CE_Failure;
896 : }
897 :
898 3 : status = H5Dread(dataset_id, native, memspace, dataspace_id,
899 : H5P_DEFAULT, pData);
900 :
901 3 : H5Sclose(memspace);
902 :
903 3 : if (status < 0)
904 : {
905 0 : CPLError(CE_Failure, CPLE_AppDefined,
906 : "HDF5ImageDataset::IRasterIO(): H5Dread() failed");
907 0 : return CE_Failure;
908 : }
909 :
910 3 : return CE_None;
911 : }
912 :
913 : // If the request is still small enough, try to read from libhdf5 with
914 : // the natural interleaving into a temporary MEMDataset, and then read
915 : // from it with the requested interleaving and data type.
916 44 : if (eRWFlag == GF_Read &&
917 44 : (bIsBandInterleavedData || bIsPixelInterleaveData) &&
918 88 : nXSize == nBufXSize && nYSize == nBufYSize &&
919 132 : IsConsecutiveBands(panBandMap, nBandCount) &&
920 43 : static_cast<GIntBig>(nXSize) * nYSize <
921 43 : CPLGetUsablePhysicalRAM() / 10 / nBandCount)
922 : {
923 43 : const char *const apszOptions[] = {
924 43 : bIsPixelInterleaveData ? "INTERLEAVE=PIXEL" : nullptr, nullptr};
925 : auto poMemDS = std::unique_ptr<GDALDataset>(
926 43 : MEMDataset::Create("", nXSize, nYSize, nBandCount, eDT,
927 43 : const_cast<char **>(apszOptions)));
928 43 : if (poMemDS)
929 : {
930 43 : void *pMemData = poMemDS->GetInternalHandle("MEMORY1");
931 43 : CPLAssert(pMemData);
932 : // Read from HDF5 into the temporary MEMDataset using the
933 : // natural interleaving of the HDF5 dataset
934 129 : if (IRasterIO(
935 : eRWFlag, nXOff, nYOff, nXSize, nYSize, pMemData, nXSize,
936 : nYSize, eDT, nBandCount, panBandMap,
937 1 : bIsBandInterleavedData ? nDTSize : nDTSize * nBandCount,
938 : bIsBandInterleavedData
939 42 : ? static_cast<GSpacing>(nXSize) * nDTSize
940 1 : : static_cast<GSpacing>(nXSize) * nDTSize * nBandCount,
941 : bIsBandInterleavedData
942 42 : ? static_cast<GSpacing>(nYSize) * nXSize * nDTSize
943 : : nDTSize,
944 43 : psExtraArg) != CE_None)
945 : {
946 0 : return CE_Failure;
947 : }
948 : // Copy to the final buffer using requested data type and spacings.
949 43 : return poMemDS->RasterIO(GF_Read, 0, 0, nXSize, nYSize, pData,
950 : nXSize, nYSize, eBufType, nBandCount,
951 : nullptr, nPixelSpace, nLineSpace,
952 43 : nBandSpace, nullptr);
953 : }
954 : }
955 :
956 1 : return HDF5Dataset::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize, pData,
957 : nBufXSize, nBufYSize, eBufType, nBandCount,
958 : panBandMap, nPixelSpace, nLineSpace,
959 1 : nBandSpace, psExtraArg);
960 : }
961 :
962 : /************************************************************************/
963 : /* Open() */
964 : /************************************************************************/
965 58 : GDALDataset *HDF5ImageDataset::Open(GDALOpenInfo *poOpenInfo)
966 : {
967 58 : if (!STARTS_WITH_CI(poOpenInfo->pszFilename, "HDF5:"))
968 0 : return nullptr;
969 :
970 : HDF5_GLOBAL_LOCK();
971 :
972 : // Confirm the requested access is supported.
973 58 : if (poOpenInfo->eAccess == GA_Update)
974 : {
975 0 : ReportUpdateNotSupportedByDriver("HDF5");
976 0 : return nullptr;
977 : }
978 :
979 58 : HDF5ImageDataset *poDS = new HDF5ImageDataset();
980 :
981 : // Create a corresponding GDALDataset.
982 : char **papszName =
983 58 : CSLTokenizeString2(poOpenInfo->pszFilename, ":",
984 : CSLT_HONOURSTRINGS | CSLT_PRESERVEESCAPES);
985 :
986 58 : if (!(CSLCount(papszName) == 3 || CSLCount(papszName) == 4))
987 : {
988 0 : CSLDestroy(papszName);
989 0 : delete poDS;
990 0 : return nullptr;
991 : }
992 :
993 58 : poDS->SetDescription(poOpenInfo->pszFilename);
994 :
995 : // Check for drive name in windows HDF5:"D:\...
996 116 : CPLString osSubdatasetName;
997 :
998 116 : CPLString osFilename(papszName[1]);
999 :
1000 58 : if ((strlen(papszName[1]) == 1 && papszName[3] != nullptr) ||
1001 58 : (STARTS_WITH(papszName[1], "/vsicurl/http") && papszName[3] != nullptr))
1002 : {
1003 0 : osFilename += ":";
1004 0 : osFilename += papszName[2];
1005 0 : osSubdatasetName = papszName[3];
1006 : }
1007 : else
1008 : {
1009 58 : osSubdatasetName = papszName[2];
1010 : }
1011 :
1012 58 : poDS->SetSubdatasetName(osSubdatasetName);
1013 :
1014 58 : CSLDestroy(papszName);
1015 58 : papszName = nullptr;
1016 :
1017 58 : poDS->SetPhysicalFilename(osFilename);
1018 :
1019 : // Try opening the dataset.
1020 58 : poDS->m_hHDF5 = GDAL_HDF5Open(osFilename);
1021 58 : if (poDS->m_hHDF5 < 0)
1022 : {
1023 0 : delete poDS;
1024 0 : return nullptr;
1025 : }
1026 :
1027 58 : poDS->hGroupID = H5Gopen(poDS->m_hHDF5, "/");
1028 58 : if (poDS->hGroupID < 0)
1029 : {
1030 0 : delete poDS;
1031 0 : return nullptr;
1032 : }
1033 :
1034 : // This is an HDF5 file.
1035 58 : poDS->ReadGlobalAttributes(FALSE);
1036 :
1037 : // Create HDF5 Data Hierarchy in a link list.
1038 58 : poDS->poH5Objects = poDS->HDF5FindDatasetObjectsbyPath(poDS->poH5RootGroup,
1039 : osSubdatasetName);
1040 :
1041 58 : if (poDS->poH5Objects == nullptr)
1042 : {
1043 0 : delete poDS;
1044 0 : return nullptr;
1045 : }
1046 :
1047 : // Retrieve HDF5 data information.
1048 58 : poDS->dataset_id = H5Dopen(poDS->m_hHDF5, poDS->poH5Objects->pszPath);
1049 58 : poDS->dataspace_id = H5Dget_space(poDS->dataset_id);
1050 58 : poDS->ndims = H5Sget_simple_extent_ndims(poDS->dataspace_id);
1051 58 : if (poDS->ndims <= 0)
1052 : {
1053 0 : delete poDS;
1054 0 : return nullptr;
1055 : }
1056 58 : poDS->dims =
1057 58 : static_cast<hsize_t *>(CPLCalloc(poDS->ndims, sizeof(hsize_t)));
1058 58 : poDS->maxdims =
1059 58 : static_cast<hsize_t *>(CPLCalloc(poDS->ndims, sizeof(hsize_t)));
1060 58 : poDS->dimensions = H5Sget_simple_extent_dims(poDS->dataspace_id, poDS->dims,
1061 : poDS->maxdims);
1062 185 : for (int i = 0; i < poDS->dimensions; ++i)
1063 : {
1064 256 : if (poDS->dims[i] >
1065 128 : static_cast<hsize_t>(std::numeric_limits<int>::max()))
1066 : {
1067 1 : CPLError(CE_Failure, CPLE_NotSupported,
1068 : "At least one dimension size exceeds INT_MAX !");
1069 1 : delete poDS;
1070 1 : return nullptr;
1071 : }
1072 : }
1073 :
1074 57 : auto datatype = H5Dget_type(poDS->dataset_id);
1075 57 : poDS->native = H5Tget_native_type(datatype, H5T_DIR_ASCEND);
1076 57 : H5Tclose(datatype);
1077 :
1078 57 : const auto eGDALDataType = poDS->GetDataType(poDS->native);
1079 57 : if (eGDALDataType == GDT_Unknown)
1080 : {
1081 0 : CPLError(CE_Failure, CPLE_AppDefined, "Unhandled HDF5 data type");
1082 0 : delete poDS;
1083 0 : return nullptr;
1084 : }
1085 :
1086 : #ifdef HDF5_HAVE_FLOAT16
1087 : if (H5Tequal(H5T_NATIVE_FLOAT16, poDS->native) ||
1088 : IsNativeCFloat16(poDS->native))
1089 : {
1090 : poDS->m_bConvertFromFloat16 = true;
1091 : }
1092 : #endif
1093 :
1094 : // CSK code in IdentifyProductType() and CreateProjections()
1095 : // uses dataset metadata.
1096 57 : poDS->SetMetadata(poDS->m_aosMetadata.List());
1097 :
1098 : // Check if the hdf5 is a well known product type
1099 57 : poDS->IdentifyProductType();
1100 :
1101 57 : poDS->m_nYIndex = poDS->IsComplexCSKL1A() ? 0 : poDS->ndims - 2;
1102 57 : poDS->m_nXIndex = poDS->IsComplexCSKL1A() ? 1 : poDS->ndims - 1;
1103 :
1104 57 : if (poDS->IsComplexCSKL1A())
1105 : {
1106 0 : poDS->m_nOtherDimIndex = 2;
1107 : }
1108 57 : else if (poDS->ndims == 3)
1109 : {
1110 14 : poDS->m_nOtherDimIndex = 0;
1111 : }
1112 :
1113 57 : if (HDF5EOSParser::HasHDFEOS(poDS->hGroupID))
1114 : {
1115 34 : HDF5EOSParser oHDFEOSParser;
1116 17 : if (oHDFEOSParser.Parse(poDS->hGroupID))
1117 : {
1118 17 : CPLDebug("HDF5", "Successfully parsed HDFEOS metadata");
1119 34 : HDF5EOSParser::GridDataFieldMetadata oGridDataFieldMetadata;
1120 34 : HDF5EOSParser::SwathDataFieldMetadata oSwathDataFieldMetadata;
1121 17 : if (oHDFEOSParser.GetDataModel() ==
1122 5 : HDF5EOSParser::DataModel::GRID &&
1123 5 : oHDFEOSParser.GetGridDataFieldMetadata(
1124 22 : osSubdatasetName.c_str(), oGridDataFieldMetadata) &&
1125 5 : static_cast<int>(oGridDataFieldMetadata.aoDimensions.size()) ==
1126 5 : poDS->ndims)
1127 : {
1128 5 : int iDim = 0;
1129 17 : for (const auto &oDim : oGridDataFieldMetadata.aoDimensions)
1130 : {
1131 12 : if (oDim.osName == "XDim")
1132 5 : poDS->m_nXIndex = iDim;
1133 7 : else if (oDim.osName == "YDim")
1134 5 : poDS->m_nYIndex = iDim;
1135 : else
1136 2 : poDS->m_nOtherDimIndex = iDim;
1137 12 : ++iDim;
1138 : }
1139 :
1140 5 : if (oGridDataFieldMetadata.poGridMetadata->GetGeoTransform(
1141 5 : poDS->adfGeoTransform))
1142 5 : poDS->bHasGeoTransform = true;
1143 :
1144 10 : auto poSRS = oGridDataFieldMetadata.poGridMetadata->GetSRS();
1145 5 : if (poSRS)
1146 5 : poDS->m_oSRS = *(poSRS.get());
1147 : }
1148 12 : else if (oHDFEOSParser.GetDataModel() ==
1149 12 : HDF5EOSParser::DataModel::SWATH &&
1150 12 : oHDFEOSParser.GetSwathDataFieldMetadata(
1151 6 : osSubdatasetName.c_str(), oSwathDataFieldMetadata) &&
1152 : static_cast<int>(
1153 6 : oSwathDataFieldMetadata.aoDimensions.size()) ==
1154 6 : poDS->ndims &&
1155 30 : oSwathDataFieldMetadata.iXDim >= 0 &&
1156 6 : oSwathDataFieldMetadata.iYDim >= 0)
1157 : {
1158 6 : poDS->m_nXIndex = oSwathDataFieldMetadata.iXDim;
1159 6 : poDS->m_nYIndex = oSwathDataFieldMetadata.iYDim;
1160 6 : poDS->m_nOtherDimIndex = oSwathDataFieldMetadata.iOtherDim;
1161 6 : if (!oSwathDataFieldMetadata.osLongitudeSubdataset.empty())
1162 : {
1163 : // Arbitrary
1164 6 : poDS->SetMetadataItem("SRS", SRS_WKT_WGS84_LAT_LONG,
1165 6 : "GEOLOCATION");
1166 6 : poDS->SetMetadataItem(
1167 : "X_DATASET",
1168 12 : ("HDF5:\"" + osFilename +
1169 12 : "\":" + oSwathDataFieldMetadata.osLongitudeSubdataset)
1170 : .c_str(),
1171 6 : "GEOLOCATION");
1172 6 : poDS->SetMetadataItem("X_BAND", "1", "GEOLOCATION");
1173 6 : poDS->SetMetadataItem(
1174 : "Y_DATASET",
1175 12 : ("HDF5:\"" + osFilename +
1176 12 : "\":" + oSwathDataFieldMetadata.osLatitudeSubdataset)
1177 : .c_str(),
1178 6 : "GEOLOCATION");
1179 6 : poDS->SetMetadataItem("Y_BAND", "1", "GEOLOCATION");
1180 6 : poDS->SetMetadataItem(
1181 : "PIXEL_OFFSET",
1182 : CPLSPrintf("%d", oSwathDataFieldMetadata.nPixelOffset),
1183 6 : "GEOLOCATION");
1184 6 : poDS->SetMetadataItem(
1185 : "PIXEL_STEP",
1186 : CPLSPrintf("%d", oSwathDataFieldMetadata.nPixelStep),
1187 6 : "GEOLOCATION");
1188 6 : poDS->SetMetadataItem(
1189 : "LINE_OFFSET",
1190 : CPLSPrintf("%d", oSwathDataFieldMetadata.nLineOffset),
1191 6 : "GEOLOCATION");
1192 6 : poDS->SetMetadataItem(
1193 : "LINE_STEP",
1194 : CPLSPrintf("%d", oSwathDataFieldMetadata.nLineStep),
1195 6 : "GEOLOCATION");
1196 : // Not totally sure about that
1197 6 : poDS->SetMetadataItem("GEOREFERENCING_CONVENTION",
1198 6 : "PIXEL_CENTER", "GEOLOCATION");
1199 : }
1200 : }
1201 : }
1202 : }
1203 :
1204 57 : poDS->nRasterYSize =
1205 57 : poDS->GetYIndex() < 0
1206 57 : ? 1
1207 56 : : static_cast<int>(poDS->dims[poDS->GetYIndex()]); // nRows
1208 57 : poDS->nRasterXSize =
1209 57 : static_cast<int>(poDS->dims[poDS->GetXIndex()]); // nCols
1210 57 : int nBands = 1;
1211 57 : if (poDS->m_nOtherDimIndex >= 0)
1212 : {
1213 14 : nBands = static_cast<int>(poDS->dims[poDS->m_nOtherDimIndex]);
1214 : }
1215 :
1216 114 : CPLStringList aosMetadata;
1217 57 : std::map<std::string, CPLStringList> oMapBandSpecificMetadata;
1218 57 : if (poDS->poH5Objects->nType == H5G_DATASET)
1219 : {
1220 57 : HDF5Dataset::CreateMetadata(poDS->m_hHDF5, poDS->poH5Objects,
1221 : H5G_DATASET, false, aosMetadata);
1222 57 : if (nBands > 1 && poDS->nRasterXSize != nBands &&
1223 13 : poDS->nRasterYSize != nBands)
1224 : {
1225 : // Heuristics to detect non-scalar attributes, that are intended
1226 : // to be attached to a specific band.
1227 26 : const CPLStringList aosMetadataDup(aosMetadata);
1228 52 : for (const auto &[pszKey, pszValue] :
1229 65 : cpl::IterateNameValue(aosMetadataDup))
1230 : {
1231 26 : const hid_t hAttrID = H5Aopen_name(poDS->dataset_id, pszKey);
1232 26 : const hid_t hAttrSpace = H5Aget_space(hAttrID);
1233 47 : if (H5Sget_simple_extent_ndims(hAttrSpace) == 1 &&
1234 21 : H5Sget_simple_extent_npoints(hAttrSpace) == nBands)
1235 : {
1236 : CPLStringList aosTokens(
1237 40 : CSLTokenizeString2(pszValue, " ", 0));
1238 20 : if (aosTokens.size() == nBands)
1239 : {
1240 40 : std::string osAttrName(pszKey);
1241 30 : if (osAttrName.size() > strlen("_coefficients") &&
1242 30 : osAttrName.substr(osAttrName.size() -
1243 10 : strlen("_coefficients")) ==
1244 : "_coefficients")
1245 : {
1246 5 : osAttrName.pop_back();
1247 : }
1248 25 : else if (osAttrName.size() > strlen("_wavelengths") &&
1249 25 : osAttrName.substr(osAttrName.size() -
1250 10 : strlen("_wavelengths")) ==
1251 : "_wavelengths")
1252 : {
1253 5 : osAttrName.pop_back();
1254 : }
1255 15 : else if (osAttrName.size() > strlen("_list") &&
1256 15 : osAttrName.substr(osAttrName.size() -
1257 5 : strlen("_list")) == "_list")
1258 : {
1259 5 : osAttrName.resize(osAttrName.size() -
1260 : strlen("_list"));
1261 : }
1262 20 : oMapBandSpecificMetadata[osAttrName] =
1263 40 : std::move(aosTokens);
1264 20 : aosMetadata.SetNameValue(pszKey, nullptr);
1265 : }
1266 : }
1267 26 : H5Sclose(hAttrSpace);
1268 26 : H5Aclose(hAttrID);
1269 : }
1270 : }
1271 : }
1272 :
1273 57 : poDS->m_nBlockXSize = poDS->GetRasterXSize();
1274 57 : poDS->m_nBlockYSize = 1;
1275 57 : poDS->m_nBandChunkSize = 1;
1276 :
1277 : // Check for chunksize and set it as the blocksize (optimizes read).
1278 57 : const hid_t listid = H5Dget_create_plist(poDS->dataset_id);
1279 57 : if (listid > 0)
1280 : {
1281 57 : if (H5Pget_layout(listid) == H5D_CHUNKED)
1282 : {
1283 12 : hsize_t panChunkDims[3] = {0, 0, 0};
1284 12 : const int nDimSize = H5Pget_chunk(listid, 3, panChunkDims);
1285 12 : CPL_IGNORE_RET_VAL(nDimSize);
1286 12 : CPLAssert(nDimSize == poDS->ndims);
1287 12 : poDS->m_nBlockXSize =
1288 12 : static_cast<int>(panChunkDims[poDS->GetXIndex()]);
1289 12 : if (poDS->GetYIndex() >= 0)
1290 12 : poDS->m_nBlockYSize =
1291 12 : static_cast<int>(panChunkDims[poDS->GetYIndex()]);
1292 12 : if (nBands > 1)
1293 : {
1294 3 : poDS->m_nBandChunkSize =
1295 3 : static_cast<int>(panChunkDims[poDS->m_nOtherDimIndex]);
1296 :
1297 3 : poDS->SetMetadataItem("BAND_CHUNK_SIZE",
1298 : CPLSPrintf("%d", poDS->m_nBandChunkSize),
1299 3 : "IMAGE_STRUCTURE");
1300 : }
1301 : }
1302 :
1303 57 : const int nFilters = H5Pget_nfilters(listid);
1304 63 : for (int i = 0; i < nFilters; ++i)
1305 : {
1306 6 : unsigned int flags = 0;
1307 6 : size_t cd_nelmts = 0;
1308 6 : char szName[64 + 1] = {0};
1309 6 : const auto eFilter = H5Pget_filter(listid, i, &flags, &cd_nelmts,
1310 : nullptr, 64, szName);
1311 6 : if (eFilter == H5Z_FILTER_DEFLATE)
1312 : {
1313 5 : poDS->SetMetadataItem("COMPRESSION", "DEFLATE",
1314 5 : "IMAGE_STRUCTURE");
1315 : }
1316 1 : else if (eFilter == H5Z_FILTER_SZIP)
1317 : {
1318 0 : poDS->SetMetadataItem("COMPRESSION", "SZIP", "IMAGE_STRUCTURE");
1319 : }
1320 : }
1321 :
1322 57 : H5Pclose(listid);
1323 : }
1324 :
1325 180 : for (int i = 0; i < nBands; i++)
1326 : {
1327 : HDF5ImageRasterBand *const poBand =
1328 123 : new HDF5ImageRasterBand(poDS, i + 1, eGDALDataType);
1329 :
1330 123 : poDS->SetBand(i + 1, poBand);
1331 :
1332 123 : if (poDS->poH5Objects->nType == H5G_DATASET)
1333 : {
1334 123 : poBand->SetMetadata(aosMetadata.List());
1335 163 : for (const auto &oIter : oMapBandSpecificMetadata)
1336 : {
1337 40 : poBand->SetMetadataItem(oIter.first.c_str(), oIter.second[i]);
1338 : }
1339 : }
1340 : }
1341 :
1342 57 : if (!poDS->GetMetadata("GEOLOCATION"))
1343 51 : poDS->CreateProjections();
1344 :
1345 : // Setup/check for pam .aux.xml.
1346 57 : poDS->TryLoadXML();
1347 :
1348 : // Setup overviews.
1349 57 : poDS->oOvManager.Initialize(poDS, ":::VIRTUAL:::");
1350 :
1351 57 : return poDS;
1352 : }
1353 :
1354 : /************************************************************************/
1355 : /* HDF5ImageDatasetDriverUnload() */
1356 : /************************************************************************/
1357 :
1358 6 : static void HDF5ImageDatasetDriverUnload(GDALDriver *)
1359 : {
1360 6 : HDF5UnloadFileDriver();
1361 6 : }
1362 :
1363 : /************************************************************************/
1364 : /* GDALRegister_HDF5Image() */
1365 : /************************************************************************/
1366 11 : void GDALRegister_HDF5Image()
1367 :
1368 : {
1369 11 : if (!GDAL_CHECK_VERSION("HDF5Image driver"))
1370 0 : return;
1371 :
1372 11 : if (GDALGetDriverByName(HDF5_IMAGE_DRIVER_NAME) != nullptr)
1373 0 : return;
1374 :
1375 11 : GDALDriver *poDriver = new GDALDriver();
1376 :
1377 11 : HDF5ImageDriverSetCommonMetadata(poDriver);
1378 :
1379 11 : poDriver->pfnOpen = HDF5ImageDataset::Open;
1380 11 : poDriver->pfnUnloadDriver = HDF5ImageDatasetDriverUnload;
1381 :
1382 11 : GetGDALDriverManager()->RegisterDriver(poDriver);
1383 : }
1384 :
1385 : /************************************************************************/
1386 : /* CreateODIMH5Projection() */
1387 : /************************************************************************/
1388 :
1389 : // Reference:
1390 : // http://www.knmi.nl/opera/opera3/OPERA_2008_03_WP2.1b_ODIM_H5_v2.1.pdf
1391 : //
1392 : // 4.3.2 where for geographically referenced image Groups
1393 : // We don't use the where_xscale and where_yscale parameters, but recompute them
1394 : // from the lower-left and upper-right coordinates. There's some difference.
1395 : // As all those parameters are linked together, I'm not sure which one should be
1396 : // considered as the reference.
1397 :
1398 0 : CPLErr HDF5ImageDataset::CreateODIMH5Projection()
1399 : {
1400 0 : const char *const pszProj4String = GetMetadataItem("where_projdef");
1401 0 : const char *const pszLL_lon = GetMetadataItem("where_LL_lon");
1402 0 : const char *const pszLL_lat = GetMetadataItem("where_LL_lat");
1403 0 : const char *const pszUR_lon = GetMetadataItem("where_UR_lon");
1404 0 : const char *const pszUR_lat = GetMetadataItem("where_UR_lat");
1405 0 : if (pszProj4String == nullptr || pszLL_lon == nullptr ||
1406 0 : pszLL_lat == nullptr || pszUR_lon == nullptr || pszUR_lat == nullptr)
1407 0 : return CE_Failure;
1408 :
1409 0 : m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
1410 0 : if (m_oSRS.importFromProj4(pszProj4String) != OGRERR_NONE)
1411 0 : return CE_Failure;
1412 :
1413 0 : OGRSpatialReference oSRSWGS84;
1414 0 : oSRSWGS84.SetWellKnownGeogCS("WGS84");
1415 0 : oSRSWGS84.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
1416 :
1417 : OGRCoordinateTransformation *poCT =
1418 0 : OGRCreateCoordinateTransformation(&oSRSWGS84, &m_oSRS);
1419 0 : if (poCT == nullptr)
1420 0 : return CE_Failure;
1421 :
1422 : // Reproject corners from long,lat WGS84 to the target SRS.
1423 0 : double dfLLX = CPLAtof(pszLL_lon);
1424 0 : double dfLLY = CPLAtof(pszLL_lat);
1425 0 : double dfURX = CPLAtof(pszUR_lon);
1426 0 : double dfURY = CPLAtof(pszUR_lat);
1427 0 : if (!poCT->Transform(1, &dfLLX, &dfLLY) ||
1428 0 : !poCT->Transform(1, &dfURX, &dfURY))
1429 : {
1430 0 : delete poCT;
1431 0 : return CE_Failure;
1432 : }
1433 0 : delete poCT;
1434 :
1435 : // Compute the geotransform now.
1436 0 : const double dfPixelX = (dfURX - dfLLX) / nRasterXSize;
1437 0 : const double dfPixelY = (dfURY - dfLLY) / nRasterYSize;
1438 :
1439 0 : bHasGeoTransform = true;
1440 0 : adfGeoTransform[0] = dfLLX;
1441 0 : adfGeoTransform[1] = dfPixelX;
1442 0 : adfGeoTransform[2] = 0;
1443 0 : adfGeoTransform[3] = dfURY;
1444 0 : adfGeoTransform[4] = 0;
1445 0 : adfGeoTransform[5] = -dfPixelY;
1446 :
1447 0 : return CE_None;
1448 : }
1449 :
1450 : /************************************************************************/
1451 : /* CreateProjections() */
1452 : /************************************************************************/
1453 51 : CPLErr HDF5ImageDataset::CreateProjections()
1454 : {
1455 51 : switch (iSubdatasetType)
1456 : {
1457 2 : case CSK_PRODUCT:
1458 : {
1459 2 : int productType = PROD_UNKNOWN;
1460 :
1461 2 : if (GetMetadataItem("Product_Type") != nullptr)
1462 : {
1463 : // Get the format's level.
1464 : const char *osMissionLevel =
1465 2 : HDF5Dataset::GetMetadataItem("Product_Type");
1466 :
1467 2 : if (STARTS_WITH_CI(osMissionLevel, "RAW"))
1468 0 : productType = PROD_CSK_L0;
1469 :
1470 2 : if (STARTS_WITH_CI(osMissionLevel, "SSC"))
1471 0 : productType = PROD_CSK_L1A;
1472 :
1473 2 : if (STARTS_WITH_CI(osMissionLevel, "DGM"))
1474 1 : productType = PROD_CSK_L1B;
1475 :
1476 2 : if (STARTS_WITH_CI(osMissionLevel, "GEC"))
1477 1 : productType = PROD_CSK_L1C;
1478 :
1479 2 : if (STARTS_WITH_CI(osMissionLevel, "GTC"))
1480 0 : productType = PROD_CSK_L1D;
1481 : }
1482 :
1483 2 : CaptureCSKGeoTransform(productType);
1484 2 : CaptureCSKGeolocation(productType);
1485 2 : CaptureCSKGCPs(productType);
1486 :
1487 2 : break;
1488 : }
1489 49 : case UNKNOWN_PRODUCT:
1490 : {
1491 49 : constexpr int NBGCPLAT = 100;
1492 49 : constexpr int NBGCPLON = 30;
1493 :
1494 49 : const int nDeltaLat = nRasterYSize / NBGCPLAT;
1495 49 : const int nDeltaLon = nRasterXSize / NBGCPLON;
1496 :
1497 49 : if (nDeltaLat == 0 || nDeltaLon == 0)
1498 41 : return CE_None;
1499 :
1500 : // Create HDF5 Data Hierarchy in a link list.
1501 8 : poH5Objects = HDF5FindDatasetObjects(poH5RootGroup, "Latitude");
1502 8 : if (!poH5Objects)
1503 : {
1504 8 : if (GetMetadataItem("where_projdef") != nullptr)
1505 0 : return CreateODIMH5Projection();
1506 8 : return CE_None;
1507 : }
1508 :
1509 : // The Latitude and Longitude arrays must have a rank of 2 to
1510 : // retrieve GCPs.
1511 0 : if (poH5Objects->nRank != 2 ||
1512 0 : poH5Objects->paDims[0] != static_cast<size_t>(nRasterYSize) ||
1513 0 : poH5Objects->paDims[1] != static_cast<size_t>(nRasterXSize))
1514 : {
1515 0 : return CE_None;
1516 : }
1517 :
1518 : // Retrieve HDF5 data information.
1519 : const hid_t LatitudeDatasetID =
1520 0 : H5Dopen(m_hHDF5, poH5Objects->pszPath);
1521 : // LatitudeDataspaceID = H5Dget_space(dataset_id);
1522 :
1523 0 : poH5Objects = HDF5FindDatasetObjects(poH5RootGroup, "Longitude");
1524 : // GCPs.
1525 0 : if (poH5Objects == nullptr || poH5Objects->nRank != 2 ||
1526 0 : poH5Objects->paDims[0] != static_cast<size_t>(nRasterYSize) ||
1527 0 : poH5Objects->paDims[1] != static_cast<size_t>(nRasterXSize))
1528 : {
1529 0 : if (LatitudeDatasetID > 0)
1530 0 : H5Dclose(LatitudeDatasetID);
1531 0 : return CE_None;
1532 : }
1533 :
1534 : const hid_t LongitudeDatasetID =
1535 0 : H5Dopen(m_hHDF5, poH5Objects->pszPath);
1536 : // LongitudeDataspaceID = H5Dget_space(dataset_id);
1537 :
1538 0 : if (LatitudeDatasetID > 0 && LongitudeDatasetID > 0)
1539 : {
1540 : float *const Latitude =
1541 0 : static_cast<float *>(VSI_MALLOC3_VERBOSE(
1542 : nRasterYSize, nRasterXSize, sizeof(float)));
1543 : float *const Longitude =
1544 0 : static_cast<float *>(VSI_MALLOC3_VERBOSE(
1545 : nRasterYSize, nRasterXSize, sizeof(float)));
1546 0 : if (!Latitude || !Longitude)
1547 : {
1548 0 : CPLFree(Latitude);
1549 0 : CPLFree(Longitude);
1550 0 : H5Dclose(LatitudeDatasetID);
1551 0 : H5Dclose(LongitudeDatasetID);
1552 0 : return CE_Failure;
1553 : }
1554 0 : memset(Latitude, 0,
1555 0 : static_cast<size_t>(nRasterXSize) * nRasterYSize *
1556 : sizeof(float));
1557 0 : memset(Longitude, 0,
1558 0 : static_cast<size_t>(nRasterXSize) * nRasterYSize *
1559 : sizeof(float));
1560 :
1561 : // netCDF convention for nodata
1562 0 : double dfLatNoData = 0;
1563 0 : bool bHasLatNoData = GH5_FetchAttribute(
1564 : LatitudeDatasetID, "_FillValue", dfLatNoData);
1565 :
1566 0 : double dfLongNoData = 0;
1567 0 : bool bHasLongNoData = GH5_FetchAttribute(
1568 : LongitudeDatasetID, "_FillValue", dfLongNoData);
1569 :
1570 0 : H5Dread(LatitudeDatasetID, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL,
1571 : H5P_DEFAULT, Latitude);
1572 :
1573 0 : H5Dread(LongitudeDatasetID, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL,
1574 : H5P_DEFAULT, Longitude);
1575 :
1576 0 : m_oSRS.Clear();
1577 0 : m_oGCPSRS.SetWellKnownGeogCS("WGS84");
1578 :
1579 0 : const int nYLimit =
1580 0 : (static_cast<int>(nRasterYSize) / nDeltaLat) * nDeltaLat;
1581 0 : const int nXLimit =
1582 0 : (static_cast<int>(nRasterXSize) / nDeltaLon) * nDeltaLon;
1583 :
1584 : // The original code in
1585 : // https://trac.osgeo.org/gdal/changeset/8066 always add +180 to
1586 : // the longitudes, but without justification I suspect this
1587 : // might be due to handling products crossing the antimeridian.
1588 : // Trying to do it just when needed through a heuristics.
1589 0 : bool bHasLonNearMinus180 = false;
1590 0 : bool bHasLonNearPlus180 = false;
1591 0 : bool bHasLonNearZero = false;
1592 0 : for (int j = 0; j < nYLimit; j += nDeltaLat)
1593 : {
1594 0 : for (int i = 0; i < nXLimit; i += nDeltaLon)
1595 : {
1596 0 : const int iGCP = j * nRasterXSize + i;
1597 0 : if ((bHasLatNoData && static_cast<float>(dfLatNoData) ==
1598 0 : Latitude[iGCP]) ||
1599 0 : (bHasLongNoData &&
1600 0 : static_cast<float>(dfLongNoData) ==
1601 0 : Longitude[iGCP]))
1602 0 : continue;
1603 0 : if (Longitude[iGCP] > 170 && Longitude[iGCP] <= 180)
1604 0 : bHasLonNearPlus180 = true;
1605 0 : if (Longitude[iGCP] < -170 && Longitude[iGCP] >= -180)
1606 0 : bHasLonNearMinus180 = true;
1607 0 : if (fabs(Longitude[iGCP]) < 90)
1608 0 : bHasLonNearZero = true;
1609 : }
1610 : }
1611 :
1612 : // Fill the GCPs list.
1613 : const char *pszShiftGCP =
1614 0 : CPLGetConfigOption("HDF5_SHIFT_GCPX_BY_180", nullptr);
1615 : const bool bAdd180 =
1616 0 : (bHasLonNearPlus180 && bHasLonNearMinus180 &&
1617 0 : !bHasLonNearZero && pszShiftGCP == nullptr) ||
1618 0 : (pszShiftGCP != nullptr && CPLTestBool(pszShiftGCP));
1619 :
1620 0 : for (int j = 0; j < nYLimit; j += nDeltaLat)
1621 : {
1622 0 : for (int i = 0; i < nXLimit; i += nDeltaLon)
1623 : {
1624 0 : const int iGCP = j * nRasterXSize + i;
1625 0 : if ((bHasLatNoData && static_cast<float>(dfLatNoData) ==
1626 0 : Latitude[iGCP]) ||
1627 0 : (bHasLongNoData &&
1628 0 : static_cast<float>(dfLongNoData) ==
1629 0 : Longitude[iGCP]))
1630 0 : continue;
1631 0 : double dfGCPX = static_cast<double>(Longitude[iGCP]);
1632 0 : if (bAdd180)
1633 0 : dfGCPX += 180.0;
1634 0 : const double dfGCPY =
1635 0 : static_cast<double>(Latitude[iGCP]);
1636 :
1637 0 : m_aoGCPs.emplace_back("", "", i + 0.5, j + 0.5, dfGCPX,
1638 0 : dfGCPY);
1639 : }
1640 : }
1641 :
1642 0 : CPLFree(Latitude);
1643 0 : CPLFree(Longitude);
1644 : }
1645 :
1646 0 : if (LatitudeDatasetID > 0)
1647 0 : H5Dclose(LatitudeDatasetID);
1648 0 : if (LongitudeDatasetID > 0)
1649 0 : H5Dclose(LongitudeDatasetID);
1650 :
1651 0 : break;
1652 : }
1653 : }
1654 :
1655 2 : return CE_None;
1656 : }
1657 :
1658 : /************************************************************************/
1659 : /* GetMetadataItem() */
1660 : /************************************************************************/
1661 :
1662 120 : const char *HDF5ImageDataset::GetMetadataItem(const char *pszName,
1663 : const char *pszDomain)
1664 : {
1665 120 : if (pszDomain && EQUAL(pszDomain, "__DEBUG__") &&
1666 66 : EQUAL(pszName, "WholeBandChunkOptim"))
1667 : {
1668 66 : switch (m_eWholeBandChunkOptim)
1669 : {
1670 4 : case WBC_DETECTION_IN_PROGRESS:
1671 4 : return "DETECTION_IN_PROGRESS";
1672 3 : case WBC_DISABLED:
1673 3 : return "DISABLED";
1674 59 : case WBC_ENABLED:
1675 59 : return "ENABLED";
1676 : }
1677 : }
1678 54 : return GDALPamDataset::GetMetadataItem(pszName, pszDomain);
1679 : }
1680 :
1681 : /************************************************************************/
1682 : /* GetSpatialRef() */
1683 : /************************************************************************/
1684 :
1685 12 : const OGRSpatialReference *HDF5ImageDataset::GetSpatialRef() const
1686 : {
1687 12 : if (!m_oSRS.IsEmpty())
1688 11 : return &m_oSRS;
1689 1 : return GDALPamDataset::GetSpatialRef();
1690 : }
1691 :
1692 : /************************************************************************/
1693 : /* GetGCPCount() */
1694 : /************************************************************************/
1695 :
1696 3 : int HDF5ImageDataset::GetGCPCount()
1697 :
1698 : {
1699 3 : if (!m_aoGCPs.empty())
1700 1 : return static_cast<int>(m_aoGCPs.size());
1701 :
1702 2 : return GDALPamDataset::GetGCPCount();
1703 : }
1704 :
1705 : /************************************************************************/
1706 : /* GetGCPSpatialRef() */
1707 : /************************************************************************/
1708 :
1709 1 : const OGRSpatialReference *HDF5ImageDataset::GetGCPSpatialRef() const
1710 :
1711 : {
1712 1 : if (!m_aoGCPs.empty() && !m_oGCPSRS.IsEmpty())
1713 1 : return &m_oGCPSRS;
1714 :
1715 0 : return GDALPamDataset::GetGCPSpatialRef();
1716 : }
1717 :
1718 : /************************************************************************/
1719 : /* GetGCPs() */
1720 : /************************************************************************/
1721 :
1722 2 : const GDAL_GCP *HDF5ImageDataset::GetGCPs()
1723 : {
1724 2 : if (!m_aoGCPs.empty())
1725 1 : return gdal::GCP::c_ptr(m_aoGCPs);
1726 :
1727 1 : return GDALPamDataset::GetGCPs();
1728 : }
1729 :
1730 : /************************************************************************/
1731 : /* GetGeoTransform() */
1732 : /************************************************************************/
1733 :
1734 6 : CPLErr HDF5ImageDataset::GetGeoTransform(double *padfTransform)
1735 : {
1736 6 : if (bHasGeoTransform)
1737 : {
1738 5 : memcpy(padfTransform, adfGeoTransform, sizeof(double) * 6);
1739 5 : return CE_None;
1740 : }
1741 :
1742 1 : return GDALPamDataset::GetGeoTransform(padfTransform);
1743 : }
1744 :
1745 : /************************************************************************/
1746 : /* IdentifyProductType() */
1747 : /************************************************************************/
1748 :
1749 : /**
1750 : * Identify if the subdataset has a known product format
1751 : * It stores a product identifier in iSubdatasetType,
1752 : * UNKNOWN_PRODUCT, if it isn't a recognizable format.
1753 : */
1754 57 : void HDF5ImageDataset::IdentifyProductType()
1755 : {
1756 57 : iSubdatasetType = UNKNOWN_PRODUCT;
1757 :
1758 : // COSMO-SKYMED
1759 :
1760 : // Get the Mission Id as a char *, because the field may not exist.
1761 57 : const char *const pszMissionId = HDF5Dataset::GetMetadataItem("Mission_ID");
1762 :
1763 : // If there is a Mission_ID field.
1764 57 : if (pszMissionId != nullptr && strstr(GetDescription(), "QLK") == nullptr)
1765 : {
1766 : // Check if the mission type is CSK, KMPS or CSG.
1767 : // KMPS: Komsat-5 is Korean mission with a SAR instrument.
1768 : // CSG: Cosmo Skymed 2nd Generation
1769 2 : if (EQUAL(pszMissionId, "CSK") || EQUAL(pszMissionId, "KMPS") ||
1770 0 : EQUAL(pszMissionId, "CSG"))
1771 : {
1772 2 : iSubdatasetType = CSK_PRODUCT;
1773 :
1774 2 : if (GetMetadataItem("Product_Type") != nullptr)
1775 : {
1776 : // Get the format's level.
1777 : const char *osMissionLevel =
1778 2 : HDF5Dataset::GetMetadataItem("Product_Type");
1779 :
1780 2 : if (STARTS_WITH_CI(osMissionLevel, "RAW"))
1781 0 : iCSKProductType = PROD_CSK_L0;
1782 :
1783 2 : if (STARTS_WITH_CI(osMissionLevel, "SCS"))
1784 0 : iCSKProductType = PROD_CSK_L1A;
1785 :
1786 2 : if (STARTS_WITH_CI(osMissionLevel, "DGM"))
1787 1 : iCSKProductType = PROD_CSK_L1B;
1788 :
1789 2 : if (STARTS_WITH_CI(osMissionLevel, "GEC"))
1790 1 : iCSKProductType = PROD_CSK_L1C;
1791 :
1792 2 : if (STARTS_WITH_CI(osMissionLevel, "GTC"))
1793 0 : iCSKProductType = PROD_CSK_L1D;
1794 : }
1795 : }
1796 : }
1797 57 : }
1798 :
1799 : /************************************************************************/
1800 : /* CaptureCSKGeolocation() */
1801 : /************************************************************************/
1802 :
1803 : /**
1804 : * Captures Geolocation information from a COSMO-SKYMED
1805 : * file.
1806 : * The geoid will always be WGS84
1807 : * The projection type may be UTM or UPS, depending on the
1808 : * latitude from the center of the image.
1809 : * @param iProductType type of CSK subproduct, see HDF5CSKProduct
1810 : */
1811 2 : void HDF5ImageDataset::CaptureCSKGeolocation(int iProductType)
1812 : {
1813 : // Set the ellipsoid to WGS84.
1814 2 : m_oSRS.SetWellKnownGeogCS("WGS84");
1815 :
1816 2 : if (iProductType == PROD_CSK_L1C || iProductType == PROD_CSK_L1D)
1817 : {
1818 1 : double *dfProjFalseEastNorth = nullptr;
1819 1 : double *dfProjScaleFactor = nullptr;
1820 1 : double *dfCenterCoord = nullptr;
1821 :
1822 : // Check if all the metadata attributes are present.
1823 1 : if (HDF5ReadDoubleAttr("Map Projection False East-North",
1824 1 : &dfProjFalseEastNorth) == CE_Failure ||
1825 1 : HDF5ReadDoubleAttr("Map Projection Scale Factor",
1826 1 : &dfProjScaleFactor) == CE_Failure ||
1827 1 : HDF5ReadDoubleAttr("Map Projection Centre", &dfCenterCoord) ==
1828 2 : CE_Failure ||
1829 1 : GetMetadataItem("Projection_ID") == nullptr)
1830 : {
1831 0 : m_oSRS.Clear();
1832 0 : m_oGCPSRS.Clear();
1833 0 : CPLError(CE_Failure, CPLE_OpenFailed,
1834 : "The CSK hdf5 file geolocation information is "
1835 : "malformed");
1836 : }
1837 : else
1838 : {
1839 : // Fetch projection Type.
1840 2 : CPLString osProjectionID = GetMetadataItem("Projection_ID");
1841 :
1842 : // If the projection is UTM.
1843 1 : if (EQUAL(osProjectionID, "UTM"))
1844 : {
1845 : // @TODO: use SetUTM
1846 1 : m_oSRS.SetProjCS(SRS_PT_TRANSVERSE_MERCATOR);
1847 1 : m_oSRS.SetTM(dfCenterCoord[0], dfCenterCoord[1],
1848 : dfProjScaleFactor[0], dfProjFalseEastNorth[0],
1849 1 : dfProjFalseEastNorth[1]);
1850 : }
1851 : else
1852 : {
1853 : // TODO: No UPS projected files to test!
1854 : // If the projection is UPS.
1855 0 : if (EQUAL(osProjectionID, "UPS"))
1856 : {
1857 0 : m_oSRS.SetProjCS(SRS_PT_POLAR_STEREOGRAPHIC);
1858 0 : m_oSRS.SetPS(dfCenterCoord[0], dfCenterCoord[1],
1859 : dfProjScaleFactor[0], dfProjFalseEastNorth[0],
1860 0 : dfProjFalseEastNorth[1]);
1861 : }
1862 : }
1863 :
1864 1 : CPLFree(dfCenterCoord);
1865 1 : CPLFree(dfProjScaleFactor);
1866 1 : CPLFree(dfProjFalseEastNorth);
1867 1 : }
1868 : }
1869 : else
1870 : {
1871 1 : m_oGCPSRS = m_oSRS;
1872 : }
1873 2 : }
1874 :
1875 : /************************************************************************/
1876 : /* CaptureCSKGeoTransform() */
1877 : /************************************************************************/
1878 :
1879 : /**
1880 : * Get Geotransform information for COSMO-SKYMED files
1881 : * In case of success it stores the transformation
1882 : * in adfGeoTransform. In case of failure it doesn't
1883 : * modify adfGeoTransform
1884 : * @param iProductType type of CSK subproduct, see HDF5CSKProduct
1885 : */
1886 2 : void HDF5ImageDataset::CaptureCSKGeoTransform(int iProductType)
1887 : {
1888 2 : const char *pszSubdatasetName = GetSubdatasetName();
1889 :
1890 2 : bHasGeoTransform = false;
1891 : // If the product level is not L1C or L1D then
1892 : // it doesn't have a valid projection.
1893 2 : if (iProductType == PROD_CSK_L1C || iProductType == PROD_CSK_L1D)
1894 : {
1895 : // If there is a subdataset.
1896 1 : if (pszSubdatasetName != nullptr)
1897 : {
1898 2 : CPLString osULPath = pszSubdatasetName;
1899 1 : osULPath += "/Top Left East-North";
1900 :
1901 2 : CPLString osLineSpacingPath = pszSubdatasetName;
1902 1 : osLineSpacingPath += "/Line Spacing";
1903 :
1904 2 : CPLString osColumnSpacingPath = pszSubdatasetName;
1905 1 : osColumnSpacingPath += "/Column Spacing";
1906 :
1907 1 : double *pdOutUL = nullptr;
1908 1 : double *pdLineSpacing = nullptr;
1909 1 : double *pdColumnSpacing = nullptr;
1910 :
1911 : // If it could find the attributes on the metadata.
1912 1 : if (HDF5ReadDoubleAttr(osULPath.c_str(), &pdOutUL) == CE_Failure ||
1913 1 : HDF5ReadDoubleAttr(osLineSpacingPath.c_str(), &pdLineSpacing) ==
1914 2 : CE_Failure ||
1915 1 : HDF5ReadDoubleAttr(osColumnSpacingPath.c_str(),
1916 : &pdColumnSpacing) == CE_Failure)
1917 : {
1918 0 : bHasGeoTransform = false;
1919 : }
1920 : else
1921 : {
1922 : // geotransform[1] : width of pixel
1923 : // geotransform[4] : rotational coefficient, zero for north up
1924 : // images.
1925 : // geotransform[2] : rotational coefficient, zero for north up
1926 : // images.
1927 : // geotransform[5] : height of pixel (but negative)
1928 :
1929 1 : adfGeoTransform[0] = pdOutUL[0];
1930 1 : adfGeoTransform[1] = pdLineSpacing[0];
1931 1 : adfGeoTransform[2] = 0;
1932 1 : adfGeoTransform[3] = pdOutUL[1];
1933 1 : adfGeoTransform[4] = 0;
1934 1 : adfGeoTransform[5] = -pdColumnSpacing[0];
1935 :
1936 1 : CPLFree(pdOutUL);
1937 1 : CPLFree(pdLineSpacing);
1938 1 : CPLFree(pdColumnSpacing);
1939 :
1940 1 : bHasGeoTransform = true;
1941 : }
1942 : }
1943 : }
1944 2 : }
1945 :
1946 : /************************************************************************/
1947 : /* CaptureCSKGCPs() */
1948 : /************************************************************************/
1949 :
1950 : /**
1951 : * Retrieves and stores the GCPs from a COSMO-SKYMED dataset
1952 : * It only retrieves the GCPs for L0, L1A and L1B products
1953 : * for L1C and L1D products, geotransform is provided.
1954 : * The GCPs provided will be the Image's corners.
1955 : * @param iProductType type of CSK product @see HDF5CSKProductEnum
1956 : */
1957 2 : void HDF5ImageDataset::CaptureCSKGCPs(int iProductType)
1958 : {
1959 : // Only retrieve GCPs for L0,L1A and L1B products.
1960 2 : if (iProductType == PROD_CSK_L0 || iProductType == PROD_CSK_L1A ||
1961 : iProductType == PROD_CSK_L1B)
1962 : {
1963 10 : CPLString osCornerName[4];
1964 1 : double pdCornerPixel[4] = {0.0, 0.0, 0.0, 0.0};
1965 1 : double pdCornerLine[4] = {0.0, 0.0, 0.0, 0.0};
1966 :
1967 1 : const char *const pszSubdatasetName = GetSubdatasetName();
1968 :
1969 : // Load the subdataset name first.
1970 5 : for (int i = 0; i < 4; i++)
1971 4 : osCornerName[i] = pszSubdatasetName;
1972 :
1973 : // Load the attribute name, and raster coordinates for
1974 : // all the corners.
1975 1 : osCornerName[0] += "/Top Left Geodetic Coordinates";
1976 1 : pdCornerPixel[0] = 0;
1977 1 : pdCornerLine[0] = 0;
1978 :
1979 1 : osCornerName[1] += "/Top Right Geodetic Coordinates";
1980 1 : pdCornerPixel[1] = GetRasterXSize();
1981 1 : pdCornerLine[1] = 0;
1982 :
1983 1 : osCornerName[2] += "/Bottom Left Geodetic Coordinates";
1984 1 : pdCornerPixel[2] = 0;
1985 1 : pdCornerLine[2] = GetRasterYSize();
1986 :
1987 1 : osCornerName[3] += "/Bottom Right Geodetic Coordinates";
1988 1 : pdCornerPixel[3] = GetRasterXSize();
1989 1 : pdCornerLine[3] = GetRasterYSize();
1990 :
1991 : // For all the image's corners.
1992 5 : for (int i = 0; i < 4; i++)
1993 : {
1994 4 : double *pdCornerCoordinates = nullptr;
1995 :
1996 : // Retrieve the attributes.
1997 4 : if (HDF5ReadDoubleAttr(osCornerName[i].c_str(),
1998 4 : &pdCornerCoordinates) == CE_Failure)
1999 : {
2000 0 : CPLError(CE_Failure, CPLE_OpenFailed,
2001 : "Error retrieving CSK GCPs");
2002 0 : m_aoGCPs.clear();
2003 0 : break;
2004 : }
2005 :
2006 0 : m_aoGCPs.emplace_back(osCornerName[i].c_str(), "", pdCornerPixel[i],
2007 4 : pdCornerLine[i],
2008 4 : /* X = */ pdCornerCoordinates[1],
2009 : /* Y = */ pdCornerCoordinates[0],
2010 4 : /* Z = */ pdCornerCoordinates[2]);
2011 :
2012 : // Free the returned coordinates.
2013 4 : CPLFree(pdCornerCoordinates);
2014 : }
2015 : }
2016 2 : }
|