LCOV - code coverage report
Current view: top level - frmts/mrf - marfa_dataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 994 1269 78.3 %
Date: 2024-11-21 22:18:42 Functions: 45 47 95.7 %

          Line data    Source code
       1             : /*
       2             :  * Copyright (c) 2002-2012, California Institute of Technology.
       3             :  * All rights reserved.  Based on Government Sponsored Research under contracts
       4             :  * NAS7-1407 and/or NAS7-03001.
       5             :  *
       6             :  * Redistribution and use in source and binary forms, with or without
       7             :  * modification, are permitted provided that the following conditions are met:
       8             :  *   1. Redistributions of source code must retain the above copyright notice,
       9             :  * this list of conditions and the following disclaimer.
      10             :  *   2. Redistributions in binary form must reproduce the above copyright
      11             :  * notice, this list of conditions and the following disclaimer in the
      12             :  * documentation and/or other materials provided with the distribution.
      13             :  *   3. Neither the name of the California Institute of Technology (Caltech),
      14             :  * its operating division the Jet Propulsion Laboratory (JPL), the National
      15             :  * Aeronautics and Space Administration (NASA), nor the names of its
      16             :  * contributors may be used to endorse or promote products derived from this
      17             :  * software without specific prior written permission.
      18             :  *
      19             :  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
      20             :  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
      21             :  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
      22             :  * ARE DISCLAIMED. IN NO EVENT SHALL THE CALIFORNIA INSTITUTE OF TECHNOLOGY BE
      23             :  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
      24             :  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
      25             :  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
      26             :  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
      27             :  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
      28             :  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
      29             :  * POSSIBILITY OF SUCH DAMAGE.
      30             :  *
      31             :  * Portions copyright 2014-2021 Esri
      32             :  *
      33             :  * Licensed under the Apache License, Version 2.0 (the "License");
      34             :  * you may not use this file except in compliance with the License.
      35             :  * You may obtain a copy of the License at
      36             :  *
      37             :  * http://www.apache.org/licenses/LICENSE-2.0
      38             :  *
      39             :  * Unless required by applicable law or agreed to in writing, software
      40             :  * distributed under the License is distributed on an "AS IS" BASIS,
      41             :  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      42             :  * See the License for the specific language governing permissions and
      43             :  * limitations under the License.
      44             :  */
      45             : 
      46             : /******************************************************************************
      47             :  *
      48             :  * Project:  Meta Raster File Format Driver Implementation, Dataset
      49             :  * Purpose:  Implementation of GDAL dataset
      50             :  *
      51             :  * Author:   Lucian Plesea, Lucian.Plesea jpl.nasa.gov, lplesea esri.com
      52             :  *
      53             :  ******************************************************************************
      54             :  *
      55             :  *   The MRF dataset and the band are closely tied together, they should be
      56             :  *   considered a single class, or a class (dataset) with extensions (bands).
      57             :  *
      58             :  *
      59             :  ****************************************************************************/
      60             : 
      61             : #include "marfa.h"
      62             : #include "mrfdrivercore.h"
      63             : #include "cpl_multiproc.h" /* for CPLSleep() */
      64             : #include "gdal_priv.h"
      65             : #include <assert.h>
      66             : 
      67             : #include <algorithm>
      68             : #include <vector>
      69             : #if defined(ZSTD_SUPPORT)
      70             : #include <zstd.h>
      71             : #endif
      72             : using std::string;
      73             : using std::vector;
      74             : 
      75             : NAMESPACE_MRF_START
      76             : 
      77             : // Initialize as invalid
      78         368 : MRFDataset::MRFDataset()
      79             :     : zslice(0), idxSize(0), clonedSource(FALSE), nocopy(FALSE),
      80             :       bypass_cache(
      81         368 :           CPLTestBool(CPLGetConfigOption("MRF_BYPASSCACHING", "FALSE"))),
      82             :       mp_safe(FALSE), hasVersions(FALSE), verCount(0),
      83             :       bCrystalized(TRUE),  // Assume not in create mode
      84             :       spacing(0), no_errors(0), missing(0), poSrcDS(nullptr), level(-1),
      85             :       cds(nullptr), scale(0.0), pbuffer(nullptr), pbsize(0), tile(ILSize()),
      86             :       bdirty(0), bGeoTransformValid(TRUE), poColorTable(nullptr), Quality(0),
      87         736 :       pzscctx(nullptr), pzsdctx(nullptr), read_timer(), write_timer(0)
      88             : {
      89         368 :     m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
      90             :     //               X0   Xx   Xy  Y0    Yx   Yy
      91         368 :     double gt[6] = {0.0, 1.0, 0.0, 0.0, 0.0, 1.0};
      92             : 
      93         368 :     memcpy(GeoTransform, gt, sizeof(gt));
      94         368 :     ifp.FP = dfp.FP = nullptr;
      95         368 :     dfp.acc = GF_Read;
      96         368 :     ifp.acc = GF_Read;
      97         368 : }
      98             : 
      99         187 : bool MRFDataset::SetPBuffer(unsigned int sz)
     100             : {
     101         187 :     if (sz == 0)
     102             :     {
     103           0 :         CPLFree(pbuffer);
     104           0 :         pbuffer = nullptr;
     105             :     }
     106         187 :     void *pbufferNew = VSIRealloc(pbuffer, sz);
     107         187 :     if (pbufferNew == nullptr)
     108             :     {
     109           0 :         CPLError(CE_Failure, CPLE_OutOfMemory, "Cannot allocate %u bytes", sz);
     110           0 :         return false;
     111             :     }
     112         187 :     pbuffer = pbufferNew;
     113         187 :     pbsize = sz;
     114         187 :     return true;
     115             : }
     116             : 
     117         256 : static GDALColorEntry GetXMLColorEntry(CPLXMLNode *p)
     118             : {
     119             :     GDALColorEntry ce;
     120         256 :     ce.c1 = static_cast<short>(getXMLNum(p, "c1", 0));
     121         256 :     ce.c2 = static_cast<short>(getXMLNum(p, "c2", 0));
     122         256 :     ce.c3 = static_cast<short>(getXMLNum(p, "c3", 0));
     123         256 :     ce.c4 = static_cast<short>(getXMLNum(p, "c4", 255));
     124         256 :     return ce;
     125             : }
     126             : 
     127             : //
     128             : // Called by dataset destructor or at GDAL termination, to avoid
     129             : // closing datasets whose drivers have already been unloaded
     130             : //
     131         368 : int MRFDataset::CloseDependentDatasets()
     132             : {
     133         368 :     int bHasDroppedRef = GDALPamDataset::CloseDependentDatasets();
     134             : 
     135         368 :     if (poSrcDS)
     136             :     {
     137           3 :         bHasDroppedRef = TRUE;
     138           3 :         GDALClose(GDALDataset::ToHandle(poSrcDS));
     139           3 :         poSrcDS = nullptr;
     140             :     }
     141             : 
     142         368 :     if (cds)
     143             :     {
     144           2 :         bHasDroppedRef = TRUE;
     145           2 :         GDALClose(GDALDataset::ToHandle(cds));
     146           2 :         cds = nullptr;
     147             :     }
     148             : 
     149         368 :     return bHasDroppedRef;
     150             : }
     151             : 
     152         736 : MRFDataset::~MRFDataset()
     153             : {  // Make sure everything gets written
     154         368 :     if (0 != write_timer.count())
     155          41 :         CPLDebug("MRF_Timing", "Compression took %fms",
     156          41 :                  1e-6 * write_timer.count());
     157             : 
     158         368 :     if (0 != read_timer.count())
     159         141 :         CPLDebug("MRF_Timing", "Decompression took %fms",
     160         141 :                  1e-6 * read_timer.count());
     161             : 
     162         368 :     if (eAccess != GA_ReadOnly && !bCrystalized)
     163          51 :         if (!MRFDataset::Crystalize())
     164             :         {
     165             :             // Can't return error code from a destructor, just emit the error
     166          10 :             CPLError(CE_Failure, CPLE_FileIO, "Error creating files");
     167             :         }
     168             : 
     169         368 :     MRFDataset::FlushCache(true);
     170         368 :     MRFDataset::CloseDependentDatasets();
     171             : 
     172         368 :     if (ifp.FP)
     173         261 :         VSIFCloseL(ifp.FP);
     174         368 :     if (dfp.FP)
     175         264 :         VSIFCloseL(dfp.FP);
     176             : 
     177         368 :     delete poColorTable;
     178             : 
     179             :     // CPLFree ignores being called with NULL
     180         368 :     CPLFree(pbuffer);
     181         368 :     pbsize = 0;
     182             : #if defined(ZSTD_SUPPORT)
     183         368 :     ZSTD_freeCCtx(static_cast<ZSTD_CCtx *>(pzscctx));
     184         368 :     ZSTD_freeDCtx(static_cast<ZSTD_DCtx *>(pzsdctx));
     185             : #endif
     186         736 : }
     187             : 
     188             : /*
     189             :  *\brief Format specific RasterIO, may be bypassed by BlockBasedRasterIO by
     190             :  *setting GDAL_FORCE_CACHING to Yes, in which case the band ReadBlock and
     191             :  *WriteBLock are called directly
     192             :  */
     193         128 : CPLErr MRFDataset::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
     194             :                              int nXSize, int nYSize, void *pData, int nBufXSize,
     195             :                              int nBufYSize, GDALDataType eBufType,
     196             :                              int nBandCount, BANDMAP_TYPE panBandMap,
     197             :                              GSpacing nPixelSpace, GSpacing nLineSpace,
     198             :                              GSpacing nBandSpace,
     199             :                              GDALRasterIOExtraArg *psExtraArgs)
     200             : {
     201         128 :     CPLDebug("MRF_IO",
     202             :              "IRasterIO %s, %d, %d, %d, %d, bufsz %d,%d,%d strides P %d, L %d, "
     203             :              "B %d \n",
     204             :              eRWFlag == GF_Write ? "Write" : "Read", nXOff, nYOff, nXSize,
     205             :              nYSize, nBufXSize, nBufYSize, nBandCount,
     206             :              static_cast<int>(nPixelSpace), static_cast<int>(nLineSpace),
     207             :              static_cast<int>(nBandSpace));
     208             : 
     209         128 :     if (eRWFlag == GF_Write && !bCrystalized && !Crystalize())
     210             :     {
     211           0 :         CPLError(CE_Failure, CPLE_FileIO, "MRF: Error creating files");
     212           0 :         return CE_Failure;
     213             :     }
     214             : 
     215             :     //
     216             :     // Call the parent implementation, which splits it into bands and calls
     217             :     // their IRasterIO
     218             :     //
     219         128 :     return GDALPamDataset::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
     220             :                                      pData, nBufXSize, nBufYSize, eBufType,
     221             :                                      nBandCount, panBandMap, nPixelSpace,
     222         128 :                                      nLineSpace, nBandSpace, psExtraArgs);
     223             : }
     224             : 
     225             : /**
     226             :  *\brief Build some overviews
     227             :  *
     228             :  *  if nOverviews is 0, erase the overviews (reduce to base image only)
     229             :  */
     230             : 
     231          31 : CPLErr MRFDataset::IBuildOverviews(const char *pszResampling, int nOverviews,
     232             :                                    const int *panOverviewList, int nBandsIn,
     233             :                                    const int *panBandList,
     234             :                                    GDALProgressFunc pfnProgress,
     235             :                                    void *pProgressData,
     236             :                                    CSLConstList papszOptions)
     237             : 
     238             : {
     239          31 :     CPLErr eErr = CE_None;
     240          31 :     CPLDebug("MRF_OVERLAY", "IBuildOverviews %d, bands %d\n", nOverviews,
     241             :              nBandsIn);
     242             : 
     243          31 :     if (nBands != nBandsIn)
     244             :     {
     245           0 :         CPLError(CE_Failure, CPLE_NotSupported, "nBands = %d not supported",
     246             :                  nBandsIn);
     247           0 :         return CE_Failure;
     248             :     }
     249             : 
     250             :     //      If we don't have write access, then create external overviews
     251          31 :     if (GetAccess() != GA_Update)
     252             :     {
     253           1 :         CPLDebug("MRF", "File open read-only, creating overviews externally.");
     254           1 :         return GDALDataset::IBuildOverviews(
     255             :             pszResampling, nOverviews, panOverviewList, nBands, panBandList,
     256           1 :             pfnProgress, pProgressData, papszOptions);
     257             :     }
     258             : 
     259          30 :     if (nOverviews == 0)
     260             :     {
     261             :         // If there are none, nothing to do
     262           0 :         if (GetRasterBand(1)->GetOverviewCount() == 0)
     263           0 :             return CE_None;
     264             : 
     265           0 :         auto *b = static_cast<MRFRasterBand *>(GetRasterBand(1));
     266             :         // If the first band internal overviews don't exist, they are external
     267           0 :         if (b->overviews.empty())
     268           0 :             return GDALDataset::IBuildOverviews(
     269             :                 pszResampling, nOverviews, panOverviewList, nBands, panBandList,
     270           0 :                 pfnProgress, pProgressData, papszOptions);
     271             : 
     272             :         // We should clean overviews, but this is not allowed in an MRF
     273           0 :         CPLError(CE_Warning, CPLE_NotSupported,
     274             :                  "MRF: Internal overviews cannot be removed, "
     275             :                  "but they can be rebuilt");
     276           0 :         return CE_None;
     277             :     }
     278             : 
     279             :     // Array of source bands
     280             :     GDALRasterBand **papoBandList =
     281          30 :         static_cast<GDALRasterBand **>(CPLCalloc(sizeof(void *), nBands));
     282             :     // Array of destination bands
     283             :     GDALRasterBand **papoOverviewBandList =
     284          30 :         static_cast<GDALRasterBand **>(CPLCalloc(sizeof(void *), nBands));
     285             :     // Triple level pointer, that's what GDAL ROMB wants
     286             :     GDALRasterBand ***papapoOverviewBands =
     287          30 :         static_cast<GDALRasterBand ***>(CPLCalloc(sizeof(void *), nBands));
     288             : 
     289             :     int *panOverviewListNew =
     290          30 :         static_cast<int *>(CPLMalloc(sizeof(int) * nOverviews));
     291          30 :     memcpy(panOverviewListNew, panOverviewList, sizeof(int) * nOverviews);
     292             : 
     293             :     try
     294             :     {  // Throw an error code, to make sure memory gets freed properly
     295             :         // Modify the metadata file if it doesn't already have the Rset model
     296             :         // set
     297          30 :         if (0.0 == scale)
     298             :         {
     299          30 :             CPLXMLNode *config = ReadConfig();
     300             :             try
     301             :             {
     302             :                 const char *model =
     303          30 :                     CPLGetXMLValue(config, "Rsets.model", "uniform");
     304          30 :                 if (!EQUAL(model, "uniform"))
     305             :                 {
     306           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
     307             :                              "MRF:IBuildOverviews, Overviews not implemented "
     308             :                              "for model %s",
     309             :                              model);
     310           0 :                     throw CE_Failure;
     311             :                 }
     312             : 
     313             :                 // The scale value is the same as first overview
     314          30 :                 scale =
     315          30 :                     strtod(CPLGetXMLValue(
     316             :                                config, "Rsets.scale",
     317          60 :                                CPLOPrintf("%d", panOverviewList[0]).c_str()),
     318             :                            nullptr);
     319             : 
     320          30 :                 if (static_cast<int>(scale) != 2 &&
     321           0 :                     (EQUALN("Avg", pszResampling, 3) ||
     322           0 :                      EQUALN("Nnb", pszResampling, 3)))
     323             :                 {
     324           0 :                     CPLError(CE_Failure, CPLE_IllegalArg,
     325             :                              "MRF internal resampling only works for a scale "
     326             :                              "factor of two");
     327           0 :                     throw CE_Failure;
     328             :                 }
     329             : 
     330             :                 // Initialize the empty overlays, all of them for a given scale
     331             :                 // They could already exist, in which case they are not erased
     332          30 :                 idxSize = AddOverviews(int(scale));
     333             : 
     334             :                 // If we don't have overviews, don't try to generate them
     335          30 :                 if (GetRasterBand(1)->GetOverviewCount() == 0)
     336           0 :                     throw CE_None;
     337             : 
     338          30 :                 if (!CheckFileSize(current.idxfname, idxSize, GA_Update))
     339             :                 {
     340           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
     341             :                              "MRF: Can't extend index file");
     342           0 :                     throw CE_Failure;
     343             :                 }
     344             : 
     345             :                 //  Set the uniform node, in case it was not set before, and
     346             :                 //  save the new configuration
     347          30 :                 CPLSetXMLValue(config, "Rsets.#model", "uniform");
     348          30 :                 CPLSetXMLValue(config, "Rsets.#scale", PrintDouble(scale));
     349             : 
     350          30 :                 if (!WriteConfig(config))
     351             :                 {
     352           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
     353             :                              "MRF: Can't rewrite the metadata file");
     354           0 :                     throw CE_Failure;
     355             :                 }
     356          30 :                 CPLDestroyXMLNode(config);
     357          30 :                 config = nullptr;
     358             :             }
     359           0 :             catch (const CPLErr &)
     360             :             {
     361           0 :                 CPLDestroyXMLNode(config);
     362           0 :                 throw;  // Rethrow
     363             :             }
     364             : 
     365             :             // To avoid issues with blacks overviews, generate all of them
     366             :             // if the user asked for a couple of overviews in the correct
     367             :             // sequence and starting with the lowest one
     368          90 :             if (!EQUAL(pszResampling, "NONE") &&
     369          32 :                 nOverviews != GetRasterBand(1)->GetOverviewCount() &&
     370           2 :                 CPLTestBool(
     371             :                     CPLGetConfigOption("MRF_ALL_OVERVIEW_LEVELS", "YES")))
     372             :             {
     373           2 :                 bool bIncreasingPowers =
     374           2 :                     (panOverviewList[0] == static_cast<int>(scale));
     375           3 :                 for (int i = 1; i < nOverviews; i++)
     376           1 :                     bIncreasingPowers =
     377           2 :                         bIncreasingPowers &&
     378           1 :                         (panOverviewList[i] ==
     379           1 :                          static_cast<int>(scale * panOverviewList[i - 1]));
     380             : 
     381           2 :                 int ovrcount = GetRasterBand(1)->GetOverviewCount();
     382           2 :                 if (bIncreasingPowers && nOverviews != ovrcount)
     383             :                 {
     384           2 :                     CPLDebug("MRF",
     385             :                              "Generating %d levels instead of the %d requested",
     386             :                              ovrcount, nOverviews);
     387           2 :                     nOverviews = ovrcount;
     388           4 :                     panOverviewListNew = reinterpret_cast<int *>(CPLRealloc(
     389           2 :                         panOverviewListNew, sizeof(int) * nOverviews));
     390           2 :                     panOverviewListNew[0] = static_cast<int>(scale);
     391           5 :                     for (int i = 1; i < nOverviews; i++)
     392           3 :                         panOverviewListNew[i] =
     393           3 :                             static_cast<int>(scale * panOverviewListNew[i - 1]);
     394             :                 }
     395             :             }
     396             :         }
     397             : 
     398          30 :         if (static_cast<int>(scale) != 2 && (EQUALN("Avg", pszResampling, 3) ||
     399           0 :                                              EQUALN("Nnb", pszResampling, 3)))
     400             :         {
     401           0 :             CPLError(
     402             :                 CE_Failure, CPLE_IllegalArg,
     403             :                 "MRF internal resampling only works for a scale factor of two");
     404           0 :             throw CE_Failure;
     405             :         }
     406             : 
     407          63 :         for (int i = 0; i < nOverviews; i++)
     408             :         {
     409             :             // Verify that scales are reasonable, val/scale has to be an integer
     410          33 :             if (!IsPower(panOverviewListNew[i], scale))
     411             :             {
     412           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
     413             :                          "MRF:IBuildOverviews, overview factor %d is not a "
     414             :                          "power of %f",
     415           0 :                          panOverviewListNew[i], scale);
     416           0 :                 continue;
     417             :             };
     418             : 
     419          33 :             int srclevel = int(logbase(panOverviewListNew[i], scale) - 0.5);
     420          33 :             MRFRasterBand *b = static_cast<MRFRasterBand *>(GetRasterBand(1));
     421             : 
     422             :             // Warn for requests for invalid levels
     423          33 :             if (srclevel >= b->GetOverviewCount())
     424             :             {
     425           0 :                 CPLError(CE_Warning, CPLE_AppDefined,
     426             :                          "MRF:IBuildOverviews, overview factor %d is not valid "
     427             :                          "for this dataset",
     428           0 :                          panOverviewListNew[i]);
     429           0 :                 continue;
     430             :             }
     431             : 
     432             :             // Generate the overview using the previous level as the source
     433             : 
     434             :             // Use "avg" flag to trigger the internal average sampling
     435          33 :             if (EQUALN("Avg", pszResampling, 3) ||
     436          19 :                 EQUALN("Nnb", pszResampling, 3))
     437             :             {
     438          26 :                 int sampling = EQUALN("Avg", pszResampling, 3) ? SAMPLING_Avg
     439             :                                                                : SAMPLING_Near;
     440             :                 // Internal, using PatchOverview
     441          26 :                 if (srclevel > 0)
     442             :                     b = static_cast<MRFRasterBand *>(
     443           3 :                         b->GetOverview(srclevel - 1));
     444             : 
     445             :                 eErr =
     446          26 :                     PatchOverview(0, 0, b->nBlocksPerRow, b->nBlocksPerColumn,
     447             :                                   srclevel, 0, sampling);
     448          26 :                 if (eErr == CE_Failure)
     449          26 :                     throw eErr;
     450             :             }
     451             :             else
     452             :             {
     453             :                 //
     454             :                 // Use the GDAL method, which is slightly different for bilinear
     455             :                 // interpolation and also handles nearest mode
     456             :                 //
     457             :                 //
     458          14 :                 for (int iBand = 0; iBand < nBands; iBand++)
     459             :                 {
     460             :                     // This is the base level
     461           7 :                     papoBandList[iBand] = GetRasterBand(panBandList[iBand]);
     462             :                     // Set up the destination
     463          14 :                     papoOverviewBandList[iBand] =
     464           7 :                         papoBandList[iBand]->GetOverview(srclevel);
     465             : 
     466             :                     // Use the previous level as the source, the overviews are 0
     467             :                     // based thus an extra -1
     468           7 :                     if (srclevel > 0)
     469           0 :                         papoBandList[iBand] =
     470           0 :                             papoBandList[iBand]->GetOverview(srclevel - 1);
     471             : 
     472             :                     // Hook it up, via triple pointer level
     473           7 :                     papapoOverviewBands[iBand] = &(papoOverviewBandList[iBand]);
     474             :                 }
     475             : 
     476             :                 //
     477             :                 // Ready, generate this overview
     478             :                 // Note that this function has a bug in GDAL, the block stepping
     479             :                 // is incorrect It can generate multiple overview in one call,
     480             :                 // Could rewrite this loop so this function only gets called
     481             :                 // once
     482             :                 //
     483           7 :                 GDALRegenerateOverviewsMultiBand(
     484             :                     nBands, papoBandList, 1, papapoOverviewBands, pszResampling,
     485             :                     pfnProgress, pProgressData, papszOptions);
     486             :             }
     487             :         }
     488             :     }
     489           0 :     catch (const CPLErr &e)
     490             :     {
     491           0 :         eErr = e;
     492             :     }
     493             : 
     494          30 :     CPLFree(panOverviewListNew);
     495          30 :     CPLFree(papapoOverviewBands);
     496          30 :     CPLFree(papoOverviewBandList);
     497          30 :     CPLFree(papoBandList);
     498          30 :     return eErr;
     499             : }
     500             : 
     501             : /*
     502             :  *\brief blank separated list to vector of doubles
     503             :  */
     504          34 : static void list2vec(std::vector<double> &v, const char *pszList)
     505             : {
     506          34 :     if ((pszList == nullptr) || (pszList[0] == 0))
     507           0 :         return;
     508          34 :     char **papszTokens = CSLTokenizeString2(
     509             :         pszList, " \t\n\r", CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES);
     510          34 :     v.clear();
     511          69 :     for (int i = 0; i < CSLCount(papszTokens); i++)
     512          35 :         v.push_back(CPLStrtod(papszTokens[i], nullptr));
     513          34 :     CSLDestroy(papszTokens);
     514             : }
     515             : 
     516          20 : void MRFDataset::SetNoDataValue(const char *pszVal)
     517             : {
     518          20 :     list2vec(vNoData, pszVal);
     519          20 : }
     520             : 
     521           7 : void MRFDataset::SetMinValue(const char *pszVal)
     522             : {
     523           7 :     list2vec(vMin, pszVal);
     524           7 : }
     525             : 
     526           7 : void MRFDataset::SetMaxValue(const char *pszVal)
     527             : {
     528           7 :     list2vec(vMax, pszVal);
     529           7 : }
     530             : 
     531             : /**
     532             :  *
     533             :  *\brief Read the XML config tree, from file
     534             :  *  Caller is responsible for freeing the memory
     535             :  *
     536             :  * @return NULL on failure, or the document tree on success.
     537             :  *
     538             :  */
     539          30 : CPLXMLNode *MRFDataset::ReadConfig() const
     540             : {
     541          30 :     if (fname[0] == '<')
     542           0 :         return CPLParseXMLString(fname);
     543          30 :     return CPLParseXMLFile(fname);
     544             : }
     545             : 
     546             : /**
     547             :  *\brief Write the XML config tree
     548             :  * Caller is responsible for correctness of data
     549             :  * and for freeing the memory
     550             :  *
     551             :  * @param config The document tree to write
     552             :  * @return TRUE on success, FALSE otherwise
     553             :  */
     554         201 : int MRFDataset::WriteConfig(CPLXMLNode *config)
     555             : {
     556         201 :     if (fname[0] == '<')
     557           0 :         return FALSE;
     558         201 :     return CPLSerializeXMLTreeToFile(config, fname);
     559             : }
     560             : 
     561             : static void
     562           5 : stringSplit(vector<string> &theStringVector,  // Altered/returned value
     563             :             const string &theString, size_t start = 0,
     564             :             const char theDelimiter = ' ')
     565             : {
     566             :     while (true)
     567             :     {
     568           5 :         size_t end = theString.find(theDelimiter, start);
     569           5 :         if (string::npos == end)
     570             :         {
     571           5 :             theStringVector.push_back(theString.substr(start));
     572           5 :             return;
     573             :         }
     574           0 :         theStringVector.push_back(theString.substr(start, end - start));
     575           0 :         start = end + 1;
     576           0 :     }
     577             : }
     578             : 
     579             : // Returns the number following the prefix if it exists in one of the vector
     580             : // strings Otherwise it returns the default
     581          15 : static int getnum(const vector<string> &theStringVector, const char prefix,
     582             :                   int def)
     583             : {
     584          25 :     for (unsigned int i = 0; i < theStringVector.size(); i++)
     585          15 :         if (theStringVector[i][0] == prefix)
     586           5 :             return atoi(theStringVector[i].c_str() + 1);
     587          10 :     return def;
     588             : }
     589             : 
     590             : /**
     591             :  *\brief Open a MRF file
     592             :  *
     593             :  */
     594         202 : GDALDataset *MRFDataset::Open(GDALOpenInfo *poOpenInfo)
     595             : {
     596         202 :     if (!MRFDriverIdentify(poOpenInfo))
     597           0 :         return nullptr;
     598             : 
     599         202 :     CPLXMLNode *config = nullptr;
     600         202 :     CPLErr ret = CE_None;
     601         202 :     const char *pszFileName = poOpenInfo->pszFilename;
     602             : 
     603         202 :     int level = -1;   // All levels
     604         202 :     int version = 0;  // Current
     605         202 :     int zslice = 0;
     606         404 :     string fn;        // Used to parse and adjust the file name
     607         404 :     string insidefn;  // inside tar file name
     608             : 
     609             :     // Different ways to open an MRF
     610         202 :     if (poOpenInfo->nHeaderBytes >= 10)
     611             :     {
     612         197 :         const char *pszHeader =
     613             :             reinterpret_cast<char *>(poOpenInfo->pabyHeader);
     614         197 :         fn.assign(pszHeader, poOpenInfo->nHeaderBytes);
     615         197 :         if (STARTS_WITH(pszHeader, "<MRF_META>"))  // Regular file name
     616         190 :             config = CPLParseXMLFile(pszFileName);
     617           7 :         else if (poOpenInfo->eAccess == GA_ReadOnly && fn.size() > 600 &&
     618           7 :                  (fn[262] == 0 || fn[262] == 32) &&
     619           1 :                  STARTS_WITH(fn.c_str() + 257, "ustar") &&
     620          15 :                  strlen(CPLGetPath(fn.c_str())) == 0 &&
     621           1 :                  STARTS_WITH(fn.c_str() + 512, "<MRF_META>"))
     622             :         {  // An MRF inside a tar
     623           1 :             insidefn = string("/vsitar/") + pszFileName + "/" + pszHeader;
     624           1 :             config = CPLParseXMLFile(insidefn.c_str());
     625             :         }
     626             : #if defined(LERC)
     627             :         else
     628           6 :             config = LERC_Band::GetMRFConfig(poOpenInfo);
     629             : #endif
     630             :     }
     631             :     else
     632             :     {
     633           5 :         if (EQUALN(pszFileName, "<MRF_META>", 10))  // Content as file name
     634           0 :             config = CPLParseXMLString(pszFileName);
     635             :         else
     636             :         {  // Try Ornate file name
     637           5 :             fn = pszFileName;
     638           5 :             size_t pos = fn.find(":MRF:");
     639           5 :             if (string::npos != pos)
     640             :             {  // Tokenize and pick known options
     641           5 :                 vector<string> tokens;
     642           5 :                 stringSplit(tokens, fn, pos + 5, ':');
     643           5 :                 level = getnum(tokens, 'L', -1);
     644           5 :                 version = getnum(tokens, 'V', 0);
     645           5 :                 zslice = getnum(tokens, 'Z', 0);
     646           5 :                 fn.resize(pos);  // Cut the ornamentations
     647           5 :                 pszFileName = fn.c_str();
     648           5 :                 config = CPLParseXMLFile(pszFileName);
     649             :             }
     650             :         }
     651             :     }
     652             : 
     653         202 :     if (!config)
     654           0 :         return nullptr;
     655             : 
     656         202 :     MRFDataset *ds = new MRFDataset();
     657         202 :     ds->fname = pszFileName;
     658         202 :     if (!insidefn.empty())
     659             :     {
     660           1 :         ds->publicname = pszFileName;
     661           1 :         ds->fname = insidefn;
     662             :     }
     663         202 :     ds->eAccess = poOpenInfo->eAccess;
     664         202 :     ds->level = level;
     665         202 :     ds->zslice = zslice;
     666             : 
     667             :     // OpenOptions can override file name arguments
     668         202 :     ds->ProcessOpenOptions(poOpenInfo->papszOpenOptions);
     669             : 
     670         202 :     if (level == -1)
     671         200 :         ret = ds->Initialize(config);
     672             :     else
     673             :     {
     674             :         // Open the whole dataset, then pick one level
     675           2 :         ds->cds = new MRFDataset();
     676           2 :         ds->cds->fname = ds->fname;
     677           2 :         ds->cds->eAccess = ds->eAccess;
     678           2 :         ds->zslice = zslice;
     679           2 :         ret = ds->cds->Initialize(config);
     680           2 :         if (ret == CE_None)
     681           2 :             ret = ds->LevelInit(level);
     682             :     }
     683         202 :     CPLDestroyXMLNode(config);
     684             : 
     685         202 :     if (ret != CE_None)
     686             :     {
     687          23 :         delete ds;
     688          23 :         return nullptr;
     689             :     }
     690             : 
     691             :     // Open a single version
     692         179 :     if (version != 0)
     693           2 :         ret = ds->SetVersion(version);
     694             : 
     695         179 :     if (ret != CE_None)
     696             :     {
     697           1 :         delete ds;
     698           1 :         return nullptr;
     699             :     }
     700             : 
     701             :     // Tell PAM what our real file name is, to help it find the aux.xml
     702         178 :     ds->SetPhysicalFilename(ds->fname);
     703             :     // Don't mess with metadata after this, otherwise PAM will re-write the
     704             :     // aux.xml
     705         178 :     ds->TryLoadXML();
     706             : 
     707             :     /* -------------------------------------------------------------------- */
     708             :     /*      Open external overviews.                                        */
     709             :     /* -------------------------------------------------------------------- */
     710         178 :     ds->oOvManager.Initialize(ds, ds->fname);
     711             : 
     712         178 :     return ds;
     713             : }
     714             : 
     715             : // Adjust the band images with the right offset, then adjust the sizes
     716           2 : CPLErr MRFDataset::SetVersion(int version)
     717             : {
     718           2 :     if (!hasVersions || version > verCount)
     719             :     {
     720           1 :         CPLError(CE_Failure, CPLE_AppDefined,
     721             :                  "GDAL MRF: Version number error!");
     722           1 :         return CE_Failure;
     723             :     }
     724             :     // Size of one version index
     725           2 :     for (int bcount = 1; bcount <= nBands; bcount++)
     726             :     {
     727             :         MRFRasterBand *srcband =
     728           1 :             reinterpret_cast<MRFRasterBand *>(GetRasterBand(bcount));
     729           1 :         srcband->img.idxoffset += idxSize * verCount;
     730           1 :         for (int l = 0; l < srcband->GetOverviewCount(); l++)
     731             :         {
     732             :             MRFRasterBand *band =
     733           0 :                 reinterpret_cast<MRFRasterBand *>(srcband->GetOverview(l));
     734           0 :             if (band != nullptr)
     735           0 :                 band->img.idxoffset += idxSize * verCount;
     736             :         }
     737             :     }
     738           1 :     hasVersions = 0;
     739           1 :     return CE_None;
     740             : }
     741             : 
     742           2 : CPLErr MRFDataset::LevelInit(const int l)
     743             : {
     744             :     // Test that this level does exist
     745           2 :     if (l < 0 || l >= cds->GetRasterBand(1)->GetOverviewCount())
     746             :     {
     747           1 :         CPLError(CE_Failure, CPLE_AppDefined,
     748             :                  "GDAL MRF: Overview not present!");
     749           1 :         return CE_Failure;
     750             :     }
     751             : 
     752             :     MRFRasterBand *srcband = reinterpret_cast<MRFRasterBand *>(
     753           1 :         cds->GetRasterBand(1)->GetOverview(l));
     754             : 
     755             :     // Copy the sizes from this level
     756           1 :     full = srcband->img;
     757           1 :     current = srcband->img;
     758           1 :     current.size.c = cds->current.size.c;
     759           1 :     scale = cds->scale;
     760           1 :     const auto poSRS = cds->GetSpatialRef();
     761           1 :     if (poSRS)
     762           1 :         m_oSRS = *poSRS;
     763             : 
     764           1 :     SetMetadataItem("INTERLEAVE", OrderName(current.order), "IMAGE_STRUCTURE");
     765           1 :     SetMetadataItem("COMPRESSION", CompName(current.comp), "IMAGE_STRUCTURE");
     766             : 
     767           1 :     bGeoTransformValid = (CE_None == cds->GetGeoTransform(GeoTransform));
     768           4 :     for (int i = 0; i < l + 1; i++)
     769             :     {
     770           3 :         GeoTransform[1] *= scale;
     771           3 :         GeoTransform[5] *= scale;
     772             :     }
     773             : 
     774           1 :     nRasterXSize = current.size.x;
     775           1 :     nRasterYSize = current.size.y;
     776           1 :     nBands = current.size.c;
     777             : 
     778             :     // Add the bands, copy constructor so they can be closed independently
     779           2 :     for (int i = 1; i <= nBands; i++)
     780           1 :         SetBand(i, new MRFLRasterBand(reinterpret_cast<MRFRasterBand *>(
     781           1 :                        cds->GetRasterBand(i)->GetOverview(l))));
     782           1 :     return CE_None;
     783             : }
     784             : 
     785             : // Is the string positive or not
     786        1268 : inline bool on(const char *pszValue)
     787             : {
     788        1268 :     if (!pszValue || pszValue[0] == 0)
     789         108 :         return false;
     790        2308 :     return EQUAL(pszValue, "ON") || EQUAL(pszValue, "TRUE") ||
     791        2308 :            EQUAL(pszValue, "YES");
     792             : }
     793             : 
     794             : /**
     795             :  *\brief Initialize the image structure and the dataset from the XML Raster node
     796             :  *
     797             :  * @param image the structure to be initialized
     798             :  * @param ds the parent dataset, some things get inherited
     799             :  * @param defimage defimage
     800             :  *
     801             :  * The structure should be initialized with the default values as much as
     802             :  *possible
     803             :  *
     804             :  */
     805             : 
     806         363 : static CPLErr Init_Raster(ILImage &image, MRFDataset *ds, CPLXMLNode *defimage)
     807             : {
     808             :     CPLXMLNode *node;  // temporary
     809         363 :     if (!defimage)
     810             :     {
     811           0 :         CPLError(CE_Failure, CPLE_AppDefined,
     812             :                  "GDAL MRF: Can't find raster info");
     813           0 :         return CE_Failure;
     814             :     }
     815             : 
     816             :     // Size is mandatory
     817         363 :     node = CPLGetXMLNode(defimage, "Size");
     818             : 
     819         363 :     if (node)
     820             :     {
     821         363 :         image.size = ILSize(static_cast<int>(getXMLNum(node, "x", -1)),
     822         363 :                             static_cast<int>(getXMLNum(node, "y", -1)),
     823         363 :                             static_cast<int>(getXMLNum(node, "z", 1)),
     824         363 :                             static_cast<int>(getXMLNum(node, "c", 1)), 0);
     825             :     }
     826             : 
     827             :     // Basic checks
     828         363 :     if (!node || image.size.x < 1 || image.size.y < 1 || image.size.z < 0 ||
     829         726 :         image.size.c < 0 || !GDALCheckBandCount(image.size.c, FALSE))
     830             :     {
     831           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Raster size missing or invalid");
     832           0 :         return CE_Failure;
     833             :     }
     834             : 
     835             :     //  Pagesize, defaults to 512,512,1,c
     836         363 :     image.pagesize = ILSize(std::min(512, image.size.x),
     837         363 :                             std::min(512, image.size.y), 1, image.size.c);
     838             : 
     839         363 :     node = CPLGetXMLNode(defimage, "PageSize");
     840         363 :     if (node)
     841             :     {
     842         363 :         image.pagesize =
     843         363 :             ILSize(static_cast<int>(getXMLNum(node, "x", image.pagesize.x)),
     844         363 :                    static_cast<int>(getXMLNum(node, "y", image.pagesize.y)),
     845             :                    1,  // One slice at a time, forced
     846         363 :                    static_cast<int>(getXMLNum(node, "c", image.pagesize.c)));
     847         363 :         if (image.pagesize.x < 1 || image.pagesize.y < 1 ||
     848         363 :             image.pagesize.c <= 0)
     849             :         {
     850           0 :             CPLError(CE_Failure, CPLE_IllegalArg, "Invalid PageSize");
     851           0 :             return CE_Failure;
     852             :         }
     853             :     }
     854             : 
     855             :     // Page Encoding, defaults to PNG
     856         363 :     const char *pszCompression = CPLGetXMLValue(defimage, "Compression", "PNG");
     857         363 :     image.comp = CompToken(pszCompression);
     858         363 :     if (image.comp == IL_ERR_COMP)
     859             :     {
     860           0 :         CPLError(CE_Failure, CPLE_IllegalArg,
     861             :                  "GDAL MRF: Compression %s is unknown", pszCompression);
     862           0 :         return CE_Failure;
     863             :     }
     864             : 
     865             :     // Is there a palette?
     866             :     //
     867             :     // GDAL only supports RGB+A palette, the other modes don't work
     868             :     //
     869             : 
     870         669 :     if ((image.pagesize.c == 1) &&
     871         306 :         (nullptr != (node = CPLGetXMLNode(defimage, "Palette"))))
     872             :     {
     873           1 :         int entries = static_cast<int>(getXMLNum(node, "Size", 255));
     874           1 :         GDALPaletteInterp eInterp = GPI_RGB;
     875           1 :         if ((entries > 0) && (entries < 257))
     876             :         {
     877           1 :             GDALColorEntry ce_start = {0, 0, 0, 255}, ce_end = {0, 0, 0, 255};
     878             : 
     879             :             // Create it and initialize it to black opaque
     880           1 :             GDALColorTable *poColorTable = new GDALColorTable(eInterp);
     881           1 :             poColorTable->CreateColorRamp(0, &ce_start, entries - 1, &ce_end);
     882             :             // Read the values
     883           1 :             CPLXMLNode *p = CPLGetXMLNode(node, "Entry");
     884           1 :             if (p)
     885             :             {
     886             :                 // Initialize the first entry
     887           1 :                 ce_start = GetXMLColorEntry(p);
     888           1 :                 int start_idx = static_cast<int>(getXMLNum(p, "idx", 0));
     889           1 :                 if (start_idx < 0)
     890             :                 {
     891           0 :                     CPLError(CE_Failure, CPLE_IllegalArg,
     892             :                              "GDAL MRF: Palette index %d not allowed",
     893             :                              start_idx);
     894           0 :                     delete poColorTable;
     895           0 :                     return CE_Failure;
     896             :                 }
     897           1 :                 poColorTable->SetColorEntry(start_idx, &ce_start);
     898         256 :                 while (nullptr != (p = SearchXMLSiblings(p, "Entry")))
     899             :                 {
     900             :                     // For every entry, create a ramp
     901         255 :                     ce_end = GetXMLColorEntry(p);
     902             :                     int end_idx =
     903         255 :                         static_cast<int>(getXMLNum(p, "idx", start_idx + 1));
     904         255 :                     if ((end_idx <= start_idx) || (start_idx >= entries))
     905             :                     {
     906           0 :                         CPLError(CE_Failure, CPLE_IllegalArg,
     907             :                                  "GDAL MRF: Index Error at index %d", end_idx);
     908           0 :                         delete poColorTable;
     909           0 :                         return CE_Failure;
     910             :                     }
     911         255 :                     poColorTable->CreateColorRamp(start_idx, &ce_start, end_idx,
     912             :                                                   &ce_end);
     913         255 :                     ce_start = ce_end;
     914         255 :                     start_idx = end_idx;
     915             :                 }
     916             :             }
     917             : 
     918           1 :             ds->SetColorTable(poColorTable);
     919             :         }
     920             :         else
     921             :         {
     922           0 :             CPLError(CE_Failure, CPLE_IllegalArg,
     923             :                      "GDAL MRF: Palette definition error");
     924           0 :             return CE_Failure;
     925             :         }
     926             :     }
     927             : 
     928             :     // Order of increment
     929         363 :     if (image.pagesize.c != image.size.c && image.pagesize.c != 1)
     930             :     {
     931             :         // Fixes heap buffer overflow in
     932             :         // GDALMRFRasterBand::ReadInterleavedBlock() See
     933             :         // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=2884
     934           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     935             :                  "GDAL MRF: image.pagesize.c = %d and image.size.c = %d",
     936             :                  image.pagesize.c, image.size.c);
     937           0 :         return CE_Failure;
     938             :     }
     939             : 
     940         363 :     image.order = OrderToken(
     941             :         CPLGetXMLValue(defimage, "Order",
     942         363 :                        (image.pagesize.c != image.size.c) ? "BAND" : "PIXEL"));
     943         363 :     if (image.order == IL_ERR_ORD)
     944             :     {
     945           0 :         CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Order %s is unknown",
     946             :                  CPLGetXMLValue(defimage, "Order", nullptr));
     947           0 :         return CE_Failure;
     948             :     }
     949             : 
     950         363 :     const char *photo_val = CPLGetXMLValue(defimage, "Photometric", nullptr);
     951         363 :     if (photo_val)
     952           5 :         ds->SetPhotometricInterpretation(photo_val);
     953             : 
     954         363 :     image.quality = atoi(CPLGetXMLValue(defimage, "Quality", "85"));
     955         363 :     if (image.quality < 0 || image.quality > 99)
     956             :     {
     957           0 :         CPLError(CE_Warning, CPLE_AppDefined,
     958             :                  "GDAL MRF: Quality setting error, using default of 85");
     959           0 :         image.quality = 85;
     960             :     }
     961             : 
     962             :     // Data Type, use GDAL Names
     963         363 :     image.dt = GDALGetDataTypeByName(
     964             :         CPLGetXMLValue(defimage, "DataType", GDALGetDataTypeName(image.dt)));
     965         363 :     if (image.dt == GDT_Unknown || GDALGetDataTypeSize(image.dt) == 0)
     966             :     {
     967           0 :         CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Unsupported type");
     968           0 :         return CE_Failure;
     969             :     }
     970             : 
     971             :     // Check the endianness if needed, assume host order
     972         363 :     if (is_Endianness_Dependent(image.dt, image.comp))
     973          69 :         image.nbo = on(CPLGetXMLValue(defimage, "NetByteOrder", "No"));
     974             : 
     975         363 :     CPLXMLNode *DataValues = CPLGetXMLNode(defimage, "DataValues");
     976         363 :     if (nullptr != DataValues)
     977             :     {
     978          27 :         const char *pszValue = CPLGetXMLValue(DataValues, "NoData", nullptr);
     979          27 :         if (pszValue)
     980          20 :             ds->SetNoDataValue(pszValue);
     981          27 :         pszValue = CPLGetXMLValue(DataValues, "min", nullptr);
     982          27 :         if (pszValue)
     983           7 :             ds->SetMinValue(pszValue);
     984          27 :         pszValue = CPLGetXMLValue(DataValues, "max", nullptr);
     985          27 :         if (pszValue)
     986           7 :             ds->SetMaxValue(pszValue);
     987             :     }
     988             : 
     989             :     // Calculate the page size in bytes
     990         363 :     const int nDTSize = GDALGetDataTypeSizeBytes(image.dt);
     991         363 :     if (nDTSize <= 0 || image.pagesize.z <= 0 ||
     992         363 :         image.pagesize.x > INT_MAX / image.pagesize.y ||
     993         363 :         image.pagesize.x * image.pagesize.y > INT_MAX / image.pagesize.z ||
     994         363 :         image.pagesize.x * image.pagesize.y * image.pagesize.z >
     995         363 :             INT_MAX / image.pagesize.c ||
     996         363 :         image.pagesize.x * image.pagesize.y * image.pagesize.z *
     997         363 :                 image.pagesize.c >
     998         363 :             INT_MAX / nDTSize)
     999             :     {
    1000           0 :         CPLError(CE_Failure, CPLE_AppDefined, "MRF page size too big");
    1001           0 :         return CE_Failure;
    1002             :     }
    1003         363 :     image.pageSizeBytes = nDTSize * image.pagesize.x * image.pagesize.y *
    1004         363 :                           image.pagesize.z * image.pagesize.c;
    1005             : 
    1006             :     // Calculate the page count, including the total for the level
    1007         363 :     image.pagecount = pcount(image.size, image.pagesize);
    1008         363 :     if (image.pagecount.l < 0)
    1009             :     {
    1010           0 :         return CE_Failure;
    1011             :     }
    1012             : 
    1013             :     // Data File Name and base offset
    1014             :     image.datfname =
    1015         363 :         getFname(defimage, "DataFile", ds->GetFname(), ILComp_Ext[image.comp]);
    1016         363 :     image.dataoffset = static_cast<int>(
    1017         363 :         getXMLNum(CPLGetXMLNode(defimage, "DataFile"), "offset", 0.0));
    1018             : 
    1019             :     // Index File Name and base offset
    1020         363 :     image.idxfname = getFname(defimage, "IndexFile", ds->GetFname(), ".idx");
    1021         363 :     image.idxoffset = static_cast<int>(
    1022         363 :         getXMLNum(CPLGetXMLNode(defimage, "IndexFile"), "offset", 0.0));
    1023             : 
    1024         363 :     return CE_None;
    1025             : }
    1026             : 
    1027         159 : char **MRFDataset::GetFileList()
    1028             : {
    1029         159 :     char **papszFileList = nullptr;
    1030             : 
    1031         159 :     string usename = fname;
    1032         159 :     if (!publicname.empty())
    1033           0 :         usename = publicname;
    1034             :     // Add the header file name if it is real
    1035             :     VSIStatBufL sStat;
    1036         159 :     if (VSIStatExL(usename.c_str(), &sStat, VSI_STAT_EXISTS_FLAG) == 0)
    1037         159 :         papszFileList = CSLAddString(papszFileList, usename.c_str());
    1038             : 
    1039             :     // These two should be real
    1040             :     // We don't really want to add these files, since they will be erased when
    1041             :     // an mrf is overwritten This collides with the concept that the data file
    1042             :     // never shrinks.  Same goes with the index, in case we just want to add
    1043             :     // things to it.
    1044             :     //    papszFileList = CSLAddString( papszFileList, full.datfname);
    1045             :     //    papszFileList = CSLAddString( papszFileList, full.idxfname);
    1046             :     //    if (!source.empty())
    1047             :     // papszFileList = CSLAddString( papszFileList, source);
    1048             : 
    1049         318 :     return papszFileList;
    1050             : }
    1051             : 
    1052             : // Try to create all the folders in the path in sequence, ignore errors
    1053           4 : static void mkdir_r(string const &fname)
    1054             : {
    1055           4 :     size_t loc = fname.find_first_of("\\/");
    1056           4 :     if (loc == string::npos)
    1057           0 :         return;
    1058             :     while (true)
    1059             :     {
    1060           5 :         ++loc;
    1061           5 :         loc = fname.find_first_of("\\/", loc);
    1062           5 :         if (loc == string::npos)
    1063           4 :             break;
    1064           1 :         VSIMkdir(fname.substr(0, loc).c_str(), 0);
    1065             :     }
    1066             : }
    1067             : 
    1068             : // Returns the dataset index file or null
    1069        7254 : VSILFILE *MRFDataset::IdxFP()
    1070             : {
    1071        7254 :     if (ifp.FP != nullptr)
    1072        6987 :         return ifp.FP;
    1073             : 
    1074             :     // If missing is set, we already checked, there is no index
    1075         267 :     if (missing)
    1076           0 :         return nullptr;
    1077             : 
    1078             :     // If name starts with '(' it is not a real file name
    1079         267 :     if (current.idxfname[0] == '(')
    1080           0 :         return nullptr;
    1081             : 
    1082         267 :     const char *mode = "rb";
    1083         267 :     ifp.acc = GF_Read;
    1084             : 
    1085         267 :     if (eAccess == GA_Update || !source.empty())
    1086             :     {
    1087         158 :         mode = "r+b";
    1088         158 :         ifp.acc = GF_Write;
    1089             :     }
    1090             : 
    1091         267 :     ifp.FP = VSIFOpenL(current.idxfname, mode);
    1092             : 
    1093             :     // If file didn't open for reading and no_errors is set, just return null
    1094             :     // and make a note
    1095         267 :     if (ifp.FP == nullptr && eAccess == GA_ReadOnly && no_errors)
    1096             :     {
    1097           0 :         missing = 1;
    1098           0 :         return nullptr;
    1099             :     }
    1100             : 
    1101             :     // need to create the index file
    1102         367 :     if (ifp.FP == nullptr && !bCrystalized &&
    1103         100 :         (eAccess == GA_Update || !source.empty()))
    1104             :     {
    1105         100 :         mode = "w+b";
    1106         100 :         ifp.FP = VSIFOpenL(current.idxfname, mode);
    1107             :     }
    1108             : 
    1109         267 :     if (nullptr == ifp.FP && !source.empty())
    1110             :     {
    1111             :         // caching and cloning, try making the folder and attempt again
    1112           4 :         mkdir_r(current.idxfname);
    1113           4 :         ifp.FP = VSIFOpenL(current.idxfname, mode);
    1114             :     }
    1115             : 
    1116         267 :     GIntBig expected_size = idxSize;
    1117         267 :     if (clonedSource)
    1118           2 :         expected_size *= 2;
    1119             : 
    1120         267 :     if (nullptr != ifp.FP)
    1121             :     {
    1122         406 :         if (!bCrystalized &&
    1123         149 :             !CheckFileSize(current.idxfname, expected_size, GA_Update))
    1124             :         {
    1125           0 :             CPLError(CE_Failure, CPLE_FileIO,
    1126             :                      "MRF: Can't extend the cache index file %s",
    1127             :                      current.idxfname.c_str());
    1128           0 :             return nullptr;
    1129             :         }
    1130             : 
    1131         257 :         if (source.empty())
    1132         253 :             return ifp.FP;
    1133             : 
    1134             :         // Make sure the index is large enough before proceeding
    1135             :         // Timeout in .1 seconds, can't really guarantee the accuracy
    1136             :         // So this is about half second, should be sufficient
    1137           4 :         int timeout = 5;
    1138           0 :         do
    1139             :         {
    1140           4 :             if (CheckFileSize(current.idxfname, expected_size, GA_ReadOnly))
    1141           4 :                 return ifp.FP;
    1142           0 :             CPLSleep(0.100); /* 100 ms */
    1143           0 :         } while (--timeout);
    1144             : 
    1145             :         // If we get here it is a time-out
    1146           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1147             :                  "GDAL MRF: Timeout on fetching cloned index file %s\n",
    1148             :                  current.idxfname.c_str());
    1149           0 :         return nullptr;
    1150             :     }
    1151             : 
    1152             :     // If single tile, and no index file, let the caller figure it out
    1153          10 :     if (IsSingleTile())
    1154           6 :         return nullptr;
    1155             : 
    1156             :     // Error if this is not a caching MRF
    1157           4 :     if (source.empty())
    1158             :     {
    1159           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1160             :                  "GDAL MRF: Can't open index file %s\n",
    1161             :                  current.idxfname.c_str());
    1162           0 :         return nullptr;
    1163             :     }
    1164             : 
    1165             :     // Caching/Cloning MRF and index could be read only
    1166             :     // Is this actually works, we should try again, maybe somebody else just
    1167             :     // created the file?
    1168           4 :     mode = "rb";
    1169           4 :     ifp.acc = GF_Read;
    1170           4 :     ifp.FP = VSIFOpenL(current.idxfname, mode);
    1171           4 :     if (nullptr != ifp.FP)
    1172           0 :         return ifp.FP;
    1173             : 
    1174             :     // Caching and index file absent, create it
    1175             :     // Due to a race, multiple processes might do this at the same time, but
    1176             :     // that is fine
    1177           4 :     ifp.FP = VSIFOpenL(current.idxfname, "wb");
    1178           4 :     if (nullptr == ifp.FP)
    1179             :     {
    1180           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1181             :                  "Can't create the MRF cache index file %s",
    1182             :                  current.idxfname.c_str());
    1183           0 :         return nullptr;
    1184             :     }
    1185           4 :     VSIFCloseL(ifp.FP);
    1186           4 :     ifp.FP = nullptr;
    1187             : 
    1188             :     // Make it large enough for caching and for cloning
    1189           4 :     if (!CheckFileSize(current.idxfname, expected_size, GA_Update))
    1190             :     {
    1191           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1192             :                  "Can't extend the cache index file %s",
    1193             :                  current.idxfname.c_str());
    1194           0 :         return nullptr;
    1195             :     }
    1196             : 
    1197             :     // Try opening it again in rw mode so we can read and write
    1198           4 :     mode = "r+b";
    1199           4 :     ifp.acc = GF_Write;
    1200           4 :     ifp.FP = VSIFOpenL(current.idxfname.c_str(), mode);
    1201             : 
    1202           4 :     if (nullptr == ifp.FP)
    1203             :     {
    1204           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1205             :                  "GDAL MRF: Can't reopen cache index file %s\n",
    1206             :                  full.idxfname.c_str());
    1207           0 :         return nullptr;
    1208             :     }
    1209           4 :     return ifp.FP;
    1210             : }
    1211             : 
    1212             : //
    1213             : // Returns the dataset data file or null
    1214             : // Data file is opened either in Read or Append mode, never in straight write
    1215             : //
    1216        7129 : VSILFILE *MRFDataset::DataFP()
    1217             : {
    1218        7129 :     if (dfp.FP != nullptr)
    1219        6865 :         return dfp.FP;
    1220         264 :     const char *mode = "rb";
    1221         264 :     dfp.acc = GF_Read;
    1222             : 
    1223             :     // Open it for writing if updating or if caching
    1224         264 :     if (eAccess == GA_Update || !source.empty())
    1225             :     {
    1226         157 :         mode = "a+b";
    1227         157 :         dfp.acc = GF_Write;
    1228             :     }
    1229             : 
    1230         264 :     dfp.FP = VSIFOpenL(current.datfname, mode);
    1231         264 :     if (dfp.FP)
    1232         264 :         return dfp.FP;
    1233             : 
    1234             :     // It could be a caching MRF
    1235           0 :     if (source.empty())
    1236           0 :         goto io_error;
    1237             : 
    1238             :     // May be there but read only, remember that it was open that way
    1239           0 :     mode = "rb";
    1240           0 :     dfp.acc = GF_Read;
    1241           0 :     dfp.FP = VSIFOpenL(current.datfname, mode);
    1242           0 :     if (nullptr != dfp.FP)
    1243             :     {
    1244           0 :         CPLDebug("MRF_IO", "Opened %s RO mode %s\n", current.datfname.c_str(),
    1245             :                  mode);
    1246           0 :         return dfp.FP;
    1247             :     }
    1248             : 
    1249           0 :     if (source.empty())
    1250           0 :         goto io_error;
    1251             : 
    1252             :     // caching, maybe the folder didn't exist
    1253           0 :     mkdir_r(current.datfname);
    1254           0 :     mode = "a+b";
    1255           0 :     dfp.acc = GF_Write;
    1256           0 :     dfp.FP = VSIFOpenL(current.datfname, mode);
    1257           0 :     if (dfp.FP)
    1258           0 :         return dfp.FP;
    1259             : 
    1260           0 : io_error:
    1261           0 :     dfp.FP = nullptr;
    1262           0 :     CPLError(CE_Failure, CPLE_FileIO, "GDAL MRF: %s : %s", strerror(errno),
    1263             :              current.datfname.c_str());
    1264           0 :     return nullptr;
    1265             : }
    1266             : 
    1267             : // Builds an XML tree from the current MRF.  If written to a file it becomes an
    1268             : // MRF
    1269         332 : CPLXMLNode *MRFDataset::BuildConfig()
    1270             : {
    1271         332 :     CPLXMLNode *config = CPLCreateXMLNode(nullptr, CXT_Element, "MRF_META");
    1272             : 
    1273         332 :     if (!source.empty())
    1274             :     {
    1275             :         CPLXMLNode *psCachedSource =
    1276           4 :             CPLCreateXMLNode(config, CXT_Element, "CachedSource");
    1277             :         // Should wrap the string in CDATA, in case it is XML
    1278             :         CPLXMLNode *psSource =
    1279           4 :             CPLCreateXMLElementAndValue(psCachedSource, "Source", source);
    1280           4 :         if (clonedSource)
    1281           0 :             CPLSetXMLValue(psSource, "#clone", "true");
    1282             :     }
    1283             : 
    1284             :     // Use the full size
    1285         332 :     CPLXMLNode *raster = CPLCreateXMLNode(config, CXT_Element, "Raster");
    1286             : 
    1287             :     // Preserve the file names if not the default ones
    1288         332 :     if (full.datfname != getFname(GetFname(), ILComp_Ext[full.comp]))
    1289           0 :         CPLCreateXMLElementAndValue(raster, "DataFile", full.datfname.c_str());
    1290         332 :     if (full.idxfname != getFname(GetFname(), ".idx"))
    1291           0 :         CPLCreateXMLElementAndValue(raster, "IndexFile", full.idxfname.c_str());
    1292         332 :     if (spacing != 0)
    1293           0 :         XMLSetAttributeVal(raster, "Spacing", static_cast<double>(spacing),
    1294             :                            "%.0f");
    1295             : 
    1296         332 :     XMLSetAttributeVal(raster, "Size", full.size, "%.0f");
    1297         332 :     XMLSetAttributeVal(raster, "PageSize", full.pagesize, "%.0f");
    1298             : 
    1299             : #ifdef HAVE_PNG
    1300         332 :     if (full.comp != IL_PNG)
    1301             : #endif
    1302             :     {
    1303         192 :         CPLCreateXMLElementAndValue(raster, "Compression", CompName(full.comp));
    1304             :     }
    1305             : 
    1306         332 :     if (full.dt != GDT_Byte)
    1307         202 :         CPLCreateXMLElementAndValue(raster, "DataType",
    1308             :                                     GDALGetDataTypeName(full.dt));
    1309             : 
    1310             :     // special photometric interpretation
    1311         332 :     if (!photometric.empty())
    1312           4 :         CPLCreateXMLElementAndValue(raster, "Photometric", photometric);
    1313             : 
    1314         332 :     if (!vNoData.empty() || !vMin.empty() || !vMax.empty())
    1315             :     {
    1316             :         CPLXMLNode *values =
    1317          43 :             CPLCreateXMLNode(raster, CXT_Element, "DataValues");
    1318          43 :         XMLSetAttributeVal(values, "NoData", vNoData);
    1319          43 :         XMLSetAttributeVal(values, "min", vMin);
    1320          43 :         XMLSetAttributeVal(values, "max", vMax);
    1321             :     }
    1322             : 
    1323             :     // palette, if we have one
    1324         332 :     if (poColorTable != nullptr)
    1325             :     {
    1326           1 :         const char *pfrmt = "%.0f";
    1327           1 :         CPLXMLNode *pal = CPLCreateXMLNode(raster, CXT_Element, "Palette");
    1328           1 :         int sz = poColorTable->GetColorEntryCount();
    1329           1 :         if (sz != 256)
    1330           0 :             XMLSetAttributeVal(pal, "Size", poColorTable->GetColorEntryCount());
    1331             :         // RGB or RGBA for now
    1332         257 :         for (int i = 0; i < sz; i++)
    1333             :         {
    1334         256 :             CPLXMLNode *entry = CPLCreateXMLNode(pal, CXT_Element, "Entry");
    1335         256 :             const GDALColorEntry *ent = poColorTable->GetColorEntry(i);
    1336             :             // No need to set the index, it is always from 0 no size-1
    1337         256 :             XMLSetAttributeVal(entry, "c1", ent->c1, pfrmt);
    1338         256 :             XMLSetAttributeVal(entry, "c2", ent->c2, pfrmt);
    1339         256 :             XMLSetAttributeVal(entry, "c3", ent->c3, pfrmt);
    1340         256 :             if (ent->c4 != 255)
    1341           0 :                 XMLSetAttributeVal(entry, "c4", ent->c4, pfrmt);
    1342             :         }
    1343             :     }
    1344             : 
    1345         332 :     if (is_Endianness_Dependent(full.dt, full.comp))  // Need to set the order
    1346          62 :         CPLCreateXMLElementAndValue(raster, "NetByteOrder",
    1347          62 :                                     (full.nbo || NET_ORDER) ? "TRUE" : "FALSE");
    1348             : 
    1349         332 :     if (full.quality > 0 && full.quality != 85)
    1350          12 :         CPLCreateXMLElementAndValue(raster, "Quality",
    1351          24 :                                     CPLOPrintf("%d", full.quality));
    1352             : 
    1353             :     // Done with the raster node
    1354             : 
    1355         332 :     if (scale != 0.0)
    1356             :     {
    1357           0 :         CPLCreateXMLNode(config, CXT_Element, "Rsets");
    1358           0 :         CPLSetXMLValue(config, "Rsets.#model", "uniform");
    1359           0 :         CPLSetXMLValue(config, "Rsets.#scale", PrintDouble(scale));
    1360             :     }
    1361         332 :     CPLXMLNode *gtags = CPLCreateXMLNode(config, CXT_Element, "GeoTags");
    1362             : 
    1363             :     // Do we have an affine transform different from identity?
    1364             :     double gt[6];
    1365         664 :     if ((MRFDataset::GetGeoTransform(gt) == CE_None) &&
    1366         332 :         (gt[0] != 0 || gt[1] != 1 || gt[2] != 0 || gt[3] != 0 || gt[4] != 0 ||
    1367         197 :          gt[5] != 1))
    1368             :     {
    1369         135 :         double minx = gt[0];
    1370         135 :         double maxx = gt[1] * full.size.x + minx;
    1371         135 :         double maxy = gt[3];
    1372         135 :         double miny = gt[5] * full.size.y + maxy;
    1373         135 :         CPLXMLNode *bbox = CPLCreateXMLNode(gtags, CXT_Element, "BoundingBox");
    1374         135 :         XMLSetAttributeVal(bbox, "minx", minx);
    1375         135 :         XMLSetAttributeVal(bbox, "miny", miny);
    1376         135 :         XMLSetAttributeVal(bbox, "maxx", maxx);
    1377         135 :         XMLSetAttributeVal(bbox, "maxy", maxy);
    1378             :     }
    1379             : 
    1380         332 :     const char *pszProj = GetProjectionRef();
    1381         332 :     if (pszProj && (!EQUAL(pszProj, "")))
    1382         136 :         CPLCreateXMLElementAndValue(gtags, "Projection", pszProj);
    1383             : 
    1384         332 :     if (optlist.Count() != 0)
    1385             :     {
    1386          48 :         CPLString options;
    1387          50 :         for (int i = 0; i < optlist.size(); i++)
    1388             :         {
    1389          26 :             options += optlist[i];
    1390          26 :             options += ' ';
    1391             :         }
    1392          24 :         options.pop_back();
    1393          24 :         CPLCreateXMLElementAndValue(config, "Options", options);
    1394             :     }
    1395             : 
    1396         332 :     return config;
    1397             : }
    1398             : 
    1399             : /**
    1400             :  * \brief Populates the dataset variables from the XML definition
    1401             :  *
    1402             :  *
    1403             :  */
    1404         363 : CPLErr MRFDataset::Initialize(CPLXMLNode *config)
    1405             : {
    1406             :     // We only need a basic initialization here, usually gets overwritten by the
    1407             :     // image params
    1408         363 :     full.dt = GDT_Byte;
    1409         363 :     full.hasNoData = false;
    1410         363 :     full.NoDataValue = 0;
    1411         363 :     Quality = 85;
    1412             : 
    1413         363 :     CPLErr ret = Init_Raster(full, this, CPLGetXMLNode(config, "Raster"));
    1414         363 :     if (CE_None != ret)
    1415           0 :         return ret;
    1416             : 
    1417         363 :     hasVersions = on(CPLGetXMLValue(config, "Raster.versioned", "no"));
    1418         363 :     mp_safe = on(CPLGetXMLValue(config, "Raster.mp_safe", "no"));
    1419         363 :     spacing = atoi(CPLGetXMLValue(config, "Raster.Spacing", "0"));
    1420             : 
    1421             :     // The zslice defined in the file wins over the oo or the file argument
    1422         363 :     if (CPLGetXMLNode(config, "Raster.zslice"))
    1423           0 :         zslice = atoi(CPLGetXMLValue(config, "Raster.zslice", "0"));
    1424             : 
    1425         363 :     Quality = full.quality;
    1426             : 
    1427             :     // Bounding box
    1428         363 :     CPLXMLNode *bbox = CPLGetXMLNode(config, "GeoTags.BoundingBox");
    1429         363 :     if (nullptr != bbox)
    1430             :     {
    1431             :         double x0, x1, y0, y1;
    1432             : 
    1433         159 :         x0 = atof(CPLGetXMLValue(bbox, "minx", "0"));
    1434         159 :         x1 = atof(CPLGetXMLValue(bbox, "maxx", "1"));
    1435         159 :         y1 = atof(CPLGetXMLValue(bbox, "maxy", "1"));
    1436         159 :         y0 = atof(CPLGetXMLValue(bbox, "miny", "0"));
    1437             : 
    1438         159 :         GeoTransform[0] = x0;
    1439         159 :         GeoTransform[1] = (x1 - x0) / full.size.x;
    1440         159 :         GeoTransform[2] = 0;
    1441         159 :         GeoTransform[3] = y1;
    1442         159 :         GeoTransform[4] = 0;
    1443         159 :         GeoTransform[5] = (y0 - y1) / full.size.y;
    1444         159 :         bGeoTransformValid = TRUE;
    1445             :     }
    1446             : 
    1447             :     const char *pszRawProjFromXML =
    1448         363 :         CPLGetXMLValue(config, "GeoTags.Projection", "");
    1449         363 :     if (strlen(pszRawProjFromXML) != 0)
    1450         160 :         m_oSRS.SetFromUserInput(
    1451             :             pszRawProjFromXML,
    1452             :             OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get());
    1453             : 
    1454             :     // Copy the full size to current, data and index are not yet open
    1455         363 :     current = full;
    1456         363 :     if (current.size.z != 1)
    1457             :     {
    1458           0 :         SetMetadataItem("ZSIZE", CPLOPrintf("%d", current.size.z),
    1459           0 :                         "IMAGE_STRUCTURE");
    1460           0 :         SetMetadataItem("ZSLICE", CPLOPrintf("%d", zslice), "IMAGE_STRUCTURE");
    1461             :         // Capture the zslice in pagesize.l
    1462           0 :         current.pagesize.l = zslice;
    1463             :         // Adjust offset for base image
    1464           0 :         if (full.size.z <= 0)
    1465             :         {
    1466           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    1467             :                      "GDAL MRF: Invalid Raster.z value");
    1468           0 :             return CE_Failure;
    1469             :         }
    1470           0 :         if (zslice >= full.size.z)
    1471             :         {
    1472           0 :             CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Invalid slice");
    1473           0 :             return CE_Failure;
    1474             :         }
    1475             : 
    1476           0 :         current.idxoffset +=
    1477           0 :             (current.pagecount.l / full.size.z) * zslice * sizeof(ILIdx);
    1478             :     }
    1479             : 
    1480             :     // Dataset metadata setup
    1481         363 :     SetMetadataItem("INTERLEAVE", OrderName(current.order), "IMAGE_STRUCTURE");
    1482         363 :     SetMetadataItem("COMPRESSION", CompName(current.comp), "IMAGE_STRUCTURE");
    1483             : 
    1484         363 :     if (is_Endianness_Dependent(current.dt, current.comp))
    1485          69 :         SetMetadataItem("NETBYTEORDER", current.nbo ? "TRUE" : "FALSE",
    1486          69 :                         "IMAGE_STRUCTURE");
    1487             : 
    1488             :     // Open the files for the current image, either RW or RO
    1489         363 :     nRasterXSize = current.size.x;
    1490         363 :     nRasterYSize = current.size.y;
    1491         363 :     nBands = current.size.c;
    1492             : 
    1493         363 :     if (!nBands || !nRasterXSize || !nRasterYSize)
    1494             :     {
    1495           0 :         CPLError(CE_Failure, CPLE_AppDefined, "GDAL MRF: Image size missing");
    1496           0 :         return CE_Failure;
    1497             :     }
    1498             : 
    1499             :     // Pick up the source data image, if there is one
    1500         363 :     source = CPLGetXMLValue(config, "CachedSource.Source", "");
    1501             :     // Is it a clone?
    1502         363 :     clonedSource =
    1503         363 :         on(CPLGetXMLValue(config, "CachedSource.Source.clone", "no"));
    1504             :     // Pick up the options, if any
    1505             :     optlist.Assign(CSLTokenizeString2(
    1506             :         CPLGetXMLValue(config, "Options", nullptr), " \t\n\r",
    1507         363 :         CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES));
    1508             : 
    1509             :     // Load all the options in the IMAGE_STRUCTURE metadata
    1510         391 :     for (int i = 0; i < optlist.Count(); i++)
    1511             :     {
    1512          56 :         CPLString s(optlist[i]);
    1513          28 :         size_t nSepPos = s.find_first_of(":=");
    1514          28 :         if (std::string::npos != nSepPos)
    1515             :         {
    1516          28 :             s.resize(nSepPos);
    1517          28 :             SetMetadataItem(s, optlist.FetchNameValue(s), "IMAGE_STRUCTURE");
    1518             :         }
    1519             :     }
    1520             : 
    1521             :     // We have the options, so we can call rasterband
    1522         781 :     for (int i = 1; i <= nBands; i++)
    1523             :     {
    1524             :         // The overviews are low resolution copies of the current one.
    1525         471 :         MRFRasterBand *band = newMRFRasterBand(this, current, i);
    1526         471 :         if (!band)
    1527          53 :             return CE_Failure;
    1528             : 
    1529         418 :         GDALColorInterp ci = GCI_Undefined;
    1530             : 
    1531             :         // Default color interpretation
    1532         418 :         switch (nBands)
    1533             :         {
    1534         264 :             case 1:
    1535             :             case 2:
    1536         264 :                 ci = (i == 1) ? GCI_GrayIndex : GCI_AlphaBand;
    1537         264 :                 break;
    1538         144 :             case 3:
    1539             :             case 4:
    1540         144 :                 if (i < 3)
    1541          94 :                     ci = (i == 1) ? GCI_RedBand : GCI_GreenBand;
    1542             :                 else
    1543          50 :                     ci = (i == 3) ? GCI_BlueBand : GCI_AlphaBand;
    1544             :         }
    1545             : 
    1546         418 :         if (GetColorTable())
    1547           1 :             ci = GCI_PaletteIndex;
    1548             : 
    1549             :         // Legacy, deprecated
    1550         418 :         if (optlist.FetchBoolean("MULTISPECTRAL", FALSE))
    1551           0 :             ci = GCI_Undefined;
    1552             : 
    1553             :         // New style
    1554         418 :         if (!photometric.empty())
    1555             :         {
    1556          15 :             if ("MULTISPECTRAL" == photometric)
    1557           0 :                 ci = GCI_Undefined;
    1558             :         }
    1559             : 
    1560         418 :         band->SetColorInterpretation(ci);
    1561         418 :         SetBand(i, band);
    1562             :     }
    1563             : 
    1564         310 :     CPLXMLNode *rsets = CPLGetXMLNode(config, "Rsets");
    1565         310 :     if (nullptr != rsets && nullptr != rsets->psChild)
    1566             :     {
    1567             :         // We have rsets
    1568             : 
    1569             :         // Regular spaced overlays, until everything fits in a single tile
    1570          32 :         if (EQUAL("uniform", CPLGetXMLValue(rsets, "model", "uniform")))
    1571             :         {
    1572          32 :             scale = getXMLNum(rsets, "scale", 2.0);
    1573          32 :             if (scale <= 1)
    1574             :             {
    1575           0 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1576             :                          "MRF: zoom factor less than unit not allowed");
    1577           0 :                 return CE_Failure;
    1578             :             }
    1579             :             // Looks like there are overlays
    1580          32 :             AddOverviews(int(scale));
    1581             :         }
    1582             :         else
    1583             :         {
    1584           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Unknown Rset definition");
    1585           0 :             return CE_Failure;
    1586             :         }
    1587             :     }
    1588             : 
    1589         310 :     idxSize = IdxSize(full, int(scale));
    1590         310 :     if (idxSize == 0)
    1591           0 :         return CE_Failure;
    1592             : 
    1593             :     // If not set by the bands, get a pageSizeBytes buffer
    1594         310 :     if (GetPBufferSize() == 0 && !SetPBuffer(current.pageSizeBytes))
    1595           0 :         return CE_Failure;
    1596             : 
    1597         310 :     if (hasVersions)
    1598             :     {                  // It has versions, but how many?
    1599           5 :         verCount = 0;  // Assume it only has one
    1600             :         VSIStatBufL statb;
    1601             :         //  If the file exists, compute the last version number
    1602           5 :         if (0 == VSIStatL(full.idxfname, &statb))
    1603           5 :             verCount = int(statb.st_size / idxSize - 1);
    1604             :     }
    1605             : 
    1606         310 :     return CE_None;
    1607             : }
    1608             : 
    1609           0 : static inline bool has_path(const CPLString &name)
    1610             : {
    1611           0 :     return name.find_first_of("/\\") != string::npos;
    1612             : }
    1613             : 
    1614             : // Does name look like an absolute gdal file name?
    1615           4 : static inline bool is_absolute(const CPLString &name)
    1616             : {
    1617           4 :     return (name.find_first_of("/\\") == 0)  // Starts with root
    1618           3 :            || (name.size() > 1 && name[1] == ':' &&
    1619           0 :                isalpha(static_cast<unsigned char>(
    1620           0 :                    name[0])))    // Starts with drive letter
    1621           7 :            || (name[0] == '<');  // Maybe it is XML
    1622             : }
    1623             : 
    1624             : // Add the dirname of path to the beginning of name, if it is relative
    1625             : // returns true if name was modified
    1626           4 : static inline bool make_absolute(CPLString &name, const CPLString &path)
    1627             : {
    1628           4 :     if (!is_absolute(path) && (path.find_first_of("/\\") != string::npos))
    1629             :     {
    1630           3 :         name = path.substr(0, path.find_last_of("/\\") + 1) + name;
    1631           3 :         return true;
    1632             :     }
    1633           1 :     return false;
    1634             : }
    1635             : 
    1636             : /**
    1637             :  *\brief Get the source dataset, open it if necessary
    1638             :  */
    1639           5 : GDALDataset *MRFDataset::GetSrcDS()
    1640             : {
    1641           5 :     if (poSrcDS)
    1642           1 :         return poSrcDS;
    1643           4 :     if (source.empty())
    1644           0 :         return nullptr;
    1645             : 
    1646             :     // Try open the source dataset as is
    1647           4 :     poSrcDS =
    1648           4 :         GDALDataset::FromHandle(GDALOpenShared(source.c_str(), GA_ReadOnly));
    1649             : 
    1650             :     // It the open fails, try again with the current dataset path prepended
    1651           4 :     if (!poSrcDS && make_absolute(source, fname))
    1652           3 :         poSrcDS = GDALDataset::FromHandle(
    1653             :             GDALOpenShared(source.c_str(), GA_ReadOnly));
    1654             : 
    1655           4 :     if (0 == source.find("<MRF_META>") && has_path(fname))
    1656             :     {
    1657             :         // MRF XML source, might need to patch the file names with the current
    1658             :         // one
    1659           0 :         MRFDataset *poMRFDS = dynamic_cast<MRFDataset *>(poSrcDS);
    1660           0 :         if (!poMRFDS)
    1661             :         {
    1662           0 :             delete poSrcDS;
    1663           0 :             poSrcDS = nullptr;
    1664           0 :             return nullptr;
    1665             :         }
    1666           0 :         make_absolute(poMRFDS->current.datfname, fname);
    1667           0 :         make_absolute(poMRFDS->current.idxfname, fname);
    1668             :     }
    1669           4 :     mp_safe = true;  // Turn on MP safety
    1670           4 :     return poSrcDS;
    1671             : }
    1672             : 
    1673             : /**
    1674             :  *\brief Add or verify that all overlays exits
    1675             :  *
    1676             :  * @return size of the index file
    1677             :  */
    1678             : 
    1679          62 : GIntBig MRFDataset::AddOverviews(int scaleIn)
    1680             : {
    1681             :     // Fit the overlays
    1682          62 :     ILImage img = current;
    1683         134 :     while (1 != img.pagecount.x * img.pagecount.y)
    1684             :     {
    1685             :         // Adjust raster data for next level
    1686             :         // Adjust the offsets for indices left at this level
    1687          72 :         img.idxoffset += sizeof(ILIdx) * img.pagecount.l / img.size.z *
    1688          72 :                          (img.size.z - zslice);
    1689             : 
    1690             :         // Next overview size
    1691          72 :         img.size.x = pcount(img.size.x, scaleIn);
    1692          72 :         img.size.y = pcount(img.size.y, scaleIn);
    1693          72 :         img.size.l++;  // Increment the level
    1694          72 :         img.pagecount = pcount(img.size, img.pagesize);
    1695             : 
    1696             :         // And adjust the offset again, within next level
    1697          72 :         img.idxoffset += sizeof(ILIdx) * img.pagecount.l / img.size.z * zslice;
    1698          72 :         int l = static_cast<int>(img.size.l);
    1699             :         // Create and register the overviews for each band
    1700         144 :         for (int i = 1; i <= nBands; i++)
    1701             :         {
    1702             :             MRFRasterBand *b =
    1703          72 :                 reinterpret_cast<MRFRasterBand *>(GetRasterBand(i));
    1704          72 :             if (!(b->GetOverview(l - 1)))
    1705          72 :                 b->AddOverview(newMRFRasterBand(this, img, i, l));
    1706             :         }
    1707             :     }
    1708             : 
    1709             :     // Last adjustment, should be a single set of c and leftover z tiles
    1710          62 :     return img.idxoffset +
    1711         124 :            sizeof(ILIdx) * img.pagecount.l / img.size.z * (img.size.z - zslice);
    1712             : }
    1713             : 
    1714             : //
    1715             : // set an entry if it doesn't already exist
    1716             : //
    1717         134 : static char **CSLAddIfMissing(char **papszList, const char *pszName,
    1718             :                               const char *pszValue)
    1719             : {
    1720         134 :     if (CSLFetchNameValue(papszList, pszName))
    1721           9 :         return papszList;
    1722         125 :     return CSLSetNameValue(papszList, pszName, pszValue);
    1723             : }
    1724             : 
    1725             : // CreateCopy implemented based on Create
    1726         133 : GDALDataset *MRFDataset::CreateCopy(const char *pszFilename,
    1727             :                                     GDALDataset *poSrcDS, int /*bStrict*/,
    1728             :                                     char **papszOptions,
    1729             :                                     GDALProgressFunc pfnProgress,
    1730             :                                     void *pProgressData)
    1731             : {
    1732         266 :     ILImage img;
    1733             : 
    1734         133 :     int x = poSrcDS->GetRasterXSize();
    1735         133 :     int y = poSrcDS->GetRasterYSize();
    1736         133 :     int nBands = poSrcDS->GetRasterCount();
    1737         133 :     if (nBands == 0)
    1738             :     {
    1739           1 :         CPLError(CE_Failure, CPLE_NotSupported, "nBands == 0 not supported");
    1740           1 :         return nullptr;
    1741             :     }
    1742         132 :     GDALRasterBand *poSrcBand1 = poSrcDS->GetRasterBand(1);
    1743             : 
    1744         132 :     GDALDataType dt = poSrcBand1->GetRasterDataType();
    1745             :     // Have our own options, to modify as we want
    1746         132 :     char **options = CSLDuplicate(papszOptions);
    1747             : 
    1748             :     const char *pszValue =
    1749         132 :         poSrcDS->GetMetadataItem("INTERLEAVE", "IMAGE_STRUCTURE");
    1750             :     options =
    1751         132 :         CSLAddIfMissing(options, "INTERLEAVE", pszValue ? pszValue : "PIXEL");
    1752             :     int xb, yb;
    1753         132 :     poSrcBand1->GetBlockSize(&xb, &yb);
    1754             : 
    1755             :     // Keep input block size if it exists and not explicitly set
    1756         133 :     if (CSLFetchNameValue(options, "BLOCKSIZE") == nullptr && xb != x &&
    1757           1 :         yb != y)
    1758             :     {
    1759           1 :         options = CSLAddIfMissing(options, "BLOCKXSIZE",
    1760           2 :                                   PrintDouble(xb, "%d").c_str());
    1761           1 :         options = CSLAddIfMissing(options, "BLOCKYSIZE",
    1762           2 :                                   PrintDouble(yb, "%d").c_str());
    1763             :     }
    1764             : 
    1765         132 :     MRFDataset *poDS = nullptr;
    1766             :     try
    1767             :     {
    1768             :         poDS = reinterpret_cast<MRFDataset *>(
    1769         132 :             Create(pszFilename, x, y, nBands, dt, options));
    1770             : 
    1771         132 :         if (poDS == nullptr || poDS->bCrystalized)
    1772          12 :             throw CPLOPrintf("MRF: Can't create %s", pszFilename);
    1773             : 
    1774         120 :         img = poDS->current;  // Deal with the current one here
    1775             : 
    1776             :         // Copy data values from source
    1777         274 :         for (int i = 0; i < poDS->nBands; i++)
    1778             :         {
    1779             :             int bHas;
    1780             :             double dfData;
    1781         154 :             GDALRasterBand *srcBand = poSrcDS->GetRasterBand(i + 1);
    1782         154 :             GDALRasterBand *mBand = poDS->GetRasterBand(i + 1);
    1783         154 :             dfData = srcBand->GetNoDataValue(&bHas);
    1784         154 :             if (bHas)
    1785             :             {
    1786          16 :                 poDS->vNoData.push_back(dfData);
    1787          16 :                 mBand->SetNoDataValue(dfData);
    1788             :             }
    1789         154 :             dfData = srcBand->GetMinimum(&bHas);
    1790         154 :             if (bHas)
    1791          17 :                 poDS->vMin.push_back(dfData);
    1792         154 :             dfData = srcBand->GetMaximum(&bHas);
    1793         154 :             if (bHas)
    1794          17 :                 poDS->vMax.push_back(dfData);
    1795             : 
    1796             :             // Copy the band metadata, PAM will handle it
    1797         154 :             char **meta = srcBand->GetMetadata("IMAGE_STRUCTURE");
    1798         154 :             if (CSLCount(meta))
    1799           7 :                 mBand->SetMetadata(meta, "IMAGE_STRUCTURE");
    1800             : 
    1801         154 :             meta = srcBand->GetMetadata();
    1802         154 :             if (CSLCount(meta))
    1803          18 :                 mBand->SetMetadata(meta);
    1804             :         }
    1805             : 
    1806             :         // Geotags
    1807             :         double gt[6];
    1808         120 :         if (CE_None == poSrcDS->GetGeoTransform(gt))
    1809         117 :             poDS->SetGeoTransform(gt);
    1810             : 
    1811         120 :         const auto poSRS = poSrcDS->GetSpatialRef();
    1812         120 :         if (poSRS)
    1813         116 :             poDS->m_oSRS = *poSRS;
    1814             : 
    1815             :         // Color palette if we only have one band
    1816         223 :         if (1 == nBands &&
    1817         103 :             GCI_PaletteIndex == poSrcBand1->GetColorInterpretation())
    1818           1 :             poDS->SetColorTable(poSrcBand1->GetColorTable()->Clone());
    1819             : 
    1820             :         // Finally write the XML in the right file name
    1821         120 :         if (!poDS->Crystalize())
    1822          10 :             throw CPLString("MRF: Error creating files");
    1823             :     }
    1824          22 :     catch (const CPLString &e)
    1825             :     {
    1826          22 :         if (nullptr != poDS)
    1827          10 :             delete poDS;
    1828          22 :         CPLError(CE_Failure, CPLE_ObjectNull, "%s", e.c_str());
    1829          22 :         poDS = nullptr;
    1830             :     }
    1831             : 
    1832         132 :     CSLDestroy(options);
    1833         132 :     if (nullptr == poDS)
    1834          22 :         return nullptr;
    1835             : 
    1836         110 :     char **papszFileList = poDS->GetFileList();
    1837         110 :     poDS->oOvManager.Initialize(poDS, poDS->GetPhysicalFilename(),
    1838             :                                 papszFileList);
    1839         110 :     CSLDestroy(papszFileList);
    1840             : 
    1841         110 :     CPLErr err = CE_None;
    1842             :     // Have PAM copy all, but skip the mask
    1843         110 :     int nCloneFlags = GCIF_PAM_DEFAULT & ~GCIF_MASK;
    1844             : 
    1845             :     // If copy is disabled, we're done, we just created an empty MRF
    1846         110 :     if (!on(CSLFetchNameValue(papszOptions, "NOCOPY")))
    1847             :     {
    1848             :         // Use the GDAL copy call
    1849             :         // Need to flag the dataset as compressed (COMPRESSED=TRUE) to force
    1850             :         // block writes This might not be what we want, if the input and out
    1851             :         // order is truly separate
    1852         108 :         nCloneFlags |= GCIF_MASK;  // We do copy the data, so copy the mask too
    1853             :                                    // if necessary
    1854         108 :         char **papszCWROptions = nullptr;
    1855             :         papszCWROptions =
    1856         108 :             CSLAddNameValue(papszCWROptions, "COMPRESSED", "TRUE");
    1857             : 
    1858             : #ifdef HAVE_JPEG
    1859             :         // Use the Zen version of the CopyWholeRaster if input has a dataset
    1860             :         // mask and JPEGs are generated
    1861         110 :         if (GMF_PER_DATASET == poSrcDS->GetRasterBand(1)->GetMaskFlags() &&
    1862           2 :             (poDS->current.comp == IL_JPEG
    1863             : #ifdef HAVE_PNG
    1864           0 :              || poDS->current.comp == IL_JPNG
    1865             : #endif
    1866             :              ))
    1867             :         {
    1868           2 :             err = poDS->ZenCopy(poSrcDS, pfnProgress, pProgressData);
    1869           2 :             nCloneFlags ^= GCIF_MASK;  // Turn the external mask off
    1870             :         }
    1871             :         else
    1872             : #endif
    1873             :         {
    1874         106 :             err = GDALDatasetCopyWholeRaster(
    1875             :                 (GDALDatasetH)poSrcDS, (GDALDatasetH)poDS, papszCWROptions,
    1876             :                 pfnProgress, pProgressData);
    1877             :         }
    1878             : 
    1879         108 :         CSLDestroy(papszCWROptions);
    1880             :     }
    1881             : 
    1882         110 :     if (CE_None == err)
    1883         110 :         err = poDS->CloneInfo(poSrcDS, nCloneFlags);
    1884             : 
    1885         110 :     if (CE_Failure == err)
    1886             :     {
    1887           0 :         delete poDS;
    1888           0 :         return nullptr;
    1889             :     }
    1890             : 
    1891         110 :     return poDS;
    1892             : }
    1893             : 
    1894             : // Prepares the data so it is suitable for Zen JPEG encoding, based on input
    1895             : // mask If bFBO is set, only the values of the first band are set non-zero when
    1896             : // needed
    1897             : template <typename T>
    1898           2 : static void ZenFilter(T *buffer, GByte *mask, int nPixels, int nBands,
    1899             :                       bool bFBO)
    1900             : {
    1901      524290 :     for (int i = 0; i < nPixels; i++)
    1902             :     {
    1903      524288 :         if (mask[i] == 0)
    1904             :         {  // enforce zero values
    1905      516096 :             for (int b = 0; b < nBands; b++)
    1906      387072 :                 buffer[nBands * i + b] = 0;
    1907             :         }
    1908             :         else
    1909             :         {  // enforce non-zero
    1910      395264 :             if (bFBO)
    1911             :             {  // First band only
    1912      197632 :                 bool f = true;
    1913      790528 :                 for (int b = 0; b < nBands; b++)
    1914             :                 {
    1915      592896 :                     if (0 == buffer[nBands * i + b])
    1916             :                     {
    1917           0 :                         f = false;
    1918           0 :                         break;
    1919             :                     }
    1920             :                 }
    1921      197632 :                 if (f)
    1922      197632 :                     buffer[nBands * i] = 1;
    1923             :             }
    1924             :             else
    1925             :             {  // Every band
    1926      790528 :                 for (int b = 0; b < nBands; b++)
    1927      592896 :                     if (0 == buffer[nBands * i + b])
    1928           0 :                         buffer[nBands * i + b] = 1;
    1929             :             }
    1930             :         }
    1931             :     }
    1932           2 : }
    1933             : 
    1934             : // Custom CopyWholeRaster for Zen JPEG, called when the input has a PER_DATASET
    1935             : // mask Works like GDALDatasetCopyWholeRaster, but it does filter the input data
    1936             : // based on the mask
    1937             : //
    1938           2 : CPLErr MRFDataset::ZenCopy(GDALDataset *poSrc, GDALProgressFunc pfnProgress,
    1939             :                            void *pProgressData)
    1940             : {
    1941           2 :     VALIDATE_POINTER1(poSrc, "MRF:ZenCopy", CE_Failure);
    1942             : 
    1943           2 :     if (!pfnProgress)
    1944           0 :         pfnProgress = GDALDummyProgress;
    1945             : 
    1946             :     /* -------------------------------------------------------------------- */
    1947             :     /*      Confirm the datasets match in size and band counts.             */
    1948             :     /* -------------------------------------------------------------------- */
    1949           2 :     const int nXSize = GetRasterXSize();
    1950           2 :     const int nYSize = GetRasterYSize();
    1951           2 :     const int nBandCount = GetRasterCount();
    1952             : 
    1953           2 :     if (poSrc->GetRasterXSize() != nXSize ||
    1954           4 :         poSrc->GetRasterYSize() != nYSize ||
    1955           2 :         poSrc->GetRasterCount() != nBandCount)
    1956             :     {
    1957           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1958             :                  "Input and output dataset sizes or band counts do not\n"
    1959             :                  "match in GDALDatasetCopyWholeRaster()");
    1960           0 :         return CE_Failure;
    1961             :     }
    1962             : 
    1963             :     /* -------------------------------------------------------------------- */
    1964             :     /*      Get our prototype band, and assume the others are similarly     */
    1965             :     /*      configured. Also get the per_dataset mask                       */
    1966             :     /* -------------------------------------------------------------------- */
    1967           2 :     GDALRasterBand *poSrcPrototypeBand = poSrc->GetRasterBand(1);
    1968           2 :     GDALRasterBand *poDstPrototypeBand = GetRasterBand(1);
    1969           2 :     GDALRasterBand *poSrcMask = poSrcPrototypeBand->GetMaskBand();
    1970             : 
    1971           2 :     const int nPageXSize = current.pagesize.x;
    1972           2 :     const int nPageYSize = current.pagesize.y;
    1973           2 :     const double nTotalBlocks =
    1974           2 :         static_cast<double>(DIV_ROUND_UP(nYSize, nPageYSize)) *
    1975           2 :         static_cast<double>(DIV_ROUND_UP(nXSize, nPageXSize));
    1976           2 :     const GDALDataType eDT = poDstPrototypeBand->GetRasterDataType();
    1977             : 
    1978             :     // All the bands are done per block
    1979             :     // this flag tells us to apply the Zen filter to the first band only
    1980           2 :     const bool bFirstBandOnly = (current.order == IL_Interleaved);
    1981             : 
    1982           2 :     if (!pfnProgress(0.0, nullptr, pProgressData))
    1983             :     {
    1984           0 :         CPLError(CE_Failure, CPLE_UserInterrupt,
    1985             :                  "User terminated CreateCopy()");
    1986           0 :         return CE_Failure;
    1987             :     }
    1988             : 
    1989           2 :     const int nPixelCount = nPageXSize * nPageYSize;
    1990           2 :     const int dts = GDALGetDataTypeSizeBytes(eDT);
    1991           2 :     void *buffer = VSI_MALLOC3_VERBOSE(nPixelCount, nBandCount, dts);
    1992           2 :     GByte *buffer_mask = nullptr;
    1993           2 :     if (buffer)
    1994             :         buffer_mask =
    1995           2 :             reinterpret_cast<GByte *>(VSI_MALLOC_VERBOSE(nPixelCount));
    1996             : 
    1997           2 :     if (!buffer || !buffer_mask)
    1998             :     {
    1999             :         // Just in case buffers did get allocated
    2000           0 :         CPLFree(buffer);
    2001           0 :         CPLFree(buffer_mask);
    2002           0 :         CPLError(CE_Failure, CPLE_OutOfMemory, "Can't allocate copy buffer");
    2003           0 :         return CE_Failure;
    2004             :     }
    2005             : 
    2006           2 :     int nBlocksDone = 0;
    2007           2 :     CPLErr eErr = CE_None;
    2008             :     // Advise the source that a complete read will be done
    2009           2 :     poSrc->AdviseRead(0, 0, nXSize, nYSize, nXSize, nYSize, eDT, nBandCount,
    2010           2 :                       nullptr, nullptr);
    2011             : 
    2012             :     // For every block, break on error
    2013           4 :     for (int row = 0; row < nYSize && eErr == CE_None; row += nPageYSize)
    2014             :     {
    2015           2 :         int nRows = std::min(nPageYSize, nYSize - row);
    2016           4 :         for (int col = 0; col < nXSize && eErr == CE_None; col += nPageXSize)
    2017             :         {
    2018           2 :             int nCols = std::min(nPageXSize, nXSize - col);
    2019             : 
    2020             :             // Report
    2021           2 :             if (eErr == CE_None && !pfnProgress(nBlocksDone++ / nTotalBlocks,
    2022             :                                                 nullptr, pProgressData))
    2023             :             {
    2024           0 :                 eErr = CE_Failure;
    2025           0 :                 CPLError(CE_Failure, CPLE_UserInterrupt,
    2026             :                          "User terminated CreateCopy()");
    2027           0 :                 break;
    2028             :             }
    2029             : 
    2030             :             // Get the data mask as byte
    2031           2 :             eErr = poSrcMask->RasterIO(GF_Read, col, row, nCols, nRows,
    2032             :                                        buffer_mask, nCols, nRows, GDT_Byte, 0,
    2033             :                                        0, nullptr);
    2034             : 
    2035           2 :             if (eErr != CE_None)
    2036           0 :                 break;
    2037             : 
    2038             :             // If there is no data at all, skip this block
    2039           2 :             if (MatchCount(buffer_mask, nPixelCount, static_cast<GByte>(0)) ==
    2040             :                 nPixelCount)
    2041           0 :                 continue;
    2042             : 
    2043             :             // get the data in the buffer, interleaved
    2044           4 :             eErr = poSrc->RasterIO(
    2045             :                 GF_Read, col, row, nCols, nRows, buffer, nCols, nRows, eDT,
    2046           2 :                 nBandCount, nullptr, static_cast<GSpacing>(nBands) * dts,
    2047           2 :                 static_cast<GSpacing>(nBands) * dts * nCols, dts, nullptr);
    2048             : 
    2049           2 :             if (eErr != CE_None)
    2050           0 :                 break;
    2051             : 
    2052             :             // This is JPEG, only 8 and 12(16) bits unsigned integer types are
    2053             :             // valid
    2054           2 :             switch (eDT)
    2055             :             {
    2056           2 :                 case GDT_Byte:
    2057           2 :                     ZenFilter(reinterpret_cast<GByte *>(buffer), buffer_mask,
    2058             :                               nPixelCount, nBandCount, bFirstBandOnly);
    2059           2 :                     break;
    2060           0 :                 case GDT_UInt16:
    2061           0 :                     ZenFilter(reinterpret_cast<GUInt16 *>(buffer), buffer_mask,
    2062             :                               nPixelCount, nBandCount, bFirstBandOnly);
    2063           0 :                     break;
    2064           0 :                 default:
    2065           0 :                     CPLError(CE_Failure, CPLE_AppDefined,
    2066             :                              "Unsupported data type for Zen filter");
    2067           0 :                     eErr = CE_Failure;
    2068           0 :                     break;
    2069             :             }
    2070             : 
    2071             :             // Write
    2072           2 :             if (eErr == CE_None)
    2073           2 :                 eErr = RasterIO(
    2074             :                     GF_Write, col, row, nCols, nRows, buffer, nCols, nRows, eDT,
    2075           2 :                     nBandCount, nullptr, static_cast<GSpacing>(nBands) * dts,
    2076           2 :                     static_cast<GSpacing>(nBands) * dts * nCols, dts, nullptr);
    2077             : 
    2078             :         }  // Columns
    2079           2 :         if (eErr != CE_None)
    2080           0 :             break;
    2081             : 
    2082             :     }  // Rows
    2083             : 
    2084             :     // Cleanup
    2085           2 :     CPLFree(buffer);
    2086           2 :     CPLFree(buffer_mask);
    2087             : 
    2088             :     // Final report
    2089           2 :     if (eErr == CE_None && !pfnProgress(1.0, nullptr, pProgressData))
    2090             :     {
    2091           0 :         eErr = CE_Failure;
    2092           0 :         CPLError(CE_Failure, CPLE_UserInterrupt,
    2093             :                  "User terminated CreateCopy()");
    2094             :     }
    2095             : 
    2096           2 :     return eErr;
    2097             : }
    2098             : 
    2099             : // Apply open options to the current dataset
    2100             : // Called before the configuration is read
    2101         202 : void MRFDataset::ProcessOpenOptions(char **papszOptions)
    2102             : {
    2103         404 :     CPLStringList opt(papszOptions, FALSE);
    2104         202 :     no_errors = opt.FetchBoolean("NOERRORS", FALSE);
    2105         202 :     const char *val = opt.FetchNameValue("ZSLICE");
    2106         202 :     if (val)
    2107           0 :         zslice = atoi(val);
    2108         202 : }
    2109             : 
    2110             : // Apply create options to the current dataset, only valid during creation
    2111         161 : void MRFDataset::ProcessCreateOptions(char **papszOptions)
    2112             : {
    2113         161 :     assert(!bCrystalized);
    2114         322 :     CPLStringList opt(papszOptions, FALSE);
    2115         161 :     ILImage &img(full);
    2116             : 
    2117         161 :     const char *val = opt.FetchNameValue("COMPRESS");
    2118         161 :     if (val && IL_ERR_COMP == (img.comp = CompToken(val)))
    2119           0 :         throw CPLString("GDAL MRF: Error setting compression");
    2120             : 
    2121         161 :     val = opt.FetchNameValue("INTERLEAVE");
    2122         161 :     if (val && IL_ERR_ORD == (img.order = OrderToken(val)))
    2123           0 :         throw CPLString("GDAL MRF: Error setting interleave");
    2124             : 
    2125         161 :     val = opt.FetchNameValue("QUALITY");
    2126         161 :     if (val)
    2127           6 :         img.quality = atoi(val);
    2128             : 
    2129         161 :     val = opt.FetchNameValue("ZSIZE");
    2130         161 :     if (val)
    2131           0 :         img.size.z = atoi(val);
    2132             : 
    2133         161 :     val = opt.FetchNameValue("BLOCKXSIZE");
    2134         161 :     if (val)
    2135           1 :         img.pagesize.x = atoi(val);
    2136             : 
    2137         161 :     val = opt.FetchNameValue("BLOCKYSIZE");
    2138         161 :     if (val)
    2139           1 :         img.pagesize.y = atoi(val);
    2140             : 
    2141         161 :     val = opt.FetchNameValue("BLOCKSIZE");
    2142         161 :     if (val)
    2143          30 :         img.pagesize.x = img.pagesize.y = atoi(val);
    2144             : 
    2145         161 :     img.nbo = opt.FetchBoolean("NETBYTEORDER", FALSE) != FALSE;
    2146             : 
    2147         161 :     val = opt.FetchNameValue("CACHEDSOURCE");
    2148         161 :     if (val)
    2149             :     {
    2150           2 :         source = val;
    2151           2 :         nocopy = opt.FetchBoolean("NOCOPY", FALSE);
    2152             :     }
    2153             : 
    2154         161 :     val = opt.FetchNameValue("UNIFORM_SCALE");
    2155         161 :     if (val)
    2156           0 :         scale = atoi(val);
    2157             : 
    2158         161 :     val = opt.FetchNameValue("PHOTOMETRIC");
    2159         161 :     if (val)
    2160           2 :         photometric = val;
    2161             : 
    2162         161 :     val = opt.FetchNameValue("DATANAME");
    2163         161 :     if (val)
    2164           0 :         img.datfname = val;
    2165             : 
    2166         161 :     val = opt.FetchNameValue("INDEXNAME");
    2167         161 :     if (val)
    2168           0 :         img.idxfname = val;
    2169             : 
    2170         161 :     val = opt.FetchNameValue("SPACING");
    2171         161 :     if (val)
    2172           0 :         spacing = atoi(val);
    2173             : 
    2174             :     optlist.Assign(
    2175             :         CSLTokenizeString2(opt.FetchNameValue("OPTIONS"), " \t\n\r",
    2176         161 :                            CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES));
    2177             : 
    2178             :     // General Fixups
    2179         161 :     if (img.order == IL_Interleaved)
    2180          65 :         img.pagesize.c = img.size.c;
    2181             : 
    2182             :     // Compression dependent fixups
    2183         161 : }
    2184             : 
    2185             : /**
    2186             :  *\brief Create an MRF dataset, some settings can be changed later
    2187             :  * papszOptions might be anything that an MRF might take
    2188             :  * Still missing are the georeference ...
    2189             :  *
    2190             :  */
    2191             : 
    2192         165 : GDALDataset *MRFDataset::Create(const char *pszName, int nXSize, int nYSize,
    2193             :                                 int nBandsIn, GDALDataType eType,
    2194             :                                 char **papszOptions)
    2195             : {
    2196         165 :     if (nBandsIn == 0)
    2197             :     {
    2198           1 :         CPLError(CE_Failure, CPLE_NotSupported, "No bands defined");
    2199           1 :         return nullptr;
    2200             :     }
    2201             : 
    2202         164 :     MRFDataset *poDS = new MRFDataset();
    2203         164 :     CPLErr err = CE_None;
    2204         164 :     poDS->fname = pszName;
    2205         164 :     poDS->nBands = nBandsIn;
    2206             : 
    2207             :     // Don't know what to do with these in this call
    2208             :     // int level = -1;
    2209             :     // int version = 0;
    2210             : 
    2211         164 :     size_t pos = poDS->fname.find(":MRF:");
    2212         164 :     if (string::npos != pos)
    2213             :     {  // Tokenize and pick known options
    2214           0 :         vector<string> tokens;
    2215           0 :         stringSplit(tokens, poDS->fname, pos + 5, ':');
    2216             :         // level = getnum(tokens, 'L', -1);
    2217             :         // version = getnum(tokens, 'V', 0);
    2218           0 :         poDS->zslice = getnum(tokens, 'Z', 0);
    2219           0 :         poDS->fname.resize(pos);  // Cut the ornamentations
    2220             :     }
    2221             : 
    2222             :     // Try creating the mrf file early, to avoid failing on Crystalize later
    2223         164 :     if (!STARTS_WITH(poDS->fname.c_str(), "<MRF_META>"))
    2224             :     {
    2225             :         // Try opening it first, even though we still clobber it later
    2226         164 :         VSILFILE *mainfile = VSIFOpenL(poDS->fname.c_str(), "r+b");
    2227         164 :         if (!mainfile)
    2228             :         {  // Then try creating it
    2229         115 :             mainfile = VSIFOpenL(poDS->fname.c_str(), "w+b");
    2230         115 :             if (!mainfile)
    2231             :             {
    2232           3 :                 CPLError(CE_Failure, CPLE_OpenFailed,
    2233             :                          "MRF: Can't open %s for writing", poDS->fname.c_str());
    2234           3 :                 delete poDS;
    2235           3 :                 return nullptr;
    2236             :             }
    2237             :         }
    2238         161 :         VSIFCloseL(mainfile);
    2239             :     }
    2240             : 
    2241             :     // Use the full, set some initial parameters
    2242         161 :     ILImage &img = poDS->full;
    2243         161 :     img.size = ILSize(nXSize, nYSize, 1, nBandsIn);
    2244             : #ifdef HAVE_PNG
    2245         161 :     img.comp = IL_PNG;
    2246             : #else
    2247             :     img.comp = IL_NONE;
    2248             : #endif
    2249         161 :     img.order = (nBandsIn < 5) ? IL_Interleaved : IL_Separate;
    2250         161 :     img.pagesize = ILSize(512, 512, 1, 1);
    2251         161 :     img.quality = 85;
    2252         161 :     img.dt = eType;
    2253         161 :     img.dataoffset = 0;
    2254         161 :     img.idxoffset = 0;
    2255         161 :     img.hasNoData = false;
    2256         161 :     img.nbo = false;
    2257             : 
    2258             :     // Set the guard that tells us it needs saving before IO can take place
    2259         161 :     poDS->bCrystalized = FALSE;
    2260             : 
    2261             :     // Process the options, anything that an MRF might take
    2262             : 
    2263             :     try
    2264             :     {
    2265             :         // Adjust the dataset and the full image
    2266         161 :         poDS->ProcessCreateOptions(papszOptions);
    2267             : 
    2268             :         // Set default file names
    2269         161 :         if (img.datfname.empty())
    2270         161 :             img.datfname = getFname(poDS->GetFname(), ILComp_Ext[img.comp]);
    2271         161 :         if (img.idxfname.empty())
    2272         161 :             img.idxfname = getFname(poDS->GetFname(), ".idx");
    2273             : 
    2274         161 :         poDS->eAccess = GA_Update;
    2275             :     }
    2276             : 
    2277           0 :     catch (const CPLString &e)
    2278             :     {
    2279           0 :         CPLError(CE_Failure, CPLE_OpenFailed, "%s", e.c_str());
    2280           0 :         delete poDS;
    2281           0 :         return nullptr;
    2282             :     }
    2283             : 
    2284         161 :     poDS->current = poDS->full;
    2285         161 :     poDS->SetDescription(poDS->GetFname());
    2286             : 
    2287             :     // Build a MRF XML and initialize from it, this creates the bands
    2288         161 :     CPLXMLNode *config = poDS->BuildConfig();
    2289         161 :     err = poDS->Initialize(config);
    2290         161 :     CPLDestroyXMLNode(config);
    2291             : 
    2292         161 :     if (CPLE_None != err)
    2293             :     {
    2294          31 :         delete poDS;
    2295          31 :         return nullptr;
    2296             :     }
    2297             : 
    2298             :     // If not set by the band, get a pageSizeBytes buffer
    2299         130 :     if (poDS->GetPBufferSize() == 0 &&
    2300           0 :         !poDS->SetPBuffer(poDS->current.pageSizeBytes))
    2301             :     {
    2302           0 :         delete poDS;
    2303           0 :         return nullptr;
    2304             :     }
    2305             : 
    2306             :     // Tell PAM what our real file name is, to help it find the aux.xml
    2307         130 :     poDS->SetPhysicalFilename(poDS->GetFname());
    2308         130 :     return poDS;
    2309             : }
    2310             : 
    2311         171 : int MRFDataset::Crystalize()
    2312             : {
    2313         171 :     if (bCrystalized || eAccess != GA_Update)
    2314             :     {
    2315           0 :         bCrystalized = TRUE;
    2316           0 :         return TRUE;
    2317             :     }
    2318             : 
    2319             :     // No need to write to disk if there is no filename.  This is a
    2320             :     // memory only dataset.
    2321         342 :     if (strlen(GetDescription()) == 0 ||
    2322         171 :         EQUALN(GetDescription(), "<MRF_META>", 10))
    2323             :     {
    2324           0 :         bCrystalized = TRUE;
    2325           0 :         return TRUE;
    2326             :     }
    2327             : 
    2328         171 :     CPLXMLNode *config = BuildConfig();
    2329         171 :     if (!WriteConfig(config))
    2330          20 :         return FALSE;
    2331         151 :     CPLDestroyXMLNode(config);
    2332         151 :     if (!nocopy && (!IdxFP() || !DataFP()))
    2333           0 :         return FALSE;
    2334         151 :     bCrystalized = TRUE;
    2335         151 :     return TRUE;
    2336             : }
    2337             : 
    2338             : // Copy the first index at the end of the file and bump the version count
    2339           1 : CPLErr MRFDataset::AddVersion()
    2340             : {
    2341           1 :     VSILFILE *l_ifp = IdxFP();
    2342           1 :     void *tbuff = CPLMalloc(static_cast<size_t>(idxSize));
    2343           1 :     VSIFSeekL(l_ifp, 0, SEEK_SET);
    2344           1 :     VSIFReadL(tbuff, 1, static_cast<size_t>(idxSize), l_ifp);
    2345           1 :     verCount++;  // The one we write
    2346           1 :     VSIFSeekL(l_ifp, idxSize * verCount,
    2347             :               SEEK_SET);  // At the end, this can mess things up royally
    2348           1 :     VSIFWriteL(tbuff, 1, static_cast<size_t>(idxSize), l_ifp);
    2349           1 :     CPLFree(tbuff);
    2350           1 :     return CE_None;
    2351             : }
    2352             : 
    2353             : //
    2354             : // Write a tile at the end of the data file
    2355             : // If buff and size are zero, it is equivalent to erasing the tile
    2356             : // If only size is zero, it is a special empty tile,
    2357             : // when used for caching, offset should be 1
    2358             : //
    2359             : // To make it multi-processor safe, open the file in append mode
    2360             : // and verify after write
    2361             : //
    2362        5084 : CPLErr MRFDataset::WriteTile(void *buff, GUIntBig infooffset, GUIntBig size)
    2363             : {
    2364        5084 :     CPLErr ret = CE_None;
    2365        5084 :     ILIdx tinfo = {0, 0};
    2366             : 
    2367        5084 :     VSILFILE *l_dfp = DataFP();
    2368        5084 :     VSILFILE *l_ifp = IdxFP();
    2369             : 
    2370             :     // Verify buffer
    2371       10168 :     std::vector<GByte> tbuff;
    2372             : 
    2373        5084 :     if (l_ifp == nullptr || l_dfp == nullptr)
    2374           0 :         return CE_Failure;
    2375             : 
    2376             :     // Flag that versioned access requires a write even if empty
    2377        5084 :     int new_tile = false;
    2378             :     // If it has versions, might need to start a new one
    2379        5084 :     if (hasVersions)
    2380             :     {
    2381           1 :         int new_version = false;  // Assume no need to build new version
    2382             : 
    2383             :         // Read the current tile info
    2384           1 :         VSIFSeekL(l_ifp, infooffset, SEEK_SET);
    2385           1 :         VSIFReadL(&tinfo, 1, sizeof(ILIdx), l_ifp);
    2386             : 
    2387           1 :         if (verCount == 0)
    2388           1 :             new_version = true;  // No previous yet, might create a new version
    2389             :         else
    2390             :         {  // We need at least two versions before we can test for changes
    2391           0 :             ILIdx prevtinfo = {0, 0};
    2392             : 
    2393             :             // Read the previous one
    2394           0 :             VSIFSeekL(l_ifp, infooffset + verCount * idxSize, SEEK_SET);
    2395           0 :             VSIFReadL(&prevtinfo, 1, sizeof(ILIdx), l_ifp);
    2396             : 
    2397             :             // current and previous tiles are different, might create version
    2398           0 :             if (tinfo.size != prevtinfo.size ||
    2399           0 :                 tinfo.offset != prevtinfo.offset)
    2400           0 :                 new_version = true;
    2401             :         }
    2402             : 
    2403             :         // tinfo contains the current info or 0,0
    2404           1 :         if (tinfo.size == GIntBig(net64(size)))
    2405             :         {  // Might be identical
    2406           0 :             if (size != 0)
    2407             :             {
    2408             :                 // Use the temporary buffer
    2409           0 :                 tbuff.resize(static_cast<size_t>(size));
    2410           0 :                 VSIFSeekL(l_dfp, infooffset, SEEK_SET);
    2411           0 :                 VSIFReadL(tbuff.data(), 1, tbuff.size(), l_dfp);
    2412             :                 // Need to write it if not the same
    2413           0 :                 new_tile = !std::equal(tbuff.begin(), tbuff.end(),
    2414             :                                        static_cast<GByte *>(buff));
    2415           0 :                 tbuff.clear();
    2416             :             }
    2417             :             else
    2418             :             {
    2419             :                 // Writing a null tile on top of a null tile, does it count?
    2420           0 :                 if (tinfo.offset != GIntBig(net64(GUIntBig(buff))))
    2421           0 :                     new_tile = true;
    2422             :             }
    2423             :         }
    2424             :         else
    2425             :         {
    2426           1 :             new_tile = true;  // Need to write it because it is different
    2427           1 :             if (verCount == 0 && tinfo.size == 0)
    2428           0 :                 new_version = false;  // Don't create a version if current is
    2429             :                                       // empty and there is no previous
    2430             :         }
    2431             : 
    2432           1 :         if (!new_tile)
    2433           0 :             return CE_None;  // No reason to write
    2434             : 
    2435             :         // Do we need to start a new version before writing the tile?
    2436           1 :         if (new_version)
    2437           1 :             AddVersion();
    2438             :     }
    2439             : 
    2440        5084 :     bool same = true;
    2441        5084 :     if (size)
    2442           0 :         do
    2443             :         {
    2444             :             // start of critical MP section
    2445        5083 :             VSIFSeekL(l_dfp, 0, SEEK_END);
    2446        5083 :             GUIntBig offset = VSIFTellL(l_dfp) + spacing;
    2447             : 
    2448             :             // Spacing should be 0 in MP safe mode, this doesn't have much of
    2449             :             // effect Use the existing data, spacing content is not guaranteed
    2450        5083 :             for (GUIntBig pending = spacing; pending != 0;
    2451           0 :                  pending -= std::min(pending, size))
    2452           0 :                 VSIFWriteL(buff, 1,
    2453           0 :                            static_cast<size_t>(std::min(pending, size)),
    2454             :                            l_dfp);  // Usually only once
    2455             : 
    2456        5083 :             if (static_cast<size_t>(size) !=
    2457        5083 :                 VSIFWriteL(buff, 1, static_cast<size_t>(size), l_dfp))
    2458           0 :                 ret = CE_Failure;
    2459             :             // End of critical section
    2460             : 
    2461        5083 :             tinfo.offset = net64(offset);
    2462             :             //
    2463             :             // For MP ops, check that we can read the same content, otherwise
    2464             :             // try again This makes the caching MRF MP safe on file systems that
    2465             :             // implement append mode fully, without using explicit locks
    2466             :             //
    2467        5083 :             if (CE_None == ret && mp_safe)
    2468             :             {  // readback and check
    2469           3 :                 if (tbuff.size() < size)
    2470           3 :                     tbuff.resize(static_cast<size_t>(size));
    2471           3 :                 VSIFSeekL(l_dfp, offset, SEEK_SET);
    2472           3 :                 VSIFReadL(tbuff.data(), 1, tbuff.size(), l_dfp);
    2473           3 :                 same = std::equal(tbuff.begin(), tbuff.end(),
    2474             :                                   static_cast<GByte *>(buff));
    2475             :             }
    2476        5083 :         } while (CE_None == ret && mp_safe && !same);
    2477             : 
    2478        5084 :     if (CE_None != ret)
    2479             :     {
    2480           0 :         CPLError(CE_Failure, CPLE_AppDefined, "MRF: Tile write failed");
    2481           0 :         return ret;
    2482             :     }
    2483             : 
    2484             :     // Convert index to net format, offset is set already
    2485        5084 :     tinfo.size = net64(size);
    2486             :     // Do nothing if the tile is empty and the file record is also empty
    2487        5084 :     if (!new_tile && 0 == size && nullptr == buff)
    2488             :     {
    2489           0 :         VSIFSeekL(l_ifp, infooffset, SEEK_SET);
    2490           0 :         VSIFReadL(&tinfo, 1, sizeof(ILIdx), l_ifp);
    2491           0 :         if (0 == tinfo.offset && 0 == tinfo.size)
    2492           0 :             return ret;
    2493             :     }
    2494             : 
    2495             :     // Special case, any non-zero offset will do
    2496        5084 :     if (nullptr != buff && 0 == size)
    2497           0 :         tinfo.offset = ~GUIntBig(0);
    2498             : 
    2499        5084 :     VSIFSeekL(l_ifp, infooffset, SEEK_SET);
    2500        5084 :     if (sizeof(tinfo) != VSIFWriteL(&tinfo, 1, sizeof(tinfo), l_ifp))
    2501             :     {
    2502           0 :         CPLError(CE_Failure, CPLE_AppDefined, "MRF: Index write failed");
    2503           0 :         ret = CE_Failure;
    2504             :     }
    2505             : 
    2506        5084 :     return ret;
    2507             : }
    2508             : 
    2509         126 : CPLErr MRFDataset::SetGeoTransform(double *gt)
    2510             : {
    2511         126 :     if (GetAccess() != GA_Update || bCrystalized)
    2512             :     {
    2513           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    2514             :                  "SetGeoTransform only works during Create call");
    2515           0 :         return CE_Failure;
    2516             :     }
    2517         126 :     memcpy(GeoTransform, gt, 6 * sizeof(double));
    2518         126 :     bGeoTransformValid = TRUE;
    2519         126 :     return CE_None;
    2520             : }
    2521             : 
    2522          16 : bool MRFDataset::IsSingleTile()
    2523             : {
    2524          16 :     if (current.pagecount.l != 1 || !source.empty() || nullptr == DataFP())
    2525           4 :         return FALSE;
    2526          12 :     return 0 == reinterpret_cast<MRFRasterBand *>(GetRasterBand(1))
    2527          12 :                     ->GetOverviewCount();
    2528             : }
    2529             : 
    2530             : /*
    2531             :  *  Returns 0,1,0,0,0,1 even if it was not set
    2532             :  */
    2533         451 : CPLErr MRFDataset::GetGeoTransform(double *gt)
    2534             : {
    2535         451 :     memcpy(gt, GeoTransform, 6 * sizeof(double));
    2536         451 :     if (GetMetadata("RPC") || GetGCPCount())
    2537           0 :         bGeoTransformValid = FALSE;
    2538         451 :     if (!bGeoTransformValid)
    2539           0 :         return CE_Failure;
    2540         451 :     return CE_None;
    2541             : }
    2542             : 
    2543             : /**
    2544             :  *\brief Read a tile index
    2545             :  *
    2546             :  * It handles the non-existent index case, for no compression
    2547             :  * The bias is non-zero only when the cloned index is read
    2548             :  */
    2549             : 
    2550        2019 : CPLErr MRFDataset::ReadTileIdx(ILIdx &tinfo, const ILSize &pos,
    2551             :                                const ILImage &img, const GIntBig bias)
    2552             : {
    2553        2019 :     VSILFILE *l_ifp = IdxFP();
    2554             : 
    2555             :     // Initialize the tinfo structure, in case the files are missing
    2556        2019 :     if (missing)
    2557           0 :         return CE_None;
    2558             : 
    2559        2019 :     GIntBig offset = bias + IdxOffset(pos, img);
    2560        2019 :     if (l_ifp == nullptr && img.comp == IL_NONE)
    2561             :     {
    2562           0 :         tinfo.size = current.pageSizeBytes;
    2563           0 :         tinfo.offset = offset * tinfo.size;
    2564           0 :         return CE_None;
    2565             :     }
    2566             : 
    2567        2019 :     if (l_ifp == nullptr && IsSingleTile())
    2568             :     {
    2569           6 :         tinfo.offset = 0;
    2570           6 :         VSILFILE *l_dfp = DataFP();  // IsSingleTile() checks that fp is valid
    2571           6 :         VSIFSeekL(l_dfp, 0, SEEK_END);
    2572           6 :         tinfo.size = VSIFTellL(l_dfp);
    2573             : 
    2574             :         // It should be less than the pagebuffer
    2575           6 :         tinfo.size = std::min(tinfo.size, static_cast<GIntBig>(pbsize));
    2576           6 :         return CE_None;
    2577             :     }
    2578             : 
    2579        2013 :     if (l_ifp == nullptr)
    2580             :     {
    2581           0 :         CPLError(CE_Failure, CPLE_FileIO, "Can't open index file");
    2582           0 :         return CE_Failure;
    2583             :     }
    2584             : 
    2585        2013 :     VSIFSeekL(l_ifp, offset, SEEK_SET);
    2586        2013 :     if (1 != VSIFReadL(&tinfo, sizeof(ILIdx), 1, l_ifp))
    2587           0 :         return CE_Failure;
    2588             :     // Convert them to native form
    2589        2013 :     tinfo.offset = net64(tinfo.offset);
    2590        2013 :     tinfo.size = net64(tinfo.size);
    2591             : 
    2592        2013 :     if (0 == bias || 0 != tinfo.size || 0 != tinfo.offset)
    2593        2012 :         return CE_None;
    2594             : 
    2595             :     // zero size and zero offset in sourced index means that this portion is
    2596             :     // un-initialized
    2597             : 
    2598             :     // Should be cloned and the offset within the cloned index
    2599           1 :     offset -= bias;
    2600           1 :     assert(offset < bias);
    2601           1 :     assert(clonedSource);
    2602             : 
    2603             :     // Read this block from the remote index, prepare it and store it in the
    2604             :     // right place The block size in bytes, should be a multiple of 16, to have
    2605             :     // full index entries
    2606           1 :     const int CPYSZ = 32768;
    2607             :     // Adjust offset to the start of the block
    2608           1 :     offset = (offset / CPYSZ) * CPYSZ;
    2609           1 :     GIntBig size = std::min(size_t(CPYSZ), size_t(bias - offset));
    2610           1 :     size /= sizeof(ILIdx);  // In records
    2611           2 :     vector<ILIdx> buf(static_cast<size_t>(size));
    2612           1 :     ILIdx *buffer = &buf[0];  // Buffer to copy the source to the clone index
    2613             : 
    2614             :     // Fetch the data from the cloned index
    2615           1 :     MRFDataset *pSrc = static_cast<MRFDataset *>(GetSrcDS());
    2616           1 :     if (nullptr == pSrc)
    2617             :     {
    2618           0 :         CPLError(CE_Failure, CPLE_FileIO, "Can't open cloned source index");
    2619           0 :         return CE_Failure;  // Source reported the error
    2620             :     }
    2621             : 
    2622           1 :     VSILFILE *srcidx = pSrc->IdxFP();
    2623           1 :     if (nullptr == srcidx)
    2624             :     {
    2625           0 :         CPLError(CE_Failure, CPLE_FileIO, "Can't open cloned source index");
    2626           0 :         return CE_Failure;  // Source reported the error
    2627             :     }
    2628             : 
    2629           1 :     VSIFSeekL(srcidx, offset, SEEK_SET);
    2630           1 :     size = VSIFReadL(buffer, sizeof(ILIdx), static_cast<size_t>(size), srcidx);
    2631           1 :     if (size != GIntBig(buf.size()))
    2632             :     {
    2633           0 :         CPLError(CE_Failure, CPLE_FileIO, "Can't read cloned source index");
    2634           0 :         return CE_Failure;  // Source reported the error
    2635             :     }
    2636             : 
    2637             :     // Mark the empty records as checked, by making the offset non-zero
    2638           2 :     for (vector<ILIdx>::iterator it = buf.begin(); it != buf.end(); ++it)
    2639             :     {
    2640           1 :         if (it->offset == 0 && it->size == 0)
    2641           0 :             it->offset = net64(1);
    2642             :     }
    2643             : 
    2644             :     // Write it in the right place in the local index file
    2645           1 :     VSIFSeekL(l_ifp, bias + offset, SEEK_SET);
    2646           1 :     size = VSIFWriteL(&buf[0], sizeof(ILIdx), static_cast<size_t>(size), l_ifp);
    2647           1 :     if (size != GIntBig(buf.size()))
    2648             :     {
    2649           0 :         CPLError(CE_Failure, CPLE_FileIO, "Can't write to cloning MRF index");
    2650           0 :         return CE_Failure;  // Source reported the error
    2651             :     }
    2652             : 
    2653             :     // Cloned index updated, restart this function, it will work now
    2654           1 :     return ReadTileIdx(tinfo, pos, img, bias);
    2655             : }
    2656             : 
    2657             : NAMESPACE_MRF_END

Generated by: LCOV version 1.14