LCOV - code coverage report
Current view: top level - frmts/hdf5 - hdf5imagedataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 691 884 78.2 %
Date: 2025-07-09 17:50:03 Functions: 32 33 97.0 %

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

Generated by: LCOV version 1.14