LCOV - code coverage report
Current view: top level - frmts/vrt - vrtdataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 1386 1528 90.7 %
Date: 2026-11-22 14:39:15 Functions: 61 64 95.3 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  Virtual GDAL Datasets
       4             :  * Purpose:  Implementation of VRTDataset
       5             :  * Author:   Frank Warmerdam <warmerdam@pobox.com>
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2001, Frank Warmerdam <warmerdam@pobox.com>
       9             :  * Copyright (c) 2007-2014, Even Rouault <even dot rouault at spatialys.com>
      10             :  *
      11             :  * SPDX-License-Identifier: MIT
      12             :  ****************************************************************************/
      13             : 
      14             : #include "vrtdataset.h"
      15             : 
      16             : #include "cpl_error_internal.h"
      17             : #include "cpl_minixml.h"
      18             : #include "cpl_string.h"
      19             : #include "cpl_worker_thread_pool.h"
      20             : #include "gdal_frmts.h"
      21             : #include "ogr_spatialref.h"
      22             : #include "gdal_thread_pool.h"
      23             : #include "gdal_utils.h"
      24             : 
      25             : #include <algorithm>
      26             : #include <cassert>
      27             : #include <cmath>
      28             : #include <set>
      29             : #include <typeinfo>
      30             : #include "gdal_proxy.h"
      31             : 
      32             : /*! @cond Doxygen_Suppress */
      33             : 
      34             : #define VRT_PROTOCOL_PREFIX "vrt://"
      35             : 
      36             : constexpr int DEFAULT_BLOCK_SIZE = 128;
      37             : 
      38             : /************************************************************************/
      39             : /*                             VRTDataset()                             */
      40             : /************************************************************************/
      41             : 
      42        6671 : VRTDataset::VRTDataset(int nXSize, int nYSize, int nBlockXSize, int nBlockYSize)
      43             : {
      44        6671 :     nRasterXSize = nXSize;
      45        6671 :     nRasterYSize = nYSize;
      46             : 
      47        6671 :     m_bBlockSizeSpecified = nBlockXSize > 0 && nBlockYSize > 0;
      48        6671 :     m_nBlockXSize =
      49        6671 :         nBlockXSize > 0 ? nBlockXSize : std::min(DEFAULT_BLOCK_SIZE, nXSize);
      50        6671 :     m_nBlockYSize =
      51        6671 :         nBlockYSize > 0 ? nBlockYSize : std::min(DEFAULT_BLOCK_SIZE, nYSize);
      52             : 
      53        6671 :     GDALRegister_VRT();
      54             : 
      55        6671 :     poDriver = static_cast<GDALDriver *>(GDALGetDriverByName("VRT"));
      56        6671 : }
      57             : 
      58             : /************************************************************************/
      59             : /*                         IsDefaultBlockSize()                         */
      60             : /************************************************************************/
      61             : 
      62        1360 : /* static */ bool VRTDataset::IsDefaultBlockSize(int nBlockSize, int nDimension)
      63             : {
      64        2281 :     return nBlockSize == DEFAULT_BLOCK_SIZE ||
      65        2281 :            (nBlockSize < DEFAULT_BLOCK_SIZE && nBlockSize == nDimension);
      66             : }
      67             : 
      68             : /*! @endcond */
      69             : 
      70             : /************************************************************************/
      71             : /*                             VRTCreate()                              */
      72             : /************************************************************************/
      73             : 
      74             : /**
      75             :  * @see VRTDataset::VRTDataset()
      76             :  */
      77             : 
      78        2376 : VRTDatasetH CPL_STDCALL VRTCreate(int nXSize, int nYSize)
      79             : 
      80             : {
      81        2376 :     auto poDS = new VRTDataset(nXSize, nYSize);
      82        2376 :     poDS->eAccess = GA_Update;
      83        2376 :     return poDS;
      84             : }
      85             : 
      86             : /*! @cond Doxygen_Suppress */
      87             : 
      88             : /************************************************************************/
      89             : /*                            ~VRTDataset()                             */
      90             : /************************************************************************/
      91             : 
      92       12298 : VRTDataset::~VRTDataset()
      93             : 
      94             : {
      95        6671 :     VRTDataset::FlushCache(true);
      96        6671 :     CPLFree(m_pszVRTPath);
      97             : 
      98        6734 :     for (size_t i = 0; i < m_apoOverviews.size(); i++)
      99          63 :         delete m_apoOverviews[i];
     100        6680 :     for (size_t i = 0; i < m_apoOverviewsBak.size(); i++)
     101           9 :         delete m_apoOverviewsBak[i];
     102        6671 :     CSLDestroy(m_papszXMLVRTMetadata);
     103       12298 : }
     104             : 
     105             : /************************************************************************/
     106             : /*                             FlushCache()                             */
     107             : /************************************************************************/
     108             : 
     109        7066 : CPLErr VRTDataset::FlushCache(bool bAtClosing)
     110             : 
     111             : {
     112        7066 :     if (m_poRootGroup)
     113             :     {
     114         389 :         m_poRootGroup->SetVRTPath(CPLGetPathSafe(GetDescription()));
     115         389 :         return m_poRootGroup->Serialize() ? CE_None : CE_Failure;
     116             :     }
     117             :     else
     118        6677 :         return VRTFlushCacheStruct<VRTDataset>::FlushCache(*this, bAtClosing);
     119             : }
     120             : 
     121             : /************************************************************************/
     122             : /*                             FlushCache()                             */
     123             : /************************************************************************/
     124             : 
     125         820 : CPLErr VRTWarpedDataset::FlushCache(bool bAtClosing)
     126             : 
     127             : {
     128         820 :     return VRTFlushCacheStruct<VRTWarpedDataset>::FlushCache(*this, bAtClosing);
     129             : }
     130             : 
     131             : /************************************************************************/
     132             : /*                             FlushCache()                             */
     133             : /************************************************************************/
     134             : 
     135         201 : CPLErr VRTPansharpenedDataset::FlushCache(bool bAtClosing)
     136             : 
     137             : {
     138         201 :     return VRTFlushCacheStruct<VRTPansharpenedDataset>::FlushCache(*this,
     139         201 :                                                                    bAtClosing);
     140             : }
     141             : 
     142             : /************************************************************************/
     143             : /*                             FlushCache()                             */
     144             : /************************************************************************/
     145             : 
     146         208 : CPLErr VRTProcessedDataset::FlushCache(bool bAtClosing)
     147             : 
     148             : {
     149         208 :     return VRTFlushCacheStruct<VRTProcessedDataset>::FlushCache(*this,
     150         208 :                                                                 bAtClosing);
     151             : }
     152             : 
     153             : /************************************************************************/
     154             : /*                             FlushCache()                             */
     155             : /************************************************************************/
     156             : 
     157             : template <class T>
     158        7906 : CPLErr VRTFlushCacheStruct<T>::FlushCache(T &obj, bool bAtClosing)
     159             : {
     160        7906 :     CPLErr eErr = obj.GDALDataset::FlushCache(bAtClosing);
     161             : 
     162        7906 :     if (!obj.m_bNeedsFlush || !obj.m_bWritable)
     163        3536 :         return eErr;
     164             : 
     165             :     // We don't write to disk if there is no filename.  This is a
     166             :     // memory only dataset.
     167        4735 :     if (strlen(obj.GetDescription()) == 0 ||
     168         365 :         STARTS_WITH_CI(obj.GetDescription(), "<VRTDataset"))
     169        4019 :         return eErr;
     170             : 
     171         351 :     obj.m_bNeedsFlush = false;
     172             : 
     173             :     // Serialize XML representation to disk
     174         351 :     const std::string osVRTPath(CPLGetPathSafe(obj.GetDescription()));
     175         351 :     CPLXMLNode *psDSTree = obj.T::SerializeToXML(osVRTPath.c_str());
     176         351 :     if (!CPLSerializeXMLTreeToFile(psDSTree, obj.GetDescription()))
     177          13 :         eErr = CE_Failure;
     178         351 :     CPLDestroyXMLNode(psDSTree);
     179         351 :     return eErr;
     180             : }
     181             : 
     182             : /************************************************************************/
     183             : /*                            GetMetadata()                             */
     184             : /************************************************************************/
     185             : 
     186       18349 : CSLConstList VRTDataset::GetMetadata(const char *pszDomain)
     187             : {
     188       18349 :     if (pszDomain != nullptr && EQUAL(pszDomain, "xml:VRT"))
     189             :     {
     190             :         /* ------------------------------------------------------------------ */
     191             :         /*      Convert tree to a single block of XML text.                   */
     192             :         /* ------------------------------------------------------------------ */
     193          33 :         const char *pszDescription = GetDescription();
     194          33 :         char *l_pszVRTPath = CPLStrdup(
     195          33 :             pszDescription[0] && !STARTS_WITH(pszDescription, "<VRTDataset")
     196          53 :                 ? CPLGetPathSafe(pszDescription).c_str()
     197             :                 : "");
     198          33 :         CPLXMLNode *psDSTree = SerializeToXML(l_pszVRTPath);
     199          33 :         char *pszXML = CPLSerializeXMLTree(psDSTree);
     200             : 
     201          33 :         CPLDestroyXMLNode(psDSTree);
     202             : 
     203          33 :         CPLFree(l_pszVRTPath);
     204             : 
     205          33 :         CSLDestroy(m_papszXMLVRTMetadata);
     206          33 :         m_papszXMLVRTMetadata =
     207          33 :             static_cast<char **>(CPLMalloc(2 * sizeof(char *)));
     208          33 :         m_papszXMLVRTMetadata[0] = pszXML;
     209          33 :         m_papszXMLVRTMetadata[1] = nullptr;
     210          33 :         return m_papszXMLVRTMetadata;
     211             :     }
     212             : 
     213       18316 :     return GDALDataset::GetMetadata(pszDomain);
     214             : }
     215             : 
     216             : /************************************************************************/
     217             : /*                          GetMetadataItem()                           */
     218             : /************************************************************************/
     219             : 
     220       28511 : const char *VRTDataset::GetMetadataItem(const char *pszName,
     221             :                                         const char *pszDomain)
     222             : 
     223             : {
     224       28511 :     if (pszName && pszDomain && EQUAL(pszDomain, "__DEBUG__"))
     225             :     {
     226          11 :         if (EQUAL(pszName, "MULTI_THREADED_RASTERIO_LAST_USED"))
     227          10 :             return m_bMultiThreadedRasterIOLastUsed ? "1" : "0";
     228           1 :         else if (EQUAL(pszName, "CheckCompatibleForDatasetIO()"))
     229           1 :             return CheckCompatibleForDatasetIO() ? "1" : "0";
     230             :     }
     231       28500 :     return GDALDataset::GetMetadataItem(pszName, pszDomain);
     232             : }
     233             : 
     234             : /*! @endcond */
     235             : 
     236             : /************************************************************************/
     237             : /*                    VRTFlushCache(bool bAtClosing)                    */
     238             : /************************************************************************/
     239             : 
     240             : /**
     241             :  * @see VRTDataset::FlushCache(bool bAtClosing)
     242             :  */
     243             : 
     244           0 : void CPL_STDCALL VRTFlushCache(VRTDatasetH hDataset)
     245             : {
     246           0 :     VALIDATE_POINTER0(hDataset, "VRTFlushCache");
     247             : 
     248           0 :     static_cast<VRTDataset *>(GDALDataset::FromHandle(hDataset))
     249           0 :         ->FlushCache(false);
     250             : }
     251             : 
     252             : /*! @cond Doxygen_Suppress */
     253             : 
     254             : /************************************************************************/
     255             : /*                           SerializeToXML()                           */
     256             : /************************************************************************/
     257             : 
     258         518 : CPLXMLNode *VRTDataset::SerializeToXML(const char *pszVRTPathIn)
     259             : 
     260             : {
     261         518 :     if (m_poRootGroup)
     262          88 :         return m_poRootGroup->SerializeToXML(pszVRTPathIn);
     263             : 
     264             :     /* -------------------------------------------------------------------- */
     265             :     /*      Setup root node and attributes.                                 */
     266             :     /* -------------------------------------------------------------------- */
     267         430 :     CPLXMLNode *psDSTree = CPLCreateXMLNode(nullptr, CXT_Element, "VRTDataset");
     268             : 
     269         430 :     char szNumber[128] = {'\0'};
     270         430 :     snprintf(szNumber, sizeof(szNumber), "%d", GetRasterXSize());
     271         430 :     CPLSetXMLValue(psDSTree, "#rasterXSize", szNumber);
     272             : 
     273         430 :     snprintf(szNumber, sizeof(szNumber), "%d", GetRasterYSize());
     274         430 :     CPLSetXMLValue(psDSTree, "#rasterYSize", szNumber);
     275             : 
     276             :     /* -------------------------------------------------------------------- */
     277             :     /*      SRS                                                             */
     278             :     /* -------------------------------------------------------------------- */
     279         430 :     if (m_poSRS && !m_poSRS->IsEmpty())
     280             :     {
     281         276 :         char *pszWKT = nullptr;
     282         276 :         m_poSRS->exportToWkt(&pszWKT);
     283             :         CPLXMLNode *psSRSNode =
     284         276 :             CPLCreateXMLElementAndValue(psDSTree, "SRS", pszWKT);
     285         276 :         CPLFree(pszWKT);
     286         276 :         const auto &mapping = m_poSRS->GetDataAxisToSRSAxisMapping();
     287         552 :         CPLString osMapping;
     288         830 :         for (size_t i = 0; i < mapping.size(); ++i)
     289             :         {
     290         554 :             if (!osMapping.empty())
     291         278 :                 osMapping += ",";
     292         554 :             osMapping += CPLSPrintf("%d", mapping[i]);
     293             :         }
     294         276 :         CPLAddXMLAttributeAndValue(psSRSNode, "dataAxisToSRSAxisMapping",
     295             :                                    osMapping.c_str());
     296         276 :         const double dfCoordinateEpoch = m_poSRS->GetCoordinateEpoch();
     297         276 :         if (dfCoordinateEpoch > 0)
     298             :         {
     299           2 :             std::string osCoordinateEpoch = CPLSPrintf("%f", dfCoordinateEpoch);
     300           1 :             if (osCoordinateEpoch.find('.') != std::string::npos)
     301             :             {
     302           6 :                 while (osCoordinateEpoch.back() == '0')
     303           5 :                     osCoordinateEpoch.pop_back();
     304             :             }
     305           1 :             CPLAddXMLAttributeAndValue(psSRSNode, "coordinateEpoch",
     306             :                                        osCoordinateEpoch.c_str());
     307             :         }
     308             :     }
     309             : 
     310             :     /* -------------------------------------------------------------------- */
     311             :     /*      Geotransform.                                                   */
     312             :     /* -------------------------------------------------------------------- */
     313         430 :     if (m_bGeoTransformSet)
     314             :     {
     315         338 :         CPLSetXMLValue(
     316             :             psDSTree, "GeoTransform",
     317             :             CPLSPrintf("%24.16e,%24.16e,%24.16e,%24.16e,%24.16e,%24.16e",
     318             :                        m_gt.xorig, m_gt.xscale, m_gt.xrot, m_gt.yorig,
     319             :                        m_gt.yrot, m_gt.yscale));
     320             :     }
     321             : 
     322             :     /* -------------------------------------------------------------------- */
     323             :     /*      Metadata                                                        */
     324             :     /* -------------------------------------------------------------------- */
     325         430 :     CPLXMLNode *psMD = oMDMD.Serialize();
     326         430 :     if (psMD != nullptr)
     327             :     {
     328         188 :         CPLAddXMLChild(psDSTree, psMD);
     329             :     }
     330             : 
     331             :     /* -------------------------------------------------------------------- */
     332             :     /*      GCPs                                                            */
     333             :     /* -------------------------------------------------------------------- */
     334         430 :     if (!m_asGCPs.empty())
     335             :     {
     336           5 :         GDALSerializeGCPListToXML(psDSTree, m_asGCPs, m_poGCP_SRS.get());
     337             :     }
     338             : 
     339             :     /* -------------------------------------------------------------------- */
     340             :     /*      Serialize bands.                                                */
     341             :     /* -------------------------------------------------------------------- */
     342         430 :     CPLXMLNode *psLastChild = psDSTree->psChild;
     343        1819 :     for (; psLastChild != nullptr && psLastChild->psNext;
     344        1389 :          psLastChild = psLastChild->psNext)
     345             :     {
     346             :     }
     347         430 :     CPLAssert(psLastChild);  // we have at least rasterXSize
     348         430 :     bool bHasWarnedAboutRAMUsage = false;
     349         430 :     size_t nAccRAMUsage = 0;
     350        1089 :     for (int iBand = 0; iBand < nBands; iBand++)
     351             :     {
     352             :         CPLXMLNode *psBandTree =
     353         659 :             static_cast<VRTRasterBand *>(papoBands[iBand])
     354        1318 :                 ->SerializeToXML(pszVRTPathIn, bHasWarnedAboutRAMUsage,
     355         659 :                                  nAccRAMUsage);
     356             : 
     357         659 :         if (psBandTree != nullptr)
     358             :         {
     359         659 :             psLastChild->psNext = psBandTree;
     360         659 :             psLastChild = psBandTree;
     361             :         }
     362             :     }
     363             : 
     364             :     /* -------------------------------------------------------------------- */
     365             :     /*      Serialize dataset mask band.                                    */
     366             :     /* -------------------------------------------------------------------- */
     367         430 :     if (m_poMaskBand)
     368             :     {
     369          19 :         CPLXMLNode *psBandTree = m_poMaskBand->SerializeToXML(
     370          19 :             pszVRTPathIn, bHasWarnedAboutRAMUsage, nAccRAMUsage);
     371             : 
     372          19 :         if (psBandTree != nullptr)
     373             :         {
     374             :             CPLXMLNode *psMaskBandElement =
     375          19 :                 CPLCreateXMLNode(psDSTree, CXT_Element, "MaskBand");
     376          19 :             CPLAddXMLChild(psMaskBandElement, psBandTree);
     377             :         }
     378             :     }
     379             : 
     380             :     /* -------------------------------------------------------------------- */
     381             :     /*      Overview factors.                                               */
     382             :     /* -------------------------------------------------------------------- */
     383         430 :     if (!m_anOverviewFactors.empty())
     384             :     {
     385          10 :         CPLString osOverviewList;
     386          16 :         for (int nOvFactor : m_anOverviewFactors)
     387             :         {
     388          11 :             if (!osOverviewList.empty())
     389           6 :                 osOverviewList += " ";
     390          11 :             osOverviewList += CPLSPrintf("%d", nOvFactor);
     391             :         }
     392           5 :         CPLXMLNode *psOverviewList = CPLCreateXMLElementAndValue(
     393             :             psDSTree, "OverviewList", osOverviewList);
     394           5 :         if (!m_osOverviewResampling.empty())
     395             :         {
     396           5 :             CPLAddXMLAttributeAndValue(psOverviewList, "resampling",
     397             :                                        m_osOverviewResampling);
     398             :         }
     399             :     }
     400             : 
     401         430 :     return psDSTree;
     402             : }
     403             : 
     404             : /*! @endcond */
     405             : /************************************************************************/
     406             : /*                         VRTSerializeToXML()                          */
     407             : /************************************************************************/
     408             : 
     409             : /**
     410             :  * @see VRTDataset::SerializeToXML()
     411             :  */
     412             : 
     413           0 : CPLXMLNode *CPL_STDCALL VRTSerializeToXML(VRTDatasetH hDataset,
     414             :                                           const char *pszVRTPath)
     415             : {
     416           0 :     VALIDATE_POINTER1(hDataset, "VRTSerializeToXML", nullptr);
     417             : 
     418           0 :     return static_cast<VRTDataset *>(GDALDataset::FromHandle(hDataset))
     419           0 :         ->SerializeToXML(pszVRTPath);
     420             : }
     421             : 
     422             : /*! @cond Doxygen_Suppress */
     423             : 
     424             : /************************************************************************/
     425             : /*                       IsRawRasterBandEnabled()                       */
     426             : /************************************************************************/
     427             : 
     428             : /** Return whether VRTRawRasterBand support is enabled */
     429             : 
     430             : /* static */
     431          78 : bool VRTDataset::IsRawRasterBandEnabled()
     432             : {
     433             : #ifdef GDAL_VRT_ENABLE_RAWRASTERBAND
     434          78 :     if (CPLTestBool(CPLGetConfigOption("GDAL_VRT_ENABLE_RAWRASTERBAND", "YES")))
     435             :     {
     436          76 :         return true;
     437             :     }
     438             :     else
     439             :     {
     440           2 :         CPLError(CE_Failure, CPLE_NotSupported,
     441             :                  "VRTRawRasterBand support has been disabled at run-time.");
     442             :     }
     443           2 :     return false;
     444             : #else
     445             :     CPLError(CE_Failure, CPLE_NotSupported,
     446             :              "VRTRawRasterBand is disabled in this GDAL build");
     447             :     return false;
     448             : #endif
     449             : }
     450             : 
     451             : /************************************************************************/
     452             : /*                              InitBand()                              */
     453             : /************************************************************************/
     454             : 
     455             : std::unique_ptr<VRTRasterBand>
     456        2722 : VRTDataset::InitBand(const char *pszSubclass, int nBand,
     457             :                      bool bAllowPansharpenedOrProcessed)
     458             : {
     459        2722 :     if (auto poProcessedDS = dynamic_cast<VRTProcessedDataset *>(this))
     460             :     {
     461          39 :         if (bAllowPansharpenedOrProcessed &&
     462          39 :             EQUAL(pszSubclass, "VRTProcessedRasterBand"))
     463             :         {
     464          78 :             return std::make_unique<VRTProcessedRasterBand>(poProcessedDS,
     465          39 :                                                             nBand);
     466             :         }
     467             :     }
     468        2683 :     else if (EQUAL(pszSubclass, "VRTSourcedRasterBand"))
     469         973 :         return std::make_unique<VRTSourcedRasterBand>(this, nBand);
     470        1710 :     else if (EQUAL(pszSubclass, "VRTDerivedRasterBand"))
     471        1360 :         return std::make_unique<VRTDerivedRasterBand>(this, nBand);
     472         350 :     else if (EQUAL(pszSubclass, "VRTRawRasterBand"))
     473             :     {
     474             : #ifdef GDAL_VRT_ENABLE_RAWRASTERBAND
     475          33 :         if (!VRTDataset::IsRawRasterBandEnabled())
     476             :         {
     477           1 :             return nullptr;
     478             :         }
     479          32 :         return std::make_unique<VRTRawRasterBand>(this, nBand);
     480             : #else
     481             :         CPLError(CE_Failure, CPLE_NotSupported,
     482             :                  "VRTDataset::InitBand(): cannot instantiate VRTRawRasterBand, "
     483             :                  "because disabled in this GDAL build");
     484             :         return nullptr;
     485             : #endif
     486             :     }
     487         575 :     else if (EQUAL(pszSubclass, "VRTWarpedRasterBand") &&
     488         258 :              dynamic_cast<VRTWarpedDataset *>(this) != nullptr)
     489             :     {
     490         258 :         return std::make_unique<VRTWarpedRasterBand>(this, nBand);
     491             :     }
     492          59 :     else if (bAllowPansharpenedOrProcessed &&
     493         118 :              EQUAL(pszSubclass, "VRTPansharpenedRasterBand") &&
     494          59 :              dynamic_cast<VRTPansharpenedDataset *>(this) != nullptr)
     495             :     {
     496          59 :         return std::make_unique<VRTPansharpenedRasterBand>(this, nBand);
     497             :     }
     498             : 
     499           0 :     CPLError(CE_Failure, CPLE_AppDefined,
     500             :              "VRTRasterBand of unrecognized subclass '%s'.", pszSubclass);
     501           0 :     return nullptr;
     502             : }
     503             : 
     504             : /************************************************************************/
     505             : /*                              XMLInit()                               */
     506             : /************************************************************************/
     507             : 
     508        2614 : CPLErr VRTDataset::XMLInit(const CPLXMLNode *psTree, const char *pszVRTPathIn)
     509             : 
     510             : {
     511        2614 :     if (pszVRTPathIn != nullptr)
     512         986 :         m_pszVRTPath = CPLStrdup(pszVRTPathIn);
     513             : 
     514             :     /* -------------------------------------------------------------------- */
     515             :     /*      Check for an SRS node.                                          */
     516             :     /* -------------------------------------------------------------------- */
     517        2614 :     const CPLXMLNode *psSRSNode = CPLGetXMLNode(psTree, "SRS");
     518        2614 :     if (psSRSNode)
     519             :     {
     520         467 :         m_poSRS = OGRSpatialReferenceRefCountedPtr::makeInstance();
     521         467 :         m_poSRS->SetFromUserInput(
     522             :             CPLGetXMLValue(psSRSNode, nullptr, ""),
     523             :             OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get());
     524             :         const char *pszMapping =
     525         467 :             CPLGetXMLValue(psSRSNode, "dataAxisToSRSAxisMapping", nullptr);
     526         467 :         if (pszMapping)
     527             :         {
     528             :             char **papszTokens =
     529         237 :                 CSLTokenizeStringComplex(pszMapping, ",", FALSE, FALSE);
     530         474 :             std::vector<int> anMapping;
     531         714 :             for (int i = 0; papszTokens && papszTokens[i]; i++)
     532             :             {
     533         477 :                 anMapping.push_back(atoi(papszTokens[i]));
     534             :             }
     535         237 :             CSLDestroy(papszTokens);
     536         237 :             m_poSRS->SetDataAxisToSRSAxisMapping(anMapping);
     537             :         }
     538             :         else
     539             :         {
     540         230 :             m_poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     541             :         }
     542             : 
     543             :         const char *pszCoordinateEpoch =
     544         467 :             CPLGetXMLValue(psSRSNode, "coordinateEpoch", nullptr);
     545         467 :         if (pszCoordinateEpoch)
     546           1 :             m_poSRS->SetCoordinateEpoch(CPLAtof(pszCoordinateEpoch));
     547             :     }
     548             : 
     549             :     /* -------------------------------------------------------------------- */
     550             :     /*      Check for a GeoTransform node.                                  */
     551             :     /* -------------------------------------------------------------------- */
     552        2614 :     const char *pszGT = CPLGetXMLValue(psTree, "GeoTransform", "");
     553        2614 :     if (strlen(pszGT) > 0)
     554             :     {
     555         544 :         if (m_gt.Init(pszGT, ","))
     556             :         {
     557         544 :             m_bGeoTransformSet = true;
     558             :         }
     559             :         else
     560             :         {
     561           0 :             CPLError(CE_Warning, CPLE_AppDefined, "Invalid GeoTransform");
     562             :         }
     563             :     }
     564             : 
     565             :     /* -------------------------------------------------------------------- */
     566             :     /*      Check for GCPs.                                                 */
     567             :     /* -------------------------------------------------------------------- */
     568        2614 :     if (const CPLXMLNode *psGCPList = CPLGetXMLNode(psTree, "GCPList"))
     569             :     {
     570          47 :         OGRSpatialReference *poSRS = nullptr;
     571          47 :         GDALDeserializeGCPListFromXML(psGCPList, m_asGCPs, &poSRS);
     572          47 :         m_poGCP_SRS.reset(poSRS, /* add_ref = */ false);
     573             :     }
     574             : 
     575             :     /* -------------------------------------------------------------------- */
     576             :     /*      Apply any dataset level metadata.                               */
     577             :     /* -------------------------------------------------------------------- */
     578        2614 :     oMDMD.XMLInit(psTree, TRUE);
     579             : 
     580             :     /* -------------------------------------------------------------------- */
     581             :     /*      Create dataset mask band.                                       */
     582             :     /* -------------------------------------------------------------------- */
     583             : 
     584             :     /* Parse dataset mask band first */
     585        2614 :     const CPLXMLNode *psMaskBandNode = CPLGetXMLNode(psTree, "MaskBand");
     586             : 
     587        2614 :     const CPLXMLNode *psChild = nullptr;
     588        2614 :     if (psMaskBandNode)
     589          28 :         psChild = psMaskBandNode->psChild;
     590             :     else
     591        2586 :         psChild = nullptr;
     592             : 
     593        2614 :     for (; psChild != nullptr; psChild = psChild->psNext)
     594             :     {
     595          28 :         if (psChild->eType == CXT_Element &&
     596          28 :             EQUAL(psChild->pszValue, "VRTRasterBand"))
     597             :         {
     598             :             const char *pszSubclass =
     599          28 :                 CPLGetXMLValue(psChild, "subclass", "VRTSourcedRasterBand");
     600             : 
     601          28 :             auto poBand = InitBand(pszSubclass, 0, false);
     602          56 :             if (poBand != nullptr &&
     603          28 :                 poBand->XMLInit(psChild, pszVRTPathIn, m_oMapSharedSources) ==
     604             :                     CE_None)
     605             :             {
     606          28 :                 SetMaskBand(std::move(poBand));
     607          28 :                 break;
     608             :             }
     609             :             else
     610             :             {
     611           0 :                 return CE_Failure;
     612             :             }
     613             :         }
     614             :     }
     615             : 
     616             :     /* -------------------------------------------------------------------- */
     617             :     /*      Create band information objects.                                */
     618             :     /* -------------------------------------------------------------------- */
     619        2614 :     int l_nBands = 0;
     620       12445 :     for (psChild = psTree->psChild; psChild != nullptr;
     621        9831 :          psChild = psChild->psNext)
     622             :     {
     623        9876 :         if (psChild->eType == CXT_Element &&
     624        5143 :             EQUAL(psChild->pszValue, "VRTRasterBand"))
     625             :         {
     626             :             const char *pszSubclass =
     627        2695 :                 CPLGetXMLValue(psChild, "subclass", "VRTSourcedRasterBand");
     628        2695 :             if (dynamic_cast<VRTProcessedDataset *>(this) &&
     629          39 :                 !EQUAL(pszSubclass, "VRTProcessedRasterBand"))
     630             :             {
     631           0 :                 CPLError(CE_Failure, CPLE_NotSupported,
     632             :                          "Only subClass=VRTProcessedRasterBand supported");
     633          45 :                 return CE_Failure;
     634             :             }
     635             : 
     636        4054 :             if (CPLGetXMLNode(psChild, "PixelFunctionType") != nullptr &&
     637        1359 :                 !EQUAL(pszSubclass, "VRTDerivedRasterBand"))
     638             :             {
     639           1 :                 CPLError(CE_Failure, CPLE_NotSupported,
     640             :                          "Pixel functions may only be used with "
     641             :                          "subClass=VRTDerivedRasterBand");
     642           1 :                 return CE_Failure;
     643             :             }
     644             : 
     645        2694 :             auto poBand = InitBand(pszSubclass, l_nBands + 1, true);
     646        5387 :             if (poBand != nullptr &&
     647        2693 :                 poBand->XMLInit(psChild, pszVRTPathIn, m_oMapSharedSources) ==
     648             :                     CE_None)
     649             :             {
     650        2650 :                 l_nBands++;
     651        2650 :                 SetBand(l_nBands, std::move(poBand));
     652             :             }
     653             :             else
     654             :             {
     655          44 :                 return CE_Failure;
     656             :             }
     657             :         }
     658             :     }
     659             : 
     660        2569 :     if (const CPLXMLNode *psGroup = CPLGetXMLNode(psTree, "Group"))
     661             :     {
     662         258 :         const char *pszName = CPLGetXMLValue(psGroup, "name", nullptr);
     663         258 :         if (pszName == nullptr || !EQUAL(pszName, "/"))
     664             :         {
     665           2 :             CPLError(CE_Failure, CPLE_AppDefined,
     666             :                      "Missing name or not equal to '/'");
     667           2 :             return CE_Failure;
     668             :         }
     669             : 
     670         256 :         m_poRootGroup = VRTGroup::Create(std::string(), "/");
     671         256 :         m_poRootGroup->SetIsRootGroup();
     672         256 :         if (!m_poRootGroup->XMLInit(m_poRootGroup, m_poRootGroup, psGroup,
     673             :                                     pszVRTPathIn))
     674             :         {
     675          22 :             return CE_Failure;
     676             :         }
     677             :     }
     678             : 
     679             :     /* -------------------------------------------------------------------- */
     680             :     /*      Create virtual overviews.                                       */
     681             :     /* -------------------------------------------------------------------- */
     682        2545 :     const char *pszSubClass = CPLGetXMLValue(psTree, "subClass", "");
     683        2545 :     if (EQUAL(pszSubClass, ""))
     684             :     {
     685             :         m_aosOverviewList =
     686        2229 :             CSLTokenizeString(CPLGetXMLValue(psTree, "OverviewList", ""));
     687             :         m_osOverviewResampling =
     688        2229 :             CPLGetXMLValue(psTree, "OverviewList.resampling", "");
     689             :     }
     690             : 
     691        2545 :     return CE_None;
     692             : }
     693             : 
     694             : /************************************************************************/
     695             : /*                            GetGCPCount()                             */
     696             : /************************************************************************/
     697             : 
     698        2451 : int VRTDataset::GetGCPCount()
     699             : 
     700             : {
     701        2451 :     return static_cast<int>(m_asGCPs.size());
     702             : }
     703             : 
     704             : /************************************************************************/
     705             : /*                              GetGCPs()                               */
     706             : /************************************************************************/
     707             : 
     708          75 : const GDAL_GCP *VRTDataset::GetGCPs()
     709             : 
     710             : {
     711          75 :     return gdal::GCP::c_ptr(m_asGCPs);
     712             : }
     713             : 
     714             : /************************************************************************/
     715             : /*                              SetGCPs()                               */
     716             : /************************************************************************/
     717             : 
     718          35 : CPLErr VRTDataset::SetGCPs(int nGCPCountIn, const GDAL_GCP *pasGCPListIn,
     719             :                            const OGRSpatialReference *poGCP_SRS)
     720             : 
     721             : {
     722          35 :     m_poGCP_SRS = OGRSpatialReferenceRefCountedPtr::makeClone(poGCP_SRS);
     723          35 :     m_asGCPs = gdal::GCP::fromC(pasGCPListIn, nGCPCountIn);
     724             : 
     725          35 :     SetNeedsFlush();
     726             : 
     727          35 :     return CE_None;
     728             : }
     729             : 
     730             : /************************************************************************/
     731             : /*                           SetSpatialRef()                            */
     732             : /************************************************************************/
     733             : 
     734        2779 : CPLErr VRTDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
     735             : 
     736             : {
     737        2779 :     m_poSRS = OGRSpatialReferenceRefCountedPtr::makeClone(poSRS);
     738             : 
     739        2779 :     SetNeedsFlush();
     740             : 
     741        2779 :     return CE_None;
     742             : }
     743             : 
     744             : /************************************************************************/
     745             : /*                          SetGeoTransform()                           */
     746             : /************************************************************************/
     747             : 
     748        2954 : CPLErr VRTDataset::SetGeoTransform(const GDALGeoTransform &gt)
     749             : 
     750             : {
     751        2954 :     m_gt = gt;
     752        2954 :     m_bGeoTransformSet = TRUE;
     753             : 
     754        2954 :     SetNeedsFlush();
     755             : 
     756        2954 :     return CE_None;
     757             : }
     758             : 
     759             : /************************************************************************/
     760             : /*                          GetGeoTransform()                           */
     761             : /************************************************************************/
     762             : 
     763        8603 : CPLErr VRTDataset::GetGeoTransform(GDALGeoTransform &gt) const
     764             : 
     765             : {
     766        8603 :     gt = m_gt;
     767             : 
     768        8603 :     return m_bGeoTransformSet ? CE_None : CE_Failure;
     769             : }
     770             : 
     771             : /************************************************************************/
     772             : /*                            SetMetadata()                             */
     773             : /************************************************************************/
     774             : 
     775        2486 : CPLErr VRTDataset::SetMetadata(CSLConstList papszMetadata,
     776             :                                const char *pszDomain)
     777             : 
     778             : {
     779        2486 :     SetNeedsFlush();
     780             : 
     781        2486 :     return GDALDataset::SetMetadata(papszMetadata, pszDomain);
     782             : }
     783             : 
     784             : /************************************************************************/
     785             : /*                          SetMetadataItem()                           */
     786             : /************************************************************************/
     787             : 
     788        2540 : CPLErr VRTDataset::SetMetadataItem(const char *pszName, const char *pszValue,
     789             :                                    const char *pszDomain)
     790             : 
     791             : {
     792        2540 :     SetNeedsFlush();
     793             : 
     794        2540 :     return GDALDataset::SetMetadataItem(pszName, pszValue, pszDomain);
     795             : }
     796             : 
     797             : /************************************************************************/
     798             : /*                              Identify()                              */
     799             : /************************************************************************/
     800             : 
     801       76836 : int VRTDataset::Identify(GDALOpenInfo *poOpenInfo)
     802             : 
     803             : {
     804       76836 :     if (poOpenInfo->nHeaderBytes > 20 &&
     805       12407 :         strstr(reinterpret_cast<const char *>(poOpenInfo->pabyHeader),
     806             :                "<VRTDataset") != nullptr)
     807        1997 :         return TRUE;
     808             : 
     809       74839 :     if (strstr(poOpenInfo->pszFilename, "<VRTDataset") != nullptr)
     810        3289 :         return TRUE;
     811             : 
     812       71550 :     if (STARTS_WITH_CI(poOpenInfo->pszFilename, VRT_PROTOCOL_PREFIX))
     813         212 :         return TRUE;
     814             : 
     815       71338 :     return FALSE;
     816             : }
     817             : 
     818             : /************************************************************************/
     819             : /*                                Open()                                */
     820             : /************************************************************************/
     821             : 
     822        2732 : GDALDataset *VRTDataset::Open(GDALOpenInfo *poOpenInfo)
     823             : 
     824             : {
     825             :     /* -------------------------------------------------------------------- */
     826             :     /*      Does this appear to be a virtual dataset definition XML         */
     827             :     /*      file?                                                           */
     828             :     /* -------------------------------------------------------------------- */
     829        2732 :     if (!Identify(poOpenInfo))
     830           0 :         return nullptr;
     831             : 
     832        2732 :     if (STARTS_WITH_CI(poOpenInfo->pszFilename, VRT_PROTOCOL_PREFIX))
     833         106 :         return OpenVRTProtocol(poOpenInfo->pszFilename);
     834             : 
     835             :     /* -------------------------------------------------------------------- */
     836             :     /*      Try to read the whole file into memory.                         */
     837             :     /* -------------------------------------------------------------------- */
     838        2626 :     char *pszXML = nullptr;
     839        2626 :     VSILFILE *fp = poOpenInfo->fpL;
     840             : 
     841        2626 :     char *pszVRTPath = nullptr;
     842        2626 :     if (fp != nullptr)
     843             :     {
     844         982 :         poOpenInfo->fpL = nullptr;
     845             : 
     846         982 :         GByte *pabyOut = nullptr;
     847         982 :         if (!VSIIngestFile(fp, poOpenInfo->pszFilename, &pabyOut, nullptr,
     848             :                            INT_MAX - 1))
     849             :         {
     850           0 :             CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
     851           0 :             return nullptr;
     852             :         }
     853         982 :         pszXML = reinterpret_cast<char *>(pabyOut);
     854             : 
     855         982 :         char *pszCurDir = CPLGetCurrentDir();
     856             :         std::string currentVrtFilename =
     857         982 :             CPLProjectRelativeFilenameSafe(pszCurDir, poOpenInfo->pszFilename);
     858         982 :         CPLString osInitialCurrentVrtFilename(currentVrtFilename);
     859         982 :         CPLFree(pszCurDir);
     860             : 
     861             : #if !defined(_WIN32)
     862             :         char filenameBuffer[2048];
     863             : 
     864             :         while (true)
     865             :         {
     866             :             VSIStatBuf statBuffer;
     867         986 :             int lstatCode = lstat(currentVrtFilename.c_str(), &statBuffer);
     868         986 :             if (lstatCode == -1)
     869             :             {
     870         337 :                 if (errno == ENOENT)
     871             :                 {
     872             :                     // File could be a virtual file, let later checks handle it.
     873         337 :                     break;
     874             :                 }
     875             :                 else
     876             :                 {
     877           0 :                     CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
     878           0 :                     CPLFree(pszXML);
     879           0 :                     CPLError(CE_Failure, CPLE_FileIO, "Failed to lstat %s: %s",
     880           0 :                              currentVrtFilename.c_str(), VSIStrerror(errno));
     881           0 :                     return nullptr;
     882             :                 }
     883             :             }
     884             : 
     885         649 :             if (!VSI_ISLNK(statBuffer.st_mode))
     886             :             {
     887         645 :                 break;
     888             :             }
     889             : 
     890             :             const int bufferSize = static_cast<int>(
     891           4 :                 readlink(currentVrtFilename.c_str(), filenameBuffer,
     892           4 :                          sizeof(filenameBuffer)));
     893           4 :             if (bufferSize != -1)
     894             :             {
     895           4 :                 filenameBuffer[std::min(
     896           4 :                     bufferSize, static_cast<int>(sizeof(filenameBuffer)) - 1)] =
     897             :                     0;
     898             :                 // The filename in filenameBuffer might be a relative path
     899             :                 // from the linkfile resolve it before looping
     900           8 :                 currentVrtFilename = CPLProjectRelativeFilenameSafe(
     901           8 :                     CPLGetDirnameSafe(currentVrtFilename.c_str()).c_str(),
     902           4 :                     filenameBuffer);
     903             :             }
     904             :             else
     905             :             {
     906           0 :                 CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
     907           0 :                 CPLFree(pszXML);
     908           0 :                 CPLError(CE_Failure, CPLE_FileIO,
     909             :                          "Failed to read filename from symlink %s: %s",
     910           0 :                          currentVrtFilename.c_str(), VSIStrerror(errno));
     911           0 :                 return nullptr;
     912             :             }
     913           4 :         }
     914             : #endif  // !defined(__WIN32)
     915             : 
     916         982 :         if (osInitialCurrentVrtFilename == currentVrtFilename)
     917             :             pszVRTPath =
     918         979 :                 CPLStrdup(CPLGetPathSafe(poOpenInfo->pszFilename).c_str());
     919             :         else
     920             :             pszVRTPath =
     921           3 :                 CPLStrdup(CPLGetPathSafe(currentVrtFilename.c_str()).c_str());
     922             : 
     923         982 :         CPL_IGNORE_RET_VAL(VSIFCloseL(fp));
     924             :     }
     925             :     /* -------------------------------------------------------------------- */
     926             :     /*      Or use the filename as the XML input.                           */
     927             :     /* -------------------------------------------------------------------- */
     928             :     else
     929             :     {
     930        1644 :         pszXML = CPLStrdup(poOpenInfo->pszFilename);
     931             :     }
     932             : 
     933        2626 :     if (CSLFetchNameValue(poOpenInfo->papszOpenOptions, "ROOT_PATH") != nullptr)
     934             :     {
     935           5 :         CPLFree(pszVRTPath);
     936           5 :         pszVRTPath = CPLStrdup(
     937           5 :             CSLFetchNameValue(poOpenInfo->papszOpenOptions, "ROOT_PATH"));
     938             :     }
     939             : 
     940             :     /* -------------------------------------------------------------------- */
     941             :     /*      Turn the XML representation into a VRTDataset.                  */
     942             :     /* -------------------------------------------------------------------- */
     943        5252 :     auto poDS = OpenXML(pszXML, pszVRTPath, poOpenInfo->eAccess);
     944             : 
     945        2626 :     if (poDS != nullptr)
     946        2486 :         poDS->m_bNeedsFlush = false;
     947             : 
     948        2626 :     if (poDS != nullptr)
     949             :     {
     950        2486 :         if (poDS->GetRasterCount() == 0 &&
     951        2487 :             (poOpenInfo->nOpenFlags & GDAL_OF_MULTIDIM_RASTER) == 0 &&
     952           1 :             strstr(pszXML, "VRTPansharpenedDataset") == nullptr)
     953             :         {
     954           0 :             poDS.reset();
     955             :         }
     956        4972 :         else if (poDS->GetRootGroup() == nullptr &&
     957        4972 :                  (poOpenInfo->nOpenFlags & GDAL_OF_RASTER) == 0 &&
     958           0 :                  (poOpenInfo->nOpenFlags & GDAL_OF_MULTIDIM_RASTER) != 0)
     959             :         {
     960           0 :             poDS.reset();
     961             :         }
     962             :     }
     963             : 
     964        2626 :     CPLFree(pszXML);
     965        2626 :     CPLFree(pszVRTPath);
     966             : 
     967             :     /* -------------------------------------------------------------------- */
     968             :     /*      Initialize info for later overview discovery.                   */
     969             :     /* -------------------------------------------------------------------- */
     970             : 
     971        2626 :     if (poDS != nullptr)
     972             :     {
     973        2486 :         if (fp != nullptr)
     974             :         {
     975         969 :             poDS->oOvManager.Initialize(poDS.get(), poOpenInfo->pszFilename);
     976         969 :             if (poOpenInfo->AreSiblingFilesLoaded())
     977           2 :                 poDS->oOvManager.TransferSiblingFiles(
     978             :                     poOpenInfo->StealSiblingFiles());
     979             :         }
     980             : 
     981             :         // Creating virtual overviews, but only if there is no higher priority
     982             :         // overview source, ie. a Overview element at VRT band level,
     983             :         // or external .vrt.ovr
     984        2486 :         if (!poDS->m_aosOverviewList.empty())
     985             :         {
     986           8 :             if (poDS->nBands > 0)
     987             :             {
     988           8 :                 auto poBand = dynamic_cast<VRTRasterBand *>(poDS->papoBands[0]);
     989           8 :                 if (poBand && !poBand->m_aoOverviewInfos.empty())
     990             :                 {
     991           0 :                     poDS->m_aosOverviewList.Clear();
     992           0 :                     CPLDebug("VRT",
     993             :                              "Ignoring virtual overviews of OverviewList "
     994             :                              "because Overview element is present on VRT band");
     995             :                 }
     996          16 :                 else if (poBand &&
     997           8 :                          poBand->GDALRasterBand::GetOverviewCount() > 0)
     998             :                 {
     999           1 :                     poDS->m_aosOverviewList.Clear();
    1000           1 :                     CPLDebug("VRT",
    1001             :                              "Ignoring virtual overviews of OverviewList "
    1002             :                              "because external .vrt.ovr is available");
    1003             :                 }
    1004             :             }
    1005          21 :             for (int iOverview = 0; iOverview < poDS->m_aosOverviewList.size();
    1006             :                  iOverview++)
    1007             :             {
    1008          13 :                 const int nOvFactor = atoi(poDS->m_aosOverviewList[iOverview]);
    1009          13 :                 if (nOvFactor <= 1)
    1010             :                 {
    1011           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    1012             :                              "Invalid overview factor");
    1013           0 :                     return nullptr;
    1014             :                 }
    1015             : 
    1016          38 :                 poDS->AddVirtualOverview(
    1017          13 :                     nOvFactor, poDS->m_osOverviewResampling.empty()
    1018             :                                    ? "nearest"
    1019          12 :                                    : poDS->m_osOverviewResampling.c_str());
    1020             :             }
    1021           8 :             poDS->m_aosOverviewList.Clear();
    1022             :         }
    1023             : 
    1024        2575 :         if (poDS->eAccess == GA_Update && poDS->m_poRootGroup &&
    1025          89 :             !STARTS_WITH_CI(poOpenInfo->pszFilename, "<VRT"))
    1026             :         {
    1027          88 :             poDS->m_poRootGroup->SetFilename(poOpenInfo->pszFilename);
    1028             :         }
    1029             :     }
    1030             : 
    1031        2626 :     return poDS.release();
    1032             : }
    1033             : 
    1034             : /************************************************************************/
    1035             : /*                         OpenVRTProtocol()                            */
    1036             : /*                                                                      */
    1037             : /*      Create an open VRTDataset from a vrt:// string.                 */
    1038             : /************************************************************************/
    1039             : 
    1040         106 : GDALDataset *VRTDataset::OpenVRTProtocol(const char *pszSpec)
    1041             : 
    1042             : {
    1043         106 :     CPLAssert(STARTS_WITH_CI(pszSpec, VRT_PROTOCOL_PREFIX));
    1044         212 :     CPLString osFilename(pszSpec + strlen(VRT_PROTOCOL_PREFIX));
    1045         106 :     const auto nPosQuotationMark = osFilename.find('?');
    1046         212 :     CPLString osQueryString;
    1047         106 :     if (nPosQuotationMark != std::string::npos)
    1048             :     {
    1049          96 :         osQueryString = osFilename.substr(nPosQuotationMark + 1);
    1050          96 :         osFilename.resize(nPosQuotationMark);
    1051             :     }
    1052             : 
    1053             :     // Parse query string, get args required for initial Open()
    1054         212 :     const CPLStringList aosTokens(CSLTokenizeString2(osQueryString, "&", 0));
    1055         212 :     CPLStringList aosAllowedDrivers;
    1056         212 :     CPLStringList aosOpenOptions;
    1057             : 
    1058         246 :     for (const auto &[pszKey, pszValue] : cpl::IterateNameValue(
    1059         348 :              aosTokens, /* bReturnNullKeyIfNotNameValue = */ true))
    1060             :     {
    1061         125 :         if (!pszKey)
    1062             :         {
    1063           2 :             CPLError(CE_Failure, CPLE_NotSupported,
    1064             :                      "Invalid option specification: %s "
    1065             :                      "must be in the form 'key=value'",
    1066             :                      pszValue);
    1067           4 :             return nullptr;
    1068             :         }
    1069         123 :         else if (EQUAL(pszKey, "if"))
    1070             :         {
    1071           4 :             if (!aosAllowedDrivers.empty())
    1072             :             {
    1073           1 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1074             :                          "'if' option should be specified once, use commas "
    1075             :                          "to input multiple values.");
    1076           1 :                 return nullptr;
    1077             :             }
    1078           3 :             aosAllowedDrivers = CSLTokenizeString2(pszValue, ",", 0);
    1079             :         }
    1080         119 :         else if (EQUAL(pszKey, "oo"))
    1081             :         {
    1082           3 :             if (!aosOpenOptions.empty())
    1083             :             {
    1084           1 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1085             :                          "'oo' option should be specified once, use commas "
    1086             :                          "to input multiple values.");
    1087           1 :                 return nullptr;
    1088             :             }
    1089           2 :             aosOpenOptions = CSLTokenizeString2(pszValue, ",", 0);
    1090             :         }
    1091             :     }
    1092             : 
    1093             :     // We don't open in GDAL_OF_SHARED mode to avoid issues when we open a
    1094             :     // http://.jp2 file with the JP2OpenJPEG driver through the HTTP driver,
    1095             :     // which returns a /vsimem/ file
    1096             :     auto poSrcDS = std::unique_ptr<GDALDataset, GDALDatasetUniquePtrReleaser>(
    1097             :         GDALDataset::Open(osFilename, GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR,
    1098         102 :                           aosAllowedDrivers.List(), aosOpenOptions.List(),
    1099         204 :                           nullptr));
    1100         102 :     if (poSrcDS == nullptr)
    1101             :     {
    1102           4 :         return nullptr;
    1103             :     }
    1104             : 
    1105          98 :     bool bFound_transpose = false;
    1106         214 :     for (const auto &[pszKey, pszValue] : cpl::IterateNameValue(aosTokens))
    1107             :     {
    1108         117 :         if (EQUAL(pszKey, "transpose"))
    1109             :         {
    1110           5 :             bFound_transpose = true;
    1111             :             const CPLStringList aosTransposeTokens(
    1112           5 :                 CSLTokenizeString2(pszValue, ":", 0));
    1113           5 :             if (aosTransposeTokens.size() != 2)
    1114             :             {
    1115           0 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1116             :                          "Invalid transpose option: %s", pszValue);
    1117           0 :                 return nullptr;
    1118             :             }
    1119             :             const CPLStringList aosTransposeIndex(
    1120           5 :                 CSLTokenizeString2(aosTransposeTokens[1], ",", 0));
    1121             :             // fail if not two values
    1122           5 :             if (aosTransposeIndex.size() != 2)
    1123             :             {
    1124           0 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1125             :                          "Invalid transpose option: %s", pszValue);
    1126           0 :                 return nullptr;
    1127             :             }
    1128             : 
    1129             :             int index_x;
    1130           5 :             if (const auto oVal = cpl::strict_parse<int>(aosTransposeIndex[0]))
    1131             :             {
    1132           4 :                 index_x = oVal.value();
    1133             :             }
    1134             :             else
    1135             :             {
    1136           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1137             :                          "Invalid transpose index: %s", aosTransposeIndex[0]);
    1138           1 :                 return nullptr;
    1139             :             }
    1140             : 
    1141             :             int index_y;
    1142           4 :             if (const auto oVal = cpl::strict_parse<int>(aosTransposeIndex[1]))
    1143             :             {
    1144           4 :                 index_y = oVal.value();
    1145             :             }
    1146             :             else
    1147             :             {
    1148           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1149             :                          "Invalid transpose index: %s", aosTransposeIndex[1]);
    1150           0 :                 return nullptr;
    1151             :             }
    1152             : 
    1153             :             auto poMDimDS = std::unique_ptr<GDALDataset>(
    1154           4 :                 GDALDataset::Open(osFilename, GDAL_OF_MULTIDIM_RASTER));
    1155           4 :             if (!poMDimDS)
    1156           0 :                 return nullptr;
    1157           4 :             auto poMdimGroup = poMDimDS->GetRootGroup();
    1158           4 :             if (!poMdimGroup)
    1159             :             {
    1160           0 :                 return nullptr;
    1161             :             }
    1162             :             auto poArray =
    1163           8 :                 poMdimGroup->OpenMDArrayFromFullname(aosTransposeTokens[0]);
    1164           4 :             if (!poArray)
    1165             :             {
    1166           0 :                 return nullptr;
    1167             :             }
    1168             : 
    1169           4 :             auto poClassicDS = poArray->AsClassicDataset(index_x, index_y);
    1170             : 
    1171           4 :             if (!poClassicDS)
    1172           0 :                 return nullptr;
    1173             :             poSrcDS =
    1174           8 :                 std::unique_ptr<GDALDataset, GDALDatasetUniquePtrReleaser>(
    1175           4 :                     poClassicDS);
    1176             :         }
    1177             :     }
    1178             :     // scan for sd_name/sd in tokens, close the source dataset and reopen if found/valid
    1179          97 :     bool bFound_subdataset = false;
    1180         206 :     for (const auto &[pszKey, pszValue] : cpl::IterateNameValue(aosTokens))
    1181             :     {
    1182         114 :         if (EQUAL(pszKey, "sd_name"))
    1183             :         {
    1184           5 :             if (bFound_transpose)
    1185             :             {
    1186           1 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1187             :                          "'sd_name' is mutually exclusive with option "
    1188             :                          "'transpose'");
    1189           5 :                 return nullptr;
    1190             :             }
    1191           4 :             if (bFound_subdataset)
    1192             :             {
    1193           1 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1194             :                          "'sd_name' is mutually exclusive with option "
    1195             :                          "'sd'");
    1196           1 :                 return nullptr;
    1197             :             }
    1198             :             CSLConstList papszSubdatasets =
    1199           3 :                 poSrcDS->GetMetadata(GDAL_MDD_SUBDATASETS);
    1200           3 :             int nSubdatasets = CSLCount(papszSubdatasets);
    1201             : 
    1202           3 :             if (nSubdatasets > 0)
    1203             :             {
    1204           3 :                 bool bFound = false;
    1205          25 :                 for (int j = 0; j < nSubdatasets && papszSubdatasets[j]; j += 2)
    1206             :                 {
    1207          24 :                     const char *pszEqual = strchr(papszSubdatasets[j], '=');
    1208          24 :                     if (!pszEqual)
    1209             :                     {
    1210           0 :                         CPLError(CE_Failure, CPLE_IllegalArg,
    1211             :                                  "'sd_name:' failed to obtain "
    1212             :                                  "subdataset string ");
    1213           0 :                         return nullptr;
    1214             :                     }
    1215          24 :                     const char *pszSubdatasetSource = pszEqual + 1;
    1216             :                     GDALSubdatasetInfoH info =
    1217          24 :                         GDALGetSubdatasetInfo(pszSubdatasetSource);
    1218             :                     char *component =
    1219          24 :                         info ? GDALSubdatasetInfoGetSubdatasetComponent(info)
    1220          24 :                              : nullptr;
    1221             : 
    1222          24 :                     bFound = component && EQUAL(pszValue, component);
    1223          24 :                     bFound_subdataset = true;
    1224          24 :                     CPLFree(component);
    1225          24 :                     GDALDestroySubdatasetInfo(info);
    1226          24 :                     if (bFound)
    1227             :                     {
    1228           2 :                         poSrcDS.reset(GDALDataset::Open(
    1229             :                             pszSubdatasetSource,
    1230             :                             GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR,
    1231           2 :                             aosAllowedDrivers.List(), aosOpenOptions.List(),
    1232             :                             nullptr));
    1233           2 :                         if (poSrcDS == nullptr)
    1234             :                         {
    1235           0 :                             return nullptr;
    1236             :                         }
    1237             : 
    1238           2 :                         break;
    1239             :                     }
    1240             :                 }
    1241             : 
    1242           3 :                 if (!bFound)
    1243             :                 {
    1244           1 :                     CPLError(CE_Failure, CPLE_IllegalArg,
    1245             :                              "'sd_name' option should be a valid "
    1246             :                              "subdataset component name");
    1247           1 :                     return nullptr;
    1248             :                 }
    1249             :             }
    1250             :         }
    1251             : 
    1252         111 :         if (EQUAL(pszKey, "sd"))
    1253             :         {
    1254           4 :             if (bFound_transpose)
    1255             :             {
    1256           1 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1257             :                          "'sd' is mutually exclusive with option "
    1258             :                          "'transpose'");
    1259           1 :                 return nullptr;
    1260             :             }
    1261           3 :             if (bFound_subdataset)
    1262             :             {
    1263           0 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1264             :                          "'sd' is mutually exclusive with option "
    1265             :                          "'sd_name'");
    1266           0 :                 return nullptr;
    1267             :             }
    1268             :             CSLConstList papszSubdatasets =
    1269           3 :                 poSrcDS->GetMetadata(GDAL_MDD_SUBDATASETS);
    1270           3 :             int nSubdatasets = CSLCount(papszSubdatasets);
    1271             : 
    1272           3 :             if (nSubdatasets > 0)
    1273             :             {
    1274           3 :                 int iSubdataset = atoi(pszValue);
    1275           3 :                 if (iSubdataset < 1 || iSubdataset > (nSubdatasets) / 2)
    1276             :                 {
    1277           1 :                     CPLError(CE_Failure, CPLE_IllegalArg,
    1278             :                              "'sd' option should indicate a valid "
    1279             :                              "subdataset component number (starting with 1)");
    1280           1 :                     return nullptr;
    1281             :                 }
    1282             :                 const std::string osSubdatasetSource(
    1283           2 :                     strstr(papszSubdatasets[(iSubdataset - 1) * 2], "=") + 1);
    1284           2 :                 if (osSubdatasetSource.empty())
    1285             :                 {
    1286           0 :                     CPLError(CE_Failure, CPLE_IllegalArg,
    1287             :                              "'sd:' failed to obtain subdataset "
    1288             :                              "string ");
    1289           0 :                     return nullptr;
    1290             :                 }
    1291             : 
    1292           2 :                 poSrcDS.reset(GDALDataset::Open(
    1293             :                     osSubdatasetSource.c_str(),
    1294             :                     GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR,
    1295           2 :                     aosAllowedDrivers.List(), aosOpenOptions.List(), nullptr));
    1296           2 :                 if (poSrcDS == nullptr)
    1297             :                 {
    1298           0 :                     return nullptr;
    1299             :                 }
    1300           2 :                 bFound_subdataset = true;
    1301             :             }
    1302             :         }
    1303             :     }
    1304             : 
    1305         184 :     std::vector<int> anBands;
    1306             : 
    1307             :     // Check for 'block' option and validate/convert to srcwin
    1308          92 :     int nBlockXOff = -1;
    1309          92 :     int nBlockYOff = -1;
    1310          92 :     bool bFoundBlock = false;
    1311         192 :     for (const auto &[pszKey, pszValue] : cpl::IterateNameValue(aosTokens))
    1312             :     {
    1313         108 :         if (EQUAL(pszKey, "block"))
    1314             :         {
    1315             :             const CPLStringList aosBlockParams(
    1316          23 :                 CSLTokenizeString2(pszValue, ",", 0));
    1317          23 :             if (aosBlockParams.size() != 2)
    1318             :             {
    1319           2 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1320             :                          "Invalid block option: %s, must be two "
    1321             :                          "values separated by comma nXBlockOff,nYBlockOff",
    1322             :                          pszValue);
    1323           2 :                 return nullptr;
    1324             :             }
    1325             : 
    1326          21 :             nBlockXOff = cpl::strict_parse<int>(aosBlockParams[0]).value_or(-1);
    1327          21 :             if (nBlockXOff < 0)
    1328             :             {
    1329           3 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1330             :                          "Invalid block option: nXBlockOff '%s' is not a valid "
    1331             :                          "non-negative integer",
    1332             :                          aosBlockParams[0]);
    1333           3 :                 return nullptr;
    1334             :             }
    1335             : 
    1336          18 :             nBlockYOff = cpl::strict_parse<int>(aosBlockParams[1]).value_or(-1);
    1337          18 :             if (nBlockYOff < 0)
    1338             :             {
    1339           3 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1340             :                          "Invalid block option: nYBlockOff '%s' is not a valid "
    1341             :                          "non-negative integer",
    1342             :                          aosBlockParams[1]);
    1343           3 :                 return nullptr;
    1344             :             }
    1345             : 
    1346          15 :             bFoundBlock = true;
    1347             :         }
    1348             :     }
    1349             : 
    1350             :     // Validate block indices and convert to pixel coordinates
    1351          84 :     int nBlockSrcWinXOff = 0;
    1352          84 :     int nBlockSrcWinYOff = 0;
    1353          84 :     int nBlockSrcWinXSize = 0;
    1354          84 :     int nBlockSrcWinYSize = 0;
    1355          84 :     if (bFoundBlock)
    1356             :     {
    1357             :         // Check mutual exclusivity with other spatial options
    1358          31 :         for (const auto &[pszKey, pszValue] : cpl::IterateNameValue(aosTokens))
    1359             :         {
    1360          22 :             if (EQUAL(pszKey, "srcwin") || EQUAL(pszKey, "projwin") ||
    1361          20 :                 EQUAL(pszKey, "outsize") || EQUAL(pszKey, "tr") ||
    1362          18 :                 EQUAL(pszKey, "r") || EQUAL(pszKey, "ovr"))
    1363             :             {
    1364           6 :                 CPLError(
    1365             :                     CE_Failure, CPLE_IllegalArg,
    1366             :                     "'block' is mutually exclusive with options "
    1367             :                     "'srcwin', 'projwin', 'outsize', 'tr', 'r', and 'ovr'");
    1368           6 :                 return nullptr;
    1369             :             }
    1370             :         }
    1371             : 
    1372             :         // Check that the dataset has at least one band
    1373           9 :         if (poSrcDS->GetRasterCount() == 0)
    1374             :         {
    1375           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    1376             :                      "'block' option requires a raster with at least one band");
    1377           0 :             return nullptr;
    1378             :         }
    1379             : 
    1380             :         // Validate using GetActualBlockSize which handles bounds checking
    1381           9 :         int nXValid = 0;
    1382           9 :         int nYValid = 0;
    1383           9 :         int nBlockXSize = 0;
    1384           9 :         int nBlockYSize = 0;
    1385           9 :         poSrcDS->GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize);
    1386           9 :         if (poSrcDS->GetRasterBand(1)->GetActualBlockSize(
    1387           9 :                 nBlockXOff, nBlockYOff, &nXValid, &nYValid) != CE_None)
    1388             :         {
    1389             : 
    1390             :             const int nMaxXBlock =
    1391           2 :                 cpl::div_round_up(poSrcDS->GetRasterXSize(), nBlockXSize);
    1392             :             const int nMaxYBlock =
    1393           2 :                 cpl::div_round_up(poSrcDS->GetRasterYSize(), nBlockYSize);
    1394           2 :             CPLError(CE_Failure, CPLE_IllegalArg,
    1395             :                      "Invalid block indices: %d,%d. "
    1396             :                      "Valid range is 0-%d for X and 0-%d for Y",
    1397             :                      nBlockXOff, nBlockYOff, nMaxXBlock - 1, nMaxYBlock - 1);
    1398           2 :             return nullptr;
    1399             :         }
    1400             : 
    1401           7 :         nBlockSrcWinXOff = nBlockXOff * nBlockXSize;
    1402           7 :         nBlockSrcWinYOff = nBlockYOff * nBlockYSize;
    1403           7 :         nBlockSrcWinXSize = nXValid;
    1404           7 :         nBlockSrcWinYSize = nYValid;
    1405             :     }
    1406             : 
    1407         152 :     CPLStringList argv;
    1408          76 :     argv.AddString("-of");
    1409          76 :     argv.AddString("VRT");
    1410             : 
    1411             :     // Add srcwin from block option before processing other options
    1412          76 :     if (bFoundBlock)
    1413             :     {
    1414           7 :         argv.AddString("-srcwin");
    1415           7 :         argv.AddString(CPLSPrintf("%d", nBlockSrcWinXOff));
    1416           7 :         argv.AddString(CPLSPrintf("%d", nBlockSrcWinYOff));
    1417           7 :         argv.AddString(CPLSPrintf("%d", nBlockSrcWinXSize));
    1418           7 :         argv.AddString(CPLSPrintf("%d", nBlockSrcWinYSize));
    1419             :     }
    1420             : 
    1421         148 :     for (const auto &[pszKey, pszValue] : cpl::IterateNameValue(aosTokens))
    1422             :     {
    1423          86 :         if (EQUAL(pszKey, "bands"))
    1424             :         {
    1425          10 :             const CPLStringList aosBands(CSLTokenizeString2(pszValue, ",", 0));
    1426          23 :             for (int j = 0; j < aosBands.size(); j++)
    1427             :             {
    1428          16 :                 if (EQUAL(aosBands[j], "mask"))
    1429             :                 {
    1430           1 :                     anBands.push_back(0);
    1431             :                 }
    1432             :                 else
    1433             :                 {
    1434          15 :                     const int nBand = atoi(aosBands[j]);
    1435          15 :                     if (nBand <= 0 || nBand > poSrcDS->GetRasterCount())
    1436             :                     {
    1437           3 :                         CPLError(CE_Failure, CPLE_IllegalArg,
    1438             :                                  "Invalid band number: %s", aosBands[j]);
    1439           3 :                         return nullptr;
    1440             :                     }
    1441          12 :                     anBands.push_back(nBand);
    1442             :                 }
    1443             :             }
    1444             : 
    1445          20 :             for (const int nBand : anBands)
    1446             :             {
    1447          13 :                 argv.AddString("-b");
    1448          13 :                 argv.AddString(nBand == 0 ? "mask" : CPLSPrintf("%d", nBand));
    1449             :             }
    1450             :         }
    1451             : 
    1452          76 :         else if (EQUAL(pszKey, "a_nodata"))
    1453             :         {
    1454           1 :             argv.AddString("-a_nodata");
    1455           1 :             argv.AddString(pszValue);
    1456             :         }
    1457             : 
    1458          75 :         else if (EQUAL(pszKey, "a_srs"))
    1459             :         {
    1460           1 :             argv.AddString("-a_srs");
    1461           1 :             argv.AddString(pszValue);
    1462             :         }
    1463             : 
    1464          74 :         else if (EQUAL(pszKey, "a_ullr"))
    1465             :         {
    1466             :             // Parse the limits
    1467           1 :             const CPLStringList aosUllr(CSLTokenizeString2(pszValue, ",", 0));
    1468             :             // fail if not four values
    1469           1 :             if (aosUllr.size() != 4)
    1470             :             {
    1471           0 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1472             :                          "Invalid a_ullr option: %s", pszValue);
    1473           0 :                 return nullptr;
    1474             :             }
    1475             : 
    1476           1 :             argv.AddString("-a_ullr");
    1477           1 :             argv.AddString(aosUllr[0]);
    1478           1 :             argv.AddString(aosUllr[1]);
    1479           1 :             argv.AddString(aosUllr[2]);
    1480           1 :             argv.AddString(aosUllr[3]);
    1481             :         }
    1482             : 
    1483          73 :         else if (EQUAL(pszKey, "ovr"))
    1484             :         {
    1485           1 :             argv.AddString("-ovr");
    1486           1 :             argv.AddString(pszValue);
    1487             :         }
    1488          72 :         else if (EQUAL(pszKey, "expand"))
    1489             :         {
    1490           1 :             argv.AddString("-expand");
    1491           1 :             argv.AddString(pszValue);
    1492             :         }
    1493          71 :         else if (EQUAL(pszKey, "a_scale"))
    1494             :         {
    1495           2 :             argv.AddString("-a_scale");
    1496           2 :             argv.AddString(pszValue);
    1497             :         }
    1498          69 :         else if (EQUAL(pszKey, "a_offset"))
    1499             :         {
    1500           1 :             argv.AddString("-a_offset");
    1501           1 :             argv.AddString(pszValue);
    1502             :         }
    1503          68 :         else if (EQUAL(pszKey, "ot"))
    1504             :         {
    1505           2 :             argv.AddString("-ot");
    1506           2 :             argv.AddString(pszValue);
    1507             :         }
    1508          66 :         else if (EQUAL(pszKey, "gcp"))
    1509             :         {
    1510           6 :             const CPLStringList aosGCP(CSLTokenizeString2(pszValue, ",", 0));
    1511             : 
    1512           6 :             if (aosGCP.size() < 4 || aosGCP.size() > 5)
    1513             :             {
    1514           1 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1515             :                          "Invalid value for GCP: %s\n  need 4, or 5 "
    1516             :                          "numbers, comma separated: "
    1517             :                          "'gcp=<pixel>,<line>,<easting>,<northing>[,<"
    1518             :                          "elevation>]'",
    1519             :                          pszValue);
    1520           1 :                 return nullptr;
    1521             :             }
    1522           5 :             argv.AddString("-gcp");
    1523          28 :             for (int j = 0; j < aosGCP.size(); j++)
    1524             :             {
    1525          23 :                 argv.AddString(aosGCP[j]);
    1526             :             }
    1527             :         }
    1528          60 :         else if (EQUAL(pszKey, "scale") || STARTS_WITH_CI(pszKey, "scale_"))
    1529             :         {
    1530             :             const CPLStringList aosScaleParams(
    1531           8 :                 CSLTokenizeString2(pszValue, ",", 0));
    1532             : 
    1533           8 :             if (!(aosScaleParams.size() == 2) &&
    1534           8 :                 !(aosScaleParams.size() == 4) && !(aosScaleParams.size() == 1))
    1535             :             {
    1536           0 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1537             :                          "Invalid value for scale, (or scale_bn): "
    1538             :                          "%s\n  need 'scale=true', or 2 or 4 "
    1539             :                          "numbers, comma separated: "
    1540             :                          "'scale=src_min,src_max[,dst_min,dst_max]' or "
    1541             :                          "'scale_bn=src_min,src_max[,dst_min,dst_max]'",
    1542             :                          pszValue);
    1543           0 :                 return nullptr;
    1544             :             }
    1545             : 
    1546             :             // -scale because scale=true or scale=min,max or scale=min,max,dstmin,dstmax
    1547           8 :             if (aosScaleParams.size() == 1)
    1548             :             {
    1549             :                 const auto oScaleVal =
    1550           3 :                     cpl::strict_parse<bool>(aosScaleParams[0]);
    1551           3 :                 if (!oScaleVal)
    1552             :                 {
    1553           1 :                     CPLError(CE_Failure, CPLE_AppDefined,
    1554             :                              "Invalid value of scale: %s", aosScaleParams[0]);
    1555           1 :                     return nullptr;
    1556             :                 }
    1557           2 :                 if (oScaleVal.value())
    1558             :                 {
    1559           2 :                     argv.AddString(CPLSPrintf("-%s", pszKey));
    1560             :                 }
    1561             :             }
    1562             :             // add remaining params (length 2 or 4)
    1563           7 :             if (aosScaleParams.size() > 1)
    1564             :             {
    1565           5 :                 argv.AddString(CPLSPrintf("-%s", pszKey));
    1566          21 :                 for (int j = 0; j < aosScaleParams.size(); j++)
    1567             :                 {
    1568          16 :                     argv.AddString(aosScaleParams[j]);
    1569             :                 }
    1570           7 :             }
    1571             :         }
    1572          52 :         else if (EQUAL(pszKey, "exponent") ||
    1573          50 :                  STARTS_WITH_CI(pszKey, "exponent_"))
    1574             :         {
    1575           3 :             argv.AddString(CPLSPrintf("-%s", pszKey));
    1576           3 :             argv.AddString(pszValue);
    1577             :         }
    1578          49 :         else if (EQUAL(pszKey, "outsize"))
    1579             :         {
    1580             :             const CPLStringList aosOutSize(
    1581           4 :                 CSLTokenizeString2(pszValue, ",", 0));
    1582           4 :             if (aosOutSize.size() != 2)
    1583             :             {
    1584           1 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1585             :                          "Invalid outsize option: %s, must be two"
    1586             :                          "values separated by comma pixel,line or two "
    1587             :                          "fraction values with percent symbol",
    1588             :                          pszValue);
    1589           1 :                 return nullptr;
    1590             :             }
    1591           3 :             argv.AddString("-outsize");
    1592           3 :             argv.AddString(aosOutSize[0]);
    1593           3 :             argv.AddString(aosOutSize[1]);
    1594             :         }
    1595          45 :         else if (EQUAL(pszKey, "projwin"))
    1596             :         {
    1597             :             // Parse the limits
    1598             :             const CPLStringList aosProjWin(
    1599           3 :                 CSLTokenizeString2(pszValue, ",", 0));
    1600             :             // fail if not four values
    1601           3 :             if (aosProjWin.size() != 4)
    1602             :             {
    1603           1 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1604             :                          "Invalid projwin option: %s", pszValue);
    1605           1 :                 return nullptr;
    1606             :             }
    1607             : 
    1608           2 :             argv.AddString("-projwin");
    1609           2 :             argv.AddString(aosProjWin[0]);
    1610           2 :             argv.AddString(aosProjWin[1]);
    1611           2 :             argv.AddString(aosProjWin[2]);
    1612           2 :             argv.AddString(aosProjWin[3]);
    1613             :         }
    1614          42 :         else if (EQUAL(pszKey, "projwin_srs"))
    1615             :         {
    1616           2 :             argv.AddString("-projwin_srs");
    1617           2 :             argv.AddString(pszValue);
    1618             :         }
    1619          40 :         else if (EQUAL(pszKey, "tr"))
    1620             :         {
    1621             :             const CPLStringList aosTargetResolution(
    1622           3 :                 CSLTokenizeString2(pszValue, ",", 0));
    1623           3 :             if (aosTargetResolution.size() != 2)
    1624             :             {
    1625           1 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1626             :                          "Invalid tr option: %s, must be two "
    1627             :                          "values separated by comma xres,yres",
    1628             :                          pszValue);
    1629           1 :                 return nullptr;
    1630             :             }
    1631           2 :             argv.AddString("-tr");
    1632           2 :             argv.AddString(aosTargetResolution[0]);
    1633           2 :             argv.AddString(aosTargetResolution[1]);
    1634             :         }
    1635          37 :         else if (EQUAL(pszKey, "r"))
    1636             :         {
    1637           1 :             argv.AddString("-r");
    1638           1 :             argv.AddString(pszValue);
    1639             :         }
    1640             : 
    1641          36 :         else if (EQUAL(pszKey, "srcwin"))
    1642             :         {
    1643             :             // Parse the limits
    1644           8 :             const CPLStringList aosSrcWin(CSLTokenizeString2(pszValue, ",", 0));
    1645             :             // fail if not four values
    1646           8 :             if (aosSrcWin.size() != 4)
    1647             :             {
    1648           1 :                 CPLError(CE_Failure, CPLE_IllegalArg,
    1649             :                          "Invalid srcwin option: %s, must be four "
    1650             :                          "values separated by comma xoff,yoff,xsize,ysize",
    1651             :                          pszValue);
    1652           1 :                 return nullptr;
    1653             :             }
    1654             : 
    1655           7 :             argv.AddString("-srcwin");
    1656           7 :             argv.AddString(aosSrcWin[0]);
    1657           7 :             argv.AddString(aosSrcWin[1]);
    1658           7 :             argv.AddString(aosSrcWin[2]);
    1659           7 :             argv.AddString(aosSrcWin[3]);
    1660             :         }
    1661             : 
    1662          28 :         else if (EQUAL(pszKey, "a_gt"))
    1663             :         {
    1664             :             // Parse the limits
    1665             :             const CPLStringList aosAGeoTransform(
    1666           2 :                 CSLTokenizeString2(pszValue, ",", 0));
    1667             :             // fail if not six values
    1668           2 :             if (aosAGeoTransform.size() != 6)
    1669             :             {
    1670           1 :                 CPLError(CE_Failure, CPLE_IllegalArg, "Invalid a_gt option: %s",
    1671             :                          pszValue);
    1672           1 :                 return nullptr;
    1673             :             }
    1674             : 
    1675           1 :             argv.AddString("-a_gt");
    1676           1 :             argv.AddString(aosAGeoTransform[0]);
    1677           1 :             argv.AddString(aosAGeoTransform[1]);
    1678           1 :             argv.AddString(aosAGeoTransform[2]);
    1679           1 :             argv.AddString(aosAGeoTransform[3]);
    1680           1 :             argv.AddString(aosAGeoTransform[4]);
    1681           1 :             argv.AddString(aosAGeoTransform[5]);
    1682             :         }
    1683          26 :         else if (EQUAL(pszKey, "oo"))
    1684             :         {
    1685             :             // do nothing, we passed this in earlier
    1686             :         }
    1687          25 :         else if (EQUAL(pszKey, "if"))
    1688             :         {
    1689             :             // do nothing, we passed this in earlier
    1690             :         }
    1691          24 :         else if (EQUAL(pszKey, "sd_name"))
    1692             :         {
    1693             :             // do nothing, we passed this in earlier
    1694             :         }
    1695          22 :         else if (EQUAL(pszKey, "sd"))
    1696             :         {
    1697             :             // do nothing, we passed this in earlier
    1698             :         }
    1699          21 :         else if (EQUAL(pszKey, "transpose"))
    1700             :         {
    1701             :             // do nothing, we passed this in earlier
    1702             :         }
    1703          19 :         else if (EQUAL(pszKey, "block"))
    1704             :         {
    1705             :             // do nothing, we passed this in earlier
    1706             :         }
    1707          12 :         else if (EQUAL(pszKey, "unscale"))
    1708             :         {
    1709           1 :             const auto oVal = cpl::strict_parse<bool>(pszValue);
    1710           1 :             if (!oVal.has_value())
    1711             :             {
    1712           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1713             :                          "Invalid value for unscale: %s", pszValue);
    1714           0 :                 return nullptr;
    1715             :             }
    1716           1 :             if (oVal.value())
    1717             :             {
    1718           1 :                 argv.AddString("-unscale");
    1719             :             }
    1720             :         }
    1721          11 :         else if (EQUAL(pszKey, "a_coord_epoch"))
    1722             :         {
    1723           0 :             argv.AddString("-a_coord_epoch");
    1724           0 :             argv.AddString(pszValue);
    1725             :         }
    1726          11 :         else if (EQUAL(pszKey, "nogcp"))
    1727             :         {
    1728           2 :             const auto oVal = cpl::strict_parse<bool>(pszValue);
    1729           2 :             if (!oVal.has_value())
    1730             :             {
    1731           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1732             :                          "Invalid value for nogcp: %s", pszValue);
    1733           1 :                 return nullptr;
    1734             :             }
    1735           1 :             if (oVal.value())
    1736             :             {
    1737           1 :                 argv.AddString("-nogcp");
    1738             :             }
    1739             :         }
    1740           9 :         else if (EQUAL(pszKey, "epo"))
    1741             :         {
    1742           4 :             const auto oVal = cpl::strict_parse<bool>(pszValue);
    1743           4 :             if (!oVal.has_value())
    1744             :             {
    1745           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1746             :                          "Invalid value for epo: %s", pszValue);
    1747           1 :                 return nullptr;
    1748             :             }
    1749           3 :             if (oVal.value())
    1750             :             {
    1751           2 :                 argv.AddString("-epo");
    1752             :             }
    1753             :         }
    1754           5 :         else if (EQUAL(pszKey, "eco"))
    1755             :         {
    1756           4 :             const auto oVal = cpl::strict_parse<bool>(pszValue);
    1757           4 :             if (!oVal.has_value())
    1758             :             {
    1759           1 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1760             :                          "Invalid value for eco: %s", pszValue);
    1761           1 :                 return nullptr;
    1762             :             }
    1763           3 :             if (oVal.value())
    1764             :             {
    1765           3 :                 argv.AddString("-eco");
    1766             :             }
    1767             :         }
    1768             : 
    1769             :         else
    1770             :         {
    1771           1 :             CPLError(CE_Failure, CPLE_NotSupported, "Unknown option: %s",
    1772             :                      pszKey);
    1773           1 :             return nullptr;
    1774             :         }
    1775             :     }
    1776             : 
    1777             :     GDALTranslateOptions *psOptions =
    1778          62 :         GDALTranslateOptionsNew(argv.List(), nullptr);
    1779             : 
    1780          62 :     auto hRet = GDALTranslate("", GDALDataset::ToHandle(poSrcDS.get()),
    1781             :                               psOptions, nullptr);
    1782             : 
    1783          62 :     GDALTranslateOptionsFree(psOptions);
    1784             : 
    1785             :     // Situation where we open a http://.jp2 file with the JP2OpenJPEG driver
    1786             :     // through the HTTP driver, which returns a /vsimem/ file
    1787             :     const bool bPatchSourceFilename =
    1788          62 :         (STARTS_WITH(osFilename.c_str(), "http://") ||
    1789          63 :          STARTS_WITH(osFilename.c_str(), "https://")) &&
    1790           1 :         osFilename != poSrcDS->GetDescription();
    1791             : 
    1792          62 :     poSrcDS.reset();
    1793             : 
    1794          62 :     auto poDS = dynamic_cast<VRTDataset *>(GDALDataset::FromHandle(hRet));
    1795          62 :     if (poDS)
    1796             :     {
    1797          59 :         if (bPatchSourceFilename)
    1798             :         {
    1799           2 :             for (int i = 0; i < poDS->nBands; ++i)
    1800             :             {
    1801             :                 auto poBand =
    1802           1 :                     dynamic_cast<VRTSourcedRasterBand *>(poDS->papoBands[i]);
    1803           2 :                 if (poBand && poBand->m_papoSources.size() == 1 &&
    1804           1 :                     poBand->m_papoSources[0]->IsSimpleSource())
    1805             :                 {
    1806           1 :                     auto poSource = cpl::down_cast<VRTSimpleSource *>(
    1807           1 :                         poBand->m_papoSources[0].get());
    1808           1 :                     poSource->m_bRelativeToVRTOri = 0;
    1809           1 :                     poSource->m_osSourceFileNameOri = osFilename;
    1810             :                 }
    1811             :             }
    1812             :         }
    1813          59 :         poDS->SetDescription(pszSpec);
    1814          59 :         poDS->SetWritable(false);
    1815             :     }
    1816          62 :     return poDS;
    1817             : }
    1818             : 
    1819             : /************************************************************************/
    1820             : /*                              OpenXML()                               */
    1821             : /*                                                                      */
    1822             : /*      Create an open VRTDataset from a supplied XML representation    */
    1823             : /*      of the dataset.                                                 */
    1824             : /************************************************************************/
    1825             : 
    1826        2627 : std::unique_ptr<VRTDataset> VRTDataset::OpenXML(const char *pszXML,
    1827             :                                                 const char *pszVRTPath,
    1828             :                                                 GDALAccess eAccessIn)
    1829             : 
    1830             : {
    1831             :     /* -------------------------------------------------------------------- */
    1832             :     /*      Parse the XML.                                                  */
    1833             :     /* -------------------------------------------------------------------- */
    1834        5254 :     CPLXMLTreeCloser psTree(CPLParseXMLString(pszXML));
    1835        2627 :     if (psTree == nullptr)
    1836           0 :         return nullptr;
    1837             : 
    1838        2627 :     CPLXMLNode *psRoot = CPLGetXMLNode(psTree.get(), "=VRTDataset");
    1839        2627 :     if (psRoot == nullptr)
    1840             :     {
    1841           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Missing VRTDataset element.");
    1842           0 :         return nullptr;
    1843             :     }
    1844             : 
    1845        2627 :     const char *pszSubClass = CPLGetXMLValue(psRoot, "subClass", "");
    1846             : 
    1847        2627 :     const bool bIsPansharpened =
    1848        2627 :         strcmp(pszSubClass, "VRTPansharpenedDataset") == 0;
    1849        2627 :     const bool bIsProcessed = strcmp(pszSubClass, "VRTProcessedDataset") == 0;
    1850             : 
    1851        2550 :     if (!bIsPansharpened && !bIsProcessed &&
    1852        7368 :         CPLGetXMLNode(psRoot, "Group") == nullptr &&
    1853        2191 :         (CPLGetXMLNode(psRoot, "rasterXSize") == nullptr ||
    1854        2190 :          CPLGetXMLNode(psRoot, "rasterYSize") == nullptr ||
    1855        2190 :          CPLGetXMLNode(psRoot, "VRTRasterBand") == nullptr))
    1856             :     {
    1857           2 :         CPLError(CE_Failure, CPLE_AppDefined,
    1858             :                  "Missing one of rasterXSize, rasterYSize or bands on"
    1859             :                  " VRTDataset.");
    1860           2 :         return nullptr;
    1861             :     }
    1862             : 
    1863             :     /* -------------------------------------------------------------------- */
    1864             :     /*      Create the new virtual dataset object.                          */
    1865             :     /* -------------------------------------------------------------------- */
    1866        2625 :     const int nXSize = atoi(CPLGetXMLValue(psRoot, "rasterXSize", "0"));
    1867        2625 :     const int nYSize = atoi(CPLGetXMLValue(psRoot, "rasterYSize", "0"));
    1868             : 
    1869        2548 :     if (!bIsPansharpened && !bIsProcessed &&
    1870        7362 :         CPLGetXMLNode(psRoot, "VRTRasterBand") != nullptr &&
    1871        2189 :         !GDALCheckDatasetDimensions(nXSize, nYSize))
    1872             :     {
    1873           0 :         return nullptr;
    1874             :     }
    1875             : 
    1876        2625 :     std::unique_ptr<VRTDataset> poDS;
    1877        2625 :     if (strcmp(pszSubClass, "VRTWarpedDataset") == 0)
    1878         149 :         poDS = std::make_unique<VRTWarpedDataset>(nXSize, nYSize);
    1879        2476 :     else if (bIsPansharpened)
    1880          77 :         poDS = std::make_unique<VRTPansharpenedDataset>(nXSize, nYSize);
    1881        2399 :     else if (bIsProcessed)
    1882         101 :         poDS = std::make_unique<VRTProcessedDataset>(nXSize, nYSize);
    1883             :     else
    1884             :     {
    1885        2298 :         poDS = std::make_unique<VRTDataset>(nXSize, nYSize);
    1886        2298 :         poDS->eAccess = eAccessIn;
    1887             :     }
    1888             : 
    1889        2625 :     if (poDS->XMLInit(psRoot, pszVRTPath) != CE_None)
    1890             :     {
    1891         139 :         poDS.reset();
    1892             :     }
    1893             : 
    1894             :     /* -------------------------------------------------------------------- */
    1895             :     /*      Try to return a regular handle on the file.                     */
    1896             :     /* -------------------------------------------------------------------- */
    1897             : 
    1898        2625 :     return poDS;
    1899             : }
    1900             : 
    1901             : /************************************************************************/
    1902             : /*                              AddBand()                               */
    1903             : /************************************************************************/
    1904             : 
    1905      139026 : CPLErr VRTDataset::AddBand(GDALDataType eType, CSLConstList papszOptions)
    1906             : 
    1907             : {
    1908      139026 :     if (eType == GDT_Unknown || eType == GDT_TypeCount)
    1909             :     {
    1910           1 :         ReportError(CE_Failure, CPLE_IllegalArg,
    1911             :                     "Illegal GDT_Unknown/GDT_TypeCount argument");
    1912           1 :         return CE_Failure;
    1913             :     }
    1914             : 
    1915      139025 :     SetNeedsFlush();
    1916             : 
    1917             :     /* ==================================================================== */
    1918             :     /*      Handle a new raw band.                                          */
    1919             :     /* ==================================================================== */
    1920      139025 :     const char *pszSubClass = CSLFetchNameValue(papszOptions, "subclass");
    1921             : 
    1922      139025 :     if (pszSubClass != nullptr && EQUAL(pszSubClass, "VRTRawRasterBand"))
    1923             :     {
    1924             : #ifdef GDAL_VRT_ENABLE_RAWRASTERBAND
    1925           7 :         if (!VRTDataset::IsRawRasterBandEnabled())
    1926             :         {
    1927           1 :             return CE_Failure;
    1928             :         }
    1929           6 :         const int nWordDataSize = GDALGetDataTypeSizeBytes(eType);
    1930             : 
    1931             :         /* ---------------------------------------------------------------- */
    1932             :         /*      Collect required information.                               */
    1933             :         /* ---------------------------------------------------------------- */
    1934             :         const char *pszImageOffset =
    1935           6 :             CSLFetchNameValueDef(papszOptions, "ImageOffset", "0");
    1936          12 :         vsi_l_offset nImageOffset = CPLScanUIntBig(
    1937           6 :             pszImageOffset, static_cast<int>(strlen(pszImageOffset)));
    1938             : 
    1939           6 :         int nPixelOffset = nWordDataSize;
    1940             :         const char *pszPixelOffset =
    1941           6 :             CSLFetchNameValue(papszOptions, "PixelOffset");
    1942           6 :         if (pszPixelOffset != nullptr)
    1943           4 :             nPixelOffset = atoi(pszPixelOffset);
    1944             : 
    1945             :         int nLineOffset;
    1946             :         const char *pszLineOffset =
    1947           6 :             CSLFetchNameValue(papszOptions, "LineOffset");
    1948           6 :         if (pszLineOffset != nullptr)
    1949           4 :             nLineOffset = atoi(pszLineOffset);
    1950             :         else
    1951             :         {
    1952           4 :             if (nPixelOffset > INT_MAX / GetRasterXSize() ||
    1953           2 :                 nPixelOffset < INT_MIN / GetRasterXSize())
    1954             :             {
    1955           0 :                 CPLError(CE_Failure, CPLE_AppDefined, "Int overflow");
    1956           0 :                 return CE_Failure;
    1957             :             }
    1958           2 :             nLineOffset = nPixelOffset * GetRasterXSize();
    1959             :         }
    1960             : 
    1961           6 :         const char *pszByteOrder = CSLFetchNameValue(papszOptions, "ByteOrder");
    1962             : 
    1963             :         const char *pszFilename =
    1964           6 :             CSLFetchNameValue(papszOptions, "SourceFilename");
    1965           6 :         if (pszFilename == nullptr)
    1966             :         {
    1967           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    1968             :                      "AddBand() requires a SourceFilename option for "
    1969             :                      "VRTRawRasterBands.");
    1970           0 :             return CE_Failure;
    1971             :         }
    1972             : 
    1973             :         const bool bRelativeToVRT =
    1974           6 :             CPLFetchBool(papszOptions, "relativeToVRT", false);
    1975             : 
    1976             :         /* --------------------------------------------------------------- */
    1977             :         /*      Create and initialize the band.                            */
    1978             :         /* --------------------------------------------------------------- */
    1979             : 
    1980             :         auto poBand = std::make_unique<VRTRawRasterBand>(
    1981          12 :             this, GetRasterCount() + 1, eType);
    1982             : 
    1983           6 :         const std::string osPath = CPLGetPathSafe(GetDescription());
    1984          18 :         const CPLErr eErr = poBand->SetRawLink(
    1985          12 :             pszFilename, osPath.empty() ? nullptr : osPath.c_str(),
    1986             :             bRelativeToVRT, nImageOffset, nPixelOffset, nLineOffset,
    1987             :             pszByteOrder);
    1988           6 :         if (eErr == CE_None)
    1989           6 :             SetBand(GetRasterCount() + 1, std::move(poBand));
    1990             : 
    1991           6 :         return eErr;
    1992             : #else
    1993             :         CPLError(CE_Failure, CPLE_NotSupported,
    1994             :                  "VRTDataset::AddBand(): cannot instantiate VRTRawRasterBand, "
    1995             :                  "because disabled in this GDAL build");
    1996             :         return CE_Failure;
    1997             : #endif
    1998             :     }
    1999             : 
    2000             :     /* ==================================================================== */
    2001             :     /*      Handle a new "sourced" band.                                    */
    2002             :     /* ==================================================================== */
    2003             :     else
    2004             :     {
    2005      139018 :         VRTSourcedRasterBand *poBand = nullptr;
    2006             : 
    2007             :         int nBlockXSizeIn =
    2008      139018 :             atoi(CSLFetchNameValueDef(papszOptions, "BLOCKXSIZE", "0"));
    2009             :         int nBlockYSizeIn =
    2010      139018 :             atoi(CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", "0"));
    2011      139018 :         if (nBlockXSizeIn == 0 && nBlockYSizeIn == 0)
    2012             :         {
    2013       71634 :             nBlockXSizeIn = m_nBlockXSize;
    2014       71634 :             nBlockYSizeIn = m_nBlockYSize;
    2015             :         }
    2016             : 
    2017             :         /* ---- Check for our sourced band 'derived' subclass ---- */
    2018      139018 :         if (pszSubClass != nullptr &&
    2019         501 :             EQUAL(pszSubClass, "VRTDerivedRasterBand"))
    2020             :         {
    2021             : 
    2022             :             /* We'll need a pointer to the subclass in case we need */
    2023             :             /* to set the new band's pixel function below. */
    2024             :             VRTDerivedRasterBand *poDerivedBand = new VRTDerivedRasterBand(
    2025         481 :                 this, GetRasterCount() + 1, eType, GetRasterXSize(),
    2026         481 :                 GetRasterYSize(), nBlockXSizeIn, nBlockYSizeIn);
    2027             : 
    2028             :             /* Set the pixel function options it provided. */
    2029             :             const char *pszFuncName =
    2030         481 :                 CSLFetchNameValue(papszOptions, "PixelFunctionType");
    2031         481 :             if (pszFuncName != nullptr)
    2032         318 :                 poDerivedBand->SetPixelFunctionName(pszFuncName);
    2033             : 
    2034             :             const char *pszLanguage =
    2035         481 :                 CSLFetchNameValue(papszOptions, "PixelFunctionLanguage");
    2036         481 :             if (pszLanguage != nullptr)
    2037           1 :                 poDerivedBand->SetPixelFunctionLanguage(pszLanguage);
    2038             : 
    2039             :             const char *pszSkipNonContributingSources =
    2040         481 :                 CSLFetchNameValue(papszOptions, "SkipNonContributingSources");
    2041         481 :             if (pszSkipNonContributingSources != nullptr)
    2042             :             {
    2043           5 :                 poDerivedBand->SetSkipNonContributingSources(
    2044           5 :                     CPLTestBool(pszSkipNonContributingSources));
    2045             :             }
    2046        2754 :             for (const auto &[pszKey, pszValue] :
    2047        3235 :                  cpl::IterateNameValue(static_cast<CSLConstList>(papszOptions)))
    2048             :             {
    2049        1377 :                 if (STARTS_WITH(pszKey, "_PIXELFN_ARG_"))
    2050             :                 {
    2051         565 :                     poDerivedBand->AddPixelFunctionArgument(pszKey + 13,
    2052             :                                                             pszValue);
    2053             :                 }
    2054             :             }
    2055             : 
    2056             :             const char *pszTransferTypeName =
    2057         481 :                 CSLFetchNameValue(papszOptions, "SourceTransferType");
    2058         481 :             if (pszTransferTypeName != nullptr)
    2059             :             {
    2060             :                 const GDALDataType eTransferType =
    2061           7 :                     GDALGetDataTypeByName(pszTransferTypeName);
    2062           7 :                 if (eTransferType == GDT_Unknown)
    2063             :                 {
    2064           1 :                     CPLError(CE_Failure, CPLE_AppDefined,
    2065             :                              "invalid SourceTransferType: \"%s\".",
    2066             :                              pszTransferTypeName);
    2067           1 :                     delete poDerivedBand;
    2068           1 :                     return CE_Failure;
    2069             :                 }
    2070           6 :                 poDerivedBand->SetSourceTransferType(eTransferType);
    2071             :             }
    2072             : 
    2073             :             /* We're done with the derived band specific stuff, so */
    2074             :             /* we can assign the base class pointer now. */
    2075         480 :             poBand = poDerivedBand;
    2076             :         }
    2077             :         else
    2078             :         {
    2079             :             /* ---- Standard sourced band ---- */
    2080      138537 :             poBand = new VRTSourcedRasterBand(
    2081      138537 :                 this, GetRasterCount() + 1, eType, GetRasterXSize(),
    2082      138537 :                 GetRasterYSize(), nBlockXSizeIn, nBlockYSizeIn);
    2083             :         }
    2084             : 
    2085      139017 :         SetBand(GetRasterCount() + 1, poBand);
    2086             : 
    2087      295747 :         for (int i = 0; papszOptions != nullptr && papszOptions[i] != nullptr;
    2088             :              i++)
    2089             :         {
    2090      156730 :             if (STARTS_WITH_CI(papszOptions[i], "AddFuncSource="))
    2091             :             {
    2092           0 :                 char **papszTokens = CSLTokenizeStringComplex(
    2093           0 :                     papszOptions[i] + 14, ",", TRUE, FALSE);
    2094           0 :                 if (CSLCount(papszTokens) < 1)
    2095             :                 {
    2096           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    2097             :                              "AddFuncSource(): required argument missing.");
    2098             :                     // TODO: How should this error be handled?  Return
    2099             :                     // CE_Failure?
    2100             :                 }
    2101             : 
    2102           0 :                 VRTImageReadFunc pfnReadFunc = nullptr;
    2103           0 :                 sscanf(papszTokens[0], "%p", &pfnReadFunc);
    2104             : 
    2105           0 :                 void *pCBData = nullptr;
    2106           0 :                 if (CSLCount(papszTokens) > 1)
    2107           0 :                     sscanf(papszTokens[1], "%p", &pCBData);
    2108             : 
    2109           0 :                 const double dfNoDataValue = (CSLCount(papszTokens) > 2)
    2110           0 :                                                  ? CPLAtof(papszTokens[2])
    2111           0 :                                                  : VRT_NODATA_UNSET;
    2112             : 
    2113           0 :                 poBand->AddFuncSource(pfnReadFunc, pCBData, dfNoDataValue);
    2114             : 
    2115           0 :                 CSLDestroy(papszTokens);
    2116             :             }
    2117             :         }
    2118             : 
    2119      139017 :         return CE_None;
    2120             :     }
    2121             : }
    2122             : 
    2123             : /*! @endcond */
    2124             : /************************************************************************/
    2125             : /*                             VRTAddBand()                             */
    2126             : /************************************************************************/
    2127             : 
    2128             : /**
    2129             :  * @see VRTDataset::VRTAddBand().
    2130             :  *
    2131             :  * @note The return type of this function is int, but the actual values
    2132             :  * returned are of type CPLErr.
    2133             :  */
    2134             : 
    2135         960 : int CPL_STDCALL VRTAddBand(VRTDatasetH hDataset, GDALDataType eType,
    2136             :                            CSLConstList papszOptions)
    2137             : 
    2138             : {
    2139         960 :     VALIDATE_POINTER1(hDataset, "VRTAddBand", 0);
    2140             : 
    2141         960 :     return static_cast<VRTDataset *>(GDALDataset::FromHandle(hDataset))
    2142         960 :         ->AddBand(eType, papszOptions);
    2143             : }
    2144             : 
    2145             : /*! @cond Doxygen_Suppress */
    2146             : 
    2147             : /************************************************************************/
    2148             : /*                               Create()                               */
    2149             : /************************************************************************/
    2150             : 
    2151         234 : GDALDataset *VRTDataset::Create(const char *pszName, int nXSize, int nYSize,
    2152             :                                 int nBandsIn, GDALDataType eType,
    2153             :                                 CSLConstList papszOptions)
    2154             : 
    2155             : {
    2156         468 :     return CreateVRTDataset(pszName, nXSize, nYSize, nBandsIn, eType,
    2157             :                             const_cast<CSLConstList>(papszOptions))
    2158         234 :         .release();
    2159             : }
    2160             : 
    2161             : /************************************************************************/
    2162             : /*                          CreateVRTDataset()                          */
    2163             : /************************************************************************/
    2164             : 
    2165             : std::unique_ptr<VRTDataset>
    2166         793 : VRTDataset::CreateVRTDataset(const char *pszName, int nXSize, int nYSize,
    2167             :                              int nBandsIn, GDALDataType eType,
    2168             :                              CSLConstList papszOptions)
    2169             : 
    2170             : {
    2171         793 :     if (STARTS_WITH_CI(pszName, "<VRTDataset"))
    2172             :     {
    2173           0 :         auto poDS = OpenXML(pszName, nullptr, GA_Update);
    2174           0 :         if (poDS != nullptr)
    2175           0 :             poDS->SetDescription("<FromXML>");
    2176           0 :         return poDS;
    2177             :     }
    2178             : 
    2179         793 :     const char *pszSubclass = CSLFetchNameValue(papszOptions, "SUBCLASS");
    2180             : 
    2181         793 :     std::unique_ptr<VRTDataset> poDS;
    2182             : 
    2183             :     const int nBlockXSize =
    2184         793 :         atoi(CSLFetchNameValueDef(papszOptions, "BLOCKXSIZE", "0"));
    2185             :     const int nBlockYSize =
    2186         793 :         atoi(CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", "0"));
    2187         793 :     if (pszSubclass == nullptr || EQUAL(pszSubclass, "VRTDataset"))
    2188        1220 :         poDS = std::make_unique<VRTDataset>(nXSize, nYSize, nBlockXSize,
    2189         610 :                                             nBlockYSize);
    2190         183 :     else if (EQUAL(pszSubclass, "VRTWarpedDataset"))
    2191             :     {
    2192         366 :         poDS = std::make_unique<VRTWarpedDataset>(nXSize, nYSize, nBlockXSize,
    2193         183 :                                                   nBlockYSize);
    2194             :     }
    2195             :     else
    2196             :     {
    2197           0 :         CPLError(CE_Failure, CPLE_AppDefined, "SUBCLASS=%s not recognised.",
    2198             :                  pszSubclass);
    2199           0 :         return nullptr;
    2200             :     }
    2201         793 :     poDS->eAccess = GA_Update;
    2202             : 
    2203         793 :     poDS->SetDescription(pszName);
    2204             : 
    2205        1197 :     for (int iBand = 0; iBand < nBandsIn; iBand++)
    2206         404 :         poDS->AddBand(eType, nullptr);
    2207             : 
    2208         793 :     poDS->SetNeedsFlush();
    2209             : 
    2210         793 :     poDS->oOvManager.Initialize(poDS.get(), pszName);
    2211             : 
    2212         793 :     return poDS;
    2213             : }
    2214             : 
    2215             : /************************************************************************/
    2216             : /*                     CreateVRTMultiDimensional()                      */
    2217             : /************************************************************************/
    2218             : 
    2219             : std::unique_ptr<VRTDataset>
    2220         128 : VRTDataset::CreateVRTMultiDimensional(const char *pszFilename,
    2221             :                                       CSLConstList /*papszRootGroupOptions*/,
    2222             :                                       CSLConstList /*papszOptions*/)
    2223             : {
    2224         128 :     auto poDS = std::make_unique<VRTDataset>(0, 0);
    2225         128 :     poDS->eAccess = GA_Update;
    2226         128 :     poDS->SetDescription(pszFilename);
    2227         128 :     poDS->m_poRootGroup = VRTGroup::Create(std::string(), "/");
    2228         128 :     poDS->m_poRootGroup->SetIsRootGroup();
    2229         128 :     poDS->m_poRootGroup->SetFilename(pszFilename);
    2230         128 :     poDS->m_poRootGroup->SetDirty();
    2231             : 
    2232         128 :     return poDS;
    2233             : }
    2234             : 
    2235             : /************************************************************************/
    2236             : /*                       CreateMultiDimensional()                       */
    2237             : /************************************************************************/
    2238             : 
    2239             : GDALDataset *
    2240           2 : VRTDataset::CreateMultiDimensional(const char *pszFilename,
    2241             :                                    CSLConstList papszRootGroupOptions,
    2242             :                                    CSLConstList papszOptions)
    2243             : {
    2244           4 :     return CreateVRTMultiDimensional(pszFilename, papszRootGroupOptions,
    2245             :                                      papszOptions)
    2246           2 :         .release();
    2247             : }
    2248             : 
    2249             : /************************************************************************/
    2250             : /*                            GetFileList()                             */
    2251             : /************************************************************************/
    2252             : 
    2253          60 : char **VRTDataset::GetFileList()
    2254             : {
    2255          60 :     char **papszFileList = GDALDataset::GetFileList();
    2256             : 
    2257          60 :     int nSize = CSLCount(papszFileList);
    2258          60 :     int nMaxSize = nSize;
    2259             : 
    2260             :     // Do not need an element deallocator as each string points to an
    2261             :     // element of the papszFileList.
    2262             :     CPLHashSet *hSetFiles =
    2263          60 :         CPLHashSetNew(CPLHashSetHashStr, CPLHashSetEqualStr, nullptr);
    2264             : 
    2265         131 :     for (int iBand = 0; iBand < nBands; iBand++)
    2266             :     {
    2267          71 :         static_cast<VRTRasterBand *>(papoBands[iBand])
    2268          71 :             ->GetFileList(&papszFileList, &nSize, &nMaxSize, hSetFiles);
    2269             :     }
    2270             : 
    2271          60 :     CPLHashSetDestroy(hSetFiles);
    2272             : 
    2273          60 :     return papszFileList;
    2274             : }
    2275             : 
    2276             : /************************************************************************/
    2277             : /*                               Delete()                               */
    2278             : /************************************************************************/
    2279             : 
    2280             : /* We implement Delete() to avoid that the default implementation */
    2281             : /* in GDALDriver::Delete() destroys the source files listed by GetFileList(),*/
    2282             : /* which would be an undesired effect... */
    2283          13 : CPLErr VRTDataset::Delete(const char *pszFilename)
    2284             : {
    2285          13 :     GDALDriverH hDriver = GDALIdentifyDriver(pszFilename, nullptr);
    2286             : 
    2287          13 :     if (!hDriver || !EQUAL(GDALGetDriverShortName(hDriver), "VRT"))
    2288           0 :         return CE_Failure;
    2289             : 
    2290          25 :     if (strstr(pszFilename, "<VRTDataset") == nullptr &&
    2291          12 :         VSIUnlink(pszFilename) != 0)
    2292             :     {
    2293           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Deleting %s failed:\n%s",
    2294           0 :                  pszFilename, VSIStrerror(errno));
    2295           0 :         return CE_Failure;
    2296             :     }
    2297             : 
    2298          13 :     return CE_None;
    2299             : }
    2300             : 
    2301             : /************************************************************************/
    2302             : /*                           CreateMaskBand()                           */
    2303             : /************************************************************************/
    2304             : 
    2305          46 : CPLErr VRTDataset::CreateMaskBand(int)
    2306             : {
    2307          46 :     if (m_poMaskBand != nullptr)
    2308             :     {
    2309           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    2310             :                  "This VRT dataset has already a mask band");
    2311           1 :         return CE_Failure;
    2312             :     }
    2313             : 
    2314          45 :     SetMaskBand(std::make_unique<VRTSourcedRasterBand>(this, 0));
    2315             : 
    2316          45 :     return CE_None;
    2317             : }
    2318             : 
    2319             : /************************************************************************/
    2320             : /*                            SetMaskBand()                             */
    2321             : /************************************************************************/
    2322             : 
    2323          83 : void VRTDataset::SetMaskBand(std::unique_ptr<VRTRasterBand> poMaskBandIn)
    2324             : {
    2325          83 :     m_poMaskBand = std::move(poMaskBandIn);
    2326          83 :     m_poMaskBand->SetIsMaskBand();
    2327          83 : }
    2328             : 
    2329             : /************************************************************************/
    2330             : /*                       CloseDependentDatasets()                       */
    2331             : /************************************************************************/
    2332             : 
    2333         660 : int VRTDataset::CloseDependentDatasets()
    2334             : {
    2335             :     /* We need to call it before removing the sources, otherwise */
    2336             :     /* we would remove them from the serizalized VRT */
    2337         660 :     FlushCache(true);
    2338             : 
    2339         660 :     int bHasDroppedRef = GDALDataset::CloseDependentDatasets();
    2340             : 
    2341        1690 :     for (int iBand = 0; iBand < nBands; iBand++)
    2342             :     {
    2343        2060 :         bHasDroppedRef |= static_cast<VRTRasterBand *>(papoBands[iBand])
    2344        1030 :                               ->CloseDependentDatasets();
    2345             :     }
    2346             : 
    2347         660 :     return bHasDroppedRef;
    2348             : }
    2349             : 
    2350             : /************************************************************************/
    2351             : /*                    CheckCompatibleForDatasetIO()                     */
    2352             : /************************************************************************/
    2353             : 
    2354             : /* We will return TRUE only if all the bands are VRTSourcedRasterBands */
    2355             : /* made of identical sources, that are strictly VRTSimpleSource, and that */
    2356             : /* the band number of each source is the band number of the */
    2357             : /* VRTSourcedRasterBand. */
    2358             : 
    2359       18376 : bool VRTDataset::CheckCompatibleForDatasetIO() const
    2360             : {
    2361       18376 :     size_t nSources = 0;
    2362       18376 :     const std::unique_ptr<VRTSource> *papoSources = nullptr;
    2363       36752 :     CPLString osResampling;
    2364             : 
    2365       18376 :     if (m_nCompatibleForDatasetIO >= 0)
    2366             :     {
    2367       16143 :         return CPL_TO_BOOL(m_nCompatibleForDatasetIO);
    2368             :     }
    2369             : 
    2370        2233 :     m_nCompatibleForDatasetIO = false;
    2371             : 
    2372        2233 :     GDALDataset *poFirstBandSourceDS = nullptr;
    2373        6485 :     for (int iBand = 0; iBand < nBands; iBand++)
    2374             :     {
    2375        4696 :         auto poVRTBand = static_cast<VRTRasterBand *>(papoBands[iBand]);
    2376        4696 :         assert(poVRTBand);
    2377        4696 :         if (!poVRTBand->IsSourcedRasterBand())
    2378          66 :             return false;
    2379             : 
    2380        4630 :         const VRTSourcedRasterBand *poBand =
    2381             :             static_cast<const VRTSourcedRasterBand *>(poVRTBand);
    2382             : 
    2383             :         // Do not allow VRTDerivedRasterBand for example
    2384        4630 :         if (typeid(*poBand) != typeid(VRTSourcedRasterBand))
    2385          75 :             return false;
    2386             : 
    2387        4555 :         if (iBand == 0)
    2388             :         {
    2389        1990 :             nSources = poBand->m_papoSources.size();
    2390        1990 :             papoSources = poBand->m_papoSources.data();
    2391        4110 :             for (auto &poSource : poBand->m_papoSources)
    2392             :             {
    2393        2313 :                 if (!poSource->IsSimpleSource())
    2394         193 :                     return false;
    2395             : 
    2396             :                 const VRTSimpleSource *poSimpleSource =
    2397        2309 :                     static_cast<const VRTSimpleSource *>(poSource.get());
    2398        2309 :                 if (poSimpleSource->GetType() !=
    2399        2309 :                     VRTSimpleSource::GetTypeStatic())
    2400         149 :                     return false;
    2401             : 
    2402        6447 :                 if (poSimpleSource->m_nBand != iBand + 1 ||
    2403        2550 :                     poSimpleSource->m_bGetMaskBand ||
    2404         390 :                     (nSources > 1 && poSimpleSource->m_osSrcDSName.empty()))
    2405             :                 {
    2406          40 :                     return false;
    2407             :                 }
    2408        2120 :                 if (nSources == 1 && poSimpleSource->m_osSrcDSName.empty())
    2409             :                 {
    2410        1021 :                     if (auto poSourceBand = poSimpleSource->GetRasterBand())
    2411             :                     {
    2412        1021 :                         poFirstBandSourceDS = poSourceBand->GetDataset();
    2413             :                     }
    2414             :                     else
    2415             :                     {
    2416           0 :                         return false;
    2417             :                     }
    2418             :                 }
    2419        2120 :                 osResampling = poSimpleSource->GetResampling();
    2420             :             }
    2421             :         }
    2422        2565 :         else if (nSources != poBand->m_papoSources.size())
    2423             :         {
    2424           0 :             return false;
    2425             :         }
    2426             :         else
    2427             :         {
    2428        5715 :             for (size_t iSource = 0; iSource < nSources; iSource++)
    2429             :             {
    2430        3260 :                 if (!poBand->m_papoSources[iSource]->IsSimpleSource())
    2431           0 :                     return false;
    2432             :                 const VRTSimpleSource *poRefSource =
    2433             :                     static_cast<const VRTSimpleSource *>(
    2434        3260 :                         papoSources[iSource].get());
    2435             : 
    2436             :                 const VRTSimpleSource *poSource =
    2437             :                     static_cast<const VRTSimpleSource *>(
    2438        3260 :                         poBand->m_papoSources[iSource].get());
    2439        3260 :                 if (poSource->GetType() != VRTSimpleSource::GetTypeStatic())
    2440          20 :                     return false;
    2441        9630 :                 if (poSource->m_nBand != iBand + 1 ||
    2442        4054 :                     poSource->m_bGetMaskBand ||
    2443         814 :                     (nSources > 1 && poSource->m_osSrcDSName.empty()))
    2444          90 :                     return false;
    2445        3150 :                 if (!poSource->IsSameExceptBandNumber(poRefSource))
    2446           0 :                     return false;
    2447        3150 :                 if (osResampling.compare(poSource->GetResampling()) != 0)
    2448           0 :                     return false;
    2449        3150 :                 if (nSources == 1 && poSource->m_osSrcDSName.empty())
    2450             :                 {
    2451        1986 :                     auto poSourceBand = poSource->GetRasterBand();
    2452        3972 :                     if (!poSourceBand ||
    2453        1986 :                         poFirstBandSourceDS != poSourceBand->GetDataset())
    2454             :                     {
    2455           0 :                         return false;
    2456             :                     }
    2457             :                 }
    2458             :             }
    2459             :         }
    2460             :     }
    2461             : 
    2462        1789 :     m_nCompatibleForDatasetIO = nSources != 0;
    2463        1789 :     return CPL_TO_BOOL(m_nCompatibleForDatasetIO);
    2464             : }
    2465             : 
    2466             : /************************************************************************/
    2467             : /*                         GetSingleSimpleSource()                      */
    2468             : /*                                                                      */
    2469             : /* Returns a non-NULL dataset if the VRT is made of a single source     */
    2470             : /* that is a simple source, in its full extent, and with all of its     */
    2471             : /* bands. Basically something produced by :                             */
    2472             : /*   gdal_translate src dst.vrt -of VRT (-a_srs / -a_ullr)              */
    2473             : /************************************************************************/
    2474             : 
    2475        1276 : GDALDataset *VRTDataset::GetSingleSimpleSource()
    2476             : {
    2477        1276 :     if (!CheckCompatibleForDatasetIO())
    2478         104 :         return nullptr;
    2479             : 
    2480        1172 :     VRTSourcedRasterBand *poVRTBand =
    2481        1172 :         static_cast<VRTSourcedRasterBand *>(papoBands[0]);
    2482        1172 :     if (poVRTBand->m_papoSources.size() != 1)
    2483           1 :         return nullptr;
    2484             : 
    2485             :     VRTSimpleSource *poSource =
    2486        1171 :         static_cast<VRTSimpleSource *>(poVRTBand->m_papoSources[0].get());
    2487             : 
    2488        1171 :     GDALRasterBand *poBand = poSource->GetRasterBand();
    2489        1171 :     if (poBand == nullptr || poSource->GetMaskBandMainBand() != nullptr)
    2490           0 :         return nullptr;
    2491             : 
    2492        1171 :     GDALDataset *poSrcDS = poBand->GetDataset();
    2493        1171 :     if (poSrcDS == nullptr)
    2494           0 :         return nullptr;
    2495             : 
    2496             :     /* Check that it uses the full source dataset */
    2497        1171 :     double dfReqXOff = 0.0;
    2498        1171 :     double dfReqYOff = 0.0;
    2499        1171 :     double dfReqXSize = 0.0;
    2500        1171 :     double dfReqYSize = 0.0;
    2501        1171 :     int nReqXOff = 0;
    2502        1171 :     int nReqYOff = 0;
    2503        1171 :     int nReqXSize = 0;
    2504        1171 :     int nReqYSize = 0;
    2505        1171 :     int nOutXOff = 0;
    2506        1171 :     int nOutYOff = 0;
    2507        1171 :     int nOutXSize = 0;
    2508        1171 :     int nOutYSize = 0;
    2509        1171 :     bool bError = false;
    2510        2342 :     if (!poSource->GetSrcDstWindow(
    2511        1171 :             0, 0, poSrcDS->GetRasterXSize(), poSrcDS->GetRasterYSize(),
    2512             :             poSrcDS->GetRasterXSize(), poSrcDS->GetRasterYSize(),
    2513             :             GRIORA_NearestNeighbour, &dfReqXOff, &dfReqYOff, &dfReqXSize,
    2514             :             &dfReqYSize, &nReqXOff, &nReqYOff, &nReqXSize, &nReqYSize,
    2515             :             &nOutXOff, &nOutYOff, &nOutXSize, &nOutYSize, bError))
    2516           0 :         return nullptr;
    2517             : 
    2518         355 :     if (nReqXOff != 0 || nReqYOff != 0 ||
    2519        1762 :         nReqXSize != poSrcDS->GetRasterXSize() ||
    2520         236 :         nReqYSize != poSrcDS->GetRasterYSize())
    2521         938 :         return nullptr;
    2522             : 
    2523         233 :     if (nOutXOff != 0 || nOutYOff != 0 ||
    2524         669 :         nOutXSize != poSrcDS->GetRasterXSize() ||
    2525         203 :         nOutYSize != poSrcDS->GetRasterYSize())
    2526          30 :         return nullptr;
    2527             : 
    2528         203 :     return poSrcDS;
    2529             : }
    2530             : 
    2531             : /************************************************************************/
    2532             : /*                             AdviseRead()                             */
    2533             : /************************************************************************/
    2534             : 
    2535        3957 : CPLErr VRTDataset::AdviseRead(int nXOff, int nYOff, int nXSize, int nYSize,
    2536             :                               int nBufXSize, int nBufYSize, GDALDataType eDT,
    2537             :                               int nBandCount, int *panBandList,
    2538             :                               CSLConstList papszOptions)
    2539             : {
    2540        3957 :     if (!CheckCompatibleForDatasetIO())
    2541         857 :         return CE_None;
    2542             : 
    2543        3100 :     VRTSourcedRasterBand *poVRTBand =
    2544        3100 :         static_cast<VRTSourcedRasterBand *>(papoBands[0]);
    2545        3100 :     if (poVRTBand->m_papoSources.size() != 1)
    2546          10 :         return CE_None;
    2547             : 
    2548             :     VRTSimpleSource *poSource =
    2549        3090 :         static_cast<VRTSimpleSource *>(poVRTBand->m_papoSources[0].get());
    2550             : 
    2551             :     /* Find source window and buffer size */
    2552        3090 :     double dfReqXOff = 0.0;
    2553        3090 :     double dfReqYOff = 0.0;
    2554        3090 :     double dfReqXSize = 0.0;
    2555        3090 :     double dfReqYSize = 0.0;
    2556        3090 :     int nReqXOff = 0;
    2557        3090 :     int nReqYOff = 0;
    2558        3090 :     int nReqXSize = 0;
    2559        3090 :     int nReqYSize = 0;
    2560        3090 :     int nOutXOff = 0;
    2561        3090 :     int nOutYOff = 0;
    2562        3090 :     int nOutXSize = 0;
    2563        3090 :     int nOutYSize = 0;
    2564        3090 :     bool bError = false;
    2565        3090 :     if (!poSource->GetSrcDstWindow(
    2566             :             nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize,
    2567             :             GRIORA_NearestNeighbour, &dfReqXOff, &dfReqYOff, &dfReqXSize,
    2568             :             &dfReqYSize, &nReqXOff, &nReqYOff, &nReqXSize, &nReqYSize,
    2569             :             &nOutXOff, &nOutYOff, &nOutXSize, &nOutYSize, bError))
    2570             :     {
    2571           2 :         return bError ? CE_Failure : CE_None;
    2572             :     }
    2573             : 
    2574        3088 :     GDALRasterBand *poBand = poSource->GetRasterBand();
    2575        3088 :     if (poBand == nullptr || poSource->GetMaskBandMainBand() != nullptr)
    2576           0 :         return CE_None;
    2577             : 
    2578        3088 :     GDALDataset *poSrcDS = poBand->GetDataset();
    2579        3088 :     if (poSrcDS == nullptr)
    2580           0 :         return CE_None;
    2581             : 
    2582        3088 :     return poSrcDS->AdviseRead(nReqXOff, nReqYOff, nReqXSize, nReqYSize,
    2583             :                                nOutXSize, nOutYSize, eDT, nBandCount,
    2584        3088 :                                panBandList, papszOptions);
    2585             : }
    2586             : 
    2587             : /************************************************************************/
    2588             : /*                           GetNumThreads()                            */
    2589             : /************************************************************************/
    2590             : 
    2591          38 : /* static */ int VRTDataset::GetNumThreads(GDALDataset *poDS)
    2592             : {
    2593          38 :     const char *pszNumThreads = nullptr;
    2594          38 :     if (poDS)
    2595          38 :         pszNumThreads = CSLFetchNameValueDef(poDS->GetOpenOptions(),
    2596             :                                              "NUM_THREADS", nullptr);
    2597          38 :     if (!pszNumThreads)
    2598          38 :         pszNumThreads = CPLGetConfigOption("VRT_NUM_THREADS", nullptr);
    2599          38 :     return GDALGetNumThreads(pszNumThreads, GDALGetMaxDatasetPoolSize(),
    2600          38 :                              /* bDefaultAllCPUs = */ true);
    2601             : }
    2602             : 
    2603             : /************************************************************************/
    2604             : /*                        VRTDatasetRasterIOJob                         */
    2605             : /************************************************************************/
    2606             : 
    2607             : /** Structure used to declare a threaded job to satisfy IRasterIO()
    2608             :  * on a given source.
    2609             :  */
    2610             : struct VRTDatasetRasterIOJob
    2611             : {
    2612             :     std::atomic<int> *pnCompletedJobs = nullptr;
    2613             :     std::atomic<bool> *pbSuccess = nullptr;
    2614             :     CPLErrorAccumulator *poErrorAccumulator = nullptr;
    2615             : 
    2616             :     GDALDataType eVRTBandDataType = GDT_Unknown;
    2617             :     int nXOff = 0;
    2618             :     int nYOff = 0;
    2619             :     int nXSize = 0;
    2620             :     int nYSize = 0;
    2621             :     void *pData = nullptr;
    2622             :     int nBufXSize = 0;
    2623             :     int nBufYSize = 0;
    2624             :     int nBandCount = 0;
    2625             :     BANDMAP_TYPE panBandMap = nullptr;
    2626             :     GDALDataType eBufType = GDT_Unknown;
    2627             :     GSpacing nPixelSpace = 0;
    2628             :     GSpacing nLineSpace = 0;
    2629             :     GSpacing nBandSpace = 0;
    2630             :     GDALRasterIOExtraArg *psExtraArg = nullptr;
    2631             :     VRTSimpleSource *poSource = nullptr;
    2632             : 
    2633             :     static void Func(void *pData);
    2634             : };
    2635             : 
    2636             : /************************************************************************/
    2637             : /*                    VRTDatasetRasterIOJob::Func()                     */
    2638             : /************************************************************************/
    2639             : 
    2640          67 : void VRTDatasetRasterIOJob::Func(void *pData)
    2641             : {
    2642             :     auto psJob = std::unique_ptr<VRTDatasetRasterIOJob>(
    2643         134 :         static_cast<VRTDatasetRasterIOJob *>(pData));
    2644          67 :     if (*psJob->pbSuccess)
    2645             :     {
    2646          67 :         GDALRasterIOExtraArg sArg = *(psJob->psExtraArg);
    2647          67 :         sArg.pfnProgress = nullptr;
    2648          67 :         sArg.pProgressData = nullptr;
    2649             : 
    2650         134 :         auto oAccumulator = psJob->poErrorAccumulator->InstallForCurrentScope();
    2651          67 :         CPL_IGNORE_RET_VAL(oAccumulator);
    2652             : 
    2653         134 :         if (psJob->poSource->DatasetRasterIO(
    2654          67 :                 psJob->eVRTBandDataType, psJob->nXOff, psJob->nYOff,
    2655          67 :                 psJob->nXSize, psJob->nYSize, psJob->pData, psJob->nBufXSize,
    2656          67 :                 psJob->nBufYSize, psJob->eBufType, psJob->nBandCount,
    2657          67 :                 psJob->panBandMap, psJob->nPixelSpace, psJob->nLineSpace,
    2658         134 :                 psJob->nBandSpace, &sArg) != CE_None)
    2659             :         {
    2660           0 :             *psJob->pbSuccess = false;
    2661             :         }
    2662             :     }
    2663             : 
    2664          67 :     ++(*psJob->pnCompletedJobs);
    2665          67 : }
    2666             : 
    2667             : /************************************************************************/
    2668             : /*                             IRasterIO()                              */
    2669             : /************************************************************************/
    2670             : 
    2671       14958 : CPLErr VRTDataset::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
    2672             :                              int nXSize, int nYSize, void *pData, int nBufXSize,
    2673             :                              int nBufYSize, GDALDataType eBufType,
    2674             :                              int nBandCount, BANDMAP_TYPE panBandMap,
    2675             :                              GSpacing nPixelSpace, GSpacing nLineSpace,
    2676             :                              GSpacing nBandSpace,
    2677             :                              GDALRasterIOExtraArg *psExtraArg)
    2678             : {
    2679       14958 :     m_bMultiThreadedRasterIOLastUsed = false;
    2680             : 
    2681       14958 :     if (nBands == 1 && nBandCount == 1)
    2682             :     {
    2683             :         VRTSourcedRasterBand *poBand =
    2684        1869 :             dynamic_cast<VRTSourcedRasterBand *>(papoBands[0]);
    2685        1869 :         if (poBand)
    2686             :         {
    2687        1866 :             return poBand->IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
    2688             :                                      pData, nBufXSize, nBufYSize, eBufType,
    2689        1866 :                                      nPixelSpace, nLineSpace, psExtraArg);
    2690             :         }
    2691             :     }
    2692             : 
    2693       13092 :     bool bLocalCompatibleForDatasetIO = CheckCompatibleForDatasetIO();
    2694       12488 :     if (bLocalCompatibleForDatasetIO && eRWFlag == GF_Read &&
    2695       25580 :         (nBufXSize < nXSize || nBufYSize < nYSize) && m_apoOverviews.empty())
    2696             :     {
    2697           3 :         int bTried = FALSE;
    2698           3 :         const CPLErr eErr = TryOverviewRasterIO(
    2699             :             eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
    2700             :             eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace,
    2701             :             nBandSpace, psExtraArg, &bTried);
    2702             : 
    2703           3 :         if (bTried)
    2704             :         {
    2705           1 :             return eErr;
    2706             :         }
    2707             : 
    2708           9 :         for (int iBand = 0; iBand < nBands; iBand++)
    2709             :         {
    2710           7 :             VRTSourcedRasterBand *poBand =
    2711           7 :                 static_cast<VRTSourcedRasterBand *>(papoBands[iBand]);
    2712             : 
    2713             :             // If there are overviews, let VRTSourcedRasterBand::IRasterIO()
    2714             :             // do the job.
    2715           7 :             if (poBand->GetOverviewCount() != 0)
    2716             :             {
    2717           0 :                 bLocalCompatibleForDatasetIO = false;
    2718           0 :                 break;
    2719             :             }
    2720             :         }
    2721             :     }
    2722             : 
    2723             :     // If resampling with non-nearest neighbour, we need to be careful
    2724             :     // if the VRT band exposes a nodata value, but the sources do not have it.
    2725             :     // To also avoid edge effects on sources when downsampling, use the
    2726             :     // base implementation of IRasterIO() (that is acquiring sources at their
    2727             :     // nominal resolution, and then downsampling), but only if none of the
    2728             :     // contributing sources have overviews.
    2729       13091 :     if (bLocalCompatibleForDatasetIO && eRWFlag == GF_Read &&
    2730       12474 :         (nXSize != nBufXSize || nYSize != nBufYSize) &&
    2731          13 :         psExtraArg->eResampleAlg != GRIORA_NearestNeighbour)
    2732             :     {
    2733           0 :         for (int iBandIndex = 0; iBandIndex < nBandCount; iBandIndex++)
    2734             :         {
    2735             :             VRTSourcedRasterBand *poBand = static_cast<VRTSourcedRasterBand *>(
    2736           0 :                 GetRasterBand(panBandMap[iBandIndex]));
    2737           0 :             if (!poBand->CanIRasterIOBeForwardedToEachSource(
    2738             :                     eRWFlag, nXOff, nYOff, nXSize, nYSize, nBufXSize, nBufYSize,
    2739             :                     psExtraArg))
    2740             :             {
    2741           0 :                 bLocalCompatibleForDatasetIO = false;
    2742           0 :                 break;
    2743             :             }
    2744             :         }
    2745             :     }
    2746             : 
    2747       13091 :     if (bLocalCompatibleForDatasetIO && eRWFlag == GF_Read)
    2748             :     {
    2749       47908 :         for (int iBandIndex = 0; iBandIndex < nBandCount; iBandIndex++)
    2750             :         {
    2751             :             VRTSourcedRasterBand *poBand = static_cast<VRTSourcedRasterBand *>(
    2752       35421 :                 GetRasterBand(panBandMap[iBandIndex]));
    2753             : 
    2754             :             /* Dirty little trick to initialize the buffer without doing */
    2755             :             /* any real I/O */
    2756       70842 :             std::vector<std::unique_ptr<VRTSource>> papoSavedSources;
    2757       35421 :             std::swap(papoSavedSources, poBand->m_papoSources);
    2758             : 
    2759       35421 :             GDALProgressFunc pfnProgressGlobal = psExtraArg->pfnProgress;
    2760       35421 :             psExtraArg->pfnProgress = nullptr;
    2761             : 
    2762       35421 :             GByte *pabyBandData =
    2763       35421 :                 static_cast<GByte *>(pData) + iBandIndex * nBandSpace;
    2764             : 
    2765       35421 :             poBand->IRasterIO(GF_Read, nXOff, nYOff, nXSize, nYSize,
    2766             :                               pabyBandData, nBufXSize, nBufYSize, eBufType,
    2767       35421 :                               nPixelSpace, nLineSpace, psExtraArg);
    2768             : 
    2769       35421 :             psExtraArg->pfnProgress = pfnProgressGlobal;
    2770             : 
    2771       35421 :             std::swap(papoSavedSources, poBand->m_papoSources);
    2772             :         }
    2773             : 
    2774       12487 :         CPLErr eErr = CE_None;
    2775             : 
    2776             :         // Use the last band, because when sources reference a GDALProxyDataset,
    2777             :         // they don't necessary instantiate all underlying rasterbands.
    2778       12487 :         VRTSourcedRasterBand *poBand =
    2779       12487 :             static_cast<VRTSourcedRasterBand *>(papoBands[nBands - 1]);
    2780             : 
    2781       12487 :         double dfXOff = nXOff;
    2782       12487 :         double dfYOff = nYOff;
    2783       12487 :         double dfXSize = nXSize;
    2784       12487 :         double dfYSize = nYSize;
    2785       12487 :         if (psExtraArg->bFloatingPointWindowValidity)
    2786             :         {
    2787          11 :             dfXOff = psExtraArg->dfXOff;
    2788          11 :             dfYOff = psExtraArg->dfYOff;
    2789          11 :             dfXSize = psExtraArg->dfXSize;
    2790          11 :             dfYSize = psExtraArg->dfYSize;
    2791             :         }
    2792             : 
    2793       12487 :         int nContributingSources = 0;
    2794       12487 :         int nMaxThreads = 0;
    2795       12487 :         constexpr int MINIMUM_PIXEL_COUNT_FOR_THREADED_IO = 1000 * 1000;
    2796       24974 :         if ((static_cast<int64_t>(nBufXSize) * nBufYSize >=
    2797       12314 :                  MINIMUM_PIXEL_COUNT_FOR_THREADED_IO ||
    2798       12314 :              static_cast<int64_t>(nXSize) * nYSize >=
    2799         173 :                  MINIMUM_PIXEL_COUNT_FOR_THREADED_IO) &&
    2800         173 :             poBand->CanMultiThreadRasterIO(dfXOff, dfYOff, dfXSize, dfYSize,
    2801         172 :                                            nContributingSources) &&
    2802       24978 :             nContributingSources > 1 &&
    2803           4 :             (nMaxThreads = VRTDataset::GetNumThreads(this)) > 1)
    2804             :         {
    2805           2 :             m_bMultiThreadedRasterIOLastUsed = true;
    2806           2 :             m_oMapSharedSources.InitMutex();
    2807             : 
    2808           4 :             CPLErrorAccumulator errorAccumulator;
    2809           2 :             std::atomic<bool> bSuccess = true;
    2810           2 :             CPLWorkerThreadPool *psThreadPool = GDALGetGlobalThreadPool(
    2811           2 :                 std::min(nContributingSources, nMaxThreads));
    2812             : 
    2813           2 :             CPLDebugOnly(
    2814             :                 "VRT",
    2815             :                 "IRasterIO(): use optimized "
    2816             :                 "multi-threaded code path for mosaic. "
    2817             :                 "Using %d threads",
    2818             :                 std::min(nContributingSources, psThreadPool->GetThreadCount()));
    2819             : 
    2820           2 :             auto oQueue = psThreadPool->CreateJobQueue();
    2821           2 :             std::atomic<int> nCompletedJobs = 0;
    2822         132 :             for (auto &poSource : poBand->m_papoSources)
    2823             :             {
    2824         130 :                 if (!poSource->IsSimpleSource())
    2825           0 :                     continue;
    2826             :                 auto poSimpleSource =
    2827         130 :                     cpl::down_cast<VRTSimpleSource *>(poSource.get());
    2828         130 :                 if (poSimpleSource->DstWindowIntersects(dfXOff, dfYOff, dfXSize,
    2829             :                                                         dfYSize))
    2830             :                 {
    2831          67 :                     auto psJob = new VRTDatasetRasterIOJob();
    2832          67 :                     psJob->pbSuccess = &bSuccess;
    2833          67 :                     psJob->poErrorAccumulator = &errorAccumulator;
    2834          67 :                     psJob->pnCompletedJobs = &nCompletedJobs;
    2835          67 :                     psJob->eVRTBandDataType = poBand->GetRasterDataType();
    2836          67 :                     psJob->nXOff = nXOff;
    2837          67 :                     psJob->nYOff = nYOff;
    2838          67 :                     psJob->nXSize = nXSize;
    2839          67 :                     psJob->nYSize = nYSize;
    2840          67 :                     psJob->pData = pData;
    2841          67 :                     psJob->nBufXSize = nBufXSize;
    2842          67 :                     psJob->nBufYSize = nBufYSize;
    2843          67 :                     psJob->eBufType = eBufType;
    2844          67 :                     psJob->nBandCount = nBandCount;
    2845          67 :                     psJob->panBandMap = panBandMap;
    2846          67 :                     psJob->nPixelSpace = nPixelSpace;
    2847          67 :                     psJob->nLineSpace = nLineSpace;
    2848          67 :                     psJob->nBandSpace = nBandSpace;
    2849          67 :                     psJob->psExtraArg = psExtraArg;
    2850          67 :                     psJob->poSource = poSimpleSource;
    2851             : 
    2852          67 :                     if (!oQueue->SubmitJob(VRTDatasetRasterIOJob::Func, psJob))
    2853             :                     {
    2854           0 :                         delete psJob;
    2855           0 :                         bSuccess = false;
    2856           0 :                         break;
    2857             :                     }
    2858             :                 }
    2859             :             }
    2860             : 
    2861          62 :             while (oQueue->WaitEvent())
    2862             :             {
    2863             :                 // Quite rough progress callback. We could do better by counting
    2864             :                 // the number of contributing pixels.
    2865          60 :                 if (psExtraArg->pfnProgress)
    2866             :                 {
    2867         120 :                     psExtraArg->pfnProgress(double(nCompletedJobs.load()) /
    2868             :                                                 nContributingSources,
    2869             :                                             "", psExtraArg->pProgressData);
    2870             :                 }
    2871             :             }
    2872             : 
    2873           2 :             errorAccumulator.ReplayErrors();
    2874           2 :             eErr = bSuccess ? CE_None : CE_Failure;
    2875             :         }
    2876             :         else
    2877             :         {
    2878       12485 :             GDALProgressFunc pfnProgressGlobal = psExtraArg->pfnProgress;
    2879       12485 :             void *pProgressDataGlobal = psExtraArg->pProgressData;
    2880             : 
    2881       12485 :             const int nSources = static_cast<int>(poBand->m_papoSources.size());
    2882       25153 :             for (int iSource = 0; eErr == CE_None && iSource < nSources;
    2883             :                  iSource++)
    2884             :             {
    2885       12668 :                 psExtraArg->pfnProgress = GDALScaledProgress;
    2886       25336 :                 psExtraArg->pProgressData = GDALCreateScaledProgress(
    2887       12668 :                     1.0 * iSource / nSources, 1.0 * (iSource + 1) / nSources,
    2888             :                     pfnProgressGlobal, pProgressDataGlobal);
    2889             : 
    2890             :                 VRTSimpleSource *poSource = static_cast<VRTSimpleSource *>(
    2891       12668 :                     poBand->m_papoSources[iSource].get());
    2892             : 
    2893       12668 :                 eErr = poSource->DatasetRasterIO(
    2894             :                     poBand->GetRasterDataType(), nXOff, nYOff, nXSize, nYSize,
    2895             :                     pData, nBufXSize, nBufYSize, eBufType, nBandCount,
    2896             :                     panBandMap, nPixelSpace, nLineSpace, nBandSpace,
    2897             :                     psExtraArg);
    2898             : 
    2899       12668 :                 GDALDestroyScaledProgress(psExtraArg->pProgressData);
    2900             :             }
    2901             : 
    2902       12485 :             psExtraArg->pfnProgress = pfnProgressGlobal;
    2903       12485 :             psExtraArg->pProgressData = pProgressDataGlobal;
    2904             :         }
    2905             : 
    2906       12487 :         if (eErr == CE_None && psExtraArg->pfnProgress)
    2907             :         {
    2908        2673 :             psExtraArg->pfnProgress(1.0, "", psExtraArg->pProgressData);
    2909             :         }
    2910             : 
    2911       12487 :         return eErr;
    2912             :     }
    2913             : 
    2914             :     CPLErr eErr;
    2915         604 :     if (eRWFlag == GF_Read &&
    2916         604 :         psExtraArg->eResampleAlg != GRIORA_NearestNeighbour &&
    2917           2 :         nBufXSize < nXSize && nBufYSize < nYSize && nBandCount > 1)
    2918             :     {
    2919             :         // Force going through VRTSourcedRasterBand::IRasterIO(), otherwise
    2920             :         // GDALDataset::IRasterIOResampled() would be used without source
    2921             :         // overviews being potentially used.
    2922           2 :         eErr = GDALDataset::BandBasedRasterIO(
    2923             :             eRWFlag, nXOff, nYOff, nXSize, nYSize, pData, nBufXSize, nBufYSize,
    2924             :             eBufType, nBandCount, panBandMap, nPixelSpace, nLineSpace,
    2925             :             nBandSpace, psExtraArg);
    2926             :     }
    2927             :     else
    2928             :     {
    2929         602 :         eErr = GDALDataset::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
    2930             :                                       pData, nBufXSize, nBufYSize, eBufType,
    2931             :                                       nBandCount, panBandMap, nPixelSpace,
    2932             :                                       nLineSpace, nBandSpace, psExtraArg);
    2933             :     }
    2934         604 :     return eErr;
    2935             : }
    2936             : 
    2937             : /************************************************************************/
    2938             : /*                  UnsetPreservedRelativeFilenames()                   */
    2939             : /************************************************************************/
    2940             : 
    2941         135 : void VRTDataset::UnsetPreservedRelativeFilenames()
    2942             : {
    2943         211 :     for (int iBand = 0; iBand < nBands; iBand++)
    2944             :     {
    2945         187 :         if (!static_cast<VRTRasterBand *>(papoBands[iBand])
    2946          76 :                  ->IsSourcedRasterBand())
    2947          35 :             continue;
    2948             : 
    2949          41 :         VRTSourcedRasterBand *poBand =
    2950          41 :             static_cast<VRTSourcedRasterBand *>(papoBands[iBand]);
    2951          82 :         for (auto &poSource : poBand->m_papoSources)
    2952             :         {
    2953          41 :             if (!poSource->IsSimpleSource())
    2954           0 :                 continue;
    2955             : 
    2956             :             VRTSimpleSource *poSimpleSource =
    2957          41 :                 static_cast<VRTSimpleSource *>(poSource.get());
    2958          41 :             poSimpleSource->UnsetPreservedRelativeFilenames();
    2959             :         }
    2960             :     }
    2961         135 : }
    2962             : 
    2963             : /************************************************************************/
    2964             : /*                       BuildVirtualOverviews()                        */
    2965             : /************************************************************************/
    2966             : 
    2967        5774 : static bool CheckBandForOverview(GDALRasterBand *poBand,
    2968             :                                  GDALRasterBand *&poFirstBand, int &nOverviews,
    2969             :                                  std::set<std::pair<int, int>> &oSetOvrSizes,
    2970             :                                  std::vector<GDALDataset *> &apoOverviewsBak)
    2971             : {
    2972        5774 :     if (!cpl::down_cast<VRTRasterBand *>(poBand)->IsSourcedRasterBand())
    2973           0 :         return false;
    2974             : 
    2975             :     VRTSourcedRasterBand *poVRTBand =
    2976        5774 :         cpl::down_cast<VRTSourcedRasterBand *>(poBand);
    2977        5774 :     if (poVRTBand->m_papoSources.size() != 1)
    2978        4296 :         return false;
    2979        1478 :     if (!poVRTBand->m_papoSources[0]->IsSimpleSource())
    2980          12 :         return false;
    2981             : 
    2982             :     VRTSimpleSource *poSource =
    2983        1466 :         cpl::down_cast<VRTSimpleSource *>(poVRTBand->m_papoSources[0].get());
    2984        1466 :     const char *pszType = poSource->GetType();
    2985        1599 :     if (pszType != VRTSimpleSource::GetTypeStatic() &&
    2986         133 :         pszType != VRTComplexSource::GetTypeStatic())
    2987             :     {
    2988          26 :         return false;
    2989             :     }
    2990        1440 :     GDALRasterBand *poSrcBand = poSource->GetMaskBandMainBand();
    2991        1440 :     if (!poSrcBand)
    2992        1437 :         poSrcBand = poSource->GetRasterBand();
    2993        1440 :     if (poSrcBand == nullptr)
    2994           1 :         return false;
    2995             : 
    2996             :     // To prevent recursion
    2997        1439 :     apoOverviewsBak.push_back(nullptr);
    2998        1439 :     const int nOvrCount = poSrcBand->GetOverviewCount();
    2999             :     oSetOvrSizes.insert(
    3000        1439 :         std::pair<int, int>(poSrcBand->GetXSize(), poSrcBand->GetYSize()));
    3001        1591 :     for (int i = 0; i < nOvrCount; ++i)
    3002             :     {
    3003         152 :         auto poSrcOvrBand = poSrcBand->GetOverview(i);
    3004         152 :         if (poSrcOvrBand)
    3005             :         {
    3006         152 :             oSetOvrSizes.insert(std::pair<int, int>(poSrcOvrBand->GetXSize(),
    3007         304 :                                                     poSrcOvrBand->GetYSize()));
    3008             :         }
    3009             :     }
    3010        1439 :     apoOverviewsBak.resize(0);
    3011             : 
    3012        1439 :     if (nOvrCount == 0)
    3013        1350 :         return false;
    3014          89 :     if (poFirstBand == nullptr)
    3015             :     {
    3016          31 :         if (poSrcBand->GetXSize() == 0 || poSrcBand->GetYSize() == 0)
    3017           0 :             return false;
    3018          31 :         poFirstBand = poSrcBand;
    3019          31 :         nOverviews = nOvrCount;
    3020             :     }
    3021          58 :     else if (nOvrCount < nOverviews)
    3022           0 :         nOverviews = nOvrCount;
    3023          89 :     return true;
    3024             : }
    3025             : 
    3026        5848 : void VRTDataset::BuildVirtualOverviews()
    3027             : {
    3028             :     // Currently we expose virtual overviews only if the dataset is made of
    3029             :     // a single SimpleSource/ComplexSource, in each band.
    3030             :     // And if the underlying sources have overviews of course
    3031        5848 :     if (!m_apoOverviews.empty() || !m_apoOverviewsBak.empty())
    3032        5820 :         return;
    3033             : 
    3034        5713 :     int nOverviews = 0;
    3035        5713 :     GDALRasterBand *poFirstBand = nullptr;
    3036        5713 :     std::set<std::pair<int, int>> oSetOvrSizes;
    3037             : 
    3038        5796 :     for (int iBand = 0; iBand < nBands; iBand++)
    3039             :     {
    3040        5768 :         if (!CheckBandForOverview(papoBands[iBand], poFirstBand, nOverviews,
    3041        5768 :                                   oSetOvrSizes, m_apoOverviewsBak))
    3042        5685 :             return;
    3043             :     }
    3044             : 
    3045          28 :     if (m_poMaskBand)
    3046             :     {
    3047           6 :         if (!CheckBandForOverview(m_poMaskBand.get(), poFirstBand, nOverviews,
    3048           6 :                                   oSetOvrSizes, m_apoOverviewsBak))
    3049           0 :             return;
    3050             :     }
    3051          28 :     if (poFirstBand == nullptr)
    3052             :     {
    3053             :         // to make cppcheck happy
    3054           0 :         CPLAssert(false);
    3055             :         return;
    3056             :     }
    3057             : 
    3058             :     VRTSourcedRasterBand *l_poVRTBand =
    3059          28 :         cpl::down_cast<VRTSourcedRasterBand *>(papoBands[0]);
    3060             :     VRTSimpleSource *poSource =
    3061          28 :         cpl::down_cast<VRTSimpleSource *>(l_poVRTBand->m_papoSources[0].get());
    3062          28 :     const double dfDstToSrcXRatio =
    3063          28 :         poSource->m_dfDstXSize / poSource->m_dfSrcXSize;
    3064          28 :     const double dfDstToSrcYRatio =
    3065          28 :         poSource->m_dfDstYSize / poSource->m_dfSrcYSize;
    3066             : 
    3067          68 :     for (int j = 0; j < nOverviews; j++)
    3068             :     {
    3069          43 :         auto poSrcOvrBand = poFirstBand->GetOverview(j);
    3070          43 :         if (!poSrcOvrBand)
    3071           0 :             return;
    3072          43 :         const double dfXRatio = static_cast<double>(poSrcOvrBand->GetXSize()) /
    3073          43 :                                 poFirstBand->GetXSize();
    3074          43 :         const double dfYRatio = static_cast<double>(poSrcOvrBand->GetYSize()) /
    3075          43 :                                 poFirstBand->GetYSize();
    3076          43 :         if (dfXRatio >= dfDstToSrcXRatio || dfYRatio >= dfDstToSrcYRatio)
    3077             :         {
    3078           5 :             continue;
    3079             :         }
    3080          38 :         int nOvrXSize = static_cast<int>(0.5 + nRasterXSize * dfXRatio);
    3081          38 :         int nOvrYSize = static_cast<int>(0.5 + nRasterYSize * dfYRatio);
    3082             : 
    3083             :         // Look for a source overview whose size is very close to the
    3084             :         // theoretical computed one.
    3085          38 :         bool bSrcOvrMatchFound = false;
    3086         127 :         for (const auto &ovrSize : oSetOvrSizes)
    3087             :         {
    3088         113 :             if (std::abs(ovrSize.first - nOvrXSize) <= 1 &&
    3089          24 :                 std::abs(ovrSize.second - nOvrYSize) <= 1)
    3090             :             {
    3091          24 :                 bSrcOvrMatchFound = true;
    3092          24 :                 nOvrXSize = ovrSize.first;
    3093          24 :                 nOvrYSize = ovrSize.second;
    3094          24 :                 break;
    3095             :             }
    3096             :         }
    3097             : 
    3098          38 :         if (!bSrcOvrMatchFound &&
    3099          14 :             (nOvrXSize < DEFAULT_BLOCK_SIZE || nOvrYSize < DEFAULT_BLOCK_SIZE))
    3100             :         {
    3101             :             break;
    3102             :         }
    3103             : 
    3104          35 :         int nBlockXSize = 0;
    3105          35 :         int nBlockYSize = 0;
    3106          35 :         l_poVRTBand->GetBlockSize(&nBlockXSize, &nBlockYSize);
    3107          35 :         if (VRTDataset::IsDefaultBlockSize(nBlockXSize, nRasterXSize))
    3108          13 :             nBlockXSize = 0;
    3109          35 :         if (VRTDataset::IsDefaultBlockSize(nBlockYSize, nRasterYSize))
    3110          17 :             nBlockYSize = 0;
    3111             : 
    3112             :         auto poOvrVDS = std::make_unique<VRTDataset>(nOvrXSize, nOvrYSize,
    3113          35 :                                                      nBlockXSize, nBlockYSize);
    3114             : 
    3115             :         const auto CreateOverviewBand =
    3116         102 :             [&poOvrVDS, nOvrXSize, nOvrYSize, dfXRatio,
    3117             :              dfYRatio](VRTSourcedRasterBand *poVRTBand)
    3118         102 :             -> std::unique_ptr<VRTSourcedRasterBand>
    3119             :         {
    3120             :             auto poOvrVRTBand = poVRTBand->CloneWithoutSources(
    3121         204 :                 poOvrVDS.get(), nOvrXSize, nOvrYSize);
    3122         102 :             auto &oOvrVRTBand = *poOvrVRTBand;
    3123         102 :             auto &oVRTBand = *poVRTBand;
    3124         102 :             if (typeid(oOvrVRTBand) != typeid(oVRTBand))
    3125             :             {
    3126           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    3127             :                          "Lack of CloneWithoutSources() implementation for "
    3128             :                          "subclass %s of VRTSourcedRasterBand",
    3129           0 :                          typeid(oVRTBand).name());
    3130           0 :                 return nullptr;
    3131             :             }
    3132             : 
    3133         102 :             VRTSimpleSource *poSrcSource = cpl::down_cast<VRTSimpleSource *>(
    3134         102 :                 poVRTBand->m_papoSources[0].get());
    3135         102 :             std::unique_ptr<VRTSimpleSource> poNewSource;
    3136         102 :             const char *pszType = poSrcSource->GetType();
    3137         102 :             if (pszType == VRTSimpleSource::GetTypeStatic())
    3138             :             {
    3139          97 :                 poNewSource = std::make_unique<VRTSimpleSource>(
    3140          97 :                     poSrcSource, dfXRatio, dfYRatio);
    3141             :             }
    3142           5 :             else if (pszType == VRTComplexSource::GetTypeStatic())
    3143             :             {
    3144           5 :                 poNewSource = std::make_unique<VRTComplexSource>(
    3145          10 :                     cpl::down_cast<VRTComplexSource *>(poSrcSource), dfXRatio,
    3146          10 :                     dfYRatio);
    3147             :             }
    3148             :             else
    3149             :             {
    3150           0 :                 CPLAssert(false);
    3151             :             }
    3152         102 :             if (poNewSource)
    3153             :             {
    3154         102 :                 poOvrVRTBand->AddSource(std::move(poNewSource));
    3155             :             }
    3156             : 
    3157         102 :             return poOvrVRTBand;
    3158          35 :         };
    3159             : 
    3160         129 :         for (int i = 0; i < nBands; i++)
    3161             :         {
    3162             :             VRTSourcedRasterBand *poSrcBand =
    3163          94 :                 cpl::down_cast<VRTSourcedRasterBand *>(GetRasterBand(i + 1));
    3164          94 :             auto poOvrBand = CreateOverviewBand(poSrcBand);
    3165          94 :             if (!poOvrBand)
    3166           0 :                 return;
    3167         188 :             poOvrVDS->SetBand(poOvrVDS->GetRasterCount() + 1,
    3168          94 :                               std::move(poOvrBand));
    3169             :         }
    3170             : 
    3171          35 :         if (m_poMaskBand)
    3172             :         {
    3173             :             VRTSourcedRasterBand *poSrcBand =
    3174           8 :                 cpl::down_cast<VRTSourcedRasterBand *>(m_poMaskBand.get());
    3175           8 :             auto poOvrBand = CreateOverviewBand(poSrcBand);
    3176           8 :             if (!poOvrBand)
    3177           0 :                 return;
    3178           8 :             poOvrVDS->SetMaskBand(std::move(poOvrBand));
    3179             :         }
    3180             : 
    3181          35 :         m_apoOverviews.push_back(poOvrVDS.release());
    3182             :     }
    3183             : }
    3184             : 
    3185             : /************************************************************************/
    3186             : /*                         AddVirtualOverview()                         */
    3187             : /************************************************************************/
    3188             : 
    3189          38 : bool VRTDataset::AddVirtualOverview(int nOvFactor, const char *pszResampling)
    3190             : {
    3191          38 :     if (nRasterXSize / nOvFactor == 0 || nRasterYSize / nOvFactor == 0)
    3192             :     {
    3193           1 :         return false;
    3194             :     }
    3195             : 
    3196          74 :     CPLStringList argv;
    3197          37 :     argv.AddString("-of");
    3198          37 :     argv.AddString("VRT");
    3199          37 :     argv.AddString("-outsize");
    3200          37 :     argv.AddString(CPLSPrintf("%d", nRasterXSize / nOvFactor));
    3201          37 :     argv.AddString(CPLSPrintf("%d", nRasterYSize / nOvFactor));
    3202          37 :     argv.AddString("-r");
    3203          37 :     argv.AddString(pszResampling);
    3204             : 
    3205          37 :     int nBlockXSize = 0;
    3206          37 :     int nBlockYSize = 0;
    3207          37 :     GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize);
    3208          37 :     if (!VRTDataset::IsDefaultBlockSize(nBlockXSize, nRasterXSize))
    3209             :     {
    3210           6 :         argv.AddString("-co");
    3211           6 :         argv.AddString(CPLSPrintf("BLOCKXSIZE=%d", nBlockXSize));
    3212             :     }
    3213          37 :     if (!VRTDataset::IsDefaultBlockSize(nBlockYSize, nRasterYSize))
    3214             :     {
    3215          11 :         argv.AddString("-co");
    3216          11 :         argv.AddString(CPLSPrintf("BLOCKYSIZE=%d", nBlockYSize));
    3217             :     }
    3218             : 
    3219             :     GDALTranslateOptions *psOptions =
    3220          37 :         GDALTranslateOptionsNew(argv.List(), nullptr);
    3221             : 
    3222             :     // Add a dummy overview so that BuildVirtualOverviews() doesn't trigger
    3223          37 :     m_apoOverviews.push_back(nullptr);
    3224          37 :     CPLAssert(m_bCanTakeRef);
    3225          37 :     m_bCanTakeRef =
    3226             :         false;  // we don't want hOverviewDS to take a reference on ourselves.
    3227             :     GDALDatasetH hOverviewDS =
    3228          37 :         GDALTranslate("", GDALDataset::ToHandle(this), psOptions, nullptr);
    3229          37 :     m_bCanTakeRef = true;
    3230          37 :     m_apoOverviews.pop_back();
    3231             : 
    3232          37 :     GDALTranslateOptionsFree(psOptions);
    3233          37 :     if (hOverviewDS == nullptr)
    3234           0 :         return false;
    3235             : 
    3236          37 :     m_anOverviewFactors.push_back(nOvFactor);
    3237          37 :     m_apoOverviews.push_back(GDALDataset::FromHandle(hOverviewDS));
    3238          37 :     return true;
    3239             : }
    3240             : 
    3241             : /************************************************************************/
    3242             : /*                          IBuildOverviews()                           */
    3243             : /************************************************************************/
    3244             : 
    3245          37 : CPLErr VRTDataset::IBuildOverviews(const char *pszResampling, int nOverviews,
    3246             :                                    const int *panOverviewList, int nListBands,
    3247             :                                    const int *panBandList,
    3248             :                                    GDALProgressFunc pfnProgress,
    3249             :                                    void *pProgressData,
    3250             :                                    CSLConstList papszOptions)
    3251             : {
    3252          37 :     if (CPLTestBool(CSLFetchNameValueDef(
    3253             :             papszOptions, "VIRTUAL",
    3254             :             CPLGetConfigOption("VRT_VIRTUAL_OVERVIEWS", "NO"))))
    3255             :     {
    3256          15 :         SetNeedsFlush();
    3257          29 :         if (nOverviews == 0 ||
    3258          14 :             (!m_apoOverviews.empty() && m_anOverviewFactors.empty()))
    3259             :         {
    3260           3 :             m_anOverviewFactors.clear();
    3261           3 :             m_apoOverviewsBak.insert(m_apoOverviewsBak.end(),
    3262             :                                      m_apoOverviews.begin(),
    3263           6 :                                      m_apoOverviews.end());
    3264           3 :             m_apoOverviews.clear();
    3265             :         }
    3266          15 :         m_osOverviewResampling = pszResampling;
    3267          40 :         for (int i = 0; i < nOverviews; i++)
    3268             :         {
    3269          25 :             if (std::find(m_anOverviewFactors.begin(),
    3270             :                           m_anOverviewFactors.end(),
    3271          25 :                           panOverviewList[i]) == m_anOverviewFactors.end())
    3272             :             {
    3273          25 :                 AddVirtualOverview(panOverviewList[i], pszResampling);
    3274             :             }
    3275             :         }
    3276          15 :         return CE_None;
    3277             :     }
    3278             : 
    3279          22 :     if (!oOvManager.IsInitialized())
    3280             :     {
    3281           0 :         const char *pszDesc = GetDescription();
    3282           0 :         if (pszDesc[0])
    3283             :         {
    3284           0 :             oOvManager.Initialize(this, pszDesc);
    3285             :         }
    3286             :     }
    3287             : 
    3288             :     // Make implicit overviews invisible, but do not destroy them in case they
    3289             :     // are already used.  Should the client do that?  Behavior might undefined
    3290             :     // in GDAL API?
    3291          22 :     if (!m_apoOverviews.empty())
    3292             :     {
    3293           2 :         m_apoOverviewsBak.insert(m_apoOverviewsBak.end(),
    3294           4 :                                  m_apoOverviews.begin(), m_apoOverviews.end());
    3295           2 :         m_apoOverviews.clear();
    3296             :     }
    3297             :     else
    3298             :     {
    3299             :         // Add a dummy overview so that GDALDataset::IBuildOverviews()
    3300             :         // doesn't manage to get a virtual implicit overview.
    3301          20 :         m_apoOverviews.push_back(nullptr);
    3302             :     }
    3303             : 
    3304          22 :     CPLErr eErr = GDALDataset::IBuildOverviews(
    3305             :         pszResampling, nOverviews, panOverviewList, nListBands, panBandList,
    3306             :         pfnProgress, pProgressData, papszOptions);
    3307             : 
    3308          22 :     m_apoOverviews.clear();
    3309          22 :     return eErr;
    3310             : }
    3311             : 
    3312             : /************************************************************************/
    3313             : /*                         GetShiftedDataset()                          */
    3314             : /*                                                                      */
    3315             : /* Returns true if the VRT is made of a single source that is a simple  */
    3316             : /* in its full resolution.                                              */
    3317             : /************************************************************************/
    3318             : 
    3319          50 : bool VRTDataset::GetShiftedDataset(int nXOff, int nYOff, int nXSize, int nYSize,
    3320             :                                    GDALDataset *&poSrcDataset, int &nSrcXOff,
    3321             :                                    int &nSrcYOff)
    3322             : {
    3323          50 :     if (!CheckCompatibleForDatasetIO())
    3324           0 :         return false;
    3325             : 
    3326          50 :     VRTSourcedRasterBand *poVRTBand =
    3327          50 :         static_cast<VRTSourcedRasterBand *>(papoBands[0]);
    3328          50 :     if (poVRTBand->m_papoSources.size() != 1)
    3329           0 :         return false;
    3330             : 
    3331             :     VRTSimpleSource *poSource =
    3332          50 :         static_cast<VRTSimpleSource *>(poVRTBand->m_papoSources[0].get());
    3333             : 
    3334          50 :     GDALRasterBand *poBand = poSource->GetRasterBand();
    3335         100 :     if (!poBand || poSource->GetMaskBandMainBand() ||
    3336          50 :         poBand->GetRasterDataType() != poVRTBand->GetRasterDataType())
    3337          23 :         return false;
    3338             : 
    3339          27 :     poSrcDataset = poBand->GetDataset();
    3340          27 :     if (!poSrcDataset)
    3341           0 :         return false;
    3342             : 
    3343          27 :     double dfReqXOff = 0.0;
    3344          27 :     double dfReqYOff = 0.0;
    3345          27 :     double dfReqXSize = 0.0;
    3346          27 :     double dfReqYSize = 0.0;
    3347          27 :     int nReqXOff = 0;
    3348          27 :     int nReqYOff = 0;
    3349          27 :     int nReqXSize = 0;
    3350          27 :     int nReqYSize = 0;
    3351          27 :     int nOutXOff = 0;
    3352          27 :     int nOutYOff = 0;
    3353          27 :     int nOutXSize = 0;
    3354          27 :     int nOutYSize = 0;
    3355          27 :     bool bError = false;
    3356          27 :     if (!poSource->GetSrcDstWindow(
    3357             :             nXOff, nYOff, nXSize, nYSize, nXSize, nYSize,
    3358             :             GRIORA_NearestNeighbour, &dfReqXOff, &dfReqYOff, &dfReqXSize,
    3359             :             &dfReqYSize, &nReqXOff, &nReqYOff, &nReqXSize, &nReqYSize,
    3360             :             &nOutXOff, &nOutYOff, &nOutXSize, &nOutYSize, bError))
    3361           0 :         return false;
    3362             : 
    3363          27 :     if (nReqXSize != nXSize || nReqYSize != nYSize || nReqXSize != nOutXSize ||
    3364          25 :         nReqYSize != nOutYSize)
    3365           2 :         return false;
    3366             : 
    3367          25 :     nSrcXOff = nReqXOff;
    3368          25 :     nSrcYOff = nReqYOff;
    3369          25 :     return true;
    3370             : }
    3371             : 
    3372             : /************************************************************************/
    3373             : /*                       GetCompressionFormats()                        */
    3374             : /************************************************************************/
    3375             : 
    3376           0 : CPLStringList VRTDataset::GetCompressionFormats(int nXOff, int nYOff,
    3377             :                                                 int nXSize, int nYSize,
    3378             :                                                 int nBandCount,
    3379             :                                                 const int *panBandList)
    3380             : {
    3381             :     GDALDataset *poSrcDataset;
    3382             :     int nSrcXOff;
    3383             :     int nSrcYOff;
    3384           0 :     if (!GetShiftedDataset(nXOff, nYOff, nXSize, nYSize, poSrcDataset, nSrcXOff,
    3385             :                            nSrcYOff))
    3386           0 :         return CPLStringList();
    3387             :     return poSrcDataset->GetCompressionFormats(nSrcXOff, nSrcYOff, nXSize,
    3388           0 :                                                nYSize, nBandCount, panBandList);
    3389             : }
    3390             : 
    3391             : /************************************************************************/
    3392             : /*                         ReadCompressedData()                         */
    3393             : /************************************************************************/
    3394             : 
    3395          50 : CPLErr VRTDataset::ReadCompressedData(const char *pszFormat, int nXOff,
    3396             :                                       int nYOff, int nXSize, int nYSize,
    3397             :                                       int nBandCount, const int *panBandList,
    3398             :                                       void **ppBuffer, size_t *pnBufferSize,
    3399             :                                       char **ppszDetailedFormat)
    3400             : {
    3401             :     GDALDataset *poSrcDataset;
    3402             :     int nSrcXOff;
    3403             :     int nSrcYOff;
    3404          50 :     if (!GetShiftedDataset(nXOff, nYOff, nXSize, nYSize, poSrcDataset, nSrcXOff,
    3405             :                            nSrcYOff))
    3406          25 :         return CE_Failure;
    3407          25 :     return poSrcDataset->ReadCompressedData(
    3408             :         pszFormat, nSrcXOff, nSrcYOff, nXSize, nYSize, nBandCount, panBandList,
    3409          25 :         ppBuffer, pnBufferSize, ppszDetailedFormat);
    3410             : }
    3411             : 
    3412             : /************************************************************************/
    3413             : /*                          ClearStatistics()                           */
    3414             : /************************************************************************/
    3415             : 
    3416           6 : void VRTDataset::ClearStatistics()
    3417             : {
    3418          18 :     for (int i = 1; i <= nBands; ++i)
    3419             :     {
    3420          12 :         bool bChanged = false;
    3421          12 :         GDALRasterBand *poBand = GetRasterBand(i);
    3422          12 :         CSLConstList papszOldMD = poBand->GetMetadata();
    3423          24 :         CPLStringList aosNewMD;
    3424          32 :         for (const char *pszMDItem : cpl::Iterate(papszOldMD))
    3425             :         {
    3426          20 :             if (STARTS_WITH_CI(pszMDItem, "STATISTICS_"))
    3427             :             {
    3428          20 :                 bChanged = true;
    3429             :             }
    3430             :             else
    3431             :             {
    3432           0 :                 aosNewMD.AddString(pszMDItem);
    3433             :             }
    3434             :         }
    3435          12 :         if (bChanged)
    3436             :         {
    3437           4 :             poBand->SetMetadata(aosNewMD.List());
    3438             :         }
    3439             :     }
    3440             : 
    3441           6 :     GDALDataset::ClearStatistics();
    3442           6 : }
    3443             : 
    3444             : /************************************************************************/
    3445             : /*                  VRTMapSharedResources::LockGuard()                  */
    3446             : /************************************************************************/
    3447             : 
    3448             : std::unique_ptr<std::lock_guard<std::mutex>>
    3449      203587 : VRTMapSharedResources::LockGuard() const
    3450             : {
    3451      203587 :     std::unique_ptr<std::lock_guard<std::mutex>> poLockGuard;
    3452      203587 :     if (m_bUseMutex)
    3453             :     {
    3454         268 :         poLockGuard = std::make_unique<std::lock_guard<std::mutex>>(m_oMutex);
    3455             :     }
    3456      203587 :     return poLockGuard;
    3457             : }
    3458             : 
    3459             : /************************************************************************/
    3460             : /*                     VRTMapSharedResources::Get()                     */
    3461             : /************************************************************************/
    3462             : 
    3463      101802 : GDALDataset *VRTMapSharedResources::Get(const std::string &osKey) const
    3464             : {
    3465      101802 :     auto poLockGuard = LockGuard();
    3466      101802 :     CPL_IGNORE_RET_VAL(poLockGuard);
    3467      101802 :     auto oIter = m_oMap.find(osKey);
    3468      101802 :     GDALDataset *poRet = nullptr;
    3469      101802 :     if (oIter != m_oMap.end())
    3470       98887 :         poRet = oIter->second;
    3471      203604 :     return poRet;
    3472             : }
    3473             : 
    3474             : /************************************************************************/
    3475             : /*                   VRTMapSharedResources::Insert()                    */
    3476             : /************************************************************************/
    3477             : 
    3478      101785 : void VRTMapSharedResources::Insert(const std::string &osKey, GDALDataset *poDS)
    3479             : {
    3480      101785 :     auto poLockGuard = LockGuard();
    3481      101785 :     CPL_IGNORE_RET_VAL(poLockGuard);
    3482      101785 :     m_oMap[osKey] = poDS;
    3483      101785 : }
    3484             : 
    3485             : /************************************************************************/
    3486             : /*                  VRTMapSharedResources::InitMutex()                  */
    3487             : /************************************************************************/
    3488             : 
    3489          20 : void VRTMapSharedResources::InitMutex()
    3490             : {
    3491          20 :     m_bUseMutex = true;
    3492          20 : }
    3493             : 
    3494             : /*! @endcond */

Generated by: LCOV version 1.14