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

Generated by: LCOV version 1.14