LCOV - code coverage report
Current view: top level - frmts/gti - gdaltileindexdataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 2218 2400 92.4 %
Date: 2025-12-21 22:14:19 Functions: 64 64 100.0 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  Virtual GDAL Datasets
       4             :  * Purpose:  Tile index based VRT
       5             :  * Author:   Even Rouault <even dot rouault at spatialys.com>
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2023, Even Rouault <even dot rouault at spatialys.com>
       9             :  *
      10             :  * SPDX-License-Identifier: MIT
      11             :  ****************************************************************************/
      12             : 
      13             : /*! @cond Doxygen_Suppress */
      14             : 
      15             : #include <array>
      16             : #include <algorithm>
      17             : #include <atomic>
      18             : #include <cmath>
      19             : #include <limits>
      20             : #include <mutex>
      21             : #include <set>
      22             : #include <tuple>
      23             : #include <utility>
      24             : #include <vector>
      25             : 
      26             : #include "cpl_port.h"
      27             : #include "cpl_error_internal.h"
      28             : #include "cpl_json.h"
      29             : #include "cpl_mem_cache.h"
      30             : #include "cpl_minixml.h"
      31             : #include "cpl_quad_tree.h"
      32             : #include "vrtdataset.h"
      33             : #include "vrt_priv.h"
      34             : #include "ogrsf_frmts.h"
      35             : #include "ogrwarpedlayer.h"
      36             : #include "gdal_frmts.h"
      37             : #include "gdal_proxy.h"
      38             : #include "gdalsubdatasetinfo.h"
      39             : #include "gdal_thread_pool.h"
      40             : #include "gdal_utils.h"
      41             : 
      42             : #include "gdalalg_raster_index.h"
      43             : 
      44             : #ifdef USE_NEON_OPTIMIZATIONS
      45             : #define USE_SSE2_OPTIM
      46             : #define USE_SSE41_OPTIM
      47             : #include "include_sse2neon.h"
      48             : #elif defined(__SSE2__) || defined(_M_X64)
      49             : #define USE_SSE2_OPTIM
      50             : #include <emmintrin.h>
      51             : // MSVC doesn't define __SSE4_1__, but if -arch:AVX2 is enabled, we do have SSE4.1
      52             : #if defined(__SSE4_1__) || defined(__AVX2__)
      53             : #define USE_SSE41_OPTIM
      54             : #include <smmintrin.h>
      55             : #endif
      56             : #endif
      57             : 
      58             : #ifndef _
      59             : #define _(x) (x)
      60             : #endif
      61             : 
      62             : // Semantincs of indices of a GeoTransform (double[6]) matrix
      63             : constexpr int GT_TOPLEFT_X = 0;
      64             : constexpr int GT_WE_RES = 1;
      65             : constexpr int GT_ROTATION_PARAM1 = 2;
      66             : constexpr int GT_TOPLEFT_Y = 3;
      67             : constexpr int GT_ROTATION_PARAM2 = 4;
      68             : constexpr int GT_NS_RES = 5;
      69             : 
      70             : constexpr const char *GTI_PREFIX = "GTI:";
      71             : 
      72             : constexpr const char *MD_DS_TILE_INDEX_LAYER = "TILE_INDEX_LAYER";
      73             : constexpr const char *MD_DS_TILE_INDEX_SQL = "TILE_INDEX_SQL";
      74             : constexpr const char *MD_DS_TILE_INDEX_SPATIAL_SQL = "TILE_INDEX_SPATIAL_SQL";
      75             : 
      76             : constexpr const char *MD_RESX = "RESX";
      77             : constexpr const char *MD_RESY = "RESY";
      78             : constexpr const char *MD_BAND_COUNT = "BAND_COUNT";
      79             : constexpr const char *MD_DATA_TYPE = "DATA_TYPE";
      80             : constexpr const char *MD_NODATA = "NODATA";
      81             : constexpr const char *MD_MINX = "MINX";
      82             : constexpr const char *MD_MINY = "MINY";
      83             : constexpr const char *MD_MAXX = "MAXX";
      84             : constexpr const char *MD_MAXY = "MAXY";
      85             : constexpr const char *MD_GEOTRANSFORM = "GEOTRANSFORM";
      86             : constexpr const char *MD_XSIZE = "XSIZE";
      87             : constexpr const char *MD_YSIZE = "YSIZE";
      88             : constexpr const char *MD_COLOR_INTERPRETATION = "COLOR_INTERPRETATION";
      89             : constexpr const char *MD_SRS = "SRS";
      90             : constexpr const char *MD_LOCATION_FIELD = "LOCATION_FIELD";
      91             : constexpr const char *MD_SORT_FIELD = "SORT_FIELD";
      92             : constexpr const char *MD_SORT_FIELD_ASC = "SORT_FIELD_ASC";
      93             : constexpr const char *MD_BLOCK_X_SIZE = "BLOCKXSIZE";
      94             : constexpr const char *MD_BLOCK_Y_SIZE = "BLOCKYSIZE";
      95             : constexpr const char *MD_MASK_BAND = "MASK_BAND";
      96             : constexpr const char *MD_RESAMPLING = "RESAMPLING";
      97             : 
      98             : constexpr const char *const apszTIOptions[] = {MD_RESX,
      99             :                                                MD_RESY,
     100             :                                                MD_BAND_COUNT,
     101             :                                                MD_DATA_TYPE,
     102             :                                                MD_NODATA,
     103             :                                                MD_MINX,
     104             :                                                MD_MINY,
     105             :                                                MD_MAXX,
     106             :                                                MD_MAXY,
     107             :                                                MD_GEOTRANSFORM,
     108             :                                                MD_XSIZE,
     109             :                                                MD_YSIZE,
     110             :                                                MD_COLOR_INTERPRETATION,
     111             :                                                MD_SRS,
     112             :                                                MD_LOCATION_FIELD,
     113             :                                                MD_SORT_FIELD,
     114             :                                                MD_SORT_FIELD_ASC,
     115             :                                                MD_BLOCK_X_SIZE,
     116             :                                                MD_BLOCK_Y_SIZE,
     117             :                                                MD_MASK_BAND,
     118             :                                                MD_RESAMPLING};
     119             : 
     120             : constexpr const char *const MD_BAND_OFFSET = "OFFSET";
     121             : constexpr const char *const MD_BAND_SCALE = "SCALE";
     122             : constexpr const char *const MD_BAND_UNITTYPE = "UNITTYPE";
     123             : constexpr const char *const apszReservedBandItems[] = {
     124             :     MD_BAND_OFFSET, MD_BAND_SCALE, MD_BAND_UNITTYPE};
     125             : 
     126             : constexpr const char *GTI_XML_BANDCOUNT = "BandCount";
     127             : constexpr const char *GTI_XML_DATATYPE = "DataType";
     128             : constexpr const char *GTI_XML_NODATAVALUE = "NoDataValue";
     129             : constexpr const char *GTI_XML_COLORINTERP = "ColorInterp";
     130             : constexpr const char *GTI_XML_LOCATIONFIELD = "LocationField";
     131             : constexpr const char *GTI_XML_SORTFIELD = "SortField";
     132             : constexpr const char *GTI_XML_SORTFIELDASC = "SortFieldAsc";
     133             : constexpr const char *GTI_XML_MASKBAND = "MaskBand";
     134             : constexpr const char *GTI_XML_OVERVIEW_ELEMENT = "Overview";
     135             : constexpr const char *GTI_XML_OVERVIEW_DATASET = "Dataset";
     136             : constexpr const char *GTI_XML_OVERVIEW_LAYER = "Layer";
     137             : constexpr const char *GTI_XML_OVERVIEW_FACTOR = "Factor";
     138             : 
     139             : constexpr const char *GTI_XML_BAND_ELEMENT = "Band";
     140             : constexpr const char *GTI_XML_BAND_NUMBER = "band";
     141             : constexpr const char *GTI_XML_BAND_DATATYPE = "dataType";
     142             : constexpr const char *GTI_XML_BAND_DESCRIPTION = "Description";
     143             : constexpr const char *GTI_XML_BAND_OFFSET = "Offset";
     144             : constexpr const char *GTI_XML_BAND_SCALE = "Scale";
     145             : constexpr const char *GTI_XML_BAND_NODATAVALUE = "NoDataValue";
     146             : constexpr const char *GTI_XML_BAND_UNITTYPE = "UnitType";
     147             : constexpr const char *GTI_XML_BAND_COLORINTERP = "ColorInterp";
     148             : constexpr const char *GTI_XML_CATEGORYNAMES = "CategoryNames";
     149             : constexpr const char *GTI_XML_COLORTABLE = "ColorTable";
     150             : constexpr const char *GTI_XML_RAT = "GDALRasterAttributeTable";
     151             : 
     152             : /************************************************************************/
     153             : /*                           ENDS_WITH_CI()                             */
     154             : /************************************************************************/
     155             : 
     156       64993 : static inline bool ENDS_WITH_CI(const char *a, const char *b)
     157             : {
     158       64993 :     return strlen(a) >= strlen(b) && EQUAL(a + strlen(a) - strlen(b), b);
     159             : }
     160             : 
     161             : /************************************************************************/
     162             : /*                       GDALTileIndexDataset                           */
     163             : /************************************************************************/
     164             : 
     165             : class GDALTileIndexBand;
     166             : 
     167             : class GDALTileIndexDataset final : public GDALPamDataset
     168             : {
     169             :   public:
     170             :     GDALTileIndexDataset();
     171             :     ~GDALTileIndexDataset() override;
     172             : 
     173             :     bool Open(GDALOpenInfo *poOpenInfo);
     174             : 
     175             :     CPLErr FlushCache(bool bAtClosing) override;
     176             : 
     177             :     CPLErr GetGeoTransform(GDALGeoTransform &gt) const override;
     178             :     const OGRSpatialReference *GetSpatialRef() const override;
     179             : 
     180             :     CPLErr IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize,
     181             :                      int nYSize, void *pData, int nBufXSize, int nBufYSize,
     182             :                      GDALDataType eBufType, int nBandCount,
     183             :                      BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
     184             :                      GSpacing nLineSpace, GSpacing nBandSpace,
     185             :                      GDALRasterIOExtraArg *psExtraArg) override;
     186             : 
     187             :     const char *GetMetadataItem(const char *pszName,
     188             :                                 const char *pszDomain) override;
     189             :     CPLErr SetMetadataItem(const char *pszName, const char *pszValue,
     190             :                            const char *pszDomain) override;
     191             :     CPLErr SetMetadata(char **papszMD, const char *pszDomain) override;
     192             : 
     193             :     void LoadOverviews();
     194             : 
     195             :     std::vector<GTISourceDesc> GetSourcesMoreRecentThan(int64_t mTime);
     196             : 
     197             :   private:
     198             :     friend class GDALTileIndexBand;
     199             : 
     200             :     //! Optional GTI XML
     201             :     CPLXMLTreeCloser m_psXMLTree{nullptr};
     202             : 
     203             :     //! Whether the GTI XML might be modified (by SetMetadata/SetMetadataItem)
     204             :     bool m_bXMLUpdatable = false;
     205             : 
     206             :     //! Whether the GTI XML has been modified (by SetMetadata/SetMetadataItem)
     207             :     bool m_bXMLModified = false;
     208             : 
     209             :     //! Unique string (without the process) for this tile index. Passed to
     210             :     //! GDALProxyPoolDataset to ensure that sources are unique for a given owner
     211             :     const std::string m_osUniqueHandle;
     212             : 
     213             :     //! Vector dataset with the sources
     214             :     std::unique_ptr<GDALDataset> m_poVectorDS{};
     215             : 
     216             :     //! Generic SQL request to return features. May be empty.
     217             :     std::string m_osSQL{};
     218             : 
     219             :     //! SQL request to return features with placeholders for spatial filtering. May be empty
     220             :     std::string m_osSpatialSQL{};
     221             : 
     222             :     //! Vector layer with the sources
     223             :     OGRLayer *m_poLayer = nullptr;
     224             : 
     225             :     //! Whether m_poLayer should be freed with m_poVectorDS->ReleaseResultSet()
     226             :     bool m_bIsSQLResultLayer = false;
     227             : 
     228             :     //! When the SRS of m_poLayer is not the one we expose
     229             :     std::unique_ptr<OGRLayer> m_poWarpedLayerKeeper{};
     230             : 
     231             :     //! Geotransform matrix of the tile index
     232             :     GDALGeoTransform m_gt{};
     233             : 
     234             :     //! Index of the "location" (or alternate name given by user) field
     235             :     //! (within m_poLayer->GetLayerDefn()), that contain source dataset names.
     236             :     int m_nLocationFieldIndex = -1;
     237             : 
     238             :     //! SRS of the tile index.
     239             :     OGRSpatialReference m_oSRS{};
     240             : 
     241             :     //! Cache from dataset name to dataset handle.
     242             :     //! Note that the dataset objects are ultimately GDALProxyPoolDataset,
     243             :     //! and that the GDALProxyPoolDataset limits the number of simultaneously
     244             :     //! opened real datasets (controlled by GDAL_MAX_DATASET_POOL_SIZE). Hence 500 is not too big.
     245             :     lru11::Cache<std::string, std::shared_ptr<GDALDataset>> m_oMapSharedSources{
     246             :         500};
     247             : 
     248             :     //! Mask band (e.g. for JPEG compressed + mask band)
     249             :     std::unique_ptr<GDALTileIndexBand> m_poMaskBand{};
     250             : 
     251             :     //! Whether all bands of the tile index have the same data type.
     252             :     bool m_bSameDataType = true;
     253             : 
     254             :     //! Whether all bands of the tile index have the same nodata value.
     255             :     bool m_bSameNoData = true;
     256             : 
     257             :     //! Minimum X of the current pixel request, in georeferenced units.
     258             :     double m_dfLastMinXFilter = std::numeric_limits<double>::quiet_NaN();
     259             : 
     260             :     //! Minimum Y of the current pixel request, in georeferenced units.
     261             :     double m_dfLastMinYFilter = std::numeric_limits<double>::quiet_NaN();
     262             : 
     263             :     //! Maximum X of the current pixel request, in georeferenced units.
     264             :     double m_dfLastMaxXFilter = std::numeric_limits<double>::quiet_NaN();
     265             : 
     266             :     //! Maximum Y of the current pixel request, in georeferenced units.
     267             :     double m_dfLastMaxYFilter = std::numeric_limits<double>::quiet_NaN();
     268             : 
     269             :     //! Index of the field (within m_poLayer->GetLayerDefn()) used to sort, or -1 if none.
     270             :     int m_nSortFieldIndex = -1;
     271             : 
     272             :     //! Whether sorting must be ascending (true) or descending (false).
     273             :     bool m_bSortFieldAsc = true;
     274             : 
     275             :     //! Resampling method by default for warping or when a source has not
     276             :     //! the same resolution as the tile index.
     277             :     std::string m_osResampling = "near";
     278             :     GDALRIOResampleAlg m_eResampling = GRIORA_NearestNeighbour;
     279             : 
     280             :     //! WKT2 representation of the tile index SRS (if needed, typically for on-the-fly warping).
     281             :     std::string m_osWKT{};
     282             : 
     283             :     //! Whether we had to open of the sources at tile index opening.
     284             :     bool m_bScannedOneFeatureAtOpening = false;
     285             : 
     286             :     //! Array of overview descriptors.
     287             :     //! Each descriptor is a tuple (dataset_name, concatenated_open_options, layer_name, overview_factor).
     288             :     std::vector<std::tuple<std::string, CPLStringList, std::string, double>>
     289             :         m_aoOverviewDescriptor{};
     290             : 
     291             :     //! Array of overview datasets.
     292             :     std::vector<std::unique_ptr<GDALDataset>> m_apoOverviews{};
     293             : 
     294             :     //! Cache of buffers used by VRTComplexSource to avoid memory reallocation.
     295             :     VRTSource::WorkingState m_oWorkingState{};
     296             : 
     297             :     //! Used by IRasterIO() when using multi-threading
     298             :     struct QueueWorkingStates
     299             :     {
     300             :         std::mutex oMutex{};
     301             :         std::vector<std::unique_ptr<VRTSource::WorkingState>> oStates{};
     302             :     };
     303             : 
     304             :     //! Used by IRasterIO() when using multi-threading
     305             :     QueueWorkingStates m_oQueueWorkingStates{};
     306             : 
     307             :     //! Structure describing one of the source raster in the tile index.
     308             :     struct SourceDesc
     309             :     {
     310             :         //! Source dataset name.
     311             :         std::string osName{};
     312             : 
     313             :         //! Source dataset handle.
     314             :         std::shared_ptr<GDALDataset> poDS{};
     315             : 
     316             :         //! VRTSimpleSource or VRTComplexSource for the source.
     317             :         std::unique_ptr<VRTSimpleSource> poSource{};
     318             : 
     319             :         //! OGRFeature corresponding to the source in the tile index.
     320             :         std::unique_ptr<OGRFeature> poFeature{};
     321             : 
     322             :         //! Work buffer containing the value of the mask band for the current pixel query.
     323             :         mutable std::vector<GByte> abyMask{};
     324             : 
     325             :         //! Whether the source covers the whole area of interest of the current pixel query.
     326             :         bool bCoversWholeAOI = false;
     327             : 
     328             :         //! Whether the source has a nodata value at least in one of its band.
     329             :         bool bHasNoData = false;
     330             : 
     331             :         //! Whether all bands of the source have the same nodata value.
     332             :         bool bSameNoData = false;
     333             : 
     334             :         //! Nodata value of all bands (when bSameNoData == true).
     335             :         double dfSameNoData = 0;
     336             : 
     337             :         //! Mask band of the source.
     338             :         GDALRasterBand *poMaskBand = nullptr;
     339             :     };
     340             : 
     341             :     //! Array of sources participating to the current pixel query.
     342             :     std::vector<SourceDesc> m_aoSourceDesc{};
     343             : 
     344             :     //! Maximum number of threads. Updated by CollectSources().
     345             :     int m_nNumThreads = -1;
     346             : 
     347             :     //! Whereas the multi-threading rendering code path must be used. Updated by CollectSources().
     348             :     bool m_bLastMustUseMultiThreading = false;
     349             : 
     350             :     //! Whether the GTI file is a STAC collection
     351             :     bool m_bSTACCollection = false;
     352             : 
     353             :     //! From a source dataset name, return its SourceDesc description structure.
     354             :     bool GetSourceDesc(const std::string &osTileName, SourceDesc &oSourceDesc,
     355             :                        std::mutex *pMutex);
     356             : 
     357             :     //! Collect sources corresponding to the georeferenced window of interest,
     358             :     //! and store them in m_aoSourceDesc[].
     359             :     bool CollectSources(double dfXOff, double dfYOff, double dfXSize,
     360             :                         double dfYSize, bool bMultiThreadAllowed);
     361             : 
     362             :     //! Sort sources according to m_nSortFieldIndex.
     363             :     void SortSourceDesc();
     364             : 
     365             :     //! Whether the output buffer needs to be nodata initialized, or if
     366             :     //! sources are fully covering it.
     367             :     bool NeedInitBuffer(int nBandCount, const int *panBandMap) const;
     368             : 
     369             :     //! Nodata initialize the output buffer.
     370             :     void InitBuffer(void *pData, int nBufXSize, int nBufYSize,
     371             :                     GDALDataType eBufType, int nBandCount,
     372             :                     const int *panBandMap, GSpacing nPixelSpace,
     373             :                     GSpacing nLineSpace, GSpacing nBandSpace) const;
     374             : 
     375             :     //! Render one source. Used by IRasterIO()
     376             :     CPLErr RenderSource(const SourceDesc &oSourceDesc, bool bNeedInitBuffer,
     377             :                         int nBandNrMax, int nXOff, int nYOff, int nXSize,
     378             :                         int nYSize, double dfXOff, double dfYOff,
     379             :                         double dfXSize, double dfYSize, int nBufXSize,
     380             :                         int nBufYSize, void *pData, GDALDataType eBufType,
     381             :                         int nBandCount, BANDMAP_TYPE panBandMap,
     382             :                         GSpacing nPixelSpace, GSpacing nLineSpace,
     383             :                         GSpacing nBandSpace, GDALRasterIOExtraArg *psExtraArg,
     384             :                         VRTSource::WorkingState &oWorkingState) const;
     385             : 
     386             :     //! Whether m_poVectorDS supports SetMetadata()/SetMetadataItem()
     387             :     bool TileIndexSupportsEditingLayerMetadata() const;
     388             : 
     389             :     //! Return number of threads that can be used
     390             :     int GetNumThreads() const;
     391             : 
     392             :     /** Structure used to declare a threaded job to satisfy IRasterIO()
     393             :      * on a given source.
     394             :      */
     395             :     struct RasterIOJob
     396             :     {
     397             :         std::atomic<int> *pnCompletedJobs = nullptr;
     398             :         std::atomic<bool> *pbSuccess = nullptr;
     399             :         CPLErrorAccumulator *poErrorAccumulator = nullptr;
     400             :         GDALTileIndexDataset *poDS = nullptr;
     401             :         GDALTileIndexDataset::QueueWorkingStates *poQueueWorkingStates =
     402             :             nullptr;
     403             :         int nBandNrMax = 0;
     404             :         bool bSTACCollection = false;
     405             : 
     406             :         int nXOff = 0;
     407             :         int nYOff = 0;
     408             :         int nXSize = 0;
     409             :         int nYSize = 0;
     410             :         void *pData = nullptr;
     411             :         int nBufXSize = 0;
     412             :         int nBufYSize = 0;
     413             :         int nBandCount = 0;
     414             :         BANDMAP_TYPE panBandMap = nullptr;
     415             :         GDALDataType eBufType = GDT_Unknown;
     416             :         GSpacing nPixelSpace = 0;
     417             :         GSpacing nLineSpace = 0;
     418             :         GSpacing nBandSpace = 0;
     419             :         GDALRasterIOExtraArg *psExtraArg = nullptr;
     420             : 
     421             :         std::string osTileName{};
     422             : 
     423             :         static void Func(void *pData);
     424             :     };
     425             : 
     426             :     CPL_DISALLOW_COPY_ASSIGN(GDALTileIndexDataset)
     427             : };
     428             : 
     429             : /************************************************************************/
     430             : /*                            GDALTileIndexBand                          */
     431             : /************************************************************************/
     432             : 
     433             : class GDALTileIndexBand final : public GDALPamRasterBand
     434             : {
     435             :   public:
     436             :     GDALTileIndexBand(GDALTileIndexDataset *poDSIn, int nBandIn,
     437             :                       GDALDataType eDT, int nBlockXSizeIn, int nBlockYSizeIn);
     438             : 
     439         105 :     double GetNoDataValue(int *pbHasNoData) override
     440             :     {
     441         105 :         if (pbHasNoData)
     442         102 :             *pbHasNoData = m_bNoDataValueSet;
     443         105 :         return m_dfNoDataValue;
     444             :     }
     445             : 
     446          58 :     GDALColorInterp GetColorInterpretation() override
     447             :     {
     448          58 :         return m_eColorInterp;
     449             :     }
     450             : 
     451             :     CPLErr IReadBlock(int nBlockXOff, int nBlockYOff, void *pData) override;
     452             : 
     453             :     CPLErr IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize,
     454             :                      int nYSize, void *pData, int nBufXSize, int nBufYSize,
     455             :                      GDALDataType eBufType, GSpacing nPixelSpace,
     456             :                      GSpacing nLineSpace,
     457             :                      GDALRasterIOExtraArg *psExtraArg) override;
     458             : 
     459             :     int IGetDataCoverageStatus(int nXOff, int nYOff, int nXSize, int nYSize,
     460             :                                int nMaskFlagStop, double *pdfDataPct) override;
     461             : 
     462          32 :     int GetMaskFlags() override
     463             :     {
     464          32 :         if (m_poDS->m_poMaskBand && m_poDS->m_poMaskBand.get() != this)
     465           4 :             return GMF_PER_DATASET;
     466          28 :         return GDALPamRasterBand::GetMaskFlags();
     467             :     }
     468             : 
     469          34 :     GDALRasterBand *GetMaskBand() override
     470             :     {
     471          34 :         if (m_poDS->m_poMaskBand && m_poDS->m_poMaskBand.get() != this)
     472           7 :             return m_poDS->m_poMaskBand.get();
     473          27 :         return GDALPamRasterBand::GetMaskBand();
     474             :     }
     475             : 
     476          13 :     double GetOffset(int *pbHasValue) override
     477             :     {
     478          13 :         int bHasValue = FALSE;
     479          13 :         double dfVal = GDALPamRasterBand::GetOffset(&bHasValue);
     480          13 :         if (bHasValue)
     481             :         {
     482           0 :             if (pbHasValue)
     483           0 :                 *pbHasValue = true;
     484           0 :             return dfVal;
     485             :         }
     486          13 :         if (pbHasValue)
     487          10 :             *pbHasValue = !std::isnan(m_dfOffset);
     488          13 :         return std::isnan(m_dfOffset) ? 0.0 : m_dfOffset;
     489             :     }
     490             : 
     491          13 :     double GetScale(int *pbHasValue) override
     492             :     {
     493          13 :         int bHasValue = FALSE;
     494          13 :         double dfVal = GDALPamRasterBand::GetScale(&bHasValue);
     495          13 :         if (bHasValue)
     496             :         {
     497           0 :             if (pbHasValue)
     498           0 :                 *pbHasValue = true;
     499           0 :             return dfVal;
     500             :         }
     501          13 :         if (pbHasValue)
     502          10 :             *pbHasValue = !std::isnan(m_dfScale);
     503          13 :         return std::isnan(m_dfScale) ? 1.0 : m_dfScale;
     504             :     }
     505             : 
     506           9 :     const char *GetUnitType() override
     507             :     {
     508           9 :         const char *pszVal = GDALPamRasterBand::GetUnitType();
     509           9 :         if (pszVal && *pszVal)
     510           0 :             return pszVal;
     511           9 :         return m_osUnit.c_str();
     512             :     }
     513             : 
     514           5 :     char **GetCategoryNames() override
     515             :     {
     516           5 :         return m_aosCategoryNames.List();
     517             :     }
     518             : 
     519          11 :     GDALColorTable *GetColorTable() override
     520             :     {
     521          11 :         return m_poColorTable.get();
     522             :     }
     523             : 
     524           5 :     GDALRasterAttributeTable *GetDefaultRAT() override
     525             :     {
     526           5 :         return m_poRAT.get();
     527             :     }
     528             : 
     529             :     int GetOverviewCount() override;
     530             :     GDALRasterBand *GetOverview(int iOvr) override;
     531             : 
     532             :     char **GetMetadataDomainList() override;
     533             :     const char *GetMetadataItem(const char *pszName,
     534             :                                 const char *pszDomain) override;
     535             :     CPLErr SetMetadataItem(const char *pszName, const char *pszValue,
     536             :                            const char *pszDomain) override;
     537             :     CPLErr SetMetadata(char **papszMD, const char *pszDomain) override;
     538             : 
     539             :   private:
     540             :     friend class GDALTileIndexDataset;
     541             : 
     542             :     //! Dataset that owns this band.
     543             :     GDALTileIndexDataset *m_poDS = nullptr;
     544             : 
     545             :     //! Whether a nodata value is set to this band.
     546             :     bool m_bNoDataValueSet = false;
     547             : 
     548             :     //! Nodata value.
     549             :     double m_dfNoDataValue = 0;
     550             : 
     551             :     //! Color interpretation.
     552             :     GDALColorInterp m_eColorInterp = GCI_Undefined;
     553             : 
     554             :     //! Cached value for GetMetadataItem("Pixel_X_Y", "LocationInfo").
     555             :     std::string m_osLastLocationInfo{};
     556             : 
     557             :     //! Scale value (returned by GetScale())
     558             :     double m_dfScale = std::numeric_limits<double>::quiet_NaN();
     559             : 
     560             :     //! Offset value (returned by GetOffset())
     561             :     double m_dfOffset = std::numeric_limits<double>::quiet_NaN();
     562             : 
     563             :     //! Unit type (returned by GetUnitType()).
     564             :     std::string m_osUnit{};
     565             : 
     566             :     //! Category names (returned by GetCategoryNames()).
     567             :     CPLStringList m_aosCategoryNames{};
     568             : 
     569             :     //! Color table (returned by GetColorTable()).
     570             :     std::unique_ptr<GDALColorTable> m_poColorTable{};
     571             : 
     572             :     //! Raster attribute table (returned by GetDefaultRAT()).
     573             :     std::unique_ptr<GDALRasterAttributeTable> m_poRAT{};
     574             : 
     575             :     CPL_DISALLOW_COPY_ASSIGN(GDALTileIndexBand)
     576             : };
     577             : 
     578             : /************************************************************************/
     579             : /*                        IsSameNaNAware()                              */
     580             : /************************************************************************/
     581             : 
     582         297 : static inline bool IsSameNaNAware(double a, double b)
     583             : {
     584         297 :     return a == b || (std::isnan(a) && std::isnan(b));
     585             : }
     586             : 
     587             : /************************************************************************/
     588             : /*                         GDALTileIndexDataset()                        */
     589             : /************************************************************************/
     590             : 
     591         280 : GDALTileIndexDataset::GDALTileIndexDataset()
     592         280 :     : m_osUniqueHandle(CPLSPrintf("%p", this))
     593             : {
     594         280 : }
     595             : 
     596             : /************************************************************************/
     597             : /*                        GetAbsoluteFileName()                         */
     598             : /************************************************************************/
     599             : 
     600         598 : static std::string GetAbsoluteFileName(const char *pszTileName,
     601             :                                        const char *pszVRTName,
     602             :                                        bool bIsStacCollection)
     603             : {
     604             :     std::string osRet =
     605        1794 :         bIsStacCollection ? VSIURIToVSIPath(pszTileName) : pszTileName;
     606         598 :     if (osRet != pszTileName)
     607           6 :         return osRet;
     608             : 
     609         592 :     if (CPLIsFilenameRelative(pszTileName) &&
     610         602 :         !STARTS_WITH(pszTileName, "<VRTDataset") &&
     611          10 :         !STARTS_WITH(pszVRTName, "<GDALTileIndexDataset"))
     612             :     {
     613          10 :         const auto oSubDSInfo(GDALGetSubdatasetInfo(pszTileName));
     614          10 :         if (oSubDSInfo && !oSubDSInfo->GetPathComponent().empty())
     615             :         {
     616           4 :             const std::string osPath(oSubDSInfo->GetPathComponent());
     617           2 :             osRet = CPLIsFilenameRelative(osPath.c_str())
     618           5 :                         ? oSubDSInfo->ModifyPathComponent(
     619           4 :                               CPLProjectRelativeFilenameSafe(
     620           3 :                                   CPLGetPathSafe(pszVRTName).c_str(),
     621             :                                   osPath.c_str()))
     622           2 :                         : std::string(pszTileName);
     623           2 :             GDALDestroySubdatasetInfo(oSubDSInfo);
     624           2 :             return osRet;
     625             :         }
     626             : 
     627             :         std::string osRelativeMadeAbsolute = CPLProjectRelativeFilenameSafe(
     628           8 :             CPLGetPathSafe(pszVRTName).c_str(), pszTileName);
     629             :         VSIStatBufL sStat;
     630           8 :         if (VSIStatL(osRelativeMadeAbsolute.c_str(), &sStat) == 0)
     631           7 :             return osRelativeMadeAbsolute;
     632             :     }
     633         583 :     return pszTileName;
     634             : }
     635             : 
     636             : /************************************************************************/
     637             : /*                    GTIDoPaletteExpansionIfNeeded()                   */
     638             : /************************************************************************/
     639             : 
     640             : //! Do palette -> RGB(A) expansion
     641             : static bool
     642         464 : GTIDoPaletteExpansionIfNeeded(std::shared_ptr<GDALDataset> &poTileDS,
     643             :                               int nBandCount)
     644             : {
     645         739 :     if (poTileDS->GetRasterCount() == 1 &&
     646         741 :         (nBandCount == 3 || nBandCount == 4) &&
     647           4 :         poTileDS->GetRasterBand(1)->GetColorTable() != nullptr)
     648             :     {
     649             : 
     650           4 :         CPLStringList aosOptions;
     651           4 :         aosOptions.AddString("-of");
     652           4 :         aosOptions.AddString("VRT");
     653             : 
     654           4 :         aosOptions.AddString("-expand");
     655           4 :         aosOptions.AddString(nBandCount == 3 ? "rgb" : "rgba");
     656             : 
     657             :         GDALTranslateOptions *psOptions =
     658           4 :             GDALTranslateOptionsNew(aosOptions.List(), nullptr);
     659           4 :         int bUsageError = false;
     660             :         auto poRGBDS = std::unique_ptr<GDALDataset>(GDALDataset::FromHandle(
     661             :             GDALTranslate("", GDALDataset::ToHandle(poTileDS.get()), psOptions,
     662           4 :                           &bUsageError)));
     663           4 :         GDALTranslateOptionsFree(psOptions);
     664           4 :         if (!poRGBDS)
     665             :         {
     666           0 :             return false;
     667             :         }
     668             : 
     669           4 :         poTileDS.reset(poRGBDS.release());
     670             :     }
     671         464 :     return true;
     672             : }
     673             : 
     674             : /************************************************************************/
     675             : /*                                Open()                                */
     676             : /************************************************************************/
     677             : 
     678         280 : bool GDALTileIndexDataset::Open(GDALOpenInfo *poOpenInfo)
     679             : {
     680         280 :     eAccess = poOpenInfo->eAccess;
     681             : 
     682         280 :     CPLXMLNode *psRoot = nullptr;
     683         280 :     const char *pszIndexDataset = poOpenInfo->pszFilename;
     684             : 
     685         280 :     if (STARTS_WITH(poOpenInfo->pszFilename, GTI_PREFIX))
     686             :     {
     687          14 :         pszIndexDataset = poOpenInfo->pszFilename + strlen(GTI_PREFIX);
     688             :     }
     689         266 :     else if (STARTS_WITH(poOpenInfo->pszFilename, "<GDALTileIndexDataset"))
     690             :     {
     691             :         // CPLParseXMLString() emits an error in case of failure
     692          25 :         m_psXMLTree.reset(CPLParseXMLString(poOpenInfo->pszFilename));
     693          25 :         if (m_psXMLTree == nullptr)
     694           1 :             return false;
     695             :     }
     696         241 :     else if (poOpenInfo->nHeaderBytes > 0 &&
     697         241 :              strstr(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
     698             :                     "<GDALTileIndexDataset"))
     699             :     {
     700             :         // CPLParseXMLFile() emits an error in case of failure
     701           6 :         m_psXMLTree.reset(CPLParseXMLFile(poOpenInfo->pszFilename));
     702           6 :         if (m_psXMLTree == nullptr)
     703           1 :             return false;
     704           5 :         m_bXMLUpdatable = (poOpenInfo->eAccess == GA_Update);
     705             :     }
     706             : 
     707         278 :     if (m_psXMLTree)
     708             :     {
     709          29 :         psRoot = CPLGetXMLNode(m_psXMLTree.get(), "=GDALTileIndexDataset");
     710          29 :         if (psRoot == nullptr)
     711             :         {
     712           1 :             CPLError(CE_Failure, CPLE_AppDefined,
     713             :                      "Missing GDALTileIndexDataset root element.");
     714           1 :             return false;
     715             :         }
     716             : 
     717          28 :         pszIndexDataset = CPLGetXMLValue(psRoot, "IndexDataset", nullptr);
     718          28 :         if (!pszIndexDataset)
     719             :         {
     720           1 :             CPLError(CE_Failure, CPLE_AppDefined,
     721             :                      "Missing IndexDataset element.");
     722           1 :             return false;
     723             :         }
     724             :     }
     725             : 
     726         276 :     if (ENDS_WITH_CI(pszIndexDataset, ".gti.gpkg") &&
     727         514 :         poOpenInfo->nHeaderBytes >= 100 &&
     728         238 :         STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
     729             :                     "SQLite format 3"))
     730             :     {
     731         234 :         const char *const apszAllowedDrivers[] = {"GPKG", nullptr};
     732         234 :         m_poVectorDS.reset(GDALDataset::Open(
     733         468 :             std::string("GPKG:\"").append(pszIndexDataset).append("\"").c_str(),
     734         234 :             GDAL_OF_VECTOR | GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR |
     735         234 :                 ((poOpenInfo->nOpenFlags & GDAL_OF_UPDATE) ? GDAL_OF_UPDATE
     736             :                                                            : GDAL_OF_READONLY),
     737             :             apszAllowedDrivers));
     738         234 :         if (!m_poVectorDS)
     739             :         {
     740           1 :             return false;
     741             :         }
     742         236 :         if (m_poVectorDS->GetLayerCount() == 0 &&
     743           2 :             (m_poVectorDS->GetRasterCount() != 0 ||
     744           1 :              m_poVectorDS->GetMetadata("SUBDATASETS") != nullptr))
     745             :         {
     746           1 :             return false;
     747             :         }
     748             :     }
     749             :     else
     750             :     {
     751          42 :         m_poVectorDS.reset(GDALDataset::Open(
     752          42 :             pszIndexDataset, GDAL_OF_VECTOR | GDAL_OF_VERBOSE_ERROR |
     753          42 :                                  ((poOpenInfo->nOpenFlags & GDAL_OF_UPDATE)
     754          42 :                                       ? GDAL_OF_UPDATE
     755             :                                       : GDAL_OF_READONLY)));
     756          42 :         if (!m_poVectorDS)
     757             :         {
     758           1 :             return false;
     759             :         }
     760             :     }
     761             : 
     762         274 :     if (m_poVectorDS->GetLayerCount() == 0)
     763             :     {
     764           1 :         CPLError(CE_Failure, CPLE_AppDefined, "%s has no vector layer",
     765             :                  poOpenInfo->pszFilename);
     766           1 :         return false;
     767             :     }
     768             : 
     769         273 :     double dfOvrFactor = 1.0;
     770         273 :     if (const char *pszFactor =
     771         273 :             CSLFetchNameValue(poOpenInfo->papszOpenOptions, "FACTOR"))
     772             :     {
     773           5 :         dfOvrFactor = CPLAtof(pszFactor);
     774           5 :         if (!(dfOvrFactor > 1.0))
     775             :         {
     776           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Wrong overview factor");
     777           1 :             return false;
     778             :         }
     779             :     }
     780             : 
     781         272 :     m_osSQL = CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "SQL", "");
     782         272 :     if (m_osSQL.empty())
     783             :     {
     784         269 :         if (!psRoot)
     785             :         {
     786         243 :             if (const char *pszVal =
     787         243 :                     m_poVectorDS->GetMetadataItem(MD_DS_TILE_INDEX_SQL))
     788           0 :                 m_osSQL = pszVal;
     789             :         }
     790             :         else
     791          26 :             m_osSQL = CPLGetXMLValue(psRoot, "SQL", "");
     792             :     }
     793             : 
     794         272 :     if (!m_osSQL.empty())
     795             :     {
     796           5 :         m_osSpatialSQL = CSLFetchNameValueDef(poOpenInfo->papszOpenOptions,
     797           5 :                                               "SPATIAL_SQL", "");
     798           5 :         if (m_osSpatialSQL.empty())
     799             :         {
     800           3 :             if (!psRoot)
     801             :             {
     802           2 :                 if (const char *pszVal = m_poVectorDS->GetMetadataItem(
     803           1 :                         MD_DS_TILE_INDEX_SPATIAL_SQL))
     804           0 :                     m_osSpatialSQL = pszVal;
     805             :             }
     806             :             else
     807           2 :                 m_osSpatialSQL = CPLGetXMLValue(psRoot, "SpatialSQL", "");
     808             :         }
     809             :     }
     810             : 
     811             :     const char *pszLayerName;
     812             : 
     813         272 :     if ((pszLayerName = CSLFetchNameValue(poOpenInfo->papszOpenOptions,
     814         272 :                                           "LAYER")) != nullptr)
     815             :     {
     816           6 :         m_poLayer = m_poVectorDS->GetLayerByName(pszLayerName);
     817           6 :         if (!m_poLayer)
     818             :         {
     819           2 :             CPLError(CE_Failure, CPLE_AppDefined, "Layer %s does not exist",
     820             :                      pszLayerName);
     821           2 :             return false;
     822             :         }
     823             :     }
     824         266 :     else if (psRoot && (pszLayerName = CPLGetXMLValue(psRoot, "IndexLayer",
     825             :                                                       nullptr)) != nullptr)
     826             :     {
     827           8 :         m_poLayer = m_poVectorDS->GetLayerByName(pszLayerName);
     828           8 :         if (!m_poLayer)
     829             :         {
     830           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Layer %s does not exist",
     831             :                      pszLayerName);
     832           1 :             return false;
     833             :         }
     834             :     }
     835         502 :     else if (!psRoot && (pszLayerName = m_poVectorDS->GetMetadataItem(
     836         244 :                              MD_DS_TILE_INDEX_LAYER)) != nullptr)
     837             :     {
     838           2 :         m_poLayer = m_poVectorDS->GetLayerByName(pszLayerName);
     839           2 :         if (!m_poLayer)
     840             :         {
     841           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Layer %s does not exist",
     842             :                      pszLayerName);
     843           1 :             return false;
     844             :         }
     845             :     }
     846         256 :     else if (!m_osSQL.empty())
     847             :     {
     848           5 :         m_poLayer = m_poVectorDS->ExecuteSQL(m_osSQL.c_str(), nullptr, nullptr);
     849           5 :         if (!m_poLayer)
     850             :         {
     851           1 :             CPLError(CE_Failure, CPLE_AppDefined, "SQL request %s failed",
     852             :                      m_osSQL.c_str());
     853           1 :             return false;
     854             :         }
     855           4 :         m_bIsSQLResultLayer = true;
     856             :     }
     857         251 :     else if (m_poVectorDS->GetLayerCount() == 1)
     858             :     {
     859         249 :         m_poLayer = m_poVectorDS->GetLayer(0);
     860         249 :         if (!m_poLayer)
     861             :         {
     862           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Cannot open layer 0");
     863           0 :             return false;
     864             :         }
     865             :     }
     866             :     else
     867             :     {
     868           2 :         if (STARTS_WITH(poOpenInfo->pszFilename, GTI_PREFIX))
     869             :         {
     870           1 :             CPLError(CE_Failure, CPLE_AppDefined,
     871             :                      "%s has more than one layer. LAYER open option "
     872             :                      "must be defined to specify which one to "
     873             :                      "use as the tile index",
     874             :                      pszIndexDataset);
     875             :         }
     876           1 :         else if (psRoot)
     877             :         {
     878           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     879             :                      "%s has more than one layer. IndexLayer element must be "
     880             :                      "defined to specify which one to "
     881             :                      "use as the tile index",
     882             :                      pszIndexDataset);
     883             :         }
     884             :         else
     885             :         {
     886           1 :             CPLError(CE_Failure, CPLE_AppDefined,
     887             :                      "%s has more than one layer. %s "
     888             :                      "metadata item must be defined to specify which one to "
     889             :                      "use as the tile index",
     890             :                      pszIndexDataset, MD_DS_TILE_INDEX_LAYER);
     891             :         }
     892           2 :         return false;
     893             :     }
     894             : 
     895             :     // Try to get the metadata from an embedded xml:GTI domain
     896         265 :     if (!m_psXMLTree)
     897             :     {
     898         241 :         char **papszMD = m_poLayer->GetMetadata("xml:GTI");
     899         241 :         if (papszMD && papszMD[0])
     900             :         {
     901           1 :             m_psXMLTree.reset(CPLParseXMLString(papszMD[0]));
     902           1 :             if (m_psXMLTree == nullptr)
     903           0 :                 return false;
     904             : 
     905           1 :             psRoot = CPLGetXMLNode(m_psXMLTree.get(), "=GDALTileIndexDataset");
     906           1 :             if (psRoot == nullptr)
     907             :             {
     908           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
     909             :                          "Missing GDALTileIndexDataset root element.");
     910           0 :                 return false;
     911             :             }
     912             :         }
     913             :     }
     914             : 
     915             :     // Get the value of an option.
     916             :     // The order of lookup is the following one (first to last):
     917             :     // - open options
     918             :     // - XML file
     919             :     // - Layer metadata items.
     920       24078 :     const auto GetOption = [poOpenInfo, psRoot, this](const char *pszItem)
     921             :     {
     922             :         const char *pszVal =
     923        7669 :             CSLFetchNameValue(poOpenInfo->papszOpenOptions, pszItem);
     924        7669 :         if (pszVal)
     925          10 :             return pszVal;
     926             : 
     927        7659 :         if (psRoot)
     928             :         {
     929         576 :             pszVal = CPLGetXMLValue(psRoot, pszItem, nullptr);
     930         576 :             if (pszVal)
     931          27 :                 return pszVal;
     932             : 
     933         549 :             if (EQUAL(pszItem, MD_BAND_COUNT))
     934          22 :                 pszItem = GTI_XML_BANDCOUNT;
     935         527 :             else if (EQUAL(pszItem, MD_DATA_TYPE))
     936          25 :                 pszItem = GTI_XML_DATATYPE;
     937         502 :             else if (EQUAL(pszItem, MD_NODATA))
     938          20 :                 pszItem = GTI_XML_NODATAVALUE;
     939         482 :             else if (EQUAL(pszItem, MD_COLOR_INTERPRETATION))
     940          25 :                 pszItem = GTI_XML_COLORINTERP;
     941         457 :             else if (EQUAL(pszItem, MD_LOCATION_FIELD))
     942          25 :                 pszItem = GTI_XML_LOCATIONFIELD;
     943         432 :             else if (EQUAL(pszItem, MD_SORT_FIELD))
     944          25 :                 pszItem = GTI_XML_SORTFIELD;
     945         407 :             else if (EQUAL(pszItem, MD_SORT_FIELD_ASC))
     946           2 :                 pszItem = GTI_XML_SORTFIELDASC;
     947         405 :             else if (EQUAL(pszItem, MD_MASK_BAND))
     948          20 :                 pszItem = GTI_XML_MASKBAND;
     949         549 :             pszVal = CPLGetXMLValue(psRoot, pszItem, nullptr);
     950         549 :             if (pszVal)
     951           7 :                 return pszVal;
     952             :         }
     953             : 
     954        7625 :         return m_poLayer->GetMetadataItem(pszItem);
     955         265 :     };
     956             : 
     957         265 :     const char *pszFilter = GetOption("Filter");
     958         265 :     if (pszFilter)
     959             :     {
     960           1 :         if (m_poLayer->SetAttributeFilter(pszFilter) != OGRERR_NONE)
     961           0 :             return false;
     962             :     }
     963             : 
     964         265 :     const OGRFeatureDefn *poLayerDefn = m_poLayer->GetLayerDefn();
     965             : 
     966         530 :     std::string osLocationFieldName;
     967             :     {
     968         265 :         const char *pszLocationFieldName = GetOption(MD_LOCATION_FIELD);
     969         265 :         if (pszLocationFieldName)
     970             :         {
     971           4 :             osLocationFieldName = pszLocationFieldName;
     972             :         }
     973             :         else
     974             :         {
     975             :             // Is this a https://stac-utils.github.io/stac-geoparquet/latest/spec/stac-geoparquet-spec ?
     976         261 :             if (poLayerDefn->GetFieldIndex("assets.data.href") >= 0)
     977             :             {
     978           0 :                 m_bSTACCollection = true;
     979           0 :                 osLocationFieldName = "assets.data.href";
     980           0 :                 CPLDebug("GTI", "Using %s as location field",
     981             :                          osLocationFieldName.c_str());
     982             :             }
     983         261 :             else if (poLayerDefn->GetFieldIndex("assets.image.href") >= 0)
     984             :             {
     985           3 :                 m_bSTACCollection = true;
     986           3 :                 osLocationFieldName = "assets.image.href";
     987           3 :                 CPLDebug("GTI", "Using %s as location field",
     988             :                          osLocationFieldName.c_str());
     989             :             }
     990         512 :             else if (poLayerDefn->GetFieldIndex("stac_version") >= 0 ||
     991         254 :                      poLayerDefn->GetFieldIndex("stac_extensions") >= 0)
     992             :             {
     993           4 :                 m_bSTACCollection = true;
     994           4 :                 const int nFieldCount = poLayerDefn->GetFieldCount();
     995             :                 // Look for "assets.xxxxx.href" fields
     996           4 :                 int nAssetCount = 0;
     997          60 :                 for (int i = 0; i < nFieldCount; ++i)
     998             :                 {
     999          56 :                     const auto poFDefn = poLayerDefn->GetFieldDefn(i);
    1000          56 :                     const char *pszFieldName = poFDefn->GetNameRef();
    1001          56 :                     if (STARTS_WITH(pszFieldName, "assets.") &&
    1002          44 :                         EQUAL(pszFieldName + strlen(pszFieldName) -
    1003             :                                   strlen(".href"),
    1004           4 :                               ".href") &&
    1005             :                         // Assets with "metadata" in them are very much likely
    1006             :                         // not rasters... We could potentially confirm that by
    1007             :                         // inspecting the value of the assets.XXX.type or
    1008             :                         // assets.XXX.roles fields of one feature
    1009           4 :                         !strstr(pszFieldName, "metadata"))
    1010             :                     {
    1011           4 :                         ++nAssetCount;
    1012           4 :                         if (!osLocationFieldName.empty())
    1013             :                         {
    1014           0 :                             osLocationFieldName += ", ";
    1015             :                         }
    1016           4 :                         osLocationFieldName += pszFieldName;
    1017             :                     }
    1018             :                 }
    1019           4 :                 if (nAssetCount > 1)
    1020             :                 {
    1021           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    1022             :                              "Several potential STAC assets. Please select one "
    1023             :                              "among %s with the LOCATION_FIELD open option",
    1024             :                              osLocationFieldName.c_str());
    1025           0 :                     return false;
    1026             :                 }
    1027           4 :                 else if (nAssetCount == 0)
    1028             :                 {
    1029           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    1030             :                              "File has stac_version or stac_extensions "
    1031             :                              "property but lacks assets");
    1032           0 :                     return false;
    1033             :                 }
    1034             :             }
    1035             :             else
    1036             :             {
    1037         254 :                 constexpr const char *DEFAULT_LOCATION_FIELD_NAME = "location";
    1038         254 :                 osLocationFieldName = DEFAULT_LOCATION_FIELD_NAME;
    1039             :             }
    1040             :         }
    1041             :     }
    1042             : 
    1043         265 :     m_nLocationFieldIndex =
    1044         265 :         poLayerDefn->GetFieldIndex(osLocationFieldName.c_str());
    1045         265 :     if (m_nLocationFieldIndex < 0)
    1046             :     {
    1047           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Cannot find field %s",
    1048             :                  osLocationFieldName.c_str());
    1049           1 :         return false;
    1050             :     }
    1051         264 :     if (poLayerDefn->GetFieldDefn(m_nLocationFieldIndex)->GetType() !=
    1052             :         OFTString)
    1053             :     {
    1054           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Field %s is not of type string",
    1055             :                  osLocationFieldName.c_str());
    1056           1 :         return false;
    1057             :     }
    1058             : 
    1059         263 :     const char *pszSortFieldName = GetOption(MD_SORT_FIELD);
    1060         263 :     if (pszSortFieldName)
    1061             :     {
    1062          96 :         m_nSortFieldIndex = poLayerDefn->GetFieldIndex(pszSortFieldName);
    1063          96 :         if (m_nSortFieldIndex < 0)
    1064             :         {
    1065           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Cannot find field %s",
    1066             :                      pszSortFieldName);
    1067           1 :             return false;
    1068             :         }
    1069             : 
    1070             :         const auto eFieldType =
    1071          95 :             poLayerDefn->GetFieldDefn(m_nSortFieldIndex)->GetType();
    1072          95 :         if (eFieldType != OFTString && eFieldType != OFTInteger &&
    1073          61 :             eFieldType != OFTInteger64 && eFieldType != OFTReal &&
    1074          19 :             eFieldType != OFTDate && eFieldType != OFTDateTime)
    1075             :         {
    1076           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1077             :                      "Unsupported type for field %s", pszSortFieldName);
    1078           1 :             return false;
    1079             :         }
    1080             : 
    1081          94 :         const char *pszSortFieldAsc = GetOption(MD_SORT_FIELD_ASC);
    1082          94 :         if (pszSortFieldAsc)
    1083             :         {
    1084           3 :             m_bSortFieldAsc = CPLTestBool(pszSortFieldAsc);
    1085             :         }
    1086             :     }
    1087             : 
    1088         261 :     const char *pszResX = GetOption(MD_RESX);
    1089         261 :     const char *pszResY = GetOption(MD_RESY);
    1090         261 :     if (pszResX && !pszResY)
    1091             :     {
    1092           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    1093             :                  "%s metadata item defined, but not %s", MD_RESX, MD_RESY);
    1094           1 :         return false;
    1095             :     }
    1096         260 :     if (!pszResX && pszResY)
    1097             :     {
    1098           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    1099             :                  "%s metadata item defined, but not %s", MD_RESY, MD_RESX);
    1100           1 :         return false;
    1101             :     }
    1102             : 
    1103         259 :     const char *pszResampling = GetOption(MD_RESAMPLING);
    1104         259 :     if (pszResampling)
    1105             :     {
    1106           8 :         const auto nErrorCountBefore = CPLGetErrorCounter();
    1107           8 :         m_eResampling = GDALRasterIOGetResampleAlg(pszResampling);
    1108           8 :         if (nErrorCountBefore != CPLGetErrorCounter())
    1109             :         {
    1110           0 :             return false;
    1111             :         }
    1112           8 :         m_osResampling = pszResampling;
    1113             :     }
    1114             : 
    1115         259 :     const char *pszMinX = GetOption(MD_MINX);
    1116         259 :     const char *pszMinY = GetOption(MD_MINY);
    1117         259 :     const char *pszMaxX = GetOption(MD_MAXX);
    1118         259 :     const char *pszMaxY = GetOption(MD_MAXY);
    1119         259 :     int nCountMinMaxXY = (pszMinX ? 1 : 0) + (pszMinY ? 1 : 0) +
    1120         259 :                          (pszMaxX ? 1 : 0) + (pszMaxY ? 1 : 0);
    1121         259 :     if (nCountMinMaxXY != 0 && nCountMinMaxXY != 4)
    1122             :     {
    1123           4 :         CPLError(CE_Failure, CPLE_AppDefined,
    1124             :                  "None or all of %s, %s, %s and %s must be specified", MD_MINX,
    1125             :                  MD_MINY, MD_MAXX, MD_MAXY);
    1126           4 :         return false;
    1127             :     }
    1128             : 
    1129         255 :     const char *pszXSize = GetOption(MD_XSIZE);
    1130         255 :     const char *pszYSize = GetOption(MD_YSIZE);
    1131         255 :     const char *pszGeoTransform = GetOption(MD_GEOTRANSFORM);
    1132         255 :     const int nCountXSizeYSizeGT =
    1133         255 :         (pszXSize ? 1 : 0) + (pszYSize ? 1 : 0) + (pszGeoTransform ? 1 : 0);
    1134         255 :     if (nCountXSizeYSizeGT != 0 && nCountXSizeYSizeGT != 3)
    1135             :     {
    1136           3 :         CPLError(CE_Failure, CPLE_AppDefined,
    1137             :                  "None or all of %s, %s, %s must be specified", MD_XSIZE,
    1138             :                  MD_YSIZE, MD_GEOTRANSFORM);
    1139           3 :         return false;
    1140             :     }
    1141             : 
    1142         252 :     const char *pszDataType = GetOption(MD_DATA_TYPE);
    1143         252 :     const char *pszColorInterp = GetOption(MD_COLOR_INTERPRETATION);
    1144         252 :     int nBandCount = 0;
    1145         504 :     std::vector<GDALDataType> aeDataTypes;
    1146         504 :     std::vector<std::pair<bool, double>> aNoData;
    1147         504 :     std::vector<GDALColorInterp> aeColorInterp;
    1148             : 
    1149         252 :     const char *pszSRS = GetOption(MD_SRS);
    1150         252 :     m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    1151         252 :     if (pszSRS)
    1152             :     {
    1153           2 :         if (m_oSRS.SetFromUserInput(
    1154             :                 pszSRS,
    1155           2 :                 OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get()) !=
    1156             :             OGRERR_NONE)
    1157             :         {
    1158           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid %s", MD_SRS);
    1159           1 :             return false;
    1160             :         }
    1161             :     }
    1162         250 :     else if (const auto poSRS = m_poLayer->GetSpatialRef())
    1163             :     {
    1164             :         // Ignore GPKG "Undefined geographic SRS" and "Undefined Cartesian SRS"
    1165         126 :         if (!STARTS_WITH(poSRS->GetName(), "Undefined "))
    1166         126 :             m_oSRS = *poSRS;
    1167             :     }
    1168             : 
    1169         502 :     std::vector<const CPLXMLNode *> apoXMLNodeBands;
    1170         251 :     if (psRoot)
    1171             :     {
    1172          25 :         int nExpectedBandNumber = 1;
    1173         113 :         for (const CPLXMLNode *psIter = psRoot->psChild; psIter;
    1174          88 :              psIter = psIter->psNext)
    1175             :         {
    1176          91 :             if (psIter->eType == CXT_Element &&
    1177          91 :                 strcmp(psIter->pszValue, GTI_XML_BAND_ELEMENT) == 0)
    1178             :             {
    1179             :                 const char *pszBand =
    1180           8 :                     CPLGetXMLValue(psIter, GTI_XML_BAND_NUMBER, nullptr);
    1181           8 :                 if (!pszBand)
    1182             :                 {
    1183           1 :                     CPLError(CE_Failure, CPLE_AppDefined,
    1184             :                              "%s attribute missing on %s element",
    1185             :                              GTI_XML_BAND_NUMBER, GTI_XML_BAND_ELEMENT);
    1186           3 :                     return false;
    1187             :                 }
    1188           7 :                 const int nBand = atoi(pszBand);
    1189           7 :                 if (nBand <= 0)
    1190             :                 {
    1191           1 :                     CPLError(CE_Failure, CPLE_AppDefined,
    1192             :                              "Invalid band number");
    1193           1 :                     return false;
    1194             :                 }
    1195           6 :                 if (nBand != nExpectedBandNumber)
    1196             :                 {
    1197           1 :                     CPLError(CE_Failure, CPLE_AppDefined,
    1198             :                              "Invalid band number: found %d, expected %d",
    1199             :                              nBand, nExpectedBandNumber);
    1200           1 :                     return false;
    1201             :                 }
    1202           5 :                 apoXMLNodeBands.push_back(psIter);
    1203           5 :                 ++nExpectedBandNumber;
    1204             :             }
    1205             :         }
    1206             :     }
    1207             : 
    1208         248 :     const char *pszBandCount = GetOption(MD_BAND_COUNT);
    1209         248 :     if (pszBandCount)
    1210          22 :         nBandCount = atoi(pszBandCount);
    1211             : 
    1212         248 :     if (!apoXMLNodeBands.empty())
    1213             :     {
    1214           5 :         if (!pszBandCount)
    1215           4 :             nBandCount = static_cast<int>(apoXMLNodeBands.size());
    1216           1 :         else if (nBandCount != static_cast<int>(apoXMLNodeBands.size()))
    1217             :         {
    1218           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1219             :                      "Inconsistent %s with actual number of %s elements",
    1220             :                      GTI_XML_BANDCOUNT, GTI_XML_BAND_ELEMENT);
    1221           1 :             return false;
    1222             :         }
    1223             :     }
    1224             : 
    1225             :     // Take into STAC GeoParquet proj:code / proj:epsg / proj:wkt2 / proj:projjson
    1226             :     // and proj:transform fields
    1227         247 :     std::unique_ptr<OGRFeature> poFeature;
    1228         494 :     std::string osResX, osResY, osMinX, osMinY, osMaxX, osMaxY;
    1229         247 :     int iProjCode = -1;
    1230         247 :     int iProjEPSG = -1;
    1231         247 :     int iProjWKT2 = -1;
    1232         247 :     int iProjPROJSON = -1;
    1233         247 :     int iProjTransform = -1;
    1234             : 
    1235             :     const bool bIsStacGeoParquet =
    1236         254 :         STARTS_WITH(osLocationFieldName.c_str(), "assets.") &&
    1237           7 :         EQUAL(osLocationFieldName.c_str() + osLocationFieldName.size() -
    1238             :                   strlen(".href"),
    1239             :               ".href");
    1240         494 :     std::string osAssetName;
    1241         247 :     if (bIsStacGeoParquet)
    1242             :     {
    1243           7 :         m_bSTACCollection = true;
    1244          14 :         osAssetName = osLocationFieldName.substr(
    1245             :             strlen("assets."),
    1246          14 :             osLocationFieldName.size() - strlen("assets.") - strlen(".href"));
    1247             :     }
    1248             : 
    1249             :     const auto GetAssetFieldIndex =
    1250          38 :         [poLayerDefn, &osAssetName](const char *pszFieldName)
    1251             :     {
    1252          21 :         const int idx = poLayerDefn->GetFieldIndex(
    1253          21 :             CPLSPrintf("assets.%s.%s", osAssetName.c_str(), pszFieldName));
    1254          21 :         if (idx >= 0)
    1255           4 :             return idx;
    1256          17 :         return poLayerDefn->GetFieldIndex(pszFieldName);
    1257         247 :     };
    1258             : 
    1259           7 :     if (bIsStacGeoParquet && !pszSRS && !pszResX && !pszResY && !pszMinX &&
    1260           7 :         !pszMinY && !pszMaxX && !pszMaxY &&
    1261           7 :         ((iProjCode = GetAssetFieldIndex("proj:code")) >= 0 ||
    1262           4 :          (iProjEPSG = GetAssetFieldIndex("proj:epsg")) >= 0 ||
    1263           2 :          (iProjWKT2 = GetAssetFieldIndex("proj:wkt2")) >= 0 ||
    1264         255 :          (iProjPROJSON = GetAssetFieldIndex("proj:projjson")) >= 0) &&
    1265           7 :         ((iProjTransform = GetAssetFieldIndex("proj:transform")) >= 0))
    1266             :     {
    1267           7 :         poFeature.reset(m_poLayer->GetNextFeature());
    1268             :         const auto poProjTransformField =
    1269           7 :             poLayerDefn->GetFieldDefn(iProjTransform);
    1270           7 :         if (poFeature &&
    1271           7 :             ((iProjCode >= 0 && poFeature->IsFieldSet(iProjCode)) ||
    1272           4 :              (iProjEPSG >= 0 && poFeature->IsFieldSet(iProjEPSG)) ||
    1273           2 :              (iProjWKT2 >= 0 && poFeature->IsFieldSet(iProjWKT2)) ||
    1274           8 :              (iProjPROJSON >= 0 && poFeature->IsFieldSet(iProjPROJSON))) &&
    1275          25 :             poFeature->IsFieldSet(iProjTransform) &&
    1276          11 :             (poProjTransformField->GetType() == OFTRealList ||
    1277           4 :              poProjTransformField->GetType() == OFTIntegerList ||
    1278           0 :              poProjTransformField->GetType() == OFTInteger64List))
    1279             :         {
    1280          14 :             OGRSpatialReference oSTACSRS;
    1281           7 :             oSTACSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
    1282             : 
    1283           7 :             if (iProjCode >= 0 && poFeature->IsFieldSet(iProjCode))
    1284           3 :                 oSTACSRS.SetFromUserInput(
    1285             :                     poFeature->GetFieldAsString(iProjCode),
    1286             :                     OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get());
    1287             : 
    1288           4 :             else if (iProjEPSG >= 0 && poFeature->IsFieldSet(iProjEPSG))
    1289           2 :                 oSTACSRS.importFromEPSG(
    1290             :                     poFeature->GetFieldAsInteger(iProjEPSG));
    1291             : 
    1292           2 :             else if (iProjWKT2 >= 0 && poFeature->IsFieldSet(iProjWKT2))
    1293           1 :                 oSTACSRS.SetFromUserInput(
    1294             :                     poFeature->GetFieldAsString(iProjWKT2),
    1295             :                     OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get());
    1296             : 
    1297           1 :             else if (iProjPROJSON >= 0 && poFeature->IsFieldSet(iProjPROJSON))
    1298           1 :                 oSTACSRS.SetFromUserInput(
    1299             :                     poFeature->GetFieldAsString(iProjPROJSON),
    1300             :                     OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get());
    1301             : 
    1302           7 :             if (!oSTACSRS.IsEmpty())
    1303             :             {
    1304           6 :                 int nTransformCount = 0;
    1305             :                 // Note: different coefficient ordering than GDAL geotransform
    1306           6 :                 double adfProjTransform[6] = {0, 0, 0, 0, 0, 0};
    1307           6 :                 if (poProjTransformField->GetType() == OFTRealList)
    1308             :                 {
    1309             :                     const auto padfFeatureTransform =
    1310           2 :                         poFeature->GetFieldAsDoubleList(iProjTransform,
    1311             :                                                         &nTransformCount);
    1312           2 :                     if (nTransformCount >= 6)
    1313           2 :                         memcpy(adfProjTransform, padfFeatureTransform,
    1314             :                                6 * sizeof(double));
    1315             :                 }
    1316           4 :                 else if (poProjTransformField->GetType() == OFTInteger64List)
    1317             :                 {
    1318             :                     const auto paFeatureTransform =
    1319           0 :                         poFeature->GetFieldAsInteger64List(iProjTransform,
    1320             :                                                            &nTransformCount);
    1321           0 :                     if (nTransformCount >= 6)
    1322             :                     {
    1323           0 :                         for (int i = 0; i < 6; ++i)
    1324           0 :                             adfProjTransform[i] =
    1325           0 :                                 static_cast<double>(paFeatureTransform[i]);
    1326             :                     }
    1327             :                 }
    1328           4 :                 else if (poProjTransformField->GetType() == OFTIntegerList)
    1329             :                 {
    1330             :                     const auto paFeatureTransform =
    1331           4 :                         poFeature->GetFieldAsIntegerList(iProjTransform,
    1332             :                                                          &nTransformCount);
    1333           4 :                     if (nTransformCount >= 6)
    1334             :                     {
    1335          28 :                         for (int i = 0; i < 6; ++i)
    1336          24 :                             adfProjTransform[i] = paFeatureTransform[i];
    1337             :                     }
    1338             :                 }
    1339           6 :                 OGREnvelope sEnvelope;
    1340          12 :                 if (nTransformCount >= 6 && m_poLayer->GetSpatialRef() &&
    1341           6 :                     m_poLayer->GetExtent(&sEnvelope, /* bForce = */ true) ==
    1342             :                         OGRERR_NONE)
    1343             :                 {
    1344           6 :                     const double dfResX = adfProjTransform[0];
    1345           6 :                     osResX = CPLSPrintf("%.17g", dfResX);
    1346           6 :                     const double dfResY = std::fabs(adfProjTransform[4]);
    1347           6 :                     osResY = CPLSPrintf("%.17g", dfResY);
    1348             : 
    1349             :                     auto poCT = std::unique_ptr<OGRCoordinateTransformation>(
    1350             :                         OGRCreateCoordinateTransformation(
    1351          12 :                             m_poLayer->GetSpatialRef(), &oSTACSRS));
    1352             :                     auto poInvCT = std::unique_ptr<OGRCoordinateTransformation>(
    1353          12 :                         poCT ? poCT->GetInverse() : nullptr);
    1354           6 :                     double dfOutMinX = 0;
    1355           6 :                     double dfOutMinY = 0;
    1356           6 :                     double dfOutMaxX = 0;
    1357           6 :                     double dfOutMaxY = 0;
    1358          12 :                     if (dfResX > 0 && dfResY > 0 && poCT && poInvCT &&
    1359          12 :                         poCT->TransformBounds(sEnvelope.MinX, sEnvelope.MinY,
    1360             :                                               sEnvelope.MaxX, sEnvelope.MaxY,
    1361             :                                               &dfOutMinX, &dfOutMinY,
    1362           6 :                                               &dfOutMaxX, &dfOutMaxY, 21))
    1363             :                     {
    1364           6 :                         constexpr double EPSILON = 1e-3;
    1365             :                         const bool bTileAlignedOnRes =
    1366           6 :                             (fmod(std::fabs(adfProjTransform[3]), dfResX) <=
    1367          12 :                                  EPSILON * dfResX &&
    1368           6 :                              fmod(std::fabs(adfProjTransform[5]), dfResY) <=
    1369           6 :                                  EPSILON * dfResY);
    1370             : 
    1371             :                         osMinX = CPLSPrintf(
    1372             :                             "%.17g",
    1373             :                             !bTileAlignedOnRes
    1374             :                                 ? dfOutMinX
    1375           6 :                                 : std::floor(dfOutMinX / dfResX) * dfResX);
    1376             :                         osMinY = CPLSPrintf(
    1377             :                             "%.17g",
    1378             :                             !bTileAlignedOnRes
    1379             :                                 ? dfOutMinY
    1380           6 :                                 : std::floor(dfOutMinY / dfResY) * dfResY);
    1381             :                         osMaxX = CPLSPrintf(
    1382             :                             "%.17g",
    1383             :                             !bTileAlignedOnRes
    1384             :                                 ? dfOutMaxX
    1385           6 :                                 : std::ceil(dfOutMaxX / dfResX) * dfResX);
    1386             :                         osMaxY = CPLSPrintf(
    1387             :                             "%.17g",
    1388             :                             !bTileAlignedOnRes
    1389             :                                 ? dfOutMaxY
    1390           6 :                                 : std::ceil(dfOutMaxY / dfResY) * dfResY);
    1391             : 
    1392           6 :                         m_oSRS = std::move(oSTACSRS);
    1393           6 :                         pszResX = osResX.c_str();
    1394           6 :                         pszResY = osResY.c_str();
    1395           6 :                         pszMinX = osMinX.c_str();
    1396           6 :                         pszMinY = osMinY.c_str();
    1397           6 :                         pszMaxX = osMaxX.c_str();
    1398           6 :                         pszMaxY = osMaxY.c_str();
    1399           6 :                         nCountMinMaxXY = 4;
    1400             : 
    1401           6 :                         poFeature.reset();
    1402           6 :                         m_poLayer->ResetReading();
    1403             : 
    1404             :                         m_poWarpedLayerKeeper =
    1405           6 :                             std::make_unique<OGRWarpedLayer>(
    1406           0 :                                 m_poLayer, /* iGeomField = */ 0,
    1407           6 :                                 /* bTakeOwnership = */ false, poCT.release(),
    1408          12 :                                 poInvCT.release());
    1409           6 :                         m_poLayer = m_poWarpedLayerKeeper.get();
    1410           6 :                         poLayerDefn = m_poLayer->GetLayerDefn();
    1411             :                     }
    1412             :                 }
    1413             :             }
    1414             :         }
    1415             :     }
    1416             : 
    1417         247 :     OGREnvelope sEnvelope;
    1418         247 :     if (nCountMinMaxXY == 4)
    1419             :     {
    1420          17 :         sEnvelope.MinX = CPLAtof(pszMinX);
    1421          17 :         sEnvelope.MinY = CPLAtof(pszMinY);
    1422          17 :         sEnvelope.MaxX = CPLAtof(pszMaxX);
    1423          17 :         sEnvelope.MaxY = CPLAtof(pszMaxY);
    1424          17 :         if (!(sEnvelope.MaxX > sEnvelope.MinX))
    1425             :         {
    1426           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1427             :                      "%s metadata item must be > %s", MD_MAXX, MD_MINX);
    1428           1 :             return false;
    1429             :         }
    1430          16 :         if (!(sEnvelope.MaxY > sEnvelope.MinY))
    1431             :         {
    1432           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1433             :                      "%s metadata item must be > %s", MD_MAXY, MD_MINY);
    1434           1 :             return false;
    1435             :         }
    1436             :     }
    1437             : 
    1438         245 :     bool bHasMaskBand = false;
    1439         245 :     std::unique_ptr<GDALColorTable> poSingleColorTable;
    1440         270 :     if ((!pszBandCount && apoXMLNodeBands.empty()) ||
    1441          25 :         (!(pszResX && pszResY) && nCountXSizeYSizeGT == 0))
    1442             :     {
    1443         234 :         CPLDebug("GTI", "Inspecting one feature due to missing metadata items");
    1444         234 :         m_bScannedOneFeatureAtOpening = true;
    1445             : 
    1446         234 :         if (!poFeature)
    1447         233 :             poFeature.reset(m_poLayer->GetNextFeature());
    1448         466 :         if (!poFeature ||
    1449         232 :             !poFeature->IsFieldSetAndNotNull(m_nLocationFieldIndex))
    1450             :         {
    1451           2 :             CPLError(
    1452             :                 CE_Failure, CPLE_AppDefined,
    1453             :                 "BAND_COUNT(+DATA_TYPE+COLOR_INTERPRETATION)+ (RESX+RESY or "
    1454             :                 "XSIZE+YSIZE+GEOTRANSFORM) metadata items "
    1455             :                 "missing");
    1456          10 :             return false;
    1457             :         }
    1458             : 
    1459             :         const char *pszTileName =
    1460         232 :             poFeature->GetFieldAsString(m_nLocationFieldIndex);
    1461             :         const std::string osTileName(GetAbsoluteFileName(
    1462         232 :             pszTileName, poOpenInfo->pszFilename, m_bSTACCollection));
    1463         232 :         pszTileName = osTileName.c_str();
    1464             : 
    1465             :         auto poTileDS = std::shared_ptr<GDALDataset>(
    1466             :             GDALDataset::Open(pszTileName,
    1467             :                               GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR),
    1468         232 :             GDALDatasetUniquePtrReleaser());
    1469         232 :         if (!poTileDS)
    1470             :         {
    1471           1 :             return false;
    1472             :         }
    1473             : 
    1474             :         // do palette -> RGB(A) expansion if needed
    1475         231 :         if (!GTIDoPaletteExpansionIfNeeded(poTileDS, nBandCount))
    1476           0 :             return false;
    1477             : 
    1478         231 :         const int nTileBandCount = poTileDS->GetRasterCount();
    1479         526 :         for (int i = 0; i < nTileBandCount; ++i)
    1480             :         {
    1481         295 :             auto poTileBand = poTileDS->GetRasterBand(i + 1);
    1482         295 :             aeDataTypes.push_back(poTileBand->GetRasterDataType());
    1483         295 :             int bHasNoData = FALSE;
    1484         295 :             const double dfNoData = poTileBand->GetNoDataValue(&bHasNoData);
    1485         295 :             aNoData.emplace_back(CPL_TO_BOOL(bHasNoData), dfNoData);
    1486         295 :             aeColorInterp.push_back(poTileBand->GetColorInterpretation());
    1487         295 :             if (nTileBandCount == 1)
    1488             :             {
    1489         200 :                 if (auto poCT = poTileBand->GetColorTable())
    1490             :                 {
    1491             :                     // We assume that this will apply to all tiles...
    1492             :                     // TODO: detect if that it is really the case, and warn
    1493             :                     // if not, or do approximate palette matching like
    1494             :                     // done in GDALRasterBand::GetIndexColorTranslationTo()
    1495           0 :                     poSingleColorTable.reset(poCT->Clone());
    1496             :                 }
    1497             :             }
    1498             : 
    1499         295 :             if (poTileBand->GetMaskFlags() == GMF_PER_DATASET)
    1500           1 :                 bHasMaskBand = true;
    1501             :         }
    1502         231 :         if (!pszBandCount && nBandCount == 0)
    1503         217 :             nBandCount = nTileBandCount;
    1504             : 
    1505         231 :         auto poTileSRS = poTileDS->GetSpatialRef();
    1506         231 :         if (!m_oSRS.IsEmpty() && poTileSRS && !m_oSRS.IsSame(poTileSRS))
    1507             :         {
    1508           7 :             CPLStringList aosOptions;
    1509           7 :             aosOptions.AddString("-of");
    1510           7 :             aosOptions.AddString("VRT");
    1511             : 
    1512           7 :             char *pszWKT = nullptr;
    1513           7 :             const char *const apszWKTOptions[] = {"FORMAT=WKT2_2019", nullptr};
    1514           7 :             m_oSRS.exportToWkt(&pszWKT, apszWKTOptions);
    1515           7 :             if (pszWKT)
    1516           7 :                 m_osWKT = pszWKT;
    1517           7 :             CPLFree(pszWKT);
    1518             : 
    1519           7 :             if (m_osWKT.empty())
    1520             :             {
    1521           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1522             :                          "Cannot export VRT SRS to WKT2");
    1523           0 :                 return false;
    1524             :             }
    1525             : 
    1526           7 :             aosOptions.AddString("-t_srs");
    1527           7 :             aosOptions.AddString(m_osWKT.c_str());
    1528             : 
    1529             :             GDALWarpAppOptions *psWarpOptions =
    1530           7 :                 GDALWarpAppOptionsNew(aosOptions.List(), nullptr);
    1531           7 :             GDALDatasetH ahSrcDS[] = {GDALDataset::ToHandle(poTileDS.get())};
    1532           7 :             int bUsageError = false;
    1533             :             auto poWarpDS =
    1534             :                 std::unique_ptr<GDALDataset>(GDALDataset::FromHandle(GDALWarp(
    1535           7 :                     "", nullptr, 1, ahSrcDS, psWarpOptions, &bUsageError)));
    1536           7 :             GDALWarpAppOptionsFree(psWarpOptions);
    1537           7 :             if (!poWarpDS)
    1538             :             {
    1539           0 :                 return false;
    1540             :             }
    1541             : 
    1542           7 :             poTileDS.reset(poWarpDS.release());
    1543           7 :             poTileSRS = poTileDS->GetSpatialRef();
    1544           7 :             CPL_IGNORE_RET_VAL(poTileSRS);
    1545             :         }
    1546             : 
    1547         231 :         GDALGeoTransform gtTile;
    1548         231 :         if (poTileDS->GetGeoTransform(gtTile) != CE_None)
    1549             :         {
    1550           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1551             :                      "Cannot find geotransform on %s", pszTileName);
    1552           1 :             return false;
    1553             :         }
    1554         230 :         if (!(gtTile[GT_ROTATION_PARAM1] == 0))
    1555             :         {
    1556           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1557             :                      "3rd value of GeoTransform of %s must be 0", pszTileName);
    1558           1 :             return false;
    1559             :         }
    1560         229 :         if (!(gtTile[GT_ROTATION_PARAM2] == 0))
    1561             :         {
    1562           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1563             :                      "5th value of GeoTransform of %s must be 0", pszTileName);
    1564           1 :             return false;
    1565             :         }
    1566             : 
    1567         228 :         const double dfResX = gtTile[GT_WE_RES];
    1568         228 :         const double dfResY = gtTile[GT_NS_RES];
    1569         228 :         if (!(dfResX > 0))
    1570             :         {
    1571           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1572             :                      "2nd value of GeoTransform of %s must be > 0",
    1573             :                      pszTileName);
    1574           1 :             return false;
    1575             :         }
    1576         227 :         if (!(dfResY != 0))
    1577             :         {
    1578           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    1579             :                      "6th value of GeoTransform of %s must be != 0",
    1580             :                      pszTileName);
    1581           0 :             return false;
    1582             :         }
    1583             : 
    1584         442 :         if (!sEnvelope.IsInit() &&
    1585         215 :             m_poLayer->GetExtent(&sEnvelope, /* bForce = */ false) ==
    1586             :                 OGRERR_FAILURE)
    1587             :         {
    1588           2 :             if (m_poLayer->GetExtent(&sEnvelope, /* bForce = */ true) ==
    1589             :                 OGRERR_FAILURE)
    1590             :             {
    1591           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1592             :                          "Cannot get layer extent");
    1593           1 :                 return false;
    1594             :             }
    1595           1 :             CPLError(CE_Warning, CPLE_AppDefined,
    1596             :                      "Could get layer extent, but using a slower method");
    1597             :         }
    1598             : 
    1599         226 :         const double dfXSize = (sEnvelope.MaxX - sEnvelope.MinX) / dfResX;
    1600         226 :         if (!(dfXSize >= 0 && dfXSize < INT_MAX))
    1601             :         {
    1602           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1603             :                      "Too small %s, or wrong layer extent", MD_RESX);
    1604           1 :             return false;
    1605             :         }
    1606             : 
    1607         225 :         const double dfYSize =
    1608         225 :             (sEnvelope.MaxY - sEnvelope.MinY) / std::fabs(dfResY);
    1609         225 :         if (!(dfYSize >= 0 && dfYSize < INT_MAX))
    1610             :         {
    1611           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1612             :                      "Too small %s, or wrong layer extent", MD_RESY);
    1613           1 :             return false;
    1614             :         }
    1615             : 
    1616         224 :         m_gt[GT_TOPLEFT_X] = sEnvelope.MinX;
    1617         224 :         m_gt[GT_WE_RES] = dfResX;
    1618         224 :         m_gt[GT_ROTATION_PARAM1] = 0;
    1619         224 :         m_gt[GT_TOPLEFT_Y] = sEnvelope.MaxY;
    1620         224 :         m_gt[GT_ROTATION_PARAM2] = 0;
    1621         224 :         m_gt[GT_NS_RES] = -std::fabs(dfResY);
    1622             : 
    1623         224 :         nRasterXSize = static_cast<int>(std::ceil(dfXSize));
    1624         224 :         nRasterYSize = static_cast<int>(std::ceil(dfYSize));
    1625             :     }
    1626             : 
    1627         235 :     if (pszXSize && pszYSize && pszGeoTransform)
    1628             :     {
    1629          12 :         const int nXSize = atoi(pszXSize);
    1630          12 :         if (nXSize <= 0)
    1631             :         {
    1632           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1633             :                      "%s metadata item must be > 0", MD_XSIZE);
    1634           6 :             return false;
    1635             :         }
    1636             : 
    1637          11 :         const int nYSize = atoi(pszYSize);
    1638          11 :         if (nYSize <= 0)
    1639             :         {
    1640           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1641             :                      "%s metadata item must be > 0", MD_YSIZE);
    1642           1 :             return false;
    1643             :         }
    1644             : 
    1645             :         const CPLStringList aosTokens(
    1646          10 :             CSLTokenizeString2(pszGeoTransform, ",", 0));
    1647          10 :         if (aosTokens.size() != 6)
    1648             :         {
    1649           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1650             :                      "%s metadata item must be 6 numeric values "
    1651             :                      "separated with comma",
    1652             :                      MD_GEOTRANSFORM);
    1653           1 :             return false;
    1654             :         }
    1655          63 :         for (int i = 0; i < 6; ++i)
    1656             :         {
    1657          54 :             m_gt[i] = CPLAtof(aosTokens[i]);
    1658             :         }
    1659           9 :         if (!(m_gt[GT_WE_RES] > 0))
    1660             :         {
    1661           0 :             CPLError(CE_Failure, CPLE_AppDefined, "2nd value of %s must be > 0",
    1662             :                      MD_GEOTRANSFORM);
    1663           0 :             return false;
    1664             :         }
    1665           9 :         if (!(m_gt[GT_ROTATION_PARAM1] == 0))
    1666             :         {
    1667           1 :             CPLError(CE_Failure, CPLE_AppDefined, "3rd value of %s must be 0",
    1668             :                      MD_GEOTRANSFORM);
    1669           1 :             return false;
    1670             :         }
    1671           8 :         if (!(m_gt[GT_ROTATION_PARAM2] == 0))
    1672             :         {
    1673           1 :             CPLError(CE_Failure, CPLE_AppDefined, "5th value of %s must be 0",
    1674             :                      MD_GEOTRANSFORM);
    1675           1 :             return false;
    1676             :         }
    1677           7 :         if (!(m_gt[GT_NS_RES] < 0))
    1678             :         {
    1679           1 :             CPLError(CE_Failure, CPLE_AppDefined, "6th value of %s must be < 0",
    1680             :                      MD_GEOTRANSFORM);
    1681           1 :             return false;
    1682             :         }
    1683           6 :         nRasterXSize = nXSize;
    1684          12 :         nRasterYSize = nYSize;
    1685             :     }
    1686         223 :     else if (pszResX && pszResY)
    1687             :     {
    1688          20 :         const double dfResX = CPLAtof(pszResX);
    1689          20 :         if (!(dfResX > 0))
    1690             :         {
    1691           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1692             :                      "RESX metadata item must be > 0");
    1693           1 :             return false;
    1694             :         }
    1695          19 :         const double dfResY = CPLAtof(pszResY);
    1696          19 :         if (!(dfResY > 0))
    1697             :         {
    1698           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1699             :                      "RESY metadata item must be > 0");
    1700           1 :             return false;
    1701             :         }
    1702             : 
    1703          18 :         if (nCountMinMaxXY == 4)
    1704             :         {
    1705          11 :             if (pszXSize || pszYSize || pszGeoTransform)
    1706             :             {
    1707           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
    1708             :                          "Ignoring %s, %s and %s when %s, "
    1709             :                          "%s, %s and %s are specified",
    1710             :                          MD_XSIZE, MD_YSIZE, MD_GEOTRANSFORM, MD_MINX, MD_MINY,
    1711             :                          MD_MAXX, MD_MAXY);
    1712             :             }
    1713             :         }
    1714           9 :         else if (!sEnvelope.IsInit() &&
    1715           2 :                  m_poLayer->GetExtent(&sEnvelope, /* bForce = */ false) ==
    1716             :                      OGRERR_FAILURE)
    1717             :         {
    1718           0 :             if (m_poLayer->GetExtent(&sEnvelope, /* bForce = */ true) ==
    1719             :                 OGRERR_FAILURE)
    1720             :             {
    1721           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1722             :                          "Cannot get layer extent");
    1723           0 :                 return false;
    1724             :             }
    1725           0 :             CPLError(CE_Warning, CPLE_AppDefined,
    1726             :                      "Could get layer extent, but using a slower method");
    1727             :         }
    1728             : 
    1729          18 :         const double dfXSize = (sEnvelope.MaxX - sEnvelope.MinX) / dfResX;
    1730          18 :         if (!(dfXSize >= 0 && dfXSize < INT_MAX))
    1731             :         {
    1732           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1733             :                      "Too small %s, or wrong layer extent", MD_RESX);
    1734           1 :             return false;
    1735             :         }
    1736             : 
    1737          17 :         const double dfYSize = (sEnvelope.MaxY - sEnvelope.MinY) / dfResY;
    1738          17 :         if (!(dfYSize >= 0 && dfYSize < INT_MAX))
    1739             :         {
    1740           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1741             :                      "Too small %s, or wrong layer extent", MD_RESY);
    1742           1 :             return false;
    1743             :         }
    1744             : 
    1745          16 :         m_gt[GT_TOPLEFT_X] = sEnvelope.MinX;
    1746          16 :         m_gt[GT_WE_RES] = dfResX;
    1747          16 :         m_gt[GT_ROTATION_PARAM1] = 0;
    1748          16 :         m_gt[GT_TOPLEFT_Y] = sEnvelope.MaxY;
    1749          16 :         m_gt[GT_ROTATION_PARAM2] = 0;
    1750          16 :         m_gt[GT_NS_RES] = -dfResY;
    1751          16 :         nRasterXSize = static_cast<int>(std::ceil(dfXSize));
    1752          16 :         nRasterYSize = static_cast<int>(std::ceil(dfYSize));
    1753             :     }
    1754             : 
    1755         225 :     if (nBandCount == 0 && !pszBandCount)
    1756             :     {
    1757           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s metadata item missing",
    1758             :                  MD_BAND_COUNT);
    1759           0 :         return false;
    1760             :     }
    1761             : 
    1762         225 :     if (!GDALCheckBandCount(nBandCount, false))
    1763           1 :         return false;
    1764             : 
    1765         224 :     if (aeDataTypes.empty() && !pszDataType)
    1766             :     {
    1767           9 :         aeDataTypes.resize(nBandCount, GDT_UInt8);
    1768             :     }
    1769         215 :     else if (pszDataType)
    1770             :     {
    1771           8 :         aeDataTypes.clear();
    1772           8 :         const CPLStringList aosTokens(CSLTokenizeString2(pszDataType, ", ", 0));
    1773           8 :         if (aosTokens.size() == 1)
    1774             :         {
    1775           6 :             const auto eDataType = GDALGetDataTypeByName(aosTokens[0]);
    1776           6 :             if (eDataType == GDT_Unknown)
    1777             :             {
    1778           1 :                 CPLError(CE_Failure, CPLE_AppDefined, "Invalid value for %s",
    1779             :                          MD_DATA_TYPE);
    1780           1 :                 return false;
    1781             :             }
    1782           5 :             aeDataTypes.resize(nBandCount, eDataType);
    1783             :         }
    1784           2 :         else if (aosTokens.size() == nBandCount)
    1785             :         {
    1786           2 :             for (int i = 0; i < nBandCount; ++i)
    1787             :             {
    1788           2 :                 const auto eDataType = GDALGetDataTypeByName(aosTokens[i]);
    1789           2 :                 if (eDataType == GDT_Unknown)
    1790             :                 {
    1791           1 :                     CPLError(CE_Failure, CPLE_AppDefined,
    1792             :                              "Invalid value for %s", MD_DATA_TYPE);
    1793           1 :                     return false;
    1794             :                 }
    1795           1 :                 aeDataTypes.push_back(eDataType);
    1796             :             }
    1797             :         }
    1798             :         else
    1799             :         {
    1800           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1801             :                      "Number of values in %s must be 1 or %s", MD_DATA_TYPE,
    1802             :                      MD_BAND_COUNT);
    1803           1 :             return false;
    1804             :         }
    1805             :     }
    1806             : 
    1807         221 :     const char *pszNoData = GetOption(MD_NODATA);
    1808         221 :     if (pszNoData)
    1809             :     {
    1810          20 :         const auto IsValidNoDataStr = [](const char *pszStr)
    1811             :         {
    1812          20 :             if (EQUAL(pszStr, "inf") || EQUAL(pszStr, "-inf") ||
    1813          16 :                 EQUAL(pszStr, "nan"))
    1814           6 :                 return true;
    1815          14 :             const auto eType = CPLGetValueType(pszStr);
    1816          14 :             return eType == CPL_VALUE_INTEGER || eType == CPL_VALUE_REAL;
    1817             :         };
    1818             : 
    1819          18 :         aNoData.clear();
    1820          18 :         const CPLStringList aosTokens(CSLTokenizeString2(pszNoData, ", ", 0));
    1821          18 :         if (aosTokens.size() == 1)
    1822             :         {
    1823          14 :             if (!EQUAL(aosTokens[0], "NONE"))
    1824             :             {
    1825          11 :                 if (!IsValidNoDataStr(aosTokens[0]))
    1826             :                 {
    1827           1 :                     CPLError(CE_Failure, CPLE_AppDefined,
    1828             :                              "Invalid value for %s", MD_NODATA);
    1829           1 :                     return false;
    1830             :                 }
    1831          10 :                 aNoData.resize(nBandCount,
    1832          20 :                                std::pair(true, CPLAtof(aosTokens[0])));
    1833             :             }
    1834             :         }
    1835           4 :         else if (aosTokens.size() == nBandCount)
    1836             :         {
    1837          12 :             for (int i = 0; i < nBandCount; ++i)
    1838             :             {
    1839          10 :                 if (EQUAL(aosTokens[i], "NONE"))
    1840             :                 {
    1841           1 :                     aNoData.emplace_back(false, 0);
    1842             :                 }
    1843           9 :                 else if (IsValidNoDataStr(aosTokens[i]))
    1844             :                 {
    1845           8 :                     aNoData.emplace_back(true, CPLAtof(aosTokens[i]));
    1846             :                 }
    1847             :                 else
    1848             :                 {
    1849           1 :                     CPLError(CE_Failure, CPLE_AppDefined,
    1850             :                              "Invalid value for %s", MD_NODATA);
    1851           1 :                     return false;
    1852             :                 }
    1853             :             }
    1854             :         }
    1855             :         else
    1856             :         {
    1857           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1858             :                      "Number of values in %s must be 1 or %s", MD_NODATA,
    1859             :                      MD_BAND_COUNT);
    1860           1 :             return false;
    1861             :         }
    1862             :     }
    1863             : 
    1864         218 :     if (pszColorInterp)
    1865             :     {
    1866          11 :         aeColorInterp.clear();
    1867             :         const CPLStringList aosTokens(
    1868          11 :             CSLTokenizeString2(pszColorInterp, ", ", 0));
    1869          11 :         if (aosTokens.size() == 1)
    1870             :         {
    1871           7 :             const auto eInterp = GDALGetColorInterpretationByName(aosTokens[0]);
    1872          12 :             if (eInterp == GCI_Undefined &&
    1873           5 :                 !EQUAL(aosTokens[0],
    1874             :                        GDALGetColorInterpretationName(GCI_Undefined)))
    1875             :             {
    1876           1 :                 CPLError(CE_Failure, CPLE_AppDefined, "Invalid value for %s",
    1877             :                          MD_COLOR_INTERPRETATION);
    1878           1 :                 return false;
    1879             :             }
    1880           6 :             aeColorInterp.resize(nBandCount, eInterp);
    1881             :         }
    1882           4 :         else if (aosTokens.size() == nBandCount)
    1883             :         {
    1884          11 :             for (int i = 0; i < nBandCount; ++i)
    1885             :             {
    1886             :                 const auto eInterp =
    1887           9 :                     GDALGetColorInterpretationByName(aosTokens[i]);
    1888          11 :                 if (eInterp == GCI_Undefined &&
    1889           2 :                     !EQUAL(aosTokens[i],
    1890             :                            GDALGetColorInterpretationName(GCI_Undefined)))
    1891             :                 {
    1892           1 :                     CPLError(CE_Failure, CPLE_AppDefined,
    1893             :                              "Invalid value for %s", MD_COLOR_INTERPRETATION);
    1894           1 :                     return false;
    1895             :                 }
    1896           8 :                 aeColorInterp.emplace_back(eInterp);
    1897             :             }
    1898             :         }
    1899             :         else
    1900             :         {
    1901           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    1902             :                      "Number of values in %s must be 1 or "
    1903             :                      "%s",
    1904             :                      MD_COLOR_INTERPRETATION, MD_BAND_COUNT);
    1905           1 :             return false;
    1906             :         }
    1907             :     }
    1908             : 
    1909             :     /* -------------------------------------------------------------------- */
    1910             :     /*      Create bands.                                                   */
    1911             :     /* -------------------------------------------------------------------- */
    1912         215 :     if (aeDataTypes.size() != static_cast<size_t>(nBandCount))
    1913             :     {
    1914           1 :         CPLError(
    1915             :             CE_Failure, CPLE_AppDefined,
    1916             :             "Number of data types values found not matching number of bands");
    1917           1 :         return false;
    1918             :     }
    1919         214 :     if (!aNoData.empty() && aNoData.size() != static_cast<size_t>(nBandCount))
    1920             :     {
    1921           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    1922             :                  "Number of nodata values found not matching number of bands");
    1923           1 :         return false;
    1924             :     }
    1925         418 :     if (!aeColorInterp.empty() &&
    1926         205 :         aeColorInterp.size() != static_cast<size_t>(nBandCount))
    1927             :     {
    1928           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    1929             :                  "Number of color interpretation values found not matching "
    1930             :                  "number of bands");
    1931           1 :         return false;
    1932             :     }
    1933             : 
    1934         212 :     int nBlockXSize = 256;
    1935         212 :     const char *pszBlockXSize = GetOption(MD_BLOCK_X_SIZE);
    1936         212 :     if (pszBlockXSize)
    1937             :     {
    1938           3 :         nBlockXSize = atoi(pszBlockXSize);
    1939           3 :         if (nBlockXSize <= 0)
    1940             :         {
    1941           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid %s",
    1942             :                      MD_BLOCK_X_SIZE);
    1943           1 :             return false;
    1944             :         }
    1945             :     }
    1946             : 
    1947         211 :     int nBlockYSize = 256;
    1948         211 :     const char *pszBlockYSize = GetOption(MD_BLOCK_Y_SIZE);
    1949         211 :     if (pszBlockYSize)
    1950             :     {
    1951           3 :         nBlockYSize = atoi(pszBlockYSize);
    1952           3 :         if (nBlockYSize <= 0)
    1953             :         {
    1954           1 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid %s",
    1955             :                      MD_BLOCK_Y_SIZE);
    1956           1 :             return false;
    1957             :         }
    1958             :     }
    1959             : 
    1960         210 :     if (nBlockXSize > INT_MAX / nBlockYSize)
    1961             :     {
    1962           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Too big %s * %s",
    1963             :                  MD_BLOCK_X_SIZE, MD_BLOCK_Y_SIZE);
    1964           1 :         return false;
    1965             :     }
    1966             : 
    1967         209 :     if (dfOvrFactor > 1.0)
    1968             :     {
    1969           4 :         m_gt[GT_WE_RES] *= dfOvrFactor;
    1970           4 :         m_gt[GT_NS_RES] *= dfOvrFactor;
    1971           4 :         nRasterXSize = static_cast<int>(std::ceil(nRasterXSize / dfOvrFactor));
    1972           4 :         nRasterYSize = static_cast<int>(std::ceil(nRasterYSize / dfOvrFactor));
    1973             :     }
    1974             : 
    1975         418 :     std::vector<std::string> aosDescriptions;
    1976         418 :     std::vector<double> adfCenterWavelength;
    1977         418 :     std::vector<double> adfFullWidthHalfMax;
    1978         418 :     std::vector<double> adfScale;
    1979         418 :     std::vector<double> adfOffset;
    1980         209 :     if (bIsStacGeoParquet && poFeature)
    1981             :     {
    1982           7 :         int nBandsIdx = poLayerDefn->GetFieldIndex(
    1983           7 :             CPLSPrintf("assets.%s.eo:bands", osAssetName.c_str()));
    1984           7 :         if (nBandsIdx < 0)
    1985           2 :             nBandsIdx = poLayerDefn->GetFieldIndex("bands");
    1986           7 :         if (nBandsIdx >= 0 &&
    1987          14 :             poLayerDefn->GetFieldDefn(nBandsIdx)->GetSubType() == OFSTJSON &&
    1988           7 :             poFeature->IsFieldSet(nBandsIdx))
    1989             :         {
    1990           7 :             const char *pszStr = poFeature->GetFieldAsString(nBandsIdx);
    1991          14 :             CPLJSONDocument oDoc;
    1992          21 :             if (oDoc.LoadMemory(pszStr) &&
    1993          14 :                 oDoc.GetRoot().GetType() == CPLJSONObject::Type::Array)
    1994             :             {
    1995          14 :                 const auto oArray = oDoc.GetRoot().ToArray();
    1996           7 :                 if (oArray.Size() == nBandCount)
    1997             :                 {
    1998           7 :                     int i = 0;
    1999           7 :                     aosDescriptions.resize(nBandCount);
    2000           7 :                     adfCenterWavelength.resize(nBandCount);
    2001           7 :                     adfFullWidthHalfMax.resize(nBandCount);
    2002          19 :                     for (const auto &oObj : oArray)
    2003             :                     {
    2004          12 :                         if (oObj.GetType() == CPLJSONObject::Type::Object)
    2005             :                         {
    2006          36 :                             auto osCommonName = oObj.GetString("common_name");
    2007          12 :                             if (osCommonName.empty())
    2008           4 :                                 osCommonName = oObj.GetString("eo:common_name");
    2009             :                             const auto eInterp =
    2010          12 :                                 GDALGetColorInterpFromSTACCommonName(
    2011             :                                     osCommonName.c_str());
    2012          12 :                             if (eInterp != GCI_Undefined)
    2013          11 :                                 aeColorInterp[i] = eInterp;
    2014             : 
    2015          12 :                             aosDescriptions[i] = oObj.GetString("name");
    2016             : 
    2017             :                             std::string osDescription =
    2018          36 :                                 oObj.GetString("description");
    2019          12 :                             if (!osDescription.empty())
    2020             :                             {
    2021           1 :                                 if (aosDescriptions[i].empty())
    2022           0 :                                     aosDescriptions[i] =
    2023           0 :                                         std::move(osDescription);
    2024             :                                 else
    2025           1 :                                     aosDescriptions[i]
    2026           1 :                                         .append(" (")
    2027           1 :                                         .append(osDescription)
    2028           1 :                                         .append(")");
    2029             :                             }
    2030             : 
    2031          24 :                             adfCenterWavelength[i] =
    2032          12 :                                 oObj.GetDouble("center_wavelength");
    2033          12 :                             if (adfCenterWavelength[i] == 0)
    2034          16 :                                 adfCenterWavelength[i] =
    2035           8 :                                     oObj.GetDouble("eo:center_wavelength");
    2036          24 :                             adfFullWidthHalfMax[i] =
    2037          12 :                                 oObj.GetDouble("full_width_half_max");
    2038          12 :                             if (adfFullWidthHalfMax[i] == 0)
    2039          16 :                                 adfFullWidthHalfMax[i] =
    2040           8 :                                     oObj.GetDouble("eo:full_width_half_max");
    2041             :                         }
    2042          12 :                         ++i;
    2043             :                     }
    2044             :                 }
    2045             :             }
    2046             :         }
    2047             : 
    2048           7 :         int nRasterBandsIdx = poLayerDefn->GetFieldIndex(
    2049           7 :             CPLSPrintf("assets.%s.raster:bands", osAssetName.c_str()));
    2050           7 :         if (nRasterBandsIdx < 0)
    2051           3 :             nRasterBandsIdx = poLayerDefn->GetFieldIndex("bands");
    2052           6 :         if (nRasterBandsIdx >= 0 &&
    2053           6 :             poLayerDefn->GetFieldDefn(nRasterBandsIdx)->GetSubType() ==
    2054          13 :                 OFSTJSON &&
    2055           6 :             poFeature->IsFieldSet(nRasterBandsIdx))
    2056             :         {
    2057           6 :             const char *pszStr = poFeature->GetFieldAsString(nRasterBandsIdx);
    2058          12 :             CPLJSONDocument oDoc;
    2059          18 :             if (oDoc.LoadMemory(pszStr) &&
    2060          12 :                 oDoc.GetRoot().GetType() == CPLJSONObject::Type::Array)
    2061             :             {
    2062          12 :                 const auto oArray = oDoc.GetRoot().ToArray();
    2063           6 :                 if (oArray.Size() == nBandCount)
    2064             :                 {
    2065           6 :                     int i = 0;
    2066           6 :                     adfScale.resize(nBandCount,
    2067           6 :                                     std::numeric_limits<double>::quiet_NaN());
    2068           6 :                     adfOffset.resize(nBandCount,
    2069           6 :                                      std::numeric_limits<double>::quiet_NaN());
    2070          14 :                     for (const auto &oObj : oArray)
    2071             :                     {
    2072           8 :                         if (oObj.GetType() == CPLJSONObject::Type::Object)
    2073             :                         {
    2074           8 :                             adfScale[i] = oObj.GetDouble(
    2075             :                                 "scale",
    2076             :                                 std::numeric_limits<double>::quiet_NaN());
    2077           8 :                             adfOffset[i] = oObj.GetDouble(
    2078             :                                 "offset",
    2079             :                                 std::numeric_limits<double>::quiet_NaN());
    2080             :                         }
    2081           8 :                         ++i;
    2082             :                     }
    2083             :                 }
    2084             :             }
    2085             :         }
    2086             :     }
    2087             : 
    2088         209 :     GDALTileIndexBand *poFirstBand = nullptr;
    2089         490 :     for (int i = 0; i < nBandCount; ++i)
    2090             :     {
    2091         281 :         GDALDataType eDataType = aeDataTypes[i];
    2092         281 :         if (!apoXMLNodeBands.empty())
    2093             :         {
    2094           4 :             const char *pszVal = CPLGetXMLValue(apoXMLNodeBands[i],
    2095             :                                                 GTI_XML_BAND_DATATYPE, nullptr);
    2096           4 :             if (pszVal)
    2097             :             {
    2098           3 :                 eDataType = GDALGetDataTypeByName(pszVal);
    2099           3 :                 if (eDataType == GDT_Unknown)
    2100           0 :                     return false;
    2101             :             }
    2102             :         }
    2103             :         auto poBandUniquePtr = std::make_unique<GDALTileIndexBand>(
    2104         562 :             this, i + 1, eDataType, nBlockXSize, nBlockYSize);
    2105         281 :         auto poBand = poBandUniquePtr.get();
    2106         281 :         SetBand(i + 1, poBandUniquePtr.release());
    2107         281 :         if (!poFirstBand)
    2108         209 :             poFirstBand = poBand;
    2109         281 :         if (poBand->GetRasterDataType() != poFirstBand->GetRasterDataType())
    2110             :         {
    2111           0 :             m_bSameDataType = false;
    2112             :         }
    2113             : 
    2114         281 :         if (!aosDescriptions.empty() && !aosDescriptions[i].empty())
    2115             :         {
    2116          12 :             poBand->GDALRasterBand::SetDescription(aosDescriptions[i].c_str());
    2117             :         }
    2118         281 :         if (!apoXMLNodeBands.empty())
    2119             :         {
    2120           4 :             const char *pszVal = CPLGetXMLValue(
    2121           4 :                 apoXMLNodeBands[i], GTI_XML_BAND_DESCRIPTION, nullptr);
    2122           4 :             if (pszVal)
    2123             :             {
    2124           2 :                 poBand->GDALRasterBand::SetDescription(pszVal);
    2125             :             }
    2126             :         }
    2127             : 
    2128         281 :         if (!aNoData.empty() && aNoData[i].first)
    2129             :         {
    2130          29 :             poBand->m_bNoDataValueSet = true;
    2131          29 :             poBand->m_dfNoDataValue = aNoData[i].second;
    2132             :         }
    2133         281 :         if (!apoXMLNodeBands.empty())
    2134             :         {
    2135           4 :             const char *pszVal = CPLGetXMLValue(
    2136           4 :                 apoXMLNodeBands[i], GTI_XML_BAND_NODATAVALUE, nullptr);
    2137           4 :             if (pszVal)
    2138             :             {
    2139           3 :                 poBand->m_bNoDataValueSet = true;
    2140           3 :                 poBand->m_dfNoDataValue = CPLAtof(pszVal);
    2141             :             }
    2142             :         }
    2143         561 :         if (poBand->m_bNoDataValueSet != poFirstBand->m_bNoDataValueSet ||
    2144         280 :             !IsSameNaNAware(poBand->m_dfNoDataValue,
    2145             :                             poFirstBand->m_dfNoDataValue))
    2146             :         {
    2147           6 :             m_bSameNoData = false;
    2148             :         }
    2149             : 
    2150         281 :         if (!aeColorInterp.empty())
    2151             :         {
    2152         270 :             poBand->m_eColorInterp = aeColorInterp[i];
    2153             :         }
    2154         281 :         if (!apoXMLNodeBands.empty())
    2155             :         {
    2156           4 :             const char *pszVal = CPLGetXMLValue(
    2157           4 :                 apoXMLNodeBands[i], GTI_XML_BAND_COLORINTERP, nullptr);
    2158           4 :             if (pszVal)
    2159             :             {
    2160           4 :                 poBand->m_eColorInterp =
    2161           4 :                     GDALGetColorInterpretationByName(pszVal);
    2162             :             }
    2163             :         }
    2164             : 
    2165         289 :         if (static_cast<int>(adfScale.size()) == nBandCount &&
    2166           8 :             !std::isnan(adfScale[i]))
    2167             :         {
    2168           4 :             poBand->m_dfScale = adfScale[i];
    2169             :         }
    2170         281 :         if (const char *pszScale =
    2171         281 :                 GetOption(CPLSPrintf("BAND_%d_%s", i + 1, MD_BAND_SCALE)))
    2172             :         {
    2173           6 :             poBand->m_dfScale = CPLAtof(pszScale);
    2174             :         }
    2175         281 :         if (!apoXMLNodeBands.empty())
    2176             :         {
    2177             :             const char *pszVal =
    2178           4 :                 CPLGetXMLValue(apoXMLNodeBands[i], GTI_XML_BAND_SCALE, nullptr);
    2179           4 :             if (pszVal)
    2180             :             {
    2181           2 :                 poBand->m_dfScale = CPLAtof(pszVal);
    2182             :             }
    2183             :         }
    2184             : 
    2185         289 :         if (static_cast<int>(adfOffset.size()) == nBandCount &&
    2186           8 :             !std::isnan(adfOffset[i]))
    2187             :         {
    2188           4 :             poBand->m_dfOffset = adfOffset[i];
    2189             :         }
    2190         281 :         if (const char *pszOffset =
    2191         281 :                 GetOption(CPLSPrintf("BAND_%d_%s", i + 1, MD_BAND_OFFSET)))
    2192             :         {
    2193           6 :             poBand->m_dfOffset = CPLAtof(pszOffset);
    2194             :         }
    2195         281 :         if (!apoXMLNodeBands.empty())
    2196             :         {
    2197           4 :             const char *pszVal = CPLGetXMLValue(apoXMLNodeBands[i],
    2198             :                                                 GTI_XML_BAND_OFFSET, nullptr);
    2199           4 :             if (pszVal)
    2200             :             {
    2201           2 :                 poBand->m_dfOffset = CPLAtof(pszVal);
    2202             :             }
    2203             :         }
    2204             : 
    2205         281 :         if (const char *pszUnit =
    2206         281 :                 GetOption(CPLSPrintf("BAND_%d_%s", i + 1, MD_BAND_UNITTYPE)))
    2207             :         {
    2208           6 :             poBand->m_osUnit = pszUnit;
    2209             :         }
    2210         281 :         if (!apoXMLNodeBands.empty())
    2211             :         {
    2212           4 :             const char *pszVal = CPLGetXMLValue(apoXMLNodeBands[i],
    2213             :                                                 GTI_XML_BAND_UNITTYPE, nullptr);
    2214           4 :             if (pszVal)
    2215             :             {
    2216           2 :                 poBand->m_osUnit = pszVal;
    2217             :             }
    2218             :         }
    2219             : 
    2220         281 :         if (!apoXMLNodeBands.empty())
    2221             :         {
    2222           4 :             const CPLXMLNode *psBandNode = apoXMLNodeBands[i];
    2223           4 :             poBand->oMDMD.XMLInit(psBandNode, TRUE);
    2224             : 
    2225           4 :             if (const CPLXMLNode *psCategoryNames =
    2226           4 :                     CPLGetXMLNode(psBandNode, GTI_XML_CATEGORYNAMES))
    2227             :             {
    2228             :                 poBand->m_aosCategoryNames =
    2229           2 :                     VRTParseCategoryNames(psCategoryNames);
    2230             :             }
    2231             : 
    2232           4 :             if (const CPLXMLNode *psColorTable =
    2233           4 :                     CPLGetXMLNode(psBandNode, GTI_XML_COLORTABLE))
    2234             :             {
    2235           2 :                 poBand->m_poColorTable = VRTParseColorTable(psColorTable);
    2236             :             }
    2237             : 
    2238           4 :             if (const CPLXMLNode *psRAT =
    2239           4 :                     CPLGetXMLNode(psBandNode, GTI_XML_RAT))
    2240             :             {
    2241             :                 poBand->m_poRAT =
    2242           2 :                     std::make_unique<GDALDefaultRasterAttributeTable>();
    2243           2 :                 poBand->m_poRAT->XMLInit(psRAT, "");
    2244             :             }
    2245             :         }
    2246             : 
    2247         293 :         if (static_cast<int>(adfCenterWavelength.size()) == nBandCount &&
    2248          12 :             adfCenterWavelength[i] != 0)
    2249             :         {
    2250           5 :             poBand->GDALRasterBand::SetMetadataItem(
    2251             :                 "CENTRAL_WAVELENGTH_UM",
    2252           5 :                 CPLSPrintf("%g", adfCenterWavelength[i]), "IMAGERY");
    2253             :         }
    2254             : 
    2255         293 :         if (static_cast<int>(adfFullWidthHalfMax.size()) == nBandCount &&
    2256          12 :             adfFullWidthHalfMax[i] != 0)
    2257             :         {
    2258           5 :             poBand->GDALRasterBand::SetMetadataItem(
    2259           5 :                 "FWHM_UM", CPLSPrintf("%g", adfFullWidthHalfMax[i]), "IMAGERY");
    2260             :         }
    2261             :     }
    2262             : 
    2263         209 :     if (nBandCount == 1 && poFirstBand && poSingleColorTable &&
    2264           0 :         !poFirstBand->m_poColorTable)
    2265           0 :         poFirstBand->m_poColorTable = std::move(poSingleColorTable);
    2266             : 
    2267         209 :     const char *pszMaskBand = GetOption(MD_MASK_BAND);
    2268         209 :     if (pszMaskBand)
    2269           7 :         bHasMaskBand = CPLTestBool(pszMaskBand);
    2270         209 :     if (bHasMaskBand)
    2271             :     {
    2272           8 :         m_poMaskBand = std::make_unique<GDALTileIndexBand>(
    2273          16 :             this, 0, GDT_UInt8, nBlockXSize, nBlockYSize);
    2274             :     }
    2275             : 
    2276         209 :     if (dfOvrFactor == 1.0)
    2277             :     {
    2278         205 :         if (psRoot)
    2279             :         {
    2280          84 :             for (const CPLXMLNode *psIter = psRoot->psChild; psIter;
    2281          66 :                  psIter = psIter->psNext)
    2282             :             {
    2283          67 :                 if (psIter->eType == CXT_Element &&
    2284          67 :                     strcmp(psIter->pszValue, GTI_XML_OVERVIEW_ELEMENT) == 0)
    2285             :                 {
    2286           9 :                     const char *pszDataset = CPLGetXMLValue(
    2287             :                         psIter, GTI_XML_OVERVIEW_DATASET, nullptr);
    2288             :                     const char *pszLayer =
    2289           9 :                         CPLGetXMLValue(psIter, GTI_XML_OVERVIEW_LAYER, nullptr);
    2290           9 :                     const char *pszFactor = CPLGetXMLValue(
    2291             :                         psIter, GTI_XML_OVERVIEW_FACTOR, nullptr);
    2292           9 :                     if (!pszDataset && !pszLayer && !pszFactor)
    2293             :                     {
    2294           1 :                         CPLError(
    2295             :                             CE_Failure, CPLE_AppDefined,
    2296             :                             "At least one of %s, %s or %s element "
    2297             :                             "must be present as an %s child",
    2298             :                             GTI_XML_OVERVIEW_DATASET, GTI_XML_OVERVIEW_LAYER,
    2299             :                             GTI_XML_OVERVIEW_FACTOR, GTI_XML_OVERVIEW_ELEMENT);
    2300           1 :                         return false;
    2301             :                     }
    2302             :                     m_aoOverviewDescriptor.emplace_back(
    2303          16 :                         std::string(pszDataset ? pszDataset : ""),
    2304          16 :                         CPLStringList(
    2305             :                             GDALDeserializeOpenOptionsFromXML(psIter)),
    2306          16 :                         std::string(pszLayer ? pszLayer : ""),
    2307          24 :                         pszFactor ? CPLAtof(pszFactor) : 0.0);
    2308             :                 }
    2309             :             }
    2310             :         }
    2311             :         else
    2312             :         {
    2313         187 :             for (int iOvr = 0;; ++iOvr)
    2314             :             {
    2315             :                 const char *pszOvrDSName =
    2316         375 :                     GetOption(CPLSPrintf("OVERVIEW_%d_DATASET", iOvr));
    2317             :                 const char *pszOpenOptions =
    2318         375 :                     GetOption(CPLSPrintf("OVERVIEW_%d_OPEN_OPTIONS", iOvr));
    2319             :                 const char *pszOvrLayer =
    2320         375 :                     GetOption(CPLSPrintf("OVERVIEW_%d_LAYER", iOvr));
    2321             :                 const char *pszOvrFactor =
    2322         375 :                     GetOption(CPLSPrintf("OVERVIEW_%d_FACTOR", iOvr));
    2323         375 :                 if (!pszOvrDSName && !pszOvrLayer && !pszOvrFactor)
    2324             :                 {
    2325             :                     // Before GDAL 3.9.2, we started the iteration at 1.
    2326         368 :                     if (iOvr == 0)
    2327         181 :                         continue;
    2328         187 :                     break;
    2329             :                 }
    2330             :                 m_aoOverviewDescriptor.emplace_back(
    2331          14 :                     std::string(pszOvrDSName ? pszOvrDSName : ""),
    2332          14 :                     pszOpenOptions ? CPLStringList(CSLTokenizeString2(
    2333             :                                          pszOpenOptions, ",", 0))
    2334             :                                    : CPLStringList(),
    2335          14 :                     std::string(pszOvrLayer ? pszOvrLayer : ""),
    2336          21 :                     pszOvrFactor ? CPLAtof(pszOvrFactor) : 0.0);
    2337         188 :             }
    2338             :         }
    2339             :     }
    2340             : 
    2341         208 :     if (psRoot)
    2342             :     {
    2343          19 :         oMDMD.XMLInit(psRoot, TRUE);
    2344             :     }
    2345             :     else
    2346             :     {
    2347             :         // Set on the dataset all metadata items from the index layer which are
    2348             :         // not "reserved" keywords.
    2349         189 :         CSLConstList papszLayerMD = m_poLayer->GetMetadata();
    2350         500 :         for (const auto &[pszKey, pszValue] :
    2351         689 :              cpl::IterateNameValue(papszLayerMD))
    2352             :         {
    2353         250 :             if (STARTS_WITH_CI(pszKey, "OVERVIEW_"))
    2354             :             {
    2355          10 :                 continue;
    2356             :             }
    2357             : 
    2358         240 :             bool bIsVRTItem = false;
    2359        3573 :             for (const char *pszTest : apszTIOptions)
    2360             :             {
    2361        3513 :                 if (EQUAL(pszKey, pszTest))
    2362             :                 {
    2363         180 :                     bIsVRTItem = true;
    2364         180 :                     break;
    2365             :                 }
    2366             :             }
    2367         240 :             if (!bIsVRTItem)
    2368             :             {
    2369          60 :                 if (STARTS_WITH_CI(pszKey, "BAND_"))
    2370             :                 {
    2371          52 :                     const int nBandNr = atoi(pszKey + strlen("BAND_"));
    2372             :                     const char *pszNextUnderscore =
    2373          52 :                         strchr(pszKey + strlen("BAND_"), '_');
    2374          52 :                     if (pszNextUnderscore && nBandNr >= 1 && nBandNr <= nBands)
    2375             :                     {
    2376          42 :                         const char *pszKeyWithoutBand = pszNextUnderscore + 1;
    2377          42 :                         bool bIsReservedBandItem = false;
    2378         132 :                         for (const char *pszItem : apszReservedBandItems)
    2379             :                         {
    2380         108 :                             if (EQUAL(pszKeyWithoutBand, pszItem))
    2381             :                             {
    2382          18 :                                 bIsReservedBandItem = true;
    2383          18 :                                 break;
    2384             :                             }
    2385             :                         }
    2386          42 :                         if (!bIsReservedBandItem)
    2387             :                         {
    2388          24 :                             GetRasterBand(nBandNr)
    2389          24 :                                 ->GDALRasterBand::SetMetadataItem(
    2390             :                                     pszKeyWithoutBand, pszValue);
    2391             :                         }
    2392             :                     }
    2393             :                 }
    2394             :                 else
    2395             :                 {
    2396           8 :                     GDALDataset::SetMetadataItem(pszKey, pszValue);
    2397             :                 }
    2398             :             }
    2399             :         }
    2400             :     }
    2401             : 
    2402         208 :     if (nBandCount > 1 && !GetMetadata("IMAGE_STRUCTURE"))
    2403             :     {
    2404          35 :         GDALDataset::SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
    2405             :     }
    2406             : 
    2407             :     /* -------------------------------------------------------------------- */
    2408             :     /*      Initialize any PAM information.                                 */
    2409             :     /* -------------------------------------------------------------------- */
    2410         208 :     SetDescription(poOpenInfo->pszFilename);
    2411         208 :     TryLoadXML();
    2412             : 
    2413             :     /* -------------------------------------------------------------------- */
    2414             :     /*      Check for overviews.                                            */
    2415             :     /* -------------------------------------------------------------------- */
    2416         208 :     oOvManager.Initialize(this, poOpenInfo->pszFilename);
    2417             : 
    2418         208 :     return true;
    2419             : }
    2420             : 
    2421             : /************************************************************************/
    2422             : /*                        GetMetadataItem()                             */
    2423             : /************************************************************************/
    2424             : 
    2425         105 : const char *GDALTileIndexDataset::GetMetadataItem(const char *pszName,
    2426             :                                                   const char *pszDomain)
    2427             : {
    2428         105 :     if (pszName && pszDomain && EQUAL(pszDomain, "__DEBUG__"))
    2429             :     {
    2430          20 :         if (EQUAL(pszName, "SCANNED_ONE_FEATURE_AT_OPENING"))
    2431             :         {
    2432           4 :             return m_bScannedOneFeatureAtOpening ? "YES" : "NO";
    2433             :         }
    2434          16 :         else if (EQUAL(pszName, "NUMBER_OF_CONTRIBUTING_SOURCES"))
    2435             :         {
    2436           5 :             return CPLSPrintf("%d", static_cast<int>(m_aoSourceDesc.size()));
    2437             :         }
    2438          11 :         else if (EQUAL(pszName, "MULTI_THREADED_RASTERIO_LAST_USED"))
    2439             :         {
    2440          11 :             return m_bLastMustUseMultiThreading ? "1" : "0";
    2441             :         }
    2442             :     }
    2443          85 :     return GDALPamDataset::GetMetadataItem(pszName, pszDomain);
    2444             : }
    2445             : 
    2446             : /************************************************************************/
    2447             : /*                TileIndexSupportsEditingLayerMetadata()               */
    2448             : /************************************************************************/
    2449             : 
    2450          17 : bool GDALTileIndexDataset::TileIndexSupportsEditingLayerMetadata() const
    2451             : {
    2452          27 :     return eAccess == GA_Update && m_poVectorDS->GetDriver() &&
    2453          27 :            EQUAL(m_poVectorDS->GetDriver()->GetDescription(), "GPKG");
    2454             : }
    2455             : 
    2456             : /************************************************************************/
    2457             : /*                        SetMetadataItem()                             */
    2458             : /************************************************************************/
    2459             : 
    2460           3 : CPLErr GDALTileIndexDataset::SetMetadataItem(const char *pszName,
    2461             :                                              const char *pszValue,
    2462             :                                              const char *pszDomain)
    2463             : {
    2464           3 :     if (m_bXMLUpdatable)
    2465             :     {
    2466           1 :         m_bXMLModified = true;
    2467           1 :         return GDALDataset::SetMetadataItem(pszName, pszValue, pszDomain);
    2468             :     }
    2469           2 :     else if (TileIndexSupportsEditingLayerMetadata())
    2470             :     {
    2471           1 :         m_poLayer->SetMetadataItem(pszName, pszValue, pszDomain);
    2472           1 :         return GDALDataset::SetMetadataItem(pszName, pszValue, pszDomain);
    2473             :     }
    2474             :     else
    2475             :     {
    2476           1 :         return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
    2477             :     }
    2478             : }
    2479             : 
    2480             : /************************************************************************/
    2481             : /*                           SetMetadata()                              */
    2482             : /************************************************************************/
    2483             : 
    2484           3 : CPLErr GDALTileIndexDataset::SetMetadata(char **papszMD, const char *pszDomain)
    2485             : {
    2486           3 :     if (m_bXMLUpdatable)
    2487             :     {
    2488           1 :         m_bXMLModified = true;
    2489           1 :         return GDALDataset::SetMetadata(papszMD, pszDomain);
    2490             :     }
    2491           2 :     else if (TileIndexSupportsEditingLayerMetadata())
    2492             :     {
    2493           2 :         if (!pszDomain || pszDomain[0] == 0)
    2494             :         {
    2495           4 :             CPLStringList aosMD(CSLDuplicate(papszMD));
    2496             : 
    2497             :             // Reinject dataset reserved items
    2498          44 :             for (const char *pszItem : apszTIOptions)
    2499             :             {
    2500          42 :                 if (!aosMD.FetchNameValue(pszItem))
    2501             :                 {
    2502          42 :                     const char *pszValue = m_poLayer->GetMetadataItem(pszItem);
    2503          42 :                     if (pszValue)
    2504             :                     {
    2505           2 :                         aosMD.SetNameValue(pszItem, pszValue);
    2506             :                     }
    2507             :                 }
    2508             :             }
    2509             : 
    2510             :             // Reinject band metadata
    2511           2 :             char **papszExistingLayerMD = m_poLayer->GetMetadata();
    2512          17 :             for (int i = 0; papszExistingLayerMD && papszExistingLayerMD[i];
    2513             :                  ++i)
    2514             :             {
    2515          15 :                 if (STARTS_WITH_CI(papszExistingLayerMD[i], "BAND_"))
    2516             :                 {
    2517          12 :                     aosMD.AddString(papszExistingLayerMD[i]);
    2518             :                 }
    2519             :             }
    2520             : 
    2521           4 :             m_poLayer->SetMetadata(aosMD.List(), pszDomain);
    2522             :         }
    2523             :         else
    2524             :         {
    2525           0 :             m_poLayer->SetMetadata(papszMD, pszDomain);
    2526             :         }
    2527           2 :         return GDALDataset::SetMetadata(papszMD, pszDomain);
    2528             :     }
    2529             :     else
    2530             :     {
    2531           0 :         return GDALPamDataset::SetMetadata(papszMD, pszDomain);
    2532             :     }
    2533             : }
    2534             : 
    2535             : /************************************************************************/
    2536             : /*                     GDALTileIndexDatasetIdentify()                   */
    2537             : /************************************************************************/
    2538             : 
    2539       91685 : static int GDALTileIndexDatasetIdentify(GDALOpenInfo *poOpenInfo)
    2540             : {
    2541       91685 :     if (STARTS_WITH(poOpenInfo->pszFilename, GTI_PREFIX))
    2542          28 :         return true;
    2543             : 
    2544       91657 :     if (STARTS_WITH(poOpenInfo->pszFilename, "<GDALTileIndexDataset"))
    2545          50 :         return true;
    2546             : 
    2547       91607 :     if (poOpenInfo->nHeaderBytes >= 100 &&
    2548       31811 :         STARTS_WITH(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
    2549             :                     "SQLite format 3"))
    2550             :     {
    2551         925 :         if (ENDS_WITH_CI(poOpenInfo->pszFilename, ".gti.gpkg"))
    2552             :         {
    2553             :             // Most likely handled by GTI driver, but we can't be sure
    2554         499 :             return GDAL_IDENTIFY_UNKNOWN;
    2555             :         }
    2556         428 :         else if (poOpenInfo->IsSingleAllowedDriver("GTI") &&
    2557           2 :                  poOpenInfo->IsExtensionEqualToCI("gpkg"))
    2558             :         {
    2559           2 :             return true;
    2560             :         }
    2561             :     }
    2562             : 
    2563       91106 :     if (poOpenInfo->nHeaderBytes > 0 &&
    2564       31908 :         (poOpenInfo->nOpenFlags & GDAL_OF_RASTER) != 0)
    2565             :     {
    2566       63816 :         if (strstr(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
    2567       31896 :                    "<GDALTileIndexDataset") ||
    2568       63804 :             ENDS_WITH_CI(poOpenInfo->pszFilename, ".gti.fgb") ||
    2569       31896 :             ENDS_WITH_CI(poOpenInfo->pszFilename, ".gti.parquet"))
    2570             :         {
    2571          12 :             return true;
    2572             :         }
    2573       31896 :         else if (poOpenInfo->IsSingleAllowedDriver("GTI") &&
    2574           0 :                  (poOpenInfo->IsExtensionEqualToCI("fgb") ||
    2575           0 :                   poOpenInfo->IsExtensionEqualToCI("parquet")))
    2576             :         {
    2577           0 :             return true;
    2578             :         }
    2579             :     }
    2580             : 
    2581       91094 :     return false;
    2582             : }
    2583             : 
    2584             : /************************************************************************/
    2585             : /*                      GDALTileIndexDatasetOpen()                       */
    2586             : /************************************************************************/
    2587             : 
    2588         280 : static GDALDataset *GDALTileIndexDatasetOpen(GDALOpenInfo *poOpenInfo)
    2589             : {
    2590         280 :     if (GDALTileIndexDatasetIdentify(poOpenInfo) == GDAL_IDENTIFY_FALSE)
    2591           0 :         return nullptr;
    2592         560 :     auto poDS = std::make_unique<GDALTileIndexDataset>();
    2593         280 :     if (!poDS->Open(poOpenInfo))
    2594          72 :         return nullptr;
    2595         208 :     return poDS.release();
    2596             : }
    2597             : 
    2598             : /************************************************************************/
    2599             : /*                          ~GDALTileIndexDataset()                      */
    2600             : /************************************************************************/
    2601             : 
    2602         560 : GDALTileIndexDataset::~GDALTileIndexDataset()
    2603             : {
    2604         280 :     if (m_poVectorDS && m_bIsSQLResultLayer)
    2605           4 :         m_poVectorDS->ReleaseResultSet(m_poLayer);
    2606             : 
    2607         280 :     GDALTileIndexDataset::FlushCache(true);
    2608         560 : }
    2609             : 
    2610             : /************************************************************************/
    2611             : /*                              FlushCache()                            */
    2612             : /************************************************************************/
    2613             : 
    2614         281 : CPLErr GDALTileIndexDataset::FlushCache(bool bAtClosing)
    2615             : {
    2616         281 :     CPLErr eErr = CE_None;
    2617         281 :     if (bAtClosing && m_bXMLModified)
    2618             :     {
    2619             :         CPLXMLNode *psRoot =
    2620           1 :             CPLGetXMLNode(m_psXMLTree.get(), "=GDALTileIndexDataset");
    2621             : 
    2622             :         // Suppress existing dataset metadata
    2623             :         while (true)
    2624             :         {
    2625           1 :             CPLXMLNode *psExistingMetadata = CPLGetXMLNode(psRoot, "Metadata");
    2626           1 :             if (!psExistingMetadata)
    2627           1 :                 break;
    2628           0 :             CPLRemoveXMLChild(psRoot, psExistingMetadata);
    2629           0 :         }
    2630             : 
    2631             :         // Serialize new dataset metadata
    2632           1 :         if (CPLXMLNode *psMD = oMDMD.Serialize())
    2633           1 :             CPLAddXMLChild(psRoot, psMD);
    2634             : 
    2635             :         // Update existing band metadata
    2636           1 :         if (CPLGetXMLNode(psRoot, GTI_XML_BAND_ELEMENT))
    2637             :         {
    2638           0 :             for (CPLXMLNode *psIter = psRoot->psChild; psIter;
    2639           0 :                  psIter = psIter->psNext)
    2640             :             {
    2641           0 :                 if (psIter->eType == CXT_Element &&
    2642           0 :                     strcmp(psIter->pszValue, GTI_XML_BAND_ELEMENT))
    2643             :                 {
    2644             :                     const char *pszBand =
    2645           0 :                         CPLGetXMLValue(psIter, GTI_XML_BAND_NUMBER, nullptr);
    2646           0 :                     if (pszBand)
    2647             :                     {
    2648           0 :                         const int nBand = atoi(pszBand);
    2649           0 :                         if (nBand >= 1 && nBand <= nBands)
    2650             :                         {
    2651             :                             while (true)
    2652             :                             {
    2653             :                                 CPLXMLNode *psExistingMetadata =
    2654           0 :                                     CPLGetXMLNode(psIter, "Metadata");
    2655           0 :                                 if (!psExistingMetadata)
    2656           0 :                                     break;
    2657           0 :                                 CPLRemoveXMLChild(psIter, psExistingMetadata);
    2658           0 :                             }
    2659             : 
    2660           0 :                             auto poBand = cpl::down_cast<GDALTileIndexBand *>(
    2661           0 :                                 papoBands[nBand - 1]);
    2662           0 :                             if (CPLXMLNode *psMD = poBand->oMDMD.Serialize())
    2663           0 :                                 CPLAddXMLChild(psIter, psMD);
    2664             :                         }
    2665             :                     }
    2666             :                 }
    2667             :             }
    2668             :         }
    2669             :         else
    2670             :         {
    2671             :             // Create new band objects if they have metadata
    2672           2 :             std::vector<CPLXMLTreeCloser> aoBandXML;
    2673           1 :             bool bHasBandMD = false;
    2674           2 :             for (int i = 1; i <= nBands; ++i)
    2675             :             {
    2676             :                 auto poBand =
    2677           1 :                     cpl::down_cast<GDALTileIndexBand *>(papoBands[i - 1]);
    2678           1 :                 auto psMD = poBand->oMDMD.Serialize();
    2679           1 :                 if (psMD)
    2680           1 :                     bHasBandMD = true;
    2681           1 :                 aoBandXML.emplace_back(CPLXMLTreeCloser(psMD));
    2682             :             }
    2683           1 :             if (bHasBandMD)
    2684             :             {
    2685           2 :                 for (int i = 1; i <= nBands; ++i)
    2686             :                 {
    2687             :                     auto poBand =
    2688           1 :                         cpl::down_cast<GDALTileIndexBand *>(papoBands[i - 1]);
    2689             : 
    2690           1 :                     CPLXMLNode *psBand = CPLCreateXMLNode(psRoot, CXT_Element,
    2691             :                                                           GTI_XML_BAND_ELEMENT);
    2692           1 :                     CPLAddXMLAttributeAndValue(psBand, GTI_XML_BAND_NUMBER,
    2693             :                                                CPLSPrintf("%d", i));
    2694           1 :                     CPLAddXMLAttributeAndValue(
    2695             :                         psBand, GTI_XML_BAND_DATATYPE,
    2696             :                         GDALGetDataTypeName(poBand->GetRasterDataType()));
    2697             : 
    2698           1 :                     const char *pszDescription = poBand->GetDescription();
    2699           1 :                     if (pszDescription && pszDescription[0])
    2700           0 :                         CPLSetXMLValue(psBand, GTI_XML_BAND_DESCRIPTION,
    2701             :                                        pszDescription);
    2702             : 
    2703           1 :                     const auto eColorInterp = poBand->GetColorInterpretation();
    2704           1 :                     if (eColorInterp != GCI_Undefined)
    2705           1 :                         CPLSetXMLValue(
    2706             :                             psBand, GTI_XML_BAND_COLORINTERP,
    2707             :                             GDALGetColorInterpretationName(eColorInterp));
    2708             : 
    2709           1 :                     if (!std::isnan(poBand->m_dfOffset))
    2710           0 :                         CPLSetXMLValue(psBand, GTI_XML_BAND_OFFSET,
    2711             :                                        CPLSPrintf("%.16g", poBand->m_dfOffset));
    2712             : 
    2713           1 :                     if (!std::isnan(poBand->m_dfScale))
    2714           0 :                         CPLSetXMLValue(psBand, GTI_XML_BAND_SCALE,
    2715             :                                        CPLSPrintf("%.16g", poBand->m_dfScale));
    2716             : 
    2717           1 :                     if (!poBand->m_osUnit.empty())
    2718           0 :                         CPLSetXMLValue(psBand, GTI_XML_BAND_UNITTYPE,
    2719             :                                        poBand->m_osUnit.c_str());
    2720             : 
    2721           1 :                     if (poBand->m_bNoDataValueSet)
    2722             :                     {
    2723           0 :                         CPLSetXMLValue(
    2724             :                             psBand, GTI_XML_BAND_NODATAVALUE,
    2725           0 :                             VRTSerializeNoData(poBand->m_dfNoDataValue,
    2726             :                                                poBand->GetRasterDataType(), 18)
    2727             :                                 .c_str());
    2728             :                     }
    2729           1 :                     if (aoBandXML[i - 1])
    2730             :                     {
    2731           1 :                         CPLAddXMLChild(psBand, aoBandXML[i - 1].release());
    2732             :                     }
    2733             :                 }
    2734             :             }
    2735             :         }
    2736             : 
    2737           1 :         if (!CPLSerializeXMLTreeToFile(m_psXMLTree.get(), GetDescription()))
    2738           0 :             eErr = CE_Failure;
    2739             :     }
    2740             : 
    2741             :     // We also clear the cache of opened sources, in case the user would
    2742             :     // change the content of a source and would want the GTI dataset to see
    2743             :     // the refreshed content.
    2744         281 :     m_oMapSharedSources.clear();
    2745         281 :     m_dfLastMinXFilter = std::numeric_limits<double>::quiet_NaN();
    2746         281 :     m_dfLastMinYFilter = std::numeric_limits<double>::quiet_NaN();
    2747         281 :     m_dfLastMaxXFilter = std::numeric_limits<double>::quiet_NaN();
    2748         281 :     m_dfLastMaxYFilter = std::numeric_limits<double>::quiet_NaN();
    2749         281 :     m_aoSourceDesc.clear();
    2750         281 :     if (GDALPamDataset::FlushCache(bAtClosing) != CE_None)
    2751           0 :         eErr = CE_Failure;
    2752         281 :     return eErr;
    2753             : }
    2754             : 
    2755             : /************************************************************************/
    2756             : /*                            LoadOverviews()                           */
    2757             : /************************************************************************/
    2758             : 
    2759          44 : void GDALTileIndexDataset::LoadOverviews()
    2760             : {
    2761          44 :     if (m_apoOverviews.empty() && !m_aoOverviewDescriptor.empty())
    2762             :     {
    2763          28 :         for (const auto &[osDSName, aosOpenOptions, osLyrName, dfFactor] :
    2764          42 :              m_aoOverviewDescriptor)
    2765             :         {
    2766          28 :             CPLStringList aosNewOpenOptions(aosOpenOptions);
    2767          14 :             if (dfFactor != 0)
    2768             :             {
    2769             :                 aosNewOpenOptions.SetNameValue("@FACTOR",
    2770           4 :                                                CPLSPrintf("%.17g", dfFactor));
    2771             :             }
    2772          14 :             if (!osLyrName.empty())
    2773             :             {
    2774           5 :                 aosNewOpenOptions.SetNameValue("@LAYER", osLyrName.c_str());
    2775             :             }
    2776             : 
    2777             :             std::unique_ptr<GDALDataset> poOvrDS(GDALDataset::Open(
    2778          28 :                 !osDSName.empty() ? osDSName.c_str() : GetDescription(),
    2779             :                 GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR, nullptr,
    2780          56 :                 aosNewOpenOptions.List(), nullptr));
    2781             : 
    2782             :             const auto IsSmaller =
    2783          10 :                 [](const GDALDataset *a, const GDALDataset *b)
    2784             :             {
    2785          10 :                 return (a->GetRasterXSize() < b->GetRasterXSize() &&
    2786          11 :                         a->GetRasterYSize() <= b->GetRasterYSize()) ||
    2787           1 :                        (a->GetRasterYSize() < b->GetRasterYSize() &&
    2788          10 :                         a->GetRasterXSize() <= b->GetRasterXSize());
    2789             :             };
    2790             : 
    2791          32 :             if (poOvrDS &&
    2792          18 :                 ((m_apoOverviews.empty() && IsSmaller(poOvrDS.get(), this)) ||
    2793           1 :                  ((!m_apoOverviews.empty() &&
    2794          14 :                    IsSmaller(poOvrDS.get(), m_apoOverviews.back().get())))))
    2795             :             {
    2796           8 :                 if (poOvrDS->GetRasterCount() == GetRasterCount())
    2797             :                 {
    2798           8 :                     m_apoOverviews.emplace_back(std::move(poOvrDS));
    2799             :                     // Add the overviews of the overview, unless the OVERVIEW_LEVEL
    2800             :                     // option option is specified
    2801           8 :                     if (aosOpenOptions.FetchNameValue("OVERVIEW_LEVEL") ==
    2802             :                         nullptr)
    2803             :                     {
    2804           7 :                         const int nOverviewCount = m_apoOverviews.back()
    2805           7 :                                                        ->GetRasterBand(1)
    2806           7 :                                                        ->GetOverviewCount();
    2807           8 :                         for (int i = 0; i < nOverviewCount; ++i)
    2808             :                         {
    2809             :                             aosNewOpenOptions.SetNameValue("OVERVIEW_LEVEL",
    2810           1 :                                                            CPLSPrintf("%d", i));
    2811             :                             std::unique_ptr<GDALDataset> poOvrOfOvrDS(
    2812             :                                 GDALDataset::Open(
    2813           2 :                                     !osDSName.empty() ? osDSName.c_str()
    2814           0 :                                                       : GetDescription(),
    2815             :                                     GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR,
    2816           1 :                                     nullptr, aosNewOpenOptions.List(),
    2817           3 :                                     nullptr));
    2818           2 :                             if (poOvrOfOvrDS &&
    2819           1 :                                 poOvrOfOvrDS->GetRasterCount() ==
    2820           3 :                                     GetRasterCount() &&
    2821           1 :                                 IsSmaller(poOvrOfOvrDS.get(),
    2822           1 :                                           m_apoOverviews.back().get()))
    2823             :                             {
    2824             :                                 m_apoOverviews.emplace_back(
    2825           1 :                                     std::move(poOvrOfOvrDS));
    2826             :                             }
    2827             :                         }
    2828             :                     }
    2829             :                 }
    2830             :                 else
    2831             :                 {
    2832           0 :                     CPLError(CE_Warning, CPLE_AppDefined,
    2833             :                              "%s has not the same number of bands as %s",
    2834           0 :                              poOvrDS->GetDescription(), GetDescription());
    2835             :                 }
    2836             :             }
    2837             :         }
    2838             :     }
    2839          44 : }
    2840             : 
    2841             : /************************************************************************/
    2842             : /*                          GetOverviewCount()                          */
    2843             : /************************************************************************/
    2844             : 
    2845          68 : int GDALTileIndexBand::GetOverviewCount()
    2846             : {
    2847          68 :     const int nPAMOverviews = GDALPamRasterBand::GetOverviewCount();
    2848          68 :     if (nPAMOverviews)
    2849          24 :         return nPAMOverviews;
    2850             : 
    2851          44 :     m_poDS->LoadOverviews();
    2852          44 :     return static_cast<int>(m_poDS->m_apoOverviews.size());
    2853             : }
    2854             : 
    2855             : /************************************************************************/
    2856             : /*                             GetOverview()                            */
    2857             : /************************************************************************/
    2858             : 
    2859          35 : GDALRasterBand *GDALTileIndexBand::GetOverview(int iOvr)
    2860             : {
    2861          35 :     if (iOvr < 0 || iOvr >= GetOverviewCount())
    2862           6 :         return nullptr;
    2863             : 
    2864          29 :     const int nPAMOverviews = GDALPamRasterBand::GetOverviewCount();
    2865          29 :     if (nPAMOverviews)
    2866          16 :         return GDALPamRasterBand::GetOverview(iOvr);
    2867             : 
    2868          13 :     if (nBand == 0)
    2869             :     {
    2870           1 :         auto poBand = m_poDS->m_apoOverviews[iOvr]->GetRasterBand(1);
    2871           1 :         if (!poBand)
    2872           0 :             return nullptr;
    2873           1 :         return poBand->GetMaskBand();
    2874             :     }
    2875             :     else
    2876             :     {
    2877          12 :         return m_poDS->m_apoOverviews[iOvr]->GetRasterBand(nBand);
    2878             :     }
    2879             : }
    2880             : 
    2881             : /************************************************************************/
    2882             : /*                           GetGeoTransform()                          */
    2883             : /************************************************************************/
    2884             : 
    2885          23 : CPLErr GDALTileIndexDataset::GetGeoTransform(GDALGeoTransform &gt) const
    2886             : {
    2887          23 :     gt = m_gt;
    2888          23 :     return CE_None;
    2889             : }
    2890             : 
    2891             : /************************************************************************/
    2892             : /*                            GetSpatialRef()                           */
    2893             : /************************************************************************/
    2894             : 
    2895          18 : const OGRSpatialReference *GDALTileIndexDataset::GetSpatialRef() const
    2896             : {
    2897          18 :     return m_oSRS.IsEmpty() ? nullptr : &m_oSRS;
    2898             : }
    2899             : 
    2900             : /************************************************************************/
    2901             : /*                           GDALTileIndexBand()                         */
    2902             : /************************************************************************/
    2903             : 
    2904         289 : GDALTileIndexBand::GDALTileIndexBand(GDALTileIndexDataset *poDSIn, int nBandIn,
    2905             :                                      GDALDataType eDT, int nBlockXSizeIn,
    2906         289 :                                      int nBlockYSizeIn)
    2907             : {
    2908         289 :     m_poDS = poDSIn;
    2909         289 :     nBand = nBandIn;
    2910         289 :     eDataType = eDT;
    2911         289 :     nRasterXSize = poDSIn->GetRasterXSize();
    2912         289 :     nRasterYSize = poDSIn->GetRasterYSize();
    2913         289 :     nBlockXSize = nBlockXSizeIn;
    2914         289 :     nBlockYSize = nBlockYSizeIn;
    2915         289 : }
    2916             : 
    2917             : /************************************************************************/
    2918             : /*                             IReadBlock()                             */
    2919             : /************************************************************************/
    2920             : 
    2921          13 : CPLErr GDALTileIndexBand::IReadBlock(int nBlockXOff, int nBlockYOff,
    2922             :                                      void *pImage)
    2923             : 
    2924             : {
    2925          13 :     const int nPixelSize = GDALGetDataTypeSizeBytes(eDataType);
    2926             : 
    2927          13 :     int nReadXSize = nBlockXSize;
    2928          13 :     int nReadYSize = nBlockYSize;
    2929          13 :     GetActualBlockSize(nBlockXOff, nBlockYOff, &nReadXSize, &nReadYSize);
    2930             : 
    2931             :     GDALRasterIOExtraArg sExtraArg;
    2932          13 :     INIT_RASTERIO_EXTRA_ARG(sExtraArg);
    2933             : 
    2934          26 :     return IRasterIO(
    2935          13 :         GF_Read, nBlockXOff * nBlockXSize, nBlockYOff * nBlockYSize, nReadXSize,
    2936             :         nReadYSize, pImage, nReadXSize, nReadYSize, eDataType, nPixelSize,
    2937          26 :         static_cast<GSpacing>(nPixelSize) * nBlockXSize, &sExtraArg);
    2938             : }
    2939             : 
    2940             : /************************************************************************/
    2941             : /*                             IRasterIO()                              */
    2942             : /************************************************************************/
    2943             : 
    2944         142 : CPLErr GDALTileIndexBand::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
    2945             :                                     int nXSize, int nYSize, void *pData,
    2946             :                                     int nBufXSize, int nBufYSize,
    2947             :                                     GDALDataType eBufType, GSpacing nPixelSpace,
    2948             :                                     GSpacing nLineSpace,
    2949             :                                     GDALRasterIOExtraArg *psExtraArg)
    2950             : {
    2951         142 :     int anBand[] = {nBand};
    2952             : 
    2953         142 :     return m_poDS->IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize, pData,
    2954             :                              nBufXSize, nBufYSize, eBufType, 1, anBand,
    2955         284 :                              nPixelSpace, nLineSpace, 0, psExtraArg);
    2956             : }
    2957             : 
    2958             : /************************************************************************/
    2959             : /*                         IGetDataCoverageStatus()                     */
    2960             : /************************************************************************/
    2961             : 
    2962             : #ifndef HAVE_GEOS
    2963             : int GDALTileIndexBand::IGetDataCoverageStatus(int /* nXOff */, int /* nYOff */,
    2964             :                                               int /* nXSize */,
    2965             :                                               int /* nYSize */,
    2966             :                                               int /* nMaskFlagStop */,
    2967             :                                               double *pdfDataPct)
    2968             : {
    2969             :     if (pdfDataPct != nullptr)
    2970             :         *pdfDataPct = -1.0;
    2971             :     return GDAL_DATA_COVERAGE_STATUS_UNIMPLEMENTED |
    2972             :            GDAL_DATA_COVERAGE_STATUS_DATA;
    2973             : }
    2974             : #else
    2975           9 : int GDALTileIndexBand::IGetDataCoverageStatus(int nXOff, int nYOff, int nXSize,
    2976             :                                               int nYSize, int nMaskFlagStop,
    2977             :                                               double *pdfDataPct)
    2978             : {
    2979           9 :     if (pdfDataPct != nullptr)
    2980           9 :         *pdfDataPct = -1.0;
    2981             : 
    2982             :     const double dfMinX =
    2983           9 :         m_poDS->m_gt[GT_TOPLEFT_X] + nXOff * m_poDS->m_gt[GT_WE_RES];
    2984           9 :     const double dfMaxX = dfMinX + nXSize * m_poDS->m_gt[GT_WE_RES];
    2985             :     const double dfMaxY =
    2986           9 :         m_poDS->m_gt[GT_TOPLEFT_Y] + nYOff * m_poDS->m_gt[GT_NS_RES];
    2987           9 :     const double dfMinY = dfMaxY + nYSize * m_poDS->m_gt[GT_NS_RES];
    2988             : 
    2989           9 :     OGRLayer *poSQLLayer = nullptr;
    2990           9 :     if (!m_poDS->m_osSpatialSQL.empty())
    2991             :     {
    2992             :         const std::string osSQL =
    2993           2 :             CPLString(m_poDS->m_osSpatialSQL)
    2994           4 :                 .replaceAll("{XMIN}", CPLSPrintf("%.17g", dfMinX))
    2995           4 :                 .replaceAll("{YMIN}", CPLSPrintf("%.17g", dfMinY))
    2996           4 :                 .replaceAll("{XMAX}", CPLSPrintf("%.17g", dfMaxX))
    2997           4 :                 .replaceAll("{YMAX}", CPLSPrintf("%.17g", dfMaxY));
    2998             :         poSQLLayer =
    2999           2 :             m_poDS->m_poVectorDS->ExecuteSQL(osSQL.c_str(), nullptr, nullptr);
    3000           2 :         if (!poSQLLayer)
    3001           1 :             return 0;
    3002             :     }
    3003             :     else
    3004             :     {
    3005           7 :         m_poDS->m_poLayer->SetSpatialFilterRect(dfMinX, dfMinY, dfMaxX, dfMaxY);
    3006           7 :         m_poDS->m_poLayer->ResetReading();
    3007             :     }
    3008             : 
    3009           8 :     OGRLayer *const poLayer = poSQLLayer ? poSQLLayer : m_poDS->m_poLayer;
    3010             : 
    3011           8 :     int nStatus = 0;
    3012             : 
    3013          16 :     auto poPolyNonCoveredBySources = std::make_unique<OGRPolygon>();
    3014             :     {
    3015          16 :         auto poLR = std::make_unique<OGRLinearRing>();
    3016           8 :         poLR->addPoint(nXOff, nYOff);
    3017           8 :         poLR->addPoint(nXOff, nYOff + nYSize);
    3018           8 :         poLR->addPoint(nXOff + nXSize, nYOff + nYSize);
    3019           8 :         poLR->addPoint(nXOff + nXSize, nYOff);
    3020           8 :         poLR->addPoint(nXOff, nYOff);
    3021           8 :         poPolyNonCoveredBySources->addRingDirectly(poLR.release());
    3022             :     }
    3023             :     while (true)
    3024             :     {
    3025          12 :         auto poFeature = std::unique_ptr<OGRFeature>(poLayer->GetNextFeature());
    3026          12 :         if (!poFeature)
    3027           2 :             break;
    3028          10 :         if (!poFeature->IsFieldSetAndNotNull(m_poDS->m_nLocationFieldIndex))
    3029             :         {
    3030           0 :             continue;
    3031             :         }
    3032             : 
    3033          10 :         const auto poGeom = poFeature->GetGeometryRef();
    3034          10 :         if (!poGeom || poGeom->IsEmpty())
    3035           0 :             continue;
    3036             : 
    3037          10 :         OGREnvelope sSourceEnvelope;
    3038          10 :         poGeom->getEnvelope(&sSourceEnvelope);
    3039             : 
    3040             :         const double dfDstXOff = std::max<double>(
    3041          10 :             nXOff, (sSourceEnvelope.MinX - m_poDS->m_gt[GT_TOPLEFT_X]) /
    3042          10 :                        m_poDS->m_gt[GT_WE_RES]);
    3043             :         const double dfDstXOff2 =
    3044          30 :             std::min<double>(nXOff + nXSize, (sSourceEnvelope.MaxX -
    3045          10 :                                               m_poDS->m_gt[GT_TOPLEFT_X]) /
    3046          10 :                                                  m_poDS->m_gt[GT_WE_RES]);
    3047             :         const double dfDstYOff = std::max<double>(
    3048          10 :             nYOff, (sSourceEnvelope.MaxY - m_poDS->m_gt[GT_TOPLEFT_Y]) /
    3049          10 :                        m_poDS->m_gt[GT_NS_RES]);
    3050             :         const double dfDstYOff2 =
    3051          30 :             std::min<double>(nYOff + nYSize, (sSourceEnvelope.MinY -
    3052          10 :                                               m_poDS->m_gt[GT_TOPLEFT_Y]) /
    3053          10 :                                                  m_poDS->m_gt[GT_NS_RES]);
    3054             : 
    3055             :         // CPLDebug("GTI", "dfDstXOff=%f, dfDstXOff2=%f, dfDstYOff=%f, dfDstYOff2=%f",
    3056             :         //         dfDstXOff, dfDstXOff2, dfDstYOff, dfDstXOff2);
    3057             : 
    3058             :         // Check if the AOI is fully inside the source
    3059          10 :         if (nXOff >= dfDstXOff && nYOff >= dfDstYOff &&
    3060           7 :             nXOff + nXSize <= dfDstXOff2 && nYOff + nYSize <= dfDstYOff2)
    3061             :         {
    3062           4 :             if (pdfDataPct)
    3063           4 :                 *pdfDataPct = 100.0;
    3064           4 :             return GDAL_DATA_COVERAGE_STATUS_DATA;
    3065             :         }
    3066             : 
    3067             :         // Check intersection of bounding boxes.
    3068           6 :         if (dfDstXOff2 > nXOff && dfDstYOff2 > nYOff &&
    3069           6 :             dfDstXOff < nXOff + nXSize && dfDstYOff < nYOff + nYSize)
    3070             :         {
    3071           6 :             nStatus |= GDAL_DATA_COVERAGE_STATUS_DATA;
    3072           6 :             if (poPolyNonCoveredBySources)
    3073             :             {
    3074           6 :                 OGRPolygon oPolySource;
    3075           6 :                 auto poLR = std::make_unique<OGRLinearRing>();
    3076           6 :                 poLR->addPoint(dfDstXOff, dfDstYOff);
    3077           6 :                 poLR->addPoint(dfDstXOff, dfDstYOff2);
    3078           6 :                 poLR->addPoint(dfDstXOff2, dfDstYOff2);
    3079           6 :                 poLR->addPoint(dfDstXOff2, dfDstYOff);
    3080           6 :                 poLR->addPoint(dfDstXOff, dfDstYOff);
    3081           6 :                 oPolySource.addRingDirectly(poLR.release());
    3082             :                 auto poRes = std::unique_ptr<OGRGeometry>(
    3083           6 :                     poPolyNonCoveredBySources->Difference(&oPolySource));
    3084           6 :                 if (poRes && poRes->IsEmpty())
    3085             :                 {
    3086           2 :                     if (pdfDataPct)
    3087           2 :                         *pdfDataPct = 100.0;
    3088           2 :                     return GDAL_DATA_COVERAGE_STATUS_DATA;
    3089             :                 }
    3090           4 :                 else if (poRes && poRes->getGeometryType() == wkbPolygon)
    3091             :                 {
    3092           4 :                     poPolyNonCoveredBySources.reset(
    3093             :                         poRes.release()->toPolygon());
    3094             :                 }
    3095             :                 else
    3096             :                 {
    3097           0 :                     poPolyNonCoveredBySources.reset();
    3098             :                 }
    3099             :             }
    3100             :         }
    3101           4 :         if (nMaskFlagStop != 0 && (nStatus & nMaskFlagStop) != 0)
    3102             :         {
    3103           0 :             if (poSQLLayer)
    3104           0 :                 m_poDS->ReleaseResultSet(poSQLLayer);
    3105           0 :             return nStatus;
    3106             :         }
    3107           4 :     }
    3108             : 
    3109           2 :     if (poSQLLayer)
    3110           0 :         m_poDS->ReleaseResultSet(poSQLLayer);
    3111             : 
    3112           2 :     if (poPolyNonCoveredBySources)
    3113             :     {
    3114           2 :         if (!poPolyNonCoveredBySources->IsEmpty())
    3115           2 :             nStatus |= GDAL_DATA_COVERAGE_STATUS_EMPTY;
    3116           2 :         if (pdfDataPct)
    3117           2 :             *pdfDataPct = 100.0 * (1.0 - poPolyNonCoveredBySources->get_Area() /
    3118           2 :                                              nXSize / nYSize);
    3119             :     }
    3120           2 :     return nStatus;
    3121             : }
    3122             : #endif  // HAVE_GEOS
    3123             : 
    3124             : /************************************************************************/
    3125             : /*                      GetMetadataDomainList()                         */
    3126             : /************************************************************************/
    3127             : 
    3128           1 : char **GDALTileIndexBand::GetMetadataDomainList()
    3129             : {
    3130           1 :     return CSLAddString(GDALRasterBand::GetMetadataDomainList(),
    3131           1 :                         "LocationInfo");
    3132             : }
    3133             : 
    3134             : /************************************************************************/
    3135             : /*                          GetMetadataItem()                           */
    3136             : /************************************************************************/
    3137             : 
    3138          44 : const char *GDALTileIndexBand::GetMetadataItem(const char *pszName,
    3139             :                                                const char *pszDomain)
    3140             : 
    3141             : {
    3142             :     /* ==================================================================== */
    3143             :     /*      LocationInfo handling.                                          */
    3144             :     /* ==================================================================== */
    3145          44 :     if (pszDomain != nullptr && EQUAL(pszDomain, "LocationInfo") &&
    3146          19 :         (STARTS_WITH_CI(pszName, "Pixel_") ||
    3147           6 :          STARTS_WITH_CI(pszName, "GeoPixel_")))
    3148             :     {
    3149             :         // What pixel are we aiming at?
    3150          18 :         int iPixel = 0;
    3151          18 :         int iLine = 0;
    3152             : 
    3153          18 :         if (STARTS_WITH_CI(pszName, "Pixel_"))
    3154             :         {
    3155          13 :             pszName += strlen("Pixel_");
    3156          13 :             iPixel = atoi(pszName);
    3157          13 :             const char *const pszUnderscore = strchr(pszName, '_');
    3158          13 :             if (!pszUnderscore)
    3159           2 :                 return nullptr;
    3160          11 :             iLine = atoi(pszUnderscore + 1);
    3161             :         }
    3162           5 :         else if (STARTS_WITH_CI(pszName, "GeoPixel_"))
    3163             :         {
    3164           5 :             pszName += strlen("GeoPixel_");
    3165           5 :             const double dfGeoX = CPLAtof(pszName);
    3166           5 :             const char *const pszUnderscore = strchr(pszName, '_');
    3167           5 :             if (!pszUnderscore)
    3168           2 :                 return nullptr;
    3169           3 :             const double dfGeoY = CPLAtof(pszUnderscore + 1);
    3170             : 
    3171           3 :             double adfInvGeoTransform[6] = {0.0};
    3172           3 :             if (!GDALInvGeoTransform(m_poDS->m_gt.data(), adfInvGeoTransform))
    3173           0 :                 return nullptr;
    3174             : 
    3175           3 :             iPixel = static_cast<int>(floor(adfInvGeoTransform[0] +
    3176           3 :                                             adfInvGeoTransform[1] * dfGeoX +
    3177           3 :                                             adfInvGeoTransform[2] * dfGeoY));
    3178           3 :             iLine = static_cast<int>(floor(adfInvGeoTransform[3] +
    3179           3 :                                            adfInvGeoTransform[4] * dfGeoX +
    3180           3 :                                            adfInvGeoTransform[5] * dfGeoY));
    3181             :         }
    3182             :         else
    3183             :         {
    3184           0 :             return nullptr;
    3185             :         }
    3186             : 
    3187          23 :         if (iPixel < 0 || iLine < 0 || iPixel >= GetXSize() ||
    3188           9 :             iLine >= GetYSize())
    3189           6 :             return nullptr;
    3190             : 
    3191           8 :         if (!m_poDS->CollectSources(iPixel, iLine, 1, 1,
    3192             :                                     /* bMultiThreadAllowed = */ false))
    3193           0 :             return nullptr;
    3194             : 
    3195             :         // Format into XML.
    3196           8 :         m_osLastLocationInfo = "<LocationInfo>";
    3197             : 
    3198           8 :         if (!m_poDS->m_aoSourceDesc.empty())
    3199             :         {
    3200             :             const auto AddSource =
    3201           6 :                 [&](const GDALTileIndexDataset::SourceDesc &oSourceDesc)
    3202             :             {
    3203           6 :                 m_osLastLocationInfo += "<File>";
    3204             :                 char *const pszXMLEscaped =
    3205           6 :                     CPLEscapeString(oSourceDesc.osName.c_str(), -1, CPLES_XML);
    3206           6 :                 m_osLastLocationInfo += pszXMLEscaped;
    3207           6 :                 CPLFree(pszXMLEscaped);
    3208           6 :                 m_osLastLocationInfo += "</File>";
    3209          11 :             };
    3210             : 
    3211           5 :             const int anBand[] = {nBand};
    3212           5 :             if (!m_poDS->NeedInitBuffer(1, anBand))
    3213             :             {
    3214           4 :                 AddSource(m_poDS->m_aoSourceDesc.back());
    3215             :             }
    3216             :             else
    3217             :             {
    3218           3 :                 for (const auto &oSourceDesc : m_poDS->m_aoSourceDesc)
    3219             :                 {
    3220           2 :                     if (oSourceDesc.poDS)
    3221           2 :                         AddSource(oSourceDesc);
    3222             :                 }
    3223             :             }
    3224             :         }
    3225             : 
    3226           8 :         m_osLastLocationInfo += "</LocationInfo>";
    3227             : 
    3228           8 :         return m_osLastLocationInfo.c_str();
    3229             :     }
    3230             : 
    3231          26 :     return GDALPamRasterBand::GetMetadataItem(pszName, pszDomain);
    3232             : }
    3233             : 
    3234             : /************************************************************************/
    3235             : /*                        SetMetadataItem()                             */
    3236             : /************************************************************************/
    3237             : 
    3238          13 : CPLErr GDALTileIndexBand::SetMetadataItem(const char *pszName,
    3239             :                                           const char *pszValue,
    3240             :                                           const char *pszDomain)
    3241             : {
    3242          13 :     if (nBand > 0 && m_poDS->m_bXMLUpdatable)
    3243             :     {
    3244           1 :         m_poDS->m_bXMLModified = true;
    3245           1 :         return GDALRasterBand::SetMetadataItem(pszName, pszValue, pszDomain);
    3246             :     }
    3247          12 :     else if (nBand > 0 && m_poDS->TileIndexSupportsEditingLayerMetadata())
    3248             :     {
    3249           6 :         m_poDS->m_poLayer->SetMetadataItem(
    3250           6 :             CPLSPrintf("BAND_%d_%s", nBand, pszName), pszValue, pszDomain);
    3251           6 :         return GDALRasterBand::SetMetadataItem(pszName, pszValue, pszDomain);
    3252             :     }
    3253             :     else
    3254             :     {
    3255           6 :         return GDALPamRasterBand::SetMetadataItem(pszName, pszValue, pszDomain);
    3256             :     }
    3257             : }
    3258             : 
    3259             : /************************************************************************/
    3260             : /*                           SetMetadata()                              */
    3261             : /************************************************************************/
    3262             : 
    3263           2 : CPLErr GDALTileIndexBand::SetMetadata(char **papszMD, const char *pszDomain)
    3264             : {
    3265           2 :     if (nBand > 0 && m_poDS->m_bXMLUpdatable)
    3266             :     {
    3267           1 :         m_poDS->m_bXMLModified = true;
    3268           1 :         return GDALRasterBand::SetMetadata(papszMD, pszDomain);
    3269             :     }
    3270           1 :     else if (nBand > 0 && m_poDS->TileIndexSupportsEditingLayerMetadata())
    3271             :     {
    3272           2 :         CPLStringList aosMD;
    3273             : 
    3274           1 :         if (!pszDomain || pszDomain[0] == 0)
    3275             :         {
    3276             :             // Reinject dataset metadata
    3277           1 :             char **papszLayerMD = m_poDS->m_poLayer->GetMetadata(pszDomain);
    3278          14 :             for (const char *const *papszIter = papszLayerMD;
    3279          14 :                  papszIter && *papszIter; ++papszIter)
    3280             :             {
    3281          13 :                 if (!STARTS_WITH(*papszIter, "BAND_") ||
    3282          12 :                     STARTS_WITH(*papszIter, MD_BAND_COUNT))
    3283           1 :                     aosMD.AddString(*papszIter);
    3284             :             }
    3285             :         }
    3286             : 
    3287           8 :         for (int i = 0; papszMD && papszMD[i]; ++i)
    3288             :         {
    3289           7 :             aosMD.AddString(CPLSPrintf("BAND_%d_%s", nBand, papszMD[i]));
    3290             :         }
    3291             : 
    3292           1 :         if (!pszDomain || pszDomain[0] == 0)
    3293             :         {
    3294           4 :             for (const char *pszItem : apszReservedBandItems)
    3295             :             {
    3296           3 :                 const char *pszKey = CPLSPrintf("BAND_%d_%s", nBand, pszItem);
    3297           3 :                 if (!aosMD.FetchNameValue(pszKey))
    3298             :                 {
    3299           3 :                     if (const char *pszVal =
    3300           3 :                             m_poDS->m_poLayer->GetMetadataItem(pszKey))
    3301             :                     {
    3302           3 :                         aosMD.SetNameValue(pszKey, pszVal);
    3303             :                     }
    3304             :                 }
    3305             :             }
    3306             :         }
    3307             : 
    3308           1 :         m_poDS->m_poLayer->SetMetadata(aosMD.List(), pszDomain);
    3309           1 :         return GDALRasterBand::SetMetadata(papszMD, pszDomain);
    3310             :     }
    3311             :     else
    3312             :     {
    3313           0 :         return GDALPamRasterBand::SetMetadata(papszMD, pszDomain);
    3314             :     }
    3315             : }
    3316             : 
    3317             : /************************************************************************/
    3318             : /*                         GetSrcDstWin()                               */
    3319             : /************************************************************************/
    3320             : 
    3321         359 : static bool GetSrcDstWin(const GDALGeoTransform &tileGT, int nTileXSize,
    3322             :                          int nTileYSize, const GDALGeoTransform &vrtGT,
    3323             :                          int nVRTXSize, int nVRTYSize, double *pdfSrcXOff,
    3324             :                          double *pdfSrcYOff, double *pdfSrcXSize,
    3325             :                          double *pdfSrcYSize, double *pdfDstXOff,
    3326             :                          double *pdfDstYOff, double *pdfDstXSize,
    3327             :                          double *pdfDstYSize)
    3328             : {
    3329         359 :     const double minX = vrtGT[GT_TOPLEFT_X];
    3330         359 :     const double we_res = vrtGT[GT_WE_RES];
    3331         359 :     const double maxX = minX + nVRTXSize * we_res;
    3332         359 :     const double maxY = vrtGT[GT_TOPLEFT_Y];
    3333         359 :     const double ns_res = vrtGT[GT_NS_RES];
    3334         359 :     const double minY = maxY + nVRTYSize * ns_res;
    3335             : 
    3336             :     /* Check that the destination bounding box intersects the source bounding
    3337             :      * box */
    3338         359 :     if (tileGT[GT_TOPLEFT_X] + nTileXSize * tileGT[GT_WE_RES] <= minX)
    3339           0 :         return false;
    3340         359 :     if (tileGT[GT_TOPLEFT_X] >= maxX)
    3341           1 :         return false;
    3342         358 :     if (tileGT[GT_TOPLEFT_Y] + nTileYSize * tileGT[GT_NS_RES] >= maxY)
    3343           0 :         return false;
    3344         358 :     if (tileGT[GT_TOPLEFT_Y] <= minY)
    3345           0 :         return false;
    3346             : 
    3347         358 :     if (tileGT[GT_TOPLEFT_X] < minX)
    3348             :     {
    3349           1 :         *pdfSrcXOff = (minX - tileGT[GT_TOPLEFT_X]) / tileGT[GT_WE_RES];
    3350           1 :         *pdfDstXOff = 0.0;
    3351             :     }
    3352             :     else
    3353             :     {
    3354         357 :         *pdfSrcXOff = 0.0;
    3355         357 :         *pdfDstXOff = ((tileGT[GT_TOPLEFT_X] - minX) / we_res);
    3356             :     }
    3357         358 :     if (maxY < tileGT[GT_TOPLEFT_Y])
    3358             :     {
    3359           1 :         *pdfSrcYOff = (tileGT[GT_TOPLEFT_Y] - maxY) / -tileGT[GT_NS_RES];
    3360           1 :         *pdfDstYOff = 0.0;
    3361             :     }
    3362             :     else
    3363             :     {
    3364         357 :         *pdfSrcYOff = 0.0;
    3365         357 :         *pdfDstYOff = ((maxY - tileGT[GT_TOPLEFT_Y]) / -ns_res);
    3366             :     }
    3367             : 
    3368         358 :     *pdfSrcXSize = nTileXSize;
    3369         358 :     *pdfSrcYSize = nTileYSize;
    3370         358 :     if (*pdfSrcXOff > 0)
    3371           1 :         *pdfSrcXSize -= *pdfSrcXOff;
    3372         358 :     if (*pdfSrcYOff > 0)
    3373           1 :         *pdfSrcYSize -= *pdfSrcYOff;
    3374             : 
    3375         358 :     const double dfSrcToDstXSize = tileGT[GT_WE_RES] / we_res;
    3376         358 :     *pdfDstXSize = *pdfSrcXSize * dfSrcToDstXSize;
    3377         358 :     const double dfSrcToDstYSize = tileGT[GT_NS_RES] / ns_res;
    3378         358 :     *pdfDstYSize = *pdfSrcYSize * dfSrcToDstYSize;
    3379             : 
    3380         358 :     if (*pdfDstXOff + *pdfDstXSize > nVRTXSize)
    3381             :     {
    3382           3 :         *pdfDstXSize = nVRTXSize - *pdfDstXOff;
    3383           3 :         *pdfSrcXSize = *pdfDstXSize / dfSrcToDstXSize;
    3384             :     }
    3385             : 
    3386         358 :     if (*pdfDstYOff + *pdfDstYSize > nVRTYSize)
    3387             :     {
    3388           1 :         *pdfDstYSize = nVRTYSize - *pdfDstYOff;
    3389           1 :         *pdfSrcYSize = *pdfDstYSize / dfSrcToDstYSize;
    3390             :     }
    3391             : 
    3392         716 :     return *pdfSrcXSize > 0 && *pdfDstXSize > 0 && *pdfSrcYSize > 0 &&
    3393         716 :            *pdfDstYSize > 0;
    3394             : }
    3395             : 
    3396             : /************************************************************************/
    3397             : /*                   GDALDatasetCastToGTIDataset()                    */
    3398             : /************************************************************************/
    3399             : 
    3400           3 : GDALTileIndexDataset *GDALDatasetCastToGTIDataset(GDALDataset *poDS)
    3401             : {
    3402           3 :     return dynamic_cast<GDALTileIndexDataset *>(poDS);
    3403             : }
    3404             : 
    3405             : /************************************************************************/
    3406             : /*                   GTIGetSourcesMoreRecentThan()                    */
    3407             : /************************************************************************/
    3408             : 
    3409             : std::vector<GTISourceDesc>
    3410           2 : GTIGetSourcesMoreRecentThan(GDALTileIndexDataset *poDS, int64_t mTime)
    3411             : {
    3412           2 :     return poDS->GetSourcesMoreRecentThan(mTime);
    3413             : }
    3414             : 
    3415             : /************************************************************************/
    3416             : /*                       GetSourcesMoreRecentThan()                     */
    3417             : /************************************************************************/
    3418             : 
    3419             : std::vector<GTISourceDesc>
    3420           2 : GDALTileIndexDataset::GetSourcesMoreRecentThan(int64_t mTime)
    3421             : {
    3422           2 :     std::vector<GTISourceDesc> oRes;
    3423             : 
    3424           2 :     m_poLayer->SetSpatialFilter(nullptr);
    3425           6 :     for (auto &&poFeature : m_poLayer)
    3426             :     {
    3427           4 :         if (!poFeature->IsFieldSetAndNotNull(m_nLocationFieldIndex))
    3428             :         {
    3429           2 :             continue;
    3430             :         }
    3431             : 
    3432           4 :         auto poGeom = poFeature->GetGeometryRef();
    3433           4 :         if (!poGeom || poGeom->IsEmpty())
    3434           0 :             continue;
    3435             : 
    3436           4 :         OGREnvelope sEnvelope;
    3437           4 :         poGeom->getEnvelope(&sEnvelope);
    3438             : 
    3439           4 :         double dfXOff = (sEnvelope.MinX - m_gt[GT_TOPLEFT_X]) / m_gt[GT_WE_RES];
    3440           4 :         if (dfXOff >= nRasterXSize)
    3441           0 :             continue;
    3442             : 
    3443           4 :         double dfYOff = (sEnvelope.MaxY - m_gt[GT_TOPLEFT_Y]) / m_gt[GT_NS_RES];
    3444           4 :         if (dfYOff >= nRasterYSize)
    3445           0 :             continue;
    3446             : 
    3447           4 :         double dfXSize = (sEnvelope.MaxX - sEnvelope.MinX) / m_gt[GT_WE_RES];
    3448           4 :         if (dfXOff < 0)
    3449             :         {
    3450           0 :             dfXSize += dfXOff;
    3451           0 :             dfXOff = 0;
    3452           0 :             if (dfXSize <= 0)
    3453           0 :                 continue;
    3454             :         }
    3455             : 
    3456             :         double dfYSize =
    3457           4 :             (sEnvelope.MaxY - sEnvelope.MinY) / std::fabs(m_gt[GT_NS_RES]);
    3458           4 :         if (dfYOff < 0)
    3459             :         {
    3460           0 :             dfYSize += dfYOff;
    3461           0 :             dfYOff = 0;
    3462           0 :             if (dfYSize <= 0)
    3463           0 :                 continue;
    3464             :         }
    3465             : 
    3466             :         const char *pszTileName =
    3467           4 :             poFeature->GetFieldAsString(m_nLocationFieldIndex);
    3468             :         std::string osTileName(GetAbsoluteFileName(
    3469           4 :             pszTileName, GetDescription(), m_bSTACCollection));
    3470             :         VSIStatBufL sStatSource;
    3471           8 :         if (VSIStatL(osTileName.c_str(), &sStatSource) != 0 ||
    3472           4 :             sStatSource.st_mtime <= mTime)
    3473             :         {
    3474           2 :             continue;
    3475             :         }
    3476             : 
    3477           2 :         constexpr double EPS = 1e-8;
    3478           4 :         GTISourceDesc oSourceDesc;
    3479           2 :         oSourceDesc.osFilename = std::move(osTileName);
    3480           2 :         oSourceDesc.nDstXOff = static_cast<int>(dfXOff + EPS);
    3481           2 :         oSourceDesc.nDstYOff = static_cast<int>(dfYOff + EPS);
    3482           2 :         oSourceDesc.nDstXSize = static_cast<int>(dfXSize + 0.5);
    3483           2 :         oSourceDesc.nDstYSize = static_cast<int>(dfYSize + 0.5);
    3484           2 :         oRes.emplace_back(std::move(oSourceDesc));
    3485             :     }
    3486             : 
    3487           2 :     return oRes;
    3488             : }
    3489             : 
    3490             : /************************************************************************/
    3491             : /*                         GetSourceDesc()                              */
    3492             : /************************************************************************/
    3493             : 
    3494         362 : bool GDALTileIndexDataset::GetSourceDesc(const std::string &osTileName,
    3495             :                                          SourceDesc &oSourceDesc,
    3496             :                                          std::mutex *pMutex)
    3497             : {
    3498         362 :     std::shared_ptr<GDALDataset> poTileDS;
    3499             : 
    3500         362 :     if (pMutex)
    3501         138 :         pMutex->lock();
    3502         362 :     const bool bTileKnown = m_oMapSharedSources.tryGet(osTileName, poTileDS);
    3503         362 :     if (pMutex)
    3504         138 :         pMutex->unlock();
    3505             : 
    3506         362 :     if (!bTileKnown)
    3507             :     {
    3508         472 :         poTileDS = std::shared_ptr<GDALDataset>(
    3509             :             GDALProxyPoolDataset::Create(
    3510             :                 osTileName.c_str(), nullptr, GA_ReadOnly,
    3511             :                 /* bShared = */ true, m_osUniqueHandle.c_str()),
    3512         236 :             GDALDatasetUniquePtrReleaser());
    3513         236 :         if (!poTileDS)
    3514             :         {
    3515           3 :             CPLError(CE_Failure, CPLE_AppDefined, "Cannot open source %s",
    3516             :                      osTileName.c_str());
    3517           3 :             return false;
    3518             :         }
    3519         233 :         if (poTileDS->GetRasterCount() == 0)
    3520             :         {
    3521           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    3522             :                      "Source %s has no raster bands", osTileName.c_str());
    3523           0 :             return false;
    3524             :         }
    3525             : 
    3526             :         // do palette -> RGB(A) expansion if needed
    3527         233 :         if (!GTIDoPaletteExpansionIfNeeded(poTileDS, nBands))
    3528           0 :             return false;
    3529             : 
    3530         233 :         bool bWarpVRT = false;
    3531         233 :         bool bExportSRS = false;
    3532         233 :         bool bAddAlphaToVRT = false;
    3533         233 :         const OGRSpatialReference *poTileSRS = poTileDS->GetSpatialRef();
    3534         233 :         GDALGeoTransform tileGT;
    3535         404 :         if (!m_oSRS.IsEmpty() && poTileSRS != nullptr &&
    3536         171 :             !m_oSRS.IsSame(poTileSRS))
    3537             :         {
    3538           2 :             CPLDebug("VRT",
    3539             :                      "Tile %s has not the same SRS as the VRT. "
    3540             :                      "Proceed to on-the-fly warping",
    3541             :                      osTileName.c_str());
    3542           2 :             bWarpVRT = true;
    3543           2 :             bExportSRS = true;
    3544           2 :             bAddAlphaToVRT = true;
    3545             :         }
    3546         231 :         else if (poTileDS->GetGeoTransform(tileGT) == CE_None &&
    3547         232 :                  tileGT[GT_NS_RES] > 0 &&
    3548           1 :                  ((m_oSRS.IsEmpty() && poTileSRS == nullptr) ||
    3549           0 :                   (!m_oSRS.IsEmpty() && poTileSRS && m_oSRS.IsSame(poTileSRS))))
    3550             : 
    3551             :         {
    3552           1 :             CPLDebug("VRT",
    3553             :                      "Tile %s is south-up oriented. "
    3554             :                      "Proceed to on-the-fly warping",
    3555             :                      osTileName.c_str());
    3556           1 :             bWarpVRT = true;
    3557             :         }
    3558             : 
    3559         233 :         if (bWarpVRT)
    3560             :         {
    3561           3 :             CPLStringList aosOptions;
    3562           3 :             aosOptions.AddString("-of");
    3563           3 :             aosOptions.AddString("VRT");
    3564             : 
    3565           3 :             if ((poTileDS->GetRasterBand(1)->GetColorTable() == nullptr &&
    3566           3 :                  poTileDS->GetRasterBand(1)->GetCategoryNames() == nullptr) ||
    3567           0 :                 m_eResampling == GRIORA_Mode)
    3568             :             {
    3569           3 :                 aosOptions.AddString("-r");
    3570           3 :                 aosOptions.AddString(m_osResampling.c_str());
    3571             :             }
    3572             : 
    3573           3 :             if (bExportSRS)
    3574             :             {
    3575           2 :                 if (m_osWKT.empty())
    3576             :                 {
    3577           0 :                     char *pszWKT = nullptr;
    3578           0 :                     const char *const apszWKTOptions[] = {"FORMAT=WKT2_2019",
    3579             :                                                           nullptr};
    3580           0 :                     m_oSRS.exportToWkt(&pszWKT, apszWKTOptions);
    3581           0 :                     if (pszWKT)
    3582           0 :                         m_osWKT = pszWKT;
    3583           0 :                     CPLFree(pszWKT);
    3584             : 
    3585           0 :                     if (m_osWKT.empty())
    3586             :                     {
    3587           0 :                         CPLError(CE_Failure, CPLE_AppDefined,
    3588             :                                  "Cannot export VRT SRS to WKT2");
    3589           0 :                         return false;
    3590             :                     }
    3591             :                 }
    3592             : 
    3593           2 :                 aosOptions.AddString("-t_srs");
    3594           2 :                 aosOptions.AddString(m_osWKT.c_str());
    3595             :             }
    3596             : 
    3597             :             // First pass to get the extent of the tile in the
    3598             :             // target VRT SRS
    3599             :             GDALWarpAppOptions *psWarpOptions =
    3600           3 :                 GDALWarpAppOptionsNew(aosOptions.List(), nullptr);
    3601           3 :             GDALDatasetH ahSrcDS[] = {GDALDataset::ToHandle(poTileDS.get())};
    3602           3 :             int bUsageError = false;
    3603             :             auto poWarpDS =
    3604             :                 std::unique_ptr<GDALDataset>(GDALDataset::FromHandle(GDALWarp(
    3605           3 :                     "", nullptr, 1, ahSrcDS, psWarpOptions, &bUsageError)));
    3606           3 :             GDALWarpAppOptionsFree(psWarpOptions);
    3607           3 :             if (!poWarpDS)
    3608             :             {
    3609           0 :                 return false;
    3610             :             }
    3611             : 
    3612             :             // Second pass to create a warped source VRT whose
    3613             :             // extent is aligned on the one of the target VRT
    3614           3 :             GDALGeoTransform warpDSGT;
    3615           3 :             const auto eErr = poWarpDS->GetGeoTransform(warpDSGT);
    3616           3 :             CPL_IGNORE_RET_VAL(eErr);
    3617           3 :             CPLAssert(eErr == CE_None);
    3618           3 :             const double dfVRTMinX = m_gt[GT_TOPLEFT_X];
    3619           3 :             const double dfVRTResX = m_gt[GT_WE_RES];
    3620           3 :             const double dfVRTMaxY = m_gt[GT_TOPLEFT_Y];
    3621           3 :             const double dfVRTResYAbs = -m_gt[GT_NS_RES];
    3622             :             const double dfWarpMinX =
    3623           3 :                 std::floor((warpDSGT[GT_TOPLEFT_X] - dfVRTMinX) / dfVRTResX) *
    3624             :                     dfVRTResX +
    3625           3 :                 dfVRTMinX;
    3626             :             const double dfWarpMaxX =
    3627           3 :                 std::ceil((warpDSGT[GT_TOPLEFT_X] +
    3628           3 :                            warpDSGT[GT_WE_RES] * poWarpDS->GetRasterXSize() -
    3629             :                            dfVRTMinX) /
    3630           3 :                           dfVRTResX) *
    3631             :                     dfVRTResX +
    3632           3 :                 dfVRTMinX;
    3633             :             const double dfWarpMaxY =
    3634           3 :                 dfVRTMaxY - std::floor((dfVRTMaxY - warpDSGT[GT_TOPLEFT_Y]) /
    3635           3 :                                        dfVRTResYAbs) *
    3636           3 :                                 dfVRTResYAbs;
    3637             :             const double dfWarpMinY =
    3638             :                 dfVRTMaxY -
    3639           3 :                 std::ceil((dfVRTMaxY -
    3640           3 :                            (warpDSGT[GT_TOPLEFT_Y] +
    3641           3 :                             warpDSGT[GT_NS_RES] * poWarpDS->GetRasterYSize())) /
    3642           3 :                           dfVRTResYAbs) *
    3643           3 :                     dfVRTResYAbs;
    3644             : 
    3645           3 :             aosOptions.AddString("-te");
    3646           3 :             aosOptions.AddString(CPLSPrintf("%.17g", dfWarpMinX));
    3647           3 :             aosOptions.AddString(CPLSPrintf("%.17g", dfWarpMinY));
    3648           3 :             aosOptions.AddString(CPLSPrintf("%.17g", dfWarpMaxX));
    3649           3 :             aosOptions.AddString(CPLSPrintf("%.17g", dfWarpMaxY));
    3650             : 
    3651           3 :             aosOptions.AddString("-tr");
    3652           3 :             aosOptions.AddString(CPLSPrintf("%.17g", dfVRTResX));
    3653           3 :             aosOptions.AddString(CPLSPrintf("%.17g", dfVRTResYAbs));
    3654             : 
    3655           3 :             if (bAddAlphaToVRT)
    3656           2 :                 aosOptions.AddString("-dstalpha");
    3657             : 
    3658           3 :             psWarpOptions = GDALWarpAppOptionsNew(aosOptions.List(), nullptr);
    3659           3 :             poWarpDS.reset(GDALDataset::FromHandle(GDALWarp(
    3660             :                 "", nullptr, 1, ahSrcDS, psWarpOptions, &bUsageError)));
    3661           3 :             GDALWarpAppOptionsFree(psWarpOptions);
    3662           3 :             if (!poWarpDS)
    3663             :             {
    3664           0 :                 return false;
    3665             :             }
    3666             : 
    3667           3 :             poTileDS.reset(poWarpDS.release());
    3668             :         }
    3669             : 
    3670         233 :         if (pMutex)
    3671          70 :             pMutex->lock();
    3672         233 :         m_oMapSharedSources.insert(osTileName, poTileDS);
    3673         233 :         if (pMutex)
    3674          70 :             pMutex->unlock();
    3675             :     }
    3676             : 
    3677         359 :     GDALGeoTransform gtTile;
    3678         359 :     if (poTileDS->GetGeoTransform(gtTile) != CE_None)
    3679             :     {
    3680           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s lacks geotransform",
    3681             :                  osTileName.c_str());
    3682           0 :         return false;
    3683             :     }
    3684             : 
    3685         359 :     bool bHasNoData = false;
    3686         359 :     bool bSameNoData = true;
    3687         359 :     double dfNoDataValue = 0;
    3688         359 :     GDALRasterBand *poMaskBand = nullptr;
    3689         359 :     const int nBandCount = poTileDS->GetRasterCount();
    3690        1235 :     for (int iBand = 0; iBand < nBandCount; ++iBand)
    3691             :     {
    3692         876 :         auto poTileBand = poTileDS->GetRasterBand(iBand + 1);
    3693         876 :         int bThisBandHasNoData = false;
    3694             :         const double dfThisBandNoDataValue =
    3695         876 :             poTileBand->GetNoDataValue(&bThisBandHasNoData);
    3696         876 :         if (bThisBandHasNoData)
    3697             :         {
    3698          22 :             bHasNoData = true;
    3699          22 :             dfNoDataValue = dfThisBandNoDataValue;
    3700             :         }
    3701        1393 :         if (iBand > 0 &&
    3702         517 :             (static_cast<int>(bThisBandHasNoData) !=
    3703         517 :                  static_cast<int>(bHasNoData) ||
    3704          12 :              (bHasNoData &&
    3705          12 :               !IsSameNaNAware(dfNoDataValue, dfThisBandNoDataValue))))
    3706             :         {
    3707           0 :             bSameNoData = false;
    3708             :         }
    3709             : 
    3710         876 :         if (poTileBand->GetMaskFlags() == GMF_PER_DATASET)
    3711           2 :             poMaskBand = poTileBand->GetMaskBand();
    3712         874 :         else if (poTileBand->GetColorInterpretation() == GCI_AlphaBand)
    3713          31 :             poMaskBand = poTileBand;
    3714             :     }
    3715             : 
    3716           0 :     std::unique_ptr<VRTSimpleSource> poSource;
    3717         359 :     if (!bHasNoData)
    3718             :     {
    3719         349 :         poSource = std::make_unique<VRTSimpleSource>();
    3720             :     }
    3721             :     else
    3722             :     {
    3723          20 :         auto poComplexSource = std::make_unique<VRTComplexSource>();
    3724          10 :         poComplexSource->SetNoDataValue(dfNoDataValue);
    3725          10 :         poSource = std::move(poComplexSource);
    3726             :     }
    3727             : 
    3728         718 :     GetSrcDstWin(gtTile, poTileDS->GetRasterXSize(), poTileDS->GetRasterYSize(),
    3729         359 :                  m_gt, GetRasterXSize(), GetRasterYSize(),
    3730         359 :                  &poSource->m_dfSrcXOff, &poSource->m_dfSrcYOff,
    3731         359 :                  &poSource->m_dfSrcXSize, &poSource->m_dfSrcYSize,
    3732         359 :                  &poSource->m_dfDstXOff, &poSource->m_dfDstYOff,
    3733         359 :                  &poSource->m_dfDstXSize, &poSource->m_dfDstYSize);
    3734             : 
    3735         359 :     oSourceDesc.osName = osTileName;
    3736         359 :     oSourceDesc.poDS = std::move(poTileDS);
    3737         359 :     oSourceDesc.poSource = std::move(poSource);
    3738         359 :     oSourceDesc.bHasNoData = bHasNoData;
    3739         359 :     oSourceDesc.bSameNoData = bSameNoData;
    3740         359 :     if (bSameNoData)
    3741         359 :         oSourceDesc.dfSameNoData = dfNoDataValue;
    3742         359 :     oSourceDesc.poMaskBand = poMaskBand;
    3743         359 :     return true;
    3744             : }
    3745             : 
    3746             : /************************************************************************/
    3747             : /*                           GetNumThreads()                            */
    3748             : /************************************************************************/
    3749             : 
    3750           8 : int GDALTileIndexDataset::GetNumThreads() const
    3751             : {
    3752             :     const char *pszNumThreads =
    3753           8 :         CSLFetchNameValueDef(GetOpenOptions(), "NUM_THREADS", nullptr);
    3754           8 :     if (!pszNumThreads)
    3755           8 :         pszNumThreads = CPLGetConfigOption("GTI_NUM_THREADS", nullptr);
    3756           8 :     if (!pszNumThreads)
    3757           6 :         pszNumThreads = CPLGetConfigOption("GDAL_NUM_THREADS", "ALL_CPUS");
    3758           8 :     if (EQUAL(pszNumThreads, "0") || EQUAL(pszNumThreads, "1"))
    3759           3 :         return atoi(pszNumThreads);
    3760           5 :     const int nMaxPoolSize = GDALGetMaxDatasetPoolSize();
    3761           5 :     const int nLimit = std::min(CPLGetNumCPUs(), nMaxPoolSize);
    3762           5 :     if (EQUAL(pszNumThreads, "ALL_CPUS"))
    3763           5 :         return nLimit;
    3764           0 :     return std::min(atoi(pszNumThreads), nLimit);
    3765             : }
    3766             : 
    3767             : /************************************************************************/
    3768             : /*                        CollectSources()                              */
    3769             : /************************************************************************/
    3770             : 
    3771         190 : bool GDALTileIndexDataset::CollectSources(double dfXOff, double dfYOff,
    3772             :                                           double dfXSize, double dfYSize,
    3773             :                                           bool bMultiThreadAllowed)
    3774             : {
    3775         190 :     const double dfMinX = m_gt[GT_TOPLEFT_X] + dfXOff * m_gt[GT_WE_RES];
    3776         190 :     const double dfMaxX = dfMinX + dfXSize * m_gt[GT_WE_RES];
    3777         190 :     const double dfMaxY = m_gt[GT_TOPLEFT_Y] + dfYOff * m_gt[GT_NS_RES];
    3778         190 :     const double dfMinY = dfMaxY + dfYSize * m_gt[GT_NS_RES];
    3779             : 
    3780         190 :     if (dfMinX == m_dfLastMinXFilter && dfMinY == m_dfLastMinYFilter &&
    3781          57 :         dfMaxX == m_dfLastMaxXFilter && dfMaxY == m_dfLastMaxYFilter)
    3782             :     {
    3783          53 :         return true;
    3784             :     }
    3785             : 
    3786         137 :     m_dfLastMinXFilter = dfMinX;
    3787         137 :     m_dfLastMinYFilter = dfMinY;
    3788         137 :     m_dfLastMaxXFilter = dfMaxX;
    3789         137 :     m_dfLastMaxYFilter = dfMaxY;
    3790         137 :     m_bLastMustUseMultiThreading = false;
    3791             : 
    3792         137 :     OGRLayer *poSQLLayer = nullptr;
    3793         137 :     if (!m_osSpatialSQL.empty())
    3794             :     {
    3795             :         const std::string osSQL =
    3796           3 :             CPLString(m_osSpatialSQL)
    3797           6 :                 .replaceAll("{XMIN}", CPLSPrintf("%.17g", dfMinX))
    3798           6 :                 .replaceAll("{YMIN}", CPLSPrintf("%.17g", dfMinY))
    3799           6 :                 .replaceAll("{XMAX}", CPLSPrintf("%.17g", dfMaxX))
    3800           6 :                 .replaceAll("{YMAX}", CPLSPrintf("%.17g", dfMaxY));
    3801           3 :         poSQLLayer = m_poVectorDS->ExecuteSQL(osSQL.c_str(), nullptr, nullptr);
    3802           3 :         if (!poSQLLayer)
    3803           1 :             return 0;
    3804             :     }
    3805             :     else
    3806             :     {
    3807         134 :         m_poLayer->SetSpatialFilterRect(dfMinX, dfMinY, dfMaxX, dfMaxY);
    3808         134 :         m_poLayer->ResetReading();
    3809             :     }
    3810             : 
    3811         136 :     OGRLayer *const poLayer = poSQLLayer ? poSQLLayer : m_poLayer;
    3812             : 
    3813         136 :     m_aoSourceDesc.clear();
    3814             :     while (true)
    3815             :     {
    3816         465 :         auto poFeature = std::unique_ptr<OGRFeature>(poLayer->GetNextFeature());
    3817         465 :         if (!poFeature)
    3818         136 :             break;
    3819         329 :         if (!poFeature->IsFieldSetAndNotNull(m_nLocationFieldIndex))
    3820             :         {
    3821           1 :             continue;
    3822             :         }
    3823             : 
    3824         328 :         SourceDesc oSourceDesc;
    3825         328 :         oSourceDesc.poFeature = std::move(poFeature);
    3826         328 :         m_aoSourceDesc.emplace_back(std::move(oSourceDesc));
    3827             : 
    3828         328 :         if (m_aoSourceDesc.size() > 10 * 1000 * 1000)
    3829             :         {
    3830             :             // Safety belt...
    3831           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    3832             :                      "More than 10 million contributing sources to a "
    3833             :                      "single RasterIO() request is not supported");
    3834           0 :             return false;
    3835             :         }
    3836         329 :     }
    3837             : 
    3838         136 :     if (poSQLLayer)
    3839           2 :         ReleaseResultSet(poSQLLayer);
    3840             : 
    3841         136 :     constexpr int MINIMUM_PIXEL_COUNT_FOR_THREADED_IO = 1000 * 1000;
    3842         205 :     if (bMultiThreadAllowed && m_aoSourceDesc.size() > 1 &&
    3843          69 :         dfXSize * dfYSize > MINIMUM_PIXEL_COUNT_FOR_THREADED_IO)
    3844             :     {
    3845           8 :         if (m_nNumThreads < 0)
    3846           8 :             m_nNumThreads = GetNumThreads();
    3847           8 :         bMultiThreadAllowed = m_nNumThreads > 1;
    3848             :     }
    3849             :     else
    3850             :     {
    3851         128 :         bMultiThreadAllowed = false;
    3852             :     }
    3853             : 
    3854         136 :     if (bMultiThreadAllowed)
    3855             :     {
    3856             :         CPLRectObj sGlobalBounds;
    3857           5 :         sGlobalBounds.minx = dfXOff;
    3858           5 :         sGlobalBounds.miny = dfYOff;
    3859           5 :         sGlobalBounds.maxx = dfXOff + dfXSize;
    3860           5 :         sGlobalBounds.maxy = dfYOff + dfYSize;
    3861           5 :         CPLQuadTree *hQuadTree = CPLQuadTreeCreate(&sGlobalBounds, nullptr);
    3862             : 
    3863           5 :         bool bCompatibleOfMultiThread = true;
    3864           5 :         std::set<std::string> oSetTileNames;
    3865          77 :         for (const auto &oSourceDesc : m_aoSourceDesc)
    3866             :         {
    3867             :             const char *pszTileName =
    3868          73 :                 oSourceDesc.poFeature->GetFieldAsString(m_nLocationFieldIndex);
    3869          73 :             if (oSetTileNames.find(pszTileName) != oSetTileNames.end())
    3870             :             {
    3871           0 :                 bCompatibleOfMultiThread = false;
    3872           1 :                 break;
    3873             :             }
    3874          73 :             oSetTileNames.insert(pszTileName);
    3875             : 
    3876          73 :             const auto poGeom = oSourceDesc.poFeature->GetGeometryRef();
    3877          73 :             if (!poGeom || poGeom->IsEmpty())
    3878           0 :                 continue;
    3879             : 
    3880          73 :             OGREnvelope sEnvelope;
    3881          73 :             poGeom->getEnvelope(&sEnvelope);
    3882             : 
    3883             :             CPLRectObj sSourceBounds;
    3884          73 :             sSourceBounds.minx =
    3885          73 :                 (sEnvelope.MinX - m_gt[GT_TOPLEFT_X]) / m_gt[GT_WE_RES];
    3886          73 :             sSourceBounds.maxx =
    3887          73 :                 (sEnvelope.MaxX - m_gt[GT_TOPLEFT_X]) / m_gt[GT_WE_RES];
    3888             :             // Yes use of MaxY to compute miny is intended given that MaxY is
    3889             :             // in georeferenced space whereas miny is in pixel space.
    3890          73 :             sSourceBounds.miny =
    3891          73 :                 (sEnvelope.MaxY - m_gt[GT_TOPLEFT_Y]) / m_gt[GT_NS_RES];
    3892             :             // Same here for maxy vs Miny
    3893          73 :             sSourceBounds.maxy =
    3894          73 :                 (sEnvelope.MinY - m_gt[GT_TOPLEFT_Y]) / m_gt[GT_NS_RES];
    3895             : 
    3896             :             // Clamp to global bounds and some epsilon to avoid adjacent tiles
    3897             :             // to be considered as overlapping
    3898          73 :             constexpr double EPSILON = 0.1;
    3899          73 :             sSourceBounds.minx =
    3900          73 :                 std::max(sGlobalBounds.minx, sSourceBounds.minx) + EPSILON;
    3901          73 :             sSourceBounds.maxx =
    3902          73 :                 std::min(sGlobalBounds.maxx, sSourceBounds.maxx) - EPSILON;
    3903          73 :             sSourceBounds.miny =
    3904          73 :                 std::max(sGlobalBounds.miny, sSourceBounds.miny) + EPSILON;
    3905          73 :             sSourceBounds.maxy =
    3906          73 :                 std::min(sGlobalBounds.maxy, sSourceBounds.maxy) - EPSILON;
    3907             : 
    3908             :             // Check that the new source doesn't overlap an existing one.
    3909          73 :             if (CPLQuadTreeHasMatch(hQuadTree, &sSourceBounds))
    3910             :             {
    3911           1 :                 bCompatibleOfMultiThread = false;
    3912           1 :                 break;
    3913             :             }
    3914             : 
    3915          72 :             CPLQuadTreeInsertWithBounds(
    3916             :                 hQuadTree,
    3917             :                 const_cast<void *>(static_cast<const void *>(&oSourceDesc)),
    3918             :                 &sSourceBounds);
    3919             :         }
    3920             : 
    3921           5 :         CPLQuadTreeDestroy(hQuadTree);
    3922             : 
    3923           5 :         if (bCompatibleOfMultiThread)
    3924             :         {
    3925           4 :             m_bLastMustUseMultiThreading = true;
    3926           4 :             return true;
    3927             :         }
    3928             :     }
    3929             : 
    3930         132 :     if (m_aoSourceDesc.size() > 1)
    3931             :     {
    3932          66 :         SortSourceDesc();
    3933             :     }
    3934             : 
    3935             :     // Try to find the last (most priority) fully opaque source covering
    3936             :     // the whole AOI. We only need to start rendering from it.
    3937         132 :     size_t i = m_aoSourceDesc.size();
    3938         267 :     while (i > 0)
    3939             :     {
    3940         224 :         --i;
    3941         224 :         auto &poFeature = m_aoSourceDesc[i].poFeature;
    3942             :         const char *pszTileName =
    3943         224 :             poFeature->GetFieldAsString(m_nLocationFieldIndex);
    3944             :         const std::string osTileName(GetAbsoluteFileName(
    3945         224 :             pszTileName, GetDescription(), m_bSTACCollection));
    3946             : 
    3947         224 :         SourceDesc oSourceDesc;
    3948         224 :         if (!GetSourceDesc(osTileName, oSourceDesc, nullptr))
    3949           2 :             return false;
    3950             : 
    3951             :         // Check consistency of bounding box in tile index vs actual
    3952             :         // extent of the tile.
    3953         222 :         GDALGeoTransform tileGT;
    3954         222 :         if (oSourceDesc.poDS->GetGeoTransform(tileGT) == CE_None &&
    3955         222 :             tileGT[GT_ROTATION_PARAM1] == 0 && tileGT[GT_ROTATION_PARAM2] == 0)
    3956             :         {
    3957         222 :             OGREnvelope sActualTileExtent;
    3958         222 :             sActualTileExtent.MinX = tileGT[GT_TOPLEFT_X];
    3959         222 :             sActualTileExtent.MaxX =
    3960         444 :                 sActualTileExtent.MinX +
    3961         222 :                 oSourceDesc.poDS->GetRasterXSize() * tileGT[GT_WE_RES];
    3962         222 :             sActualTileExtent.MaxY = tileGT[GT_TOPLEFT_Y];
    3963         222 :             sActualTileExtent.MinY =
    3964         444 :                 sActualTileExtent.MaxY +
    3965         222 :                 oSourceDesc.poDS->GetRasterYSize() * tileGT[GT_NS_RES];
    3966         222 :             const auto poGeom = poFeature->GetGeometryRef();
    3967         222 :             if (poGeom && !poGeom->IsEmpty())
    3968             :             {
    3969         222 :                 OGREnvelope sGeomTileExtent;
    3970         222 :                 poGeom->getEnvelope(&sGeomTileExtent);
    3971         222 :                 sGeomTileExtent.MinX -= m_gt[GT_WE_RES];
    3972         222 :                 sGeomTileExtent.MaxX += m_gt[GT_WE_RES];
    3973         222 :                 sGeomTileExtent.MinY -= std::fabs(m_gt[GT_NS_RES]);
    3974         222 :                 sGeomTileExtent.MaxY += std::fabs(m_gt[GT_NS_RES]);
    3975         222 :                 if (!sGeomTileExtent.Contains(sActualTileExtent))
    3976             :                 {
    3977           2 :                     if (!sGeomTileExtent.Intersects(sActualTileExtent))
    3978             :                     {
    3979           1 :                         CPLError(CE_Warning, CPLE_AppDefined,
    3980             :                                  "Tile index is out of sync with actual "
    3981             :                                  "extent of %s. Bounding box from tile index "
    3982             :                                  "is (%g, %g, %g, %g) does not intersect at "
    3983             :                                  "all bounding box from tile (%g, %g, %g, %g)",
    3984             :                                  osTileName.c_str(), sGeomTileExtent.MinX,
    3985             :                                  sGeomTileExtent.MinY, sGeomTileExtent.MaxX,
    3986             :                                  sGeomTileExtent.MaxY, sActualTileExtent.MinX,
    3987             :                                  sActualTileExtent.MinY, sActualTileExtent.MaxX,
    3988             :                                  sActualTileExtent.MaxY);
    3989           1 :                         continue;
    3990             :                     }
    3991           1 :                     CPLError(CE_Warning, CPLE_AppDefined,
    3992             :                              "Tile index is out of sync with actual extent "
    3993             :                              "of %s. Bounding box from tile index is (%g, %g, "
    3994             :                              "%g, %g) does not fully contain bounding box from "
    3995             :                              "tile (%g, %g, %g, %g)",
    3996             :                              osTileName.c_str(), sGeomTileExtent.MinX,
    3997             :                              sGeomTileExtent.MinY, sGeomTileExtent.MaxX,
    3998             :                              sGeomTileExtent.MaxY, sActualTileExtent.MinX,
    3999             :                              sActualTileExtent.MinY, sActualTileExtent.MaxX,
    4000             :                              sActualTileExtent.MaxY);
    4001             :                 }
    4002             :             }
    4003             :         }
    4004             : 
    4005         221 :         const auto &poSource = oSourceDesc.poSource;
    4006         221 :         if (dfXOff >= poSource->m_dfDstXOff + poSource->m_dfDstXSize ||
    4007         221 :             dfYOff >= poSource->m_dfDstYOff + poSource->m_dfDstYSize ||
    4008         660 :             poSource->m_dfDstXOff >= dfXOff + dfXSize ||
    4009         218 :             poSource->m_dfDstYOff >= dfYOff + dfYSize)
    4010             :         {
    4011             :             // Can happen as some spatial filters select slightly more features
    4012             :             // than strictly needed.
    4013           3 :             continue;
    4014             :         }
    4015             : 
    4016             :         const bool bCoversWholeAOI =
    4017         218 :             (poSource->m_dfDstXOff <= dfXOff &&
    4018         141 :              poSource->m_dfDstYOff <= dfYOff &&
    4019         140 :              poSource->m_dfDstXOff + poSource->m_dfDstXSize >=
    4020         486 :                  dfXOff + dfXSize &&
    4021         127 :              poSource->m_dfDstYOff + poSource->m_dfDstYSize >=
    4022         127 :                  dfYOff + dfYSize);
    4023         218 :         oSourceDesc.bCoversWholeAOI = bCoversWholeAOI;
    4024             : 
    4025         218 :         m_aoSourceDesc[i] = std::move(oSourceDesc);
    4026             : 
    4027         218 :         if (m_aoSourceDesc[i].bCoversWholeAOI &&
    4028         218 :             !m_aoSourceDesc[i].bHasNoData && !m_aoSourceDesc[i].poMaskBand)
    4029             :         {
    4030          87 :             break;
    4031             :         }
    4032             :     }
    4033             : 
    4034         130 :     if (i > 0)
    4035             :     {
    4036             :         // Remove sources that will not be rendered
    4037          32 :         m_aoSourceDesc.erase(m_aoSourceDesc.begin(),
    4038          64 :                              m_aoSourceDesc.begin() + i);
    4039             :     }
    4040             : 
    4041             :     // Remove elements that have no dataset
    4042           0 :     m_aoSourceDesc.erase(std::remove_if(m_aoSourceDesc.begin(),
    4043             :                                         m_aoSourceDesc.end(),
    4044         222 :                                         [](const SourceDesc &desc)
    4045         352 :                                         { return desc.poDS == nullptr; }),
    4046         260 :                          m_aoSourceDesc.end());
    4047             : 
    4048         130 :     return true;
    4049             : }
    4050             : 
    4051             : /************************************************************************/
    4052             : /*                          SortSourceDesc()                            */
    4053             : /************************************************************************/
    4054             : 
    4055          66 : void GDALTileIndexDataset::SortSourceDesc()
    4056             : {
    4057          66 :     const auto eFieldType = m_nSortFieldIndex >= 0
    4058          66 :                                 ? m_poLayer->GetLayerDefn()
    4059          47 :                                       ->GetFieldDefn(m_nSortFieldIndex)
    4060          47 :                                       ->GetType()
    4061          66 :                                 : OFTMaxType;
    4062          66 :     std::sort(
    4063             :         m_aoSourceDesc.begin(), m_aoSourceDesc.end(),
    4064        1828 :         [this, eFieldType](const SourceDesc &a, const SourceDesc &b)
    4065             :         {
    4066         419 :             const auto &poFeatureA = (m_bSortFieldAsc ? a : b).poFeature;
    4067         419 :             const auto &poFeatureB = (m_bSortFieldAsc ? b : a).poFeature;
    4068         918 :             if (m_nSortFieldIndex >= 0 &&
    4069         499 :                 poFeatureA->IsFieldSetAndNotNull(m_nSortFieldIndex) &&
    4070          80 :                 poFeatureB->IsFieldSetAndNotNull(m_nSortFieldIndex))
    4071             :             {
    4072          80 :                 if (eFieldType == OFTString)
    4073             :                 {
    4074             :                     const int nCmp =
    4075           5 :                         strcmp(poFeatureA->GetFieldAsString(m_nSortFieldIndex),
    4076             :                                poFeatureB->GetFieldAsString(m_nSortFieldIndex));
    4077           5 :                     if (nCmp < 0)
    4078           1 :                         return true;
    4079           4 :                     if (nCmp > 0)
    4080           2 :                         return false;
    4081             :                 }
    4082          75 :                 else if (eFieldType == OFTInteger || eFieldType == OFTInteger64)
    4083             :                 {
    4084             :                     const auto nA =
    4085          45 :                         poFeatureA->GetFieldAsInteger64(m_nSortFieldIndex);
    4086             :                     const auto nB =
    4087          45 :                         poFeatureB->GetFieldAsInteger64(m_nSortFieldIndex);
    4088          45 :                     if (nA < nB)
    4089           3 :                         return true;
    4090          42 :                     if (nA > nB)
    4091          42 :                         return false;
    4092             :                 }
    4093          30 :                 else if (eFieldType == OFTReal)
    4094             :                 {
    4095             :                     const auto dfA =
    4096           3 :                         poFeatureA->GetFieldAsDouble(m_nSortFieldIndex);
    4097             :                     const auto dfB =
    4098           3 :                         poFeatureB->GetFieldAsDouble(m_nSortFieldIndex);
    4099           3 :                     if (dfA < dfB)
    4100           1 :                         return true;
    4101           2 :                     if (dfA > dfB)
    4102           2 :                         return false;
    4103             :                 }
    4104          27 :                 else if (eFieldType == OFTDate || eFieldType == OFTDateTime)
    4105             :                 {
    4106             :                     const auto poFieldA =
    4107          27 :                         poFeatureA->GetRawFieldRef(m_nSortFieldIndex);
    4108             :                     const auto poFieldB =
    4109          27 :                         poFeatureB->GetRawFieldRef(m_nSortFieldIndex);
    4110             : 
    4111             : #define COMPARE_DATE_COMPONENT(comp)                                           \
    4112             :     do                                                                         \
    4113             :     {                                                                          \
    4114             :         if (poFieldA->Date.comp < poFieldB->Date.comp)                         \
    4115             :             return true;                                                       \
    4116             :         if (poFieldA->Date.comp > poFieldB->Date.comp)                         \
    4117             :             return false;                                                      \
    4118             :     } while (0)
    4119             : 
    4120          27 :                     COMPARE_DATE_COMPONENT(Year);
    4121          21 :                     COMPARE_DATE_COMPONENT(Month);
    4122          15 :                     COMPARE_DATE_COMPONENT(Day);
    4123           9 :                     COMPARE_DATE_COMPONENT(Hour);
    4124           8 :                     COMPARE_DATE_COMPONENT(Minute);
    4125           7 :                     COMPARE_DATE_COMPONENT(Second);
    4126             :                 }
    4127             :                 else
    4128             :                 {
    4129           0 :                     CPLAssert(false);
    4130             :                 }
    4131             :             }
    4132         347 :             return poFeatureA->GetFID() < poFeatureB->GetFID();
    4133             :         });
    4134          66 : }
    4135             : 
    4136             : /************************************************************************/
    4137             : /*                   CompositeSrcWithMaskIntoDest()                     */
    4138             : /************************************************************************/
    4139             : 
    4140             : static void
    4141          66 : CompositeSrcWithMaskIntoDest(const int nOutXSize, const int nOutYSize,
    4142             :                              const GDALDataType eBufType,
    4143             :                              const int nBufTypeSize, const GSpacing nPixelSpace,
    4144             :                              const GSpacing nLineSpace, const GByte *pabySrc,
    4145             :                              const GByte *const pabyMask, GByte *const pabyDest)
    4146             : {
    4147          66 :     size_t iMaskIdx = 0;
    4148          66 :     if (eBufType == GDT_UInt8)
    4149             :     {
    4150             :         // Optimization for byte case
    4151         136 :         for (int iY = 0; iY < nOutYSize; iY++)
    4152             :         {
    4153          86 :             GByte *pabyDestLine =
    4154          86 :                 pabyDest + static_cast<GPtrDiff_t>(iY * nLineSpace);
    4155          86 :             int iX = 0;
    4156             : #ifdef USE_SSE2_OPTIM
    4157          86 :             if (nPixelSpace == 1)
    4158             :             {
    4159             :                 // SSE2 version up to 6 times faster than portable version
    4160          86 :                 const auto xmm_zero = _mm_setzero_si128();
    4161          86 :                 constexpr int SIZEOF_REG = static_cast<int>(sizeof(xmm_zero));
    4162         110 :                 for (; iX + SIZEOF_REG <= nOutXSize; iX += SIZEOF_REG)
    4163             :                 {
    4164          48 :                     auto xmm_mask = _mm_loadu_si128(
    4165             :                         reinterpret_cast<__m128i const *>(pabyMask + iMaskIdx));
    4166          24 :                     const auto xmm_src = _mm_loadu_si128(
    4167             :                         reinterpret_cast<__m128i const *>(pabySrc));
    4168          24 :                     auto xmm_dst = _mm_loadu_si128(
    4169             :                         reinterpret_cast<__m128i const *>(pabyDestLine));
    4170             : #ifdef USE_SSE41_OPTIM
    4171             :                     xmm_dst = _mm_blendv_epi8(xmm_dst, xmm_src, xmm_mask);
    4172             : #else
    4173             :                     // mask[i] = 0 becomes 255, and mask[i] != 0 becomes 0
    4174          24 :                     xmm_mask = _mm_cmpeq_epi8(xmm_mask, xmm_zero);
    4175             :                     // dst_data[i] = (mask[i] & dst_data[i]) |
    4176             :                     //               (~mask[i] & src_data[i])
    4177             :                     // That is:
    4178             :                     // dst_data[i] = dst_data[i] when mask[i] = 255
    4179             :                     // dst_data[i] = src_data[i] when mask[i] = 0
    4180          72 :                     xmm_dst = _mm_or_si128(_mm_and_si128(xmm_mask, xmm_dst),
    4181             :                                            _mm_andnot_si128(xmm_mask, xmm_src));
    4182             : #endif
    4183             :                     _mm_storeu_si128(reinterpret_cast<__m128i *>(pabyDestLine),
    4184             :                                      xmm_dst);
    4185          24 :                     pabyDestLine += SIZEOF_REG;
    4186          24 :                     pabySrc += SIZEOF_REG;
    4187          24 :                     iMaskIdx += SIZEOF_REG;
    4188             :                 }
    4189             :             }
    4190             : #endif
    4191         342 :             for (; iX < nOutXSize; iX++)
    4192             :             {
    4193         256 :                 if (pabyMask[iMaskIdx])
    4194             :                 {
    4195         218 :                     *pabyDestLine = *pabySrc;
    4196             :                 }
    4197         256 :                 pabyDestLine += static_cast<GPtrDiff_t>(nPixelSpace);
    4198         256 :                 pabySrc++;
    4199         256 :                 iMaskIdx++;
    4200             :             }
    4201             :         }
    4202             :     }
    4203             :     else
    4204             :     {
    4205          38 :         for (int iY = 0; iY < nOutYSize; iY++)
    4206             :         {
    4207          22 :             GByte *pabyDestLine =
    4208          22 :                 pabyDest + static_cast<GPtrDiff_t>(iY * nLineSpace);
    4209          54 :             for (int iX = 0; iX < nOutXSize; iX++)
    4210             :             {
    4211          32 :                 if (pabyMask[iMaskIdx])
    4212             :                 {
    4213          16 :                     memcpy(pabyDestLine, pabySrc, nBufTypeSize);
    4214             :                 }
    4215          32 :                 pabyDestLine += static_cast<GPtrDiff_t>(nPixelSpace);
    4216          32 :                 pabySrc += nBufTypeSize;
    4217          32 :                 iMaskIdx++;
    4218             :             }
    4219             :         }
    4220             :     }
    4221          66 : }
    4222             : 
    4223             : /************************************************************************/
    4224             : /*                         NeedInitBuffer()                             */
    4225             : /************************************************************************/
    4226             : 
    4227             : // Must be called after CollectSources()
    4228         178 : bool GDALTileIndexDataset::NeedInitBuffer(int nBandCount,
    4229             :                                           const int *panBandMap) const
    4230             : {
    4231         178 :     bool bNeedInitBuffer = true;
    4232             :     // If the last source (that is the most priority one) covers at least
    4233             :     // the window of interest and is fully opaque, then we don't need to
    4234             :     // initialize the buffer, and can directly render that source.
    4235         178 :     int bHasNoData = false;
    4236         353 :     if (!m_aoSourceDesc.empty() && m_aoSourceDesc.back().bCoversWholeAOI &&
    4237         163 :         (!m_aoSourceDesc.back().bHasNoData ||
    4238             :          // Also, if there's a single source and that the VRT bands and the
    4239             :          // source bands have the same nodata value, we can skip initialization.
    4240          12 :          (m_aoSourceDesc.size() == 1 && m_aoSourceDesc.back().bSameNoData &&
    4241          10 :           m_bSameNoData && m_bSameDataType &&
    4242           5 :           IsSameNaNAware(papoBands[0]->GetNoDataValue(&bHasNoData),
    4243           5 :                          m_aoSourceDesc.back().dfSameNoData) &&
    4244         358 :           bHasNoData)) &&
    4245         190 :         (!m_aoSourceDesc.back().poMaskBand ||
    4246             :          // Also, if there's a single source that has a mask band, and the VRT
    4247             :          // bands have no-nodata or a 0-nodata value, we can skip
    4248             :          // initialization.
    4249          43 :          (m_aoSourceDesc.size() == 1 && m_bSameDataType &&
    4250           7 :           !(nBandCount == 1 && panBandMap[0] == 0) && m_bSameNoData &&
    4251           7 :           papoBands[0]->GetNoDataValue(&bHasNoData) == 0)))
    4252             :     {
    4253         125 :         bNeedInitBuffer = false;
    4254             :     }
    4255         178 :     return bNeedInitBuffer;
    4256             : }
    4257             : 
    4258             : /************************************************************************/
    4259             : /*                            InitBuffer()                              */
    4260             : /************************************************************************/
    4261             : 
    4262          58 : void GDALTileIndexDataset::InitBuffer(void *pData, int nBufXSize, int nBufYSize,
    4263             :                                       GDALDataType eBufType, int nBandCount,
    4264             :                                       const int *panBandMap,
    4265             :                                       GSpacing nPixelSpace, GSpacing nLineSpace,
    4266             :                                       GSpacing nBandSpace) const
    4267             : {
    4268          58 :     const int nBufTypeSize = GDALGetDataTypeSizeBytes(eBufType);
    4269          58 :     if (m_bSameNoData && nBandCount > 1 &&
    4270          18 :         ((nPixelSpace == nBufTypeSize &&
    4271          18 :           nLineSpace == nBufXSize * nPixelSpace &&
    4272          18 :           nBandSpace == nBufYSize * nLineSpace) ||
    4273           0 :          (nBandSpace == nBufTypeSize &&
    4274           0 :           nPixelSpace == nBandCount * nBandSpace &&
    4275           0 :           nLineSpace == nBufXSize * nPixelSpace)))
    4276             :     {
    4277          18 :         const int nBandNr = panBandMap[0];
    4278             :         auto poVRTBand =
    4279             :             nBandNr == 0
    4280          18 :                 ? m_poMaskBand.get()
    4281          18 :                 : cpl::down_cast<GDALTileIndexBand *>(papoBands[nBandNr - 1]);
    4282          18 :         CPLAssert(poVRTBand);
    4283          18 :         const double dfNoData = poVRTBand->m_dfNoDataValue;
    4284          18 :         if (dfNoData == 0.0)
    4285             :         {
    4286          16 :             memset(pData, 0,
    4287          16 :                    static_cast<size_t>(nBufXSize) * nBufYSize * nBandCount *
    4288          16 :                        nBufTypeSize);
    4289             :         }
    4290             :         else
    4291             :         {
    4292           2 :             GDALCopyWords64(
    4293             :                 &dfNoData, GDT_Float64, 0, pData, eBufType, nBufTypeSize,
    4294           2 :                 static_cast<size_t>(nBufXSize) * nBufYSize * nBandCount);
    4295          18 :         }
    4296             :     }
    4297             :     else
    4298             :     {
    4299          81 :         for (int i = 0; i < nBandCount; ++i)
    4300             :         {
    4301          41 :             const int nBandNr = panBandMap[i];
    4302          41 :             auto poVRTBand = nBandNr == 0 ? m_poMaskBand.get()
    4303          39 :                                           : cpl::down_cast<GDALTileIndexBand *>(
    4304          39 :                                                 papoBands[nBandNr - 1]);
    4305          41 :             GByte *pabyBandData = static_cast<GByte *>(pData) + i * nBandSpace;
    4306          41 :             if (nPixelSpace == nBufTypeSize &&
    4307          41 :                 poVRTBand->m_dfNoDataValue == 0.0)
    4308             :             {
    4309          37 :                 if (nLineSpace == nBufXSize * nPixelSpace)
    4310             :                 {
    4311          37 :                     memset(pabyBandData, 0,
    4312          37 :                            static_cast<size_t>(nBufYSize * nLineSpace));
    4313             :                 }
    4314             :                 else
    4315             :                 {
    4316           0 :                     for (int iLine = 0; iLine < nBufYSize; iLine++)
    4317             :                     {
    4318           0 :                         memset(static_cast<GByte *>(pabyBandData) +
    4319           0 :                                    static_cast<GIntBig>(iLine) * nLineSpace,
    4320           0 :                                0, static_cast<size_t>(nBufXSize * nPixelSpace));
    4321             :                     }
    4322          37 :                 }
    4323             :             }
    4324             :             else
    4325             :             {
    4326           4 :                 double dfWriteValue = poVRTBand->m_dfNoDataValue;
    4327             : 
    4328          12 :                 for (int iLine = 0; iLine < nBufYSize; iLine++)
    4329             :                 {
    4330           8 :                     GDALCopyWords(&dfWriteValue, GDT_Float64, 0,
    4331           8 :                                   static_cast<GByte *>(pabyBandData) +
    4332           8 :                                       static_cast<GIntBig>(nLineSpace) * iLine,
    4333             :                                   eBufType, static_cast<int>(nPixelSpace),
    4334             :                                   nBufXSize);
    4335             :                 }
    4336             :             }
    4337             :         }
    4338             :     }
    4339          58 : }
    4340             : 
    4341             : /************************************************************************/
    4342             : /*                            RenderSource()                            */
    4343             : /************************************************************************/
    4344             : 
    4345         481 : CPLErr GDALTileIndexDataset::RenderSource(
    4346             :     const SourceDesc &oSourceDesc, bool bNeedInitBuffer, int nBandNrMax,
    4347             :     int nXOff, int nYOff, int nXSize, int nYSize, double dfXOff, double dfYOff,
    4348             :     double dfXSize, double dfYSize, int nBufXSize, int nBufYSize, void *pData,
    4349             :     GDALDataType eBufType, int nBandCount, BANDMAP_TYPE panBandMap,
    4350             :     GSpacing nPixelSpace, GSpacing nLineSpace, GSpacing nBandSpace,
    4351             :     GDALRasterIOExtraArg *psExtraArg,
    4352             :     VRTSource::WorkingState &oWorkingState) const
    4353             : {
    4354         481 :     auto &poTileDS = oSourceDesc.poDS;
    4355         481 :     auto &poSource = oSourceDesc.poSource;
    4356         481 :     auto poComplexSource = dynamic_cast<VRTComplexSource *>(poSource.get());
    4357         481 :     CPLErr eErr = CE_None;
    4358             : 
    4359         481 :     if (poTileDS->GetRasterCount() + 1 == nBandNrMax &&
    4360         485 :         papoBands[nBandNrMax - 1]->GetColorInterpretation() == GCI_AlphaBand &&
    4361           4 :         papoBands[nBandNrMax - 1]->GetRasterDataType() == GDT_UInt8)
    4362             :     {
    4363             :         GDALRasterIOExtraArg sExtraArg;
    4364           4 :         INIT_RASTERIO_EXTRA_ARG(sExtraArg);
    4365           4 :         if (psExtraArg->eResampleAlg != GRIORA_NearestNeighbour)
    4366             :         {
    4367             :             // cppcheck-suppress redundantAssignment
    4368           0 :             sExtraArg.eResampleAlg = psExtraArg->eResampleAlg;
    4369             :         }
    4370             :         else
    4371             :         {
    4372             :             // cppcheck-suppress redundantAssignment
    4373           4 :             sExtraArg.eResampleAlg = m_eResampling;
    4374             :         }
    4375             : 
    4376             :         // Special case when there's typically a mix of RGB and RGBA source
    4377             :         // datasets and we read a RGB one.
    4378          14 :         for (int iBand = 0; iBand < nBandCount && eErr == CE_None; ++iBand)
    4379             :         {
    4380          10 :             const int nBandNr = panBandMap[iBand];
    4381          10 :             if (nBandNr == nBandNrMax)
    4382             :             {
    4383             :                 // The window we will actually request from the source raster band.
    4384           4 :                 double dfReqXOff = 0.0;
    4385           4 :                 double dfReqYOff = 0.0;
    4386           4 :                 double dfReqXSize = 0.0;
    4387           4 :                 double dfReqYSize = 0.0;
    4388           4 :                 int nReqXOff = 0;
    4389           4 :                 int nReqYOff = 0;
    4390           4 :                 int nReqXSize = 0;
    4391           4 :                 int nReqYSize = 0;
    4392             : 
    4393             :                 // The window we will actual set _within_ the pData buffer.
    4394           4 :                 int nOutXOff = 0;
    4395           4 :                 int nOutYOff = 0;
    4396           4 :                 int nOutXSize = 0;
    4397           4 :                 int nOutYSize = 0;
    4398             : 
    4399           4 :                 bool bError = false;
    4400             : 
    4401           4 :                 auto poTileBand = poTileDS->GetRasterBand(1);
    4402           4 :                 poSource->SetRasterBand(poTileBand, false);
    4403           4 :                 if (poSource->GetSrcDstWindow(
    4404             :                         dfXOff, dfYOff, dfXSize, dfYSize, nBufXSize, nBufYSize,
    4405             :                         sExtraArg.eResampleAlg, &dfReqXOff, &dfReqYOff,
    4406             :                         &dfReqXSize, &dfReqYSize, &nReqXOff, &nReqYOff,
    4407             :                         &nReqXSize, &nReqYSize, &nOutXOff, &nOutYOff,
    4408           4 :                         &nOutXSize, &nOutYSize, bError))
    4409             :                 {
    4410           4 :                     GByte *pabyOut =
    4411             :                         static_cast<GByte *>(pData) +
    4412           4 :                         static_cast<GPtrDiff_t>(iBand * nBandSpace +
    4413           4 :                                                 nOutXOff * nPixelSpace +
    4414           4 :                                                 nOutYOff * nLineSpace);
    4415             : 
    4416           4 :                     constexpr GByte n255 = 255;
    4417           8 :                     for (int iY = 0; iY < nOutYSize; iY++)
    4418             :                     {
    4419           4 :                         GDALCopyWords(
    4420             :                             &n255, GDT_UInt8, 0,
    4421           4 :                             pabyOut + static_cast<GPtrDiff_t>(iY * nLineSpace),
    4422             :                             eBufType, static_cast<int>(nPixelSpace), nOutXSize);
    4423             :                     }
    4424             :                 }
    4425             :             }
    4426             :             else
    4427             :             {
    4428           6 :                 auto poTileBand = poTileDS->GetRasterBand(nBandNr);
    4429           6 :                 if (poComplexSource)
    4430             :                 {
    4431           0 :                     int bHasNoData = false;
    4432             :                     const double dfNoDataValue =
    4433           0 :                         poTileBand->GetNoDataValue(&bHasNoData);
    4434           0 :                     poComplexSource->SetNoDataValue(
    4435           0 :                         bHasNoData ? dfNoDataValue : VRT_NODATA_UNSET);
    4436             :                 }
    4437           6 :                 poSource->SetRasterBand(poTileBand, false);
    4438             : 
    4439           6 :                 GByte *pabyBandData =
    4440           6 :                     static_cast<GByte *>(pData) + iBand * nBandSpace;
    4441          12 :                 eErr = poSource->RasterIO(
    4442             :                     poTileBand->GetRasterDataType(), nXOff, nYOff, nXSize,
    4443             :                     nYSize, pabyBandData, nBufXSize, nBufYSize, eBufType,
    4444           6 :                     nPixelSpace, nLineSpace, &sExtraArg, oWorkingState);
    4445             :             }
    4446             :         }
    4447           4 :         return eErr;
    4448             :     }
    4449         477 :     else if (poTileDS->GetRasterCount() < nBandNrMax)
    4450             :     {
    4451           2 :         CPLError(CE_Failure, CPLE_AppDefined, "%s has not enough bands.",
    4452             :                  oSourceDesc.osName.c_str());
    4453           2 :         return CE_Failure;
    4454             :     }
    4455             : 
    4456         475 :     if ((oSourceDesc.poMaskBand && bNeedInitBuffer) || nBandNrMax == 0)
    4457             :     {
    4458             :         // The window we will actually request from the source raster band.
    4459          55 :         double dfReqXOff = 0.0;
    4460          55 :         double dfReqYOff = 0.0;
    4461          55 :         double dfReqXSize = 0.0;
    4462          55 :         double dfReqYSize = 0.0;
    4463          55 :         int nReqXOff = 0;
    4464          55 :         int nReqYOff = 0;
    4465          55 :         int nReqXSize = 0;
    4466          55 :         int nReqYSize = 0;
    4467             : 
    4468             :         // The window we will actual set _within_ the pData buffer.
    4469          55 :         int nOutXOff = 0;
    4470          55 :         int nOutYOff = 0;
    4471          55 :         int nOutXSize = 0;
    4472          55 :         int nOutYSize = 0;
    4473             : 
    4474          55 :         bool bError = false;
    4475             : 
    4476          55 :         auto poFirstTileBand = poTileDS->GetRasterBand(1);
    4477          55 :         poSource->SetRasterBand(poFirstTileBand, false);
    4478             : 
    4479             :         GDALRasterIOExtraArg sExtraArg;
    4480          55 :         INIT_RASTERIO_EXTRA_ARG(sExtraArg);
    4481          55 :         CPL_IGNORE_RET_VAL(sExtraArg.bFloatingPointWindowValidity);
    4482          55 :         CPL_IGNORE_RET_VAL(sExtraArg.eResampleAlg);
    4483          55 :         if (psExtraArg->eResampleAlg != GRIORA_NearestNeighbour)
    4484             :         {
    4485           0 :             sExtraArg.eResampleAlg = psExtraArg->eResampleAlg;
    4486             :         }
    4487             :         else
    4488             :         {
    4489          55 :             sExtraArg.eResampleAlg = m_eResampling;
    4490             :         }
    4491             : 
    4492          55 :         if (poSource->GetSrcDstWindow(
    4493             :                 dfXOff, dfYOff, dfXSize, dfYSize, nBufXSize, nBufYSize,
    4494             :                 sExtraArg.eResampleAlg, &dfReqXOff, &dfReqYOff, &dfReqXSize,
    4495             :                 &dfReqYSize, &nReqXOff, &nReqYOff, &nReqXSize, &nReqYSize,
    4496          55 :                 &nOutXOff, &nOutYOff, &nOutXSize, &nOutYSize, bError))
    4497             :         {
    4498          55 :             int iMaskBandIdx = -1;
    4499          55 :             if (eBufType == GDT_UInt8 && nBandNrMax == 0)
    4500             :             {
    4501             :                 // when called from m_poMaskBand
    4502           4 :                 iMaskBandIdx = 0;
    4503             :             }
    4504          51 :             else if (oSourceDesc.poMaskBand)
    4505             :             {
    4506             :                 // If we request a Byte buffer and the mask band is actually
    4507             :                 // one of the queried bands of this request, we can save
    4508             :                 // requesting it separately.
    4509          51 :                 const int nMaskBandNr = oSourceDesc.poMaskBand->GetBand();
    4510          39 :                 if (eBufType == GDT_UInt8 && nMaskBandNr >= 1 &&
    4511         129 :                     nMaskBandNr <= poTileDS->GetRasterCount() &&
    4512          39 :                     poTileDS->GetRasterBand(nMaskBandNr) ==
    4513          39 :                         oSourceDesc.poMaskBand)
    4514             :                 {
    4515          61 :                     for (int iBand = 0; iBand < nBandCount; ++iBand)
    4516             :                     {
    4517          44 :                         if (panBandMap[iBand] == nMaskBandNr)
    4518             :                         {
    4519          20 :                             iMaskBandIdx = iBand;
    4520          20 :                             break;
    4521             :                         }
    4522             :                     }
    4523             :                 }
    4524             :             }
    4525             : 
    4526          55 :             sExtraArg.bFloatingPointWindowValidity = TRUE;
    4527          55 :             sExtraArg.dfXOff = dfReqXOff;
    4528          55 :             sExtraArg.dfYOff = dfReqYOff;
    4529          55 :             sExtraArg.dfXSize = dfReqXSize;
    4530          55 :             sExtraArg.dfYSize = dfReqYSize;
    4531             : 
    4532          76 :             if (iMaskBandIdx < 0 && oSourceDesc.abyMask.empty() &&
    4533          21 :                 oSourceDesc.poMaskBand)
    4534             :             {
    4535             :                 // Fetch the mask band
    4536             :                 try
    4537             :                 {
    4538          21 :                     oSourceDesc.abyMask.resize(static_cast<size_t>(nOutXSize) *
    4539          21 :                                                nOutYSize);
    4540             :                 }
    4541           0 :                 catch (const std::bad_alloc &)
    4542             :                 {
    4543           0 :                     CPLError(CE_Failure, CPLE_OutOfMemory,
    4544             :                              "Cannot allocate working buffer for mask");
    4545           0 :                     return CE_Failure;
    4546             :                 }
    4547             : 
    4548          21 :                 if (oSourceDesc.poMaskBand->RasterIO(
    4549             :                         GF_Read, nReqXOff, nReqYOff, nReqXSize, nReqYSize,
    4550          21 :                         oSourceDesc.abyMask.data(), nOutXSize, nOutYSize,
    4551          21 :                         GDT_UInt8, 0, 0, &sExtraArg) != CE_None)
    4552             :                 {
    4553           0 :                     oSourceDesc.abyMask.clear();
    4554           0 :                     return CE_Failure;
    4555             :                 }
    4556             :             }
    4557             : 
    4558             :             // Allocate a temporary contiguous buffer to receive pixel data
    4559          55 :             const int nBufTypeSize = GDALGetDataTypeSizeBytes(eBufType);
    4560          55 :             const size_t nWorkBufferBandSize =
    4561          55 :                 static_cast<size_t>(nOutXSize) * nOutYSize * nBufTypeSize;
    4562          55 :             std::vector<GByte> abyWorkBuffer;
    4563             :             try
    4564             :             {
    4565          55 :                 abyWorkBuffer.resize(nBandCount * nWorkBufferBandSize);
    4566             :             }
    4567           0 :             catch (const std::bad_alloc &)
    4568             :             {
    4569           0 :                 CPLError(CE_Failure, CPLE_OutOfMemory,
    4570             :                          "Cannot allocate working buffer");
    4571           0 :                 return CE_Failure;
    4572             :             }
    4573             : 
    4574             :             const GByte *const pabyMask =
    4575             :                 iMaskBandIdx >= 0
    4576          24 :                     ? abyWorkBuffer.data() + iMaskBandIdx * nWorkBufferBandSize
    4577          79 :                     : oSourceDesc.abyMask.data();
    4578             : 
    4579          55 :             if (nBandNrMax == 0)
    4580             :             {
    4581             :                 // Special case when called from m_poMaskBand
    4582          12 :                 if (poTileDS->GetRasterBand(1)->GetMaskBand()->RasterIO(
    4583             :                         GF_Read, nReqXOff, nReqYOff, nReqXSize, nReqYSize,
    4584           6 :                         abyWorkBuffer.data(), nOutXSize, nOutYSize, eBufType, 0,
    4585           6 :                         0, &sExtraArg) != CE_None)
    4586             :                 {
    4587           0 :                     return CE_Failure;
    4588             :                 }
    4589             :             }
    4590          98 :             else if (poTileDS->RasterIO(GF_Read, nReqXOff, nReqYOff, nReqXSize,
    4591          49 :                                         nReqYSize, abyWorkBuffer.data(),
    4592             :                                         nOutXSize, nOutYSize, eBufType,
    4593             :                                         nBandCount, panBandMap, 0, 0, 0,
    4594          49 :                                         &sExtraArg) != CE_None)
    4595             :             {
    4596           0 :                 return CE_Failure;
    4597             :             }
    4598             : 
    4599             :             // Compose the temporary contiguous buffer into the target
    4600             :             // buffer, taking into account the mask
    4601          55 :             GByte *pabyOut = static_cast<GByte *>(pData) +
    4602          55 :                              static_cast<GPtrDiff_t>(nOutXOff * nPixelSpace +
    4603          55 :                                                      nOutYOff * nLineSpace);
    4604             : 
    4605         121 :             for (int iBand = 0; iBand < nBandCount && eErr == CE_None; ++iBand)
    4606             :             {
    4607          66 :                 GByte *pabyDestBand =
    4608          66 :                     pabyOut + static_cast<GPtrDiff_t>(iBand * nBandSpace);
    4609             :                 const GByte *pabySrc =
    4610          66 :                     abyWorkBuffer.data() + iBand * nWorkBufferBandSize;
    4611             : 
    4612          66 :                 CompositeSrcWithMaskIntoDest(
    4613             :                     nOutXSize, nOutYSize, eBufType, nBufTypeSize, nPixelSpace,
    4614             :                     nLineSpace, pabySrc, pabyMask, pabyDestBand);
    4615             :             }
    4616          55 :         }
    4617             :     }
    4618         420 :     else if (m_bSameDataType && !bNeedInitBuffer && oSourceDesc.bHasNoData)
    4619             :     {
    4620             :         // We create a non-VRTComplexSource SimpleSource copy of poSource
    4621             :         // to be able to call DatasetRasterIO()
    4622           4 :         VRTSimpleSource oSimpleSource(poSource.get(), 1.0, 1.0);
    4623             : 
    4624             :         GDALRasterIOExtraArg sExtraArg;
    4625           4 :         INIT_RASTERIO_EXTRA_ARG(sExtraArg);
    4626           4 :         if (psExtraArg->eResampleAlg != GRIORA_NearestNeighbour)
    4627             :         {
    4628             :             // cppcheck-suppress redundantAssignment
    4629           0 :             sExtraArg.eResampleAlg = psExtraArg->eResampleAlg;
    4630             :         }
    4631             :         else
    4632             :         {
    4633             :             // cppcheck-suppress redundantAssignment
    4634           4 :             sExtraArg.eResampleAlg = m_eResampling;
    4635             :         }
    4636             : 
    4637           4 :         auto poTileBand = poTileDS->GetRasterBand(panBandMap[0]);
    4638           4 :         oSimpleSource.SetRasterBand(poTileBand, false);
    4639           4 :         eErr = oSimpleSource.DatasetRasterIO(
    4640           4 :             papoBands[0]->GetRasterDataType(), nXOff, nYOff, nXSize, nYSize,
    4641             :             pData, nBufXSize, nBufYSize, eBufType, nBandCount, panBandMap,
    4642           4 :             nPixelSpace, nLineSpace, nBandSpace, &sExtraArg);
    4643             :     }
    4644         416 :     else if (m_bSameDataType && !poComplexSource)
    4645             :     {
    4646         408 :         auto poTileBand = poTileDS->GetRasterBand(panBandMap[0]);
    4647         408 :         poSource->SetRasterBand(poTileBand, false);
    4648             : 
    4649             :         GDALRasterIOExtraArg sExtraArg;
    4650         408 :         INIT_RASTERIO_EXTRA_ARG(sExtraArg);
    4651         408 :         if (poTileBand->GetColorTable())
    4652             :         {
    4653             :             // cppcheck-suppress redundantAssignment
    4654           0 :             sExtraArg.eResampleAlg = GRIORA_NearestNeighbour;
    4655             :         }
    4656         408 :         else if (psExtraArg->eResampleAlg != GRIORA_NearestNeighbour)
    4657             :         {
    4658             :             // cppcheck-suppress redundantAssignment
    4659           0 :             sExtraArg.eResampleAlg = psExtraArg->eResampleAlg;
    4660             :         }
    4661             :         else
    4662             :         {
    4663             :             // cppcheck-suppress redundantAssignment
    4664         408 :             sExtraArg.eResampleAlg = m_eResampling;
    4665             :         }
    4666             : 
    4667         816 :         eErr = poSource->DatasetRasterIO(
    4668         408 :             papoBands[0]->GetRasterDataType(), nXOff, nYOff, nXSize, nYSize,
    4669             :             pData, nBufXSize, nBufYSize, eBufType, nBandCount, panBandMap,
    4670         408 :             nPixelSpace, nLineSpace, nBandSpace, &sExtraArg);
    4671             :     }
    4672             :     else
    4673             :     {
    4674          16 :         for (int i = 0; i < nBandCount && eErr == CE_None; ++i)
    4675             :         {
    4676           8 :             const int nBandNr = panBandMap[i];
    4677           8 :             GByte *pabyBandData = static_cast<GByte *>(pData) + i * nBandSpace;
    4678           8 :             auto poTileBand = poTileDS->GetRasterBand(nBandNr);
    4679           8 :             if (poComplexSource)
    4680             :             {
    4681           8 :                 int bHasNoData = false;
    4682             :                 const double dfNoDataValue =
    4683           8 :                     poTileBand->GetNoDataValue(&bHasNoData);
    4684           8 :                 poComplexSource->SetNoDataValue(bHasNoData ? dfNoDataValue
    4685           8 :                                                            : VRT_NODATA_UNSET);
    4686             :             }
    4687           8 :             poSource->SetRasterBand(poTileBand, false);
    4688             : 
    4689             :             GDALRasterIOExtraArg sExtraArg;
    4690           8 :             INIT_RASTERIO_EXTRA_ARG(sExtraArg);
    4691           8 :             if (poTileBand->GetColorTable())
    4692             :             {
    4693             :                 // cppcheck-suppress redundantAssignment
    4694           0 :                 sExtraArg.eResampleAlg = GRIORA_NearestNeighbour;
    4695             :             }
    4696           8 :             else if (psExtraArg->eResampleAlg != GRIORA_NearestNeighbour)
    4697             :             {
    4698             :                 // cppcheck-suppress redundantAssignment
    4699           0 :                 sExtraArg.eResampleAlg = psExtraArg->eResampleAlg;
    4700             :             }
    4701             :             else
    4702             :             {
    4703             :                 // cppcheck-suppress redundantAssignment
    4704           8 :                 sExtraArg.eResampleAlg = m_eResampling;
    4705             :             }
    4706             : 
    4707          16 :             eErr = poSource->RasterIO(
    4708           8 :                 papoBands[nBandNr - 1]->GetRasterDataType(), nXOff, nYOff,
    4709             :                 nXSize, nYSize, pabyBandData, nBufXSize, nBufYSize, eBufType,
    4710           8 :                 nPixelSpace, nLineSpace, &sExtraArg, oWorkingState);
    4711             :         }
    4712             :     }
    4713         475 :     return eErr;
    4714             : }
    4715             : 
    4716             : /************************************************************************/
    4717             : /*                             IRasterIO()                              */
    4718             : /************************************************************************/
    4719             : 
    4720         184 : CPLErr GDALTileIndexDataset::IRasterIO(
    4721             :     GDALRWFlag eRWFlag, int nXOff, int nYOff, int nXSize, int nYSize,
    4722             :     void *pData, int nBufXSize, int nBufYSize, GDALDataType eBufType,
    4723             :     int nBandCount, BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
    4724             :     GSpacing nLineSpace, GSpacing nBandSpace, GDALRasterIOExtraArg *psExtraArg)
    4725             : {
    4726         184 :     if (eRWFlag != GF_Read)
    4727           0 :         return CE_Failure;
    4728             : 
    4729         184 :     if (nBufXSize < nXSize && nBufYSize < nYSize && AreOverviewsEnabled())
    4730             :     {
    4731           2 :         int bTried = FALSE;
    4732           2 :         const CPLErr eErr = TryOverviewRasterIO(
    4733             :             eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
    4734             :             eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace,
    4735             :             nBandSpace, psExtraArg, &bTried);
    4736           2 :         if (bTried)
    4737           2 :             return eErr;
    4738             :     }
    4739             : 
    4740         182 :     double dfXOff = nXOff;
    4741         182 :     double dfYOff = nYOff;
    4742         182 :     double dfXSize = nXSize;
    4743         182 :     double dfYSize = nYSize;
    4744         182 :     if (psExtraArg->bFloatingPointWindowValidity)
    4745             :     {
    4746           6 :         dfXOff = psExtraArg->dfXOff;
    4747           6 :         dfYOff = psExtraArg->dfYOff;
    4748           6 :         dfXSize = psExtraArg->dfXSize;
    4749           6 :         dfYSize = psExtraArg->dfYSize;
    4750             :     }
    4751             : 
    4752         182 :     if (!CollectSources(dfXOff, dfYOff, dfXSize, dfYSize,
    4753             :                         /* bMultiThreadAllowed = */ true))
    4754             :     {
    4755           3 :         return CE_Failure;
    4756             :     }
    4757             : 
    4758             :     // We might be called with nBandCount == 1 && panBandMap[0] == 0
    4759             :     // to mean m_poMaskBand
    4760         179 :     int nBandNrMax = 0;
    4761         407 :     for (int i = 0; i < nBandCount; ++i)
    4762             :     {
    4763         228 :         const int nBandNr = panBandMap[i];
    4764         228 :         nBandNrMax = std::max(nBandNrMax, nBandNr);
    4765             :     }
    4766             : 
    4767             :     const bool bNeedInitBuffer =
    4768         179 :         m_bLastMustUseMultiThreading || NeedInitBuffer(nBandCount, panBandMap);
    4769             : 
    4770         179 :     if (!bNeedInitBuffer)
    4771             :     {
    4772         121 :         return RenderSource(
    4773         121 :             m_aoSourceDesc.back(), bNeedInitBuffer, nBandNrMax, nXOff, nYOff,
    4774             :             nXSize, nYSize, dfXOff, dfYOff, dfXSize, dfYSize, nBufXSize,
    4775             :             nBufYSize, pData, eBufType, nBandCount, panBandMap, nPixelSpace,
    4776         242 :             nLineSpace, nBandSpace, psExtraArg, m_oWorkingState);
    4777             :     }
    4778             :     else
    4779             :     {
    4780          58 :         InitBuffer(pData, nBufXSize, nBufYSize, eBufType, nBandCount,
    4781             :                    panBandMap, nPixelSpace, nLineSpace, nBandSpace);
    4782             : 
    4783          58 :         if (m_bLastMustUseMultiThreading)
    4784             :         {
    4785          12 :             CPLErrorAccumulator oErrorAccumulator;
    4786           6 :             std::atomic<bool> bSuccess = true;
    4787             :             const int nContributingSources =
    4788           6 :                 static_cast<int>(m_aoSourceDesc.size());
    4789           6 :             CPLWorkerThreadPool *psThreadPool = GDALGetGlobalThreadPool(
    4790           6 :                 std::min(nContributingSources, m_nNumThreads));
    4791             :             const int nThreads =
    4792           6 :                 std::min(nContributingSources, psThreadPool->GetThreadCount());
    4793           6 :             CPLDebugOnly("GTI",
    4794             :                          "IRasterIO(): use optimized "
    4795             :                          "multi-threaded code path. "
    4796             :                          "Using %d threads",
    4797             :                          nThreads);
    4798             : 
    4799             :             {
    4800          12 :                 std::lock_guard oLock(m_oQueueWorkingStates.oMutex);
    4801           6 :                 if (m_oQueueWorkingStates.oStates.size() <
    4802           6 :                     static_cast<size_t>(nThreads))
    4803             :                 {
    4804           4 :                     m_oQueueWorkingStates.oStates.resize(nThreads);
    4805             :                 }
    4806          22 :                 for (int i = 0; i < nThreads; ++i)
    4807             :                 {
    4808          16 :                     if (!m_oQueueWorkingStates.oStates[i])
    4809          10 :                         m_oQueueWorkingStates.oStates[i] =
    4810          20 :                             std::make_unique<VRTSource::WorkingState>();
    4811             :                 }
    4812             :             }
    4813             : 
    4814           6 :             auto oQueue = psThreadPool->CreateJobQueue();
    4815           6 :             std::atomic<int> nCompletedJobs = 0;
    4816         144 :             for (auto &oSourceDesc : m_aoSourceDesc)
    4817             :             {
    4818         138 :                 auto psJob = new RasterIOJob();
    4819         138 :                 psJob->bSTACCollection = m_bSTACCollection;
    4820         138 :                 psJob->poDS = this;
    4821         138 :                 psJob->pbSuccess = &bSuccess;
    4822         138 :                 psJob->poErrorAccumulator = &oErrorAccumulator;
    4823         138 :                 psJob->pnCompletedJobs = &nCompletedJobs;
    4824         138 :                 psJob->poQueueWorkingStates = &m_oQueueWorkingStates;
    4825         138 :                 psJob->nBandNrMax = nBandNrMax;
    4826         138 :                 psJob->nXOff = nXOff;
    4827         138 :                 psJob->nYOff = nYOff;
    4828         138 :                 psJob->nXSize = nXSize;
    4829         138 :                 psJob->nYSize = nYSize;
    4830         138 :                 psJob->pData = pData;
    4831         138 :                 psJob->nBufXSize = nBufXSize;
    4832         138 :                 psJob->nBufYSize = nBufYSize;
    4833         138 :                 psJob->eBufType = eBufType;
    4834         138 :                 psJob->nBandCount = nBandCount;
    4835         138 :                 psJob->panBandMap = panBandMap;
    4836         138 :                 psJob->nPixelSpace = nPixelSpace;
    4837         138 :                 psJob->nLineSpace = nLineSpace;
    4838         138 :                 psJob->nBandSpace = nBandSpace;
    4839         138 :                 psJob->psExtraArg = psExtraArg;
    4840             : 
    4841             :                 psJob->osTileName = oSourceDesc.poFeature->GetFieldAsString(
    4842         138 :                     m_nLocationFieldIndex);
    4843             : 
    4844         138 :                 if (!oQueue->SubmitJob(RasterIOJob::Func, psJob))
    4845             :                 {
    4846           0 :                     delete psJob;
    4847           0 :                     bSuccess = false;
    4848           0 :                     break;
    4849             :                 }
    4850             :             }
    4851             : 
    4852         100 :             while (oQueue->WaitEvent())
    4853             :             {
    4854             :                 // Quite rough progress callback. We could do better by counting
    4855             :                 // the number of contributing pixels.
    4856          94 :                 if (psExtraArg->pfnProgress)
    4857             :                 {
    4858         184 :                     psExtraArg->pfnProgress(double(nCompletedJobs.load()) /
    4859             :                                                 nContributingSources,
    4860             :                                             "", psExtraArg->pProgressData);
    4861             :                 }
    4862             :             }
    4863             : 
    4864           6 :             oErrorAccumulator.ReplayErrors();
    4865             : 
    4866           6 :             if (bSuccess && psExtraArg->pfnProgress)
    4867             :             {
    4868           4 :                 psExtraArg->pfnProgress(1.0, "", psExtraArg->pProgressData);
    4869             :             }
    4870             : 
    4871           6 :             return bSuccess ? CE_None : CE_Failure;
    4872             :         }
    4873             :         else
    4874             :         {
    4875             :             // Now render from bottom of the stack to top.
    4876         275 :             for (auto &oSourceDesc : m_aoSourceDesc)
    4877             :             {
    4878         446 :                 if (oSourceDesc.poDS &&
    4879         223 :                     RenderSource(oSourceDesc, bNeedInitBuffer, nBandNrMax,
    4880             :                                  nXOff, nYOff, nXSize, nYSize, dfXOff, dfYOff,
    4881             :                                  dfXSize, dfYSize, nBufXSize, nBufYSize, pData,
    4882             :                                  eBufType, nBandCount, panBandMap, nPixelSpace,
    4883             :                                  nLineSpace, nBandSpace, psExtraArg,
    4884         446 :                                  m_oWorkingState) != CE_None)
    4885           0 :                     return CE_Failure;
    4886             :             }
    4887             : 
    4888          52 :             if (psExtraArg->pfnProgress)
    4889             :             {
    4890           4 :                 psExtraArg->pfnProgress(1.0, "", psExtraArg->pProgressData);
    4891             :             }
    4892             : 
    4893          52 :             return CE_None;
    4894             :         }
    4895             :     }
    4896             : }
    4897             : 
    4898             : /************************************************************************/
    4899             : /*                 GDALTileIndexDataset::RasterIOJob::Func()            */
    4900             : /************************************************************************/
    4901             : 
    4902         138 : void GDALTileIndexDataset::RasterIOJob::Func(void *pData)
    4903             : {
    4904             :     auto psJob =
    4905         276 :         std::unique_ptr<RasterIOJob>(static_cast<RasterIOJob *>(pData));
    4906         138 :     if (*psJob->pbSuccess)
    4907             :     {
    4908             :         const std::string osTileName(GetAbsoluteFileName(
    4909         414 :             psJob->osTileName.c_str(), psJob->poDS->GetDescription(),
    4910         276 :             psJob->bSTACCollection));
    4911             : 
    4912         276 :         SourceDesc oSourceDesc;
    4913             : 
    4914         276 :         auto oAccumulator = psJob->poErrorAccumulator->InstallForCurrentScope();
    4915         138 :         CPL_IGNORE_RET_VAL(oAccumulator);
    4916             : 
    4917             :         const bool bCanOpenSource =
    4918         138 :             psJob->poDS->GetSourceDesc(osTileName, oSourceDesc,
    4919         275 :                                        &psJob->poQueueWorkingStates->oMutex) &&
    4920         137 :             oSourceDesc.poDS;
    4921             : 
    4922         138 :         if (!bCanOpenSource)
    4923             :         {
    4924           1 :             *psJob->pbSuccess = false;
    4925             :         }
    4926             :         else
    4927             :         {
    4928         137 :             GDALRasterIOExtraArg sArg = *(psJob->psExtraArg);
    4929         137 :             sArg.pfnProgress = nullptr;
    4930         137 :             sArg.pProgressData = nullptr;
    4931             : 
    4932         137 :             std::unique_ptr<VRTSource::WorkingState> poWorkingState;
    4933             :             {
    4934         274 :                 std::lock_guard oLock(psJob->poQueueWorkingStates->oMutex);
    4935             :                 poWorkingState =
    4936         137 :                     std::move(psJob->poQueueWorkingStates->oStates.back());
    4937         137 :                 psJob->poQueueWorkingStates->oStates.pop_back();
    4938         137 :                 CPLAssert(poWorkingState.get());
    4939             :             }
    4940             : 
    4941         137 :             double dfXOff = psJob->nXOff;
    4942         137 :             double dfYOff = psJob->nYOff;
    4943         137 :             double dfXSize = psJob->nXSize;
    4944         137 :             double dfYSize = psJob->nYSize;
    4945         137 :             if (psJob->psExtraArg->bFloatingPointWindowValidity)
    4946             :             {
    4947           0 :                 dfXOff = psJob->psExtraArg->dfXOff;
    4948           0 :                 dfYOff = psJob->psExtraArg->dfYOff;
    4949           0 :                 dfXSize = psJob->psExtraArg->dfXSize;
    4950           0 :                 dfYSize = psJob->psExtraArg->dfYSize;
    4951             :             }
    4952             : 
    4953             :             const bool bRenderOK =
    4954         274 :                 psJob->poDS->RenderSource(
    4955         137 :                     oSourceDesc, /*bNeedInitBuffer = */ true, psJob->nBandNrMax,
    4956         137 :                     psJob->nXOff, psJob->nYOff, psJob->nXSize, psJob->nYSize,
    4957         137 :                     dfXOff, dfYOff, dfXSize, dfYSize, psJob->nBufXSize,
    4958         137 :                     psJob->nBufYSize, psJob->pData, psJob->eBufType,
    4959         137 :                     psJob->nBandCount, psJob->panBandMap, psJob->nPixelSpace,
    4960         137 :                     psJob->nLineSpace, psJob->nBandSpace, &sArg,
    4961         137 :                     *(poWorkingState.get())) == CE_None;
    4962             : 
    4963         137 :             if (!bRenderOK)
    4964             :             {
    4965           1 :                 *psJob->pbSuccess = false;
    4966             :             }
    4967             : 
    4968             :             {
    4969         274 :                 std::lock_guard oLock(psJob->poQueueWorkingStates->oMutex);
    4970         274 :                 psJob->poQueueWorkingStates->oStates.push_back(
    4971         137 :                     std::move(poWorkingState));
    4972             :             }
    4973             :         }
    4974             :     }
    4975             : 
    4976         138 :     ++(*psJob->pnCompletedJobs);
    4977         138 : }
    4978             : 
    4979             : #ifdef GDAL_ENABLE_ALGORITHMS
    4980             : 
    4981             : /************************************************************************/
    4982             : /*                     GDALGTICreateAlgorithm                           */
    4983             : /************************************************************************/
    4984             : 
    4985             : class GDALGTICreateAlgorithm final : public GDALRasterIndexAlgorithm
    4986             : {
    4987             :   public:
    4988             :     static constexpr const char *NAME = "create";
    4989             :     static constexpr const char *DESCRIPTION =
    4990             :         "Create an index of raster datasets compatible of the GDAL Tile Index "
    4991             :         "(GTI) driver.";
    4992             :     static constexpr const char *HELP_URL =
    4993             :         "/programs/gdal_driver_gti_create.html";
    4994             : 
    4995             :     GDALGTICreateAlgorithm();
    4996             : 
    4997             :   protected:
    4998             :     bool AddExtraOptions(CPLStringList &aosOptions) override;
    4999             : 
    5000             :   private:
    5001             :     std::string m_xmlFilename{};
    5002             :     std::vector<double> m_resolution{};
    5003             :     std::vector<double> m_bbox{};
    5004             :     std::string m_dataType{};
    5005             :     int m_bandCount = 0;
    5006             :     std::vector<double> m_nodata{};
    5007             :     std::vector<std::string> m_colorInterpretation{};
    5008             :     bool m_mask = false;
    5009             :     std::vector<std::string> m_fetchedMetadata{};
    5010             : };
    5011             : 
    5012             : /************************************************************************/
    5013             : /*          GDALGTICreateAlgorithm::GDALGTICreateAlgorithm()            */
    5014             : /************************************************************************/
    5015             : 
    5016          31 : GDALGTICreateAlgorithm::GDALGTICreateAlgorithm()
    5017          31 :     : GDALRasterIndexAlgorithm(NAME, DESCRIPTION, HELP_URL)
    5018             : {
    5019          31 :     AddProgressArg();
    5020          31 :     AddInputDatasetArg(&m_inputDatasets, GDAL_OF_RASTER)
    5021          31 :         .SetAutoOpenDataset(false);
    5022          31 :     GDALVectorOutputAbstractAlgorithm::AddAllOutputArgs();
    5023             : 
    5024          31 :     AddCommonOptions();
    5025             : 
    5026             :     AddArg("xml-filename", 0,
    5027             :            _("Filename of the XML Virtual Tile Index file to generate, that "
    5028             :              "can be used as an input for the GDAL GTI / Virtual Raster Tile "
    5029             :              "Index driver"),
    5030          62 :            &m_xmlFilename)
    5031          31 :         .SetMinCharCount(1);
    5032             : 
    5033             :     AddArg("resolution", 0,
    5034             :            _("Resolution (in destination CRS units) of the virtual mosaic"),
    5035          62 :            &m_resolution)
    5036          31 :         .SetMinCount(2)
    5037          31 :         .SetMaxCount(2)
    5038          31 :         .SetMinValueExcluded(0)
    5039          31 :         .SetRepeatedArgAllowed(false)
    5040          31 :         .SetDisplayHintAboutRepetition(false)
    5041          31 :         .SetMetaVar("<xres>,<yres>");
    5042             : 
    5043             :     AddBBOXArg(
    5044             :         &m_bbox,
    5045          31 :         _("Bounding box (in destination CRS units) of the virtual mosaic"));
    5046          31 :     AddOutputDataTypeArg(&m_dataType, _("Datatype of the virtual mosaic"));
    5047             :     AddArg("band-count", 0, _("Number of bands of the virtual mosaic"),
    5048          62 :            &m_bandCount)
    5049          31 :         .SetMinValueIncluded(1);
    5050             :     AddArg("nodata", 0, _("Nodata value(s) of the bands of the virtual mosaic"),
    5051          31 :            &m_nodata);
    5052             :     AddArg("color-interpretation", 0,
    5053             :            _("Color interpretation(s) of the bands of the virtual mosaic"),
    5054          62 :            &m_colorInterpretation)
    5055          31 :         .SetChoices("red", "green", "blue", "alpha", "gray", "undefined");
    5056             :     AddArg("mask", 0, _("Defines that the virtual mosaic has a mask band"),
    5057          31 :            &m_mask);
    5058             :     AddArg("fetch-metadata", 0,
    5059             :            _("Fetch a metadata item from source rasters and write it as a "
    5060             :              "field in the index."),
    5061          62 :            &m_fetchedMetadata)
    5062          62 :         .SetMetaVar("<gdal-metadata-name>,<field-name>,<field-type>")
    5063          31 :         .SetPackedValuesAllowed(false)
    5064             :         .AddValidationAction(
    5065           6 :             [this]()
    5066             :             {
    5067           6 :                 for (const std::string &s : m_fetchedMetadata)
    5068             :                 {
    5069             :                     const CPLStringList aosTokens(
    5070           4 :                         CSLTokenizeString2(s.c_str(), ",", 0));
    5071           4 :                     if (aosTokens.size() != 3)
    5072             :                     {
    5073           1 :                         ReportError(
    5074             :                             CE_Failure, CPLE_IllegalArg,
    5075             :                             "'%s' is not of the form "
    5076             :                             "<gdal-metadata-name>,<field-name>,<field-type>",
    5077             :                             s.c_str());
    5078           1 :                         return false;
    5079             :                     }
    5080           3 :                     bool ok = false;
    5081          18 :                     for (const char *type : {"String", "Integer", "Integer64",
    5082          21 :                                              "Real", "Date", "DateTime"})
    5083             :                     {
    5084          18 :                         if (EQUAL(aosTokens[2], type))
    5085           2 :                             ok = true;
    5086             :                     }
    5087           3 :                     if (!ok)
    5088             :                     {
    5089           1 :                         ReportError(CE_Failure, CPLE_IllegalArg,
    5090             :                                     "'%s' has an invalid field type '%s'. It "
    5091             :                                     "should be one of 'String', 'Integer', "
    5092             :                                     "'Integer64', 'Real', 'Date', 'DateTime'.",
    5093             :                                     s.c_str(), aosTokens[2]);
    5094           1 :                         return false;
    5095             :                     }
    5096             :                 }
    5097           2 :                 return true;
    5098          31 :             });
    5099          31 : }
    5100             : 
    5101             : /************************************************************************/
    5102             : /*            GDALGTICreateAlgorithm::AddExtraOptions()                 */
    5103             : /************************************************************************/
    5104             : 
    5105           4 : bool GDALGTICreateAlgorithm::AddExtraOptions(CPLStringList &aosOptions)
    5106             : {
    5107           4 :     if (!m_xmlFilename.empty())
    5108             :     {
    5109           1 :         aosOptions.push_back("-gti_filename");
    5110           1 :         aosOptions.push_back(m_xmlFilename);
    5111             :     }
    5112           4 :     if (!m_resolution.empty())
    5113             :     {
    5114           1 :         aosOptions.push_back("-tr");
    5115           1 :         aosOptions.push_back(CPLSPrintf("%.17g", m_resolution[0]));
    5116           1 :         aosOptions.push_back(CPLSPrintf("%.17g", m_resolution[1]));
    5117             :     }
    5118           4 :     if (!m_bbox.empty())
    5119             :     {
    5120           1 :         aosOptions.push_back("-te");
    5121           1 :         aosOptions.push_back(CPLSPrintf("%.17g", m_bbox[0]));
    5122           1 :         aosOptions.push_back(CPLSPrintf("%.17g", m_bbox[1]));
    5123           1 :         aosOptions.push_back(CPLSPrintf("%.17g", m_bbox[2]));
    5124           1 :         aosOptions.push_back(CPLSPrintf("%.17g", m_bbox[3]));
    5125             :     }
    5126           4 :     if (!m_dataType.empty())
    5127             :     {
    5128           1 :         aosOptions.push_back("-ot");
    5129           1 :         aosOptions.push_back(m_dataType);
    5130             :     }
    5131           4 :     if (m_bandCount > 0)
    5132             :     {
    5133           3 :         aosOptions.push_back("-bandcount");
    5134           3 :         aosOptions.push_back(CPLSPrintf("%d", m_bandCount));
    5135             : 
    5136           5 :         if (!m_nodata.empty() && m_nodata.size() != 1 &&
    5137           2 :             static_cast<int>(m_nodata.size()) != m_bandCount)
    5138             :         {
    5139           1 :             ReportError(CE_Failure, CPLE_IllegalArg,
    5140             :                         "%d nodata values whereas one or %d were expected",
    5141           1 :                         static_cast<int>(m_nodata.size()), m_bandCount);
    5142           1 :             return false;
    5143             :         }
    5144             : 
    5145           4 :         if (!m_colorInterpretation.empty() &&
    5146           4 :             m_colorInterpretation.size() != 1 &&
    5147           2 :             static_cast<int>(m_colorInterpretation.size()) != m_bandCount)
    5148             :         {
    5149           1 :             ReportError(
    5150             :                 CE_Failure, CPLE_IllegalArg,
    5151             :                 "%d color interpretations whereas one or %d were expected",
    5152           1 :                 static_cast<int>(m_colorInterpretation.size()), m_bandCount);
    5153           1 :             return false;
    5154             :         }
    5155             :     }
    5156           2 :     if (!m_nodata.empty())
    5157             :     {
    5158           2 :         std::string val;
    5159           3 :         for (double v : m_nodata)
    5160             :         {
    5161           2 :             if (!val.empty())
    5162           1 :                 val += ',';
    5163           2 :             val += CPLSPrintf("%.17g", v);
    5164             :         }
    5165           1 :         aosOptions.push_back("-nodata");
    5166           1 :         aosOptions.push_back(val);
    5167             :     }
    5168           2 :     if (!m_colorInterpretation.empty())
    5169             :     {
    5170           2 :         std::string val;
    5171           3 :         for (const std::string &s : m_colorInterpretation)
    5172             :         {
    5173           2 :             if (!val.empty())
    5174           1 :                 val += ',';
    5175           2 :             val += s;
    5176             :         }
    5177           1 :         aosOptions.push_back("-colorinterp");
    5178           1 :         aosOptions.push_back(val);
    5179             :     }
    5180           2 :     if (m_mask)
    5181           1 :         aosOptions.push_back("-mask");
    5182           3 :     for (const std::string &s : m_fetchedMetadata)
    5183             :     {
    5184           1 :         aosOptions.push_back("-fetch_md");
    5185           2 :         const CPLStringList aosTokens(CSLTokenizeString2(s.c_str(), ",", 0));
    5186           4 :         for (const char *token : aosTokens)
    5187             :         {
    5188           3 :             aosOptions.push_back(token);
    5189             :         }
    5190             :     }
    5191           2 :     return true;
    5192             : }
    5193             : 
    5194             : /************************************************************************/
    5195             : /*                 GDALTileIndexInstantiateAlgorithm()                  */
    5196             : /************************************************************************/
    5197             : 
    5198             : static GDALAlgorithm *
    5199          31 : GDALTileIndexInstantiateAlgorithm(const std::vector<std::string> &aosPath)
    5200             : {
    5201          31 :     if (aosPath.size() == 1 && aosPath[0] == "create")
    5202             :     {
    5203          31 :         return std::make_unique<GDALGTICreateAlgorithm>().release();
    5204             :     }
    5205             :     else
    5206             :     {
    5207           0 :         return nullptr;
    5208             :     }
    5209             : }
    5210             : 
    5211             : #endif
    5212             : 
    5213             : /************************************************************************/
    5214             : /*                         GDALRegister_GTI()                           */
    5215             : /************************************************************************/
    5216             : 
    5217        2058 : void GDALRegister_GTI()
    5218             : {
    5219        2058 :     if (GDALGetDriverByName("GTI") != nullptr)
    5220         283 :         return;
    5221             : 
    5222        3550 :     auto poDriver = std::make_unique<GDALDriver>();
    5223             : 
    5224        1775 :     poDriver->SetDescription("GTI");
    5225        1775 :     poDriver->SetMetadataItem(GDAL_DCAP_RASTER, "YES");
    5226        1775 :     poDriver->SetMetadataItem(GDAL_DMD_LONGNAME, "GDAL Raster Tile Index");
    5227        1775 :     poDriver->SetMetadataItem(GDAL_DMD_EXTENSIONS, "gti.gpkg gti.fgb gti");
    5228        1775 :     poDriver->SetMetadataItem(GDAL_DMD_CONNECTION_PREFIX, GTI_PREFIX);
    5229        1775 :     poDriver->SetMetadataItem(GDAL_DMD_HELPTOPIC, "drivers/raster/gti.html");
    5230             : 
    5231        1775 :     poDriver->pfnOpen = GDALTileIndexDatasetOpen;
    5232        1775 :     poDriver->pfnIdentify = GDALTileIndexDatasetIdentify;
    5233             : 
    5234        1775 :     poDriver->SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");
    5235             : 
    5236        1775 :     poDriver->SetMetadataItem(
    5237             :         GDAL_DMD_OPENOPTIONLIST,
    5238             :         "<OpenOptionList>"
    5239             :         "  <Option name='LAYER' type='string'/>"
    5240             :         "  <Option name='SQL' type='string'/>"
    5241             :         "  <Option name='SPATIAL_SQL' type='string'/>"
    5242             :         "  <Option name='LOCATION_FIELD' type='string'/>"
    5243             :         "  <Option name='SORT_FIELD' type='string'/>"
    5244             :         "  <Option name='SORT_FIELD_ASC' type='boolean'/>"
    5245             :         "  <Option name='FILTER' type='string'/>"
    5246             :         "  <Option name='SRS' type='string'/>"
    5247             :         "  <Option name='RESX' type='float'/>"
    5248             :         "  <Option name='RESY' type='float'/>"
    5249             :         "  <Option name='MINX' type='float'/>"
    5250             :         "  <Option name='MINY' type='float'/>"
    5251             :         "  <Option name='MAXX' type='float'/>"
    5252             :         "  <Option name='MAXY' type='float'/>"
    5253             :         "<Option name='NUM_THREADS' type='string' description="
    5254             :         "'Number of worker threads for reading. Can be set to ALL_CPUS' "
    5255             :         "default='ALL_CPUS'/>"
    5256        1775 :         "</OpenOptionList>");
    5257             : 
    5258             : #ifdef GDAL_ENABLE_ALGORITHMS
    5259        3550 :     poDriver->DeclareAlgorithm({"create"});
    5260        1775 :     poDriver->pfnInstantiateAlgorithm = GDALTileIndexInstantiateAlgorithm;
    5261             : #endif
    5262             : 
    5263             : #ifdef BUILT_AS_PLUGIN
    5264             :     // Used by gdaladdo and test_gdaladdo.py
    5265             :     poDriver->SetMetadataItem("IS_PLUGIN", "YES");
    5266             : #endif
    5267             : 
    5268        1775 :     GetGDALDriverManager()->RegisterDriver(poDriver.release());
    5269             : }

Generated by: LCOV version 1.14