LCOV - code coverage report
Current view: top level - frmts/rmf - rmfdataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 1339 1608 83.3 %
Date: 2026-06-19 21:24:00 Functions: 52 52 100.0 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  Raster Matrix Format
       4             :  * Purpose:  Read/write raster files used in GIS "Integratsia"
       5             :  *           (also known as "Panorama" GIS).
       6             :  * Author:   Andrey Kiselev, dron@ak4719.spb.edu
       7             :  *
       8             :  ******************************************************************************
       9             :  * Copyright (c) 2005, Andrey Kiselev <dron@ak4719.spb.edu>
      10             :  * Copyright (c) 2007-2012, Even Rouault <even dot rouault at spatialys.com>
      11             :  * Copyright (c) 2023, NextGIS <info@nextgis.com>
      12             :  *
      13             :  * SPDX-License-Identifier: MIT
      14             :  ****************************************************************************/
      15             : #include <algorithm>
      16             : #include <array>
      17             : #include <limits>
      18             : 
      19             : #include "cpl_string.h"
      20             : #include "gdal_frmts.h"
      21             : #include "ogr_spatialref.h"
      22             : #include "gdal_thread_pool.h"
      23             : 
      24             : #include "rmfdataset.h"
      25             : 
      26             : #include "cpl_safemaths.hpp"
      27             : 
      28             : constexpr int RMF_DEFAULT_BLOCKXSIZE = 256;
      29             : constexpr int RMF_DEFAULT_BLOCKYSIZE = 256;
      30             : 
      31             : static const char RMF_SigRSW[] = {'R', 'S', 'W', '\0'};
      32             : static const char RMF_SigRSW_BE[] = {'\0', 'W', 'S', 'R'};
      33             : static const char RMF_SigMTW[] = {'M', 'T', 'W', '\0'};
      34             : 
      35             : static const char RMF_UnitsEmpty[] = "";
      36             : static const char RMF_UnitsM[] = "m";
      37             : static const char RMF_UnitsCM[] = "cm";
      38             : static const char RMF_UnitsDM[] = "dm";
      39             : static const char RMF_UnitsMM[] = "mm";
      40             : 
      41             : constexpr double RMF_DEFAULT_SCALE = 10000.0;
      42             : constexpr double RMF_DEFAULT_RESOLUTION = 100.0;
      43             : 
      44             : constexpr const char *MD_VERSION_KEY = "VERSION";
      45             : constexpr const char *MD_NAME_KEY = "NAME";
      46             : constexpr const char *MD_SCALE_KEY = "SCALE";
      47             : constexpr const char *MD_FRAME_KEY = "FRAME";
      48             : 
      49             : constexpr const char *MD_MATH_BASE_MAP_TYPE_KEY = "MATH_BASE.Map type";
      50             : constexpr const char *MD_MATH_BASE_PROJECTION_KEY = "MATH_BASE.Projection";
      51             : 
      52             : constexpr int nMaxFramePointCount = 2048;
      53             : constexpr GInt32 nPolygonType =
      54             :     2147385342;  // 2147385342 magic number for polygon
      55             : 
      56             : /* -------------------------------------------------------------------- */
      57             : /*  Note: Due to the fact that in the early versions of RMF             */
      58             : /*  format the field of the iEPSGCode was marked as a 'reserved',       */
      59             : /*  in the header on its place in many cases garbage values were written.*/
      60             : /*  Most of them can be weeded out by the minimum EPSG code value.      */
      61             : /*                                                                      */
      62             : /*  see: Surveying and Positioning Guidance Note Number 7, part 1       */
      63             : /*       Using the EPSG Geodetic Parameter Dataset p. 22                */
      64             : /*       http://www.epsg.org/Portals/0/373-07-1.pdf                     */
      65             : /* -------------------------------------------------------------------- */
      66             : constexpr GInt32 RMF_EPSG_MIN_CODE = 1024;
      67             : 
      68          74 : static char *RMFUnitTypeToStr(GUInt32 iElevationUnit)
      69             : {
      70          74 :     switch (iElevationUnit)
      71             :     {
      72          68 :         case 0:
      73          68 :             return CPLStrdup(RMF_UnitsM);
      74           0 :         case 1:
      75           0 :             return CPLStrdup(RMF_UnitsDM);
      76           1 :         case 2:
      77           1 :             return CPLStrdup(RMF_UnitsCM);
      78           5 :         case 3:
      79           5 :             return CPLStrdup(RMF_UnitsMM);
      80           0 :         default:
      81           0 :             return CPLStrdup(RMF_UnitsEmpty);
      82             :     }
      83             : }
      84             : 
      85          80 : static GUInt32 RMFStrToUnitType(const char *pszUnit, int *pbSuccess = nullptr)
      86             : {
      87          80 :     if (pbSuccess != nullptr)
      88             :     {
      89           3 :         *pbSuccess = TRUE;
      90             :     }
      91          80 :     if (EQUAL(pszUnit, RMF_UnitsM))
      92           0 :         return 0;
      93          80 :     else if (EQUAL(pszUnit, RMF_UnitsDM))
      94           0 :         return 1;
      95          80 :     else if (EQUAL(pszUnit, RMF_UnitsCM))
      96           1 :         return 2;
      97          79 :     else if (EQUAL(pszUnit, RMF_UnitsMM))
      98           1 :         return 3;
      99             :     else
     100             :     {
     101             :         // There is no 'invalid unit' in RMF format. So meter is default...
     102          78 :         if (pbSuccess != nullptr)
     103             :         {
     104           1 :             *pbSuccess = FALSE;
     105             :         }
     106          78 :         return 0;
     107             :     }
     108             : }
     109             : 
     110             : /************************************************************************/
     111             : /* ==================================================================== */
     112             : /*                            RMFRasterBand                             */
     113             : /* ==================================================================== */
     114             : /************************************************************************/
     115             : 
     116             : /************************************************************************/
     117             : /*                           RMFRasterBand()                            */
     118             : /************************************************************************/
     119             : 
     120         419 : RMFRasterBand::RMFRasterBand(RMFDataset *poDSIn, int nBandIn,
     121         419 :                              GDALDataType eType)
     122         838 :     : nLastTileWidth(poDSIn->GetRasterXSize() % poDSIn->sHeader.nTileWidth),
     123         838 :       nLastTileHeight(poDSIn->GetRasterYSize() % poDSIn->sHeader.nTileHeight),
     124         419 :       nDataSize(GDALGetDataTypeSizeBytes(eType))
     125             : {
     126         419 :     poDS = poDSIn;
     127         419 :     nBand = nBandIn;
     128             : 
     129         419 :     eDataType = eType;
     130         419 :     nBlockXSize = poDSIn->sHeader.nTileWidth;
     131         419 :     nBlockYSize = poDSIn->sHeader.nTileHeight;
     132         419 :     nBlockSize = nBlockXSize * nBlockYSize;
     133         419 :     nBlockBytes = nBlockSize * nDataSize;
     134             : 
     135             : #ifdef DEBUG
     136         419 :     CPLDebug("RMF",
     137             :              "Band %d: tile width is %d, tile height is %d, "
     138             :              " last tile width %u, last tile height %u, "
     139             :              "bytes per pixel is %d, data type size is %d",
     140             :              nBand, nBlockXSize, nBlockYSize, nLastTileWidth, nLastTileHeight,
     141         419 :              poDSIn->sHeader.nBitDepth / 8, nDataSize);
     142             : #endif
     143         419 : }
     144             : 
     145             : /************************************************************************/
     146             : /*                           ~RMFRasterBand()                           */
     147             : /************************************************************************/
     148             : 
     149         838 : RMFRasterBand::~RMFRasterBand()
     150             : {
     151         838 : }
     152             : 
     153             : /************************************************************************/
     154             : /*                             IReadBlock()                             */
     155             : /************************************************************************/
     156             : 
     157         454 : CPLErr RMFRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff, void *pImage)
     158             : {
     159         454 :     RMFDataset *poGDS = cpl::down_cast<RMFDataset *>(poDS);
     160             : 
     161         454 :     CPLAssert(poGDS != nullptr && nBlockXOff >= 0 && nBlockYOff >= 0 &&
     162             :               pImage != nullptr);
     163             : 
     164         454 :     memset(pImage, 0, nBlockBytes);
     165             : 
     166         454 :     GUInt32 nRawXSize = nBlockXSize;
     167         454 :     GUInt32 nRawYSize = nBlockYSize;
     168             : 
     169         454 :     if (nLastTileWidth &&
     170         381 :         static_cast<GUInt32>(nBlockXOff) == poGDS->nXTiles - 1)
     171         176 :         nRawXSize = nLastTileWidth;
     172             : 
     173         454 :     if (nLastTileHeight &&
     174         365 :         static_cast<GUInt32>(nBlockYOff) == poGDS->nYTiles - 1)
     175         198 :         nRawYSize = nLastTileHeight;
     176             : 
     177         454 :     GUInt32 nRawBytes = nRawXSize * nRawYSize * poGDS->sHeader.nBitDepth / 8;
     178             : 
     179             :     // Direct read optimization
     180         454 :     if (poGDS->nBands == 1 && poGDS->sHeader.nBitDepth >= 8 &&
     181         183 :         nRawXSize == static_cast<GUInt32>(nBlockXSize) &&
     182          71 :         nRawYSize == static_cast<GUInt32>(nBlockYSize))
     183             :     {
     184          67 :         bool bNullTile = false;
     185          67 :         if (CE_None != poGDS->ReadTile(nBlockXOff, nBlockYOff,
     186             :                                        reinterpret_cast<GByte *>(pImage),
     187             :                                        nRawBytes, nRawXSize, nRawYSize,
     188             :                                        bNullTile))
     189             :         {
     190           0 :             CPLError(CE_Failure, CPLE_FileIO,
     191             :                      "Failed to read tile xOff %d yOff %d", nBlockXOff,
     192             :                      nBlockYOff);
     193           0 :             return CE_Failure;
     194             :         }
     195          67 :         if (bNullTile)
     196             :         {
     197             :             const int nChunkSize =
     198           1 :                 std::max(1, GDALGetDataTypeSizeBytes(eDataType));
     199           1 :             const GPtrDiff_t nWords =
     200           1 :                 static_cast<GPtrDiff_t>(nBlockXSize) * nBlockYSize;
     201           1 :             GDALCopyWords64(&poGDS->sHeader.dfNoData, GDT_Float64, 0, pImage,
     202             :                             eDataType, nChunkSize, nWords);
     203             :         }
     204          67 :         return CE_None;
     205             :     }
     206             : #ifdef DEBUG
     207         387 :     CPLDebug("RMF", "IReadBlock nBand %d, RawSize [%d, %d], Bits %u", nBand,
     208             :              nRawXSize, nRawYSize, poGDS->sHeader.nBitDepth);
     209             : #endif  // DEBUG
     210         387 :     if (poGDS->pabyCurrentTile == nullptr ||
     211         290 :         poGDS->nCurrentTileXOff != nBlockXOff ||
     212         102 :         poGDS->nCurrentTileYOff != nBlockYOff ||
     213         102 :         poGDS->nCurrentTileBytes != nRawBytes)
     214             :     {
     215         285 :         if (poGDS->pabyCurrentTile == nullptr)
     216             :         {
     217          97 :             GUInt32 nMaxTileBytes = poGDS->sHeader.nTileWidth *
     218          97 :                                     poGDS->sHeader.nTileHeight *
     219          97 :                                     poGDS->sHeader.nBitDepth / 8;
     220          97 :             poGDS->pabyCurrentTile = reinterpret_cast<GByte *>(
     221          97 :                 VSIMalloc(std::max(1U, nMaxTileBytes)));
     222          97 :             if (!poGDS->pabyCurrentTile)
     223             :             {
     224           0 :                 CPLError(CE_Failure, CPLE_OutOfMemory,
     225             :                          "Can't allocate tile block of size %lu.\n%s",
     226             :                          static_cast<unsigned long>(nMaxTileBytes),
     227           0 :                          VSIStrerror(errno));
     228           0 :                 poGDS->nCurrentTileBytes = 0;
     229           0 :                 return CE_Failure;
     230             :             }
     231             :         }
     232             : 
     233         285 :         poGDS->nCurrentTileXOff = nBlockXOff;
     234         285 :         poGDS->nCurrentTileYOff = nBlockYOff;
     235         285 :         poGDS->nCurrentTileBytes = nRawBytes;
     236             : 
     237         285 :         if (CE_None != poGDS->ReadTile(nBlockXOff, nBlockYOff,
     238             :                                        poGDS->pabyCurrentTile, nRawBytes,
     239             :                                        nRawXSize, nRawYSize,
     240         285 :                                        poGDS->bCurrentTileIsNull))
     241             :         {
     242           0 :             CPLError(CE_Failure, CPLE_FileIO,
     243             :                      "Failed to read tile xOff %d yOff %d", nBlockXOff,
     244             :                      nBlockYOff);
     245           0 :             poGDS->nCurrentTileBytes = 0;
     246           0 :             return CE_Failure;
     247             :         }
     248             :     }
     249             : 
     250             :     /* -------------------------------------------------------------------- */
     251             :     /*  Deinterleave pixels from input buffer.                              */
     252             :     /* -------------------------------------------------------------------- */
     253             : 
     254         387 :     if (poGDS->bCurrentTileIsNull)
     255             :     {
     256           0 :         const int nChunkSize = std::max(1, GDALGetDataTypeSizeBytes(eDataType));
     257           0 :         const GPtrDiff_t nWords =
     258           0 :             static_cast<GPtrDiff_t>(nBlockXSize) * nBlockYSize;
     259           0 :         GDALCopyWords64(&poGDS->sHeader.dfNoData, GDT_Float64, 0, pImage,
     260             :                         eDataType, nChunkSize, nWords);
     261           0 :         return CE_None;
     262             :     }
     263         387 :     else if ((poGDS->eRMFType == RMFT_RSW &&
     264         283 :               (poGDS->sHeader.nBitDepth == 8 ||
     265         271 :                poGDS->sHeader.nBitDepth == 24 ||
     266           9 :                poGDS->sHeader.nBitDepth == 32)) ||
     267         107 :              (poGDS->eRMFType == RMFT_MTW))
     268             :     {
     269         384 :         const size_t nTilePixelSize = poGDS->sHeader.nBitDepth / 8;
     270         384 :         const size_t nTileLineSize = nTilePixelSize * nRawXSize;
     271         384 :         const size_t nBlockLineSize =
     272         384 :             static_cast<size_t>(nDataSize) * nBlockXSize;
     273         384 :         int iDstBand = (poGDS->nBands - nBand);
     274       50423 :         for (GUInt32 iLine = 0; iLine != nRawYSize; ++iLine)
     275             :         {
     276             :             GByte *pabySrc;
     277             :             GByte *pabyDst;
     278       50039 :             pabySrc = poGDS->pabyCurrentTile + iLine * nTileLineSize +
     279       50039 :                       iDstBand * nDataSize;
     280       50039 :             pabyDst =
     281       50039 :                 reinterpret_cast<GByte *>(pImage) + iLine * nBlockLineSize;
     282       50039 :             GDALCopyWords(pabySrc, eDataType, static_cast<int>(nTilePixelSize),
     283       50039 :                           pabyDst, eDataType, static_cast<int>(nDataSize),
     284             :                           nRawXSize);
     285             :         }
     286         384 :         return CE_None;
     287             :     }
     288           3 :     else if (poGDS->eRMFType == RMFT_RSW && poGDS->sHeader.nBitDepth == 16 &&
     289           0 :              poGDS->nBands == 3)
     290             :     {
     291           0 :         const size_t nTilePixelBits = poGDS->sHeader.nBitDepth;
     292           0 :         const size_t nTileLineSize = nTilePixelBits * nRawXSize / 8;
     293           0 :         const size_t nBlockLineSize =
     294           0 :             static_cast<size_t>(nDataSize) * nBlockXSize;
     295             : 
     296           0 :         for (GUInt32 iLine = 0; iLine != nRawYSize; ++iLine)
     297             :         {
     298             :             GUInt16 *pabySrc;
     299             :             GByte *pabyDst;
     300           0 :             pabySrc = reinterpret_cast<GUInt16 *>(poGDS->pabyCurrentTile +
     301           0 :                                                   iLine * nTileLineSize);
     302           0 :             pabyDst =
     303           0 :                 reinterpret_cast<GByte *>(pImage) + iLine * nBlockLineSize;
     304             : 
     305           0 :             for (GUInt32 i = 0; i < nRawXSize; i++)
     306             :             {
     307           0 :                 switch (nBand)
     308             :                 {
     309           0 :                     case 1:
     310           0 :                         pabyDst[i] =
     311           0 :                             static_cast<GByte>((pabySrc[i] & 0x7c00) >> 7);
     312           0 :                         break;
     313           0 :                     case 2:
     314           0 :                         pabyDst[i] =
     315           0 :                             static_cast<GByte>((pabySrc[i] & 0x03e0) >> 2);
     316           0 :                         break;
     317           0 :                     case 3:
     318           0 :                         pabyDst[i] =
     319           0 :                             static_cast<GByte>((pabySrc[i] & 0x1F) << 3);
     320           0 :                         break;
     321           0 :                     default:
     322           0 :                         break;
     323             :                 }
     324             :             }
     325             :         }
     326           0 :         return CE_None;
     327             :     }
     328           3 :     else if (poGDS->eRMFType == RMFT_RSW && poGDS->nBands == 1 &&
     329           3 :              poGDS->sHeader.nBitDepth == 4)
     330             :     {
     331           2 :         if (poGDS->nCurrentTileBytes != (nBlockSize + 1) / 2)
     332             :         {
     333           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     334             :                      "Tile has %d bytes, %d were expected",
     335           0 :                      poGDS->nCurrentTileBytes, (nBlockSize + 1) / 2);
     336           0 :             return CE_Failure;
     337             :         }
     338             : 
     339           2 :         const size_t nTilePixelBits = poGDS->sHeader.nBitDepth;
     340           2 :         const size_t nTileLineSize = nTilePixelBits * nRawXSize / 8;
     341           2 :         const size_t nBlockLineSize =
     342           2 :             static_cast<size_t>(nDataSize) * nBlockXSize;
     343             : 
     344         464 :         for (GUInt32 iLine = 0; iLine != nRawYSize; ++iLine)
     345             :         {
     346             :             GByte *pabySrc;
     347             :             GByte *pabyDst;
     348         462 :             pabySrc = poGDS->pabyCurrentTile + iLine * nTileLineSize;
     349         462 :             pabyDst =
     350         462 :                 reinterpret_cast<GByte *>(pImage) + iLine * nBlockLineSize;
     351      112266 :             for (GUInt32 i = 0; i < nRawXSize; ++i)
     352             :             {
     353      111804 :                 if (i & 0x01)
     354       55902 :                     pabyDst[i] = (*pabySrc++ & 0xF0) >> 4;
     355             :                 else
     356       55902 :                     pabyDst[i] = *pabySrc & 0x0F;
     357             :             }
     358             :         }
     359           2 :         return CE_None;
     360             :     }
     361           1 :     else if (poGDS->eRMFType == RMFT_RSW && poGDS->nBands == 1 &&
     362           1 :              poGDS->sHeader.nBitDepth == 1)
     363             :     {
     364           1 :         if (poGDS->nCurrentTileBytes != (nBlockSize + 7) / 8)
     365             :         {
     366           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     367             :                      "Tile has %d bytes, %d were expected",
     368           0 :                      poGDS->nCurrentTileBytes, (nBlockSize + 7) / 8);
     369           0 :             return CE_Failure;
     370             :         }
     371             : 
     372           1 :         const size_t nTilePixelBits = poGDS->sHeader.nBitDepth;
     373           1 :         const size_t nTileLineSize = nTilePixelBits * nRawXSize / 8;
     374           1 :         const size_t nBlockLineSize =
     375           1 :             static_cast<size_t>(nDataSize) * nBlockXSize;
     376             : 
     377         232 :         for (GUInt32 iLine = 0; iLine != nRawYSize; ++iLine)
     378             :         {
     379             :             GByte *pabySrc;
     380             :             GByte *pabyDst;
     381         231 :             pabySrc = poGDS->pabyCurrentTile + iLine * nTileLineSize;
     382         231 :             pabyDst =
     383         231 :                 reinterpret_cast<GByte *>(pImage) + iLine * nBlockLineSize;
     384             : 
     385       57519 :             for (GUInt32 i = 0; i < nRawXSize; ++i)
     386             :             {
     387       57288 :                 switch (i & 0x7)
     388             :                 {
     389        7161 :                     case 0:
     390        7161 :                         pabyDst[i] = (*pabySrc & 0x80) >> 7;
     391        7161 :                         break;
     392        7161 :                     case 1:
     393        7161 :                         pabyDst[i] = (*pabySrc & 0x40) >> 6;
     394        7161 :                         break;
     395        7161 :                     case 2:
     396        7161 :                         pabyDst[i] = (*pabySrc & 0x20) >> 5;
     397        7161 :                         break;
     398        7161 :                     case 3:
     399        7161 :                         pabyDst[i] = (*pabySrc & 0x10) >> 4;
     400        7161 :                         break;
     401        7161 :                     case 4:
     402        7161 :                         pabyDst[i] = (*pabySrc & 0x08) >> 3;
     403        7161 :                         break;
     404        7161 :                     case 5:
     405        7161 :                         pabyDst[i] = (*pabySrc & 0x04) >> 2;
     406        7161 :                         break;
     407        7161 :                     case 6:
     408        7161 :                         pabyDst[i] = (*pabySrc & 0x02) >> 1;
     409        7161 :                         break;
     410        7161 :                     case 7:
     411        7161 :                         pabyDst[i] = *pabySrc++ & 0x01;
     412        7161 :                         break;
     413           0 :                     default:
     414           0 :                         break;
     415             :                 }
     416             :             }
     417             :         }
     418           1 :         return CE_None;
     419             :     }
     420             : 
     421           0 :     CPLError(CE_Failure, CPLE_AppDefined,
     422             :              "Invalid block data type. BitDepth %d, nBands %d",
     423           0 :              static_cast<int>(poGDS->sHeader.nBitDepth), poGDS->nBands);
     424             : 
     425           0 :     return CE_Failure;
     426             : }
     427             : 
     428             : /************************************************************************/
     429             : /*                            IWriteBlock()                             */
     430             : /************************************************************************/
     431             : 
     432         454 : CPLErr RMFRasterBand::IWriteBlock(int nBlockXOff, int nBlockYOff, void *pImage)
     433             : {
     434         454 :     CPLAssert(poDS != nullptr && nBlockXOff >= 0 && nBlockYOff >= 0 &&
     435             :               pImage != nullptr);
     436             : 
     437         454 :     RMFDataset *poGDS = cpl::down_cast<RMFDataset *>(poDS);
     438             : 
     439             :     // First drop current tile read by IReadBlock
     440         454 :     poGDS->nCurrentTileBytes = 0;
     441             : 
     442         454 :     GUInt32 nRawXSize = nBlockXSize;
     443         454 :     GUInt32 nRawYSize = nBlockYSize;
     444             : 
     445         454 :     if (nLastTileWidth &&
     446         426 :         static_cast<GUInt32>(nBlockXOff) == poGDS->nXTiles - 1)
     447         103 :         nRawXSize = nLastTileWidth;
     448             : 
     449         454 :     if (nLastTileHeight &&
     450         402 :         static_cast<GUInt32>(nBlockYOff) == poGDS->nYTiles - 1)
     451         136 :         nRawYSize = nLastTileHeight;
     452             : 
     453         454 :     const size_t nTilePixelSize =
     454         454 :         static_cast<size_t>(nDataSize) * poGDS->nBands;
     455         454 :     const size_t nTileLineSize = nTilePixelSize * nRawXSize;
     456         454 :     const size_t nTileSize = nTileLineSize * nRawYSize;
     457         454 :     const size_t nBlockLineSize = static_cast<size_t>(nDataSize) * nBlockXSize;
     458             : 
     459             : #ifdef DEBUG
     460         454 :     CPLDebug(
     461             :         "RMF",
     462             :         "IWriteBlock BlockSize [%d, %d], RawSize [%d, %d], size %d, nBand %d",
     463             :         nBlockXSize, nBlockYSize, nRawXSize, nRawYSize,
     464             :         static_cast<int>(nTileSize), nBand);
     465             : #endif  // DEBUG
     466             : 
     467         454 :     if (poGDS->nBands == 1 && nRawXSize == static_cast<GUInt32>(nBlockXSize) &&
     468          24 :         nRawYSize == static_cast<GUInt32>(nBlockYSize))
     469             :     {  // Immediate write
     470          46 :         return poGDS->WriteTile(
     471             :             nBlockXOff, nBlockYOff, reinterpret_cast<GByte *>(pImage),
     472          23 :             static_cast<size_t>(nRawXSize) * nRawYSize * nDataSize, nRawXSize,
     473          23 :             nRawYSize);
     474             :     }
     475             :     else
     476             :     {  // Try to construct full tile in memory and write later
     477         431 :         const GUInt32 nTile = nBlockYOff * poGDS->nXTiles + nBlockXOff;
     478             : 
     479             :         // Find tile
     480         431 :         auto poTile(poGDS->oUnfinishedTiles.find(nTile));
     481         431 :         if (poTile == poGDS->oUnfinishedTiles.end())
     482             :         {
     483         167 :             RMFTileData oTile;
     484         167 :             oTile.oData.resize(nTileSize);
     485             :             // If not found, but exist on disk than read it
     486         167 :             if (poGDS->paiTiles[2 * nTile + 1])
     487             :             {
     488             :                 CPLErr eRes;
     489           0 :                 bool bNullTile = false;
     490             :                 eRes =
     491           0 :                     poGDS->ReadTile(nBlockXOff, nBlockYOff, oTile.oData.data(),
     492             :                                     nTileSize, nRawXSize, nRawYSize, bNullTile);
     493           0 :                 if (eRes != CE_None)
     494             :                 {
     495           0 :                     CPLError(CE_Failure, CPLE_FileIO,
     496             :                              "Can't read block with offset [%d, %d]",
     497             :                              nBlockXOff, nBlockYOff);
     498           0 :                     return eRes;
     499             :                 }
     500             :             }
     501             :             poTile = poGDS->oUnfinishedTiles.insert(
     502         167 :                 poGDS->oUnfinishedTiles.end(), std::make_pair(nTile, oTile));
     503             :         }
     504             : 
     505         431 :         GByte *pabyTileData = poTile->second.oData.data();
     506             : 
     507             :         // Copy new data to a tile
     508         431 :         int iDstBand = (poGDS->nBands - nBand);
     509       79381 :         for (GUInt32 iLine = 0; iLine != nRawYSize; ++iLine)
     510             :         {
     511             :             const GByte *pabySrc;
     512             :             GByte *pabyDst;
     513       78950 :             pabySrc = reinterpret_cast<const GByte *>(pImage) +
     514       78950 :                       iLine * nBlockLineSize;
     515       78950 :             pabyDst =
     516       78950 :                 pabyTileData + iLine * nTileLineSize + iDstBand * nDataSize;
     517       78950 :             GDALCopyWords(pabySrc, eDataType, static_cast<int>(nDataSize),
     518             :                           pabyDst, eDataType, static_cast<int>(nTilePixelSize),
     519             :                           nRawXSize);
     520             :         }
     521         431 :         ++poTile->second.nBandsWritten;
     522             : 
     523             :         // Write to disk if tile is finished
     524         431 :         if (poTile->second.nBandsWritten == poGDS->nBands)
     525             :         {
     526         167 :             poGDS->WriteTile(nBlockXOff, nBlockYOff, pabyTileData, nTileSize,
     527             :                              nRawXSize, nRawYSize);
     528         167 :             poGDS->oUnfinishedTiles.erase(poTile);
     529             :         }
     530             : #ifdef DEBUG
     531         431 :         CPLDebug("RMF", "poGDS->oUnfinishedTiles.size() %d",
     532         431 :                  static_cast<int>(poGDS->oUnfinishedTiles.size()));
     533             : #endif  // DEBUG
     534             :     }
     535             : 
     536         431 :     return CE_None;
     537             : }
     538             : 
     539             : /************************************************************************/
     540             : /*                           GetNoDataValue()                           */
     541             : /************************************************************************/
     542             : 
     543         269 : double RMFRasterBand::GetNoDataValue(int *pbSuccess)
     544             : 
     545             : {
     546         269 :     RMFDataset *poGDS = cpl::down_cast<RMFDataset *>(poDS);
     547             : 
     548         269 :     if (pbSuccess)
     549         242 :         *pbSuccess = TRUE;
     550             : 
     551         269 :     return poGDS->sHeader.dfNoData;
     552             : }
     553             : 
     554          27 : CPLErr RMFRasterBand::SetNoDataValue(double dfNoData)
     555             : {
     556          27 :     RMFDataset *poGDS = cpl::down_cast<RMFDataset *>(poDS);
     557             : 
     558          27 :     poGDS->sHeader.dfNoData = dfNoData;
     559          27 :     poGDS->bHeaderDirty = true;
     560             : 
     561          27 :     return CE_None;
     562             : }
     563             : 
     564             : /************************************************************************/
     565             : /*                            GetUnitType()                             */
     566             : /************************************************************************/
     567             : 
     568          10 : const char *RMFRasterBand::GetUnitType()
     569             : 
     570             : {
     571          10 :     RMFDataset *poGDS = cpl::down_cast<RMFDataset *>(poDS);
     572             : 
     573          10 :     return poGDS->pszUnitType;
     574             : }
     575             : 
     576             : /************************************************************************/
     577             : /*                            SetUnitType()                             */
     578             : /************************************************************************/
     579             : 
     580           3 : CPLErr RMFRasterBand::SetUnitType(const char *pszNewValue)
     581             : 
     582             : {
     583           3 :     RMFDataset *poGDS = cpl::down_cast<RMFDataset *>(poDS);
     584           3 :     int bSuccess = FALSE;
     585           3 :     int iNewUnit = RMFStrToUnitType(pszNewValue, &bSuccess);
     586             : 
     587           3 :     if (bSuccess)
     588             :     {
     589           2 :         CPLFree(poGDS->pszUnitType);
     590           2 :         poGDS->pszUnitType = CPLStrdup(pszNewValue);
     591           2 :         poGDS->sHeader.iElevationUnit = iNewUnit;
     592           2 :         poGDS->bHeaderDirty = true;
     593           2 :         return CE_None;
     594             :     }
     595             :     else
     596             :     {
     597           1 :         CPLError(CE_Warning, CPLE_NotSupported,
     598             :                  "RMF driver does not support '%s' elevation units. "
     599             :                  "Possible values are: m, dm, cm, mm.",
     600             :                  pszNewValue);
     601           1 :         return CE_Failure;
     602             :     }
     603             : }
     604             : 
     605             : /************************************************************************/
     606             : /*                           GetColorTable()                            */
     607             : /************************************************************************/
     608             : 
     609          28 : GDALColorTable *RMFRasterBand::GetColorTable()
     610             : {
     611          28 :     RMFDataset *poGDS = cpl::down_cast<RMFDataset *>(poDS);
     612             : 
     613          28 :     return poGDS->poColorTable;
     614             : }
     615             : 
     616             : /************************************************************************/
     617             : /*                           SetColorTable()                            */
     618             : /************************************************************************/
     619             : 
     620           8 : CPLErr RMFRasterBand::SetColorTable(GDALColorTable *poColorTable)
     621             : {
     622           8 :     RMFDataset *poGDS = cpl::down_cast<RMFDataset *>(poDS);
     623             : 
     624           8 :     if (poColorTable)
     625             :     {
     626           8 :         if (poGDS->eRMFType == RMFT_RSW && poGDS->nBands == 1)
     627             :         {
     628           8 :             if (!poGDS->pabyColorTable)
     629           0 :                 return CE_Failure;
     630             : 
     631             :             GDALColorEntry oEntry;
     632        2056 :             for (GUInt32 i = 0; i < poGDS->nColorTableSize; i++)
     633             :             {
     634        2048 :                 poColorTable->GetColorEntryAsRGB(i, &oEntry);
     635             :                 // Red
     636        2048 :                 poGDS->pabyColorTable[i * 4 + 0] =
     637        2048 :                     static_cast<GByte>(oEntry.c1);
     638             :                 // Green
     639        2048 :                 poGDS->pabyColorTable[i * 4 + 1] =
     640        2048 :                     static_cast<GByte>(oEntry.c2);
     641             :                 // Blue
     642        2048 :                 poGDS->pabyColorTable[i * 4 + 2] =
     643        2048 :                     static_cast<GByte>(oEntry.c3);
     644        2048 :                 poGDS->pabyColorTable[i * 4 + 3] = 0;
     645             :             }
     646             : 
     647           8 :             poGDS->bHeaderDirty = true;
     648             :         }
     649           8 :         return CE_None;
     650             :     }
     651             : 
     652           0 :     return CE_Failure;
     653             : }
     654             : 
     655          59 : int RMFRasterBand::GetOverviewCount()
     656             : {
     657          59 :     RMFDataset *poGDS = cpl::down_cast<RMFDataset *>(poDS);
     658          59 :     if (poGDS->poOvrDatasets.empty())
     659           0 :         return GDALRasterBand::GetOverviewCount();
     660             :     else
     661          59 :         return static_cast<int>(poGDS->poOvrDatasets.size());
     662             : }
     663             : 
     664          79 : GDALRasterBand *RMFRasterBand::GetOverview(int i)
     665             : {
     666          79 :     RMFDataset *poGDS = cpl::down_cast<RMFDataset *>(poDS);
     667          79 :     size_t n = static_cast<size_t>(i);
     668          79 :     if (poGDS->poOvrDatasets.empty())
     669           0 :         return GDALRasterBand::GetOverview(i);
     670             :     else
     671          79 :         return poGDS->poOvrDatasets[n]->GetRasterBand(nBand);
     672             : }
     673             : 
     674         694 : CPLErr RMFRasterBand::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
     675             :                                 int nXSize, int nYSize, void *pData,
     676             :                                 int nBufXSize, int nBufYSize,
     677             :                                 GDALDataType eType, GSpacing nPixelSpace,
     678             :                                 GSpacing nLineSpace,
     679             :                                 GDALRasterIOExtraArg *psExtraArg)
     680             : {
     681         694 :     RMFDataset *poGDS = cpl::down_cast<RMFDataset *>(poDS);
     682             : 
     683         743 :     if (eRWFlag == GF_Read && poGDS->poCompressData != nullptr &&
     684          49 :         poGDS->poCompressData->oThreadPool.GetThreadCount() > 0)
     685             :     {
     686           9 :         poGDS->poCompressData->oThreadPool.WaitCompletion();
     687             :     }
     688             : 
     689         694 :     return GDALRasterBand::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
     690             :                                      pData, nBufXSize, nBufYSize, eType,
     691         694 :                                      nPixelSpace, nLineSpace, psExtraArg);
     692             : }
     693             : 
     694             : /************************************************************************/
     695             : /*                       GetColorInterpretation()                       */
     696             : /************************************************************************/
     697             : 
     698         104 : GDALColorInterp RMFRasterBand::GetColorInterpretation()
     699             : {
     700         104 :     RMFDataset *poGDS = cpl::down_cast<RMFDataset *>(poDS);
     701             : 
     702         104 :     if (poGDS->nBands == 3)
     703             :     {
     704          53 :         if (nBand == 1)
     705          18 :             return GCI_RedBand;
     706          35 :         else if (nBand == 2)
     707          17 :             return GCI_GreenBand;
     708          18 :         else if (nBand == 3)
     709          18 :             return GCI_BlueBand;
     710             : 
     711           0 :         return GCI_Undefined;
     712             :     }
     713             : 
     714          51 :     if (poGDS->eRMFType == RMFT_RSW)
     715          28 :         return GCI_PaletteIndex;
     716             : 
     717          23 :     return GCI_Undefined;
     718             : }
     719             : 
     720             : /************************************************************************/
     721             : /* ==================================================================== */
     722             : /*                              RMFDataset                              */
     723             : /* ==================================================================== */
     724             : /************************************************************************/
     725             : 
     726             : /************************************************************************/
     727             : /*                             RMFDataset()                             */
     728             : /************************************************************************/
     729             : 
     730         297 : RMFDataset::RMFDataset() : pszUnitType(CPLStrdup(RMF_UnitsEmpty))
     731             : {
     732         297 :     m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     733         297 :     nBands = 0;
     734         297 :     memset(&sHeader, 0, sizeof(sHeader));
     735         297 :     memset(&sExtHeader, 0, sizeof(sExtHeader));
     736         297 : }
     737             : 
     738             : /************************************************************************/
     739             : /*                            ~RMFDataset()                             */
     740             : /************************************************************************/
     741             : 
     742         594 : RMFDataset::~RMFDataset()
     743             : {
     744         297 :     RMFDataset::FlushCache(true);
     745         404 :     for (size_t n = 0; n != poOvrDatasets.size(); ++n)
     746             :     {
     747         107 :         poOvrDatasets[n]->RMFDataset::FlushCache(true);
     748             :     }
     749             : 
     750         297 :     VSIFree(paiTiles);
     751         297 :     VSIFree(pabyDecompressBuffer);
     752         297 :     VSIFree(pabyCurrentTile);
     753         297 :     CPLFree(pszUnitType);
     754         297 :     CPLFree(pabyColorTable);
     755         297 :     if (poColorTable != nullptr)
     756          68 :         delete poColorTable;
     757             : 
     758         404 :     for (size_t n = 0; n != poOvrDatasets.size(); ++n)
     759             :     {
     760         107 :         GDALClose(poOvrDatasets[n]);
     761             :     }
     762             : 
     763         297 :     if (fp != nullptr && poParentDS == nullptr)
     764             :     {
     765         177 :         VSIFCloseL(fp);
     766             :     }
     767         594 : }
     768             : 
     769             : /************************************************************************/
     770             : /*                          GetGeoTransform()                           */
     771             : /************************************************************************/
     772             : 
     773          47 : CPLErr RMFDataset::GetGeoTransform(GDALGeoTransform &gt) const
     774             : {
     775          47 :     gt = m_gt;
     776             : 
     777          47 :     if (sHeader.iGeorefFlag)
     778          41 :         return CE_None;
     779             : 
     780           6 :     return CE_Failure;
     781             : }
     782             : 
     783             : /************************************************************************/
     784             : /*                          SetGeoTransform()                           */
     785             : /************************************************************************/
     786             : 
     787          41 : CPLErr RMFDataset::SetGeoTransform(const GDALGeoTransform &gt)
     788             : {
     789          41 :     m_gt = gt;
     790          41 :     sHeader.dfPixelSize = m_gt.xscale;
     791          41 :     if (sHeader.dfPixelSize != 0.0)
     792          41 :         sHeader.dfResolution = sHeader.dfScale / sHeader.dfPixelSize;
     793          41 :     sHeader.dfLLX = m_gt.xorig;
     794          41 :     sHeader.dfLLY = m_gt.yorig - nRasterYSize * sHeader.dfPixelSize;
     795          41 :     sHeader.iGeorefFlag = 1;
     796             : 
     797          41 :     bHeaderDirty = true;
     798             : 
     799          41 :     return CE_None;
     800             : }
     801             : 
     802             : /************************************************************************/
     803             : /*                           GetSpatialRef()                            */
     804             : /************************************************************************/
     805             : 
     806          34 : const OGRSpatialReference *RMFDataset::GetSpatialRef() const
     807             : 
     808             : {
     809          34 :     return m_oSRS.IsEmpty() ? nullptr : &m_oSRS;
     810             : }
     811             : 
     812             : /************************************************************************/
     813             : /*                           SetSpatialRef()                            */
     814             : /************************************************************************/
     815             : 
     816          41 : CPLErr RMFDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
     817             : 
     818             : {
     819          41 :     m_oSRS.Clear();
     820          41 :     if (poSRS)
     821          41 :         m_oSRS = *poSRS;
     822             : 
     823          41 :     bHeaderDirty = true;
     824             : 
     825          41 :     return CE_None;
     826             : }
     827             : 
     828             : /************************************************************************/
     829             : /*                            WriteHeader()                             */
     830             : /************************************************************************/
     831             : 
     832         200 : CPLErr RMFDataset::WriteHeader()
     833             : {
     834             :     /* -------------------------------------------------------------------- */
     835             :     /*  Setup projection.                                                   */
     836             :     /* -------------------------------------------------------------------- */
     837         200 :     if (!m_oSRS.IsEmpty())
     838             :     {
     839          52 :         long iProjection = 0;
     840          52 :         long iDatum = 0;
     841          52 :         long iEllips = 0;
     842          52 :         long iZone = 0;
     843          52 :         int iVertCS = 0;
     844          52 :         double adfPrjParams[7] = {};
     845             : 
     846          52 :         m_oSRS.exportToPanorama(&iProjection, &iDatum, &iEllips, &iZone,
     847             :                                 adfPrjParams);
     848          52 :         m_oSRS.exportVertCSToPanorama(&iVertCS);
     849          52 :         sHeader.iProjection = static_cast<GInt32>(iProjection);
     850          52 :         sHeader.dfStdP1 = adfPrjParams[0];
     851          52 :         sHeader.dfStdP2 = adfPrjParams[1];
     852          52 :         sHeader.dfCenterLat = adfPrjParams[2];
     853          52 :         sHeader.dfCenterLong = adfPrjParams[3];
     854          52 :         if (m_oSRS.GetAuthorityName() != nullptr &&
     855          62 :             m_oSRS.GetAuthorityCode() != nullptr &&
     856          10 :             EQUAL(m_oSRS.GetAuthorityName(), "EPSG"))
     857             :         {
     858          10 :             sHeader.iEPSGCode = atoi(m_oSRS.GetAuthorityCode());
     859             :         }
     860             : 
     861          52 :         sExtHeader.nEllipsoid = static_cast<GInt32>(iEllips);
     862          52 :         sExtHeader.nDatum = static_cast<GInt32>(iDatum);
     863          52 :         sExtHeader.nZone = static_cast<GInt32>(iZone);
     864          52 :         sExtHeader.nVertDatum = static_cast<GInt32>(iVertCS);
     865             : 
     866             :         // Set map type
     867          52 :         auto pszMapType = GetMetadataItem(MD_MATH_BASE_MAP_TYPE_KEY);
     868          52 :         if (pszMapType != nullptr)
     869             :         {
     870          31 :             sHeader.iMapType = static_cast<GInt32>(atoi(pszMapType));
     871             :         }
     872             :     }
     873             : 
     874             : #define RMF_WRITE_LONG(ptr, value, offset)                                     \
     875             :     do                                                                         \
     876             :     {                                                                          \
     877             :         GInt32 iLong = CPL_LSBWORD32(value);                                   \
     878             :         memcpy((ptr) + (offset), &iLong, 4);                                   \
     879             :     } while (false);
     880             : 
     881             : #define RMF_WRITE_ULONG(ptr, value, offset)                                    \
     882             :     do                                                                         \
     883             :     {                                                                          \
     884             :         GUInt32 iULong = CPL_LSBWORD32(value);                                 \
     885             :         memcpy((ptr) + (offset), &iULong, 4);                                  \
     886             :     } while (false);
     887             : 
     888             : #define RMF_WRITE_DOUBLE(ptr, value, offset)                                   \
     889             :     do                                                                         \
     890             :     {                                                                          \
     891             :         double dfDouble = (value);                                             \
     892             :         CPL_LSBPTR64(&dfDouble);                                               \
     893             :         memcpy((ptr) + (offset), &dfDouble, 8);                                \
     894             :     } while (false);
     895             : 
     896             :     // Frame if present
     897         400 :     std::vector<RSWFrameCoord> astFrameCoords;
     898         200 :     auto pszFrameWKT = GetMetadataItem(MD_FRAME_KEY);
     899         200 :     if (pszFrameWKT != nullptr)
     900             :     {
     901           2 :         CPLDebug("RMF", "Write to header frame: %s", pszFrameWKT);
     902           2 :         OGRGeometry *poFrameGeom = nullptr;
     903           2 :         if (OGRGeometryFactory::createFromWkt(pszFrameWKT, nullptr,
     904           2 :                                               &poFrameGeom) == OGRERR_NONE)
     905             :         {
     906           2 :             if (poFrameGeom->getGeometryType() == wkbPolygon)
     907             :             {
     908           2 :                 GDALGeoTransform reverseGT;
     909           2 :                 if (m_gt.GetInverse(reverseGT))
     910             :                 {
     911           2 :                     OGRPolygon *poFramePoly = poFrameGeom->toPolygon();
     912           2 :                     if (!poFramePoly->IsEmpty())
     913             :                     {
     914             :                         OGRLinearRing *poFrameRing =
     915           2 :                             poFramePoly->getExteriorRing();
     916          12 :                         for (int i = 0; i < poFrameRing->getNumPoints(); i++)
     917             :                         {
     918             :                             int nX =
     919          10 :                                 int(reverseGT[0] +
     920          10 :                                     poFrameRing->getX(i) * reverseGT[1] - 0.5);
     921             :                             int nY =
     922          10 :                                 int(reverseGT[3] +
     923          10 :                                     poFrameRing->getY(i) * reverseGT[5] - 0.5);
     924             : 
     925          10 :                             CPLDebug("RMF", "X: %d, Y: %d", nX, nY);
     926             : 
     927          10 :                             astFrameCoords.push_back({nX, nY});
     928             :                         }
     929             :                     }
     930             : 
     931           4 :                     if (astFrameCoords.empty() ||
     932           2 :                         astFrameCoords.size() > nMaxFramePointCount)
     933             :                     {
     934             :                         // CPLError(CE_Warning, CPLE_AppDefined, "Invalid frame WKT: %s", pszFrameWKT);
     935           0 :                         CPLDebug("RMF", "Write to header frame failed: no "
     936             :                                         "points or too many");
     937           0 :                         astFrameCoords.clear();
     938             :                     }
     939             :                     else
     940             :                     {
     941           2 :                         sHeader.nROISize = static_cast<GUInt32>(
     942           2 :                             sizeof(RSWFrame) +
     943             :                             sizeof(RSWFrameCoord) *
     944             :                                 astFrameCoords
     945           2 :                                     .size());  // Set real size and real point count
     946           2 :                         sHeader.iFrameFlag = 0;
     947             :                     }
     948             :                 }
     949             :                 else
     950             :                 {
     951           0 :                     CPLDebug("RMF", "Write to header frame failed: "
     952             :                                     "GDALInvGeoTransform == FALSE");
     953             :                 }
     954             :             }
     955           2 :             OGRGeometryFactory::destroyGeometry(poFrameGeom);
     956             :         }
     957             :         else
     958             :         {
     959           0 :             CPLDebug("RMF", "Write to header frame failed: "
     960             :                             "OGRGeometryFactory::createFromWkt error");
     961             :         }
     962             :     }
     963             : 
     964         200 :     vsi_l_offset iCurrentFileSize(GetLastOffset());
     965         200 :     sHeader.nFileSize0 = GetRMFOffset(iCurrentFileSize, &iCurrentFileSize);
     966         200 :     sHeader.nSize = sHeader.nFileSize0 - GetRMFOffset(nHeaderOffset, nullptr);
     967             :     /* -------------------------------------------------------------------- */
     968             :     /*  Write out the main header.                                          */
     969             :     /* -------------------------------------------------------------------- */
     970             :     {
     971         200 :         GByte abyHeader[RMF_HEADER_SIZE] = {};
     972             : 
     973         200 :         memcpy(abyHeader, sHeader.bySignature, RMF_SIGNATURE_SIZE);
     974         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.iVersion, 4);
     975         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nSize, 8);
     976         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nOvrOffset, 12);
     977         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.iUserID, 16);
     978         200 :         memcpy(abyHeader + 20, sHeader.byName, RMF_NAME_SIZE);
     979         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nBitDepth, 52);
     980         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nHeight, 56);
     981         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nWidth, 60);
     982         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nXTiles, 64);
     983         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nYTiles, 68);
     984         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nTileHeight, 72);
     985         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nTileWidth, 76);
     986         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nLastTileHeight, 80);
     987         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nLastTileWidth, 84);
     988         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nROIOffset, 88);
     989         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nROISize, 92);
     990         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nClrTblOffset, 96);
     991         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nClrTblSize, 100);
     992         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nTileTblOffset, 104);
     993         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nTileTblSize, 108);
     994         200 :         RMF_WRITE_LONG(abyHeader, sHeader.iMapType, 124);
     995         200 :         RMF_WRITE_LONG(abyHeader, sHeader.iProjection, 128);
     996         200 :         RMF_WRITE_LONG(abyHeader, sHeader.iEPSGCode, 132);
     997         200 :         RMF_WRITE_DOUBLE(abyHeader, sHeader.dfScale, 136);
     998         200 :         RMF_WRITE_DOUBLE(abyHeader, sHeader.dfResolution, 144);
     999         200 :         RMF_WRITE_DOUBLE(abyHeader, sHeader.dfPixelSize, 152);
    1000         200 :         RMF_WRITE_DOUBLE(abyHeader, sHeader.dfLLY, 160);
    1001         200 :         RMF_WRITE_DOUBLE(abyHeader, sHeader.dfLLX, 168);
    1002         200 :         RMF_WRITE_DOUBLE(abyHeader, sHeader.dfStdP1, 176);
    1003         200 :         RMF_WRITE_DOUBLE(abyHeader, sHeader.dfStdP2, 184);
    1004         200 :         RMF_WRITE_DOUBLE(abyHeader, sHeader.dfCenterLong, 192);
    1005         200 :         RMF_WRITE_DOUBLE(abyHeader, sHeader.dfCenterLat, 200);
    1006         200 :         *(abyHeader + 208) = sHeader.iCompression;
    1007         200 :         *(abyHeader + 209) = sHeader.iMaskType;
    1008         200 :         *(abyHeader + 210) = sHeader.iMaskStep;
    1009         200 :         *(abyHeader + 211) = sHeader.iFrameFlag;
    1010         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nFlagsTblOffset, 212);
    1011         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nFlagsTblSize, 216);
    1012         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nFileSize0, 220);
    1013         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nFileSize1, 224);
    1014         200 :         *(abyHeader + 228) = sHeader.iUnknown;
    1015         200 :         *(abyHeader + 244) = sHeader.iGeorefFlag;
    1016         200 :         *(abyHeader + 245) = sHeader.iInverse;
    1017         200 :         *(abyHeader + 246) = sHeader.iJpegQuality;
    1018         200 :         memcpy(abyHeader + 248, sHeader.abyInvisibleColors,
    1019             :                sizeof(sHeader.abyInvisibleColors));
    1020         200 :         RMF_WRITE_DOUBLE(abyHeader, sHeader.adfElevMinMax[0], 280);
    1021         200 :         RMF_WRITE_DOUBLE(abyHeader, sHeader.adfElevMinMax[1], 288);
    1022         200 :         RMF_WRITE_DOUBLE(abyHeader, sHeader.dfNoData, 296);
    1023         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.iElevationUnit, 304);
    1024         200 :         *(abyHeader + 308) = sHeader.iElevationType;
    1025         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nExtHdrOffset, 312);
    1026         200 :         RMF_WRITE_ULONG(abyHeader, sHeader.nExtHdrSize, 316);
    1027             : 
    1028         200 :         VSIFSeekL(fp, nHeaderOffset, SEEK_SET);
    1029         200 :         VSIFWriteL(abyHeader, 1, sizeof(abyHeader), fp);
    1030             :     }
    1031             : 
    1032             :     /* -------------------------------------------------------------------- */
    1033             :     /*  Write out the extended header.                                      */
    1034             :     /* -------------------------------------------------------------------- */
    1035             : 
    1036         200 :     if (sHeader.nExtHdrOffset && sHeader.nExtHdrSize >= RMF_MIN_EXT_HEADER_SIZE)
    1037             :     {
    1038         200 :         if (sHeader.nExtHdrSize > RMF_MAX_EXT_HEADER_SIZE)
    1039             :         {
    1040           0 :             CPLError(CE_Failure, CPLE_FileIO, "RMF File malformed");
    1041           0 :             return CE_Failure;
    1042             :         }
    1043             :         GByte *pabyExtHeader =
    1044         200 :             static_cast<GByte *>(CPLCalloc(sHeader.nExtHdrSize, 1));
    1045             : 
    1046         200 :         RMF_WRITE_LONG(pabyExtHeader, sExtHeader.nEllipsoid, 24);
    1047         200 :         RMF_WRITE_LONG(pabyExtHeader, sExtHeader.nVertDatum, 28);
    1048         200 :         RMF_WRITE_LONG(pabyExtHeader, sExtHeader.nDatum, 32);
    1049         200 :         RMF_WRITE_LONG(pabyExtHeader, sExtHeader.nZone, 36);
    1050             : 
    1051         200 :         VSIFSeekL(fp, GetFileOffset(sHeader.nExtHdrOffset), SEEK_SET);
    1052         200 :         VSIFWriteL(pabyExtHeader, 1, sHeader.nExtHdrSize, fp);
    1053             : 
    1054         200 :         CPLFree(pabyExtHeader);
    1055             :     }
    1056             : 
    1057             :     /* -------------------------------------------------------------------- */
    1058             :     /*  Write out the color table.                                          */
    1059             :     /* -------------------------------------------------------------------- */
    1060             : 
    1061         200 :     if (sHeader.nClrTblOffset && sHeader.nClrTblSize)
    1062             :     {
    1063          59 :         VSIFSeekL(fp, GetFileOffset(sHeader.nClrTblOffset), SEEK_SET);
    1064          59 :         VSIFWriteL(pabyColorTable, 1, sHeader.nClrTblSize, fp);
    1065             :     }
    1066             : 
    1067         200 :     if (sHeader.nROIOffset && sHeader.nROISize)
    1068             :     {
    1069           2 :         GByte *pabyROI = static_cast<GByte *>(CPLCalloc(sHeader.nROISize, 1));
    1070           2 :         memset(pabyROI, 0, sHeader.nROISize);
    1071             : 
    1072           2 :         auto nPointCount = astFrameCoords.size();
    1073           2 :         size_t offset = 0;
    1074           2 :         RMF_WRITE_LONG(pabyROI, nPolygonType, offset);
    1075           2 :         offset += 4;
    1076           2 :         RMF_WRITE_LONG(pabyROI, static_cast<GInt32>((4 + nPointCount * 2) * 4),
    1077             :                        offset);
    1078           2 :         offset += 4;
    1079           2 :         RMF_WRITE_LONG(pabyROI, 0, offset);
    1080           2 :         offset += 4;
    1081           2 :         RMF_WRITE_LONG(pabyROI, static_cast<GInt32>(32768 * nPointCount * 2),
    1082             :                        offset);
    1083           2 :         offset += 4;
    1084             : 
    1085             :         // Write points
    1086          12 :         for (size_t i = 0; i < nPointCount; i++)
    1087             :         {
    1088          10 :             RMF_WRITE_LONG(pabyROI, astFrameCoords[i].nX, offset);
    1089          10 :             offset += 4;
    1090          10 :             RMF_WRITE_LONG(pabyROI, astFrameCoords[i].nY, offset);
    1091          10 :             offset += 4;
    1092             :         }
    1093             : 
    1094           2 :         VSIFSeekL(fp, GetFileOffset(sHeader.nROIOffset), SEEK_SET);
    1095           2 :         VSIFWriteL(pabyROI, 1, sHeader.nROISize, fp);
    1096             : 
    1097           2 :         CPLFree(pabyROI);
    1098             :     }
    1099             : 
    1100         200 :     if (sHeader.nFlagsTblOffset && sHeader.nFlagsTblSize)
    1101             :     {
    1102             :         GByte *pabyFlagsTbl =
    1103         200 :             static_cast<GByte *>(CPLCalloc(sHeader.nFlagsTblSize, 1));
    1104             : 
    1105         200 :         if (sHeader.iFrameFlag == 0)
    1106             :         {
    1107             :             // TODO: Add more strictly check for flag value
    1108           2 :             memset(
    1109             :                 pabyFlagsTbl, 2,
    1110             :                 sHeader
    1111           2 :                     .nFlagsTblSize);  // Mark all blocks as intersected with ROI. 0 - complete outside, 1 - complete inside.
    1112             :         }
    1113             :         else
    1114             :         {
    1115         198 :             memset(pabyFlagsTbl, 0, sHeader.nFlagsTblSize);
    1116             :         }
    1117             : 
    1118         200 :         VSIFSeekL(fp, GetFileOffset(sHeader.nFlagsTblOffset), SEEK_SET);
    1119         200 :         VSIFWriteL(pabyFlagsTbl, 1, sHeader.nFlagsTblSize, fp);
    1120             : 
    1121         200 :         CPLFree(pabyFlagsTbl);
    1122             :     }
    1123             : 
    1124             : #undef RMF_WRITE_DOUBLE
    1125             : #undef RMF_WRITE_ULONG
    1126             : #undef RMF_WRITE_LONG
    1127             : 
    1128             :     /* -------------------------------------------------------------------- */
    1129             :     /*  Write out the block table, swap if needed.                          */
    1130             :     /* -------------------------------------------------------------------- */
    1131             : 
    1132         200 :     VSIFSeekL(fp, GetFileOffset(sHeader.nTileTblOffset), SEEK_SET);
    1133             : 
    1134             : #ifdef CPL_MSB
    1135             :     GUInt32 *paiTilesSwapped =
    1136             :         static_cast<GUInt32 *>(CPLMalloc(sHeader.nTileTblSize));
    1137             :     if (!paiTilesSwapped)
    1138             :         return CE_Failure;
    1139             : 
    1140             :     memcpy(paiTilesSwapped, paiTiles, sHeader.nTileTblSize);
    1141             :     for (GUInt32 i = 0; i < sHeader.nTileTblSize / sizeof(GUInt32); i++)
    1142             :         CPL_SWAP32PTR(paiTilesSwapped + i);
    1143             :     VSIFWriteL(paiTilesSwapped, 1, sHeader.nTileTblSize, fp);
    1144             : 
    1145             :     CPLFree(paiTilesSwapped);
    1146             : #else
    1147         200 :     VSIFWriteL(paiTiles, 1, sHeader.nTileTblSize, fp);
    1148             : #endif
    1149             : 
    1150         200 :     bHeaderDirty = false;
    1151             : 
    1152         200 :     return CE_None;
    1153             : }
    1154             : 
    1155             : /************************************************************************/
    1156             : /*                             FlushCache()                             */
    1157             : /************************************************************************/
    1158             : 
    1159         411 : CPLErr RMFDataset::FlushCache(bool bAtClosing)
    1160             : 
    1161             : {
    1162         411 :     CPLErr eErr = GDALDataset::FlushCache(bAtClosing);
    1163             : 
    1164         549 :     if (poCompressData != nullptr &&
    1165         138 :         poCompressData->oThreadPool.GetThreadCount() > 0)
    1166             :     {
    1167           9 :         poCompressData->oThreadPool.WaitCompletion();
    1168             :     }
    1169             : 
    1170         411 :     if (bAtClosing && eRMFType == RMFT_MTW && eAccess == GA_Update)
    1171             :     {
    1172          77 :         GDALRasterBand *poBand = GetRasterBand(1);
    1173             : 
    1174          77 :         if (poBand)
    1175             :         {
    1176             :             // ComputeRasterMinMax can setup error in case of dataset full
    1177             :             // from NoData values, but it  makes no sense here.
    1178          77 :             CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
    1179          77 :             poBand->ComputeRasterMinMax(FALSE, sHeader.adfElevMinMax);
    1180          77 :             bHeaderDirty = true;
    1181             :         }
    1182             :     }
    1183         411 :     if (bHeaderDirty && WriteHeader() != CE_None)
    1184           0 :         eErr = CE_Failure;
    1185         411 :     return eErr;
    1186             : }
    1187             : 
    1188             : /************************************************************************/
    1189             : /*                              Identify()                              */
    1190             : /************************************************************************/
    1191             : 
    1192       65041 : int RMFDataset::Identify(GDALOpenInfo *poOpenInfo)
    1193             : 
    1194             : {
    1195       65041 :     if (poOpenInfo->pabyHeader == nullptr)
    1196       58288 :         return FALSE;
    1197             : 
    1198        6753 :     if (memcmp(poOpenInfo->pabyHeader, RMF_SigRSW, sizeof(RMF_SigRSW)) != 0 &&
    1199        6544 :         memcmp(poOpenInfo->pabyHeader, RMF_SigRSW_BE, sizeof(RMF_SigRSW_BE)) !=
    1200        6532 :             0 &&
    1201        6532 :         memcmp(poOpenInfo->pabyHeader, RMF_SigMTW, sizeof(RMF_SigMTW)) != 0)
    1202        6414 :         return FALSE;
    1203             : 
    1204         339 :     return TRUE;
    1205             : }
    1206             : 
    1207             : /************************************************************************/
    1208             : /*                                Open()                                */
    1209             : /************************************************************************/
    1210             : 
    1211         128 : GDALDataset *RMFDataset::Open(GDALOpenInfo *poOpenInfo)
    1212             : {
    1213         128 :     auto poDS = Open(poOpenInfo, nullptr, 0);
    1214         128 :     if (poDS == nullptr)
    1215             :     {
    1216           9 :         return nullptr;
    1217             :     }
    1218             : 
    1219         119 :     RMFDataset *poCurrentLayer = poDS;
    1220         119 :     RMFDataset *poParent = poCurrentLayer;
    1221         119 :     const int nMaxPossibleOvCount = 64;
    1222             : 
    1223         200 :     for (int iOv = 0; iOv < nMaxPossibleOvCount && poCurrentLayer != nullptr;
    1224             :          ++iOv)
    1225             :     {
    1226         200 :         poCurrentLayer = poCurrentLayer->OpenOverview(poParent, poOpenInfo);
    1227         200 :         if (poCurrentLayer == nullptr)
    1228         119 :             break;
    1229          81 :         poParent->poOvrDatasets.push_back(poCurrentLayer);
    1230             :     }
    1231             : 
    1232         119 :     return poDS;
    1233             : }
    1234             : 
    1235         213 : RMFDataset *RMFDataset::Open(GDALOpenInfo *poOpenInfo, RMFDataset *poParentDS,
    1236             :                              vsi_l_offset nNextHeaderOffset)
    1237             : {
    1238         341 :     if (!Identify(poOpenInfo) ||
    1239         128 :         (poParentDS == nullptr && poOpenInfo->fpL == nullptr))
    1240           2 :         return nullptr;
    1241             : 
    1242             :     /* -------------------------------------------------------------------- */
    1243             :     /*  Create a corresponding GDALDataset.                                 */
    1244             :     /* -------------------------------------------------------------------- */
    1245         211 :     RMFDataset *poDS = new RMFDataset();
    1246             : 
    1247         211 :     if (poParentDS == nullptr)
    1248             :     {
    1249         128 :         poDS->fp = poOpenInfo->fpL;
    1250         128 :         poOpenInfo->fpL = nullptr;
    1251         128 :         poDS->nHeaderOffset = 0;
    1252         128 :         poDS->poParentDS = nullptr;
    1253             :     }
    1254             :     else
    1255             :     {
    1256          83 :         poDS->fp = poParentDS->fp;
    1257          83 :         poDS->poParentDS = poParentDS;
    1258          83 :         poDS->nHeaderOffset = nNextHeaderOffset;
    1259             :     }
    1260         211 :     poDS->eAccess = poOpenInfo->eAccess;
    1261             : 
    1262             : #define RMF_READ_SHORT(ptr, value, offset)                                     \
    1263             :     do                                                                         \
    1264             :     {                                                                          \
    1265             :         memcpy(&(value), reinterpret_cast<GInt16 *>((ptr) + (offset)),         \
    1266             :                sizeof(GInt16));                                                \
    1267             :         if (poDS->bBigEndian)                                                  \
    1268             :         {                                                                      \
    1269             :             CPL_MSBPTR16(&(value));                                            \
    1270             :         }                                                                      \
    1271             :         else                                                                   \
    1272             :         {                                                                      \
    1273             :             CPL_LSBPTR16(&(value));                                            \
    1274             :         }                                                                      \
    1275             :     } while (false);
    1276             : 
    1277             : #define RMF_READ_ULONG(ptr, value, offset)                                     \
    1278             :     do                                                                         \
    1279             :     {                                                                          \
    1280             :         memcpy(&(value), reinterpret_cast<GUInt32 *>((ptr) + (offset)),        \
    1281             :                sizeof(GUInt32));                                               \
    1282             :         if (poDS->bBigEndian)                                                  \
    1283             :         {                                                                      \
    1284             :             CPL_MSBPTR32(&(value));                                            \
    1285             :         }                                                                      \
    1286             :         else                                                                   \
    1287             :         {                                                                      \
    1288             :             CPL_LSBPTR32(&(value));                                            \
    1289             :         }                                                                      \
    1290             :     } while (false);
    1291             : 
    1292             : #define RMF_READ_LONG(ptr, value, offset) RMF_READ_ULONG(ptr, value, offset)
    1293             : 
    1294             : #define RMF_READ_DOUBLE(ptr, value, offset)                                    \
    1295             :     do                                                                         \
    1296             :     {                                                                          \
    1297             :         memcpy(&(value), reinterpret_cast<double *>((ptr) + (offset)),         \
    1298             :                sizeof(double));                                                \
    1299             :         if (poDS->bBigEndian)                                                  \
    1300             :         {                                                                      \
    1301             :             CPL_MSBPTR64(&(value));                                            \
    1302             :         }                                                                      \
    1303             :         else                                                                   \
    1304             :         {                                                                      \
    1305             :             CPL_LSBPTR64(&(value));                                            \
    1306             :         }                                                                      \
    1307             :     } while (false);
    1308             : 
    1309             :     /* -------------------------------------------------------------------- */
    1310             :     /*  Read the main header.                                               */
    1311             :     /* -------------------------------------------------------------------- */
    1312             : 
    1313             :     {
    1314         211 :         GByte abyHeader[RMF_HEADER_SIZE] = {};
    1315             : 
    1316         211 :         VSIFSeekL(poDS->fp, nNextHeaderOffset, SEEK_SET);
    1317         211 :         if (VSIFReadL(abyHeader, 1, sizeof(abyHeader), poDS->fp) !=
    1318             :             sizeof(abyHeader))
    1319             :         {
    1320           0 :             delete poDS;
    1321           0 :             return nullptr;
    1322             :         }
    1323             : 
    1324         211 :         if (memcmp(abyHeader, RMF_SigMTW, sizeof(RMF_SigMTW)) == 0)
    1325             :         {
    1326          76 :             poDS->eRMFType = RMFT_MTW;
    1327             :         }
    1328         135 :         else if (memcmp(abyHeader, RMF_SigRSW_BE, sizeof(RMF_SigRSW_BE)) == 0)
    1329             :         {
    1330           6 :             poDS->eRMFType = RMFT_RSW;
    1331           6 :             poDS->bBigEndian = true;
    1332             :         }
    1333             :         else
    1334             :         {
    1335         129 :             poDS->eRMFType = RMFT_RSW;
    1336             :         }
    1337             : 
    1338         211 :         memcpy(poDS->sHeader.bySignature, abyHeader, RMF_SIGNATURE_SIZE);
    1339         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.iVersion, 4);
    1340         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nSize, 8);
    1341         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nOvrOffset, 12);
    1342         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.iUserID, 16);
    1343         211 :         memcpy(poDS->sHeader.byName, abyHeader + 20,
    1344             :                sizeof(poDS->sHeader.byName));
    1345         211 :         poDS->sHeader.byName[sizeof(poDS->sHeader.byName) - 1] = '\0';
    1346         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nBitDepth, 52);
    1347         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nHeight, 56);
    1348         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nWidth, 60);
    1349         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nXTiles, 64);
    1350         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nYTiles, 68);
    1351         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nTileHeight, 72);
    1352         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nTileWidth, 76);
    1353         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nLastTileHeight, 80);
    1354         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nLastTileWidth, 84);
    1355         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nROIOffset, 88);
    1356         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nROISize, 92);
    1357         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nClrTblOffset, 96);
    1358         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nClrTblSize, 100);
    1359         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nTileTblOffset, 104);
    1360         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nTileTblSize, 108);
    1361         211 :         RMF_READ_LONG(abyHeader, poDS->sHeader.iMapType, 124);
    1362         211 :         RMF_READ_LONG(abyHeader, poDS->sHeader.iProjection, 128);
    1363         211 :         RMF_READ_LONG(abyHeader, poDS->sHeader.iEPSGCode, 132);
    1364         211 :         RMF_READ_DOUBLE(abyHeader, poDS->sHeader.dfScale, 136);
    1365         211 :         RMF_READ_DOUBLE(abyHeader, poDS->sHeader.dfResolution, 144);
    1366         211 :         RMF_READ_DOUBLE(abyHeader, poDS->sHeader.dfPixelSize, 152);
    1367         211 :         RMF_READ_DOUBLE(abyHeader, poDS->sHeader.dfLLY, 160);
    1368         211 :         RMF_READ_DOUBLE(abyHeader, poDS->sHeader.dfLLX, 168);
    1369         211 :         RMF_READ_DOUBLE(abyHeader, poDS->sHeader.dfStdP1, 176);
    1370         211 :         RMF_READ_DOUBLE(abyHeader, poDS->sHeader.dfStdP2, 184);
    1371         211 :         RMF_READ_DOUBLE(abyHeader, poDS->sHeader.dfCenterLong, 192);
    1372         211 :         RMF_READ_DOUBLE(abyHeader, poDS->sHeader.dfCenterLat, 200);
    1373         211 :         poDS->sHeader.iCompression = *(abyHeader + 208);
    1374         211 :         poDS->sHeader.iMaskType = *(abyHeader + 209);
    1375         211 :         poDS->sHeader.iMaskStep = *(abyHeader + 210);
    1376         211 :         poDS->sHeader.iFrameFlag = *(abyHeader + 211);
    1377         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nFlagsTblOffset, 212);
    1378         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nFlagsTblSize, 216);
    1379         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nFileSize0, 220);
    1380         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nFileSize1, 224);
    1381         211 :         poDS->sHeader.iUnknown = *(abyHeader + 228);
    1382         211 :         poDS->sHeader.iGeorefFlag = *(abyHeader + 244);
    1383         211 :         poDS->sHeader.iInverse = *(abyHeader + 245);
    1384         211 :         poDS->sHeader.iJpegQuality = *(abyHeader + 246);
    1385         211 :         memcpy(poDS->sHeader.abyInvisibleColors, abyHeader + 248,
    1386             :                sizeof(poDS->sHeader.abyInvisibleColors));
    1387         211 :         RMF_READ_DOUBLE(abyHeader, poDS->sHeader.adfElevMinMax[0], 280);
    1388         211 :         RMF_READ_DOUBLE(abyHeader, poDS->sHeader.adfElevMinMax[1], 288);
    1389         211 :         RMF_READ_DOUBLE(abyHeader, poDS->sHeader.dfNoData, 296);
    1390             : 
    1391         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.iElevationUnit, 304);
    1392         211 :         poDS->sHeader.iElevationType = *(abyHeader + 308);
    1393         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nExtHdrOffset, 312);
    1394         211 :         RMF_READ_ULONG(abyHeader, poDS->sHeader.nExtHdrSize, 316);
    1395         211 :         poDS->SetMetadataItem(MD_SCALE_KEY,
    1396         211 :                               CPLSPrintf("1 : %u", int(poDS->sHeader.dfScale)));
    1397         211 :         poDS->SetMetadataItem(MD_NAME_KEY,
    1398         211 :                               CPLSPrintf("%s", poDS->sHeader.byName));
    1399         211 :         poDS->SetMetadataItem(MD_VERSION_KEY,
    1400             :                               CPLSPrintf("%d", poDS->sHeader.iVersion));
    1401         211 :         poDS->SetMetadataItem(MD_MATH_BASE_MAP_TYPE_KEY,
    1402             :                               CPLSPrintf("%d", poDS->sHeader.iMapType));
    1403         211 :         poDS->SetMetadataItem(MD_MATH_BASE_PROJECTION_KEY,
    1404             :                               CPLSPrintf("%d", poDS->sHeader.iProjection));
    1405             :     }
    1406             : 
    1407         211 :     if (poDS->sHeader.nTileTblSize % (sizeof(GUInt32) * 2))
    1408             :     {
    1409           0 :         CPLError(CE_Warning, CPLE_IllegalArg, "Invalid tile table size.");
    1410           0 :         delete poDS;
    1411           0 :         return nullptr;
    1412             :     }
    1413             : 
    1414             :     bool bInvalidTileSize;
    1415             :     try
    1416             :     {
    1417             :         uint64_t nMaxTileBits =
    1418         211 :             (CPLSM(static_cast<uint64_t>(2)) *
    1419         422 :              CPLSM(static_cast<uint64_t>(poDS->sHeader.nTileWidth)) *
    1420         422 :              CPLSM(static_cast<uint64_t>(poDS->sHeader.nTileHeight)) *
    1421         422 :              CPLSM(static_cast<uint64_t>(poDS->sHeader.nBitDepth)))
    1422         211 :                 .v();
    1423         211 :         bInvalidTileSize =
    1424             :             (nMaxTileBits >
    1425         211 :              static_cast<uint64_t>(std::numeric_limits<GUInt32>::max()));
    1426             :     }
    1427           0 :     catch (...)
    1428             :     {
    1429           0 :         bInvalidTileSize = true;
    1430             :     }
    1431         211 :     if (bInvalidTileSize)
    1432             :     {
    1433           0 :         CPLError(CE_Warning, CPLE_IllegalArg,
    1434             :                  "Invalid tile size. Width %lu, height %lu, bit depth %lu.",
    1435           0 :                  static_cast<unsigned long>(poDS->sHeader.nTileWidth),
    1436           0 :                  static_cast<unsigned long>(poDS->sHeader.nTileHeight),
    1437           0 :                  static_cast<unsigned long>(poDS->sHeader.nBitDepth));
    1438           0 :         delete poDS;
    1439           0 :         return nullptr;
    1440             :     }
    1441             : 
    1442         211 :     if (poDS->sHeader.nLastTileWidth > poDS->sHeader.nTileWidth ||
    1443         211 :         poDS->sHeader.nLastTileHeight > poDS->sHeader.nTileHeight)
    1444             :     {
    1445           0 :         CPLError(CE_Warning, CPLE_IllegalArg,
    1446             :                  "Invalid last tile size %lu x %lu. "
    1447             :                  "It can't be greater than %lu x %lu.",
    1448           0 :                  static_cast<unsigned long>(poDS->sHeader.nLastTileWidth),
    1449           0 :                  static_cast<unsigned long>(poDS->sHeader.nLastTileHeight),
    1450           0 :                  static_cast<unsigned long>(poDS->sHeader.nTileWidth),
    1451           0 :                  static_cast<unsigned long>(poDS->sHeader.nTileHeight));
    1452           0 :         delete poDS;
    1453           0 :         return nullptr;
    1454             :     }
    1455             : 
    1456         211 :     if (poParentDS != nullptr)
    1457             :     {
    1458          83 :         if (0 != memcmp(poDS->sHeader.bySignature,
    1459          83 :                         poParentDS->sHeader.bySignature, RMF_SIGNATURE_SIZE))
    1460             :         {
    1461           2 :             CPLError(CE_Warning, CPLE_IllegalArg,
    1462             :                      "Invalid subheader signature.");
    1463           2 :             delete poDS;
    1464           2 :             return nullptr;
    1465             :         }
    1466             :     }
    1467             : 
    1468             :     /* -------------------------------------------------------------------- */
    1469             :     /*  Read the extended header.                                           */
    1470             :     /* -------------------------------------------------------------------- */
    1471             : 
    1472         209 :     if (poDS->sHeader.nExtHdrOffset &&
    1473         198 :         poDS->sHeader.nExtHdrSize >= RMF_MIN_EXT_HEADER_SIZE)
    1474             :     {
    1475         198 :         if (poDS->sHeader.nExtHdrSize > RMF_MAX_EXT_HEADER_SIZE)
    1476             :         {
    1477           0 :             CPLError(CE_Failure, CPLE_FileIO, "RMF File malformed");
    1478           0 :             delete poDS;
    1479           0 :             return nullptr;
    1480             :         }
    1481             :         GByte *pabyExtHeader =
    1482         198 :             static_cast<GByte *>(CPLCalloc(poDS->sHeader.nExtHdrSize, 1));
    1483         198 :         if (pabyExtHeader == nullptr)
    1484             :         {
    1485           0 :             delete poDS;
    1486           0 :             return nullptr;
    1487             :         }
    1488             : 
    1489         198 :         VSIFSeekL(poDS->fp, poDS->GetFileOffset(poDS->sHeader.nExtHdrOffset),
    1490             :                   SEEK_SET);
    1491         198 :         VSIFReadL(pabyExtHeader, 1, poDS->sHeader.nExtHdrSize, poDS->fp);
    1492             : 
    1493         198 :         RMF_READ_LONG(pabyExtHeader, poDS->sExtHeader.nEllipsoid, 24);
    1494         198 :         RMF_READ_LONG(pabyExtHeader, poDS->sExtHeader.nVertDatum, 28);
    1495         198 :         RMF_READ_LONG(pabyExtHeader, poDS->sExtHeader.nDatum, 32);
    1496         198 :         RMF_READ_LONG(pabyExtHeader, poDS->sExtHeader.nZone, 36);
    1497             : 
    1498         198 :         CPLFree(pabyExtHeader);
    1499             :     }
    1500             : 
    1501         209 :     CPLDebug("RMF", "Version %d", poDS->sHeader.iVersion);
    1502             : 
    1503         209 :     constexpr GUInt32 ROI_MAX_SIZE_TO_AVOID_EXCESSIVE_RAM_USAGE =
    1504             :         10 * 1024 * 1024;
    1505             : #ifdef DEBUG
    1506             : 
    1507         418 :     CPLDebug("RMF",
    1508             :              "%s image has width %d, height %d, bit depth %d, "
    1509             :              "compression scheme %d, %s, nodata %f",
    1510         209 :              (poDS->eRMFType == RMFT_MTW) ? "MTW" : "RSW", poDS->sHeader.nWidth,
    1511             :              poDS->sHeader.nHeight, poDS->sHeader.nBitDepth,
    1512         209 :              poDS->sHeader.iCompression,
    1513         209 :              poDS->bBigEndian ? "big endian" : "little endian",
    1514             :              poDS->sHeader.dfNoData);
    1515         209 :     CPLDebug("RMF",
    1516             :              "Size %d, offset to overview %#lx, user ID %d, "
    1517             :              "ROI offset %#lx, ROI size %d",
    1518             :              poDS->sHeader.nSize,
    1519         209 :              static_cast<unsigned long>(poDS->sHeader.nOvrOffset),
    1520             :              poDS->sHeader.iUserID,
    1521         209 :              static_cast<unsigned long>(poDS->sHeader.nROIOffset),
    1522             :              poDS->sHeader.nROISize);
    1523         209 :     CPLDebug("RMF", "Map type %d, projection %d, scale %f, resolution %f, ",
    1524             :              poDS->sHeader.iMapType, poDS->sHeader.iProjection,
    1525             :              poDS->sHeader.dfScale, poDS->sHeader.dfResolution);
    1526         209 :     CPLDebug("RMF", "EPSG %d ", poDS->sHeader.iEPSGCode);
    1527         209 :     CPLDebug("RMF", "Georeferencing: pixel size %f, LLX %f, LLY %f",
    1528             :              poDS->sHeader.dfPixelSize, poDS->sHeader.dfLLX,
    1529             :              poDS->sHeader.dfLLY);
    1530             : 
    1531         209 :     if (poDS->sHeader.nROIOffset &&
    1532         116 :         poDS->sHeader.nROISize >= sizeof(RSWFrame) &&
    1533          12 :         poDS->sHeader.nROISize <= ROI_MAX_SIZE_TO_AVOID_EXCESSIVE_RAM_USAGE)
    1534             :     {
    1535             :         GByte *pabyROI = reinterpret_cast<GByte *>(
    1536          12 :             VSI_MALLOC_VERBOSE(poDS->sHeader.nROISize));
    1537          12 :         if (pabyROI == nullptr)
    1538             :         {
    1539           0 :             delete poDS;
    1540           0 :             return nullptr;
    1541             :         }
    1542             : 
    1543          12 :         VSIFSeekL(poDS->fp, poDS->GetFileOffset(poDS->sHeader.nROIOffset),
    1544             :                   SEEK_SET);
    1545          12 :         if (VSIFReadL(pabyROI, poDS->sHeader.nROISize, 1, poDS->fp) != 1)
    1546             :         {
    1547           0 :             CPLError(CE_Failure, CPLE_FileIO, "Cannot read ROI");
    1548           0 :             CPLFree(pabyROI);
    1549           0 :             delete poDS;
    1550           0 :             return nullptr;
    1551             :         }
    1552             : 
    1553             :         GInt32 nValue;
    1554             : 
    1555          12 :         CPLDebug("RMF", "ROI coordinates:");
    1556             :         /* coverity[tainted_data] */
    1557        3504 :         for (GUInt32 i = 0; i + sizeof(nValue) <= poDS->sHeader.nROISize;
    1558        3492 :              i += sizeof(nValue))
    1559             :         {
    1560        3492 :             RMF_READ_LONG(pabyROI, nValue, i);
    1561        3492 :             CPLDebug("RMF", "%d", nValue);
    1562             :         }
    1563             : 
    1564          12 :         CPLFree(pabyROI);
    1565             :     }
    1566             : #endif
    1567         418 :     if (poDS->sHeader.nWidth >= INT_MAX || poDS->sHeader.nHeight >= INT_MAX ||
    1568         209 :         !GDALCheckDatasetDimensions(poDS->sHeader.nWidth,
    1569         209 :                                     poDS->sHeader.nHeight))
    1570             :     {
    1571           0 :         delete poDS;
    1572           0 :         return nullptr;
    1573             :     }
    1574             : 
    1575             :     /* -------------------------------------------------------------------- */
    1576             :     /*  Read array of blocks offsets/sizes.                                 */
    1577             :     /* -------------------------------------------------------------------- */
    1578             : 
    1579             :     // To avoid useless excessive memory allocation
    1580         209 :     if (poDS->sHeader.nTileTblSize > 1000000)
    1581             :     {
    1582           0 :         VSIFSeekL(poDS->fp, 0, SEEK_END);
    1583           0 :         vsi_l_offset nFileSize = VSIFTellL(poDS->fp);
    1584           0 :         if (nFileSize < poDS->sHeader.nTileTblSize)
    1585             :         {
    1586           0 :             delete poDS;
    1587           0 :             return nullptr;
    1588             :         }
    1589             :     }
    1590             : 
    1591         209 :     if (VSIFSeekL(poDS->fp, poDS->GetFileOffset(poDS->sHeader.nTileTblOffset),
    1592         209 :                   SEEK_SET) < 0)
    1593             :     {
    1594           0 :         delete poDS;
    1595           0 :         return nullptr;
    1596             :     }
    1597             : 
    1598         209 :     poDS->paiTiles =
    1599         209 :         reinterpret_cast<GUInt32 *>(VSIMalloc(poDS->sHeader.nTileTblSize));
    1600         209 :     if (!poDS->paiTiles)
    1601             :     {
    1602           0 :         delete poDS;
    1603           0 :         return nullptr;
    1604             :     }
    1605             : 
    1606         209 :     if (VSIFReadL(poDS->paiTiles, 1, poDS->sHeader.nTileTblSize, poDS->fp) <
    1607         209 :         poDS->sHeader.nTileTblSize)
    1608             :     {
    1609           9 :         CPLDebug("RMF", "Can't read tiles offsets/sizes table.");
    1610           9 :         delete poDS;
    1611           9 :         return nullptr;
    1612             :     }
    1613             : 
    1614             : #ifdef CPL_MSB
    1615             :     if (!poDS->bBigEndian)
    1616             :     {
    1617             :         for (GUInt32 i = 0; i < poDS->sHeader.nTileTblSize / sizeof(GUInt32);
    1618             :              i++)
    1619             :             CPL_SWAP32PTR(poDS->paiTiles + i);
    1620             :     }
    1621             : #else
    1622         200 :     if (poDS->bBigEndian)
    1623             :     {
    1624          30 :         for (GUInt32 i = 0; i < poDS->sHeader.nTileTblSize / sizeof(GUInt32);
    1625             :              i++)
    1626          24 :             CPL_SWAP32PTR(poDS->paiTiles + i);
    1627             :     }
    1628             : #endif
    1629             : 
    1630             : #ifdef DEBUG
    1631         200 :     CPLDebug("RMF", "List of block offsets/sizes:");
    1632             : 
    1633         646 :     for (GUInt32 i = 0; i < poDS->sHeader.nTileTblSize / sizeof(GUInt32);
    1634         446 :          i += 2)
    1635             :     {
    1636         446 :         CPLDebug("RMF", "    %u / %u", poDS->paiTiles[i],
    1637         446 :                  poDS->paiTiles[i + 1]);
    1638             :     }
    1639             : #endif
    1640             : 
    1641             :     /* -------------------------------------------------------------------- */
    1642             :     /*  Set up essential image parameters.                                  */
    1643             :     /* -------------------------------------------------------------------- */
    1644         200 :     GDALDataType eType = GDT_UInt8;
    1645             : 
    1646         200 :     poDS->nRasterXSize = poDS->sHeader.nWidth;
    1647         200 :     poDS->nRasterYSize = poDS->sHeader.nHeight;
    1648             : 
    1649         200 :     if (poDS->eRMFType == RMFT_RSW)
    1650             :     {
    1651         126 :         switch (poDS->sHeader.nBitDepth)
    1652             :         {
    1653          58 :             case 32:
    1654             :             case 24:
    1655             :             case 16:
    1656          58 :                 poDS->nBands = 3;
    1657          58 :                 break;
    1658          68 :             case 1:
    1659             :             case 4:
    1660             :             case 8:
    1661          68 :                 if (poParentDS != nullptr &&
    1662          26 :                     poParentDS->poColorTable != nullptr)
    1663             :                 {
    1664          26 :                     poDS->poColorTable = poParentDS->poColorTable->Clone();
    1665             :                 }
    1666             :                 else
    1667             :                 {
    1668             :                     // Allocate memory for colour table and read it
    1669          42 :                     poDS->nColorTableSize = 1 << poDS->sHeader.nBitDepth;
    1670          42 :                     GUInt32 nExpectedColorTableBytes =
    1671          42 :                         poDS->nColorTableSize * 4;
    1672          42 :                     if (nExpectedColorTableBytes > poDS->sHeader.nClrTblSize)
    1673             :                     {
    1674             :                         // We could probably test for strict equality in
    1675             :                         // the above test ???
    1676           0 :                         CPLDebug("RMF",
    1677             :                                  "Wrong color table size. "
    1678             :                                  "Expected %u, got %u.",
    1679             :                                  nExpectedColorTableBytes,
    1680             :                                  poDS->sHeader.nClrTblSize);
    1681           0 :                         delete poDS;
    1682           0 :                         return nullptr;
    1683             :                     }
    1684          42 :                     poDS->pabyColorTable = reinterpret_cast<GByte *>(
    1685          42 :                         VSIMalloc(nExpectedColorTableBytes));
    1686          42 :                     if (poDS->pabyColorTable == nullptr)
    1687             :                     {
    1688           0 :                         CPLDebug("RMF", "Can't allocate color table.");
    1689           0 :                         delete poDS;
    1690           0 :                         return nullptr;
    1691             :                     }
    1692          42 :                     if (VSIFSeekL(
    1693             :                             poDS->fp,
    1694             :                             poDS->GetFileOffset(poDS->sHeader.nClrTblOffset),
    1695          42 :                             SEEK_SET) < 0)
    1696             :                     {
    1697           0 :                         CPLDebug("RMF", "Can't seek to color table location.");
    1698           0 :                         delete poDS;
    1699           0 :                         return nullptr;
    1700             :                     }
    1701          42 :                     if (VSIFReadL(poDS->pabyColorTable, 1,
    1702             :                                   nExpectedColorTableBytes,
    1703          42 :                                   poDS->fp) < nExpectedColorTableBytes)
    1704             :                     {
    1705           0 :                         CPLDebug("RMF", "Can't read color table.");
    1706           0 :                         delete poDS;
    1707           0 :                         return nullptr;
    1708             :                     }
    1709             : 
    1710          42 :                     poDS->poColorTable = new GDALColorTable();
    1711        9326 :                     for (GUInt32 i = 0; i < poDS->nColorTableSize; i++)
    1712             :                     {
    1713        9284 :                         const GDALColorEntry oEntry = {
    1714        9284 :                             poDS->pabyColorTable[i * 4],      // Red
    1715        9284 :                             poDS->pabyColorTable[i * 4 + 1],  // Green
    1716        9284 :                             poDS->pabyColorTable[i * 4 + 2],  // Blue
    1717             :                             255                               // Alpha
    1718        9284 :                         };
    1719             : 
    1720        9284 :                         poDS->poColorTable->SetColorEntry(i, &oEntry);
    1721             :                     }
    1722             :                 }
    1723          68 :                 poDS->nBands = 1;
    1724          68 :                 break;
    1725           0 :             default:
    1726           0 :                 CPLError(CE_Warning, CPLE_IllegalArg,
    1727             :                          "Invalid RSW bit depth %lu.",
    1728           0 :                          static_cast<unsigned long>(poDS->sHeader.nBitDepth));
    1729           0 :                 delete poDS;
    1730           0 :                 return nullptr;
    1731             :         }
    1732         126 :         eType = GDT_UInt8;
    1733             :     }
    1734             :     else
    1735             :     {
    1736          74 :         poDS->nBands = 1;
    1737          74 :         if (poDS->sHeader.nBitDepth == 8)
    1738             :         {
    1739           0 :             eType = GDT_UInt8;
    1740             :         }
    1741          74 :         else if (poDS->sHeader.nBitDepth == 16)
    1742             :         {
    1743           0 :             eType = GDT_Int16;
    1744             :         }
    1745          74 :         else if (poDS->sHeader.nBitDepth == 32)
    1746             :         {
    1747           9 :             eType = GDT_Int32;
    1748             :         }
    1749          65 :         else if (poDS->sHeader.nBitDepth == 64)
    1750             :         {
    1751          65 :             eType = GDT_Float64;
    1752             :         }
    1753             :         else
    1754             :         {
    1755           0 :             CPLError(CE_Warning, CPLE_IllegalArg, "Invalid MTW bit depth %lu.",
    1756           0 :                      static_cast<unsigned long>(poDS->sHeader.nBitDepth));
    1757           0 :             delete poDS;
    1758           0 :             return nullptr;
    1759             :         }
    1760             :     }
    1761             : 
    1762         200 :     if (poDS->sHeader.nTileWidth == 0 || poDS->sHeader.nTileWidth > INT_MAX ||
    1763         200 :         poDS->sHeader.nTileHeight == 0 || poDS->sHeader.nTileHeight > INT_MAX)
    1764             :     {
    1765           0 :         CPLDebug("RMF", "Invalid tile dimension : %u x %u",
    1766             :                  poDS->sHeader.nTileWidth, poDS->sHeader.nTileHeight);
    1767           0 :         delete poDS;
    1768           0 :         return nullptr;
    1769             :     }
    1770             : 
    1771         200 :     const int nDataSize = GDALGetDataTypeSizeBytes(eType);
    1772         200 :     const int nBlockXSize = static_cast<int>(poDS->sHeader.nTileWidth);
    1773         200 :     const int nBlockYSize = static_cast<int>(poDS->sHeader.nTileHeight);
    1774         200 :     if (nDataSize == 0 || nBlockXSize > INT_MAX / nBlockYSize ||
    1775         200 :         nBlockYSize > INT_MAX / nDataSize ||
    1776         200 :         nBlockXSize > INT_MAX / (nBlockYSize * nDataSize))
    1777             :     {
    1778           0 :         CPLDebug("RMF", "Too big raster / tile dimension");
    1779           0 :         delete poDS;
    1780           0 :         return nullptr;
    1781             :     }
    1782             : 
    1783         200 :     poDS->nXTiles = DIV_ROUND_UP(poDS->nRasterXSize, nBlockXSize);
    1784         200 :     poDS->nYTiles = DIV_ROUND_UP(poDS->nRasterYSize, nBlockYSize);
    1785             : 
    1786             : #ifdef DEBUG
    1787         200 :     CPLDebug("RMF", "Image is %d tiles wide, %d tiles long", poDS->nXTiles,
    1788             :              poDS->nYTiles);
    1789             : #endif
    1790             : 
    1791             :     /* -------------------------------------------------------------------- */
    1792             :     /*  Choose compression scheme.                                          */
    1793             :     /* -------------------------------------------------------------------- */
    1794         200 :     if (CE_None != poDS->SetupCompression(eType, poOpenInfo->pszFilename))
    1795             :     {
    1796           0 :         delete poDS;
    1797           0 :         return nullptr;
    1798             :     }
    1799             : 
    1800         200 :     if (poOpenInfo->eAccess == GA_Update)
    1801             :     {
    1802          20 :         if (poParentDS == nullptr)
    1803             :         {
    1804          12 :             if (CE_None !=
    1805          12 :                 poDS->InitCompressorData(poOpenInfo->papszOpenOptions))
    1806             :             {
    1807           0 :                 delete poDS;
    1808           0 :                 return nullptr;
    1809             :             }
    1810             :         }
    1811             :         else
    1812             :         {
    1813           8 :             poDS->poCompressData = poParentDS->poCompressData;
    1814             :         }
    1815             :     }
    1816             :     /* -------------------------------------------------------------------- */
    1817             :     /*  Create band information objects.                                    */
    1818             :     /* -------------------------------------------------------------------- */
    1819         516 :     for (int iBand = 1; iBand <= poDS->nBands; iBand++)
    1820         316 :         poDS->SetBand(iBand, new RMFRasterBand(poDS, iBand, eType));
    1821             : 
    1822         200 :     poDS->SetupNBits();
    1823             : 
    1824         200 :     if (poDS->nBands > 1)
    1825             :     {
    1826          58 :         poDS->SetMetadataItem(GDALMD_INTERLEAVE, "PIXEL",
    1827             :                               GDAL_MDD_IMAGE_STRUCTURE);
    1828             :     }
    1829             :     /* -------------------------------------------------------------------- */
    1830             :     /*  Set up projection.                                                  */
    1831             :     /*                                                                      */
    1832             :     /*  XXX: If projection value is not specified, but image still have     */
    1833             :     /*  georeferencing information, assume Gauss-Kruger projection.         */
    1834             :     /* -------------------------------------------------------------------- */
    1835         200 :     if (poDS->sHeader.iEPSGCode > RMF_EPSG_MIN_CODE ||
    1836         186 :         poDS->sHeader.iProjection > 0 ||
    1837         117 :         (poDS->sHeader.dfPixelSize != 0.0 && poDS->sHeader.dfLLX != 0.0 &&
    1838          15 :          poDS->sHeader.dfLLY != 0.0))
    1839             :     {
    1840          98 :         GInt32 nProj =
    1841          98 :             (poDS->sHeader.iProjection) ? poDS->sHeader.iProjection : 1;
    1842          98 :         double padfPrjParams[8] = {poDS->sHeader.dfStdP1,
    1843          98 :                                    poDS->sHeader.dfStdP2,
    1844          98 :                                    poDS->sHeader.dfCenterLat,
    1845          98 :                                    poDS->sHeader.dfCenterLong,
    1846             :                                    1.0,
    1847             :                                    0.0,
    1848             :                                    0.0,
    1849          98 :                                    0.0};
    1850             : 
    1851             :         // XXX: Compute zone number for Gauss-Kruger (Transverse Mercator)
    1852             :         // projection if it is not specified.
    1853          98 :         if (nProj == 1L && poDS->sHeader.dfCenterLong == 0.0)
    1854             :         {
    1855           6 :             if (poDS->sExtHeader.nZone == 0)
    1856             :             {
    1857           0 :                 double centerXCoord =
    1858           0 :                     poDS->sHeader.dfLLX +
    1859           0 :                     (poDS->nRasterXSize * poDS->sHeader.dfPixelSize / 2.0);
    1860           0 :                 padfPrjParams[7] = floor((centerXCoord - 500000.0) / 1000000.0);
    1861             :             }
    1862             :             else
    1863             :             {
    1864           6 :                 padfPrjParams[7] = poDS->sExtHeader.nZone;
    1865             :             }
    1866             :         }
    1867             : 
    1868          98 :         OGRErr res = OGRERR_FAILURE;
    1869          98 :         if (nProj >= 0 &&
    1870          88 :             (poDS->sExtHeader.nDatum >= 0 || poDS->sExtHeader.nEllipsoid >= 0))
    1871             :         {
    1872          88 :             res = poDS->m_oSRS.importFromPanorama(
    1873          88 :                 nProj, poDS->sExtHeader.nDatum, poDS->sExtHeader.nEllipsoid,
    1874             :                 padfPrjParams);
    1875             :         }
    1876             : 
    1877         111 :         if (poDS->sHeader.iEPSGCode > RMF_EPSG_MIN_CODE &&
    1878          13 :             (OGRERR_NONE != res || poDS->m_oSRS.IsLocal()))
    1879             :         {
    1880           1 :             res = poDS->m_oSRS.importFromEPSG(poDS->sHeader.iEPSGCode);
    1881             :         }
    1882             : 
    1883             :         const char *pszSetVertCS =
    1884          98 :             CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "RMF_SET_VERTCS",
    1885             :                                  CPLGetConfigOption("RMF_SET_VERTCS", "NO"));
    1886          98 :         if (CPLTestBool(pszSetVertCS) && res == OGRERR_NONE &&
    1887           0 :             poDS->sExtHeader.nVertDatum > 0)
    1888             :         {
    1889           0 :             poDS->m_oSRS.importVertCSFromPanorama(poDS->sExtHeader.nVertDatum);
    1890             :         }
    1891             :     }
    1892             : 
    1893             :     /* -------------------------------------------------------------------- */
    1894             :     /*  Set up georeferencing.                                              */
    1895             :     /* -------------------------------------------------------------------- */
    1896         200 :     if ((poDS->eRMFType == RMFT_RSW && poDS->sHeader.iGeorefFlag) ||
    1897         128 :         (poDS->eRMFType == RMFT_MTW && poDS->sHeader.dfPixelSize != 0.0))
    1898             :     {
    1899         146 :         poDS->m_gt.xorig = poDS->sHeader.dfLLX;
    1900         146 :         poDS->m_gt.yorig = poDS->sHeader.dfLLY +
    1901         146 :                            poDS->nRasterYSize * poDS->sHeader.dfPixelSize;
    1902         146 :         poDS->m_gt.xscale = poDS->sHeader.dfPixelSize;
    1903         146 :         poDS->m_gt.yscale = -poDS->sHeader.dfPixelSize;
    1904         146 :         poDS->m_gt.xrot = 0.0;
    1905         146 :         poDS->m_gt.yrot = 0.0;
    1906             :     }
    1907             : 
    1908             :     /* -------------------------------------------------------------------- */
    1909             :     /*  Set units.                                                          */
    1910             :     /* -------------------------------------------------------------------- */
    1911             : 
    1912         200 :     if (poDS->eRMFType == RMFT_MTW)
    1913             :     {
    1914          74 :         CPLFree(poDS->pszUnitType);
    1915          74 :         poDS->pszUnitType = RMFUnitTypeToStr(poDS->sHeader.iElevationUnit);
    1916             :     }
    1917             : 
    1918             :     /* -------------------------------------------------------------------- */
    1919             :     /*  Report some other dataset related information.                      */
    1920             :     /* -------------------------------------------------------------------- */
    1921             : 
    1922         200 :     if (poDS->eRMFType == RMFT_MTW)
    1923             :     {
    1924          74 :         char szTemp[256] = {};
    1925             : 
    1926          74 :         snprintf(szTemp, sizeof(szTemp), "%g", poDS->sHeader.adfElevMinMax[0]);
    1927          74 :         poDS->SetMetadataItem("ELEVATION_MINIMUM", szTemp);
    1928             : 
    1929          74 :         snprintf(szTemp, sizeof(szTemp), "%g", poDS->sHeader.adfElevMinMax[1]);
    1930          74 :         poDS->SetMetadataItem("ELEVATION_MAXIMUM", szTemp);
    1931             : 
    1932          74 :         poDS->SetMetadataItem("ELEVATION_UNITS", poDS->pszUnitType);
    1933             : 
    1934          74 :         snprintf(szTemp, sizeof(szTemp), "%d", poDS->sHeader.iElevationType);
    1935          74 :         poDS->SetMetadataItem("ELEVATION_TYPE", szTemp);
    1936             :     }
    1937             : 
    1938             :     /* -------------------------------------------------------------------- */
    1939             :     /*      Check for overviews.                                            */
    1940             :     /* -------------------------------------------------------------------- */
    1941         200 :     if (nNextHeaderOffset == 0 && poParentDS == nullptr)
    1942             :     {
    1943         119 :         poDS->oOvManager.Initialize(poDS, poOpenInfo->pszFilename);
    1944             :     }
    1945             : 
    1946             :     /* Set frame */
    1947         200 :     if (poDS->sHeader.nROIOffset &&
    1948         107 :         poDS->sHeader.nROISize >= sizeof(RSWFrame) &&
    1949          12 :         poDS->sHeader.nROISize <= ROI_MAX_SIZE_TO_AVOID_EXCESSIVE_RAM_USAGE)
    1950             :     {
    1951             :         GByte *pabyROI = reinterpret_cast<GByte *>(
    1952          12 :             VSI_MALLOC_VERBOSE(poDS->sHeader.nROISize));
    1953          12 :         if (pabyROI == nullptr)
    1954             :         {
    1955           0 :             delete poDS;
    1956           0 :             return nullptr;
    1957             :         }
    1958             : 
    1959          12 :         VSIFSeekL(poDS->fp, poDS->GetFileOffset(poDS->sHeader.nROIOffset),
    1960             :                   SEEK_SET);
    1961          12 :         if (VSIFReadL(pabyROI, poDS->sHeader.nROISize, 1, poDS->fp) != 1)
    1962             :         {
    1963           0 :             CPLError(CE_Failure, CPLE_FileIO, "Cannot read ROI");
    1964           0 :             CPLFree(pabyROI);
    1965           0 :             delete poDS;
    1966           0 :             return nullptr;
    1967             :         }
    1968             : 
    1969             :         GInt32 nFrameType;
    1970          12 :         RMF_READ_LONG(pabyROI, nFrameType, 0);
    1971          12 :         if (nFrameType == nPolygonType)
    1972             :         {
    1973          24 :             CPLString osWKT = "POLYGON((";
    1974          12 :             bool bFirst = true;
    1975             : 
    1976          12 :             CPLDebug("RMF", "ROI coordinates:");
    1977             :             /* coverity[tainted_data] */
    1978          12 :             for (GUInt32 i = sizeof(RSWFrame);
    1979        1734 :                  i + sizeof(RSWFrameCoord) <= poDS->sHeader.nROISize;
    1980        1722 :                  i += sizeof(RSWFrameCoord))
    1981             :             {
    1982             :                 GInt32 nX, nY;
    1983        1722 :                 RMF_READ_LONG(pabyROI, nX, i);
    1984        1722 :                 RMF_READ_LONG(pabyROI, nY, i + 4);
    1985             : 
    1986        1722 :                 CPLDebug("RMF", "X: %d, Y: %d", nX, nY);
    1987             : 
    1988        1722 :                 double dfX = poDS->m_gt.xorig + nX * poDS->m_gt.xscale +
    1989        1722 :                              nY * poDS->m_gt.xrot;
    1990        1722 :                 double dfY = poDS->m_gt.yorig + nX * poDS->m_gt.yrot +
    1991        1722 :                              nY * poDS->m_gt.yscale;
    1992             : 
    1993        1722 :                 if (bFirst)
    1994             :                 {
    1995          12 :                     osWKT += CPLSPrintf("%f %f", dfX, dfY);
    1996          12 :                     bFirst = false;
    1997             :                 }
    1998             :                 else
    1999             :                 {
    2000        1710 :                     osWKT += CPLSPrintf(", %f %f", dfX, dfY);
    2001             :                 }
    2002             :             }
    2003          12 :             osWKT += "))";
    2004          12 :             CPLDebug("RMF", "Frame WKT: %s", osWKT.c_str());
    2005          12 :             poDS->SetMetadataItem(MD_FRAME_KEY, osWKT);
    2006             :         }
    2007          12 :         CPLFree(pabyROI);
    2008             :     }
    2009             : 
    2010             : #undef RMF_READ_DOUBLE
    2011             : #undef RMF_READ_LONG
    2012             : #undef RMF_READ_ULONG
    2013             : 
    2014         200 :     if (poDS->sHeader.nFlagsTblOffset && poDS->sHeader.nFlagsTblSize)
    2015             :     {
    2016         107 :         VSIFSeekL(poDS->fp, poDS->GetFileOffset(poDS->sHeader.nFlagsTblOffset),
    2017             :                   SEEK_SET);
    2018         107 :         CPLDebug("RMF", "Blocks flags:");
    2019             :         /* coverity[tainted_data] */
    2020         416 :         for (GUInt32 i = 0; i < poDS->sHeader.nFlagsTblSize; i += sizeof(GByte))
    2021             :         {
    2022             :             GByte nValue;
    2023         309 :             if (VSIFReadL(&nValue, 1, sizeof(nValue), poDS->fp) !=
    2024             :                 sizeof(nValue))
    2025             :             {
    2026           0 :                 CPLDebug("RMF", "Cannot read Block flag at index %u", i);
    2027           0 :                 break;
    2028             :             }
    2029         309 :             CPLDebug("RMF", "Block %u -- flag %d", i, nValue);
    2030             :         }
    2031             :     }
    2032         200 :     return poDS;
    2033             : }
    2034             : 
    2035             : /************************************************************************/
    2036             : /*                               Create()                               */
    2037             : /************************************************************************/
    2038          89 : GDALDataset *RMFDataset::Create(const char *pszFilename, int nXSize, int nYSize,
    2039             :                                 int nBandsIn, GDALDataType eType,
    2040             :                                 CSLConstList papszParamList)
    2041             : {
    2042          89 :     return Create(pszFilename, nXSize, nYSize, nBandsIn, eType, papszParamList,
    2043          89 :                   nullptr, 1.0);
    2044             : }
    2045             : 
    2046         123 : GDALDataset *RMFDataset::Create(const char *pszFilename, int nXSize, int nYSize,
    2047             :                                 int nBandsIn, GDALDataType eType,
    2048             :                                 CSLConstList papszParamList,
    2049             :                                 RMFDataset *poParentDS, double dfOvFactor)
    2050             : 
    2051             : {
    2052         123 :     if (nBandsIn != 1 && nBandsIn != 3)
    2053             :     {
    2054           7 :         CPLError(CE_Failure, CPLE_NotSupported,
    2055             :                  "RMF driver doesn't support %d bands. Must be 1 or 3.",
    2056             :                  nBandsIn);
    2057             : 
    2058           7 :         return nullptr;
    2059             :     }
    2060             : 
    2061         116 :     if (nBandsIn == 1 && eType != GDT_UInt8 && eType != GDT_Int16 &&
    2062          52 :         eType != GDT_Int32 && eType != GDT_Float64)
    2063             :     {
    2064          17 :         CPLError(
    2065             :             CE_Failure, CPLE_AppDefined,
    2066             :             "Attempt to create RMF dataset with an illegal data type (%s), "
    2067             :             "only Byte, Int16, Int32 and Float64 types supported "
    2068             :             "by the format for single-band images.",
    2069             :             GDALGetDataTypeName(eType));
    2070             : 
    2071          17 :         return nullptr;
    2072             :     }
    2073             : 
    2074          99 :     if (nBandsIn == 3 && eType != GDT_UInt8)
    2075             :     {
    2076          13 :         CPLError(
    2077             :             CE_Failure, CPLE_AppDefined,
    2078             :             "Attempt to create RMF dataset with an illegal data type (%s), "
    2079             :             "only Byte type supported by the format for three-band images.",
    2080             :             GDALGetDataTypeName(eType));
    2081             : 
    2082          13 :         return nullptr;
    2083             :     }
    2084             : 
    2085             :     /* -------------------------------------------------------------------- */
    2086             :     /*  Create the dataset.                                                 */
    2087             :     /* -------------------------------------------------------------------- */
    2088          86 :     RMFDataset *poDS = new RMFDataset();
    2089             : 
    2090          86 :     GUInt32 nBlockXSize =
    2091          86 :         (nXSize < RMF_DEFAULT_BLOCKXSIZE) ? nXSize : RMF_DEFAULT_BLOCKXSIZE;
    2092          86 :     GUInt32 nBlockYSize =
    2093          86 :         (nYSize < RMF_DEFAULT_BLOCKYSIZE) ? nYSize : RMF_DEFAULT_BLOCKYSIZE;
    2094             :     double dfScale;
    2095             :     double dfResolution;
    2096             :     double dfPixelSize;
    2097          86 :     if (poParentDS == nullptr)
    2098             :     {
    2099          52 :         poDS->fp = VSIFOpenL(pszFilename, "w+b");
    2100          52 :         if (poDS->fp == nullptr)
    2101             :         {
    2102           3 :             CPLError(CE_Failure, CPLE_OpenFailed, "Unable to create file %s.",
    2103             :                      pszFilename);
    2104           3 :             delete poDS;
    2105           3 :             return nullptr;
    2106             :         }
    2107             : 
    2108             :         const char *pszScaleValue =
    2109          49 :             CSLFetchNameValue(papszParamList, MD_SCALE_KEY);
    2110          49 :         if (pszScaleValue != nullptr && CPLStrnlen(pszScaleValue, 10) > 4)
    2111             :         {
    2112           0 :             dfScale = atof(pszScaleValue + 4);
    2113             :         }
    2114             :         else
    2115             :         {
    2116          49 :             dfScale = RMF_DEFAULT_SCALE;
    2117             :         }
    2118          49 :         dfResolution = RMF_DEFAULT_RESOLUTION;
    2119          49 :         dfPixelSize = 1;
    2120             : 
    2121          49 :         if (CPLFetchBool(papszParamList, "MTW", false))
    2122          12 :             poDS->eRMFType = RMFT_MTW;
    2123             :         else
    2124          37 :             poDS->eRMFType = RMFT_RSW;
    2125             : 
    2126          49 :         GUInt32 iVersion = RMF_VERSION;
    2127          49 :         const char *pszRMFHUGE = CSLFetchNameValue(papszParamList, "RMFHUGE");
    2128             : 
    2129          49 :         if (pszRMFHUGE == nullptr)
    2130          35 :             pszRMFHUGE = "NO";  // Keep old behavior by default
    2131             : 
    2132          49 :         if (EQUAL(pszRMFHUGE, "NO"))
    2133             :         {
    2134          42 :             iVersion = RMF_VERSION;
    2135             :         }
    2136           7 :         else if (EQUAL(pszRMFHUGE, "YES"))
    2137             :         {
    2138           7 :             iVersion = RMF_VERSION_HUGE;
    2139             :         }
    2140           0 :         else if (EQUAL(pszRMFHUGE, "IF_SAFER"))
    2141             :         {
    2142             :             const double dfImageSize =
    2143           0 :                 static_cast<double>(nXSize) * static_cast<double>(nYSize) *
    2144           0 :                 static_cast<double>(nBandsIn) *
    2145           0 :                 static_cast<double>(GDALGetDataTypeSizeBytes(eType));
    2146           0 :             if (dfImageSize > 3.0 * 1024.0 * 1024.0 * 1024.0)
    2147             :             {
    2148           0 :                 iVersion = RMF_VERSION_HUGE;
    2149             :             }
    2150             :             else
    2151             :             {
    2152           0 :                 iVersion = RMF_VERSION;
    2153             :             }
    2154             :         }
    2155             : 
    2156          49 :         const char *pszValue = CSLFetchNameValue(papszParamList, "BLOCKXSIZE");
    2157          49 :         if (pszValue != nullptr)
    2158           1 :             nBlockXSize = atoi(pszValue);
    2159          49 :         if (static_cast<int>(nBlockXSize) <= 0)
    2160           0 :             nBlockXSize = RMF_DEFAULT_BLOCKXSIZE;
    2161             : 
    2162          49 :         pszValue = CSLFetchNameValue(papszParamList, "BLOCKYSIZE");
    2163          49 :         if (pszValue != nullptr)
    2164           1 :             nBlockYSize = atoi(pszValue);
    2165          49 :         if (static_cast<int>(nBlockYSize) <= 0)
    2166           0 :             nBlockYSize = RMF_DEFAULT_BLOCKXSIZE;
    2167             : 
    2168          49 :         if (poDS->eRMFType == RMFT_MTW)
    2169          12 :             memcpy(poDS->sHeader.bySignature, RMF_SigMTW, RMF_SIGNATURE_SIZE);
    2170             :         else
    2171          37 :             memcpy(poDS->sHeader.bySignature, RMF_SigRSW, RMF_SIGNATURE_SIZE);
    2172          49 :         poDS->sHeader.iVersion = iVersion;
    2173          49 :         poDS->sHeader.nOvrOffset = 0x00;
    2174             :     }
    2175             :     else
    2176             :     {
    2177          34 :         poDS->fp = poParentDS->fp;
    2178          34 :         memcpy(poDS->sHeader.bySignature, poParentDS->sHeader.bySignature,
    2179             :                RMF_SIGNATURE_SIZE);
    2180          34 :         poDS->sHeader.iVersion = poParentDS->sHeader.iVersion;
    2181          34 :         poDS->eRMFType = poParentDS->eRMFType;
    2182          34 :         nBlockXSize = poParentDS->sHeader.nTileWidth;
    2183          34 :         nBlockYSize = poParentDS->sHeader.nTileHeight;
    2184          34 :         dfScale = poParentDS->sHeader.dfScale;
    2185          34 :         dfResolution = poParentDS->sHeader.dfResolution / dfOvFactor;
    2186          34 :         dfPixelSize = poParentDS->sHeader.dfPixelSize * dfOvFactor;
    2187             : 
    2188          34 :         poDS->nHeaderOffset = poParentDS->GetLastOffset();
    2189          34 :         poParentDS->sHeader.nOvrOffset =
    2190          34 :             poDS->GetRMFOffset(poDS->nHeaderOffset, &poDS->nHeaderOffset);
    2191          34 :         poParentDS->bHeaderDirty = true;
    2192          34 :         VSIFSeekL(poDS->fp, poDS->nHeaderOffset, SEEK_SET);
    2193          34 :         poDS->poParentDS = poParentDS;
    2194          34 :         CPLDebug("RMF",
    2195             :                  "Create overview subfile at " CPL_FRMT_GUIB
    2196             :                  " with size %dx%d, parent overview offset %d",
    2197             :                  poDS->nHeaderOffset, nXSize, nYSize,
    2198             :                  poParentDS->sHeader.nOvrOffset);
    2199             :     }
    2200             :     /* -------------------------------------------------------------------- */
    2201             :     /*  Fill the RMFHeader                                                  */
    2202             :     /* -------------------------------------------------------------------- */
    2203          83 :     CPLDebug("RMF", "Version %d", poDS->sHeader.iVersion);
    2204             : 
    2205          83 :     poDS->sHeader.iUserID = 0x00;
    2206          83 :     memset(poDS->sHeader.byName, 0, sizeof(poDS->sHeader.byName));
    2207          83 :     poDS->sHeader.nBitDepth = GDALGetDataTypeSizeBits(eType) * nBandsIn;
    2208          83 :     poDS->sHeader.nHeight = nYSize;
    2209          83 :     poDS->sHeader.nWidth = nXSize;
    2210          83 :     poDS->sHeader.nTileWidth = nBlockXSize;
    2211          83 :     poDS->sHeader.nTileHeight = nBlockYSize;
    2212             : 
    2213          83 :     poDS->nXTiles = poDS->sHeader.nXTiles =
    2214          83 :         DIV_ROUND_UP(nXSize, poDS->sHeader.nTileWidth);
    2215          83 :     poDS->nYTiles = poDS->sHeader.nYTiles =
    2216          83 :         DIV_ROUND_UP(nYSize, poDS->sHeader.nTileHeight);
    2217          83 :     poDS->sHeader.nLastTileHeight = nYSize % poDS->sHeader.nTileHeight;
    2218          83 :     if (!poDS->sHeader.nLastTileHeight)
    2219          44 :         poDS->sHeader.nLastTileHeight = poDS->sHeader.nTileHeight;
    2220          83 :     poDS->sHeader.nLastTileWidth = nXSize % poDS->sHeader.nTileWidth;
    2221          83 :     if (!poDS->sHeader.nLastTileWidth)
    2222          40 :         poDS->sHeader.nLastTileWidth = poDS->sHeader.nTileWidth;
    2223             : 
    2224             :     // poDS->sHeader.nROIOffset = 0x00;
    2225             :     // poDS->sHeader.nROISize = 0x00;
    2226             : 
    2227          83 :     vsi_l_offset nCurPtr = poDS->nHeaderOffset + RMF_HEADER_SIZE;
    2228             : 
    2229             :     // Extended header
    2230          83 :     poDS->sHeader.nExtHdrOffset = poDS->GetRMFOffset(nCurPtr, &nCurPtr);
    2231          83 :     poDS->sHeader.nExtHdrSize = RMF_EXT_HEADER_SIZE;
    2232          83 :     nCurPtr += poDS->sHeader.nExtHdrSize;
    2233             : 
    2234             :     // Color table
    2235          83 :     if (poDS->eRMFType == RMFT_RSW && nBandsIn == 1)
    2236             :     {
    2237          34 :         if (poDS->sHeader.nBitDepth > 8)
    2238             :         {
    2239           6 :             CPLError(CE_Failure, CPLE_AppDefined,
    2240             :                      "Cannot create color table of RSW with nBitDepth = %d. "
    2241             :                      "Retry with MTW ?",
    2242             :                      poDS->sHeader.nBitDepth);
    2243           6 :             delete poDS;
    2244           6 :             return nullptr;
    2245             :         }
    2246             : 
    2247          28 :         poDS->sHeader.nClrTblOffset = poDS->GetRMFOffset(nCurPtr, &nCurPtr);
    2248          28 :         poDS->nColorTableSize = 1 << poDS->sHeader.nBitDepth;
    2249          28 :         poDS->sHeader.nClrTblSize = poDS->nColorTableSize * 4;
    2250          28 :         poDS->pabyColorTable =
    2251          28 :             static_cast<GByte *>(VSI_MALLOC_VERBOSE(poDS->sHeader.nClrTblSize));
    2252          28 :         if (poDS->pabyColorTable == nullptr)
    2253             :         {
    2254           0 :             delete poDS;
    2255           0 :             return nullptr;
    2256             :         }
    2257        7196 :         for (GUInt32 i = 0; i < poDS->nColorTableSize; i++)
    2258             :         {
    2259        7168 :             poDS->pabyColorTable[i * 4 + 0] = static_cast<GByte>(i);
    2260        7168 :             poDS->pabyColorTable[i * 4 + 1] = static_cast<GByte>(i);
    2261        7168 :             poDS->pabyColorTable[i * 4 + 2] = static_cast<GByte>(i);
    2262        7168 :             poDS->pabyColorTable[i * 4 + 3] = 0;
    2263             :         }
    2264          28 :         nCurPtr += poDS->sHeader.nClrTblSize;
    2265             :     }
    2266             :     else
    2267             :     {
    2268          49 :         poDS->sHeader.nClrTblOffset = 0x00;
    2269          49 :         poDS->sHeader.nClrTblSize = 0x00;
    2270             :     }
    2271             : 
    2272             :     // Add room for ROI (frame)
    2273          77 :     poDS->sHeader.nROIOffset = poDS->GetRMFOffset(nCurPtr, &nCurPtr);
    2274          77 :     poDS->sHeader.nROISize = 0x00;
    2275          77 :     nCurPtr +=
    2276             :         sizeof(RSWFrame) +
    2277             :         sizeof(RSWFrameCoord) *
    2278             :             nMaxFramePointCount;  // Allocate nMaxFramePointCount coordinates for frame
    2279             : 
    2280             :     // Add blocks flags
    2281          77 :     poDS->sHeader.nFlagsTblOffset = poDS->GetRMFOffset(nCurPtr, &nCurPtr);
    2282          77 :     poDS->sHeader.nFlagsTblSize =
    2283          77 :         sizeof(GByte) * poDS->sHeader.nXTiles * poDS->sHeader.nYTiles;
    2284          77 :     nCurPtr += poDS->sHeader.nFlagsTblSize;
    2285             : 
    2286             :     // Blocks table
    2287          77 :     poDS->sHeader.nTileTblOffset = poDS->GetRMFOffset(nCurPtr, &nCurPtr);
    2288          77 :     poDS->sHeader.nTileTblSize =
    2289          77 :         2 * sizeof(GUInt32) * poDS->sHeader.nXTiles * poDS->sHeader.nYTiles;
    2290          77 :     poDS->paiTiles =
    2291          77 :         static_cast<GUInt32 *>(CPLCalloc(poDS->sHeader.nTileTblSize, 1));
    2292             :     // nCurPtr += poDS->sHeader.nTileTblSize;
    2293          77 :     const GUInt32 nTileSize = poDS->sHeader.nTileWidth *
    2294          77 :                               poDS->sHeader.nTileHeight *
    2295          77 :                               GDALGetDataTypeSizeBytes(eType);
    2296          77 :     poDS->sHeader.nSize =
    2297          77 :         poDS->paiTiles[poDS->sHeader.nTileTblSize / 4 - 2] + nTileSize;
    2298             : 
    2299             :     // Elevation units
    2300          77 :     poDS->sHeader.iElevationUnit = RMFStrToUnitType(poDS->pszUnitType);
    2301             : 
    2302          77 :     poDS->sHeader.iMapType = -1;
    2303          77 :     poDS->sHeader.iProjection = -1;
    2304          77 :     poDS->sHeader.iEPSGCode = -1;
    2305          77 :     poDS->sHeader.dfScale = dfScale;
    2306          77 :     poDS->sHeader.dfResolution = dfResolution;
    2307          77 :     poDS->sHeader.dfPixelSize = dfPixelSize;
    2308          77 :     poDS->sHeader.iMaskType = 0;
    2309          77 :     poDS->sHeader.iMaskStep = 0;
    2310          77 :     poDS->sHeader.iFrameFlag = 1;  // 1 - Frame not using
    2311             :     // poDS->sHeader.nFlagsTblOffset = 0x00;
    2312             :     // poDS->sHeader.nFlagsTblSize = 0x00;
    2313          77 :     poDS->sHeader.nFileSize0 = 0x00;
    2314          77 :     poDS->sHeader.nFileSize1 = 0x00;
    2315          77 :     poDS->sHeader.iUnknown = 0;
    2316          77 :     poDS->sHeader.iGeorefFlag = 0;
    2317          77 :     poDS->sHeader.iInverse = 0;
    2318          77 :     poDS->sHeader.iJpegQuality = 0;
    2319          77 :     memset(poDS->sHeader.abyInvisibleColors, 0,
    2320             :            sizeof(poDS->sHeader.abyInvisibleColors));
    2321          77 :     poDS->sHeader.iElevationType = 0;
    2322             : 
    2323          77 :     poDS->nRasterXSize = nXSize;
    2324          77 :     poDS->nRasterYSize = nYSize;
    2325          77 :     poDS->eAccess = GA_Update;
    2326          77 :     poDS->nBands = nBandsIn;
    2327             : 
    2328          77 :     if (poParentDS == nullptr)
    2329             :     {
    2330          43 :         poDS->sHeader.adfElevMinMax[0] = 0.0;
    2331          43 :         poDS->sHeader.adfElevMinMax[1] = 0.0;
    2332          43 :         poDS->sHeader.dfNoData = 0.0;
    2333          43 :         poDS->sHeader.iCompression =
    2334          43 :             GetCompressionType(CSLFetchNameValue(papszParamList, "COMPRESS"));
    2335          43 :         if (CE_None != poDS->InitCompressorData(papszParamList))
    2336             :         {
    2337           0 :             delete poDS;
    2338           0 :             return nullptr;
    2339             :         }
    2340             : 
    2341          43 :         if (poDS->sHeader.iCompression == RMF_COMPRESSION_JPEG)
    2342             :         {
    2343             :             const char *pszJpegQuality =
    2344           1 :                 CSLFetchNameValue(papszParamList, "JPEG_QUALITY");
    2345           1 :             if (pszJpegQuality == nullptr)
    2346             :             {
    2347           1 :                 poDS->sHeader.iJpegQuality = 75;
    2348             :             }
    2349             :             else
    2350             :             {
    2351           0 :                 int iJpegQuality = atoi(pszJpegQuality);
    2352           0 :                 if (iJpegQuality < 10 || iJpegQuality > 100)
    2353             :                 {
    2354           0 :                     CPLError(CE_Failure, CPLE_IllegalArg,
    2355             :                              "JPEG_QUALITY=%s is not a legal value in the "
    2356             :                              "range 10-100.\n"
    2357             :                              "Defaulting to 75",
    2358             :                              pszJpegQuality);
    2359           0 :                     iJpegQuality = 75;
    2360             :                 }
    2361           0 :                 poDS->sHeader.iJpegQuality = static_cast<GByte>(iJpegQuality);
    2362             :             }
    2363             :         }
    2364             : 
    2365          43 :         if (CE_None != poDS->SetupCompression(eType, pszFilename))
    2366             :         {
    2367           0 :             delete poDS;
    2368           0 :             return nullptr;
    2369             :         }
    2370             :     }
    2371             :     else
    2372             :     {
    2373          34 :         poDS->sHeader.adfElevMinMax[0] = poParentDS->sHeader.adfElevMinMax[0];
    2374          34 :         poDS->sHeader.adfElevMinMax[1] = poParentDS->sHeader.adfElevMinMax[1];
    2375          34 :         poDS->sHeader.dfNoData = poParentDS->sHeader.dfNoData;
    2376          34 :         poDS->sHeader.iCompression = poParentDS->sHeader.iCompression;
    2377          34 :         poDS->sHeader.iJpegQuality = poParentDS->sHeader.iJpegQuality;
    2378          34 :         poDS->Decompress = poParentDS->Decompress;
    2379          34 :         poDS->Compress = poParentDS->Compress;
    2380          34 :         poDS->poCompressData = poParentDS->poCompressData;
    2381             :     }
    2382             : 
    2383          77 :     if (nBandsIn > 1)
    2384             :     {
    2385          13 :         poDS->SetMetadataItem(GDALMD_INTERLEAVE, "PIXEL",
    2386             :                               GDAL_MDD_IMAGE_STRUCTURE);
    2387             :     }
    2388             : 
    2389          77 :     poDS->WriteHeader();
    2390             : 
    2391             :     /* -------------------------------------------------------------------- */
    2392             :     /*      Create band information objects.                                */
    2393             :     /* -------------------------------------------------------------------- */
    2394         180 :     for (int iBand = 1; iBand <= poDS->nBands; iBand++)
    2395         103 :         poDS->SetBand(iBand, new RMFRasterBand(poDS, iBand, eType));
    2396             : 
    2397          77 :     poDS->SetupNBits();
    2398             : 
    2399          77 :     return GDALDataset::FromHandle(poDS);
    2400             : }
    2401             : 
    2402             : // GIS Panorama 11 was introduced new format for huge files (greater than 3 Gb)
    2403        3859 : vsi_l_offset RMFDataset::GetFileOffset(GUInt32 iRMFOffset) const
    2404             : {
    2405        3859 :     if (sHeader.iVersion >= RMF_VERSION_HUGE)
    2406             :     {
    2407        1142 :         return (static_cast<vsi_l_offset>(iRMFOffset)) * RMF_HUGE_OFFSET_FACTOR;
    2408             :     }
    2409             : 
    2410        2717 :     return static_cast<vsi_l_offset>(iRMFOffset);
    2411             : }
    2412             : 
    2413         966 : GUInt32 RMFDataset::GetRMFOffset(vsi_l_offset nFileOffset,
    2414             :                                  vsi_l_offset *pnNewFileOffset) const
    2415             : {
    2416         966 :     if (sHeader.iVersion >= RMF_VERSION_HUGE)
    2417             :     {
    2418             :         // Round offset to next RMF_HUGE_OFFSET_FACTOR
    2419         272 :         const GUInt32 iRMFOffset =
    2420         272 :             static_cast<GUInt32>((nFileOffset + (RMF_HUGE_OFFSET_FACTOR - 1)) /
    2421             :                                  RMF_HUGE_OFFSET_FACTOR);
    2422         272 :         if (pnNewFileOffset != nullptr)
    2423             :         {
    2424         205 :             *pnNewFileOffset = GetFileOffset(iRMFOffset);
    2425             :         }
    2426         272 :         return iRMFOffset;
    2427             :     }
    2428             : 
    2429         694 :     if (pnNewFileOffset != nullptr)
    2430             :     {
    2431         561 :         *pnNewFileOffset = nFileOffset;
    2432             :     }
    2433         694 :     return static_cast<GUInt32>(nFileOffset);
    2434             : }
    2435             : 
    2436         200 : RMFDataset *RMFDataset::OpenOverview(RMFDataset *poParent,
    2437             :                                      GDALOpenInfo *poOpenInfo)
    2438             : {
    2439         200 :     if (sHeader.nOvrOffset == 0)
    2440             :     {
    2441         111 :         return nullptr;
    2442             :     }
    2443             : 
    2444          89 :     if (poParent == nullptr)
    2445             :     {
    2446           0 :         return nullptr;
    2447             :     }
    2448             : 
    2449          89 :     vsi_l_offset nSubOffset = GetFileOffset(sHeader.nOvrOffset);
    2450             : 
    2451          89 :     CPLDebug("RMF",
    2452             :              "Try to open overview subfile at " CPL_FRMT_GUIB " for '%s'",
    2453             :              nSubOffset, poOpenInfo->pszFilename);
    2454             : 
    2455          89 :     if (!poParent->poOvrDatasets.empty())
    2456             :     {
    2457          49 :         if (poParent->GetFileOffset(poParent->sHeader.nOvrOffset) == nSubOffset)
    2458             :         {
    2459           2 :             CPLError(CE_Warning, CPLE_IllegalArg,
    2460             :                      "Recursive subdataset list is detected. "
    2461             :                      "Overview open failed.");
    2462           2 :             return nullptr;
    2463             :         }
    2464             : 
    2465          58 :         for (size_t n = 0; n != poParent->poOvrDatasets.size() - 1; ++n)
    2466             :         {
    2467          13 :             RMFDataset *poOvr(poParent->poOvrDatasets[n]);
    2468             : 
    2469          13 :             if (poOvr == nullptr)
    2470           0 :                 continue;
    2471          13 :             if (poOvr->GetFileOffset(poOvr->sHeader.nOvrOffset) == nSubOffset)
    2472             :             {
    2473           2 :                 CPLError(CE_Warning, CPLE_IllegalArg,
    2474             :                          "Recursive subdataset list is detected. "
    2475             :                          "Overview open failed.");
    2476           2 :                 return nullptr;
    2477             :             }
    2478             :         }
    2479             :     }
    2480             : 
    2481          85 :     size_t nHeaderSize(RMF_HEADER_SIZE);
    2482             :     GByte *pabyNewHeader;
    2483             :     pabyNewHeader = static_cast<GByte *>(
    2484          85 :         CPLRealloc(poOpenInfo->pabyHeader, nHeaderSize + 1));
    2485          85 :     if (pabyNewHeader == nullptr)
    2486             :     {
    2487           0 :         CPLError(CE_Warning, CPLE_OutOfMemory,
    2488             :                  "Can't allocate buffer for overview header");
    2489           0 :         return nullptr;
    2490             :     }
    2491             : 
    2492          85 :     poOpenInfo->pabyHeader = pabyNewHeader;
    2493          85 :     memset(poOpenInfo->pabyHeader, 0, nHeaderSize + 1);
    2494          85 :     VSIFSeekL(fp, nSubOffset, SEEK_SET);
    2495          85 :     poOpenInfo->nHeaderBytes =
    2496          85 :         static_cast<int>(VSIFReadL(poOpenInfo->pabyHeader, 1, nHeaderSize, fp));
    2497             : 
    2498          85 :     return Open(poOpenInfo, poParent, nSubOffset);
    2499             : }
    2500             : 
    2501          17 : CPLErr RMFDataset::IBuildOverviews(const char *pszResampling, int nOverviews,
    2502             :                                    const int *panOverviewList, int nBandsIn,
    2503             :                                    const int *panBandList,
    2504             :                                    GDALProgressFunc pfnProgress,
    2505             :                                    void *pProgressData,
    2506             :                                    CSLConstList papszOptions)
    2507             : {
    2508          17 :     bool bUseGenericHandling = false;
    2509             : 
    2510          17 :     if (GetAccess() != GA_Update)
    2511             :     {
    2512           0 :         CPLDebug("RMF", "File open for read-only accessing, "
    2513             :                         "creating overviews externally.");
    2514             : 
    2515           0 :         bUseGenericHandling = true;
    2516             :     }
    2517             : 
    2518          17 :     if (bUseGenericHandling)
    2519             :     {
    2520           0 :         if (!poOvrDatasets.empty())
    2521             :         {
    2522           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    2523             :                      "Cannot add external overviews when there are already "
    2524             :                      "internal overviews");
    2525           0 :             return CE_Failure;
    2526             :         }
    2527             : 
    2528           0 :         return GDALDataset::IBuildOverviews(
    2529             :             pszResampling, nOverviews, panOverviewList, nBandsIn, panBandList,
    2530           0 :             pfnProgress, pProgressData, papszOptions);
    2531             :     }
    2532             : 
    2533          17 :     if (nBandsIn != GetRasterCount())
    2534             :     {
    2535           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    2536             :                  "Generation of overviews in RMF is only "
    2537             :                  "supported when operating on all bands.  "
    2538             :                  "Operation failed.");
    2539           0 :         return CE_Failure;
    2540             :     }
    2541             : 
    2542          17 :     if (nOverviews == 0)
    2543             :     {
    2544           0 :         if (poOvrDatasets.empty())
    2545             :         {
    2546           0 :             return GDALDataset::IBuildOverviews(
    2547             :                 pszResampling, nOverviews, panOverviewList, nBandsIn,
    2548           0 :                 panBandList, pfnProgress, pProgressData, papszOptions);
    2549             :         }
    2550           0 :         return CleanOverviews();
    2551             :     }
    2552             : 
    2553             :     // First destroy old overviews
    2554          17 :     if (CE_None != CleanOverviews())
    2555             :     {
    2556           0 :         return CE_Failure;
    2557             :     }
    2558             : 
    2559          17 :     CPLDebug("RMF", "Build overviews on dataset %d x %d size", GetRasterXSize(),
    2560             :              GetRasterYSize());
    2561             : 
    2562          17 :     GDALDataType eMainType = GetRasterBand(1)->GetRasterDataType();
    2563          17 :     RMFDataset *poParent = this;
    2564          17 :     double prevOvLevel = 1.0;
    2565          51 :     for (int n = 0; n != nOverviews; ++n)
    2566             :     {
    2567          34 :         int nOvLevel = panOverviewList[n];
    2568          34 :         const int nOXSize = DIV_ROUND_UP(GetRasterXSize(), nOvLevel);
    2569          34 :         const int nOYSize = DIV_ROUND_UP(GetRasterYSize(), nOvLevel);
    2570          34 :         CPLDebug("RMF", "\tCreate overview #%d size %d x %d", nOvLevel, nOXSize,
    2571             :                  nOYSize);
    2572             : 
    2573             :         RMFDataset *poOvrDataset;
    2574          34 :         poOvrDataset = static_cast<RMFDataset *>(RMFDataset::Create(
    2575             :             nullptr, nOXSize, nOYSize, GetRasterCount(), eMainType, nullptr,
    2576             :             poParent, nOvLevel / prevOvLevel));
    2577             : 
    2578          34 :         if (poOvrDataset == nullptr)
    2579             :         {
    2580           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2581             :                      "Can't create overview dataset #%d size %d x %d", nOvLevel,
    2582             :                      nOXSize, nOYSize);
    2583           0 :             return CE_Failure;
    2584             :         }
    2585             : 
    2586          34 :         prevOvLevel = nOvLevel;
    2587          34 :         poParent = poOvrDataset;
    2588          34 :         poOvrDatasets.push_back(poOvrDataset);
    2589             :     }
    2590             : 
    2591             :     GDALRasterBand ***papapoOverviewBands =
    2592          17 :         static_cast<GDALRasterBand ***>(CPLCalloc(sizeof(void *), nBandsIn));
    2593             :     GDALRasterBand **papoBandList =
    2594          17 :         static_cast<GDALRasterBand **>(CPLCalloc(sizeof(void *), nBandsIn));
    2595             : 
    2596          36 :     for (int iBand = 0; iBand < nBandsIn; ++iBand)
    2597             :     {
    2598          19 :         GDALRasterBand *poBand = GetRasterBand(panBandList[iBand]);
    2599             : 
    2600          19 :         papoBandList[iBand] = poBand;
    2601          38 :         papapoOverviewBands[iBand] = static_cast<GDALRasterBand **>(
    2602          19 :             CPLCalloc(sizeof(void *), poBand->GetOverviewCount()));
    2603             : 
    2604          57 :         for (int i = 0; i < nOverviews; ++i)
    2605             :         {
    2606          38 :             papapoOverviewBands[iBand][i] = poBand->GetOverview(i);
    2607             :         }
    2608             :     }
    2609             : #ifdef DEBUG
    2610          36 :     for (int iBand = 0; iBand < nBandsIn; ++iBand)
    2611             :     {
    2612          19 :         CPLDebug("RMF", "Try to create overview for #%d size %d x %d",
    2613          19 :                  iBand + 1, papoBandList[iBand]->GetXSize(),
    2614          19 :                  papoBandList[iBand]->GetYSize());
    2615          57 :         for (int i = 0; i < nOverviews; ++i)
    2616             :         {
    2617          38 :             CPLDebug("RMF", "\t%d x %d",
    2618          38 :                      papapoOverviewBands[iBand][i]->GetXSize(),
    2619          38 :                      papapoOverviewBands[iBand][i]->GetYSize());
    2620             :         }
    2621             :     }
    2622             : #endif  // DEBUG
    2623             :     CPLErr res;
    2624          17 :     res = GDALRegenerateOverviewsMultiBand(
    2625             :         nBandsIn, papoBandList, nOverviews, papapoOverviewBands, pszResampling,
    2626             :         pfnProgress, pProgressData, papszOptions);
    2627             : 
    2628          36 :     for (int iBand = 0; iBand < nBandsIn; ++iBand)
    2629             :     {
    2630          19 :         CPLFree(papapoOverviewBands[iBand]);
    2631             :     }
    2632             : 
    2633          17 :     CPLFree(papapoOverviewBands);
    2634          17 :     CPLFree(papoBandList);
    2635             : 
    2636          17 :     return res;
    2637             : }
    2638             : 
    2639          68 : CPLErr RMFDataset::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
    2640             :                              int nXSize, int nYSize, void *pData, int nBufXSize,
    2641             :                              int nBufYSize, GDALDataType eBufType,
    2642             :                              int nBandCount, BANDMAP_TYPE panBandMap,
    2643             :                              GSpacing nPixelSpace, GSpacing nLineSpace,
    2644             :                              GSpacing nBandSpace,
    2645             :                              GDALRasterIOExtraArg *psExtraArg)
    2646             : {
    2647             : #ifdef DEBUG
    2648          68 :     CPLDebug("RMF", "Dataset %p, %s %d %d %d %d, %d %d", this,
    2649             :              (eRWFlag == GF_Read ? "Read" : "Write"), nXOff, nYOff, nXSize,
    2650             :              nYSize, nBufXSize, nBufYSize);
    2651             : #endif  // DEBUG
    2652          68 :     if (eRWFlag == GF_Read && poCompressData != nullptr &&
    2653           0 :         poCompressData->oThreadPool.GetThreadCount() > 0)
    2654             :     {
    2655           0 :         poCompressData->oThreadPool.WaitCompletion();
    2656             :     }
    2657             : 
    2658          68 :     return GDALDataset::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize, pData,
    2659             :                                   nBufXSize, nBufYSize, eBufType, nBandCount,
    2660             :                                   panBandMap, nPixelSpace, nLineSpace,
    2661          68 :                                   nBandSpace, psExtraArg);
    2662             : }
    2663             : 
    2664         238 : vsi_l_offset RMFDataset::GetLastOffset() const
    2665             : {
    2666         238 :     vsi_l_offset nLastTileOff = 0;
    2667         238 :     GUInt32 nTiles(sHeader.nTileTblSize / sizeof(GUInt32));
    2668             : 
    2669         768 :     for (GUInt32 n = 0; n < nTiles; n += 2)
    2670             :     {
    2671         530 :         vsi_l_offset nTileOffset = GetFileOffset(paiTiles[n]);
    2672         530 :         GUInt32 nTileBytes = paiTiles[n + 1];
    2673         530 :         nLastTileOff = std::max(nLastTileOff, nTileOffset + nTileBytes);
    2674             :     }
    2675             : 
    2676         238 :     nLastTileOff = std::max(nLastTileOff, GetFileOffset(sHeader.nROIOffset) +
    2677         238 :                                               sHeader.nROISize);
    2678         238 :     nLastTileOff = std::max(nLastTileOff, GetFileOffset(sHeader.nClrTblOffset) +
    2679         238 :                                               sHeader.nClrTblSize);
    2680         238 :     nLastTileOff =
    2681         238 :         std::max(nLastTileOff,
    2682         238 :                  GetFileOffset(sHeader.nTileTblOffset) + sHeader.nTileTblSize);
    2683         238 :     nLastTileOff =
    2684         238 :         std::max(nLastTileOff, GetFileOffset(sHeader.nFlagsTblOffset) +
    2685         238 :                                    sHeader.nFlagsTblSize);
    2686         238 :     nLastTileOff = std::max(nLastTileOff, GetFileOffset(sHeader.nExtHdrOffset) +
    2687         238 :                                               sHeader.nExtHdrSize);
    2688         238 :     return nLastTileOff;
    2689             : }
    2690             : 
    2691          17 : CPLErr RMFDataset::CleanOverviews()
    2692             : {
    2693          17 :     if (sHeader.nOvrOffset == 0)
    2694             :     {
    2695          13 :         return CE_None;
    2696             :     }
    2697             : 
    2698           4 :     if (GetAccess() != GA_Update)
    2699             :     {
    2700           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    2701             :                  "File open for read-only accessing, "
    2702             :                  "overviews cleanup failed.");
    2703           0 :         return CE_Failure;
    2704             :     }
    2705             : 
    2706           4 :     if (poParentDS != nullptr)
    2707             :     {
    2708           0 :         CPLError(CE_Failure, CPLE_NotSupported,
    2709             :                  "Overviews cleanup for non-root dataset is not possible.");
    2710           0 :         return CE_Failure;
    2711             :     }
    2712             : 
    2713          12 :     for (size_t n = 0; n != poOvrDatasets.size(); ++n)
    2714             :     {
    2715           8 :         GDALClose(poOvrDatasets[n]);
    2716             :     }
    2717           4 :     poOvrDatasets.clear();
    2718             : 
    2719           4 :     vsi_l_offset nLastTileOff = GetLastOffset();
    2720             : 
    2721           4 :     if (0 != VSIFSeekL(fp, 0, SEEK_END))
    2722             :     {
    2723           0 :         CPLError(CE_Failure, CPLE_FileIO,
    2724             :                  "Failed to seek to end of file, "
    2725             :                  "overviews cleanup failed.");
    2726             :     }
    2727             : 
    2728           4 :     vsi_l_offset nFileSize = VSIFTellL(fp);
    2729           4 :     if (nFileSize < nLastTileOff)
    2730             :     {
    2731           0 :         CPLError(CE_Failure, CPLE_FileIO,
    2732             :                  "Invalid file offset, "
    2733             :                  "overviews cleanup failed.");
    2734           0 :         return CE_Failure;
    2735             :     }
    2736             : 
    2737           4 :     CPLDebug("RMF", "Truncate to " CPL_FRMT_GUIB, nLastTileOff);
    2738           4 :     CPLDebug("RMF", "File size:  " CPL_FRMT_GUIB, nFileSize);
    2739             : 
    2740           4 :     if (0 != VSIFTruncateL(fp, nLastTileOff))
    2741             :     {
    2742           0 :         CPLError(CE_Failure, CPLE_FileIO,
    2743             :                  "Failed to truncate file, "
    2744             :                  "overviews cleanup failed.");
    2745           0 :         return CE_Failure;
    2746             :     }
    2747             : 
    2748           4 :     sHeader.nOvrOffset = 0;
    2749           4 :     bHeaderDirty = true;
    2750             : 
    2751           4 :     return CE_None;
    2752             : }
    2753             : 
    2754             : /************************************************************************/
    2755             : /*                         GetCompressionType()                         */
    2756             : /************************************************************************/
    2757             : 
    2758          43 : GByte RMFDataset::GetCompressionType(const char *pszCompressName)
    2759             : {
    2760          43 :     if (pszCompressName == nullptr || EQUAL(pszCompressName, "NONE"))
    2761             :     {
    2762          35 :         return RMF_COMPRESSION_NONE;
    2763             :     }
    2764           8 :     else if (EQUAL(pszCompressName, "LZW"))
    2765             :     {
    2766           5 :         return RMF_COMPRESSION_LZW;
    2767             :     }
    2768           3 :     else if (EQUAL(pszCompressName, "JPEG"))
    2769             :     {
    2770           1 :         return RMF_COMPRESSION_JPEG;
    2771             :     }
    2772           2 :     else if (EQUAL(pszCompressName, "RMF_DEM"))
    2773             :     {
    2774           2 :         return RMF_COMPRESSION_DEM;
    2775             :     }
    2776             : 
    2777           0 :     CPLError(CE_Failure, CPLE_AppDefined,
    2778             :              "RMF: Unknown compression scheme <%s>.\n"
    2779             :              "Defaults to NONE compression.",
    2780             :              pszCompressName);
    2781           0 :     return RMF_COMPRESSION_NONE;
    2782             : }
    2783             : 
    2784             : /************************************************************************/
    2785             : /*                          SetupCompression()                          */
    2786             : /************************************************************************/
    2787             : 
    2788         243 : int RMFDataset::SetupCompression(GDALDataType eType, const char *pszFilename)
    2789             : {
    2790             :     /* -------------------------------------------------------------------- */
    2791             :     /*  XXX: The DEM compression method seems to be only applicable         */
    2792             :     /*  to Int32 data.                                                      */
    2793             :     /* -------------------------------------------------------------------- */
    2794         243 :     if (sHeader.iCompression == RMF_COMPRESSION_NONE)
    2795             :     {
    2796         173 :         Decompress = nullptr;
    2797         173 :         Compress = nullptr;
    2798             :     }
    2799          70 :     else if (sHeader.iCompression == RMF_COMPRESSION_LZW)
    2800             :     {
    2801          57 :         Decompress = &LZWDecompress;
    2802          57 :         Compress = &LZWCompress;
    2803          57 :         SetMetadataItem(GDALMD_COMPRESSION, "LZW", GDAL_MDD_IMAGE_STRUCTURE);
    2804             :     }
    2805          13 :     else if (sHeader.iCompression == RMF_COMPRESSION_JPEG)
    2806             :     {
    2807           3 :         if (eType != GDT_UInt8 || nBands != RMF_JPEG_BAND_COUNT ||
    2808           3 :             sHeader.nBitDepth != 24)
    2809             :         {
    2810           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2811             :                      "RMF support only 24 bpp JPEG compressed files.");
    2812           0 :             return CE_Failure;
    2813             :         }
    2814             : #ifdef HAVE_LIBJPEG
    2815           6 :         CPLString oBuf;
    2816           3 :         oBuf.Printf("%d", sHeader.iJpegQuality);
    2817           3 :         Decompress = &JPEGDecompress;
    2818           3 :         Compress = &JPEGCompress;
    2819           3 :         SetMetadataItem("JPEG_QUALITY", oBuf.c_str(), GDAL_MDD_IMAGE_STRUCTURE);
    2820           3 :         SetMetadataItem(GDALMD_COMPRESSION, "JPEG", GDAL_MDD_IMAGE_STRUCTURE);
    2821             : #else   // HAVE_LIBJPEG
    2822             :         CPLError(CE_Failure, CPLE_AppDefined,
    2823             :                  "JPEG codec is needed to open <%s>.\n"
    2824             :                  "Please rebuild GDAL with libjpeg support.",
    2825             :                  pszFilename);
    2826             :         return CE_Failure;
    2827             : #endif  // HAVE_LIBJPEG
    2828             :     }
    2829          10 :     else if (sHeader.iCompression == RMF_COMPRESSION_DEM &&
    2830          10 :              eType == GDT_Int32 && nBands == RMF_DEM_BAND_COUNT)
    2831             :     {
    2832          10 :         Decompress = &DEMDecompress;
    2833          10 :         Compress = &DEMCompress;
    2834          10 :         SetMetadataItem(GDALMD_COMPRESSION, "RMF_DEM",
    2835             :                         GDAL_MDD_IMAGE_STRUCTURE);
    2836             :     }
    2837             :     else
    2838             :     {
    2839           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2840           0 :                  "Unknown compression #%d at file <%s>.", sHeader.iCompression,
    2841             :                  pszFilename);
    2842           0 :         return CE_Failure;
    2843             :     }
    2844             : 
    2845         243 :     return CE_None;
    2846             : }
    2847             : 
    2848         190 : void RMFDataset::WriteTileJobFunc(void *pData)
    2849             : {
    2850         190 :     RMFCompressionJob *psJob = static_cast<RMFCompressionJob *>(pData);
    2851         190 :     RMFDataset *poDS = psJob->poDS;
    2852             : 
    2853             :     GByte *pabyTileData;
    2854             :     size_t nTileSize;
    2855             : 
    2856         190 :     if (poDS->Compress)
    2857             :     {
    2858             :         // RMF doesn't store compressed tiles with size greater than 80% of
    2859             :         // uncompressed size
    2860         131 :         GUInt32 nMaxCompressedTileSize =
    2861         131 :             static_cast<GUInt32>((psJob->nUncompressedBytes * 8) / 10);
    2862             :         size_t nCompressedBytes =
    2863         262 :             poDS->Compress(psJob->pabyUncompressedData,
    2864         131 :                            static_cast<GUInt32>(psJob->nUncompressedBytes),
    2865             :                            psJob->pabyCompressedData, nMaxCompressedTileSize,
    2866             :                            psJob->nXSize, psJob->nYSize, poDS);
    2867         131 :         if (nCompressedBytes == 0)
    2868             :         {
    2869          28 :             pabyTileData = psJob->pabyUncompressedData;
    2870          28 :             nTileSize = psJob->nUncompressedBytes;
    2871             :         }
    2872             :         else
    2873             :         {
    2874         103 :             pabyTileData = psJob->pabyCompressedData;
    2875         103 :             nTileSize = nCompressedBytes;
    2876             :         }
    2877             :     }
    2878             :     else
    2879             :     {
    2880          59 :         pabyTileData = psJob->pabyUncompressedData;
    2881          59 :         nTileSize = psJob->nUncompressedBytes;
    2882             :     }
    2883             : 
    2884             :     {
    2885         190 :         CPLMutexHolder oHolder(poDS->poCompressData->hWriteTileMutex);
    2886         190 :         psJob->eResult = poDS->WriteRawTile(
    2887             :             psJob->nBlockXOff, psJob->nBlockYOff, pabyTileData, nTileSize);
    2888             :     }
    2889         190 :     if (poDS->poCompressData->oThreadPool.GetThreadCount() > 0)
    2890             :     {
    2891         188 :         CPLMutexHolder oHolder(poDS->poCompressData->hReadyJobMutex);
    2892          94 :         poDS->poCompressData->asReadyJobs.push_back(psJob);
    2893             :     }
    2894         190 : }
    2895             : 
    2896          55 : CPLErr RMFDataset::InitCompressorData(CSLConstList papszParamList)
    2897             : {
    2898          55 :     const int nThreads = GDALGetNumThreads(papszParamList, "NUM_THREADS",
    2899             :                                            GDAL_DEFAULT_MAX_THREAD_COUNT,
    2900             :                                            /* bDefaultAllCPUs = */ false);
    2901             : 
    2902          55 :     poCompressData = std::make_shared<RMFCompressData>();
    2903          55 :     if (nThreads > 1)
    2904             :     {
    2905           3 :         if (!poCompressData->oThreadPool.Setup(nThreads, nullptr, nullptr))
    2906             :         {
    2907           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2908             :                      "Can't setup %d compressor threads", nThreads);
    2909           0 :             return CE_Failure;
    2910             :         }
    2911             :     }
    2912             : 
    2913          55 :     poCompressData->asJobs.resize(nThreads + 1);
    2914             : 
    2915          55 :     size_t nMaxTileBytes =
    2916          55 :         sHeader.nTileWidth * sHeader.nTileHeight * sHeader.nBitDepth / 8;
    2917             :     size_t nCompressBufferSize =
    2918          55 :         2 * nMaxTileBytes * poCompressData->asJobs.size();
    2919         110 :     poCompressData->pabyBuffers =
    2920          55 :         static_cast<GByte *>(VSIMalloc(nCompressBufferSize));
    2921             : 
    2922          55 :     CPLDebug("RMF", "Setup %d compressor threads and allocate %lu bytes buffer",
    2923             :              nThreads, static_cast<unsigned long>(nCompressBufferSize));
    2924          55 :     if (poCompressData->pabyBuffers == nullptr)
    2925             :     {
    2926           0 :         CPLError(CE_Failure, CPLE_OutOfMemory,
    2927             :                  "Can't allocate compress buffer of size %lu.",
    2928             :                  static_cast<unsigned long>(nCompressBufferSize));
    2929           0 :         return CE_Failure;
    2930             :     }
    2931             : 
    2932         174 :     for (size_t i = 0; i < poCompressData->asJobs.size(); ++i)
    2933             :     {
    2934         119 :         RMFCompressionJob &sJob(poCompressData->asJobs[i]);
    2935         119 :         sJob.pabyCompressedData =
    2936         119 :             poCompressData->pabyBuffers + 2 * i * nMaxTileBytes;
    2937         119 :         sJob.pabyUncompressedData = sJob.pabyCompressedData + nMaxTileBytes;
    2938         119 :         poCompressData->asReadyJobs.push_back(&sJob);
    2939             :     }
    2940             : 
    2941          55 :     if (nThreads > 1)
    2942             :     {
    2943           3 :         poCompressData->hReadyJobMutex = CPLCreateMutex();
    2944           3 :         CPLReleaseMutex(poCompressData->hReadyJobMutex);
    2945           3 :         poCompressData->hWriteTileMutex = CPLCreateMutex();
    2946           3 :         CPLReleaseMutex(poCompressData->hWriteTileMutex);
    2947             :     }
    2948             : 
    2949          55 :     return CE_None;
    2950             : }
    2951             : 
    2952         190 : CPLErr RMFDataset::WriteTile(int nBlockXOff, int nBlockYOff, GByte *pabyData,
    2953             :                              size_t nBytes, GUInt32 nRawXSize,
    2954             :                              GUInt32 nRawYSize)
    2955             : {
    2956         190 :     RMFCompressionJob *poJob = nullptr;
    2957         190 :     if (poCompressData == nullptr)
    2958             :     {
    2959           0 :         CPLError(CE_Failure, CPLE_AppDefined, "RMF: Compress data is null");
    2960           0 :         return CE_Failure;
    2961             :     }
    2962             : 
    2963         190 :     if (poCompressData->oThreadPool.GetThreadCount() > 0)
    2964             :     {
    2965          94 :         size_t nJobs(poCompressData->asJobs.size());
    2966             : 
    2967          94 :         poCompressData->oThreadPool.WaitCompletion(static_cast<int>(nJobs - 1));
    2968             : 
    2969         188 :         CPLMutexHolder oHolder(poCompressData->hReadyJobMutex);
    2970          94 :         CPLAssert(!poCompressData->asReadyJobs.empty());
    2971          94 :         poJob = poCompressData->asReadyJobs.front();
    2972          94 :         poCompressData->asReadyJobs.pop_front();
    2973             :     }
    2974             :     else
    2975             :     {
    2976          96 :         poJob = poCompressData->asReadyJobs.front();
    2977             :     }
    2978             : 
    2979         190 :     if (poJob->eResult != CE_None)
    2980             :     {
    2981             :         // One of the previous jobs is not done.
    2982             :         // Detailed debug message is already emitted from WriteRawTile
    2983           0 :         return poJob->eResult;
    2984             :     }
    2985         190 :     poJob->poDS = this;
    2986         190 :     poJob->eResult = CE_Failure;
    2987         190 :     poJob->nBlockXOff = nBlockXOff;
    2988         190 :     poJob->nBlockYOff = nBlockYOff;
    2989         190 :     poJob->nUncompressedBytes = nBytes;
    2990         190 :     poJob->nXSize = nRawXSize;
    2991         190 :     poJob->nYSize = nRawYSize;
    2992             : 
    2993         190 :     memcpy(poJob->pabyUncompressedData, pabyData, nBytes);
    2994             : 
    2995         190 :     if (poCompressData->oThreadPool.GetThreadCount() > 0)
    2996             :     {
    2997          94 :         if (!poCompressData->oThreadPool.SubmitJob(WriteTileJobFunc, poJob))
    2998             :         {
    2999           0 :             CPLError(CE_Failure, CPLE_NotSupported,
    3000             :                      "Can't submit job to thread pool.");
    3001           0 :             return CE_Failure;
    3002             :         }
    3003             :     }
    3004             :     else
    3005             :     {
    3006          96 :         WriteTileJobFunc(poJob);
    3007          96 :         if (poJob->eResult != CE_None)
    3008             :         {
    3009           0 :             return poJob->eResult;
    3010             :         }
    3011             :     }
    3012             : 
    3013         190 :     return CE_None;
    3014             : }
    3015             : 
    3016         190 : CPLErr RMFDataset::WriteRawTile(int nBlockXOff, int nBlockYOff, GByte *pabyData,
    3017             :                                 size_t nTileBytes)
    3018             : {
    3019         190 :     CPLAssert(nBlockXOff >= 0 && nBlockYOff >= 0 && pabyData != nullptr &&
    3020             :               nTileBytes > 0);
    3021             : 
    3022         190 :     const GUInt32 nTile = nBlockYOff * nXTiles + nBlockXOff;
    3023             : 
    3024         190 :     vsi_l_offset nTileOffset = GetFileOffset(paiTiles[2 * nTile]);
    3025         190 :     size_t nTileSize = static_cast<size_t>(paiTiles[2 * nTile + 1]);
    3026             : 
    3027         190 :     if (nTileOffset && nTileSize <= nTileBytes)
    3028             :     {
    3029           0 :         if (VSIFSeekL(fp, nTileOffset, SEEK_SET) < 0)
    3030             :         {
    3031           0 :             CPLError(
    3032             :                 CE_Failure, CPLE_FileIO,
    3033             :                 "Can't seek to offset %ld in output file to write data.\n%s",
    3034           0 :                 static_cast<long>(nTileOffset), VSIStrerror(errno));
    3035           0 :             return CE_Failure;
    3036             :         }
    3037             :     }
    3038             :     else
    3039             :     {
    3040         190 :         if (VSIFSeekL(fp, 0, SEEK_END) < 0)
    3041             :         {
    3042           0 :             CPLError(
    3043             :                 CE_Failure, CPLE_FileIO,
    3044             :                 "Can't seek to offset %ld in output file to write data.\n%s",
    3045           0 :                 static_cast<long>(nTileOffset), VSIStrerror(errno));
    3046           0 :             return CE_Failure;
    3047             :         }
    3048         190 :         nTileOffset = VSIFTellL(fp);
    3049         190 :         vsi_l_offset nNewTileOffset = 0;
    3050         190 :         paiTiles[2 * nTile] = GetRMFOffset(nTileOffset, &nNewTileOffset);
    3051             : 
    3052         190 :         if (nTileOffset != nNewTileOffset)
    3053             :         {
    3054          23 :             if (VSIFSeekL(fp, nNewTileOffset, SEEK_SET) < 0)
    3055             :             {
    3056           0 :                 CPLError(CE_Failure, CPLE_FileIO,
    3057             :                          "Can't seek to offset %ld in output file to "
    3058             :                          "write data.\n%s",
    3059           0 :                          static_cast<long>(nNewTileOffset), VSIStrerror(errno));
    3060           0 :                 return CE_Failure;
    3061             :             }
    3062             :         }
    3063         190 :         bHeaderDirty = true;
    3064             :     }
    3065             : 
    3066             : #ifdef CPL_MSB
    3067             :     // Compressed tiles are already with proper byte order
    3068             :     if (eRMFType == RMFT_MTW && sHeader.iCompression == RMF_COMPRESSION_NONE)
    3069             :     {
    3070             :         // Byte swap can be done in place
    3071             :         if (sHeader.nBitDepth == 16)
    3072             :         {
    3073             :             for (size_t i = 0; i < nTileBytes; i += 2)
    3074             :                 CPL_SWAP16PTR(pabyData + i);
    3075             :         }
    3076             :         else if (sHeader.nBitDepth == 32)
    3077             :         {
    3078             :             for (size_t i = 0; i < nTileBytes; i += 4)
    3079             :                 CPL_SWAP32PTR(pabyData + i);
    3080             :         }
    3081             :         else if (sHeader.nBitDepth == 64)
    3082             :         {
    3083             :             for (size_t i = 0; i < nTileBytes; i += 8)
    3084             :                 CPL_SWAPDOUBLE(pabyData + i);
    3085             :         }
    3086             :     }
    3087             : #endif
    3088             : 
    3089         190 :     bool bOk = (VSIFWriteL(pabyData, 1, nTileBytes, fp) == nTileBytes);
    3090             : 
    3091         190 :     if (!bOk)
    3092             :     {
    3093           0 :         CPLError(CE_Failure, CPLE_FileIO,
    3094             :                  "Can't write tile with X offset %d and Y offset %d.\n%s",
    3095           0 :                  nBlockXOff, nBlockYOff, VSIStrerror(errno));
    3096           0 :         return CE_Failure;
    3097             :     }
    3098             : 
    3099         190 :     paiTiles[2 * nTile + 1] = static_cast<GUInt32>(nTileBytes);
    3100         190 :     bHeaderDirty = true;
    3101             : 
    3102         190 :     return CE_None;
    3103             : }
    3104             : 
    3105         352 : CPLErr RMFDataset::ReadTile(int nBlockXOff, int nBlockYOff, GByte *pabyData,
    3106             :                             size_t nRawBytes, GUInt32 nRawXSize,
    3107             :                             GUInt32 nRawYSize, bool &bNullTile)
    3108             : {
    3109         352 :     bNullTile = false;
    3110             : 
    3111         352 :     const GUInt32 nTile = nBlockYOff * nXTiles + nBlockXOff;
    3112         352 :     if (2 * nTile + 1 >= sHeader.nTileTblSize / sizeof(GUInt32))
    3113             :     {
    3114           0 :         return CE_Failure;
    3115             :     }
    3116         352 :     vsi_l_offset nTileOffset = GetFileOffset(paiTiles[2 * nTile]);
    3117         352 :     GUInt32 nTileBytes = paiTiles[2 * nTile + 1];
    3118             :     // RMF doesn't store compressed tiles with size greater than 80% of
    3119             :     // uncompressed size. But just in case, select twice as many.
    3120         352 :     GUInt32 nMaxTileBytes =
    3121         352 :         2 * sHeader.nTileWidth * sHeader.nTileHeight * sHeader.nBitDepth / 8;
    3122             : 
    3123         352 :     if (nTileBytes >= nMaxTileBytes)
    3124             :     {
    3125           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    3126             :                  "Invalid tile size %lu at offset %ld. Must be less than %lu",
    3127             :                  static_cast<unsigned long>(nTileBytes),
    3128             :                  static_cast<long>(nTileOffset),
    3129             :                  static_cast<unsigned long>(nMaxTileBytes));
    3130           0 :         return CE_Failure;
    3131             :     }
    3132             : 
    3133         352 :     if (nTileOffset == 0)
    3134             :     {
    3135           1 :         bNullTile = true;
    3136           1 :         return CE_None;
    3137             :     }
    3138             : 
    3139             : #ifdef DEBUG
    3140         351 :     CPLDebug("RMF", "Read RawSize [%d, %d], nTileBytes %d, nRawBytes %d",
    3141             :              nRawXSize, nRawYSize, static_cast<int>(nTileBytes),
    3142             :              static_cast<int>(nRawBytes));
    3143             : #endif  // DEBUG
    3144             : 
    3145         351 :     if (VSIFSeekL(fp, nTileOffset, SEEK_SET) < 0)
    3146             :     {
    3147             :         // XXX: We will not report error here, because file just may be
    3148             :         // in update state and data for this block will be available later
    3149           0 :         if (eAccess == GA_Update)
    3150           0 :             return CE_None;
    3151             : 
    3152           0 :         CPLError(CE_Failure, CPLE_FileIO,
    3153             :                  "Can't seek to offset %ld in input file to read data.\n%s",
    3154           0 :                  static_cast<long>(nTileOffset), VSIStrerror(errno));
    3155           0 :         return CE_Failure;
    3156             :     }
    3157             : 
    3158         351 :     if (Decompress == nullptr || nTileBytes == nRawBytes)
    3159             :     {
    3160         166 :         if (nTileBytes != nRawBytes)
    3161             :         {
    3162           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    3163             :                      "RMF: Invalid tile size %lu, expected %lu",
    3164             :                      static_cast<unsigned long>(nTileBytes),
    3165             :                      static_cast<unsigned long>(nRawBytes));
    3166           0 :             return CE_Failure;
    3167             :         }
    3168             : 
    3169         166 :         if (VSIFReadL(pabyData, 1, nRawBytes, fp) < nRawBytes)
    3170             :         {
    3171           0 :             CPLError(CE_Failure, CPLE_FileIO,
    3172             :                      "RMF: Can't read at offset %lu from input file.\n%s",
    3173             :                      static_cast<unsigned long>(nTileOffset),
    3174           0 :                      VSIStrerror(errno));
    3175           0 :             return CE_Failure;
    3176             :         }
    3177             : 
    3178             : #ifdef CPL_MSB
    3179             :         if (eRMFType == RMFT_MTW)
    3180             :         {
    3181             :             if (sHeader.nBitDepth == 16)
    3182             :             {
    3183             :                 for (GUInt32 i = 0; i < nRawBytes; i += 2)
    3184             :                     CPL_SWAP16PTR(pabyData + i);
    3185             :             }
    3186             :             else if (sHeader.nBitDepth == 32)
    3187             :             {
    3188             :                 for (GUInt32 i = 0; i < nRawBytes; i += 4)
    3189             :                     CPL_SWAP32PTR(pabyData + i);
    3190             :             }
    3191             :             else if (sHeader.nBitDepth == 64)
    3192             :             {
    3193             :                 for (GUInt32 i = 0; i < nRawBytes; i += 8)
    3194             :                     CPL_SWAPDOUBLE(pabyData + i);
    3195             :             }
    3196             :         }
    3197             : #endif
    3198         166 :         return CE_None;
    3199             :     }
    3200             : 
    3201         185 :     if (pabyDecompressBuffer == nullptr)
    3202             :     {
    3203          21 :         pabyDecompressBuffer =
    3204          21 :             static_cast<GByte *>(VSIMalloc(std::max(1U, nMaxTileBytes)));
    3205          21 :         if (!pabyDecompressBuffer)
    3206             :         {
    3207           0 :             CPLError(CE_Failure, CPLE_OutOfMemory,
    3208             :                      "Can't allocate decompress buffer of size %lu.\n%s",
    3209             :                      static_cast<unsigned long>(nMaxTileBytes),
    3210           0 :                      VSIStrerror(errno));
    3211           0 :             return CE_Failure;
    3212             :         }
    3213             :     }
    3214             : 
    3215         185 :     if (VSIFReadL(pabyDecompressBuffer, 1, nTileBytes, fp) < nTileBytes)
    3216             :     {
    3217           0 :         CPLError(CE_Failure, CPLE_FileIO,
    3218             :                  "RMF: Can't read at offset %lu from input file.\n%s",
    3219           0 :                  static_cast<unsigned long>(nTileOffset), VSIStrerror(errno));
    3220           0 :         return CE_Failure;
    3221             :     }
    3222             : 
    3223             :     size_t nDecompressedSize =
    3224         185 :         Decompress(pabyDecompressBuffer, nTileBytes, pabyData,
    3225             :                    static_cast<GUInt32>(nRawBytes), nRawXSize, nRawYSize);
    3226             : 
    3227         185 :     if (nDecompressedSize != static_cast<size_t>(nRawBytes))
    3228             :     {
    3229           0 :         CPLError(CE_Failure, CPLE_FileIO,
    3230             :                  "Can't decompress tile xOff %d yOff %d. "
    3231             :                  "Raw tile size is %lu but decompressed is %lu. "
    3232             :                  "Compressed tile size is %lu",
    3233             :                  nBlockXOff, nBlockYOff, static_cast<unsigned long>(nRawBytes),
    3234             :                  static_cast<unsigned long>(nDecompressedSize),
    3235             :                  static_cast<unsigned long>(nTileBytes));
    3236           0 :         return CE_Failure;
    3237             :     }
    3238             :     // We don't need to swap bytes here,
    3239             :     // because decompressed data is in proper byte order
    3240         185 :     return CE_None;
    3241             : }
    3242             : 
    3243         277 : void RMFDataset::SetupNBits()
    3244             : {
    3245         277 :     int nBitDepth = 0;
    3246         277 :     if (sHeader.nBitDepth < 8 && nBands == 1)
    3247             :     {
    3248           6 :         nBitDepth = static_cast<int>(sHeader.nBitDepth);
    3249             :     }
    3250         271 :     else if (sHeader.nBitDepth == 16 && nBands == 3 && eRMFType == RMFT_RSW)
    3251             :     {
    3252           0 :         nBitDepth = 5;
    3253             :     }
    3254             : 
    3255         277 :     if (nBitDepth > 0)
    3256             :     {
    3257           6 :         char szNBits[32] = {};
    3258           6 :         snprintf(szNBits, sizeof(szNBits), "%d", nBitDepth);
    3259          12 :         for (int iBand = 1; iBand <= nBands; iBand++)
    3260             :         {
    3261           6 :             GetRasterBand(iBand)->SetMetadataItem(GDALMD_NBITS, szNBits,
    3262           6 :                                                   GDAL_MDD_IMAGE_STRUCTURE);
    3263             :         }
    3264             :     }
    3265         277 : }
    3266             : 
    3267             : /************************************************************************/
    3268             : /*                          GDALRegister_RMF()                          */
    3269             : /************************************************************************/
    3270             : 
    3271        2135 : void GDALRegister_RMF()
    3272             : 
    3273             : {
    3274        2135 :     if (GDALGetDriverByName("RMF") != nullptr)
    3275         263 :         return;
    3276             : 
    3277        1872 :     GDALDriver *poDriver = new GDALDriver();
    3278             : 
    3279        1872 :     poDriver->SetDescription("RMF");
    3280        1872 :     poDriver->SetMetadataItem(GDAL_DCAP_RASTER, "YES");
    3281        1872 :     poDriver->SetMetadataItem(GDAL_DMD_LONGNAME, "Raster Matrix Format");
    3282        1872 :     poDriver->SetMetadataItem(GDAL_DMD_HELPTOPIC, "drivers/raster/rmf.html");
    3283        1872 :     poDriver->SetMetadataItem(GDAL_DMD_EXTENSION, "rsw");
    3284        1872 :     poDriver->SetMetadataItem(GDAL_DMD_CREATIONDATATYPES,
    3285        1872 :                               "Byte Int16 Int32 Float64");
    3286        1872 :     poDriver->SetMetadataItem(
    3287             :         GDAL_DMD_CREATIONOPTIONLIST,
    3288             :         "<CreationOptionList>"
    3289             :         "   <Option name='MTW' type='boolean' description='Create MTW DEM "
    3290             :         "matrix'/>"
    3291             :         "   <Option name='BLOCKXSIZE' type='int' description='Tile Width'/>"
    3292             :         "   <Option name='BLOCKYSIZE' type='int' description='Tile Height'/>"
    3293             :         "   <Option name='RMFHUGE' type='string-select' description='Creation "
    3294             :         "of huge RMF file (Supported by GIS Panorama since v11)'>"
    3295             :         "     <Value>NO</Value>"
    3296             :         "     <Value>YES</Value>"
    3297             :         "     <Value>IF_SAFER</Value>"
    3298             :         "   </Option>"
    3299             :         "   <Option name='COMPRESS' type='string-select' default='NONE'>"
    3300             :         "     <Value>NONE</Value>"
    3301             :         "     <Value>LZW</Value>"
    3302             :         "     <Value>JPEG</Value>"
    3303             :         "     <Value>RMF_DEM</Value>"
    3304             :         "   </Option>"
    3305             :         "   <Option name='JPEG_QUALITY' type='int' description='JPEG quality "
    3306             :         "1-100' default='75'/>"
    3307             :         "   <Option name='NUM_THREADS' type='string' description='Number of "
    3308             :         "worker threads for compression. Can be set to ALL_CPUS' default='1'/>"
    3309        1872 :         "</CreationOptionList>");
    3310        1872 :     poDriver->SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");
    3311             : 
    3312        1872 :     poDriver->pfnIdentify = RMFDataset::Identify;
    3313        1872 :     poDriver->pfnOpen = RMFDataset::Open;
    3314        1872 :     poDriver->pfnCreate = RMFDataset::Create;
    3315        1872 :     poDriver->SetMetadataItem(
    3316             :         GDAL_DMD_OPENOPTIONLIST,
    3317             :         "<OpenOptionList>"
    3318             :         "  <Option name='RMF_SET_VERTCS' type='string' description='Layers "
    3319             :         "spatial reference will include vertical coordinate system description "
    3320             :         "if exist' default='NO'/>"
    3321        1872 :         "</OpenOptionList>");
    3322             : 
    3323        1872 :     GetGDALDriverManager()->RegisterDriver(poDriver);
    3324             : }
    3325             : 
    3326             : /************************************************************************/
    3327             : /*                           RMFCompressData                            */
    3328             : /************************************************************************/
    3329             : 
    3330          55 : RMFCompressData::RMFCompressData() : pabyBuffers(nullptr)
    3331             : {
    3332          55 : }
    3333             : 
    3334          55 : RMFCompressData::~RMFCompressData()
    3335             : {
    3336          55 :     if (pabyBuffers != nullptr)
    3337             :     {
    3338          55 :         VSIFree(pabyBuffers);
    3339             :     }
    3340             : 
    3341          55 :     if (hWriteTileMutex != nullptr)
    3342             :     {
    3343           3 :         CPLDestroyMutex(hWriteTileMutex);
    3344             :     }
    3345             : 
    3346          55 :     if (hReadyJobMutex != nullptr)
    3347             :     {
    3348           3 :         CPLDestroyMutex(hReadyJobMutex);
    3349             :     }
    3350          55 : }
    3351             : 
    3352             : GDALSuggestedBlockAccessPattern
    3353          21 : RMFRasterBand::GetSuggestedBlockAccessPattern() const
    3354             : {
    3355          21 :     return GSBAP_RANDOM;
    3356             : }
    3357             : 
    3358        1507 : CPLErr RMFDataset::SetMetadataItem(const char *pszName, const char *pszValue,
    3359             :                                    const char *pszDomain)
    3360             : {
    3361        1507 :     if (GetAccess() == GA_Update)
    3362             :     {
    3363         190 :         CPLDebug("RMF", "SetMetadataItem: %s=%s", pszName, pszValue);
    3364         190 :         if (EQUAL(pszName, MD_NAME_KEY))
    3365             :         {
    3366          20 :             memcpy(sHeader.byName, pszValue,
    3367             :                    CPLStrnlen(pszValue, RMF_NAME_SIZE));
    3368          20 :             bHeaderDirty = true;
    3369             :         }
    3370         170 :         else if (EQUAL(pszName, MD_SCALE_KEY) && CPLStrnlen(pszValue, 10) > 4)
    3371             :         {
    3372          20 :             sHeader.dfScale = atof(pszValue + 4);
    3373          20 :             sHeader.dfResolution = sHeader.dfScale / sHeader.dfPixelSize;
    3374          20 :             bHeaderDirty = true;
    3375             :         }
    3376         150 :         else if (EQUAL(pszName, MD_FRAME_KEY))
    3377             :         {
    3378           0 :             bHeaderDirty = true;
    3379             :         }
    3380             :     }
    3381        1507 :     return GDALDataset::SetMetadataItem(pszName, pszValue, pszDomain);
    3382             : }
    3383             : 
    3384          39 : CPLErr RMFDataset::SetMetadata(CSLConstList papszMetadata,
    3385             :                                const char *pszDomain)
    3386             : {
    3387          39 :     if (GetAccess() == GA_Update)
    3388             :     {
    3389          39 :         auto pszName = CSLFetchNameValue(papszMetadata, MD_NAME_KEY);
    3390          39 :         if (pszName != nullptr)
    3391             :         {
    3392          21 :             memcpy(sHeader.byName, pszName, CPLStrnlen(pszName, RMF_NAME_SIZE));
    3393          21 :             bHeaderDirty = true;
    3394             : 
    3395          21 :             CPLDebug("RMF", "SetMetadata: %s", pszName);
    3396             :         }
    3397          39 :         auto pszScale = CSLFetchNameValue(papszMetadata, MD_SCALE_KEY);
    3398          39 :         if (pszScale != nullptr && CPLStrnlen(pszScale, 10) > 4)
    3399             :         {
    3400          21 :             sHeader.dfScale = atof(pszScale + 4);
    3401          21 :             sHeader.dfResolution = sHeader.dfScale / sHeader.dfPixelSize;
    3402          21 :             bHeaderDirty = true;
    3403             : 
    3404          21 :             CPLDebug("RMF", "SetMetadata: %s", pszScale);
    3405             :         }
    3406          39 :         auto pszFrame = CSLFetchNameValue(papszMetadata, MD_FRAME_KEY);
    3407          39 :         if (pszFrame != nullptr)
    3408             :         {
    3409           2 :             bHeaderDirty = true;
    3410             : 
    3411           2 :             CPLDebug("RMF", "SetMetadata: %s", pszFrame);
    3412             :         }
    3413             :     }
    3414          39 :     return GDALDataset::SetMetadata(papszMetadata, pszDomain);
    3415             : }

Generated by: LCOV version 1.14