LCOV - code coverage report
Current view: top level - frmts/mbtiles - mbtilesdataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 1256 1698 74.0 %
Date: 2025-07-06 19:57:03 Functions: 62 67 92.5 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  GDAL MBTiles driver
       4             :  * Purpose:  Implement GDAL MBTiles support using OGR SQLite driver
       5             :  * Author:   Even Rouault, Even Rouault <even.rouault at spatialys.com>
       6             :  *
       7             :  **********************************************************************
       8             :  * Copyright (c) 2012-2016, Even Rouault <even.rouault at spatialys.com>
       9             :  *
      10             :  * SPDX-License-Identifier: MIT
      11             :  ****************************************************************************/
      12             : 
      13             : #if defined(HAVE_SQLITE) && defined(HAVE_GEOS)
      14             : // Needed by mvtutils.h
      15             : #define HAVE_MVT_WRITE_SUPPORT
      16             : #endif
      17             : 
      18             : #include "gdal_frmts.h"
      19             : #include "gdal_pam.h"
      20             : #include "ogr_api.h"
      21             : #include "cpl_json.h"
      22             : #include "cpl_vsil_curl_priv.h"
      23             : #include "gpkgmbtilescommon.h"
      24             : #include "gdal_utils.h"
      25             : #include "gdalwarper.h"
      26             : #include "mvtutils.h"
      27             : #include "ogrsqlitevfs.h"
      28             : #include "ogrsqlitebase.h"
      29             : 
      30             : #include "zlib.h"
      31             : #include "ogrlibjsonutils.h"
      32             : 
      33             : #include <math.h>
      34             : #include <algorithm>
      35             : #include <memory>
      36             : #include <vector>
      37             : 
      38             : static const char *const apszAllowedDrivers[] = {"JPEG", "PNG", "WEBP",
      39             :                                                  nullptr};
      40             : 
      41             : #define SRS_EPSG_3857                                                          \
      42             :     "PROJCS[\"WGS 84 / Pseudo-Mercator\",GEOGCS[\"WGS "                        \
      43             :     "84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS "                                  \
      44             :     "84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY["      \
      45             :     "\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]]" \
      46             :     ",UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],"       \
      47             :     "AUTHORITY[\"EPSG\",\"4326\"]],PROJECTION[\"Mercator_1SP\"],PARAMETER["    \
      48             :     "\"central_meridian\",0],PARAMETER[\"scale_factor\",1],PARAMETER[\"false_" \
      49             :     "easting\",0],PARAMETER[\"false_northing\",0],UNIT[\"metre\",1,AUTHORITY[" \
      50             :     "\"EPSG\",\"9001\"]],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH],EXTENSION["        \
      51             :     "\"PROJ4\",\"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 "     \
      52             :     "+x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  "                \
      53             :     "+no_defs\"],AUTHORITY[\"EPSG\",\"3857\"]]"
      54             : 
      55             : #define SPHERICAL_RADIUS 6378137.0
      56             : #define MAX_GM (SPHERICAL_RADIUS * M_PI)  // 20037508.342789244
      57             : 
      58             : // TileMatrixSet origin : caution this is in GeoPackage / WMTS convention ! That
      59             : // is upper-left corner
      60             : #define TMS_ORIGIN_X -MAX_GM
      61             : #define TMS_ORIGIN_Y MAX_GM
      62             : 
      63             : #if defined(DEBUG) || defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) ||     \
      64             :     defined(ALLOW_FORMAT_DUMPS)
      65             : // Enable accepting a SQL dump (starting with a "-- SQL MBTILES" line) as a
      66             : // valid file. This makes fuzzer life easier
      67             : #define ENABLE_SQL_SQLITE_FORMAT
      68             : #endif
      69             : 
      70             : constexpr int knDEFAULT_BLOCK_SIZE = 256;
      71             : 
      72             : class MBTilesBand;
      73             : 
      74             : /************************************************************************/
      75             : /*                         MBTILESOpenSQLiteDB()                        */
      76             : /************************************************************************/
      77             : 
      78          77 : static GDALDatasetH MBTILESOpenSQLiteDB(const char *pszFilename,
      79             :                                         GDALAccess eAccess)
      80             : {
      81          77 :     const char *l_apszAllowedDrivers[] = {"SQLITE", nullptr};
      82         154 :     return GDALOpenEx((CPLString("SQLITE:") + pszFilename).c_str(),
      83             :                       GDAL_OF_VECTOR | GDAL_OF_INTERNAL |
      84             :                           ((eAccess == GA_Update) ? GDAL_OF_UPDATE : 0),
      85         154 :                       l_apszAllowedDrivers, nullptr, nullptr);
      86             : }
      87             : 
      88             : /************************************************************************/
      89             : /* ==================================================================== */
      90             : /*                              MBTilesDataset                          */
      91             : /* ==================================================================== */
      92             : /************************************************************************/
      93             : 
      94             : class MBTilesDataset final : public GDALPamDataset,
      95             :                              public GDALGPKGMBTilesLikePseudoDataset
      96             : {
      97             :     friend class MBTilesBand;
      98             :     friend class MBTilesVectorLayer;
      99             : 
     100             :   public:
     101             :     MBTilesDataset();
     102             : 
     103             :     virtual ~MBTilesDataset();
     104             : 
     105             :     virtual CPLErr GetGeoTransform(GDALGeoTransform &gt) const override;
     106             :     virtual CPLErr SetGeoTransform(const GDALGeoTransform &gt) override;
     107             :     const OGRSpatialReference *GetSpatialRef() const override;
     108             :     CPLErr SetSpatialRef(const OGRSpatialReference *poSRS) override;
     109             : 
     110             :     virtual char **GetMetadataDomainList() override;
     111             :     virtual char **GetMetadata(const char *pszDomain = "") override;
     112             :     virtual const char *GetMetadataItem(const char *pszName,
     113             :                                         const char *pszDomain = "") override;
     114             : 
     115             :     virtual CPLErr IBuildOverviews(const char *pszResampling, int nOverviews,
     116             :                                    const int *panOverviewList, int nBandsIn,
     117             :                                    const int * /* panBandList */,
     118             :                                    GDALProgressFunc pfnProgress,
     119             :                                    void *pProgressData,
     120             :                                    CSLConstList papszOptions) override;
     121             : 
     122        1166 :     virtual int GetLayerCount() override
     123             :     {
     124        1166 :         return static_cast<int>(m_apoLayers.size());
     125             :     }
     126             : 
     127             :     virtual OGRLayer *GetLayer(int) override;
     128             : 
     129             :     static GDALDataset *Open(GDALOpenInfo *);
     130             :     static int Identify(GDALOpenInfo *);
     131             :     static GDALDataset *Create(const char *pszFilename, int nXSize, int nYSize,
     132             :                                int nBandsIn, GDALDataType eDT,
     133             :                                char **papszOptions);
     134             :     static GDALDataset *CreateCopy(const char *pszFilename,
     135             :                                    GDALDataset *poSrcDS, int bStrict,
     136             :                                    char **papszOptions,
     137             :                                    GDALProgressFunc pfnProgress,
     138             :                                    void *pProgressData);
     139             : 
     140             :     char *FindKey(int iPixel, int iLine);
     141             : 
     142             :     bool HasNonEmptyGrids();
     143             : 
     144             :   private:
     145             :     bool m_bWriteBounds;
     146             :     CPLString m_osBounds;
     147             :     CPLString m_osCenter;
     148             :     bool m_bWriteMinMaxZoom;
     149             :     MBTilesDataset *poMainDS;
     150             :     bool m_bGeoTransformValid;
     151             :     GDALGeoTransform m_gt{};
     152             :     int m_nMinZoomLevel = 0;
     153             :     OGRSpatialReference m_oSRS{};
     154             : 
     155             :     int m_nOverviewCount;
     156             :     MBTilesDataset **m_papoOverviewDS;
     157             : 
     158             :     GDALDatasetH hDS;
     159             :     sqlite3 *hDB;
     160             : 
     161             :     sqlite3_vfs *pMyVFS;
     162             : 
     163             :     bool bFetchedMetadata;
     164             :     CPLStringList aosList;
     165             : 
     166             :     int nHasNonEmptyGrids;
     167             : 
     168             :     bool m_bInFlushCache;
     169             : 
     170             :     CPLString m_osMetadataMemFilename;
     171             :     CPLString m_osClip;
     172             :     std::vector<std::unique_ptr<OGRLayer>> m_apoLayers;
     173             : 
     174             :     void ParseCompressionOptions(char **papszOptions);
     175             :     CPLErr FinalizeRasterRegistration();
     176             :     void ComputeTileAndPixelShifts();
     177             :     bool InitRaster(MBTilesDataset *poParentDS, int nZoomLevel, int nBandCount,
     178             :                     int nTileSize, double dfGDALMinX, double dfGDALMinY,
     179             :                     double dfGDALMaxX, double dfGDALMaxY);
     180             : 
     181             :     bool CreateInternal(const char *pszFilename, int nXSize, int nYSize,
     182             :                         int nBandsIn, GDALDataType eDT, char **papszOptions);
     183             :     void InitVector(double dfMinX, double dfMinY, double dfMaxX, double dfMaxY,
     184             :                     bool bZoomLevelFromSpatialFilter, bool bJsonField);
     185             : 
     186             :   protected:
     187             :     // Coming from GDALGPKGMBTilesLikePseudoDataset
     188             : 
     189             :     virtual CPLErr IFlushCacheWithErrCode(bool bAtClosing) override;
     190             : 
     191        1963 :     virtual int IGetRasterCount() override
     192             :     {
     193        1963 :         return nBands;
     194             :     }
     195             : 
     196        3310 :     virtual GDALRasterBand *IGetRasterBand(int nBand) override
     197             :     {
     198        3310 :         return GetRasterBand(nBand);
     199             :     }
     200             : 
     201         546 :     virtual sqlite3 *IGetDB() override
     202             :     {
     203         546 :         return hDB;
     204             :     }
     205             : 
     206         943 :     virtual bool IGetUpdate() override
     207             :     {
     208         943 :         return eAccess == GA_Update;
     209             :     }
     210             : 
     211             :     virtual bool ICanIWriteBlock() override;
     212             :     virtual OGRErr IStartTransaction() override;
     213             :     virtual OGRErr ICommitTransaction() override;
     214             : 
     215          22 :     virtual const char *IGetFilename() override
     216             :     {
     217          22 :         return GetDescription();
     218             :     }
     219             : 
     220             :     virtual int GetRowFromIntoTopConvention(int nRow) override;
     221             : };
     222             : 
     223             : /************************************************************************/
     224             : /* ==================================================================== */
     225             : /*                          MBTilesVectorLayer                          */
     226             : /* ==================================================================== */
     227             : /************************************************************************/
     228             : 
     229             : class MBTilesVectorLayer final : public OGRLayer
     230             : {
     231             :     MBTilesDataset *m_poDS = nullptr;
     232             :     OGRFeatureDefn *m_poFeatureDefn = nullptr;
     233             :     OGRLayerH m_hTileIteratorLyr = nullptr;
     234             :     bool m_bEOF = false;
     235             :     CPLString m_osTmpFilename;
     236             :     GDALDatasetH m_hTileDS = nullptr;
     237             :     GIntBig m_nFeatureCount = -1;
     238             :     int m_nX = 0;
     239             :     int m_nY = 0;
     240             :     OGREnvelope m_sExtent;
     241             :     int m_nFilterMinX = 0;
     242             :     int m_nFilterMinY = 0;
     243             :     int m_nFilterMaxX = 0;
     244             :     int m_nFilterMaxY = 0;
     245             :     int m_nZoomLevel = 0;
     246             :     bool m_bZoomLevelAuto = false;
     247             :     bool m_bJsonField = false;
     248             : 
     249             :     OGRFeature *GetNextRawFeature();
     250             :     OGRFeature *GetNextSrcFeature();
     251             :     OGRFeature *CreateFeatureFrom(OGRFeature *poSrcFeature);
     252             : 
     253             :   public:
     254             :     MBTilesVectorLayer(MBTilesDataset *poDS, const char *pszLayerName,
     255             :                        const CPLJSONObject &oFields,
     256             :                        const CPLJSONArray &oAttributesFromTileStats,
     257             :                        bool bJsonField, double dfMinX, double dfMinY,
     258             :                        double dfMaxX, double dfMaxY,
     259             :                        OGRwkbGeometryType eGeomType,
     260             :                        bool bZoomLevelFromSpatialFilter);
     261             :     ~MBTilesVectorLayer();
     262             : 
     263             :     virtual void ResetReading() override;
     264             :     virtual OGRFeature *GetNextFeature() override;
     265             : 
     266         858 :     virtual OGRFeatureDefn *GetLayerDefn() override
     267             :     {
     268         858 :         return m_poFeatureDefn;
     269             :     }
     270             : 
     271             :     virtual GIntBig GetFeatureCount(int bForce) override;
     272             :     virtual int TestCapability(const char *) override;
     273             : 
     274             :     virtual OGRErr IGetExtent(int iGeomField, OGREnvelope *psExtent,
     275             :                               bool bForce) override;
     276             : 
     277             :     virtual OGRErr ISetSpatialFilter(int iGeomField,
     278             :                                      const OGRGeometry *poGeom) override;
     279             : 
     280             :     virtual OGRFeature *GetFeature(GIntBig nFID) override;
     281             : };
     282             : 
     283             : /************************************************************************/
     284             : /* ==================================================================== */
     285             : /*                              MBTilesBand                             */
     286             : /* ==================================================================== */
     287             : /************************************************************************/
     288             : 
     289             : class MBTilesBand final : public GDALGPKGMBTilesLikeRasterBand
     290             : {
     291             :     friend class MBTilesDataset;
     292             : 
     293             :     CPLString osLocationInfo;
     294             : 
     295             :   public:
     296             :     explicit MBTilesBand(MBTilesDataset *poDS, int nTileSize);
     297             : 
     298             :     virtual int GetOverviewCount() override;
     299             :     virtual GDALRasterBand *GetOverview(int nLevel) override;
     300             : 
     301             :     virtual char **GetMetadataDomainList() override;
     302             :     virtual const char *GetMetadataItem(const char *pszName,
     303             :                                         const char *pszDomain = "") override;
     304             : };
     305             : 
     306             : /************************************************************************/
     307             : /*                            MBTilesBand()                             */
     308             : /************************************************************************/
     309             : 
     310         734 : MBTilesBand::MBTilesBand(MBTilesDataset *poDSIn, int nTileSize)
     311         734 :     : GDALGPKGMBTilesLikeRasterBand(poDSIn, nTileSize, nTileSize)
     312             : {
     313         734 : }
     314             : 
     315             : /************************************************************************/
     316             : /*                           utf8decode()                               */
     317             : /************************************************************************/
     318             : 
     319           0 : static unsigned utf8decode(const char *p, const char *end, int *len)
     320             : {
     321           0 :     unsigned char c = *(unsigned char *)p;
     322           0 :     if (c < 0x80)
     323             :     {
     324           0 :         *len = 1;
     325           0 :         return c;
     326             :     }
     327           0 :     else if (c < 0xc2)
     328             :     {
     329           0 :         goto FAIL;
     330             :     }
     331           0 :     if (p + 1 >= end || (p[1] & 0xc0) != 0x80)
     332           0 :         goto FAIL;
     333           0 :     if (c < 0xe0)
     334             :     {
     335           0 :         *len = 2;
     336           0 :         return ((p[0] & 0x1f) << 6) + ((p[1] & 0x3f));
     337             :     }
     338           0 :     else if (c == 0xe0)
     339             :     {
     340           0 :         if (((unsigned char *)p)[1] < 0xa0)
     341           0 :             goto FAIL;
     342           0 :         goto UTF8_3;
     343             :     }
     344             : #if STRICT_RFC3629
     345             :     else if (c == 0xed)
     346             :     {
     347             :         // RFC 3629 says surrogate chars are illegal.
     348             :         if (((unsigned char *)p)[1] >= 0xa0)
     349             :             goto FAIL;
     350             :         goto UTF8_3;
     351             :     }
     352             :     else if (c == 0xef)
     353             :     {
     354             :         // 0xfffe and 0xffff are also illegal characters
     355             :         if (((unsigned char *)p)[1] == 0xbf && ((unsigned char *)p)[2] >= 0xbe)
     356             :             goto FAIL;
     357             :         goto UTF8_3;
     358             :     }
     359             : #endif
     360           0 :     else if (c < 0xf0)
     361             :     {
     362           0 :     UTF8_3:
     363           0 :         if (p + 2 >= end || (p[2] & 0xc0) != 0x80)
     364           0 :             goto FAIL;
     365           0 :         *len = 3;
     366           0 :         return ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6) + ((p[2] & 0x3f));
     367             :     }
     368           0 :     else if (c == 0xf0)
     369             :     {
     370           0 :         if (((unsigned char *)p)[1] < 0x90)
     371           0 :             goto FAIL;
     372           0 :         goto UTF8_4;
     373             :     }
     374           0 :     else if (c < 0xf4)
     375             :     {
     376           0 :     UTF8_4:
     377           0 :         if (p + 3 >= end || (p[2] & 0xc0) != 0x80 || (p[3] & 0xc0) != 0x80)
     378           0 :             goto FAIL;
     379           0 :         *len = 4;
     380             : #if STRICT_RFC3629
     381             :         // RFC 3629 says all codes ending in fffe or ffff are illegal:
     382             :         if ((p[1] & 0xf) == 0xf && ((unsigned char *)p)[2] == 0xbf &&
     383             :             ((unsigned char *)p)[3] >= 0xbe)
     384             :             goto FAIL;
     385             : #endif
     386           0 :         return ((p[0] & 0x07) << 18) + ((p[1] & 0x3f) << 12) +
     387           0 :                ((p[2] & 0x3f) << 6) + ((p[3] & 0x3f));
     388             :     }
     389           0 :     else if (c == 0xf4)
     390             :     {
     391           0 :         if (((unsigned char *)p)[1] > 0x8f)
     392           0 :             goto FAIL;  // after 0x10ffff
     393           0 :         goto UTF8_4;
     394             :     }
     395             :     else
     396             :     {
     397           0 :     FAIL:
     398           0 :         *len = 1;
     399           0 :         return 0xfffd;  // Unicode REPLACEMENT CHARACTER
     400             :     }
     401             : }
     402             : 
     403             : /************************************************************************/
     404             : /*                          HasNonEmptyGrids()                          */
     405             : /************************************************************************/
     406             : 
     407           0 : bool MBTilesDataset::HasNonEmptyGrids()
     408             : {
     409             :     OGRLayerH hSQLLyr;
     410             :     OGRFeatureH hFeat;
     411             : 
     412           0 :     if (poMainDS)
     413           0 :         return poMainDS->HasNonEmptyGrids();
     414             : 
     415           0 :     if (nHasNonEmptyGrids >= 0)
     416           0 :         return nHasNonEmptyGrids != FALSE;
     417             : 
     418           0 :     nHasNonEmptyGrids = false;
     419             : 
     420           0 :     if (GDALDatasetGetLayerByName(hDS, "grids") == nullptr)
     421           0 :         return false;
     422             : 
     423           0 :     const char *pszSQL = "SELECT type FROM sqlite_master WHERE name = 'grids'";
     424           0 :     CPLDebug("MBTILES", "%s", pszSQL);
     425           0 :     hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
     426           0 :     if (hSQLLyr == nullptr)
     427           0 :         return false;
     428             : 
     429           0 :     hFeat = OGR_L_GetNextFeature(hSQLLyr);
     430           0 :     if (hFeat == nullptr || !OGR_F_IsFieldSetAndNotNull(hFeat, 0))
     431             :     {
     432           0 :         OGR_F_Destroy(hFeat);
     433           0 :         GDALDatasetReleaseResultSet(hDS, hSQLLyr);
     434           0 :         return false;
     435             :     }
     436             : 
     437           0 :     bool bGridsIsView = strcmp(OGR_F_GetFieldAsString(hFeat, 0), "view") == 0;
     438             : 
     439           0 :     OGR_F_Destroy(hFeat);
     440           0 :     GDALDatasetReleaseResultSet(hDS, hSQLLyr);
     441             : 
     442           0 :     nHasNonEmptyGrids = TRUE;
     443             : 
     444             :     /* In the case 'grids' is a view (and a join between the 'map' and
     445             :      * 'grid_utfgrid' layers */
     446             :     /* the cost of evaluating a join is very long, even if grid_utfgrid is empty
     447             :      */
     448             :     /* so check it is not empty */
     449           0 :     if (bGridsIsView)
     450             :     {
     451             :         OGRLayerH hGridUTFGridLyr;
     452           0 :         hGridUTFGridLyr = GDALDatasetGetLayerByName(hDS, "grid_utfgrid");
     453           0 :         if (hGridUTFGridLyr != nullptr)
     454             :         {
     455           0 :             OGR_L_ResetReading(hGridUTFGridLyr);
     456           0 :             hFeat = OGR_L_GetNextFeature(hGridUTFGridLyr);
     457           0 :             OGR_F_Destroy(hFeat);
     458             : 
     459           0 :             nHasNonEmptyGrids = hFeat != nullptr;
     460             :         }
     461             :     }
     462             : 
     463           0 :     return nHasNonEmptyGrids != FALSE;
     464             : }
     465             : 
     466             : /************************************************************************/
     467             : /*                             FindKey()                                */
     468             : /************************************************************************/
     469             : 
     470           0 : char *MBTilesDataset::FindKey(int iPixel, int iLine)
     471             : {
     472             :     int nBlockXSize;
     473             :     int nBlockYSize;
     474           0 :     GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize);
     475             : 
     476             :     // Compute shift between GDAL origin and TileMatrixSet origin
     477             :     // Caution this is in GeoPackage / WMTS convention ! That is upper-left
     478             :     // corner
     479             :     const int nShiftXPixels =
     480           0 :         (int)floor(0.5 + (m_gt[0] - TMS_ORIGIN_X) / m_gt[1]);
     481             :     const int nShiftYPixelsFromGPKGOrigin =
     482           0 :         (int)floor(0.5 + (m_gt[3] - TMS_ORIGIN_Y) / m_gt[5]);
     483             : 
     484           0 :     const int iLineFromGPKGOrigin = iLine + nShiftYPixelsFromGPKGOrigin;
     485           0 :     const int iLineFromMBTilesOrigin =
     486           0 :         m_nTileMatrixHeight * nBlockYSize - 1 - iLineFromGPKGOrigin;
     487           0 :     const int iPixelFromMBTilesOrigin = iPixel + nShiftXPixels;
     488             : 
     489           0 :     const int nTileColumn = iPixelFromMBTilesOrigin / nBlockXSize;
     490           0 :     const int nTileRow = iLineFromMBTilesOrigin / nBlockYSize;
     491           0 :     int nColInTile = iPixelFromMBTilesOrigin % nBlockXSize;
     492           0 :     int nRowInTile = nBlockYSize - 1 - (iLineFromMBTilesOrigin % nBlockYSize);
     493             : 
     494           0 :     char *pszKey = nullptr;
     495             : 
     496             :     OGRLayerH hSQLLyr;
     497             :     OGRFeatureH hFeat;
     498           0 :     json_object *poGrid = nullptr;
     499             :     int i;
     500             : 
     501             :     /* See https://github.com/mapbox/utfgrid-spec/blob/master/1.0/utfgrid.md */
     502             :     /* for the explanation of the following process */
     503             :     const char *pszSQL =
     504           0 :         CPLSPrintf("SELECT grid FROM grids WHERE "
     505             :                    "zoom_level = %d AND tile_column = %d AND tile_row = %d",
     506             :                    m_nZoomLevel, nTileColumn, nTileRow);
     507           0 :     CPLDebug("MBTILES", "%s", pszSQL);
     508           0 :     hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
     509           0 :     if (hSQLLyr == nullptr)
     510           0 :         return nullptr;
     511             : 
     512           0 :     hFeat = OGR_L_GetNextFeature(hSQLLyr);
     513           0 :     if (hFeat == nullptr || !OGR_F_IsFieldSetAndNotNull(hFeat, 0))
     514             :     {
     515           0 :         OGR_F_Destroy(hFeat);
     516           0 :         GDALDatasetReleaseResultSet(hDS, hSQLLyr);
     517           0 :         return nullptr;
     518             :     }
     519             : 
     520           0 :     int nDataSize = 0;
     521           0 :     GByte *pabyData = OGR_F_GetFieldAsBinary(hFeat, 0, &nDataSize);
     522             : 
     523           0 :     int nUncompressedSize = nBlockXSize * nBlockYSize;
     524           0 :     GByte *pabyUncompressed = (GByte *)VSIMalloc(nUncompressedSize + 1);
     525           0 :     if (pabyUncompressed == nullptr)
     526             :     {
     527           0 :         OGR_F_Destroy(hFeat);
     528           0 :         GDALDatasetReleaseResultSet(hDS, hSQLLyr);
     529           0 :         return nullptr;
     530             :     }
     531             : 
     532             :     z_stream sStream;
     533           0 :     memset(&sStream, 0, sizeof(sStream));
     534           0 :     if (inflateInit(&sStream) != Z_OK)
     535             :     {
     536           0 :         OGR_F_Destroy(hFeat);
     537           0 :         GDALDatasetReleaseResultSet(hDS, hSQLLyr);
     538           0 :         CPLFree(pabyUncompressed);
     539           0 :         return nullptr;
     540             :     }
     541           0 :     sStream.next_in = pabyData;
     542           0 :     sStream.avail_in = nDataSize;
     543           0 :     sStream.next_out = pabyUncompressed;
     544           0 :     sStream.avail_out = nUncompressedSize;
     545           0 :     int nStatus = inflate(&sStream, Z_FINISH);
     546           0 :     inflateEnd(&sStream);
     547           0 :     if (nStatus != Z_OK && nStatus != Z_STREAM_END)
     548             :     {
     549           0 :         CPLDebug("MBTILES", "Error unzipping grid");
     550           0 :         nUncompressedSize = 0;
     551           0 :         pabyUncompressed[nUncompressedSize] = 0;
     552             :     }
     553             :     else
     554             :     {
     555           0 :         nUncompressedSize -= sStream.avail_out;
     556           0 :         pabyUncompressed[nUncompressedSize] = 0;
     557             :         // CPLDebug("MBTILES", "Grid size = %d", nUncompressedSize);
     558             :         // CPLDebug("MBTILES", "Grid value = %s", (const
     559             :         // char*)pabyUncompressed);
     560             :     }
     561             : 
     562           0 :     json_object *jsobj = nullptr;
     563             : 
     564           0 :     if (nUncompressedSize == 0)
     565             :     {
     566           0 :         goto end;
     567             :     }
     568             : 
     569           0 :     if (!OGRJSonParse((const char *)pabyUncompressed, &jsobj, true))
     570             :     {
     571           0 :         goto end;
     572             :     }
     573             : 
     574           0 :     if (json_object_is_type(jsobj, json_type_object))
     575             :     {
     576           0 :         poGrid = CPL_json_object_object_get(jsobj, "grid");
     577             :     }
     578           0 :     if (poGrid != nullptr && json_object_is_type(poGrid, json_type_array))
     579             :     {
     580             :         int nFactor;
     581             :         json_object *poRow;
     582           0 :         char *pszRow = nullptr;
     583             : 
     584           0 :         const int nLines = static_cast<int>(json_object_array_length(poGrid));
     585           0 :         if (nLines == 0)
     586           0 :             goto end;
     587             : 
     588           0 :         nFactor = nBlockXSize / nLines;
     589           0 :         nRowInTile /= nFactor;
     590           0 :         nColInTile /= nFactor;
     591             : 
     592           0 :         poRow = json_object_array_get_idx(poGrid, nRowInTile);
     593             : 
     594             :         /* Extract line of interest in grid */
     595           0 :         if (poRow != nullptr && json_object_is_type(poRow, json_type_string))
     596             :         {
     597           0 :             pszRow = CPLStrdup(json_object_get_string(poRow));
     598             :         }
     599             : 
     600           0 :         if (pszRow == nullptr)
     601           0 :             goto end;
     602             : 
     603             :         /* Unapply JSON encoding */
     604           0 :         for (i = 0; pszRow[i] != '\0'; i++)
     605             :         {
     606           0 :             unsigned char c = ((GByte *)pszRow)[i];
     607           0 :             if (c >= 93)
     608           0 :                 c--;
     609           0 :             if (c >= 35)
     610           0 :                 c--;
     611           0 :             if (c < 32)
     612             :             {
     613           0 :                 CPLDebug("MBTILES", "Invalid character at byte %d", i);
     614           0 :                 break;
     615             :             }
     616           0 :             c -= 32;
     617           0 :             ((GByte *)pszRow)[i] = c;
     618             :         }
     619             : 
     620           0 :         if (pszRow[i] == '\0')
     621             :         {
     622           0 :             char *pszEnd = pszRow + i;
     623             : 
     624           0 :             int iCol = 0;
     625           0 :             i = 0;
     626           0 :             int nKey = -1;
     627           0 :             while (pszRow + i < pszEnd)
     628             :             {
     629           0 :                 int len = 0;
     630           0 :                 unsigned int res = utf8decode(pszRow + i, pszEnd, &len);
     631             : 
     632             :                 /* Invalid UTF8 ? */
     633           0 :                 if (res > 127 && len == 1)
     634           0 :                     break;
     635             : 
     636           0 :                 if (iCol == nColInTile)
     637             :                 {
     638           0 :                     nKey = (int)res;
     639             :                     // CPLDebug("MBTILES", "Key index = %d", nKey);
     640           0 :                     break;
     641             :                 }
     642           0 :                 i += len;
     643           0 :                 iCol++;
     644             :             }
     645             : 
     646             :             /* Find key */
     647           0 :             json_object *poKeys = CPL_json_object_object_get(jsobj, "keys");
     648           0 :             if (nKey >= 0 && poKeys != nullptr &&
     649           0 :                 json_object_is_type(poKeys, json_type_array) &&
     650           0 :                 nKey < static_cast<int>(json_object_array_length(poKeys)))
     651             :             {
     652           0 :                 json_object *poKey = json_object_array_get_idx(poKeys, nKey);
     653           0 :                 if (poKey != nullptr &&
     654           0 :                     json_object_is_type(poKey, json_type_string))
     655             :                 {
     656           0 :                     pszKey = CPLStrdup(json_object_get_string(poKey));
     657             :                 }
     658             :             }
     659             :         }
     660             : 
     661           0 :         CPLFree(pszRow);
     662             :     }
     663             : 
     664           0 : end:
     665           0 :     if (jsobj)
     666           0 :         json_object_put(jsobj);
     667           0 :     VSIFree(pabyUncompressed);
     668           0 :     if (hFeat)
     669           0 :         OGR_F_Destroy(hFeat);
     670           0 :     if (hSQLLyr)
     671           0 :         GDALDatasetReleaseResultSet(hDS, hSQLLyr);
     672             : 
     673           0 :     return pszKey;
     674             : }
     675             : 
     676             : /************************************************************************/
     677             : /*                      GetMetadataDomainList()                         */
     678             : /************************************************************************/
     679             : 
     680           0 : char **MBTilesBand::GetMetadataDomainList()
     681             : {
     682           0 :     return CSLAddString(GDALPamRasterBand::GetMetadataDomainList(),
     683           0 :                         "LocationInfo");
     684             : }
     685             : 
     686             : /************************************************************************/
     687             : /*                         GetMetadataItem()                            */
     688             : /************************************************************************/
     689             : 
     690          42 : const char *MBTilesBand::GetMetadataItem(const char *pszName,
     691             :                                          const char *pszDomain)
     692             : {
     693          42 :     MBTilesDataset *poGDS = (MBTilesDataset *)poDS;
     694             : 
     695             :     /* ==================================================================== */
     696             :     /*      LocationInfo handling.                                          */
     697             :     /* ==================================================================== */
     698          42 :     if (poGDS->hDS != nullptr && pszDomain != nullptr &&
     699          20 :         EQUAL(pszDomain, "LocationInfo") &&
     700           0 :         (STARTS_WITH_CI(pszName, "Pixel_") ||
     701           0 :          STARTS_WITH_CI(pszName, "GeoPixel_")))
     702             :     {
     703             :         int iPixel, iLine;
     704             : 
     705           0 :         if (!poGDS->HasNonEmptyGrids())
     706           0 :             return nullptr;
     707             : 
     708             :         /* --------------------------------------------------------------------
     709             :          */
     710             :         /*      What pixel are we aiming at? */
     711             :         /* --------------------------------------------------------------------
     712             :          */
     713           0 :         if (STARTS_WITH_CI(pszName, "Pixel_"))
     714             :         {
     715           0 :             if (sscanf(pszName + 6, "%d_%d", &iPixel, &iLine) != 2)
     716           0 :                 return nullptr;
     717             :         }
     718           0 :         else if (STARTS_WITH_CI(pszName, "GeoPixel_"))
     719             :         {
     720           0 :             GDALGeoTransform gt;
     721           0 :             GDALGeoTransform invGT;
     722             :             double dfGeoX, dfGeoY;
     723             : 
     724           0 :             dfGeoX = CPLAtof(pszName + 9);
     725           0 :             const char *pszUnderscore = strchr(pszName + 9, '_');
     726           0 :             if (!pszUnderscore)
     727           0 :                 return nullptr;
     728           0 :             dfGeoY = CPLAtof(pszUnderscore + 1);
     729             : 
     730           0 :             if (GetDataset() == nullptr)
     731           0 :                 return nullptr;
     732             : 
     733           0 :             if (GetDataset()->GetGeoTransform(gt) != CE_None)
     734           0 :                 return nullptr;
     735             : 
     736           0 :             if (!GDALInvGeoTransform(gt.data(), invGT.data()))
     737           0 :                 return nullptr;
     738             : 
     739           0 :             iPixel =
     740           0 :                 (int)floor(invGT[0] + invGT[1] * dfGeoX + invGT[2] * dfGeoY);
     741           0 :             iLine =
     742           0 :                 (int)floor(invGT[3] + invGT[4] * dfGeoX + invGT[5] * dfGeoY);
     743             :         }
     744             :         else
     745           0 :             return nullptr;
     746             : 
     747           0 :         if (iPixel < 0 || iLine < 0 || iPixel >= GetXSize() ||
     748           0 :             iLine >= GetYSize())
     749           0 :             return nullptr;
     750             : 
     751           0 :         char *pszKey = poGDS->FindKey(iPixel, iLine);
     752             : 
     753           0 :         if (pszKey != nullptr)
     754             :         {
     755             :             // CPLDebug("MBTILES", "Key = %s", pszKey);
     756             : 
     757           0 :             osLocationInfo = "<LocationInfo>";
     758           0 :             osLocationInfo += "<Key>";
     759             :             char *pszXMLEscaped =
     760           0 :                 CPLEscapeString(pszKey, -1, CPLES_XML_BUT_QUOTES);
     761           0 :             osLocationInfo += pszXMLEscaped;
     762           0 :             CPLFree(pszXMLEscaped);
     763           0 :             osLocationInfo += "</Key>";
     764             : 
     765           0 :             if (GDALDatasetGetLayerByName(poGDS->hDS, "grid_data") != nullptr &&
     766           0 :                 strchr(pszKey, '\'') == nullptr)
     767             :             {
     768             :                 OGRLayerH hSQLLyr;
     769             :                 OGRFeatureH hFeat;
     770             : 
     771             :                 const char *pszSQL =
     772           0 :                     CPLSPrintf("SELECT key_json FROM keymap WHERE "
     773             :                                "key_name = '%s'",
     774             :                                pszKey);
     775           0 :                 CPLDebug("MBTILES", "%s", pszSQL);
     776             :                 hSQLLyr =
     777           0 :                     GDALDatasetExecuteSQL(poGDS->hDS, pszSQL, nullptr, nullptr);
     778           0 :                 if (hSQLLyr)
     779             :                 {
     780           0 :                     hFeat = OGR_L_GetNextFeature(hSQLLyr);
     781           0 :                     if (hFeat != nullptr &&
     782           0 :                         OGR_F_IsFieldSetAndNotNull(hFeat, 0))
     783             :                     {
     784           0 :                         const char *pszJSon = OGR_F_GetFieldAsString(hFeat, 0);
     785             :                         // CPLDebug("MBTILES", "JSon = %s", pszJSon);
     786             : 
     787           0 :                         osLocationInfo += "<JSon>";
     788             : #ifdef CPLES_XML_BUT_QUOTES
     789             :                         pszXMLEscaped =
     790           0 :                             CPLEscapeString(pszJSon, -1, CPLES_XML_BUT_QUOTES);
     791             : #else
     792             :                         pszXMLEscaped = CPLEscapeString(pszJSon, -1, CPLES_XML);
     793             : #endif
     794           0 :                         osLocationInfo += pszXMLEscaped;
     795           0 :                         CPLFree(pszXMLEscaped);
     796           0 :                         osLocationInfo += "</JSon>";
     797             :                     }
     798           0 :                     OGR_F_Destroy(hFeat);
     799             :                 }
     800           0 :                 GDALDatasetReleaseResultSet(poGDS->hDS, hSQLLyr);
     801             :             }
     802             : 
     803           0 :             osLocationInfo += "</LocationInfo>";
     804             : 
     805           0 :             CPLFree(pszKey);
     806             : 
     807           0 :             return osLocationInfo.c_str();
     808             :         }
     809             : 
     810           0 :         return nullptr;
     811             :     }
     812             :     else
     813          42 :         return GDALPamRasterBand::GetMetadataItem(pszName, pszDomain);
     814             : }
     815             : 
     816             : /************************************************************************/
     817             : /*                         GetOverviewCount()                           */
     818             : /************************************************************************/
     819             : 
     820           6 : int MBTilesBand::GetOverviewCount()
     821             : {
     822           6 :     MBTilesDataset *poGDS = (MBTilesDataset *)poDS;
     823             : 
     824           6 :     if (poGDS->m_nOverviewCount >= 1)
     825           5 :         return poGDS->m_nOverviewCount;
     826             :     else
     827           1 :         return GDALPamRasterBand::GetOverviewCount();
     828             : }
     829             : 
     830             : /************************************************************************/
     831             : /*                              GetOverview()                           */
     832             : /************************************************************************/
     833             : 
     834           7 : GDALRasterBand *MBTilesBand::GetOverview(int nLevel)
     835             : {
     836           7 :     MBTilesDataset *poGDS = (MBTilesDataset *)poDS;
     837             : 
     838           7 :     if (poGDS->m_nOverviewCount == 0)
     839           0 :         return GDALPamRasterBand::GetOverview(nLevel);
     840             : 
     841           7 :     if (nLevel < 0 || nLevel >= poGDS->m_nOverviewCount)
     842           0 :         return nullptr;
     843             : 
     844           7 :     GDALDataset *poOvrDS = poGDS->m_papoOverviewDS[nLevel];
     845           7 :     if (poOvrDS)
     846           7 :         return poOvrDS->GetRasterBand(nBand);
     847             :     else
     848           0 :         return nullptr;
     849             : }
     850             : 
     851             : /************************************************************************/
     852             : /*                         MBTilesDataset()                          */
     853             : /************************************************************************/
     854             : 
     855         276 : MBTilesDataset::MBTilesDataset()
     856             : {
     857         276 :     m_bWriteBounds = true;
     858         276 :     m_bWriteMinMaxZoom = true;
     859         276 :     poMainDS = nullptr;
     860         276 :     m_nOverviewCount = 0;
     861         276 :     hDS = nullptr;
     862         276 :     m_papoOverviewDS = nullptr;
     863         276 :     bFetchedMetadata = false;
     864         276 :     nHasNonEmptyGrids = -1;
     865         276 :     hDB = nullptr;
     866         276 :     pMyVFS = nullptr;
     867             : 
     868         276 :     m_bGeoTransformValid = false;
     869         276 :     m_bInFlushCache = false;
     870             : 
     871         276 :     m_osRasterTable = "tiles";
     872         276 :     m_eTF = GPKG_TF_PNG;
     873             : 
     874         276 :     m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     875         276 :     m_oSRS.importFromEPSG(3857);
     876         276 : }
     877             : 
     878             : /************************************************************************/
     879             : /*                        ~MBTilesDataset()                             */
     880             : /************************************************************************/
     881             : 
     882         552 : MBTilesDataset::~MBTilesDataset()
     883             : {
     884             :     // Need to explicitly clear it before close hDS
     885         276 :     m_apoLayers.clear();
     886             : 
     887         276 :     FlushCache(true);
     888             : 
     889         276 :     if (poMainDS == nullptr)
     890             :     {
     891         101 :         if (m_papoOverviewDS)
     892             :         {
     893         235 :             for (int i = 0; i < m_nOverviewCount; i++)
     894         175 :                 delete m_papoOverviewDS[i];
     895          60 :             CPLFree(m_papoOverviewDS);
     896             :         }
     897             : 
     898         101 :         if (hDS != nullptr)
     899             :         {
     900          60 :             GDALClose(hDS);
     901          60 :             hDB = nullptr;
     902             :         }
     903         101 :         if (hDB != nullptr)
     904             :         {
     905          41 :             sqlite3_close(hDB);
     906             : 
     907          41 :             if (pMyVFS)
     908             :             {
     909          23 :                 sqlite3_vfs_unregister(pMyVFS);
     910          23 :                 CPLFree(pMyVFS->pAppData);
     911          23 :                 CPLFree(pMyVFS);
     912             :             }
     913             :         }
     914             :     }
     915             : 
     916         276 :     if (!m_osMetadataMemFilename.empty())
     917             :     {
     918          32 :         VSIUnlink(m_osMetadataMemFilename);
     919             :     }
     920         552 : }
     921             : 
     922             : /************************************************************************/
     923             : /*                         IStartTransaction()                          */
     924             : /************************************************************************/
     925             : 
     926          24 : OGRErr MBTilesDataset::IStartTransaction()
     927             : {
     928          24 :     char *pszErrMsg = nullptr;
     929          24 :     const int rc = sqlite3_exec(hDB, "BEGIN", nullptr, nullptr, &pszErrMsg);
     930          24 :     if (rc != SQLITE_OK)
     931             :     {
     932           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s transaction failed: %s",
     933             :                  "BEGIN", pszErrMsg);
     934           0 :         sqlite3_free(pszErrMsg);
     935           0 :         return OGRERR_FAILURE;
     936             :     }
     937             : 
     938          24 :     return OGRERR_NONE;
     939             : }
     940             : 
     941             : /************************************************************************/
     942             : /*                         ICommitTransaction()                         */
     943             : /************************************************************************/
     944             : 
     945          24 : OGRErr MBTilesDataset::ICommitTransaction()
     946             : {
     947          24 :     char *pszErrMsg = nullptr;
     948          24 :     const int rc = sqlite3_exec(hDB, "COMMIT", nullptr, nullptr, &pszErrMsg);
     949          24 :     if (rc != SQLITE_OK)
     950             :     {
     951           0 :         CPLError(CE_Failure, CPLE_AppDefined, "%s transaction failed: %s",
     952             :                  "COMMIT", pszErrMsg);
     953           0 :         sqlite3_free(pszErrMsg);
     954           0 :         return OGRERR_FAILURE;
     955             :     }
     956             : 
     957          24 :     return OGRERR_NONE;
     958             : }
     959             : 
     960             : /************************************************************************/
     961             : /*                         ICanIWriteBlock()                            */
     962             : /************************************************************************/
     963             : 
     964         155 : bool MBTilesDataset::ICanIWriteBlock()
     965             : {
     966         155 :     if (eAccess != GA_Update)
     967             :     {
     968           0 :         CPLError(
     969             :             CE_Failure, CPLE_NotSupported,
     970             :             "IWriteBlock() not supported on dataset opened in read-only mode");
     971           0 :         return false;
     972             :     }
     973             : 
     974         155 :     if (!m_bGeoTransformValid)
     975             :     {
     976           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     977             :                  "IWriteBlock() not supported if georeferencing not set");
     978           0 :         return false;
     979             :     }
     980         155 :     return true;
     981             : }
     982             : 
     983             : /************************************************************************/
     984             : /*                         IFlushCacheWithErrCode()                     */
     985             : /************************************************************************/
     986             : 
     987        3240 : CPLErr MBTilesDataset::IFlushCacheWithErrCode(bool bAtClosing)
     988             : 
     989             : {
     990        3240 :     if (m_bInFlushCache)
     991        2474 :         return CE_None;
     992         766 :     m_bInFlushCache = true;
     993             :     // Short circuit GDALPamDataset to avoid serialization to .aux.xml
     994         766 :     GDALDataset::FlushCache(bAtClosing);
     995             : 
     996         766 :     CPLErr eErr = FlushTiles();
     997             : 
     998         766 :     m_bInFlushCache = false;
     999         766 :     return eErr;
    1000             : }
    1001             : 
    1002             : /************************************************************************/
    1003             : /*                         ICanIWriteBlock()                            */
    1004             : /************************************************************************/
    1005             : 
    1006         546 : int MBTilesDataset::GetRowFromIntoTopConvention(int nRow)
    1007             : {
    1008         546 :     return m_nTileMatrixHeight - 1 - nRow;
    1009             : }
    1010             : 
    1011             : /************************************************************************/
    1012             : /*                          GetGeoTransform()                           */
    1013             : /************************************************************************/
    1014             : 
    1015          31 : CPLErr MBTilesDataset::GetGeoTransform(GDALGeoTransform &gt) const
    1016             : {
    1017          31 :     gt = m_gt;
    1018          31 :     return (m_bGeoTransformValid) ? CE_None : CE_Failure;
    1019             : }
    1020             : 
    1021             : /************************************************************************/
    1022             : /*                     SphericalMercatorToLongLat()                     */
    1023             : /************************************************************************/
    1024             : 
    1025          69 : static void SphericalMercatorToLongLat(double *x, double *y)
    1026             : {
    1027          69 :     double lng = *x / SPHERICAL_RADIUS / M_PI * 180;
    1028          69 :     double lat = 2 * (atan(exp(*y / SPHERICAL_RADIUS)) - M_PI / 4) / M_PI * 180;
    1029          69 :     *x = lng;
    1030          69 :     *y = lat;
    1031          69 : }
    1032             : 
    1033             : /************************************************************************/
    1034             : /*                     LongLatToSphericalMercator()                     */
    1035             : /************************************************************************/
    1036             : 
    1037         112 : static void LongLatToSphericalMercator(double *x, double *y)
    1038             : {
    1039         112 :     double X = SPHERICAL_RADIUS * (*x) / 180 * M_PI;
    1040         112 :     double Y = SPHERICAL_RADIUS * log(tan(M_PI / 4 + 0.5 * (*y) / 180 * M_PI));
    1041         112 :     *x = X;
    1042         112 :     *y = Y;
    1043         112 : }
    1044             : 
    1045             : /************************************************************************/
    1046             : /*                          SetGeoTransform()                           */
    1047             : /************************************************************************/
    1048             : 
    1049          28 : CPLErr MBTilesDataset::SetGeoTransform(const GDALGeoTransform &gt)
    1050             : {
    1051          28 :     if (eAccess != GA_Update)
    1052             :     {
    1053           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    1054             :                  "SetGeoTransform() not supported on read-only dataset");
    1055           1 :         return CE_Failure;
    1056             :     }
    1057          27 :     if (m_bGeoTransformValid)
    1058             :     {
    1059           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    1060             :                  "Cannot modify geotransform once set");
    1061           1 :         return CE_Failure;
    1062             :     }
    1063          26 :     if (gt[2] != 0.0 || gt[4] != 0 || gt[5] > 0.0)
    1064             :     {
    1065           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    1066             :                  "Only north-up non rotated geotransform supported");
    1067           1 :         return CE_Failure;
    1068             :     }
    1069             : 
    1070          25 :     if (m_bWriteBounds)
    1071             :     {
    1072          46 :         CPLString osBounds(m_osBounds);
    1073          23 :         if (osBounds.empty())
    1074             :         {
    1075          23 :             double minx = gt[0];
    1076          23 :             double miny = gt[3] + nRasterYSize * gt[5];
    1077          23 :             double maxx = gt[0] + nRasterXSize * gt[1];
    1078          23 :             double maxy = gt[3];
    1079             : 
    1080          23 :             SphericalMercatorToLongLat(&minx, &miny);
    1081          23 :             SphericalMercatorToLongLat(&maxx, &maxy);
    1082          23 :             if (fabs(minx + 180) < 1e-7)
    1083             :             {
    1084           3 :                 minx = -180.0;
    1085             :             }
    1086          23 :             if (fabs(maxx - 180) < 1e-7)
    1087             :             {
    1088           3 :                 maxx = 180.0;
    1089             :             }
    1090             : 
    1091             :             // Clamp latitude so that when transformed back to EPSG:3857, we
    1092             :             // don't have too big northings
    1093          23 :             double tmpx = 0.0;
    1094          23 :             double ok_maxy = MAX_GM;
    1095          23 :             SphericalMercatorToLongLat(&tmpx, &ok_maxy);
    1096          23 :             if (maxy > ok_maxy)
    1097           0 :                 maxy = ok_maxy;
    1098          23 :             if (miny < -ok_maxy)
    1099           0 :                 miny = -ok_maxy;
    1100             : 
    1101          23 :             osBounds.Printf("%.17g,%.17g,%.17g,%.17g", minx, miny, maxx, maxy);
    1102             :         }
    1103             : 
    1104          23 :         char *pszSQL = sqlite3_mprintf(
    1105             :             "INSERT INTO metadata (name, value) VALUES ('bounds', '%q')",
    1106             :             osBounds.c_str());
    1107          23 :         sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
    1108          23 :         sqlite3_free(pszSQL);
    1109             : 
    1110          23 :         if (!m_osCenter.empty())
    1111             :         {
    1112           0 :             pszSQL = sqlite3_mprintf(
    1113             :                 "INSERT INTO metadata (name, value) VALUES ('center', '%q')",
    1114             :                 m_osCenter.c_str());
    1115           0 :             sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
    1116           0 :             sqlite3_free(pszSQL);
    1117             :         }
    1118             :     }
    1119             : 
    1120             :     int nBlockXSize;
    1121             :     int nBlockYSize;
    1122          25 :     GetRasterBand(1)->GetBlockSize(&nBlockXSize, &nBlockYSize);
    1123          25 :     const double dfPixelXSizeZoomLevel0 = 2 * MAX_GM / nBlockXSize;
    1124          25 :     const double dfPixelYSizeZoomLevel0 = 2 * MAX_GM / nBlockYSize;
    1125         181 :     for (m_nZoomLevel = 0; m_nZoomLevel < 25; m_nZoomLevel++)
    1126             :     {
    1127         180 :         double dfExpectedPixelXSize =
    1128         180 :             dfPixelXSizeZoomLevel0 / (1 << m_nZoomLevel);
    1129         180 :         double dfExpectedPixelYSize =
    1130         180 :             dfPixelYSizeZoomLevel0 / (1 << m_nZoomLevel);
    1131         204 :         if (fabs(gt[1] - dfExpectedPixelXSize) < 1e-8 * dfExpectedPixelXSize &&
    1132          24 :             fabs(fabs(gt[5]) - dfExpectedPixelYSize) <
    1133          24 :                 1e-8 * dfExpectedPixelYSize)
    1134             :         {
    1135          24 :             break;
    1136             :         }
    1137             :     }
    1138          25 :     if (m_nZoomLevel == 25)
    1139             :     {
    1140           1 :         m_nZoomLevel = -1;
    1141           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    1142             :                  "Could not find an appropriate zoom level that matches raster "
    1143             :                  "pixel size");
    1144           1 :         return CE_Failure;
    1145             :     }
    1146             : 
    1147          24 :     m_gt = gt;
    1148          24 :     m_bGeoTransformValid = true;
    1149             : 
    1150          24 :     return FinalizeRasterRegistration();
    1151             : }
    1152             : 
    1153             : /************************************************************************/
    1154             : /*                      ComputeTileAndPixelShifts()                     */
    1155             : /************************************************************************/
    1156             : 
    1157         259 : void MBTilesDataset::ComputeTileAndPixelShifts()
    1158             : {
    1159             :     int nTileWidth, nTileHeight;
    1160         259 :     GetRasterBand(1)->GetBlockSize(&nTileWidth, &nTileHeight);
    1161             : 
    1162             :     // Compute shift between GDAL origin and TileMatrixSet origin
    1163             :     // Caution this is in GeoPackage / WMTS convention ! That is upper-left
    1164             :     // corner
    1165         259 :     int nShiftXPixels = (int)floor(0.5 + (m_gt[0] - TMS_ORIGIN_X) / m_gt[1]);
    1166         259 :     m_nShiftXTiles = (int)floor(1.0 * nShiftXPixels / nTileWidth);
    1167         259 :     m_nShiftXPixelsMod =
    1168         259 :         ((nShiftXPixels % nTileWidth) + nTileWidth) % nTileWidth;
    1169         259 :     int nShiftYPixels = (int)floor(0.5 + (m_gt[3] - TMS_ORIGIN_Y) / m_gt[5]);
    1170         259 :     m_nShiftYTiles = (int)floor(1.0 * nShiftYPixels / nTileHeight);
    1171         259 :     m_nShiftYPixelsMod =
    1172         259 :         ((nShiftYPixels % nTileHeight) + nTileHeight) % nTileHeight;
    1173         259 : }
    1174             : 
    1175             : /************************************************************************/
    1176             : /*                      FinalizeRasterRegistration()                    */
    1177             : /************************************************************************/
    1178             : 
    1179          24 : CPLErr MBTilesDataset::FinalizeRasterRegistration()
    1180             : {
    1181          24 :     m_nTileMatrixWidth = (1 << m_nZoomLevel);
    1182          24 :     m_nTileMatrixHeight = (1 << m_nZoomLevel);
    1183             : 
    1184          24 :     ComputeTileAndPixelShifts();
    1185             : 
    1186          24 :     double dfGDALMinX = m_gt[0];
    1187          24 :     double dfGDALMinY = m_gt[3] + nRasterYSize * m_gt[5];
    1188          24 :     double dfGDALMaxX = m_gt[0] + nRasterXSize * m_gt[1];
    1189          24 :     double dfGDALMaxY = m_gt[3];
    1190             : 
    1191          24 :     m_nOverviewCount = m_nZoomLevel;
    1192          48 :     m_papoOverviewDS = (MBTilesDataset **)CPLCalloc(sizeof(MBTilesDataset *),
    1193          24 :                                                     m_nOverviewCount);
    1194             : 
    1195          24 :     if (m_bWriteMinMaxZoom)
    1196             :     {
    1197          24 :         char *pszSQL = sqlite3_mprintf(
    1198             :             "INSERT INTO metadata (name, value) VALUES ('minzoom', '%d')",
    1199             :             m_nZoomLevel);
    1200          24 :         sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
    1201          24 :         sqlite3_free(pszSQL);
    1202          24 :         pszSQL = sqlite3_mprintf(
    1203             :             "INSERT INTO metadata (name, value) VALUES ('maxzoom', '%d')",
    1204             :             m_nZoomLevel);
    1205          24 :         sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
    1206          24 :         sqlite3_free(pszSQL);
    1207             :     }
    1208             : 
    1209         155 :     for (int i = 0; i < m_nOverviewCount; i++)
    1210             :     {
    1211         131 :         MBTilesDataset *poOvrDS = new MBTilesDataset();
    1212         131 :         poOvrDS->ShareLockWithParentDataset(this);
    1213             :         int nBlockSize;
    1214         131 :         GetRasterBand(1)->GetBlockSize(&nBlockSize, &nBlockSize);
    1215         131 :         poOvrDS->InitRaster(this, i, nBands, nBlockSize, dfGDALMinX, dfGDALMinY,
    1216             :                             dfGDALMaxX, dfGDALMaxY);
    1217             : 
    1218         131 :         m_papoOverviewDS[m_nZoomLevel - 1 - i] = poOvrDS;
    1219             :     }
    1220             : 
    1221          24 :     return CE_None;
    1222             : }
    1223             : 
    1224             : /************************************************************************/
    1225             : /*                         InitRaster()                                 */
    1226             : /************************************************************************/
    1227             : 
    1228         235 : bool MBTilesDataset::InitRaster(MBTilesDataset *poParentDS, int nZoomLevel,
    1229             :                                 int nBandCount, int nTileSize,
    1230             :                                 double dfGDALMinX, double dfGDALMinY,
    1231             :                                 double dfGDALMaxX, double dfGDALMaxY)
    1232             : {
    1233         235 :     m_nZoomLevel = nZoomLevel;
    1234         235 :     m_nTileMatrixWidth = 1 << nZoomLevel;
    1235         235 :     m_nTileMatrixHeight = 1 << nZoomLevel;
    1236             : 
    1237         235 :     const int nTileWidth = nTileSize;
    1238         235 :     const int nTileHeight = nTileSize;
    1239         235 :     const double dfPixelXSize = 2 * MAX_GM / nTileWidth / (1 << nZoomLevel);
    1240         235 :     const double dfPixelYSize = 2 * MAX_GM / nTileHeight / (1 << nZoomLevel);
    1241             : 
    1242         235 :     m_bGeoTransformValid = true;
    1243         235 :     m_gt[0] = dfGDALMinX;
    1244         235 :     m_gt[1] = dfPixelXSize;
    1245         235 :     m_gt[3] = dfGDALMaxY;
    1246         235 :     m_gt[5] = -dfPixelYSize;
    1247         235 :     double dfRasterXSize = 0.5 + (dfGDALMaxX - dfGDALMinX) / dfPixelXSize;
    1248         235 :     double dfRasterYSize = 0.5 + (dfGDALMaxY - dfGDALMinY) / dfPixelYSize;
    1249         235 :     if (dfRasterXSize > INT_MAX || dfRasterYSize > INT_MAX)
    1250           0 :         return false;
    1251         235 :     nRasterXSize = (int)dfRasterXSize;
    1252         235 :     nRasterYSize = (int)dfRasterYSize;
    1253             : 
    1254         235 :     m_pabyCachedTiles =
    1255         235 :         (GByte *)VSI_MALLOC3_VERBOSE(4 * 4, nTileWidth, nTileHeight);
    1256         235 :     if (m_pabyCachedTiles == nullptr)
    1257             :     {
    1258           0 :         return false;
    1259             :     }
    1260             : 
    1261         235 :     if (poParentDS)
    1262             :     {
    1263         175 :         eAccess = poParentDS->eAccess;
    1264             :     }
    1265             : 
    1266         914 :     for (int i = 1; i <= nBandCount; i++)
    1267         679 :         SetBand(i, new MBTilesBand(this, nTileSize));
    1268             : 
    1269         235 :     ComputeTileAndPixelShifts();
    1270             : 
    1271         235 :     GDALDataset::SetMetadataItem("INTERLEAVE", "PIXEL", "IMAGE_STRUCTURE");
    1272         235 :     GDALDataset::SetMetadataItem("ZOOM_LEVEL", CPLSPrintf("%d", m_nZoomLevel));
    1273             : 
    1274         235 :     if (poParentDS)
    1275             :     {
    1276         175 :         m_poParentDS = poParentDS;
    1277         175 :         poMainDS = poParentDS;
    1278         175 :         hDS = poParentDS->hDS;
    1279         175 :         hDB = poParentDS->hDB;
    1280         175 :         m_eTF = poParentDS->m_eTF;
    1281         175 :         m_nQuality = poParentDS->m_nQuality;
    1282         175 :         m_nZLevel = poParentDS->m_nZLevel;
    1283         175 :         m_bDither = poParentDS->m_bDither;
    1284         175 :         m_osWHERE = poParentDS->m_osWHERE;
    1285         175 :         SetDescription(CPLSPrintf("%s - zoom_level=%d",
    1286         175 :                                   poParentDS->GetDescription(), m_nZoomLevel));
    1287             :     }
    1288             : 
    1289         235 :     return true;
    1290             : }
    1291             : 
    1292             : /************************************************************************/
    1293             : /*                         GetSpatialRef()                              */
    1294             : /************************************************************************/
    1295             : 
    1296           3 : const OGRSpatialReference *MBTilesDataset::GetSpatialRef() const
    1297             : {
    1298           3 :     return &m_oSRS;
    1299             : }
    1300             : 
    1301             : /************************************************************************/
    1302             : /*                           SetSpatialRef()                            */
    1303             : /************************************************************************/
    1304             : 
    1305           3 : CPLErr MBTilesDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
    1306             : {
    1307           3 :     if (eAccess != GA_Update)
    1308             :     {
    1309           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    1310             :                  "SetSpatialRef() not supported on read-only dataset");
    1311           1 :         return CE_Failure;
    1312             :     }
    1313             : 
    1314           2 :     if (poSRS == nullptr || poSRS->GetAuthorityName(nullptr) == nullptr ||
    1315           1 :         !EQUAL(poSRS->GetAuthorityName(nullptr), "EPSG") ||
    1316           5 :         poSRS->GetAuthorityCode(nullptr) == nullptr ||
    1317           1 :         !EQUAL(poSRS->GetAuthorityCode(nullptr), "3857"))
    1318             :     {
    1319           1 :         CPLError(CE_Failure, CPLE_NotSupported,
    1320             :                  "Only EPSG:3857 supported on MBTiles dataset");
    1321           1 :         return CE_Failure;
    1322             :     }
    1323           1 :     return CE_None;
    1324             : }
    1325             : 
    1326             : /************************************************************************/
    1327             : /*                      GetMetadataDomainList()                         */
    1328             : /************************************************************************/
    1329             : 
    1330           0 : char **MBTilesDataset::GetMetadataDomainList()
    1331             : {
    1332           0 :     return BuildMetadataDomainList(GDALDataset::GetMetadataDomainList(), TRUE,
    1333           0 :                                    "", nullptr);
    1334             : }
    1335             : 
    1336             : /************************************************************************/
    1337             : /*                            GetMetadata()                             */
    1338             : /************************************************************************/
    1339             : 
    1340         104 : char **MBTilesDataset::GetMetadata(const char *pszDomain)
    1341             : {
    1342         104 :     if (hDS == nullptr || (pszDomain != nullptr && !EQUAL(pszDomain, "")))
    1343          29 :         return GDALPamDataset::GetMetadata(pszDomain);
    1344             : 
    1345          75 :     if (bFetchedMetadata)
    1346          15 :         return aosList.List();
    1347             : 
    1348          60 :     bFetchedMetadata = true;
    1349          60 :     aosList = CPLStringList(GDALPamDataset::GetMetadata(), FALSE);
    1350             : 
    1351          60 :     OGRLayerH hSQLLyr = GDALDatasetExecuteSQL(
    1352             :         hDS, "SELECT name, value FROM metadata WHERE name != 'json' LIMIT 1000",
    1353             :         nullptr, nullptr);
    1354          60 :     if (hSQLLyr == nullptr)
    1355           0 :         return nullptr;
    1356             : 
    1357          60 :     if (OGR_FD_GetFieldCount(OGR_L_GetLayerDefn(hSQLLyr)) != 2)
    1358             :     {
    1359           0 :         GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    1360           0 :         return nullptr;
    1361             :     }
    1362             : 
    1363             :     OGRFeatureH hFeat;
    1364         577 :     while ((hFeat = OGR_L_GetNextFeature(hSQLLyr)) != nullptr)
    1365             :     {
    1366        1034 :         if (OGR_F_IsFieldSetAndNotNull(hFeat, 0) &&
    1367         517 :             OGR_F_IsFieldSetAndNotNull(hFeat, 1))
    1368             :         {
    1369        1034 :             CPLString osName = OGR_F_GetFieldAsString(hFeat, 0);
    1370        1034 :             CPLString osValue = OGR_F_GetFieldAsString(hFeat, 1);
    1371        1034 :             if (osName[0] != '\0' && !STARTS_WITH(osValue, "function(") &&
    1372         517 :                 strstr(osValue, "<img ") == nullptr &&
    1373         517 :                 strstr(osValue, "<p>") == nullptr &&
    1374        1551 :                 strstr(osValue, "</p>") == nullptr &&
    1375         517 :                 strstr(osValue, "<div") == nullptr)
    1376             :             {
    1377         517 :                 aosList.AddNameValue(osName, osValue);
    1378             :             }
    1379             :         }
    1380         517 :         OGR_F_Destroy(hFeat);
    1381             :     }
    1382          60 :     GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    1383             : 
    1384          60 :     return aosList.List();
    1385             : }
    1386             : 
    1387             : /************************************************************************/
    1388             : /*                         GetMetadataItem()                            */
    1389             : /************************************************************************/
    1390             : 
    1391          89 : const char *MBTilesDataset::GetMetadataItem(const char *pszName,
    1392             :                                             const char *pszDomain)
    1393             : {
    1394          89 :     if (pszDomain == nullptr || EQUAL(pszDomain, ""))
    1395             :     {
    1396          83 :         const char *pszValue = CSLFetchNameValue(GetMetadata(), pszName);
    1397          83 :         if (pszValue)
    1398          65 :             return pszValue;
    1399             :     }
    1400          24 :     return GDALPamDataset::GetMetadataItem(pszName, pszDomain);
    1401             : }
    1402             : 
    1403             : /************************************************************************/
    1404             : /*                              GetLayer()                              */
    1405             : /************************************************************************/
    1406             : 
    1407          59 : OGRLayer *MBTilesDataset::GetLayer(int iLayer)
    1408             : 
    1409             : {
    1410          59 :     if (iLayer < 0 || iLayer >= GetLayerCount())
    1411           2 :         return nullptr;
    1412          57 :     return m_apoLayers[iLayer].get();
    1413             : }
    1414             : 
    1415             : /************************************************************************/
    1416             : /*                        MBTilesVectorLayer()                          */
    1417             : /************************************************************************/
    1418             : 
    1419          37 : MBTilesVectorLayer::MBTilesVectorLayer(
    1420             :     MBTilesDataset *poDS, const char *pszLayerName,
    1421             :     const CPLJSONObject &oFields, const CPLJSONArray &oAttributesFromTileStats,
    1422             :     bool bJsonField, double dfMinX, double dfMinY, double dfMaxX, double dfMaxY,
    1423          37 :     OGRwkbGeometryType eGeomType, bool bZoomLevelFromSpatialFilter)
    1424          37 :     : m_poDS(poDS), m_poFeatureDefn(new OGRFeatureDefn(pszLayerName)),
    1425          74 :       m_bJsonField(bJsonField)
    1426             : {
    1427          37 :     SetDescription(pszLayerName);
    1428          37 :     m_poFeatureDefn->SetGeomType(eGeomType);
    1429          37 :     OGRSpatialReference *poSRS = new OGRSpatialReference();
    1430          37 :     poSRS->SetFromUserInput(SRS_EPSG_3857);
    1431          37 :     m_poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef(poSRS);
    1432          37 :     poSRS->Release();
    1433          37 :     m_poFeatureDefn->Reference();
    1434             : 
    1435          37 :     if (m_bJsonField)
    1436             :     {
    1437           2 :         OGRFieldDefn oFieldDefnId("mvt_id", OFTInteger64);
    1438           1 :         m_poFeatureDefn->AddFieldDefn(&oFieldDefnId);
    1439             :     }
    1440             :     else
    1441             :     {
    1442          36 :         OGRMVTInitFields(m_poFeatureDefn, oFields, oAttributesFromTileStats);
    1443             :     }
    1444             : 
    1445          37 :     m_sExtent.MinX = dfMinX;
    1446          37 :     m_sExtent.MinY = dfMinY;
    1447          37 :     m_sExtent.MaxX = dfMaxX;
    1448          37 :     m_sExtent.MaxY = dfMaxY;
    1449             : 
    1450          37 :     m_nZoomLevel = m_poDS->m_nZoomLevel;
    1451          37 :     m_bZoomLevelAuto = bZoomLevelFromSpatialFilter;
    1452          37 :     MBTilesVectorLayer::SetSpatialFilter(nullptr);
    1453             : 
    1454             :     // If the metadata contains an empty fields object, this may be a sign
    1455             :     // that it doesn't know the schema. In that case check if a tile has
    1456             :     // attributes, and in that case create a json field.
    1457          37 :     if (!m_bJsonField && oFields.IsValid() && oFields.GetChildren().empty())
    1458             :     {
    1459           8 :         m_bJsonField = true;
    1460           8 :         OGRFeature *poSrcFeature = GetNextSrcFeature();
    1461           8 :         m_bJsonField = false;
    1462             : 
    1463           8 :         if (poSrcFeature)
    1464             :         {
    1465             :             // There is at least the mvt_id field
    1466           8 :             if (poSrcFeature->GetFieldCount() > 1)
    1467             :             {
    1468           1 :                 m_bJsonField = true;
    1469             :             }
    1470           8 :             delete poSrcFeature;
    1471             :         }
    1472           8 :         MBTilesVectorLayer::ResetReading();
    1473             :     }
    1474             : 
    1475          37 :     if (m_bJsonField)
    1476             :     {
    1477           4 :         OGRFieldDefn oFieldDefn("json", OFTString);
    1478           2 :         m_poFeatureDefn->AddFieldDefn(&oFieldDefn);
    1479             :     }
    1480          37 : }
    1481             : 
    1482             : /************************************************************************/
    1483             : /*                       ~MBTilesVectorLayer()                          */
    1484             : /************************************************************************/
    1485             : 
    1486          74 : MBTilesVectorLayer::~MBTilesVectorLayer()
    1487             : {
    1488          37 :     m_poFeatureDefn->Release();
    1489          37 :     if (m_hTileIteratorLyr)
    1490          15 :         GDALDatasetReleaseResultSet(m_poDS->hDS, m_hTileIteratorLyr);
    1491          37 :     if (!m_osTmpFilename.empty())
    1492             :     {
    1493          15 :         VSIUnlink(m_osTmpFilename);
    1494             :     }
    1495          37 :     if (m_hTileDS)
    1496          11 :         GDALClose(m_hTileDS);
    1497          74 : }
    1498             : 
    1499             : /************************************************************************/
    1500             : /*                           TestCapability()                           */
    1501             : /************************************************************************/
    1502             : 
    1503          35 : int MBTilesVectorLayer::TestCapability(const char *pszCap)
    1504             : {
    1505          35 :     if (EQUAL(pszCap, OLCStringsAsUTF8) ||
    1506          23 :         EQUAL(pszCap, OLCFastSpatialFilter) || EQUAL(pszCap, OLCFastGetExtent))
    1507             :     {
    1508          14 :         return TRUE;
    1509             :     }
    1510          21 :     return FALSE;
    1511             : }
    1512             : 
    1513             : /************************************************************************/
    1514             : /*                            IGetExtent()                              */
    1515             : /************************************************************************/
    1516             : 
    1517           4 : OGRErr MBTilesVectorLayer::IGetExtent(int /* iGeomField */,
    1518             :                                       OGREnvelope *psExtent, bool /* bForce */)
    1519             : {
    1520           4 :     *psExtent = m_sExtent;
    1521           4 :     return OGRERR_NONE;
    1522             : }
    1523             : 
    1524             : /************************************************************************/
    1525             : /*                          ResetReading()                              */
    1526             : /************************************************************************/
    1527             : 
    1528         109 : void MBTilesVectorLayer::ResetReading()
    1529             : {
    1530         109 :     if (m_hTileDS)
    1531          44 :         GDALClose(m_hTileDS);
    1532         109 :     m_hTileDS = nullptr;
    1533         109 :     m_bEOF = false;
    1534         109 :     if (m_hTileIteratorLyr)
    1535          94 :         GDALDatasetReleaseResultSet(m_poDS->hDS, m_hTileIteratorLyr);
    1536         109 :     CPLString osSQL;
    1537             :     osSQL.Printf("SELECT tile_column, tile_row, tile_data FROM tiles "
    1538             :                  "WHERE zoom_level = %d "
    1539             :                  "AND tile_column BETWEEN %d AND %d "
    1540             :                  "AND tile_row BETWEEN %d AND %d",
    1541             :                  m_nZoomLevel, m_nFilterMinX, m_nFilterMaxX, m_nFilterMinY,
    1542         109 :                  m_nFilterMaxY);
    1543         109 :     m_hTileIteratorLyr =
    1544         109 :         GDALDatasetExecuteSQL(m_poDS->hDS, osSQL.c_str(), nullptr, nullptr);
    1545         109 : }
    1546             : 
    1547             : /************************************************************************/
    1548             : /*                        ISetSpatialFilter()                           */
    1549             : /************************************************************************/
    1550             : 
    1551          62 : OGRErr MBTilesVectorLayer::ISetSpatialFilter(int iGeomField,
    1552             :                                              const OGRGeometry *poGeomIn)
    1553             : {
    1554          62 :     OGRErr eErr = OGRLayer::ISetSpatialFilter(iGeomField, poGeomIn);
    1555          62 :     if (eErr == OGRERR_NONE)
    1556             :     {
    1557          62 :         if (m_poFilterGeom != nullptr && m_sFilterEnvelope.MinX <= -MAX_GM &&
    1558           2 :             m_sFilterEnvelope.MinY <= -MAX_GM &&
    1559           2 :             m_sFilterEnvelope.MaxX >= MAX_GM &&
    1560           2 :             m_sFilterEnvelope.MaxY >= MAX_GM)
    1561             :         {
    1562           2 :             if (m_bZoomLevelAuto)
    1563             :             {
    1564           0 :                 m_nZoomLevel = m_poDS->m_nMinZoomLevel;
    1565             :             }
    1566           2 :             m_nFilterMinX = 0;
    1567           2 :             m_nFilterMinY = 0;
    1568           2 :             m_nFilterMaxX = (1 << m_nZoomLevel) - 1;
    1569           2 :             m_nFilterMaxY = (1 << m_nZoomLevel) - 1;
    1570             :         }
    1571          60 :         else if (m_poFilterGeom != nullptr &&
    1572           6 :                  m_sFilterEnvelope.MinX >= -10 * MAX_GM &&
    1573           6 :                  m_sFilterEnvelope.MinY >= -10 * MAX_GM &&
    1574           6 :                  m_sFilterEnvelope.MaxX <= 10 * MAX_GM &&
    1575           6 :                  m_sFilterEnvelope.MaxY <= 10 * MAX_GM)
    1576             :         {
    1577           6 :             if (m_bZoomLevelAuto)
    1578             :             {
    1579             :                 double dfExtent =
    1580           0 :                     std::min(m_sFilterEnvelope.MaxX - m_sFilterEnvelope.MinX,
    1581           0 :                              m_sFilterEnvelope.MaxY - m_sFilterEnvelope.MinY);
    1582           0 :                 m_nZoomLevel = std::max(
    1583           0 :                     m_poDS->m_nMinZoomLevel,
    1584           0 :                     std::min(static_cast<int>(0.5 + log(2 * MAX_GM / dfExtent) /
    1585             :                                                         log(2.0)),
    1586           0 :                              m_poDS->m_nZoomLevel));
    1587           0 :                 CPLDebug("MBTILES", "Zoom level = %d", m_nZoomLevel);
    1588             :             }
    1589           6 :             const double dfTileDim = 2 * MAX_GM / (1 << m_nZoomLevel);
    1590           6 :             m_nFilterMinX = std::max(
    1591          12 :                 0, static_cast<int>(
    1592           6 :                        floor((m_sFilterEnvelope.MinX + MAX_GM) / dfTileDim)));
    1593           6 :             m_nFilterMinY = std::max(
    1594          12 :                 0, static_cast<int>(
    1595           6 :                        floor((m_sFilterEnvelope.MinY + MAX_GM) / dfTileDim)));
    1596           6 :             m_nFilterMaxX =
    1597          12 :                 std::min(static_cast<int>(ceil(
    1598           6 :                              (m_sFilterEnvelope.MaxX + MAX_GM) / dfTileDim)),
    1599           6 :                          (1 << m_nZoomLevel) - 1);
    1600           6 :             m_nFilterMaxY =
    1601          12 :                 std::min(static_cast<int>(ceil(
    1602           6 :                              (m_sFilterEnvelope.MaxY + MAX_GM) / dfTileDim)),
    1603           6 :                          (1 << m_nZoomLevel) - 1);
    1604             :         }
    1605             :         else
    1606             :         {
    1607          54 :             if (m_bZoomLevelAuto)
    1608             :             {
    1609           0 :                 m_nZoomLevel = m_poDS->m_nZoomLevel;
    1610             :             }
    1611          54 :             m_nFilterMinX = 0;
    1612          54 :             m_nFilterMinY = 0;
    1613          54 :             m_nFilterMaxX = (1 << m_nZoomLevel) - 1;
    1614          54 :             m_nFilterMaxY = (1 << m_nZoomLevel) - 1;
    1615             :         }
    1616             :     }
    1617          62 :     return eErr;
    1618             : }
    1619             : 
    1620             : /************************************************************************/
    1621             : /*                          GetNextFeature()                            */
    1622             : /************************************************************************/
    1623             : 
    1624         151 : OGRFeature *MBTilesVectorLayer::GetNextFeature()
    1625             : {
    1626             :     while (true)
    1627             :     {
    1628         151 :         OGRFeature *poFeature = GetNextRawFeature();
    1629         151 :         if (poFeature == nullptr)
    1630          29 :             return nullptr;
    1631             : 
    1632         286 :         if ((m_poFilterGeom == nullptr ||
    1633         231 :              FilterGeometry(poFeature->GetGeometryRef())) &&
    1634         109 :             (m_poAttrQuery == nullptr || m_poAttrQuery->Evaluate(poFeature)))
    1635             :         {
    1636          81 :             return poFeature;
    1637             :         }
    1638             : 
    1639          41 :         delete poFeature;
    1640          41 :     }
    1641             : }
    1642             : 
    1643             : /************************************************************************/
    1644             : /*                         GetFeatureCount()                            */
    1645             : /************************************************************************/
    1646             : 
    1647          15 : GIntBig MBTilesVectorLayer::GetFeatureCount(int bForce)
    1648             : {
    1649          15 :     if (m_poFilterGeom == nullptr && m_poAttrQuery == nullptr)
    1650             :     {
    1651           9 :         if (m_nFeatureCount < 0)
    1652             :         {
    1653           1 :             m_nFeatureCount = 0;
    1654           1 :             ResetReading();
    1655           5 :             while (m_hTileIteratorLyr != nullptr)
    1656             :             {
    1657           5 :                 OGRFeatureH hFeat = OGR_L_GetNextFeature(m_hTileIteratorLyr);
    1658           5 :                 if (hFeat == nullptr)
    1659             :                 {
    1660           1 :                     break;
    1661             :                 }
    1662           4 :                 m_nX = OGR_F_GetFieldAsInteger(hFeat, 0);
    1663             :                 // MBTiles y origin is bottom based, whereas MVT directory
    1664             :                 // is top based
    1665           4 :                 m_nY =
    1666           4 :                     (1 << m_nZoomLevel) - 1 - OGR_F_GetFieldAsInteger(hFeat, 1);
    1667           4 :                 int nDataSize = 0;
    1668           4 :                 GByte *pabyData = OGR_F_GetFieldAsBinary(hFeat, 2, &nDataSize);
    1669           4 :                 GByte *pabyDataDup = static_cast<GByte *>(CPLMalloc(nDataSize));
    1670           4 :                 memcpy(pabyDataDup, pabyData, nDataSize);
    1671           4 :                 OGR_F_Destroy(hFeat);
    1672             : 
    1673           4 :                 if (!m_osTmpFilename.empty())
    1674             :                 {
    1675           3 :                     VSIUnlink(m_osTmpFilename);
    1676             :                 }
    1677             :                 m_osTmpFilename = VSIMemGenerateHiddenFilename(
    1678           4 :                     CPLSPrintf("mvt_%d_%d.pbf", m_nX, m_nY));
    1679           4 :                 VSIFCloseL(VSIFileFromMemBuffer(m_osTmpFilename, pabyDataDup,
    1680             :                                                 nDataSize, true));
    1681             : 
    1682           4 :                 const char *l_apszAllowedDrivers[] = {"MVT", nullptr};
    1683           4 :                 if (m_hTileDS)
    1684           0 :                     GDALClose(m_hTileDS);
    1685           4 :                 char **papszOpenOptions = nullptr;
    1686             :                 papszOpenOptions =
    1687           4 :                     CSLSetNameValue(papszOpenOptions, "METADATA_FILE",
    1688           4 :                                     m_poDS->m_osMetadataMemFilename.c_str());
    1689           4 :                 m_hTileDS =
    1690           4 :                     GDALOpenEx(("MVT:" + m_osTmpFilename).c_str(),
    1691             :                                GDAL_OF_VECTOR | GDAL_OF_INTERNAL,
    1692             :                                l_apszAllowedDrivers, papszOpenOptions, nullptr);
    1693           4 :                 CSLDestroy(papszOpenOptions);
    1694           4 :                 if (m_hTileDS)
    1695             :                 {
    1696             :                     OGRLayerH hLayer =
    1697           4 :                         GDALDatasetGetLayerByName(m_hTileDS, GetName());
    1698           4 :                     if (hLayer)
    1699             :                     {
    1700           4 :                         m_nFeatureCount += OGR_L_GetFeatureCount(hLayer, true);
    1701             :                     }
    1702           4 :                     GDALClose(m_hTileDS);
    1703           4 :                     m_hTileDS = nullptr;
    1704             :                 }
    1705             :             }
    1706           1 :             ResetReading();
    1707             :         }
    1708           9 :         return m_nFeatureCount;
    1709             :     }
    1710           6 :     return OGRLayer::GetFeatureCount(bForce);
    1711             : }
    1712             : 
    1713             : /************************************************************************/
    1714             : /*                        GetNextSrcFeature()                           */
    1715             : /************************************************************************/
    1716             : 
    1717         159 : OGRFeature *MBTilesVectorLayer::GetNextSrcFeature()
    1718             : {
    1719         159 :     if (m_bEOF)
    1720             :     {
    1721           1 :         return nullptr;
    1722             :     }
    1723         158 :     if (m_hTileIteratorLyr == nullptr)
    1724             :     {
    1725          14 :         ResetReading();
    1726          14 :         if (m_hTileIteratorLyr == nullptr)
    1727             :         {
    1728           0 :             return nullptr;
    1729             :         }
    1730             :     }
    1731             : 
    1732         158 :     OGRFeatureH hTileFeat = nullptr;
    1733         261 :     if (m_hTileDS == nullptr ||
    1734         103 :         (hTileFeat = OGR_L_GetNextFeature(
    1735         103 :              GDALDatasetGetLayerByName(m_hTileDS, GetName()))) == nullptr)
    1736             :     {
    1737             :         while (true)
    1738             :         {
    1739         167 :             OGRFeatureH hFeat = OGR_L_GetNextFeature(m_hTileIteratorLyr);
    1740         167 :             if (hFeat == nullptr)
    1741             :             {
    1742          28 :                 m_bEOF = true;
    1743          28 :                 return nullptr;
    1744             :             }
    1745         139 :             m_nX = OGR_F_GetFieldAsInteger(hFeat, 0);
    1746             :             // MBTiles y origin is bottom based, whereas MVT directory
    1747             :             // is top based
    1748         139 :             m_nY = (1 << m_nZoomLevel) - 1 - OGR_F_GetFieldAsInteger(hFeat, 1);
    1749         139 :             CPLDebug("MBTiles", "X=%d, Y=%d", m_nX, m_nY);
    1750             : 
    1751         139 :             int nDataSize = 0;
    1752         139 :             GByte *pabyData = OGR_F_GetFieldAsBinary(hFeat, 2, &nDataSize);
    1753         139 :             GByte *pabyDataDup = static_cast<GByte *>(CPLMalloc(nDataSize));
    1754         139 :             memcpy(pabyDataDup, pabyData, nDataSize);
    1755         139 :             OGR_F_Destroy(hFeat);
    1756             : 
    1757         139 :             if (!m_osTmpFilename.empty())
    1758             :             {
    1759         125 :                 VSIUnlink(m_osTmpFilename);
    1760             :             }
    1761             :             m_osTmpFilename = VSIMemGenerateHiddenFilename(
    1762         139 :                 CPLSPrintf("mvt_%d_%d.pbf", m_nX, m_nY));
    1763         139 :             VSIFCloseL(VSIFileFromMemBuffer(m_osTmpFilename, pabyDataDup,
    1764             :                                             nDataSize, true));
    1765             : 
    1766         139 :             const char *l_apszAllowedDrivers[] = {"MVT", nullptr};
    1767         139 :             if (m_hTileDS)
    1768          72 :                 GDALClose(m_hTileDS);
    1769         139 :             char **papszOpenOptions = nullptr;
    1770             :             papszOpenOptions =
    1771         139 :                 CSLSetNameValue(papszOpenOptions, "X", CPLSPrintf("%d", m_nX));
    1772             :             papszOpenOptions =
    1773         139 :                 CSLSetNameValue(papszOpenOptions, "Y", CPLSPrintf("%d", m_nY));
    1774         139 :             papszOpenOptions = CSLSetNameValue(papszOpenOptions, "Z",
    1775             :                                                CPLSPrintf("%d", m_nZoomLevel));
    1776         139 :             papszOpenOptions = CSLSetNameValue(
    1777             :                 papszOpenOptions, "METADATA_FILE",
    1778         139 :                 m_bJsonField ? "" : m_poDS->m_osMetadataMemFilename.c_str());
    1779         139 :             if (!m_poDS->m_osClip.empty())
    1780             :             {
    1781             :                 papszOpenOptions =
    1782           3 :                     CSLSetNameValue(papszOpenOptions, "CLIP", m_poDS->m_osClip);
    1783             :             }
    1784         139 :             m_hTileDS =
    1785         139 :                 GDALOpenEx(("MVT:" + m_osTmpFilename).c_str(),
    1786             :                            GDAL_OF_VECTOR | GDAL_OF_INTERNAL,
    1787             :                            l_apszAllowedDrivers, papszOpenOptions, nullptr);
    1788         139 :             CSLDestroy(papszOpenOptions);
    1789         139 :             if (m_hTileDS)
    1790             :             {
    1791         139 :                 if (GDALDatasetGetLayerByName(m_hTileDS, GetName()))
    1792             :                 {
    1793         131 :                     hTileFeat = OGR_L_GetNextFeature(
    1794         131 :                         GDALDatasetGetLayerByName(m_hTileDS, GetName()));
    1795         131 :                     if (hTileFeat)
    1796         127 :                         break;
    1797             :                 }
    1798          12 :                 GDALClose(m_hTileDS);
    1799          12 :                 m_hTileDS = nullptr;
    1800             :             }
    1801          12 :         }
    1802             :     }
    1803             : 
    1804         130 :     return reinterpret_cast<OGRFeature *>(hTileFeat);
    1805             : }
    1806             : 
    1807             : /************************************************************************/
    1808             : /*                         CreateFeatureFrom()                          */
    1809             : /************************************************************************/
    1810             : 
    1811         124 : OGRFeature *MBTilesVectorLayer::CreateFeatureFrom(OGRFeature *poSrcFeature)
    1812             : {
    1813             : 
    1814         124 :     return OGRMVTCreateFeatureFrom(poSrcFeature, m_poFeatureDefn, m_bJsonField,
    1815         248 :                                    GetSpatialRef());
    1816             : }
    1817             : 
    1818             : /************************************************************************/
    1819             : /*                        GetNextRawFeature()                           */
    1820             : /************************************************************************/
    1821             : 
    1822         151 : OGRFeature *MBTilesVectorLayer::GetNextRawFeature()
    1823             : {
    1824         151 :     OGRFeature *poSrcFeat = GetNextSrcFeature();
    1825         151 :     if (poSrcFeat == nullptr)
    1826          29 :         return nullptr;
    1827             : 
    1828         122 :     const GIntBig nFIDBase =
    1829         122 :         (static_cast<GIntBig>(m_nY) << m_nZoomLevel) | m_nX;
    1830         122 :     OGRFeature *poFeature = CreateFeatureFrom(poSrcFeat);
    1831         122 :     poFeature->SetFID((poSrcFeat->GetFID() << (2 * m_nZoomLevel)) | nFIDBase);
    1832         122 :     delete poSrcFeat;
    1833             : 
    1834         122 :     return poFeature;
    1835             : }
    1836             : 
    1837             : /************************************************************************/
    1838             : /*                           GetFeature()                               */
    1839             : /************************************************************************/
    1840             : 
    1841           5 : OGRFeature *MBTilesVectorLayer::GetFeature(GIntBig nFID)
    1842             : {
    1843           5 :     const int nZ = m_nZoomLevel;
    1844           5 :     const int nX = static_cast<int>(nFID & ((1 << nZ) - 1));
    1845           5 :     const int nY = static_cast<int>((nFID >> nZ) & ((1 << nZ) - 1));
    1846           5 :     const GIntBig nTileFID = nFID >> (2 * nZ);
    1847             : 
    1848          10 :     CPLString osSQL;
    1849             :     osSQL.Printf("SELECT tile_data FROM tiles "
    1850             :                  "WHERE zoom_level = %d AND "
    1851             :                  "tile_column = %d AND tile_row = %d",
    1852           5 :                  m_nZoomLevel, nX, (1 << nZ) - 1 - nY);
    1853             :     auto hSQLLyr =
    1854           5 :         GDALDatasetExecuteSQL(m_poDS->hDS, osSQL.c_str(), nullptr, nullptr);
    1855           5 :     if (hSQLLyr == nullptr)
    1856           0 :         return nullptr;
    1857           5 :     auto hFeat = OGR_L_GetNextFeature(hSQLLyr);
    1858           5 :     if (hFeat == nullptr)
    1859             :     {
    1860           0 :         GDALDatasetReleaseResultSet(m_poDS->hDS, hSQLLyr);
    1861           0 :         return nullptr;
    1862             :     }
    1863           5 :     int nDataSize = 0;
    1864           5 :     GByte *pabyData = OGR_F_GetFieldAsBinary(hFeat, 0, &nDataSize);
    1865           5 :     GByte *pabyDataDup = static_cast<GByte *>(CPLMalloc(nDataSize));
    1866           5 :     memcpy(pabyDataDup, pabyData, nDataSize);
    1867           5 :     OGR_F_Destroy(hFeat);
    1868           5 :     GDALDatasetReleaseResultSet(m_poDS->hDS, hSQLLyr);
    1869             : 
    1870             :     const CPLString osTmpFilename = VSIMemGenerateHiddenFilename(
    1871           5 :         CPLSPrintf("mvt_get_feature_%d_%d.pbf", m_nX, m_nY));
    1872           5 :     VSIFCloseL(
    1873             :         VSIFileFromMemBuffer(osTmpFilename, pabyDataDup, nDataSize, true));
    1874             : 
    1875           5 :     const char *l_apszAllowedDrivers[] = {"MVT", nullptr};
    1876           5 :     char **papszOpenOptions = nullptr;
    1877             :     papszOpenOptions =
    1878           5 :         CSLSetNameValue(papszOpenOptions, "X", CPLSPrintf("%d", nX));
    1879             :     papszOpenOptions =
    1880           5 :         CSLSetNameValue(papszOpenOptions, "Y", CPLSPrintf("%d", nY));
    1881             :     papszOpenOptions =
    1882           5 :         CSLSetNameValue(papszOpenOptions, "Z", CPLSPrintf("%d", m_nZoomLevel));
    1883           5 :     papszOpenOptions = CSLSetNameValue(
    1884             :         papszOpenOptions, "METADATA_FILE",
    1885           5 :         m_bJsonField ? "" : m_poDS->m_osMetadataMemFilename.c_str());
    1886           5 :     if (!m_poDS->m_osClip.empty())
    1887             :     {
    1888             :         papszOpenOptions =
    1889           0 :             CSLSetNameValue(papszOpenOptions, "CLIP", m_poDS->m_osClip);
    1890             :     }
    1891           5 :     auto hTileDS = GDALOpenEx(("MVT:" + osTmpFilename).c_str(),
    1892             :                               GDAL_OF_VECTOR | GDAL_OF_INTERNAL,
    1893             :                               l_apszAllowedDrivers, papszOpenOptions, nullptr);
    1894           5 :     CSLDestroy(papszOpenOptions);
    1895             : 
    1896           5 :     OGRFeature *poFeature = nullptr;
    1897           5 :     if (hTileDS)
    1898             :     {
    1899           5 :         OGRLayerH hLayer = GDALDatasetGetLayerByName(hTileDS, GetName());
    1900           5 :         if (hLayer)
    1901             :         {
    1902             :             OGRFeature *poUnderlyingFeature = reinterpret_cast<OGRFeature *>(
    1903           5 :                 OGR_L_GetFeature(hLayer, nTileFID));
    1904           5 :             if (poUnderlyingFeature)
    1905             :             {
    1906           2 :                 poFeature = CreateFeatureFrom(poUnderlyingFeature);
    1907           2 :                 poFeature->SetFID(nFID);
    1908             :             }
    1909           5 :             delete poUnderlyingFeature;
    1910             :         }
    1911             :     }
    1912           5 :     GDALClose(hTileDS);
    1913             : 
    1914           5 :     VSIUnlink(osTmpFilename);
    1915             : 
    1916           5 :     return poFeature;
    1917             : }
    1918             : 
    1919             : /************************************************************************/
    1920             : /*                           InitVector()                               */
    1921             : /************************************************************************/
    1922             : 
    1923          32 : void MBTilesDataset::InitVector(double dfMinX, double dfMinY, double dfMaxX,
    1924             :                                 double dfMaxY, bool bZoomLevelFromSpatialFilter,
    1925             :                                 bool bJsonField)
    1926             : {
    1927          32 :     const char *pszSQL = "SELECT value FROM metadata WHERE name = 'json'";
    1928          32 :     CPLDebug("MBTILES", "%s", pszSQL);
    1929          64 :     CPLJSONDocument oJsonDoc;
    1930          64 :     CPLJSONDocument oDoc;
    1931          32 :     auto hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
    1932          32 :     if (hSQLLyr)
    1933             :     {
    1934          32 :         auto hFeat = OGR_L_GetNextFeature(hSQLLyr);
    1935          32 :         if (hFeat)
    1936             :         {
    1937          32 :             auto pszJson = OGR_F_GetFieldAsString(hFeat, 0);
    1938          32 :             oDoc.GetRoot().Add("json", pszJson);
    1939          32 :             CPL_IGNORE_RET_VAL(
    1940          32 :                 oJsonDoc.LoadMemory(reinterpret_cast<const GByte *>(pszJson)));
    1941          32 :             OGR_F_Destroy(hFeat);
    1942             :         }
    1943          32 :         GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    1944             :     }
    1945             : 
    1946             :     m_osMetadataMemFilename =
    1947          32 :         VSIMemGenerateHiddenFilename("mbtiles_metadata.json");
    1948          32 :     oDoc.Save(m_osMetadataMemFilename);
    1949             : 
    1950          64 :     CPLJSONArray oVectorLayers;
    1951          32 :     oVectorLayers.Deinit();
    1952             : 
    1953          64 :     CPLJSONArray oTileStatLayers;
    1954          32 :     oTileStatLayers.Deinit();
    1955             : 
    1956          32 :     oVectorLayers = oJsonDoc.GetRoot().GetArray("vector_layers");
    1957             : 
    1958          32 :     oTileStatLayers = oJsonDoc.GetRoot().GetArray("tilestats/layers");
    1959             : 
    1960          69 :     for (int i = 0; i < oVectorLayers.Size(); i++)
    1961             :     {
    1962         111 :         CPLJSONObject oId = oVectorLayers[i].GetObj("id");
    1963          37 :         if (oId.IsValid() && oId.GetType() == CPLJSONObject::Type::String)
    1964             :         {
    1965          37 :             OGRwkbGeometryType eGeomType = wkbUnknown;
    1966          37 :             if (oTileStatLayers.IsValid())
    1967             :             {
    1968          36 :                 eGeomType = OGRMVTFindGeomTypeFromTileStat(
    1969          72 :                     oTileStatLayers, oId.ToString().c_str());
    1970             :             }
    1971             : 
    1972         111 :             CPLJSONObject oFields = oVectorLayers[i].GetObj("fields");
    1973             :             CPLJSONArray oAttributesFromTileStats =
    1974             :                 OGRMVTFindAttributesFromTileStat(oTileStatLayers,
    1975          74 :                                                  oId.ToString().c_str());
    1976          37 :             m_apoLayers.push_back(
    1977          74 :                 std::unique_ptr<OGRLayer>(new MBTilesVectorLayer(
    1978          74 :                     this, oId.ToString().c_str(), oFields,
    1979             :                     oAttributesFromTileStats, bJsonField, dfMinX, dfMinY,
    1980          37 :                     dfMaxX, dfMaxY, eGeomType, bZoomLevelFromSpatialFilter)));
    1981             :         }
    1982             :     }
    1983          32 : }
    1984             : 
    1985             : /************************************************************************/
    1986             : /*                             Identify()                               */
    1987             : /************************************************************************/
    1988             : 
    1989       68861 : int MBTilesDataset::Identify(GDALOpenInfo *poOpenInfo)
    1990             : {
    1991             : #ifdef ENABLE_SQL_SQLITE_FORMAT
    1992       68861 :     if (poOpenInfo->pabyHeader &&
    1993       12324 :         STARTS_WITH((const char *)poOpenInfo->pabyHeader, "-- SQL MBTILES"))
    1994             :     {
    1995           2 :         return TRUE;
    1996             :     }
    1997             : #endif
    1998             : 
    1999       68859 :     if ((poOpenInfo->IsExtensionEqualToCI("MBTILES") ||
    2000             :          // Allow direct Amazon S3 signed URLs that contains .mbtiles in the
    2001             :          // middle of the URL
    2002       68580 :          strstr(poOpenInfo->pszFilename, ".mbtiles") != nullptr) &&
    2003      137592 :         poOpenInfo->nHeaderBytes >= 1024 && poOpenInfo->pabyHeader &&
    2004         153 :         STARTS_WITH_CI((const char *)poOpenInfo->pabyHeader, "SQLite Format 3"))
    2005             :     {
    2006         153 :         return TRUE;
    2007             :     }
    2008             : 
    2009       68706 :     return FALSE;
    2010             : }
    2011             : 
    2012             : /************************************************************************/
    2013             : /*                        MBTilesGetMinMaxZoomLevel()                   */
    2014             : /************************************************************************/
    2015             : 
    2016          77 : static int MBTilesGetMinMaxZoomLevel(GDALDatasetH hDS, int bHasMap,
    2017             :                                      int &nMinLevel, int &nMaxLevel)
    2018             : {
    2019             :     OGRLayerH hSQLLyr;
    2020             :     OGRFeatureH hFeat;
    2021          77 :     int bHasMinMaxLevel = FALSE;
    2022             : 
    2023          77 :     const char *pszSQL =
    2024             :         "SELECT value FROM metadata WHERE name = 'minzoom' UNION ALL "
    2025             :         "SELECT value FROM metadata WHERE name = 'maxzoom'";
    2026          77 :     CPLDebug("MBTILES", "%s", pszSQL);
    2027          77 :     hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
    2028          77 :     if (hSQLLyr)
    2029             :     {
    2030          77 :         hFeat = OGR_L_GetNextFeature(hSQLLyr);
    2031          77 :         if (hFeat)
    2032             :         {
    2033          73 :             int bHasMinLevel = FALSE;
    2034          73 :             if (OGR_F_IsFieldSetAndNotNull(hFeat, 0))
    2035             :             {
    2036          73 :                 nMinLevel = OGR_F_GetFieldAsInteger(hFeat, 0);
    2037          73 :                 bHasMinLevel = TRUE;
    2038             :             }
    2039          73 :             OGR_F_Destroy(hFeat);
    2040             : 
    2041          73 :             if (bHasMinLevel)
    2042             :             {
    2043          73 :                 hFeat = OGR_L_GetNextFeature(hSQLLyr);
    2044          73 :                 if (hFeat)
    2045             :                 {
    2046          73 :                     if (OGR_F_IsFieldSetAndNotNull(hFeat, 0))
    2047             :                     {
    2048          73 :                         nMaxLevel = OGR_F_GetFieldAsInteger(hFeat, 0);
    2049          73 :                         bHasMinMaxLevel = TRUE;
    2050             :                     }
    2051          73 :                     OGR_F_Destroy(hFeat);
    2052             :                 }
    2053             :             }
    2054             :         }
    2055             : 
    2056          77 :         GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    2057             :     }
    2058             : 
    2059          77 :     if (!bHasMinMaxLevel)
    2060             :     {
    2061             : #define OPTIMIZED_FOR_VSICURL
    2062             : #ifdef OPTIMIZED_FOR_VSICURL
    2063             :         int iLevel;
    2064          40 :         for (iLevel = 0; nMinLevel < 0 && iLevel <= 32; iLevel++)
    2065             :         {
    2066          36 :             pszSQL = CPLSPrintf(
    2067             :                 "SELECT zoom_level FROM %s WHERE zoom_level = %d LIMIT 1",
    2068             :                 (bHasMap) ? "map" : "tiles", iLevel);
    2069          36 :             CPLDebug("MBTILES", "%s", pszSQL);
    2070          36 :             hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
    2071          36 :             if (hSQLLyr)
    2072             :             {
    2073          36 :                 hFeat = OGR_L_GetNextFeature(hSQLLyr);
    2074          36 :                 if (hFeat)
    2075             :                 {
    2076           3 :                     nMinLevel = iLevel;
    2077           3 :                     OGR_F_Destroy(hFeat);
    2078             :                 }
    2079          36 :                 GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    2080             :             }
    2081             :         }
    2082             : 
    2083           4 :         if (nMinLevel < 0)
    2084           1 :             return FALSE;
    2085             : 
    2086          99 :         for (iLevel = 32; nMaxLevel < 0 && iLevel >= nMinLevel; iLevel--)
    2087             :         {
    2088          96 :             pszSQL = CPLSPrintf(
    2089             :                 "SELECT zoom_level FROM %s WHERE zoom_level = %d LIMIT 1",
    2090             :                 (bHasMap) ? "map" : "tiles", iLevel);
    2091          96 :             CPLDebug("MBTILES", "%s", pszSQL);
    2092          96 :             hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
    2093          96 :             if (hSQLLyr)
    2094             :             {
    2095          96 :                 hFeat = OGR_L_GetNextFeature(hSQLLyr);
    2096          96 :                 if (hFeat)
    2097             :                 {
    2098           3 :                     nMaxLevel = iLevel;
    2099           3 :                     bHasMinMaxLevel = TRUE;
    2100           3 :                     OGR_F_Destroy(hFeat);
    2101             :                 }
    2102          96 :                 GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    2103             :             }
    2104             :         }
    2105             : #else
    2106             :         pszSQL = "SELECT min(zoom_level), max(zoom_level) FROM tiles";
    2107             :         CPLDebug("MBTILES", "%s", pszSQL);
    2108             :         hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, NULL, nullptr);
    2109             :         if (hSQLLyr == NULL)
    2110             :         {
    2111             :             return FALSE;
    2112             :         }
    2113             : 
    2114             :         hFeat = OGR_L_GetNextFeature(hSQLLyr);
    2115             :         if (hFeat == NULL)
    2116             :         {
    2117             :             GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    2118             :             return FALSE;
    2119             :         }
    2120             : 
    2121             :         if (OGR_F_IsFieldSetAndNotNull(hFeat, 0) &&
    2122             :             OGR_F_IsFieldSetAndNotNull(hFeat, 1))
    2123             :         {
    2124             :             nMinLevel = OGR_F_GetFieldAsInteger(hFeat, 0);
    2125             :             nMaxLevel = OGR_F_GetFieldAsInteger(hFeat, 1);
    2126             :             bHasMinMaxLevel = TRUE;
    2127             :         }
    2128             : 
    2129             :         OGR_F_Destroy(hFeat);
    2130             :         GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    2131             : #endif
    2132             :     }
    2133             : 
    2134          76 :     return bHasMinMaxLevel;
    2135             : }
    2136             : 
    2137             : /************************************************************************/
    2138             : /*                   MBTilesTileCoordToWorldCoord()                     */
    2139             : /************************************************************************/
    2140             : 
    2141          16 : static double MBTilesTileCoordToWorldCoord(double dfTileCoord, int nZoomLevel)
    2142             : {
    2143          16 :     return -MAX_GM + 2 * MAX_GM * (dfTileCoord / (1 << nZoomLevel));
    2144             : }
    2145             : 
    2146             : /************************************************************************/
    2147             : /*                   MBTilesWorldCoordToTileCoord()                     */
    2148             : /************************************************************************/
    2149             : 
    2150         240 : static double MBTilesWorldCoordToTileCoord(double dfWorldCoord, int nZoomLevel)
    2151             : {
    2152         240 :     return (dfWorldCoord + MAX_GM) / (2 * MAX_GM) * (1 << nZoomLevel);
    2153             : }
    2154             : 
    2155             : /************************************************************************/
    2156             : /*                           MBTilesGetBounds()                         */
    2157             : /************************************************************************/
    2158             : 
    2159          76 : static bool MBTilesGetBounds(GDALDatasetH hDS, bool bUseBounds, int nMaxLevel,
    2160             :                              double &minX, double &minY, double &maxX,
    2161             :                              double &maxY)
    2162             : {
    2163          76 :     bool bHasBounds = false;
    2164             :     OGRLayerH hSQLLyr;
    2165             :     OGRFeatureH hFeat;
    2166             : 
    2167          76 :     if (bUseBounds)
    2168             :     {
    2169          75 :         const char *pszSQL = "SELECT value FROM metadata WHERE name = 'bounds'";
    2170          75 :         CPLDebug("MBTILES", "%s", pszSQL);
    2171          75 :         hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
    2172          75 :         if (hSQLLyr)
    2173             :         {
    2174          75 :             hFeat = OGR_L_GetNextFeature(hSQLLyr);
    2175          75 :             if (hFeat != nullptr)
    2176             :             {
    2177          73 :                 const char *pszBounds = OGR_F_GetFieldAsString(hFeat, 0);
    2178          73 :                 char **papszTokens = CSLTokenizeString2(pszBounds, ",", 0);
    2179          73 :                 if (CSLCount(papszTokens) != 4 ||
    2180          72 :                     fabs(CPLAtof(papszTokens[0])) > 180 ||
    2181          56 :                     fabs(CPLAtof(papszTokens[1])) >= 89.99 ||
    2182          56 :                     fabs(CPLAtof(papszTokens[2])) > 180 ||
    2183          56 :                     fabs(CPLAtof(papszTokens[3])) >= 89.99 ||
    2184         201 :                     CPLAtof(papszTokens[0]) > CPLAtof(papszTokens[2]) ||
    2185          56 :                     CPLAtof(papszTokens[1]) > CPLAtof(papszTokens[3]))
    2186             :                 {
    2187          17 :                     CPLError(CE_Warning, CPLE_AppDefined,
    2188             :                              "Invalid value for 'bounds' metadata. Ignoring it "
    2189             :                              "and fall back to present tile extent");
    2190             :                 }
    2191             :                 else
    2192             :                 {
    2193          56 :                     minX = CPLAtof(papszTokens[0]);
    2194          56 :                     minY = CPLAtof(papszTokens[1]);
    2195          56 :                     maxX = CPLAtof(papszTokens[2]);
    2196          56 :                     maxY = CPLAtof(papszTokens[3]);
    2197          56 :                     LongLatToSphericalMercator(&minX, &minY);
    2198          56 :                     LongLatToSphericalMercator(&maxX, &maxY);
    2199             : 
    2200             :                     // Clamp northings
    2201          56 :                     if (maxY > MAX_GM)
    2202           0 :                         maxY = MAX_GM;
    2203          56 :                     if (minY < -MAX_GM)
    2204           8 :                         minY = -MAX_GM;
    2205             : 
    2206          56 :                     bHasBounds = true;
    2207             :                 }
    2208             : 
    2209          73 :                 CSLDestroy(papszTokens);
    2210             : 
    2211          73 :                 OGR_F_Destroy(hFeat);
    2212             :             }
    2213          75 :             GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    2214             :         }
    2215             :     }
    2216             : 
    2217          76 :     if (!bHasBounds)
    2218             :     {
    2219             :         const char *pszSQL =
    2220          20 :             CPLSPrintf("SELECT min(tile_column), max(tile_column), "
    2221             :                        "min(tile_row), max(tile_row) FROM tiles "
    2222             :                        "WHERE zoom_level = %d",
    2223             :                        nMaxLevel);
    2224          20 :         CPLDebug("MBTILES", "%s", pszSQL);
    2225          20 :         hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
    2226          20 :         if (hSQLLyr == nullptr)
    2227             :         {
    2228           0 :             return false;
    2229             :         }
    2230             : 
    2231          20 :         hFeat = OGR_L_GetNextFeature(hSQLLyr);
    2232          20 :         if (hFeat == nullptr)
    2233             :         {
    2234           0 :             GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    2235           0 :             return false;
    2236             :         }
    2237             : 
    2238          20 :         if (OGR_F_IsFieldSetAndNotNull(hFeat, 0) &&
    2239           4 :             OGR_F_IsFieldSetAndNotNull(hFeat, 1) &&
    2240          28 :             OGR_F_IsFieldSetAndNotNull(hFeat, 2) &&
    2241           4 :             OGR_F_IsFieldSetAndNotNull(hFeat, 3))
    2242             :         {
    2243           4 :             int nMinTileCol = OGR_F_GetFieldAsInteger(hFeat, 0);
    2244           4 :             int nMaxTileCol = OGR_F_GetFieldAsInteger(hFeat, 1);
    2245           4 :             int nMinTileRow = OGR_F_GetFieldAsInteger(hFeat, 2);
    2246           4 :             int nMaxTileRow = OGR_F_GetFieldAsInteger(hFeat, 3);
    2247           4 :             if (nMaxTileCol < INT_MAX && nMaxTileRow < INT_MAX)
    2248             :             {
    2249           4 :                 minX = MBTilesTileCoordToWorldCoord(nMinTileCol, nMaxLevel);
    2250           4 :                 minY = MBTilesTileCoordToWorldCoord(nMinTileRow, nMaxLevel);
    2251           4 :                 maxX = MBTilesTileCoordToWorldCoord(nMaxTileCol + 1, nMaxLevel);
    2252           4 :                 maxY = MBTilesTileCoordToWorldCoord(nMaxTileRow + 1, nMaxLevel);
    2253           4 :                 bHasBounds = true;
    2254             :             }
    2255             :         }
    2256             : 
    2257          20 :         OGR_F_Destroy(hFeat);
    2258          20 :         GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    2259             :     }
    2260             : 
    2261          76 :     return bHasBounds;
    2262             : }
    2263             : 
    2264             : /************************************************************************/
    2265             : /*                        MBTilesCurlReadCbk()                          */
    2266             : /************************************************************************/
    2267             : 
    2268             : typedef struct
    2269             : {
    2270             :     int nBands;
    2271             :     int nSize;
    2272             : } TileProperties;
    2273             : 
    2274             : /* We spy the data received by CURL for the initial request where we try */
    2275             : /* to get a first tile to see its characteristics. We just need the header */
    2276             : /* to determine that, so let's make VSICurl stop reading after we have found it
    2277             :  */
    2278             : 
    2279           2 : static int MBTilesCurlReadCbk(CPL_UNUSED VSILFILE *fp, void *pabyBuffer,
    2280             :                               size_t nBufferSize, void *pfnUserData)
    2281             : {
    2282           2 :     TileProperties *psTP = static_cast<TileProperties *>(pfnUserData);
    2283             : 
    2284           2 :     const GByte abyPNGSig[] = {0x89, 0x50, 0x4E, 0x47,
    2285             :                                0x0D, 0x0A, 0x1A, 0x0A, /* PNG signature */
    2286             :                                0x00, 0x00, 0x00, 0x0D, /* IHDR length */
    2287             :                                0x49, 0x48, 0x44, 0x52 /* IHDR chunk */};
    2288             : 
    2289             :     /* JPEG SOF0 (Start Of Frame 0) marker */
    2290           2 :     const GByte abyJPEG1CompSig[] = {0xFF, 0xC0, /* marker */
    2291             :                                      0x00, 0x0B, /* data length = 8 + 1 * 3 */
    2292             :                                      0x08, /* depth : 8 bit */};
    2293           2 :     const GByte abyJPEG3CompSig[] = {0xFF, 0xC0, /* marker */
    2294             :                                      0x00, 0x11, /* data length = 8 + 3 * 3 */
    2295             :                                      0x08, /* depth : 8 bit */};
    2296             : 
    2297             :     int i;
    2298       16354 :     for (i = 0; i < (int)nBufferSize - (int)sizeof(abyPNGSig); i++)
    2299             :     {
    2300       16352 :         if (memcmp(((GByte *)pabyBuffer) + i, abyPNGSig, sizeof(abyPNGSig)) ==
    2301           0 :                 0 &&
    2302           0 :             i + sizeof(abyPNGSig) + 4 + 4 + 1 + 1 < nBufferSize)
    2303             :         {
    2304           0 :             GByte *ptr = ((GByte *)(pabyBuffer)) + i + (int)sizeof(abyPNGSig);
    2305             : 
    2306             :             int nWidth;
    2307           0 :             memcpy(&nWidth, ptr, 4);
    2308           0 :             CPL_MSBPTR32(&nWidth);
    2309           0 :             ptr += 4;
    2310             : 
    2311             :             int nHeight;
    2312           0 :             memcpy(&nHeight, ptr, 4);
    2313           0 :             CPL_MSBPTR32(&nHeight);
    2314           0 :             ptr += 4;
    2315             : 
    2316           0 :             GByte nDepth = *ptr;
    2317           0 :             ptr += 1;
    2318             : 
    2319           0 :             GByte nColorType = *ptr;
    2320           0 :             CPLDebug("MBTILES",
    2321             :                      "PNG: nWidth=%d nHeight=%d depth=%d nColorType=%d", nWidth,
    2322             :                      nHeight, nDepth, nColorType);
    2323             : 
    2324           0 :             psTP->nBands = -2;
    2325           0 :             psTP->nSize = nWidth;
    2326           0 :             if (nWidth == nHeight && nDepth == 8)
    2327             :             {
    2328           0 :                 if (nColorType == 0)
    2329           0 :                     psTP->nBands = 1; /* Gray */
    2330           0 :                 else if (nColorType == 2)
    2331           0 :                     psTP->nBands = 3; /* RGB */
    2332           0 :                 else if (nColorType == 3)
    2333             :                 {
    2334             :                     /* This might also be a color table with transparency */
    2335             :                     /* but we cannot tell ! */
    2336           0 :                     psTP->nBands = -1;
    2337           0 :                     return TRUE;
    2338             :                 }
    2339           0 :                 else if (nColorType == 4)
    2340           0 :                     psTP->nBands = 2; /* Gray + alpha */
    2341           0 :                 else if (nColorType == 6)
    2342           0 :                     psTP->nBands = 4; /* RGB + alpha */
    2343             :             }
    2344             : 
    2345           0 :             return FALSE;
    2346             :         }
    2347             :     }
    2348             : 
    2349       16366 :     for (i = 0; i < (int)nBufferSize - ((int)sizeof(abyJPEG1CompSig) + 5); i++)
    2350             :     {
    2351       16364 :         if (memcmp(((GByte *)pabyBuffer) + i, abyJPEG1CompSig,
    2352           0 :                    sizeof(abyJPEG1CompSig)) == 0 &&
    2353           0 :             ((GByte *)pabyBuffer)[sizeof(abyJPEG1CompSig) + 4] == 1)
    2354             :         {
    2355             :             GUInt16 nWidth;
    2356           0 :             memcpy(&nWidth, &(((GByte *)pabyBuffer)[sizeof(abyJPEG1CompSig)]),
    2357             :                    2);
    2358           0 :             CPL_MSBPTR16(&nWidth);
    2359             :             GUInt16 nHeight;
    2360           0 :             memcpy(&nHeight,
    2361           0 :                    &(((GByte *)pabyBuffer)[sizeof(abyJPEG1CompSig) + 2]), 2);
    2362           0 :             CPL_MSBPTR16(&nHeight);
    2363             : 
    2364           0 :             CPLDebug("MBTILES", "JPEG: nWidth=%d nHeight=%d depth=%d nBands=%d",
    2365             :                      nWidth, nHeight, 8, 1);
    2366             : 
    2367           0 :             psTP->nBands = -2;
    2368           0 :             if (nWidth == nHeight)
    2369             :             {
    2370           0 :                 psTP->nSize = nWidth;
    2371           0 :                 psTP->nBands = 1;
    2372             :             }
    2373             : 
    2374           0 :             return FALSE;
    2375             :         }
    2376       16364 :         else if (memcmp(((GByte *)pabyBuffer) + i, abyJPEG3CompSig,
    2377           3 :                         sizeof(abyJPEG3CompSig)) == 0 &&
    2378           3 :                  ((GByte *)pabyBuffer)[sizeof(abyJPEG3CompSig) + 4] == 3)
    2379             :         {
    2380             :             GUInt16 nWidth;
    2381           0 :             memcpy(&nWidth, &(((GByte *)pabyBuffer)[sizeof(abyJPEG3CompSig)]),
    2382             :                    2);
    2383           0 :             CPL_MSBPTR16(&nWidth);
    2384             :             GUInt16 nHeight;
    2385           0 :             memcpy(&nHeight,
    2386           0 :                    &(((GByte *)pabyBuffer)[sizeof(abyJPEG3CompSig) + 2]), 2);
    2387           0 :             CPL_MSBPTR16(&nHeight);
    2388             : 
    2389           0 :             CPLDebug("MBTILES", "JPEG: nWidth=%d nHeight=%d depth=%d nBands=%d",
    2390             :                      nWidth, nHeight, 8, 3);
    2391             : 
    2392           0 :             psTP->nBands = -2;
    2393           0 :             if (nWidth == nHeight)
    2394             :             {
    2395           0 :                 psTP->nSize = nWidth;
    2396           0 :                 psTP->nBands = 3;
    2397             :             }
    2398             : 
    2399           0 :             return FALSE;
    2400             :         }
    2401             :     }
    2402             : 
    2403           2 :     return TRUE;
    2404             : }
    2405             : 
    2406             : /************************************************************************/
    2407             : /*                  MBTilesGetBandCountAndTileSize()                    */
    2408             : /************************************************************************/
    2409             : 
    2410          60 : static int MBTilesGetBandCountAndTileSize(bool bIsVSICURL, GDALDatasetH &hDS,
    2411             :                                           int nMaxLevel, int nMinTileRow,
    2412             :                                           int nMaxTileRow, int nMinTileCol,
    2413             :                                           int nMaxTileCol, int &nTileSize)
    2414             : {
    2415             :     OGRLayerH hSQLLyr;
    2416             :     OGRFeatureH hFeat;
    2417          60 :     VSILFILE *fpCURLOGR = nullptr;
    2418          60 :     int bFirstSelect = TRUE;
    2419             : 
    2420          60 :     int nBands = -1;
    2421          60 :     nTileSize = 0;
    2422             : 
    2423             :     /* Get the VSILFILE associated with the OGR SQLite DB */
    2424         120 :     CPLString osDSName(GDALGetDescription(hDS));
    2425          60 :     if (bIsVSICURL)
    2426             :     {
    2427           3 :         auto poDS = dynamic_cast<OGRSQLiteBaseDataSource *>(
    2428           6 :             GDALDataset::FromHandle(hDS));
    2429           3 :         CPLAssert(poDS);
    2430           3 :         if (poDS)
    2431             :         {
    2432           3 :             fpCURLOGR = poDS->GetVSILFILE();
    2433             :         }
    2434             :     }
    2435             : 
    2436             :     const char *pszSQL =
    2437         120 :         CPLSPrintf("SELECT tile_data FROM tiles WHERE "
    2438             :                    "tile_column = %d AND tile_row = %d AND zoom_level = %d",
    2439          60 :                    nMinTileCol / 2 + nMaxTileCol / 2,
    2440          60 :                    nMinTileRow / 2 + nMaxTileRow / 2, nMaxLevel);
    2441          60 :     CPLDebug("MBTILES", "%s", pszSQL);
    2442             : 
    2443          60 :     if (fpCURLOGR)
    2444             :     {
    2445             :         /* Install a spy on the file connection that will intercept */
    2446             :         /* PNG or JPEG headers, to interrupt their downloading */
    2447             :         /* once the header is found. Speeds up dataset opening. */
    2448           3 :         CPLErrorReset();
    2449             :         TileProperties tp;
    2450           3 :         tp.nBands = -1;
    2451           3 :         tp.nSize = 0;
    2452           3 :         VSICurlInstallReadCbk(fpCURLOGR, MBTilesCurlReadCbk, &tp, TRUE);
    2453           3 :         nBands = tp.nBands;
    2454           3 :         nTileSize = tp.nSize;
    2455             : 
    2456           3 :         CPLErrorReset();
    2457           3 :         CPLPushErrorHandler(CPLQuietErrorHandler);
    2458           3 :         hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
    2459           3 :         CPLPopErrorHandler();
    2460             : 
    2461           3 :         VSICurlUninstallReadCbk(fpCURLOGR);
    2462             : 
    2463             :         /* Did the spy intercept something interesting ? */
    2464             :         // cppcheck-suppress knownConditionTrueFalse
    2465           3 :         if (nBands != -1)
    2466             :         {
    2467           0 :             CPLErrorReset();
    2468             : 
    2469           0 :             GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    2470           0 :             hSQLLyr = nullptr;
    2471             : 
    2472             :             // Re-open OGR SQLite DB, because with our spy we have simulated an
    2473             :             // I/O error that SQLite will have difficulties to recover within
    2474             :             // the existing connection.  This will be fast because
    2475             :             // the /vsicurl/ cache has cached the already read blocks.
    2476           0 :             GDALClose(hDS);
    2477           0 :             hDS = MBTILESOpenSQLiteDB(osDSName.c_str(), GA_ReadOnly);
    2478           0 :             if (hDS == nullptr)
    2479           0 :                 return -1;
    2480             : 
    2481             :             /* Unrecognized form of PNG. Error out */
    2482           0 :             if (nBands <= 0)
    2483           0 :                 return -1;
    2484             : 
    2485           0 :             return nBands;
    2486             :         }
    2487           3 :         else if (CPLGetLastErrorType() == CE_Failure)
    2488             :         {
    2489           0 :             CPLError(CE_Failure, CPLGetLastErrorNo(), "%s",
    2490             :                      CPLGetLastErrorMsg());
    2491             :         }
    2492             :     }
    2493             :     else
    2494             :     {
    2495          57 :         hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
    2496             :     }
    2497             : 
    2498             :     while (true)
    2499             :     {
    2500          73 :         if (hSQLLyr == nullptr && bFirstSelect)
    2501             :         {
    2502          13 :             bFirstSelect = FALSE;
    2503          13 :             pszSQL = CPLSPrintf("SELECT tile_data FROM tiles WHERE "
    2504             :                                 "zoom_level = %d LIMIT 1",
    2505             :                                 nMaxLevel);
    2506          13 :             CPLDebug("MBTILES", "%s", pszSQL);
    2507          13 :             hSQLLyr = GDALDatasetExecuteSQL(hDS, pszSQL, nullptr, nullptr);
    2508          13 :             if (hSQLLyr == nullptr)
    2509           0 :                 return -1;
    2510             :         }
    2511             : 
    2512          73 :         hFeat = OGR_L_GetNextFeature(hSQLLyr);
    2513          73 :         if (hFeat == nullptr)
    2514             :         {
    2515          18 :             GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    2516          18 :             hSQLLyr = nullptr;
    2517          18 :             if (!bFirstSelect)
    2518           5 :                 return -1;
    2519             :         }
    2520             :         else
    2521          55 :             break;
    2522             :     }
    2523             : 
    2524         110 :     const CPLString osMemFileName(VSIMemGenerateHiddenFilename("mvt_temp.db"));
    2525             : 
    2526          55 :     int nDataSize = 0;
    2527          55 :     GByte *pabyData = OGR_F_GetFieldAsBinary(hFeat, 0, &nDataSize);
    2528             : 
    2529          55 :     VSIFCloseL(VSIFileFromMemBuffer(osMemFileName.c_str(), pabyData, nDataSize,
    2530             :                                     FALSE));
    2531             : 
    2532          55 :     GDALDatasetH hDSTile = GDALOpenEx(osMemFileName.c_str(), GDAL_OF_RASTER,
    2533             :                                       apszAllowedDrivers, nullptr, nullptr);
    2534          55 :     if (hDSTile == nullptr)
    2535             :     {
    2536          28 :         VSIUnlink(osMemFileName.c_str());
    2537          28 :         OGR_F_Destroy(hFeat);
    2538          28 :         GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    2539          28 :         return -1;
    2540             :     }
    2541             : 
    2542          27 :     nBands = GDALGetRasterCount(hDSTile);
    2543             : 
    2544          14 :     if ((nBands != 1 && nBands != 2 && nBands != 3 && nBands != 4) ||
    2545          68 :         GDALGetRasterXSize(hDSTile) != GDALGetRasterYSize(hDSTile) ||
    2546          27 :         GDALGetRasterDataType(GDALGetRasterBand(hDSTile, 1)) != GDT_Byte)
    2547             :     {
    2548           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    2549             :                  "Unsupported tile characteristics");
    2550           0 :         GDALClose(hDSTile);
    2551           0 :         VSIUnlink(osMemFileName.c_str());
    2552           0 :         OGR_F_Destroy(hFeat);
    2553           0 :         GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    2554           0 :         return -1;
    2555             :     }
    2556             : 
    2557          27 :     nTileSize = GDALGetRasterXSize(hDSTile);
    2558             :     GDALColorTableH hCT =
    2559          27 :         GDALGetRasterColorTable(GDALGetRasterBand(hDSTile, 1));
    2560          27 :     if (nBands == 1 && hCT != nullptr)
    2561             :     {
    2562           8 :         nBands = 3;
    2563           8 :         if (GDALGetColorEntryCount(hCT) > 0)
    2564             :         {
    2565             :             /* Typical of paletted PNG with transparency */
    2566           8 :             const GDALColorEntry *psEntry = GDALGetColorEntry(hCT, 0);
    2567           8 :             if (psEntry->c4 == 0)
    2568           0 :                 nBands = 4;
    2569             :         }
    2570             :     }
    2571             : 
    2572          27 :     GDALClose(hDSTile);
    2573          27 :     VSIUnlink(osMemFileName.c_str());
    2574          27 :     OGR_F_Destroy(hFeat);
    2575          27 :     GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    2576             : 
    2577          27 :     return nBands;
    2578             : }
    2579             : 
    2580             : /************************************************************************/
    2581             : /*                                Open()                                */
    2582             : /************************************************************************/
    2583             : 
    2584          77 : GDALDataset *MBTilesDataset::Open(GDALOpenInfo *poOpenInfo)
    2585             : {
    2586         154 :     CPLString osFileName;
    2587         154 :     CPLString osTableName;
    2588             : 
    2589          77 :     if (!Identify(poOpenInfo))
    2590           0 :         return nullptr;
    2591             : 
    2592          77 :     if ((poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) != 0 &&
    2593          52 :         (poOpenInfo->nOpenFlags & GDAL_OF_RASTER) == 0 &&
    2594          15 :         (poOpenInfo->nOpenFlags & GDAL_OF_UPDATE) != 0)
    2595             :     {
    2596           0 :         return nullptr;
    2597             :     }
    2598             : 
    2599             :     /* -------------------------------------------------------------------- */
    2600             :     /*      Open underlying OGR DB                                          */
    2601             :     /* -------------------------------------------------------------------- */
    2602             : 
    2603             :     GDALDatasetH hDS =
    2604          77 :         MBTILESOpenSQLiteDB(poOpenInfo->pszFilename, poOpenInfo->eAccess);
    2605             : 
    2606          77 :     MBTilesDataset *poDS = nullptr;
    2607             : 
    2608          77 :     if (hDS == nullptr)
    2609           0 :         goto end;
    2610             : 
    2611             :     /* -------------------------------------------------------------------- */
    2612             :     /*      Build dataset                                                   */
    2613             :     /* -------------------------------------------------------------------- */
    2614             :     {
    2615          77 :         CPLString osMetadataTableName, osRasterTableName;
    2616          77 :         CPLString osSQL;
    2617             :         OGRLayerH hMetadataLyr, hRasterLyr;
    2618             :         OGRFeatureH hFeat;
    2619             :         int nBands;
    2620          77 :         OGRLayerH hSQLLyr = nullptr;
    2621          77 :         int nMinLevel = -1;
    2622          77 :         int nMaxLevel = -1;
    2623          77 :         int bHasMinMaxLevel = FALSE;
    2624             :         int bHasMap;
    2625             : 
    2626          77 :         osMetadataTableName = "metadata";
    2627             : 
    2628             :         hMetadataLyr =
    2629          77 :             GDALDatasetGetLayerByName(hDS, osMetadataTableName.c_str());
    2630          77 :         if (hMetadataLyr == nullptr)
    2631           0 :             goto end;
    2632             : 
    2633          77 :         osRasterTableName += "tiles";
    2634             : 
    2635          77 :         hRasterLyr = GDALDatasetGetLayerByName(hDS, osRasterTableName.c_str());
    2636          77 :         if (hRasterLyr == nullptr)
    2637           0 :             goto end;
    2638             : 
    2639          77 :         bHasMap = GDALDatasetGetLayerByName(hDS, "map") != nullptr;
    2640          77 :         if (bHasMap)
    2641             :         {
    2642           0 :             bHasMap = FALSE;
    2643             : 
    2644           0 :             hSQLLyr = GDALDatasetExecuteSQL(
    2645             :                 hDS, "SELECT type FROM sqlite_master WHERE name = 'tiles'",
    2646             :                 nullptr, nullptr);
    2647           0 :             if (hSQLLyr != nullptr)
    2648             :             {
    2649           0 :                 hFeat = OGR_L_GetNextFeature(hSQLLyr);
    2650           0 :                 if (hFeat)
    2651             :                 {
    2652           0 :                     if (OGR_F_IsFieldSetAndNotNull(hFeat, 0))
    2653             :                     {
    2654           0 :                         bHasMap = strcmp(OGR_F_GetFieldAsString(hFeat, 0),
    2655           0 :                                          "view") == 0;
    2656           0 :                         if (!bHasMap)
    2657             :                         {
    2658           0 :                             CPLDebug("MBTILES", "Weird! 'tiles' is not a view, "
    2659             :                                                 "but 'map' exists");
    2660             :                         }
    2661             :                     }
    2662           0 :                     OGR_F_Destroy(hFeat);
    2663             :                 }
    2664           0 :                 GDALDatasetReleaseResultSet(hDS, hSQLLyr);
    2665             :             }
    2666             :         }
    2667             : 
    2668             :         /* --------------------------------------------------------------------
    2669             :          */
    2670             :         /*      Get minimum and maximum zoom levels */
    2671             :         /* --------------------------------------------------------------------
    2672             :          */
    2673             : 
    2674             :         bHasMinMaxLevel =
    2675          77 :             MBTilesGetMinMaxZoomLevel(hDS, bHasMap, nMinLevel, nMaxLevel);
    2676             : 
    2677             :         const char *pszZoomLevel =
    2678          77 :             CSLFetchNameValue(poOpenInfo->papszOpenOptions, "ZOOM_LEVEL");
    2679          77 :         if (pszZoomLevel != nullptr)
    2680           0 :             nMaxLevel = atoi(pszZoomLevel);
    2681             : 
    2682          77 :         if (bHasMinMaxLevel && (nMinLevel < 0 || nMinLevel > nMaxLevel))
    2683             :         {
    2684           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2685             :                      "Inconsistent values : min(zoom_level) = %d, "
    2686             :                      "max(zoom_level) = %d",
    2687             :                      nMinLevel, nMaxLevel);
    2688           0 :             goto end;
    2689             :         }
    2690             : 
    2691          77 :         if (bHasMinMaxLevel && nMaxLevel > 22)
    2692             :         {
    2693           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    2694             :                      "zoom_level > 22 not supported");
    2695           0 :             goto end;
    2696             :         }
    2697             : 
    2698          77 :         if (!bHasMinMaxLevel)
    2699             :         {
    2700           1 :             CPLError(CE_Failure, CPLE_AppDefined,
    2701             :                      "Cannot find min and max zoom_level");
    2702           1 :             goto end;
    2703             :         }
    2704             : 
    2705             :         /* --------------------------------------------------------------------
    2706             :          */
    2707             :         /*      Get bounds */
    2708             :         /* --------------------------------------------------------------------
    2709             :          */
    2710          76 :         double dfMinX = 0.0;
    2711          76 :         double dfMinY = 0.0;
    2712          76 :         double dfMaxX = 0.0;
    2713          76 :         double dfMaxY = 0.0;
    2714         152 :         bool bUseBounds = CPLFetchBool(
    2715          76 :             const_cast<const char **>(poOpenInfo->papszOpenOptions),
    2716             :             "USE_BOUNDS", true);
    2717             :         const char *pszMinX =
    2718          76 :             CSLFetchNameValue(poOpenInfo->papszOpenOptions, "MINX");
    2719             :         const char *pszMinY =
    2720          76 :             CSLFetchNameValue(poOpenInfo->papszOpenOptions, "MINY");
    2721             :         const char *pszMaxX =
    2722          76 :             CSLFetchNameValue(poOpenInfo->papszOpenOptions, "MAXX");
    2723             :         const char *pszMaxY =
    2724          76 :             CSLFetchNameValue(poOpenInfo->papszOpenOptions, "MAXY");
    2725             :         bool bHasBounds;
    2726          76 :         if (pszMinX != nullptr && pszMinY != nullptr && pszMaxX != nullptr &&
    2727             :             pszMaxY != nullptr)
    2728             :         {
    2729           0 :             bHasBounds = true;
    2730             :         }
    2731             :         else
    2732             :         {
    2733          76 :             bHasBounds = MBTilesGetBounds(hDS, bUseBounds, nMaxLevel, dfMinX,
    2734             :                                           dfMinY, dfMaxX, dfMaxY);
    2735             :         }
    2736          76 :         if (!bHasBounds)
    2737             :         {
    2738          16 :             CPLError(CE_Failure, CPLE_AppDefined,
    2739             :                      "Cannot find min and max tile numbers");
    2740          16 :             goto end;
    2741             :         }
    2742          60 :         if (pszMinX != nullptr)
    2743           0 :             dfMinX = CPLAtof(pszMinX);
    2744          60 :         if (pszMinY != nullptr)
    2745           0 :             dfMinY = CPLAtof(pszMinY);
    2746          60 :         if (pszMaxX != nullptr)
    2747           0 :             dfMaxX = CPLAtof(pszMaxX);
    2748          60 :         if (pszMaxY != nullptr)
    2749           0 :             dfMaxY = CPLAtof(pszMaxY);
    2750             : 
    2751             :         /* --------------------------------------------------------------------
    2752             :          */
    2753             :         /*      Get number of bands */
    2754             :         /* --------------------------------------------------------------------
    2755             :          */
    2756             :         int nMinTileCol =
    2757          60 :             static_cast<int>(MBTilesWorldCoordToTileCoord(dfMinX, nMaxLevel));
    2758             :         int nMinTileRow =
    2759          60 :             static_cast<int>(MBTilesWorldCoordToTileCoord(dfMinY, nMaxLevel));
    2760             :         int nMaxTileCol =
    2761          60 :             static_cast<int>(MBTilesWorldCoordToTileCoord(dfMaxX, nMaxLevel));
    2762             :         int nMaxTileRow =
    2763          60 :             static_cast<int>(MBTilesWorldCoordToTileCoord(dfMaxY, nMaxLevel));
    2764          60 :         int nTileSize = 0;
    2765         120 :         nBands = MBTilesGetBandCountAndTileSize(
    2766          60 :             STARTS_WITH_CI(poOpenInfo->pszFilename, "/vsicurl/"), hDS,
    2767             :             nMaxLevel, nMinTileRow, nMaxTileRow, nMinTileCol, nMaxTileCol,
    2768             :             nTileSize);
    2769          60 :         bool bFoundRasterTile = nBands > 0;
    2770          60 :         if (!bFoundRasterTile)
    2771          33 :             nTileSize = knDEFAULT_BLOCK_SIZE;
    2772             : 
    2773             :         // Force 4 bands by default (see #6119)
    2774          60 :         nBands = 4;
    2775             : 
    2776          60 :         const char *pszBandCount = CSLFetchNameValueDef(
    2777          60 :             poOpenInfo->papszOpenOptions, "BAND_COUNT",
    2778             :             CPLGetConfigOption("MBTILES_BAND_COUNT", nullptr));
    2779          60 :         if (pszBandCount)
    2780             :         {
    2781           1 :             int nTmpBands = atoi(pszBandCount);
    2782           1 :             if (nTmpBands >= 1 && nTmpBands <= 4)
    2783           1 :                 nBands = nTmpBands;
    2784             :         }
    2785             : 
    2786          60 :         if (poOpenInfo->eAccess == GA_Update)
    2787             :         {
    2788             :             // So that we can edit all potential overviews
    2789           4 :             nMinLevel = 0;
    2790             :         }
    2791             : 
    2792             :         /* --------------------------------------------------------------------
    2793             :          */
    2794             :         /*      Set dataset attributes */
    2795             :         /* --------------------------------------------------------------------
    2796             :          */
    2797             : 
    2798          60 :         poDS = new MBTilesDataset();
    2799          60 :         poDS->eAccess = poOpenInfo->eAccess;
    2800          60 :         poDS->hDS = hDS;
    2801          60 :         poDS->hDB = (sqlite3 *)GDALGetInternalHandle((GDALDatasetH)hDS,
    2802             :                                                      "SQLITE_HANDLE");
    2803          60 :         CPLAssert(poDS->hDB != nullptr);
    2804             : 
    2805             :         /* poDS will release it from now */
    2806          60 :         hDS = nullptr;
    2807             : 
    2808             :         poDS->m_osClip =
    2809          60 :             CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "CLIP", "");
    2810          60 :         poDS->m_nMinZoomLevel = nMinLevel;
    2811          60 :         bool bRasterOK = poDS->InitRaster(nullptr, nMaxLevel, nBands, nTileSize,
    2812             :                                           dfMinX, dfMinY, dfMaxX, dfMaxY);
    2813             : 
    2814          60 :         const char *pszFormat = poDS->GetMetadataItem("format");
    2815          60 :         if (pszFormat != nullptr && EQUAL(pszFormat, "pbf"))
    2816             :         {
    2817          33 :             if ((poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) == 0)
    2818             :             {
    2819           1 :                 CPLDebug("MBTiles", "This files contain vector tiles, "
    2820             :                                     "but driver open in raster-only mode");
    2821           1 :                 delete poDS;
    2822           1 :                 return nullptr;
    2823             :             }
    2824          64 :             poDS->InitVector(dfMinX, dfMinY, dfMaxX, dfMaxY,
    2825          32 :                              CPLFetchBool(poOpenInfo->papszOpenOptions,
    2826             :                                           "ZOOM_LEVEL_AUTO",
    2827          32 :                                           CPLTestBool(CPLGetConfigOption(
    2828             :                                               "MVT_ZOOM_LEVEL_AUTO", "NO"))),
    2829          32 :                              CPLFetchBool(poOpenInfo->papszOpenOptions,
    2830             :                                           "JSON_FIELD", false));
    2831             :         }
    2832          27 :         else if ((pszFormat != nullptr && !EQUAL(pszFormat, "pbf")) ||
    2833             :                  bFoundRasterTile)
    2834             :         {
    2835          27 :             if ((poOpenInfo->nOpenFlags & GDAL_OF_RASTER) == 0)
    2836             :             {
    2837           1 :                 CPLDebug("MBTiles", "This files contain raster tiles, "
    2838             :                                     "but driver open in vector-only mode");
    2839           1 :                 delete poDS;
    2840           1 :                 return nullptr;
    2841             :             }
    2842             :         }
    2843             : 
    2844          58 :         if ((pszFormat == nullptr || !EQUAL(pszFormat, "pbf")) && !bRasterOK)
    2845             :         {
    2846           0 :             delete poDS;
    2847           0 :             return nullptr;
    2848             :         }
    2849             : 
    2850          58 :         if (poDS->eAccess == GA_Update)
    2851             :         {
    2852           4 :             if (pszFormat != nullptr &&
    2853           4 :                 (EQUAL(pszFormat, "jpg") || EQUAL(pszFormat, "jpeg")))
    2854             :             {
    2855           0 :                 poDS->m_eTF = GPKG_TF_JPEG;
    2856             :             }
    2857           4 :             else if (pszFormat != nullptr && (EQUAL(pszFormat, "webp")))
    2858             :             {
    2859           0 :                 poDS->m_eTF = GPKG_TF_WEBP;
    2860             :             }
    2861             : 
    2862             :             const char *pszTF =
    2863           4 :                 CSLFetchNameValue(poOpenInfo->papszOpenOptions, "TILE_FORMAT");
    2864           4 :             if (pszTF)
    2865             :             {
    2866           0 :                 poDS->m_eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
    2867           0 :                 if ((pszFormat != nullptr &&
    2868           0 :                      (EQUAL(pszFormat, "jpg") || EQUAL(pszFormat, "jpeg")) &&
    2869           0 :                      poDS->m_eTF != GPKG_TF_JPEG) ||
    2870           0 :                     (pszFormat != nullptr && EQUAL(pszFormat, "webp") &&
    2871           0 :                      poDS->m_eTF != GPKG_TF_WEBP) ||
    2872           0 :                     (pszFormat != nullptr && EQUAL(pszFormat, "png") &&
    2873           0 :                      poDS->m_eTF == GPKG_TF_JPEG))
    2874             :                 {
    2875           0 :                     CPLError(CE_Warning, CPLE_AppDefined,
    2876             :                              "Format metadata = '%s', but TILE_FORMAT='%s'",
    2877             :                              pszFormat, pszTF);
    2878             :                 }
    2879             :             }
    2880             : 
    2881           4 :             poDS->ParseCompressionOptions(poOpenInfo->papszOpenOptions);
    2882             :         }
    2883             : 
    2884             :         /* --------------------------------------------------------------------
    2885             :          */
    2886             :         /*      Add overview levels as internal datasets */
    2887             :         /* --------------------------------------------------------------------
    2888             :          */
    2889          71 :         for (int iLevel = nMaxLevel - 1; iLevel >= nMinLevel; iLevel--)
    2890             :         {
    2891          44 :             MBTilesDataset *poOvrDS = new MBTilesDataset();
    2892          44 :             poOvrDS->ShareLockWithParentDataset(poDS);
    2893          44 :             poOvrDS->InitRaster(poDS, iLevel, nBands, nTileSize, dfMinX, dfMinY,
    2894             :                                 dfMaxX, dfMaxY);
    2895             : 
    2896          88 :             poDS->m_papoOverviewDS = (MBTilesDataset **)CPLRealloc(
    2897          44 :                 poDS->m_papoOverviewDS,
    2898          44 :                 sizeof(MBTilesDataset *) * (poDS->m_nOverviewCount + 1));
    2899          44 :             poDS->m_papoOverviewDS[poDS->m_nOverviewCount++] = poOvrDS;
    2900             : 
    2901          75 :             if (poOvrDS->GetRasterXSize() < 256 &&
    2902          31 :                 poOvrDS->GetRasterYSize() < 256)
    2903             :             {
    2904          31 :                 break;
    2905             :             }
    2906             :         }
    2907             : 
    2908             :         /* --------------------------------------------------------------------
    2909             :          */
    2910             :         /*      Initialize any PAM information. */
    2911             :         /* --------------------------------------------------------------------
    2912             :          */
    2913          58 :         poDS->SetDescription(poOpenInfo->pszFilename);
    2914             : 
    2915          58 :         if (!STARTS_WITH_CI(poOpenInfo->pszFilename, "/vsicurl/"))
    2916          55 :             poDS->TryLoadXML();
    2917             :         else
    2918             :         {
    2919           3 :             poDS->SetPamFlags(poDS->GetPamFlags() & ~GPF_DIRTY);
    2920             :         }
    2921             :     }
    2922             : 
    2923          75 : end:
    2924          75 :     if (hDS)
    2925          17 :         GDALClose(hDS);
    2926             : 
    2927          75 :     return poDS;
    2928             : }
    2929             : 
    2930             : /************************************************************************/
    2931             : /*                                Create()                              */
    2932             : /************************************************************************/
    2933             : 
    2934          82 : GDALDataset *MBTilesDataset::Create(const char *pszFilename, int nXSize,
    2935             :                                     int nYSize, int nBandsIn, GDALDataType eDT,
    2936             :                                     char **papszOptions)
    2937             : {
    2938             : #ifdef HAVE_MVT_WRITE_SUPPORT
    2939          82 :     if (nXSize == 0 && nYSize == 0 && nBandsIn == 0 && eDT == GDT_Unknown)
    2940             :     {
    2941          41 :         char **papszOptionsMod = CSLDuplicate(papszOptions);
    2942          41 :         papszOptionsMod = CSLSetNameValue(papszOptionsMod, "FORMAT", "MBTILES");
    2943          41 :         GDALDataset *poRet = OGRMVTWriterDatasetCreate(
    2944             :             pszFilename, nXSize, nYSize, nBandsIn, eDT, papszOptionsMod);
    2945          41 :         CSLDestroy(papszOptionsMod);
    2946          41 :         return poRet;
    2947             :     }
    2948             : #endif
    2949             : 
    2950          41 :     MBTilesDataset *poDS = new MBTilesDataset();
    2951          41 :     if (!poDS->CreateInternal(pszFilename, nXSize, nYSize, nBandsIn, eDT,
    2952             :                               papszOptions))
    2953             :     {
    2954          13 :         delete poDS;
    2955          13 :         poDS = nullptr;
    2956             :     }
    2957          41 :     return poDS;
    2958             : }
    2959             : 
    2960             : /************************************************************************/
    2961             : /*                            CreateInternal()                          */
    2962             : /************************************************************************/
    2963             : 
    2964          41 : bool MBTilesDataset::CreateInternal(const char *pszFilename, int nXSize,
    2965             :                                     int nYSize, int nBandsIn, GDALDataType eDT,
    2966             :                                     char **papszOptions)
    2967             : {
    2968          41 :     if (eDT != GDT_Byte)
    2969             :     {
    2970           0 :         CPLError(CE_Failure, CPLE_NotSupported, "Only Byte supported");
    2971           0 :         return false;
    2972             :     }
    2973          41 :     if (nBandsIn != 1 && nBandsIn != 2 && nBandsIn != 3 && nBandsIn != 4)
    2974             :     {
    2975           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    2976             :                  "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), 3 (RGB) or 4 "
    2977             :                  "(RGBA) band dataset supported");
    2978           0 :         return false;
    2979             :     }
    2980             : 
    2981             :     // for test/debug purposes only. true is the nominal value
    2982          41 :     m_bPNGSupports2Bands =
    2983          41 :         CPLTestBool(CPLGetConfigOption("MBTILES_PNG_SUPPORTS_2BANDS", "TRUE"));
    2984          41 :     m_bPNGSupportsCT =
    2985          41 :         CPLTestBool(CPLGetConfigOption("MBTILES_PNG_SUPPORTS_CT", "TRUE"));
    2986          41 :     m_bWriteBounds = CPLFetchBool(const_cast<const char **>(papszOptions),
    2987             :                                   "WRITE_BOUNDS", true);
    2988          41 :     m_bWriteMinMaxZoom = CPLFetchBool(const_cast<const char **>(papszOptions),
    2989             :                                       "WRITE_MINMAXZOOM", true);
    2990             :     int nBlockSize = std::max(
    2991          41 :         64, std::min(8192, atoi(CSLFetchNameValueDef(
    2992             :                                papszOptions, "BLOCKSIZE",
    2993          41 :                                CPLSPrintf("%d", knDEFAULT_BLOCK_SIZE)))));
    2994          41 :     m_osBounds = CSLFetchNameValueDef(papszOptions, "BOUNDS", "");
    2995          41 :     m_osCenter = CSLFetchNameValueDef(papszOptions, "CENTER", "");
    2996             : 
    2997          41 :     VSIUnlink(pszFilename);
    2998          41 :     SetDescription(pszFilename);
    2999             : 
    3000             :     int rc;
    3001          41 :     if (STARTS_WITH(pszFilename, "/vsi"))
    3002             :     {
    3003          23 :         pMyVFS = OGRSQLiteCreateVFS(nullptr, nullptr);
    3004          23 :         sqlite3_vfs_register(pMyVFS, 0);
    3005          23 :         rc = sqlite3_open_v2(pszFilename, &hDB,
    3006             :                              SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
    3007          23 :                              pMyVFS->zName);
    3008             :     }
    3009             :     else
    3010             :     {
    3011          18 :         rc = sqlite3_open(pszFilename, &hDB);
    3012             :     }
    3013             : 
    3014          41 :     if (rc != SQLITE_OK)
    3015             :     {
    3016           3 :         CPLError(CE_Failure, CPLE_FileIO, "Cannot create %s", pszFilename);
    3017           3 :         return false;
    3018             :     }
    3019             : 
    3020          38 :     sqlite3_exec(hDB, "PRAGMA synchronous = OFF", nullptr, nullptr, nullptr);
    3021             : 
    3022          38 :     rc = sqlite3_exec(hDB,
    3023             :                       "CREATE TABLE tiles ("
    3024             :                       "zoom_level INTEGER NOT NULL,"
    3025             :                       "tile_column INTEGER NOT NULL,"
    3026             :                       "tile_row INTEGER NOT NULL,"
    3027             :                       "tile_data BLOB NOT NULL,"
    3028             :                       "UNIQUE (zoom_level, tile_column, tile_row) )",
    3029             :                       nullptr, nullptr, nullptr);
    3030          38 :     if (rc != SQLITE_OK)
    3031             :     {
    3032           8 :         CPLError(CE_Failure, CPLE_FileIO, "Cannot create tiles table");
    3033           8 :         return false;
    3034             :     }
    3035             : 
    3036          30 :     rc = sqlite3_exec(hDB, "CREATE TABLE metadata (name TEXT, value TEXT)",
    3037             :                       nullptr, nullptr, nullptr);
    3038          30 :     if (rc != SQLITE_OK)
    3039             :     {
    3040           2 :         CPLError(CE_Failure, CPLE_FileIO, "Cannot create metadata table");
    3041           2 :         return false;
    3042             :     }
    3043             : 
    3044             :     const std::string osName = CSLFetchNameValueDef(
    3045          84 :         papszOptions, "NAME", CPLGetBasenameSafe(pszFilename).c_str());
    3046          28 :     char *pszSQL = sqlite3_mprintf(
    3047             :         "INSERT INTO metadata (name, value) VALUES ('name', '%q')",
    3048             :         osName.c_str());
    3049          28 :     sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
    3050          28 :     sqlite3_free(pszSQL);
    3051             : 
    3052          28 :     const char *pszType = CSLFetchNameValueDef(papszOptions, "TYPE", "overlay");
    3053          28 :     pszSQL = sqlite3_mprintf(
    3054             :         "INSERT INTO metadata (name, value) VALUES ('type', '%q')", pszType);
    3055          28 :     sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
    3056          28 :     sqlite3_free(pszSQL);
    3057             : 
    3058             :     const std::string osDescription = CSLFetchNameValueDef(
    3059          84 :         papszOptions, "DESCRIPTION", CPLGetBasenameSafe(pszFilename).c_str());
    3060          28 :     pszSQL = sqlite3_mprintf(
    3061             :         "INSERT INTO metadata (name, value) VALUES ('description', '%q')",
    3062             :         osDescription.c_str());
    3063          28 :     sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
    3064          28 :     sqlite3_free(pszSQL);
    3065             : 
    3066          28 :     const char *pszTF = CSLFetchNameValue(papszOptions, "TILE_FORMAT");
    3067          28 :     if (pszTF)
    3068           3 :         m_eTF = GDALGPKGMBTilesGetTileFormat(pszTF);
    3069             : 
    3070          28 :     const char *pszVersion = CSLFetchNameValueDef(
    3071          28 :         papszOptions, "VERSION", (m_eTF == GPKG_TF_WEBP) ? "1.3" : "1.1");
    3072          28 :     pszSQL = sqlite3_mprintf(
    3073             :         "INSERT INTO metadata (name, value) VALUES ('version', '%q')",
    3074             :         pszVersion);
    3075          28 :     sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
    3076          28 :     sqlite3_free(pszSQL);
    3077             : 
    3078          28 :     const char *pszFormat = CSLFetchNameValueDef(
    3079             :         papszOptions, "FORMAT", GDALMBTilesGetTileFormatName(m_eTF));
    3080          28 :     pszSQL = sqlite3_mprintf(
    3081             :         "INSERT INTO metadata (name, value) VALUES ('format', '%q')",
    3082             :         pszFormat);
    3083          28 :     sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
    3084          28 :     sqlite3_free(pszSQL);
    3085             : 
    3086          28 :     m_bNew = true;
    3087          28 :     eAccess = GA_Update;
    3088          28 :     nRasterXSize = nXSize;
    3089          28 :     nRasterYSize = nYSize;
    3090             : 
    3091          28 :     m_pabyCachedTiles =
    3092          28 :         (GByte *)VSI_MALLOC3_VERBOSE(4 * 4, nBlockSize, nBlockSize);
    3093          28 :     if (m_pabyCachedTiles == nullptr)
    3094             :     {
    3095           0 :         return false;
    3096             :     }
    3097             : 
    3098          83 :     for (int i = 1; i <= nBandsIn; i++)
    3099          55 :         SetBand(i, new MBTilesBand(this, nBlockSize));
    3100             : 
    3101          28 :     ParseCompressionOptions(papszOptions);
    3102             : 
    3103          28 :     return true;
    3104             : }
    3105             : 
    3106             : /************************************************************************/
    3107             : /*                            CreateCopy()                              */
    3108             : /************************************************************************/
    3109             : 
    3110             : typedef struct
    3111             : {
    3112             :     const char *pszName;
    3113             :     GDALResampleAlg eResampleAlg;
    3114             : } WarpResamplingAlg;
    3115             : 
    3116             : static const WarpResamplingAlg asResamplingAlg[] = {
    3117             :     {"NEAREST", GRA_NearestNeighbour},
    3118             :     {"BILINEAR", GRA_Bilinear},
    3119             :     {"CUBIC", GRA_Cubic},
    3120             :     {"CUBICSPLINE", GRA_CubicSpline},
    3121             :     {"LANCZOS", GRA_Lanczos},
    3122             :     {"MODE", GRA_Mode},
    3123             :     {"AVERAGE", GRA_Average},
    3124             :     {"RMS", GRA_RMS},
    3125             : };
    3126             : 
    3127          38 : GDALDataset *MBTilesDataset::CreateCopy(const char *pszFilename,
    3128             :                                         GDALDataset *poSrcDS, int /*bStrict*/,
    3129             :                                         char **papszOptions,
    3130             :                                         GDALProgressFunc pfnProgress,
    3131             :                                         void *pProgressData)
    3132             : {
    3133             : 
    3134          38 :     int nBands = poSrcDS->GetRasterCount();
    3135          38 :     if (nBands != 1 && nBands != 2 && nBands != 3 && nBands != 4)
    3136             :     {
    3137           2 :         CPLError(CE_Failure, CPLE_NotSupported,
    3138             :                  "Only 1 (Grey/ColorTable), 2 (Grey+Alpha), 3 (RGB) or 4 "
    3139             :                  "(RGBA) band dataset supported");
    3140           2 :         return nullptr;
    3141             :     }
    3142             : 
    3143          36 :     char **papszTO = CSLSetNameValue(nullptr, "DST_SRS", SRS_EPSG_3857);
    3144             : 
    3145          36 :     void *hTransformArg = nullptr;
    3146             : 
    3147             :     // Hack to compensate for GDALSuggestedWarpOutput2() failure (or not
    3148             :     // ideal suggestion with PROJ 8) when reprojecting latitude = +/- 90 to
    3149             :     // EPSG:3857.
    3150          36 :     GDALGeoTransform srcGT;
    3151          36 :     std::unique_ptr<GDALDataset> poTmpDS;
    3152          36 :     bool bModifiedMaxLat = false;
    3153          36 :     bool bModifiedMinLat = false;
    3154          36 :     const auto poSrcSRS = poSrcDS->GetSpatialRef();
    3155          72 :     if (poSrcDS->GetGeoTransform(srcGT) == CE_None && srcGT[2] == 0 &&
    3156          72 :         srcGT[4] == 0 && srcGT[5] < 0)
    3157             :     {
    3158          36 :         if (poSrcSRS && poSrcSRS->IsGeographic())
    3159             :         {
    3160          30 :             double maxLat = srcGT[3];
    3161          30 :             double minLat = srcGT[3] + poSrcDS->GetRasterYSize() * srcGT[5];
    3162             :             // Corresponds to the latitude of MAX_GM
    3163          30 :             constexpr double MAX_LAT = 85.0511287798066;
    3164          30 :             if (maxLat > MAX_LAT)
    3165             :             {
    3166           3 :                 maxLat = MAX_LAT;
    3167           3 :                 bModifiedMaxLat = true;
    3168             :             }
    3169          30 :             if (minLat < -MAX_LAT)
    3170             :             {
    3171           3 :                 minLat = -MAX_LAT;
    3172           3 :                 bModifiedMinLat = true;
    3173             :             }
    3174          30 :             if (bModifiedMaxLat || bModifiedMinLat)
    3175             :             {
    3176           6 :                 CPLStringList aosOptions;
    3177           3 :                 aosOptions.AddString("-of");
    3178           3 :                 aosOptions.AddString("VRT");
    3179           3 :                 aosOptions.AddString("-projwin");
    3180           3 :                 aosOptions.AddString(CPLSPrintf("%.17g", srcGT[0]));
    3181           3 :                 aosOptions.AddString(CPLSPrintf("%.17g", maxLat));
    3182             :                 aosOptions.AddString(CPLSPrintf(
    3183           3 :                     "%.17g", srcGT[0] + poSrcDS->GetRasterXSize() * srcGT[1]));
    3184           3 :                 aosOptions.AddString(CPLSPrintf("%.17g", minLat));
    3185             :                 auto psOptions =
    3186           3 :                     GDALTranslateOptionsNew(aosOptions.List(), nullptr);
    3187           3 :                 poTmpDS.reset(GDALDataset::FromHandle(GDALTranslate(
    3188             :                     "", GDALDataset::ToHandle(poSrcDS), psOptions, nullptr)));
    3189           3 :                 GDALTranslateOptionsFree(psOptions);
    3190           3 :                 if (poTmpDS)
    3191             :                 {
    3192           3 :                     hTransformArg = GDALCreateGenImgProjTransformer2(
    3193           3 :                         GDALDataset::FromHandle(poTmpDS.get()), nullptr,
    3194             :                         papszTO);
    3195             :                 }
    3196             :             }
    3197             :         }
    3198             :     }
    3199          36 :     if (hTransformArg == nullptr)
    3200             :     {
    3201             :         hTransformArg =
    3202          33 :             GDALCreateGenImgProjTransformer2(poSrcDS, nullptr, papszTO);
    3203             :     }
    3204          36 :     if (hTransformArg == nullptr)
    3205             :     {
    3206           0 :         CSLDestroy(papszTO);
    3207           0 :         return nullptr;
    3208             :     }
    3209             : 
    3210          36 :     GDALTransformerInfo *psInfo = (GDALTransformerInfo *)hTransformArg;
    3211          36 :     GDALGeoTransform gt;
    3212             :     double adfExtent[4];
    3213             :     int nXSize, nYSize;
    3214             : 
    3215          36 :     if (GDALSuggestedWarpOutput2(poSrcDS, psInfo->pfnTransform, hTransformArg,
    3216             :                                  gt.data(), &nXSize, &nYSize, adfExtent,
    3217          36 :                                  0) != CE_None)
    3218             :     {
    3219           0 :         CSLDestroy(papszTO);
    3220           0 :         GDALDestroyGenImgProjTransformer(hTransformArg);
    3221           0 :         return nullptr;
    3222             :     }
    3223             : 
    3224          36 :     GDALDestroyGenImgProjTransformer(hTransformArg);
    3225          36 :     hTransformArg = nullptr;
    3226          36 :     poTmpDS.reset();
    3227             : 
    3228          36 :     if (bModifiedMaxLat || bModifiedMinLat)
    3229             :     {
    3230           3 :         if (bModifiedMaxLat)
    3231             :         {
    3232           3 :             const double maxNorthing = MAX_GM;
    3233           3 :             gt[3] = maxNorthing;
    3234           3 :             adfExtent[3] = maxNorthing;
    3235             :         }
    3236           3 :         if (bModifiedMinLat)
    3237             :         {
    3238           3 :             const double minNorthing = -MAX_GM;
    3239           3 :             adfExtent[1] = minNorthing;
    3240             :         }
    3241             : 
    3242           3 :         if (poSrcSRS && poSrcSRS->IsGeographic())
    3243             :         {
    3244           3 :             if (srcGT[0] + poSrcDS->GetRasterXSize() * srcGT[1] == 180)
    3245             :             {
    3246           3 :                 adfExtent[2] = MAX_GM;
    3247             :             }
    3248             :         }
    3249             :     }
    3250             : 
    3251             :     int nZoomLevel;
    3252          36 :     double dfComputedRes = gt[1];
    3253          36 :     double dfPrevRes = 0.0;
    3254          36 :     double dfRes = 0.0;
    3255             :     int nBlockSize = std::max(
    3256          36 :         64, std::min(8192, atoi(CSLFetchNameValueDef(
    3257             :                                papszOptions, "BLOCKSIZE",
    3258          36 :                                CPLSPrintf("%d", knDEFAULT_BLOCK_SIZE)))));
    3259          36 :     const double dfPixelXSizeZoomLevel0 = 2 * MAX_GM / nBlockSize;
    3260         242 :     for (nZoomLevel = 0; nZoomLevel < 25; nZoomLevel++)
    3261             :     {
    3262         242 :         dfRes = dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
    3263         242 :         if (dfComputedRes > dfRes)
    3264          36 :             break;
    3265         206 :         dfPrevRes = dfRes;
    3266             :     }
    3267          36 :     if (nZoomLevel == 25)
    3268             :     {
    3269           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3270             :                  "Could not find an appropriate zoom level");
    3271           0 :         CSLDestroy(papszTO);
    3272           0 :         return nullptr;
    3273             :     }
    3274             : 
    3275             :     const char *pszZoomLevelStrategy =
    3276          36 :         CSLFetchNameValueDef(papszOptions, "ZOOM_LEVEL_STRATEGY", "AUTO");
    3277          36 :     if (fabs(dfComputedRes - dfRes) / dfRes > 1e-8)
    3278             :     {
    3279          36 :         if (EQUAL(pszZoomLevelStrategy, "LOWER"))
    3280             :         {
    3281           0 :             if (nZoomLevel > 0)
    3282           0 :                 nZoomLevel--;
    3283             :         }
    3284          36 :         else if (EQUAL(pszZoomLevelStrategy, "UPPER"))
    3285             :         {
    3286             :             /* do nothing */
    3287             :         }
    3288          36 :         else if (nZoomLevel > 0)
    3289             :         {
    3290          35 :             if (dfPrevRes / dfComputedRes < dfComputedRes / dfRes)
    3291          33 :                 nZoomLevel--;
    3292             :         }
    3293             :     }
    3294             : 
    3295          36 :     dfRes = dfPixelXSizeZoomLevel0 / (1 << nZoomLevel);
    3296             : 
    3297          36 :     double dfMinX = adfExtent[0];
    3298          36 :     double dfMinY = adfExtent[1];
    3299          36 :     double dfMaxX = adfExtent[2];
    3300          36 :     double dfMaxY = adfExtent[3];
    3301             : 
    3302          36 :     nXSize = (int)(0.5 + (dfMaxX - dfMinX) / dfRes);
    3303          36 :     nYSize = (int)(0.5 + (dfMaxY - dfMinY) / dfRes);
    3304          36 :     gt[1] = dfRes;
    3305          36 :     gt[5] = -dfRes;
    3306             : 
    3307          36 :     int nTargetBands = nBands;
    3308             :     /* For grey level or RGB, if there's reprojection involved, add an alpha */
    3309             :     /* channel */
    3310          68 :     if ((nBands == 1 &&
    3311          36 :          poSrcDS->GetRasterBand(1)->GetColorTable() == nullptr) ||
    3312             :         nBands == 3)
    3313             :     {
    3314          64 :         OGRSpatialReference oSrcSRS;
    3315          32 :         oSrcSRS.SetFromUserInput(poSrcDS->GetProjectionRef());
    3316          32 :         oSrcSRS.AutoIdentifyEPSG();
    3317          39 :         if (oSrcSRS.GetAuthorityCode(nullptr) == nullptr ||
    3318           7 :             atoi(oSrcSRS.GetAuthorityCode(nullptr)) != 3857)
    3319             :         {
    3320          32 :             nTargetBands++;
    3321             :         }
    3322             :     }
    3323             : 
    3324          36 :     GDALResampleAlg eResampleAlg = GRA_Bilinear;
    3325          36 :     const char *pszResampling = CSLFetchNameValue(papszOptions, "RESAMPLING");
    3326          36 :     if (pszResampling)
    3327             :     {
    3328           4 :         for (size_t iAlg = 0;
    3329           4 :              iAlg < sizeof(asResamplingAlg) / sizeof(asResamplingAlg[0]);
    3330             :              iAlg++)
    3331             :         {
    3332           4 :             if (EQUAL(pszResampling, asResamplingAlg[iAlg].pszName))
    3333             :             {
    3334           4 :                 eResampleAlg = asResamplingAlg[iAlg].eResampleAlg;
    3335           4 :                 break;
    3336             :             }
    3337             :         }
    3338             :     }
    3339             : 
    3340          32 :     if (nBands == 1 && poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr &&
    3341          68 :         eResampleAlg != GRA_NearestNeighbour && eResampleAlg != GRA_Mode)
    3342             :     {
    3343           0 :         CPLError(
    3344             :             CE_Warning, CPLE_AppDefined,
    3345             :             "Input dataset has a color table, which will likely lead to "
    3346             :             "bad results when using a resampling method other than "
    3347             :             "nearest neighbour or mode. Converting the dataset to 24/32 bit "
    3348             :             "(e.g. with gdal_translate -expand rgb/rgba) is advised.");
    3349             :     }
    3350             : 
    3351          36 :     GDALDataset *poDS = Create(pszFilename, nXSize, nYSize, nTargetBands,
    3352             :                                GDT_Byte, papszOptions);
    3353          36 :     if (poDS == nullptr)
    3354             :     {
    3355          13 :         CSLDestroy(papszTO);
    3356          13 :         return nullptr;
    3357             :     }
    3358          23 :     poDS->SetGeoTransform(gt);
    3359          25 :     if (nTargetBands == 1 && nBands == 1 &&
    3360           2 :         poSrcDS->GetRasterBand(1)->GetColorTable() != nullptr)
    3361             :     {
    3362           4 :         poDS->GetRasterBand(1)->SetColorTable(
    3363           2 :             poSrcDS->GetRasterBand(1)->GetColorTable());
    3364             :     }
    3365             : 
    3366          23 :     hTransformArg = GDALCreateGenImgProjTransformer2(poSrcDS, poDS, papszTO);
    3367          23 :     CSLDestroy(papszTO);
    3368          23 :     if (hTransformArg == nullptr)
    3369             :     {
    3370           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3371             :                  "GDALCreateGenImgProjTransformer2 failed");
    3372           0 :         delete poDS;
    3373           0 :         return nullptr;
    3374             :     }
    3375             : 
    3376             :     /* -------------------------------------------------------------------- */
    3377             :     /*      Warp the transformer with a linear approximator                 */
    3378             :     /* -------------------------------------------------------------------- */
    3379          23 :     hTransformArg = GDALCreateApproxTransformer(GDALGenImgProjTransform,
    3380             :                                                 hTransformArg, 0.125);
    3381          23 :     GDALApproxTransformerOwnsSubtransformer(hTransformArg, TRUE);
    3382             : 
    3383             :     /* -------------------------------------------------------------------- */
    3384             :     /*      Setup warp options.                                             */
    3385             :     /* -------------------------------------------------------------------- */
    3386          23 :     GDALWarpOptions *psWO = GDALCreateWarpOptions();
    3387             : 
    3388          23 :     psWO->papszWarpOptions = CSLSetNameValue(nullptr, "OPTIMIZE_SIZE", "YES");
    3389          23 :     psWO->eWorkingDataType = GDT_Byte;
    3390             : 
    3391          23 :     psWO->eResampleAlg = eResampleAlg;
    3392             : 
    3393          23 :     psWO->hSrcDS = poSrcDS;
    3394          23 :     psWO->hDstDS = poDS;
    3395             : 
    3396          23 :     psWO->pfnTransformer = GDALApproxTransform;
    3397          23 :     psWO->pTransformerArg = hTransformArg;
    3398             : 
    3399          23 :     psWO->pfnProgress = pfnProgress;
    3400          23 :     psWO->pProgressArg = pProgressData;
    3401             : 
    3402             :     /* -------------------------------------------------------------------- */
    3403             :     /*      Setup band mapping.                                             */
    3404             :     /* -------------------------------------------------------------------- */
    3405             : 
    3406          23 :     if (nBands == 2 || nBands == 4)
    3407           2 :         psWO->nBandCount = nBands - 1;
    3408             :     else
    3409          21 :         psWO->nBandCount = nBands;
    3410             : 
    3411          23 :     psWO->panSrcBands = (int *)CPLMalloc(psWO->nBandCount * sizeof(int));
    3412          23 :     psWO->panDstBands = (int *)CPLMalloc(psWO->nBandCount * sizeof(int));
    3413             : 
    3414          52 :     for (int i = 0; i < psWO->nBandCount; i++)
    3415             :     {
    3416          29 :         psWO->panSrcBands[i] = i + 1;
    3417          29 :         psWO->panDstBands[i] = i + 1;
    3418             :     }
    3419             : 
    3420          23 :     if (nBands == 2 || nBands == 4)
    3421             :     {
    3422           2 :         psWO->nSrcAlphaBand = nBands;
    3423             :     }
    3424          23 :     if (nTargetBands == 2 || nTargetBands == 4)
    3425             :     {
    3426          21 :         psWO->nDstAlphaBand = nTargetBands;
    3427             :     }
    3428             : 
    3429             :     /* -------------------------------------------------------------------- */
    3430             :     /*      Initialize and execute the warp.                                */
    3431             :     /* -------------------------------------------------------------------- */
    3432          23 :     GDALWarpOperation oWO;
    3433             : 
    3434          23 :     CPLErr eErr = oWO.Initialize(psWO);
    3435          23 :     if (eErr == CE_None)
    3436             :     {
    3437             :         /*if( bMulti )
    3438             :             eErr = oWO.ChunkAndWarpMulti( 0, 0, nXSize, nYSize );
    3439             :         else*/
    3440          23 :         eErr = oWO.ChunkAndWarpImage(0, 0, nXSize, nYSize);
    3441             :     }
    3442          23 :     if (eErr != CE_None)
    3443             :     {
    3444           0 :         delete poDS;
    3445           0 :         poDS = nullptr;
    3446             :     }
    3447             : 
    3448          23 :     GDALDestroyTransformer(hTransformArg);
    3449          23 :     GDALDestroyWarpOptions(psWO);
    3450             : 
    3451          23 :     return poDS;
    3452             : }
    3453             : 
    3454             : /************************************************************************/
    3455             : /*                        ParseCompressionOptions()                     */
    3456             : /************************************************************************/
    3457             : 
    3458          32 : void MBTilesDataset::ParseCompressionOptions(char **papszOptions)
    3459             : {
    3460          32 :     const char *pszZLevel = CSLFetchNameValue(papszOptions, "ZLEVEL");
    3461          32 :     if (pszZLevel)
    3462           0 :         m_nZLevel = atoi(pszZLevel);
    3463             : 
    3464          32 :     const char *pszQuality = CSLFetchNameValue(papszOptions, "QUALITY");
    3465          32 :     if (pszQuality)
    3466           2 :         m_nQuality = atoi(pszQuality);
    3467             : 
    3468          32 :     const char *pszDither = CSLFetchNameValue(papszOptions, "DITHER");
    3469          32 :     if (pszDither)
    3470           1 :         m_bDither = CPLTestBool(pszDither);
    3471          32 : }
    3472             : 
    3473             : /************************************************************************/
    3474             : /*                          IBuildOverviews()                           */
    3475             : /************************************************************************/
    3476             : 
    3477           4 : static int GetFloorPowerOfTwo(int n)
    3478             : {
    3479           4 :     int p2 = 1;
    3480          11 :     while ((n = n >> 1) > 0)
    3481             :     {
    3482           7 :         p2 <<= 1;
    3483             :     }
    3484           4 :     return p2;
    3485             : }
    3486             : 
    3487           4 : CPLErr MBTilesDataset::IBuildOverviews(
    3488             :     const char *pszResampling, int nOverviews, const int *panOverviewList,
    3489             :     int nBandsIn, const int * /*panBandList*/, GDALProgressFunc pfnProgress,
    3490             :     void *pProgressData, CSLConstList papszOptions)
    3491             : {
    3492           4 :     if (GetAccess() != GA_Update)
    3493             :     {
    3494           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3495             :                  "Overview building not supported on a database opened in "
    3496             :                  "read-only mode");
    3497           0 :         return CE_Failure;
    3498             :     }
    3499           4 :     if (m_poParentDS != nullptr)
    3500             :     {
    3501           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3502             :                  "Overview building not supported on overview dataset");
    3503           0 :         return CE_Failure;
    3504             :     }
    3505             : 
    3506           4 :     if (nOverviews == 0)
    3507             :     {
    3508           2 :         for (int i = 0; i < m_nOverviewCount; i++)
    3509           1 :             m_papoOverviewDS[i]->FlushCache(false);
    3510           1 :         char *pszSQL = sqlite3_mprintf(
    3511             :             "DELETE FROM 'tiles' WHERE zoom_level < %d", m_nZoomLevel);
    3512           1 :         char *pszErrMsg = nullptr;
    3513           1 :         int ret = sqlite3_exec(hDB, pszSQL, nullptr, nullptr, &pszErrMsg);
    3514           1 :         sqlite3_free(pszSQL);
    3515           1 :         if (ret != SQLITE_OK)
    3516             :         {
    3517           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Failure: %s",
    3518           0 :                      pszErrMsg ? pszErrMsg : "");
    3519           0 :             sqlite3_free(pszErrMsg);
    3520           0 :             return CE_Failure;
    3521             :         }
    3522             : 
    3523           1 :         int nRows = 0;
    3524           1 :         int nCols = 0;
    3525           1 :         char **papszResult = nullptr;
    3526           1 :         sqlite3_get_table(
    3527             :             hDB, "SELECT * FROM metadata WHERE name = 'minzoom' LIMIT 2",
    3528             :             &papszResult, &nRows, &nCols, nullptr);
    3529           1 :         sqlite3_free_table(papszResult);
    3530           1 :         if (nRows == 1)
    3531             :         {
    3532           1 :             pszSQL = sqlite3_mprintf(
    3533             :                 "UPDATE metadata SET value = %d WHERE name = 'minzoom'",
    3534             :                 m_nZoomLevel);
    3535           1 :             sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
    3536           1 :             sqlite3_free(pszSQL);
    3537             :         }
    3538             : 
    3539           1 :         return CE_None;
    3540             :     }
    3541             : 
    3542           3 :     if (nBandsIn != nBands)
    3543             :     {
    3544           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    3545             :                  "Generation of overviews only"
    3546             :                  "supported when operating on all bands.");
    3547           0 :         return CE_Failure;
    3548             :     }
    3549             : 
    3550           3 :     if (m_nOverviewCount == 0)
    3551             :     {
    3552           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3553             :                  "Image too small to support overviews");
    3554           0 :         return CE_Failure;
    3555             :     }
    3556             : 
    3557           3 :     FlushCache(false);
    3558             : 
    3559          24 :     const auto GetOverviewIndex = [](int nVal)
    3560             :     {
    3561          24 :         int iOvr = -1;
    3562          66 :         while (nVal > 1)
    3563             :         {
    3564          42 :             nVal >>= 1;
    3565          42 :             iOvr++;
    3566             :         }
    3567          24 :         return iOvr;
    3568             :     };
    3569             : 
    3570           7 :     for (int i = 0; i < nOverviews; i++)
    3571             :     {
    3572           4 :         if (panOverviewList[i] < 2)
    3573             :         {
    3574           0 :             CPLError(CE_Failure, CPLE_IllegalArg,
    3575           0 :                      "Overview factor '%d' must be >= 2", panOverviewList[i]);
    3576           0 :             return CE_Failure;
    3577             :         }
    3578             : 
    3579           4 :         if (GetFloorPowerOfTwo(panOverviewList[i]) != panOverviewList[i])
    3580             :         {
    3581           0 :             CPLError(CE_Failure, CPLE_IllegalArg,
    3582             :                      "Overview factor '%d' is not a power of 2",
    3583           0 :                      panOverviewList[i]);
    3584           0 :             return CE_Failure;
    3585             :         }
    3586           4 :         const int iOvr = GetOverviewIndex(panOverviewList[i]);
    3587           4 :         if (iOvr >= m_nOverviewCount)
    3588             :         {
    3589           1 :             CPLDebug("MBTILES",
    3590             :                      "Requested overview factor %d leads to too small overview "
    3591             :                      "and will be ignored",
    3592           1 :                      panOverviewList[i]);
    3593             :         }
    3594             :     }
    3595             : 
    3596             :     GDALRasterBand ***papapoOverviewBands =
    3597           3 :         (GDALRasterBand ***)CPLCalloc(sizeof(void *), nBands);
    3598           3 :     int iCurOverview = 0;
    3599          15 :     for (int iBand = 0; iBand < nBands; iBand++)
    3600             :     {
    3601          24 :         papapoOverviewBands[iBand] =
    3602          12 :             (GDALRasterBand **)CPLCalloc(sizeof(void *), nOverviews);
    3603          12 :         iCurOverview = 0;
    3604          28 :         for (int i = 0; i < nOverviews; i++)
    3605             :         {
    3606          16 :             const int iOvr = GetOverviewIndex(panOverviewList[i]);
    3607          16 :             if (iOvr < m_nOverviewCount)
    3608             :             {
    3609          12 :                 MBTilesDataset *poODS = m_papoOverviewDS[iOvr];
    3610          24 :                 papapoOverviewBands[iBand][iCurOverview] =
    3611          12 :                     poODS->GetRasterBand(iBand + 1);
    3612          12 :                 iCurOverview++;
    3613             :             }
    3614             :         }
    3615             :     }
    3616             : 
    3617           6 :     CPLErr eErr = GDALRegenerateOverviewsMultiBand(
    3618           3 :         nBands, papoBands, iCurOverview, papapoOverviewBands, pszResampling,
    3619             :         pfnProgress, pProgressData, papszOptions);
    3620             : 
    3621          15 :     for (int iBand = 0; iBand < nBands; iBand++)
    3622             :     {
    3623          12 :         CPLFree(papapoOverviewBands[iBand]);
    3624             :     }
    3625           3 :     CPLFree(papapoOverviewBands);
    3626             : 
    3627           3 :     if (eErr == CE_None)
    3628             :     {
    3629             :         // Determine new minzoom value from the existing one and the new
    3630             :         // requested overview levels
    3631           3 :         int nMinZoom = m_nZoomLevel;
    3632           3 :         bool bHasMinZoomMetadata = false;
    3633           3 :         int nRows = 0;
    3634           3 :         int nCols = 0;
    3635           3 :         char **papszResult = nullptr;
    3636           3 :         sqlite3_get_table(
    3637             :             hDB, "SELECT value FROM metadata WHERE name = 'minzoom' LIMIT 2",
    3638             :             &papszResult, &nRows, &nCols, nullptr);
    3639           3 :         if (nRows == 1 && nCols == 1 && papszResult[1])
    3640             :         {
    3641           3 :             bHasMinZoomMetadata = true;
    3642           3 :             nMinZoom = atoi(papszResult[1]);
    3643             :         }
    3644           3 :         sqlite3_free_table(papszResult);
    3645           3 :         if (bHasMinZoomMetadata)
    3646             :         {
    3647           7 :             for (int i = 0; i < nOverviews; i++)
    3648             :             {
    3649           4 :                 const int iOvr = GetOverviewIndex(panOverviewList[i]);
    3650           4 :                 if (iOvr < m_nOverviewCount)
    3651             :                 {
    3652           3 :                     const MBTilesDataset *poODS = m_papoOverviewDS[iOvr];
    3653           3 :                     nMinZoom = std::min(nMinZoom, poODS->m_nZoomLevel);
    3654             :                 }
    3655             :             }
    3656             : 
    3657           3 :             char *pszSQL = sqlite3_mprintf(
    3658             :                 "UPDATE metadata SET value = '%d' WHERE name = 'minzoom'",
    3659             :                 nMinZoom);
    3660           3 :             sqlite3_exec(hDB, pszSQL, nullptr, nullptr, nullptr);
    3661           3 :             sqlite3_free(pszSQL);
    3662             :         }
    3663             :     }
    3664             : 
    3665           3 :     return eErr;
    3666             : }
    3667             : 
    3668             : /************************************************************************/
    3669             : /*                       GDALRegister_MBTiles()                         */
    3670             : /************************************************************************/
    3671             : 
    3672        1928 : void GDALRegister_MBTiles()
    3673             : 
    3674             : {
    3675        1928 :     if (!GDAL_CHECK_VERSION("MBTiles driver"))
    3676           0 :         return;
    3677             : 
    3678        1928 :     if (GDALGetDriverByName("MBTiles") != nullptr)
    3679         282 :         return;
    3680             : 
    3681        1646 :     GDALDriver *poDriver = new GDALDriver();
    3682             : 
    3683        1646 :     poDriver->SetDescription("MBTiles");
    3684        1646 :     poDriver->SetMetadataItem(GDAL_DCAP_RASTER, "YES");
    3685        1646 :     poDriver->SetMetadataItem(GDAL_DCAP_VECTOR, "YES");
    3686        1646 :     poDriver->SetMetadataItem(GDAL_DMD_LONGNAME, "MBTiles");
    3687        1646 :     poDriver->SetMetadataItem(GDAL_DMD_HELPTOPIC,
    3688        1646 :                               "drivers/raster/mbtiles.html");
    3689        1646 :     poDriver->SetMetadataItem(GDAL_DMD_EXTENSION, "mbtiles");
    3690        1646 :     poDriver->SetMetadataItem(GDAL_DMD_CREATIONDATATYPES, "Byte");
    3691             : 
    3692             : #define COMPRESSION_OPTIONS                                                    \
    3693             :     "  <Option name='TILE_FORMAT' scope='raster' type='string-select' "        \
    3694             :     "description='Format to use to create tiles' default='PNG'>"               \
    3695             :     "    <Value>PNG</Value>"                                                   \
    3696             :     "    <Value>PNG8</Value>"                                                  \
    3697             :     "    <Value>JPEG</Value>"                                                  \
    3698             :     "    <Value>WEBP</Value>"                                                  \
    3699             :     "  </Option>"                                                              \
    3700             :     "  <Option name='QUALITY' scope='raster' type='int' min='1' max='100' "    \
    3701             :     "description='Quality for JPEG and WEBP tiles' default='75'/>"             \
    3702             :     "  <Option name='ZLEVEL' scope='raster' type='int' min='1' max='9' "       \
    3703             :     "description='DEFLATE compression level for PNG tiles' default='6'/>"      \
    3704             :     "  <Option name='DITHER' scope='raster' type='boolean' "                   \
    3705             :     "description='Whether to apply Floyd-Steinberg dithering (for "            \
    3706             :     "TILE_FORMAT=PNG8)' default='NO'/>"
    3707             : 
    3708        1646 :     poDriver->SetMetadataItem(
    3709             :         GDAL_DMD_OPENOPTIONLIST,
    3710             :         "<OpenOptionList>"
    3711             :         "  <Option name='ZOOM_LEVEL' scope='raster,vector' type='integer' "
    3712             :         "description='Zoom level of full resolution. If not specified, maximum "
    3713             :         "non-empty zoom level'/>"
    3714             :         "  <Option name='BAND_COUNT' scope='raster' type='string-select' "
    3715             :         "description='Number of raster bands' default='AUTO'>"
    3716             :         "    <Value>AUTO</Value>"
    3717             :         "    <Value>1</Value>"
    3718             :         "    <Value>2</Value>"
    3719             :         "    <Value>3</Value>"
    3720             :         "    <Value>4</Value>"
    3721             :         "  </Option>"
    3722             :         "  <Option name='MINX' scope='raster,vector' type='float' "
    3723             :         "description='Minimum X of area of interest'/>"
    3724             :         "  <Option name='MINY' scope='raster,vector' type='float' "
    3725             :         "description='Minimum Y of area of interest'/>"
    3726             :         "  <Option name='MAXX' scope='raster,vector' type='float' "
    3727             :         "description='Maximum X of area of interest'/>"
    3728             :         "  <Option name='MAXY' scope='raster,vector' type='float' "
    3729             :         "description='Maximum Y of area of interest'/>"
    3730             :         "  <Option name='USE_BOUNDS' scope='raster,vector' type='boolean' "
    3731             :         "description='Whether to use the bounds metadata, when available, to "
    3732             :         "determine the AOI' default='YES'/>" COMPRESSION_OPTIONS
    3733             :         "  <Option name='CLIP' scope='vector' type='boolean' "
    3734             :         "description='Whether to clip geometries to tile extent' "
    3735             :         "default='YES'/>"
    3736             :         "  <Option name='ZOOM_LEVEL_AUTO' scope='vector' type='boolean' "
    3737             :         "description='Whether to auto-select the zoom level for vector layers "
    3738             :         "according to spatial filter extent. Only for display purpose' "
    3739             :         "default='NO'/>"
    3740             :         "  <Option name='JSON_FIELD' scope='vector' type='boolean' "
    3741             :         "description='For vector layers, "
    3742             :         "whether to put all attributes as a serialized JSon dictionary'/>"
    3743        1646 :         "</OpenOptionList>");
    3744             : 
    3745        1646 :     poDriver->SetMetadataItem(
    3746             :         GDAL_DMD_CREATIONOPTIONLIST,
    3747             :         "<CreationOptionList>"
    3748             :         "  <Option name='NAME' scope='raster,vector' type='string' "
    3749             :         "description='Tileset name'/>"
    3750             :         "  <Option name='DESCRIPTION' scope='raster,vector' type='string' "
    3751             :         "description='A description of the layer'/>"
    3752             :         "  <Option name='TYPE' scope='raster,vector' type='string-select' "
    3753             :         "description='Layer type' default='overlay'>"
    3754             :         "    <Value>overlay</Value>"
    3755             :         "    <Value>baselayer</Value>"
    3756             :         "  </Option>"
    3757             :         "  <Option name='VERSION' scope='raster' type='string' "
    3758             :         "description='The version of the tileset, as a plain number' "
    3759             :         "default='1.1'/>"
    3760             :         "  <Option name='BLOCKSIZE' scope='raster' type='int' "
    3761             :         "description='Block size in pixels' default='256' min='64' "
    3762             :         "max='8192'/>" COMPRESSION_OPTIONS
    3763             :         "  <Option name='ZOOM_LEVEL_STRATEGY' scope='raster' "
    3764             :         "type='string-select' description='Strategy to determine zoom level.' "
    3765             :         "default='AUTO'>"
    3766             :         "    <Value>AUTO</Value>"
    3767             :         "    <Value>LOWER</Value>"
    3768             :         "    <Value>UPPER</Value>"
    3769             :         "  </Option>"
    3770             :         "  <Option name='RESAMPLING' scope='raster' type='string-select' "
    3771             :         "description='Resampling algorithm.' default='BILINEAR'>"
    3772             :         "    <Value>NEAREST</Value>"
    3773             :         "    <Value>BILINEAR</Value>"
    3774             :         "    <Value>CUBIC</Value>"
    3775             :         "    <Value>CUBICSPLINE</Value>"
    3776             :         "    <Value>LANCZOS</Value>"
    3777             :         "    <Value>MODE</Value>"
    3778             :         "    <Value>AVERAGE</Value>"
    3779             :         "  </Option>"
    3780             :         "  <Option name='WRITE_BOUNDS' scope='raster' type='boolean' "
    3781             :         "description='Whether to write the bounds metadata' default='YES'/>"
    3782             :         "  <Option name='WRITE_MINMAXZOOM' scope='raster' type='boolean' "
    3783             :         "description='Whether to write the minzoom and maxzoom metadata' "
    3784             :         "default='YES'/>"
    3785             :         "  <Option name='BOUNDS' scope='raster,vector' type='string' "
    3786             :         "description='Override default value for bounds metadata item'/>"
    3787             :         "  <Option name='CENTER' scope='raster,vector' type='string' "
    3788             :         "description='Override default value for center metadata item'/>"
    3789             : #ifdef HAVE_MVT_WRITE_SUPPORT
    3790             :         MVT_MBTILES_COMMON_DSCO
    3791             : #endif
    3792        1646 :         "</CreationOptionList>");
    3793        1646 :     poDriver->SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");
    3794             : 
    3795             : #ifdef HAVE_MVT_WRITE_SUPPORT
    3796        1646 :     poDriver->SetMetadataItem(GDAL_DCAP_CREATE_FIELD, "YES");
    3797        1646 :     poDriver->SetMetadataItem(GDAL_DMD_CREATIONFIELDDATATYPES,
    3798        1646 :                               "Integer Integer64 Real String");
    3799        1646 :     poDriver->SetMetadataItem(GDAL_DMD_CREATIONFIELDDATASUBTYPES,
    3800        1646 :                               "Boolean Float32");
    3801             : 
    3802        1646 :     poDriver->SetMetadataItem(GDAL_DS_LAYER_CREATIONOPTIONLIST, MVT_LCO);
    3803             : #endif
    3804             : 
    3805             : #ifdef ENABLE_SQL_SQLITE_FORMAT
    3806        1646 :     poDriver->SetMetadataItem("ENABLE_SQL_SQLITE_FORMAT", "YES");
    3807             : #endif
    3808        1646 :     poDriver->SetMetadataItem(GDAL_DMD_SUPPORTED_SQL_DIALECTS, "SQLITE OGRSQL");
    3809             : 
    3810        1646 :     poDriver->pfnOpen = MBTilesDataset::Open;
    3811        1646 :     poDriver->pfnIdentify = MBTilesDataset::Identify;
    3812        1646 :     poDriver->pfnCreateCopy = MBTilesDataset::CreateCopy;
    3813        1646 :     poDriver->pfnCreate = MBTilesDataset::Create;
    3814             : 
    3815        1646 :     GetGDALDriverManager()->RegisterDriver(poDriver);
    3816             : }

Generated by: LCOV version 1.14