LCOV - code coverage report
Current view: top level - frmts/webp - webpdataset.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 385 520 74.0 %
Date: 2025-10-25 23:36:32 Functions: 21 22 95.5 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  GDAL WEBP Driver
       4             :  * Purpose:  Implement GDAL WEBP Support based on libwebp
       5             :  * Author:   Even Rouault, <even dot rouault at spatialys.com>
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2011-2013, Even Rouault <even dot rouault at spatialys.com>
       9             :  *
      10             :  * SPDX-License-Identifier: MIT
      11             :  ****************************************************************************/
      12             : 
      13             : #include "cpl_string.h"
      14             : #include "cpl_vsi_virtual.h"
      15             : #include "gdal_frmts.h"
      16             : #include "gdal_pam.h"
      17             : 
      18             : #include "webp_headers.h"
      19             : #include "webpdrivercore.h"
      20             : 
      21             : #include <limits>
      22             : 
      23             : /************************************************************************/
      24             : /* ==================================================================== */
      25             : /*                               WEBPDataset                            */
      26             : /* ==================================================================== */
      27             : /************************************************************************/
      28             : 
      29             : class WEBPRasterBand;
      30             : 
      31             : class WEBPDataset final : public GDALPamDataset
      32             : {
      33             :     friend class WEBPRasterBand;
      34             : 
      35             :     VSILFILE *fpImage;
      36             :     GByte *pabyUncompressed;
      37             :     int bHasBeenUncompressed;
      38             :     CPLErr eUncompressErrRet;
      39             :     CPLErr Uncompress();
      40             : 
      41             :     int bHasReadXMPMetadata;
      42             : 
      43             :     CPL_DISALLOW_COPY_ASSIGN(WEBPDataset)
      44             : 
      45             :     CPLErr GetGeoTransform(GDALGeoTransform &gt,
      46             :                            std::string &osWorldFilename) const;
      47             : 
      48             :   public:
      49             :     WEBPDataset();
      50             :     ~WEBPDataset() override;
      51             : 
      52             :     CPLErr Close() override;
      53             : 
      54             :     char **GetFileList() override;
      55             : 
      56             :     CPLErr GetGeoTransform(GDALGeoTransform &gt) const override;
      57             :     CPLErr IRasterIO(GDALRWFlag, int, int, int, int, void *, int, int,
      58             :                      GDALDataType, int, BANDMAP_TYPE, GSpacing nPixelSpace,
      59             :                      GSpacing nLineSpace, GSpacing nBandSpace,
      60             :                      GDALRasterIOExtraArg *psExtraArg) override;
      61             : 
      62             :     char **GetMetadataDomainList() override;
      63             :     char **GetMetadata(const char *pszDomain = "") override;
      64             : 
      65             :     CPLStringList GetCompressionFormats(int nXOff, int nYOff, int nXSize,
      66             :                                         int nYSize, int nBandCount,
      67             :                                         const int *panBandList) override;
      68             :     CPLErr ReadCompressedData(const char *pszFormat, int nXOff, int nYOff,
      69             :                               int nXSize, int nYSize, int nBandCount,
      70             :                               const int *panBandList, void **ppBuffer,
      71             :                               size_t *pnBufferSize,
      72             :                               char **ppszDetailedFormat) override;
      73             : 
      74             :     static GDALPamDataset *OpenPAM(GDALOpenInfo *poOpenInfo);
      75             :     static GDALDataset *Open(GDALOpenInfo *);
      76             :     static GDALDataset *CreateCopy(const char *pszFilename,
      77             :                                    GDALDataset *poSrcDS, int bStrict,
      78             :                                    char **papszOptions,
      79             :                                    GDALProgressFunc pfnProgress,
      80             :                                    void *pProgressData);
      81             : };
      82             : 
      83             : /************************************************************************/
      84             : /* ==================================================================== */
      85             : /*                            WEBPRasterBand                            */
      86             : /* ==================================================================== */
      87             : /************************************************************************/
      88             : 
      89             : class WEBPRasterBand final : public GDALPamRasterBand
      90             : {
      91             :     friend class WEBPDataset;
      92             : 
      93             :   public:
      94             :     WEBPRasterBand(WEBPDataset *, int);
      95             : 
      96             :     CPLErr IReadBlock(int, int, void *) override;
      97             :     GDALColorInterp GetColorInterpretation() override;
      98             : };
      99             : 
     100             : /************************************************************************/
     101             : /*                          WEBPRasterBand()                            */
     102             : /************************************************************************/
     103             : 
     104        1785 : WEBPRasterBand::WEBPRasterBand(WEBPDataset *poDSIn, int)
     105             : {
     106        1786 :     poDS = poDSIn;
     107             : 
     108        1786 :     eDataType = GDT_Byte;
     109             : 
     110        1786 :     nBlockXSize = poDSIn->nRasterXSize;
     111        1786 :     nBlockYSize = 1;
     112        1786 : }
     113             : 
     114             : /************************************************************************/
     115             : /*                             IReadBlock()                             */
     116             : /************************************************************************/
     117             : 
     118       11676 : CPLErr WEBPRasterBand::IReadBlock(CPL_UNUSED int nBlockXOff, int nBlockYOff,
     119             :                                   void *pImage)
     120             : {
     121       11676 :     WEBPDataset *poGDS = cpl::down_cast<WEBPDataset *>(poDS);
     122             : 
     123       11676 :     if (poGDS->Uncompress() != CE_None)
     124           0 :         return CE_Failure;
     125             : 
     126       11676 :     GByte *pabyUncompressed =
     127       11676 :         &poGDS->pabyUncompressed[nBlockYOff * nRasterXSize * poGDS->nBands +
     128       11676 :                                  nBand - 1];
     129     2885230 :     for (int i = 0; i < nRasterXSize; i++)
     130     2873560 :         reinterpret_cast<GByte *>(pImage)[i] =
     131     2873560 :             pabyUncompressed[poGDS->nBands * i];
     132             : 
     133       11676 :     return CE_None;
     134             : }
     135             : 
     136             : /************************************************************************/
     137             : /*                       GetColorInterpretation()                       */
     138             : /************************************************************************/
     139             : 
     140          87 : GDALColorInterp WEBPRasterBand::GetColorInterpretation()
     141             : 
     142             : {
     143          87 :     if (nBand == 1)
     144          28 :         return GCI_RedBand;
     145             : 
     146          59 :     else if (nBand == 2)
     147          28 :         return GCI_GreenBand;
     148             : 
     149          31 :     else if (nBand == 3)
     150          28 :         return GCI_BlueBand;
     151             : 
     152           3 :     return GCI_AlphaBand;
     153             : }
     154             : 
     155             : /************************************************************************/
     156             : /* ==================================================================== */
     157             : /*                             WEBPDataset                               */
     158             : /* ==================================================================== */
     159             : /************************************************************************/
     160             : 
     161             : /************************************************************************/
     162             : /*                            WEBPDataset()                              */
     163             : /************************************************************************/
     164             : 
     165         491 : WEBPDataset::WEBPDataset()
     166             :     : fpImage(nullptr), pabyUncompressed(nullptr), bHasBeenUncompressed(FALSE),
     167         491 :       eUncompressErrRet(CE_None), bHasReadXMPMetadata(FALSE)
     168             : {
     169         491 : }
     170             : 
     171             : /************************************************************************/
     172             : /*                           ~WEBPDataset()                             */
     173             : /************************************************************************/
     174             : 
     175         982 : WEBPDataset::~WEBPDataset()
     176             : 
     177             : {
     178         491 :     WEBPDataset::Close();
     179         491 :     VSIFree(pabyUncompressed);
     180         982 : }
     181             : 
     182             : /************************************************************************/
     183             : /*                                Close()                               */
     184             : /************************************************************************/
     185             : 
     186         621 : CPLErr WEBPDataset::Close()
     187             : {
     188         621 :     CPLErr eErr = CE_None;
     189             : 
     190         621 :     if (nOpenFlags != OPEN_FLAGS_CLOSED)
     191             :     {
     192         491 :         eErr = WEBPDataset::FlushCache(true);
     193             : 
     194         491 :         if (fpImage != nullptr && VSIFCloseL(fpImage) != 0)
     195           0 :             eErr = CE_Failure;
     196         491 :         fpImage = nullptr;
     197             : 
     198         491 :         eErr = GDAL::Combine(eErr, GDALPamDataset::Close());
     199             :     }
     200         621 :     return eErr;
     201             : }
     202             : 
     203             : /************************************************************************/
     204             : /*                               GetFileList()                          */
     205             : /************************************************************************/
     206             : 
     207           3 : char **WEBPDataset::GetFileList()
     208             : {
     209           3 :     char **papszFileList = GDALPamDataset::GetFileList();
     210           3 :     GDALGeoTransform gt;
     211           3 :     std::string osWorldFilename;
     212           3 :     CPL_IGNORE_RET_VAL(GetGeoTransform(gt, osWorldFilename));
     213           3 :     if (!osWorldFilename.empty())
     214             :     {
     215           1 :         papszFileList = CSLAddString(papszFileList, osWorldFilename.c_str());
     216             :     }
     217           6 :     return papszFileList;
     218             : }
     219             : 
     220             : /************************************************************************/
     221             : /*                            GetGeoTransform()                         */
     222             : /************************************************************************/
     223             : 
     224          19 : CPLErr WEBPDataset::GetGeoTransform(GDALGeoTransform &gt) const
     225             : {
     226          38 :     std::string osWorldFilename;
     227          38 :     return GetGeoTransform(gt, osWorldFilename);
     228             : }
     229             : 
     230          22 : CPLErr WEBPDataset::GetGeoTransform(GDALGeoTransform &gt,
     231             :                                     std::string &osWorldFilename) const
     232             : {
     233          22 :     bool bGeoTransformValid = GDALPamDataset::GetGeoTransform(gt) == CE_None;
     234          22 :     if (!bGeoTransformValid)
     235             :     {
     236          22 :         char *pszWldFilename = nullptr;
     237          22 :         bGeoTransformValid =
     238          22 :             GDALReadWorldFile2(GetDescription(), ".wld", gt,
     239          19 :                                oOvManager.GetSiblingFiles(), &pszWldFilename) ||
     240          19 :             GDALReadWorldFile2(GetDescription(), ".wpw", gt,
     241          41 :                                oOvManager.GetSiblingFiles(), &pszWldFilename) ||
     242          19 :             GDALReadWorldFile2(GetDescription(), ".webpw", gt,
     243             :                                oOvManager.GetSiblingFiles(), &pszWldFilename);
     244          22 :         if (bGeoTransformValid)
     245           3 :             osWorldFilename = pszWldFilename;
     246          22 :         CPLFree(pszWldFilename);
     247             :     }
     248          22 :     return bGeoTransformValid ? CE_None : CE_Failure;
     249             : }
     250             : 
     251             : /************************************************************************/
     252             : /*                      GetMetadataDomainList()                         */
     253             : /************************************************************************/
     254             : 
     255           1 : char **WEBPDataset::GetMetadataDomainList()
     256             : {
     257           1 :     return BuildMetadataDomainList(GDALPamDataset::GetMetadataDomainList(),
     258           1 :                                    TRUE, "xml:XMP", nullptr);
     259             : }
     260             : 
     261             : /************************************************************************/
     262             : /*                           GetMetadata()                              */
     263             : /************************************************************************/
     264             : 
     265          55 : char **WEBPDataset::GetMetadata(const char *pszDomain)
     266             : {
     267          55 :     if ((pszDomain != nullptr && EQUAL(pszDomain, "xml:XMP")) &&
     268           4 :         !bHasReadXMPMetadata)
     269             :     {
     270           4 :         bHasReadXMPMetadata = TRUE;
     271             : 
     272           4 :         VSIFSeekL(fpImage, 12, SEEK_SET);
     273             : 
     274           4 :         bool bFirst = true;
     275             :         while (true)
     276             :         {
     277             :             char szHeader[5];
     278             :             GUInt32 nChunkSize;
     279             : 
     280          16 :             if (VSIFReadL(szHeader, 1, 4, fpImage) != 4 ||
     281           8 :                 VSIFReadL(&nChunkSize, 1, 4, fpImage) != 4)
     282           4 :                 break;
     283             : 
     284           8 :             szHeader[4] = '\0';
     285           8 :             CPL_LSBPTR32(&nChunkSize);
     286             : 
     287           8 :             if (bFirst)
     288             :             {
     289           4 :                 if (strcmp(szHeader, "VP8X") != 0 || nChunkSize < 10)
     290             :                     break;
     291             : 
     292             :                 int l_nFlags;
     293           2 :                 if (VSIFReadL(&l_nFlags, 1, 4, fpImage) != 4)
     294           0 :                     break;
     295           2 :                 CPL_LSBPTR32(&l_nFlags);
     296           2 :                 if ((l_nFlags & 8) == 0)
     297           0 :                     break;
     298             : 
     299           2 :                 VSIFSeekL(fpImage, nChunkSize - 4, SEEK_CUR);
     300             : 
     301           2 :                 bFirst = false;
     302             :             }
     303           4 :             else if (strcmp(szHeader, "META") == 0)
     304             :             {
     305           2 :                 if (nChunkSize > 1024 * 1024)
     306           0 :                     break;
     307             : 
     308             :                 char *pszXMP =
     309           2 :                     reinterpret_cast<char *>(VSIMalloc(nChunkSize + 1));
     310           2 :                 if (pszXMP == nullptr)
     311           0 :                     break;
     312             : 
     313           2 :                 if (static_cast<GUInt32>(VSIFReadL(pszXMP, 1, nChunkSize,
     314           2 :                                                    fpImage)) != nChunkSize)
     315             :                 {
     316           0 :                     VSIFree(pszXMP);
     317           0 :                     break;
     318             :                 }
     319           2 :                 pszXMP[nChunkSize] = '\0';
     320             : 
     321             :                 /* Avoid setting the PAM dirty bit just for that */
     322           2 :                 const int nOldPamFlags = nPamFlags;
     323             : 
     324           2 :                 char *apszMDList[2] = {pszXMP, nullptr};
     325           2 :                 SetMetadata(apszMDList, "xml:XMP");
     326             : 
     327             :                 // cppcheck-suppress redundantAssignment
     328           2 :                 nPamFlags = nOldPamFlags;
     329             : 
     330           2 :                 VSIFree(pszXMP);
     331           2 :                 break;
     332             :             }
     333             :             else
     334           2 :                 VSIFSeekL(fpImage, nChunkSize, SEEK_CUR);
     335           4 :         }
     336             :     }
     337             : 
     338          55 :     return GDALPamDataset::GetMetadata(pszDomain);
     339             : }
     340             : 
     341             : /************************************************************************/
     342             : /*                            Uncompress()                              */
     343             : /************************************************************************/
     344             : 
     345       12011 : CPLErr WEBPDataset::Uncompress()
     346             : {
     347       12011 :     if (bHasBeenUncompressed)
     348       11654 :         return eUncompressErrRet;
     349             : 
     350         357 :     bHasBeenUncompressed = TRUE;
     351         357 :     eUncompressErrRet = CE_Failure;
     352             : 
     353             :     // To avoid excessive memory allocation attempts
     354             :     // Normally WebP images are no larger than 16383x16383*4 ~= 1 GB
     355         357 :     if (nRasterXSize > INT_MAX / (nRasterYSize * nBands))
     356             :     {
     357           0 :         CPLError(CE_Failure, CPLE_NotSupported, "Too large image");
     358           0 :         return CE_Failure;
     359             :     }
     360             : 
     361         357 :     pabyUncompressed = reinterpret_cast<GByte *>(
     362         357 :         VSIMalloc3(nRasterXSize, nRasterYSize, nBands));
     363         357 :     if (pabyUncompressed == nullptr)
     364           0 :         return CE_Failure;
     365             : 
     366         357 :     VSIFSeekL(fpImage, 0, SEEK_END);
     367         357 :     vsi_l_offset nSizeLarge = VSIFTellL(fpImage);
     368         357 :     if (nSizeLarge !=
     369         357 :         static_cast<vsi_l_offset>(static_cast<uint32_t>(nSizeLarge)))
     370           0 :         return CE_Failure;
     371         357 :     VSIFSeekL(fpImage, 0, SEEK_SET);
     372         357 :     uint32_t nSize = static_cast<uint32_t>(nSizeLarge);
     373         357 :     uint8_t *pabyCompressed = reinterpret_cast<uint8_t *>(VSIMalloc(nSize));
     374         357 :     if (pabyCompressed == nullptr)
     375           0 :         return CE_Failure;
     376         357 :     VSIFReadL(pabyCompressed, 1, nSize, fpImage);
     377             :     uint8_t *pRet;
     378             : 
     379         357 :     if (nBands == 4)
     380         234 :         pRet = WebPDecodeRGBAInto(pabyCompressed, static_cast<uint32_t>(nSize),
     381         234 :                                   static_cast<uint8_t *>(pabyUncompressed),
     382         234 :                                   static_cast<size_t>(nRasterXSize) *
     383         234 :                                       nRasterYSize * nBands,
     384         234 :                                   nRasterXSize * nBands);
     385             :     else
     386         123 :         pRet = WebPDecodeRGBInto(pabyCompressed, static_cast<uint32_t>(nSize),
     387         123 :                                  static_cast<uint8_t *>(pabyUncompressed),
     388         123 :                                  static_cast<size_t>(nRasterXSize) *
     389         123 :                                      nRasterYSize * nBands,
     390         123 :                                  nRasterXSize * nBands);
     391             : 
     392         357 :     VSIFree(pabyCompressed);
     393         357 :     if (pRet == nullptr)
     394             :     {
     395           0 :         CPLError(CE_Failure, CPLE_AppDefined, "WebPDecodeRGBInto() failed");
     396           0 :         return CE_Failure;
     397             :     }
     398         357 :     eUncompressErrRet = CE_None;
     399             : 
     400         357 :     return CE_None;
     401             : }
     402             : 
     403             : /************************************************************************/
     404             : /*                             IRasterIO()                              */
     405             : /************************************************************************/
     406             : 
     407         339 : CPLErr WEBPDataset::IRasterIO(GDALRWFlag eRWFlag, int nXOff, int nYOff,
     408             :                               int nXSize, int nYSize, void *pData,
     409             :                               int nBufXSize, int nBufYSize,
     410             :                               GDALDataType eBufType, int nBandCount,
     411             :                               BANDMAP_TYPE panBandMap, GSpacing nPixelSpace,
     412             :                               GSpacing nLineSpace, GSpacing nBandSpace,
     413             :                               GDALRasterIOExtraArg *psExtraArg)
     414             : 
     415             : {
     416         339 :     if ((eRWFlag == GF_Read) && (nBandCount == nBands) && (nXOff == 0) &&
     417         339 :         (nYOff == 0) && (nXSize == nBufXSize) && (nXSize == nRasterXSize) &&
     418         335 :         (nYSize == nBufYSize) && (nYSize == nRasterYSize) &&
     419        1013 :         (eBufType == GDT_Byte) && (pData != nullptr) &&
     420         335 :         IsAllBands(nBandCount, panBandMap))
     421             :     {
     422         335 :         if (Uncompress() != CE_None)
     423           0 :             return CE_Failure;
     424         335 :         if (nPixelSpace == nBands && nLineSpace == (nPixelSpace * nXSize) &&
     425             :             nBandSpace == 1)
     426             :         {
     427          95 :             memcpy(pData, pabyUncompressed,
     428          95 :                    static_cast<size_t>(nBands) * nXSize * nYSize);
     429             :         }
     430             :         else
     431             :         {
     432        8024 :             for (int y = 0; y < nYSize; ++y)
     433             :             {
     434        7784 :                 GByte *pabyScanline = pabyUncompressed + y * nBands * nXSize;
     435     1101290 :                 for (int x = 0; x < nXSize; ++x)
     436             :                 {
     437     5276670 :                     for (int iBand = 0; iBand < nBands; iBand++)
     438             :                         reinterpret_cast<GByte *>(
     439     4183170 :                             pData)[(y * nLineSpace) + (x * nPixelSpace) +
     440     4183170 :                                    iBand * nBandSpace] =
     441     4183170 :                             pabyScanline[x * nBands + iBand];
     442             :                 }
     443             :             }
     444             :         }
     445             : 
     446         335 :         return CE_None;
     447             :     }
     448             : 
     449           4 :     return GDALPamDataset::IRasterIO(eRWFlag, nXOff, nYOff, nXSize, nYSize,
     450             :                                      pData, nBufXSize, nBufYSize, eBufType,
     451             :                                      nBandCount, panBandMap, nPixelSpace,
     452           4 :                                      nLineSpace, nBandSpace, psExtraArg);
     453             : }
     454             : 
     455             : /************************************************************************/
     456             : /*                       GetCompressionFormats()                        */
     457             : /************************************************************************/
     458             : 
     459           0 : CPLStringList WEBPDataset::GetCompressionFormats(int nXOff, int nYOff,
     460             :                                                  int nXSize, int nYSize,
     461             :                                                  int nBandCount,
     462             :                                                  const int *panBandList)
     463             : {
     464           0 :     CPLStringList aosRet;
     465           0 :     if (nXOff == 0 && nYOff == 0 && nXSize == nRasterXSize &&
     466           0 :         nYSize == nRasterYSize && IsAllBands(nBandCount, panBandList))
     467             :     {
     468           0 :         aosRet.AddString("WEBP");
     469             :     }
     470           0 :     return aosRet;
     471             : }
     472             : 
     473             : /************************************************************************/
     474             : /*                       ReadCompressedData()                           */
     475             : /************************************************************************/
     476             : 
     477           2 : CPLErr WEBPDataset::ReadCompressedData(const char *pszFormat, int nXOff,
     478             :                                        int nYOff, int nXSize, int nYSize,
     479             :                                        int nBandCount, const int *panBandList,
     480             :                                        void **ppBuffer, size_t *pnBufferSize,
     481             :                                        char **ppszDetailedFormat)
     482             : {
     483           2 :     if (nXOff == 0 && nYOff == 0 && nXSize == nRasterXSize &&
     484           4 :         nYSize == nRasterYSize && IsAllBands(nBandCount, panBandList))
     485             :     {
     486           2 :         const CPLStringList aosTokens(CSLTokenizeString2(pszFormat, ";", 0));
     487           2 :         if (aosTokens.size() != 1)
     488           0 :             return CE_Failure;
     489             : 
     490           2 :         if (EQUAL(aosTokens[0], "WEBP"))
     491             :         {
     492           2 :             if (ppszDetailedFormat)
     493           0 :                 *ppszDetailedFormat = VSIStrdup("WEBP");
     494           2 :             VSIFSeekL(fpImage, 0, SEEK_END);
     495           2 :             const auto nFileSize = VSIFTellL(fpImage);
     496           2 :             if (nFileSize > std::numeric_limits<uint32_t>::max())
     497           0 :                 return CE_Failure;
     498           2 :             auto nSize = static_cast<uint32_t>(nFileSize);
     499           2 :             if (ppBuffer)
     500             :             {
     501           2 :                 if (!pnBufferSize)
     502           0 :                     return CE_Failure;
     503           2 :                 bool bFreeOnError = false;
     504           2 :                 if (*ppBuffer)
     505             :                 {
     506           0 :                     if (*pnBufferSize < nSize)
     507           0 :                         return CE_Failure;
     508             :                 }
     509             :                 else
     510             :                 {
     511           2 :                     *ppBuffer = VSI_MALLOC_VERBOSE(nSize);
     512           2 :                     if (*ppBuffer == nullptr)
     513           0 :                         return CE_Failure;
     514           2 :                     bFreeOnError = true;
     515             :                 }
     516           2 :                 VSIFSeekL(fpImage, 0, SEEK_SET);
     517           2 :                 if (VSIFReadL(*ppBuffer, nSize, 1, fpImage) != 1)
     518             :                 {
     519           0 :                     if (bFreeOnError)
     520             :                     {
     521           0 :                         VSIFree(*ppBuffer);
     522           0 :                         *ppBuffer = nullptr;
     523             :                     }
     524           0 :                     return CE_Failure;
     525             :                 }
     526             : 
     527             :                 // Remove META box
     528           2 :                 if (nSize > 12 && memcmp(*ppBuffer, "RIFF", 4) == 0)
     529             :                 {
     530           2 :                     size_t nPos = 12;
     531           2 :                     GByte *pabyData = static_cast<GByte *>(*ppBuffer);
     532           6 :                     while (nPos <= nSize - 8)
     533             :                     {
     534           4 :                         char szBoxName[5] = {0, 0, 0, 0, 0};
     535           4 :                         memcpy(szBoxName, pabyData + nPos, 4);
     536             :                         uint32_t nChunkSize;
     537           4 :                         memcpy(&nChunkSize, pabyData + nPos + 4, 4);
     538           4 :                         CPL_LSBPTR32(&nChunkSize);
     539           4 :                         if (nChunkSize % 2)  // Payload padding if needed
     540           1 :                             nChunkSize++;
     541           4 :                         if (nChunkSize > nSize - (nPos + 8))
     542           0 :                             break;
     543           4 :                         if (memcmp(szBoxName, "META", 4) == 0)
     544             :                         {
     545           1 :                             CPLDebug("WEBP",
     546             :                                      "Remove existing %s box from "
     547             :                                      "source compressed data",
     548             :                                      szBoxName);
     549           1 :                             if (nPos + 8 + nChunkSize < nSize)
     550             :                             {
     551           0 :                                 memmove(pabyData + nPos,
     552           0 :                                         pabyData + nPos + 8 + nChunkSize,
     553           0 :                                         nSize - (nPos + 8 + nChunkSize));
     554             :                             }
     555           1 :                             nSize -= 8 + nChunkSize;
     556             :                         }
     557             :                         else
     558             :                         {
     559           3 :                             nPos += 8 + nChunkSize;
     560             :                         }
     561             :                     }
     562             : 
     563             :                     // Patch size of RIFF
     564           2 :                     uint32_t nSize32 = nSize - 8;
     565           2 :                     CPL_LSBPTR32(&nSize32);
     566           2 :                     memcpy(pabyData + 4, &nSize32, 4);
     567             :                 }
     568             :             }
     569           2 :             if (pnBufferSize)
     570           2 :                 *pnBufferSize = nSize;
     571           2 :             return CE_None;
     572             :         }
     573             :     }
     574           0 :     return CE_Failure;
     575             : }
     576             : 
     577             : /************************************************************************/
     578             : /*                          OpenPAM()                                   */
     579             : /************************************************************************/
     580             : 
     581         491 : GDALPamDataset *WEBPDataset::OpenPAM(GDALOpenInfo *poOpenInfo)
     582             : 
     583             : {
     584         491 :     if (!WEBPDriverIdentify(poOpenInfo) || poOpenInfo->fpL == nullptr)
     585           0 :         return nullptr;
     586             : 
     587             :     int nWidth, nHeight;
     588         491 :     if (!WebPGetInfo(reinterpret_cast<const uint8_t *>(poOpenInfo->pabyHeader),
     589         491 :                      static_cast<uint32_t>(poOpenInfo->nHeaderBytes), &nWidth,
     590             :                      &nHeight))
     591           0 :         return nullptr;
     592             : 
     593         491 :     int nBands = 3;
     594             : 
     595         982 :     auto poDS = std::make_unique<WEBPDataset>();
     596             : 
     597             : #if WEBP_DECODER_ABI_VERSION >= 0x0002
     598             :     WebPDecoderConfig config;
     599         491 :     if (!WebPInitDecoderConfig(&config))
     600           0 :         return nullptr;
     601             : 
     602             :     const bool bOK =
     603         491 :         WebPGetFeatures(poOpenInfo->pabyHeader, poOpenInfo->nHeaderBytes,
     604         491 :                         &config.input) == VP8_STATUS_OK;
     605             : 
     606             :     // Cf commit https://github.com/webmproject/libwebp/commit/86c0031eb2c24f78d4dcfc5dab752ebc9f511607#diff-859d219dccb3163cc11cd538effed461ff0145135070abfe70bd263f16408023
     607             :     // Added in webp 0.4.0
     608             : #if WEBP_DECODER_ABI_VERSION >= 0x0202
     609         982 :     poDS->GDALDataset::SetMetadataItem(
     610             :         "COMPRESSION_REVERSIBILITY",
     611         491 :         config.input.format == 2 ? "LOSSLESS" : "LOSSY", "IMAGE_STRUCTURE");
     612             : #endif
     613             : 
     614         684 :     if (config.input.has_alpha ||
     615         194 :         CPLTestBool(CSLFetchNameValueDef(poOpenInfo->papszOpenOptions,
     616             :                                          "FORCE_4BANDS", "NO")))
     617         314 :         nBands = 4;
     618             : 
     619         490 :     WebPFreeDecBuffer(&config.output);
     620             : 
     621         490 :     if (!bOK)
     622           0 :         return nullptr;
     623             : 
     624             : #endif
     625             : 
     626         490 :     if (poOpenInfo->eAccess == GA_Update)
     627             :     {
     628           0 :         ReportUpdateNotSupportedByDriver("WEBP");
     629           0 :         return nullptr;
     630             :     }
     631             : 
     632             :     /* -------------------------------------------------------------------- */
     633             :     /*      Create a corresponding GDALDataset.                             */
     634             :     /* -------------------------------------------------------------------- */
     635         490 :     poDS->nRasterXSize = nWidth;
     636         491 :     poDS->nRasterYSize = nHeight;
     637         490 :     poDS->fpImage = poOpenInfo->fpL;
     638         491 :     poOpenInfo->fpL = nullptr;
     639             : 
     640             :     /* -------------------------------------------------------------------- */
     641             :     /*      Create band information objects.                                */
     642             :     /* -------------------------------------------------------------------- */
     643        2277 :     for (int iBand = 0; iBand < nBands; iBand++)
     644        1786 :         poDS->SetBand(iBand + 1, new WEBPRasterBand(poDS.get(), iBand + 1));
     645             : 
     646             :     /* -------------------------------------------------------------------- */
     647             :     /*      Initialize any PAM information.                                 */
     648             :     /* -------------------------------------------------------------------- */
     649         491 :     poDS->SetDescription(poOpenInfo->pszFilename);
     650             : 
     651         491 :     poDS->TryLoadXML(poOpenInfo->GetSiblingFiles());
     652             : 
     653             :     /* -------------------------------------------------------------------- */
     654             :     /*      Open overviews.                                                 */
     655             :     /* -------------------------------------------------------------------- */
     656         982 :     poDS->oOvManager.Initialize(poDS.get(), poOpenInfo->pszFilename,
     657         491 :                                 poOpenInfo->GetSiblingFiles());
     658             : 
     659         491 :     return poDS.release();
     660             : }
     661             : 
     662             : /************************************************************************/
     663             : /*                             Open()                                   */
     664             : /************************************************************************/
     665             : 
     666         383 : GDALDataset *WEBPDataset::Open(GDALOpenInfo *poOpenInfo)
     667             : 
     668             : {
     669         383 :     return OpenPAM(poOpenInfo);
     670             : }
     671             : 
     672             : /************************************************************************/
     673             : /*                              WebPUserData                            */
     674             : /************************************************************************/
     675             : 
     676             : typedef struct
     677             : {
     678             :     VSILFILE *fp;
     679             :     GDALProgressFunc pfnProgress;
     680             :     void *pProgressData;
     681             : } WebPUserData;
     682             : 
     683             : /************************************************************************/
     684             : /*                         WEBPDatasetWriter()                          */
     685             : /************************************************************************/
     686             : 
     687         861 : static int WEBPDatasetWriter(const uint8_t *data, size_t data_size,
     688             :                              const WebPPicture *const picture)
     689             : {
     690         861 :     WebPUserData *pUserData =
     691             :         reinterpret_cast<WebPUserData *>(picture->custom_ptr);
     692         861 :     return VSIFWriteL(data, 1, data_size, pUserData->fp) == data_size;
     693             : }
     694             : 
     695             : /************************************************************************/
     696             : /*                        WEBPDatasetProgressHook()                     */
     697             : /************************************************************************/
     698             : 
     699             : #if WEBP_ENCODER_ABI_VERSION >= 0x0100
     700        1071 : static int WEBPDatasetProgressHook(int percent,
     701             :                                    const WebPPicture *const picture)
     702             : {
     703        1071 :     WebPUserData *pUserData =
     704             :         reinterpret_cast<WebPUserData *>(picture->custom_ptr);
     705        1071 :     return pUserData->pfnProgress(percent / 100.0, nullptr,
     706        1071 :                                   pUserData->pProgressData);
     707             : }
     708             : #endif
     709             : 
     710             : /************************************************************************/
     711             : /*                              CreateCopy()                            */
     712             : /************************************************************************/
     713             : 
     714         135 : GDALDataset *WEBPDataset::CreateCopy(const char *pszFilename,
     715             :                                      GDALDataset *poSrcDS, int bStrict,
     716             :                                      char **papszOptions,
     717             :                                      GDALProgressFunc pfnProgress,
     718             :                                      void *pProgressData)
     719             : 
     720             : {
     721             :     const char *pszLossLessCopy =
     722         135 :         CSLFetchNameValueDef(papszOptions, "LOSSLESS_COPY", "AUTO");
     723         135 :     if (EQUAL(pszLossLessCopy, "AUTO") || CPLTestBool(pszLossLessCopy))
     724             :     {
     725         135 :         void *pWEBPContent = nullptr;
     726         135 :         size_t nWEBPContent = 0;
     727         135 :         if (poSrcDS->ReadCompressedData(
     728             :                 "WEBP", 0, 0, poSrcDS->GetRasterXSize(),
     729             :                 poSrcDS->GetRasterYSize(), poSrcDS->GetRasterCount(), nullptr,
     730         270 :                 &pWEBPContent, &nWEBPContent, nullptr) == CE_None)
     731             :         {
     732           2 :             CPLDebug("WEBP", "Lossless copy from source dataset");
     733           2 :             std::vector<GByte> abyData;
     734             :             try
     735             :             {
     736           2 :                 abyData.assign(static_cast<const GByte *>(pWEBPContent),
     737           2 :                                static_cast<const GByte *>(pWEBPContent) +
     738           2 :                                    nWEBPContent);
     739             : 
     740           2 :                 char **papszXMP = poSrcDS->GetMetadata("xml:XMP");
     741           2 :                 if (papszXMP && papszXMP[0])
     742             :                 {
     743             :                     GByte abyChunkHeader[8];
     744           1 :                     memcpy(abyChunkHeader, "META", 4);
     745           1 :                     const size_t nXMPSize = strlen(papszXMP[0]);
     746           1 :                     uint32_t nChunkSize = static_cast<uint32_t>(nXMPSize);
     747           1 :                     CPL_LSBPTR32(&nChunkSize);
     748           1 :                     memcpy(abyChunkHeader + 4, &nChunkSize, 4);
     749           0 :                     abyData.insert(abyData.end(), abyChunkHeader,
     750           1 :                                    abyChunkHeader + sizeof(abyChunkHeader));
     751             :                     abyData.insert(
     752           0 :                         abyData.end(), reinterpret_cast<GByte *>(papszXMP[0]),
     753           1 :                         reinterpret_cast<GByte *>(papszXMP[0]) + nXMPSize);
     754           1 :                     if ((abyData.size() % 2) != 0)  // Payload padding if needed
     755           1 :                         abyData.push_back(0);
     756             : 
     757             :                     // Patch size of RIFF
     758             :                     uint32_t nSize32 =
     759           1 :                         static_cast<uint32_t>(abyData.size()) - 8;
     760           1 :                     CPL_LSBPTR32(&nSize32);
     761           1 :                     memcpy(abyData.data() + 4, &nSize32, 4);
     762             :                 }
     763             :             }
     764           0 :             catch (const std::exception &e)
     765             :             {
     766           0 :                 CPLError(CE_Failure, CPLE_AppDefined, "Exception occurred: %s",
     767           0 :                          e.what());
     768           0 :                 abyData.clear();
     769             :             }
     770           2 :             VSIFree(pWEBPContent);
     771             : 
     772           2 :             if (!abyData.empty())
     773             :             {
     774             :                 auto fpImage(
     775           2 :                     CPLTestBool(CSLFetchNameValueDef(
     776             :                         papszOptions, "@CREATE_ONLY_VISIBLE_AT_CLOSE_TIME",
     777             :                         "NO"))
     778           0 :                         ? VSIFileManager::GetHandler(pszFilename)
     779             :                               ->CreateOnlyVisibleAtCloseTime(pszFilename, true,
     780           0 :                                                              nullptr)
     781           4 :                         : VSIFilesystemHandler::OpenStatic(pszFilename, "wb"));
     782           2 :                 if (fpImage == nullptr)
     783             :                 {
     784           0 :                     CPLError(CE_Failure, CPLE_OpenFailed,
     785             :                              "Unable to create jpeg file %s.", pszFilename);
     786             : 
     787           0 :                     return nullptr;
     788             :                 }
     789           4 :                 if (fpImage->Write(abyData.data(), 1, abyData.size()) !=
     790           2 :                     abyData.size())
     791             :                 {
     792           0 :                     CPLError(CE_Failure, CPLE_FileIO,
     793           0 :                              "Failure writing data: %s", VSIStrerror(errno));
     794           0 :                     fpImage->CancelCreation();
     795           0 :                     return nullptr;
     796             :                 }
     797             : 
     798           2 :                 if (fpImage->Close() != 0)
     799             :                 {
     800           0 :                     CPLError(CE_Failure, CPLE_FileIO,
     801             :                              "Error at file closing of '%s': %s", pszFilename,
     802           0 :                              VSIStrerror(errno));
     803           0 :                     return nullptr;
     804             :                 }
     805             : 
     806           2 :                 pfnProgress(1.0, nullptr, pProgressData);
     807             : 
     808             :                 // Re-open file and clone missing info to PAM
     809           2 :                 GDALOpenInfo oOpenInfo(pszFilename, GA_ReadOnly);
     810           2 :                 auto poDS = OpenPAM(&oOpenInfo);
     811           2 :                 if (poDS)
     812             :                 {
     813           2 :                     poDS->CloneInfo(poSrcDS, GCIF_PAM_DEFAULT);
     814             :                 }
     815             : 
     816           2 :                 return poDS;
     817             :             }
     818             :         }
     819             :     }
     820             : 
     821         133 :     const bool bLossless = CPLFetchBool(papszOptions, "LOSSLESS", false);
     822         257 :     if (!bLossless &&
     823         124 :         (!EQUAL(pszLossLessCopy, "AUTO") && CPLTestBool(pszLossLessCopy)))
     824             :     {
     825           0 :         CPLError(CE_Failure, CPLE_AppDefined,
     826             :                  "LOSSLESS_COPY=YES requested but not possible");
     827           0 :         return nullptr;
     828             :     }
     829             : 
     830             :     /* -------------------------------------------------------------------- */
     831             :     /*      WEBP library initialization                                     */
     832             :     /* -------------------------------------------------------------------- */
     833             : 
     834             :     WebPPicture sPicture;
     835         133 :     if (!WebPPictureInit(&sPicture))
     836             :     {
     837           0 :         CPLError(CE_Failure, CPLE_AppDefined, "WebPPictureInit() failed");
     838           0 :         return nullptr;
     839             :     }
     840             : 
     841             :     /* -------------------------------------------------------------------- */
     842             :     /*      Some some rudimentary checks                                    */
     843             :     /* -------------------------------------------------------------------- */
     844             : 
     845         133 :     const int nXSize = poSrcDS->GetRasterXSize();
     846         133 :     const int nYSize = poSrcDS->GetRasterYSize();
     847         133 :     if (nXSize > 16383 || nYSize > 16383)
     848             :     {
     849           0 :         CPLError(CE_Failure, CPLE_NotSupported,
     850             :                  "WEBP maximum image dimensions are 16383 x 16383.");
     851             : 
     852           0 :         return nullptr;
     853             :     }
     854             : 
     855         133 :     const int nBands = poSrcDS->GetRasterCount();
     856         133 :     if (nBands != 3
     857             : #if WEBP_ENCODER_ABI_VERSION >= 0x0100
     858          96 :         && nBands != 4
     859             : #endif
     860             :     )
     861             :     {
     862          14 :         CPLError(CE_Failure, CPLE_NotSupported,
     863             :                  "WEBP driver doesn't support %d bands. Must be 3 (RGB) "
     864             : #if WEBP_ENCODER_ABI_VERSION >= 0x0100
     865             :                  "or 4 (RGBA) "
     866             : #endif
     867             :                  "bands.",
     868             :                  nBands);
     869             : 
     870          14 :         return nullptr;
     871             :     }
     872             : 
     873         119 :     const GDALDataType eDT = poSrcDS->GetRasterBand(1)->GetRasterDataType();
     874             : 
     875         119 :     if (eDT != GDT_Byte)
     876             :     {
     877           0 :         CPLError((bStrict) ? CE_Failure : CE_Warning, CPLE_NotSupported,
     878             :                  "WEBP driver doesn't support data type %s. "
     879             :                  "Only eight bit byte bands supported.",
     880             :                  GDALGetDataTypeName(
     881             :                      poSrcDS->GetRasterBand(1)->GetRasterDataType()));
     882             : 
     883           0 :         if (bStrict)
     884           0 :             return nullptr;
     885             :     }
     886             : 
     887             :     /* -------------------------------------------------------------------- */
     888             :     /*      What options has the user selected?                             */
     889             :     /* -------------------------------------------------------------------- */
     890         119 :     float fQuality = 75.0f;
     891         119 :     const char *pszQUALITY = CSLFetchNameValue(papszOptions, "QUALITY");
     892         119 :     if (pszQUALITY != nullptr)
     893             :     {
     894          91 :         fQuality = static_cast<float>(CPLAtof(pszQUALITY));
     895          91 :         if (fQuality < 0.0f || fQuality > 100.0f)
     896             :         {
     897           0 :             CPLError(CE_Failure, CPLE_IllegalArg, "%s=%s is not a legal value.",
     898             :                      "QUALITY", pszQUALITY);
     899           0 :             return nullptr;
     900             :         }
     901             :     }
     902             : 
     903         119 :     WebPPreset nPreset = WEBP_PRESET_DEFAULT;
     904             :     const char *pszPRESET =
     905         119 :         CSLFetchNameValueDef(papszOptions, "PRESET", "DEFAULT");
     906         119 :     if (EQUAL(pszPRESET, "DEFAULT"))
     907         119 :         nPreset = WEBP_PRESET_DEFAULT;
     908           0 :     else if (EQUAL(pszPRESET, "PICTURE"))
     909           0 :         nPreset = WEBP_PRESET_PICTURE;
     910           0 :     else if (EQUAL(pszPRESET, "PHOTO"))
     911           0 :         nPreset = WEBP_PRESET_PHOTO;
     912           0 :     else if (EQUAL(pszPRESET, "PICTURE"))
     913           0 :         nPreset = WEBP_PRESET_PICTURE;
     914           0 :     else if (EQUAL(pszPRESET, "DRAWING"))
     915           0 :         nPreset = WEBP_PRESET_DRAWING;
     916           0 :     else if (EQUAL(pszPRESET, "ICON"))
     917           0 :         nPreset = WEBP_PRESET_ICON;
     918           0 :     else if (EQUAL(pszPRESET, "TEXT"))
     919           0 :         nPreset = WEBP_PRESET_TEXT;
     920             :     else
     921             :     {
     922           0 :         CPLError(CE_Failure, CPLE_IllegalArg, "%s=%s is not a legal value.",
     923             :                  "PRESET", pszPRESET);
     924           0 :         return nullptr;
     925             :     }
     926             : 
     927             :     WebPConfig sConfig;
     928         119 :     if (!WebPConfigInitInternal(&sConfig, nPreset, fQuality,
     929             :                                 WEBP_ENCODER_ABI_VERSION))
     930             :     {
     931           0 :         CPLError(CE_Failure, CPLE_AppDefined, "WebPConfigInit() failed");
     932           0 :         return nullptr;
     933             :     }
     934             : 
     935             :     // TODO: Get rid of this macro in a reasonable way.
     936             : #define FETCH_AND_SET_OPTION_INT(name, fieldname, minval, maxval)              \
     937             :     {                                                                          \
     938             :         const char *pszVal = CSLFetchNameValue(papszOptions, name);            \
     939             :         if (pszVal != nullptr)                                                 \
     940             :         {                                                                      \
     941             :             sConfig.fieldname = atoi(pszVal);                                  \
     942             :             if (sConfig.fieldname < minval || sConfig.fieldname > maxval)      \
     943             :             {                                                                  \
     944             :                 CPLError(CE_Failure, CPLE_IllegalArg,                          \
     945             :                          "%s=%s is not a legal value.", name, pszVal);         \
     946             :                 return nullptr;                                                \
     947             :             }                                                                  \
     948             :         }                                                                      \
     949             :     }
     950             : 
     951         119 :     FETCH_AND_SET_OPTION_INT("TARGETSIZE", target_size, 0, INT_MAX - 1);
     952             : 
     953         119 :     const char *pszPSNR = CSLFetchNameValue(papszOptions, "PSNR");
     954         119 :     if (pszPSNR)
     955             :     {
     956           0 :         sConfig.target_PSNR = static_cast<float>(CPLAtof(pszPSNR));
     957           0 :         if (sConfig.target_PSNR < 0)
     958             :         {
     959           0 :             CPLError(CE_Failure, CPLE_IllegalArg,
     960             :                      "PSNR=%s is not a legal value.", pszPSNR);
     961           0 :             return nullptr;
     962             :         }
     963             :     }
     964             : 
     965         119 :     FETCH_AND_SET_OPTION_INT("METHOD", method, 0, 6);
     966         119 :     FETCH_AND_SET_OPTION_INT("SEGMENTS", segments, 1, 4);
     967         119 :     FETCH_AND_SET_OPTION_INT("SNS_STRENGTH", sns_strength, 0, 100);
     968         119 :     FETCH_AND_SET_OPTION_INT("FILTER_STRENGTH", filter_strength, 0, 100);
     969         119 :     FETCH_AND_SET_OPTION_INT("FILTER_SHARPNESS", filter_sharpness, 0, 7);
     970         119 :     FETCH_AND_SET_OPTION_INT("FILTER_TYPE", filter_type, 0, 1);
     971         119 :     FETCH_AND_SET_OPTION_INT("AUTOFILTER", autofilter, 0, 1);
     972         119 :     FETCH_AND_SET_OPTION_INT("PASS", pass, 1, 10);
     973         119 :     FETCH_AND_SET_OPTION_INT("PREPROCESSING", preprocessing, 0, 1);
     974         119 :     FETCH_AND_SET_OPTION_INT("PARTITIONS", partitions, 0, 3);
     975             : #if WEBP_ENCODER_ABI_VERSION >= 0x0002
     976         119 :     FETCH_AND_SET_OPTION_INT("PARTITION_LIMIT", partition_limit, 0, 100);
     977             : #endif
     978             : #if WEBP_ENCODER_ABI_VERSION >= 0x0100
     979         119 :     sConfig.lossless = bLossless;
     980         119 :     if (sConfig.lossless)
     981           9 :         sPicture.use_argb = 1;
     982             : #endif
     983             : #if WEBP_ENCODER_ABI_VERSION >= 0x0209
     984         119 :     FETCH_AND_SET_OPTION_INT("EXACT", exact, 0, 1);
     985             : #endif
     986             : 
     987         119 :     if (!WebPValidateConfig(&sConfig))
     988             :     {
     989           0 :         CPLError(CE_Failure, CPLE_AppDefined, "WebPValidateConfig() failed");
     990           0 :         return nullptr;
     991             :     }
     992             : 
     993             :     /* -------------------------------------------------------------------- */
     994             :     /*      Allocate memory                                                 */
     995             :     /* -------------------------------------------------------------------- */
     996             :     GByte *pabyBuffer =
     997         119 :         static_cast<GByte *>(VSI_MALLOC3_VERBOSE(nBands, nXSize, nYSize));
     998         119 :     if (pabyBuffer == nullptr)
     999             :     {
    1000           0 :         return nullptr;
    1001             :     }
    1002             : 
    1003             :     /* -------------------------------------------------------------------- */
    1004             :     /*      Create the dataset.                                             */
    1005             :     /* -------------------------------------------------------------------- */
    1006             :     auto fpImage(
    1007         119 :         CPLTestBool(CSLFetchNameValueDef(
    1008             :             papszOptions, "@CREATE_ONLY_VISIBLE_AT_CLOSE_TIME", "NO"))
    1009           1 :             ? VSIFileManager::GetHandler(pszFilename)
    1010           1 :                   ->CreateOnlyVisibleAtCloseTime(pszFilename, true, nullptr)
    1011         239 :             : VSIFilesystemHandler::OpenStatic(pszFilename, "wb"));
    1012         119 :     if (fpImage == nullptr)
    1013             :     {
    1014           3 :         CPLError(CE_Failure, CPLE_OpenFailed,
    1015             :                  "Unable to create WEBP file %s.\n", pszFilename);
    1016           3 :         VSIFree(pabyBuffer);
    1017           3 :         return nullptr;
    1018             :     }
    1019             : 
    1020             :     WebPUserData sUserData;
    1021         116 :     sUserData.fp = fpImage.get();
    1022         116 :     sUserData.pfnProgress = pfnProgress ? pfnProgress : GDALDummyProgress;
    1023         116 :     sUserData.pProgressData = pProgressData;
    1024             : 
    1025             :     /* -------------------------------------------------------------------- */
    1026             :     /*      WEBP library settings                                           */
    1027             :     /* -------------------------------------------------------------------- */
    1028             : 
    1029         116 :     sPicture.width = nXSize;
    1030         116 :     sPicture.height = nYSize;
    1031         116 :     sPicture.writer = WEBPDatasetWriter;
    1032         116 :     sPicture.custom_ptr = &sUserData;
    1033             : #if WEBP_ENCODER_ABI_VERSION >= 0x0100
    1034         116 :     sPicture.progress_hook = WEBPDatasetProgressHook;
    1035             : #endif
    1036         116 :     if (!WebPPictureAlloc(&sPicture))
    1037             :     {
    1038           0 :         CPLError(CE_Failure, CPLE_AppDefined, "WebPPictureAlloc() failed");
    1039           0 :         VSIFree(pabyBuffer);
    1040           0 :         fpImage->CancelCreation();
    1041           0 :         return nullptr;
    1042             :     }
    1043             : 
    1044             :     /* -------------------------------------------------------------------- */
    1045             :     /*      Acquire source imagery.                                         */
    1046             :     /* -------------------------------------------------------------------- */
    1047             :     CPLErr eErr =
    1048         232 :         poSrcDS->RasterIO(GF_Read, 0, 0, nXSize, nYSize, pabyBuffer, nXSize,
    1049             :                           nYSize, GDT_Byte, nBands, nullptr, nBands,
    1050         116 :                           static_cast<GSpacing>(nBands) * nXSize, 1, nullptr);
    1051             : 
    1052             : /* -------------------------------------------------------------------- */
    1053             : /*      Import and write to file                                        */
    1054             : /* -------------------------------------------------------------------- */
    1055             : #if WEBP_ENCODER_ABI_VERSION >= 0x0100
    1056         116 :     if (eErr == CE_None && nBands == 4)
    1057             :     {
    1058          82 :         if (!WebPPictureImportRGBA(&sPicture, pabyBuffer, nBands * nXSize))
    1059             :         {
    1060           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    1061             :                      "WebPPictureImportRGBA() failed");
    1062           0 :             eErr = CE_Failure;
    1063             :         }
    1064             :     }
    1065             :     else
    1066             : #endif
    1067          68 :         if (eErr == CE_None &&
    1068          34 :             !WebPPictureImportRGB(&sPicture, pabyBuffer, nBands * nXSize))
    1069             :     {
    1070           0 :         CPLError(CE_Failure, CPLE_AppDefined, "WebPPictureImportRGB() failed");
    1071           0 :         eErr = CE_Failure;
    1072             :     }
    1073             : 
    1074         116 :     if (pfnProgress)
    1075         116 :         pfnProgress(0.5, "", pProgressData);
    1076             : 
    1077         116 :     if (eErr == CE_None && !WebPEncode(&sConfig, &sPicture))
    1078             :     {
    1079             : #if WEBP_ENCODER_ABI_VERSION >= 0x0100
    1080          10 :         const char *pszErrorMsg = nullptr;
    1081          10 :         switch (sPicture.error_code)
    1082             :         {
    1083           0 :             case VP8_ENC_ERROR_OUT_OF_MEMORY:
    1084           0 :                 pszErrorMsg = "Out of memory";
    1085           0 :                 break;
    1086           0 :             case VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY:
    1087           0 :                 pszErrorMsg = "Out of memory while flushing bits";
    1088           0 :                 break;
    1089           0 :             case VP8_ENC_ERROR_NULL_PARAMETER:
    1090           0 :                 pszErrorMsg = "A pointer parameter is NULL";
    1091           0 :                 break;
    1092           0 :             case VP8_ENC_ERROR_INVALID_CONFIGURATION:
    1093           0 :                 pszErrorMsg = "Configuration is invalid";
    1094           0 :                 break;
    1095           0 :             case VP8_ENC_ERROR_BAD_DIMENSION:
    1096           0 :                 pszErrorMsg = "Picture has invalid width/height";
    1097           0 :                 break;
    1098           0 :             case VP8_ENC_ERROR_PARTITION0_OVERFLOW:
    1099           0 :                 pszErrorMsg = "Partition is bigger than 512k. Try using less "
    1100             :                               "SEGMENTS, or increase PARTITION_LIMIT value";
    1101           0 :                 break;
    1102           0 :             case VP8_ENC_ERROR_PARTITION_OVERFLOW:
    1103           0 :                 pszErrorMsg = "Partition is bigger than 16M";
    1104           0 :                 break;
    1105           5 :             case VP8_ENC_ERROR_BAD_WRITE:
    1106           5 :                 pszErrorMsg = "Error while flushing bytes";
    1107           5 :                 break;
    1108           0 :             case VP8_ENC_ERROR_FILE_TOO_BIG:
    1109           0 :                 pszErrorMsg = "File is bigger than 4G";
    1110           0 :                 break;
    1111           0 :             case VP8_ENC_ERROR_USER_ABORT:
    1112           0 :                 pszErrorMsg = "User interrupted";
    1113           0 :                 break;
    1114           5 :             default:
    1115           5 :                 CPLError(CE_Failure, CPLE_AppDefined,
    1116             :                          "WebPEncode returned an unknown error code: %d",
    1117           5 :                          sPicture.error_code);
    1118           5 :                 pszErrorMsg = "Unknown WebP error type.";
    1119           5 :                 break;
    1120             :         }
    1121          10 :         CPLError(CE_Failure, CPLE_AppDefined, "WebPEncode() failed : %s",
    1122             :                  pszErrorMsg);
    1123             : #else
    1124             :         CPLError(CE_Failure, CPLE_AppDefined, "WebPEncode() failed");
    1125             : #endif
    1126          10 :         eErr = CE_Failure;
    1127             :     }
    1128             : 
    1129             :     /* -------------------------------------------------------------------- */
    1130             :     /*      Cleanup and close.                                              */
    1131             :     /* -------------------------------------------------------------------- */
    1132         116 :     CPLFree(pabyBuffer);
    1133             : 
    1134         116 :     WebPPictureFree(&sPicture);
    1135             : 
    1136         116 :     if (eErr == CE_None)
    1137             :     {
    1138         106 :         if (fpImage->Close() != 0)
    1139             :         {
    1140           0 :             CPLError(CE_Failure, CPLE_FileIO,
    1141             :                      "Error at file closing of '%s': %s", pszFilename,
    1142           0 :                      VSIStrerror(errno));
    1143           0 :             eErr = CE_Failure;
    1144             :         }
    1145             :     }
    1146             :     else
    1147             :     {
    1148          10 :         fpImage->CancelCreation();
    1149          10 :         fpImage.reset();
    1150             :     }
    1151             : 
    1152         116 :     if (pfnProgress)
    1153         116 :         pfnProgress(1.0, "", pProgressData);
    1154             : 
    1155         116 :     if (eErr != CE_None)
    1156             :     {
    1157          10 :         VSIUnlink(pszFilename);
    1158          10 :         return nullptr;
    1159             :     }
    1160             : 
    1161             :     // Do we need a world file?
    1162         106 :     if (CPLFetchBool(papszOptions, "WORLDFILE", false))
    1163             :     {
    1164           1 :         GDALGeoTransform gt;
    1165           1 :         poSrcDS->GetGeoTransform(gt);
    1166           1 :         GDALWriteWorldFile(pszFilename, "wld", gt.data());
    1167             :     }
    1168             : 
    1169             :     /* -------------------------------------------------------------------- */
    1170             :     /*      Re-open dataset, and copy any auxiliary pam information.        */
    1171             :     /* -------------------------------------------------------------------- */
    1172         212 :     GDALOpenInfo oOpenInfo(pszFilename, GA_ReadOnly);
    1173             : 
    1174             :     /* If writing to stdout, we can't reopen it, so return */
    1175             :     /* a fake dataset to make the caller happy */
    1176         106 :     CPLPushErrorHandler(CPLQuietErrorHandler);
    1177         106 :     auto poDS = WEBPDataset::OpenPAM(&oOpenInfo);
    1178         106 :     CPLPopErrorHandler();
    1179         106 :     if (poDS)
    1180             :     {
    1181         106 :         poDS->CloneInfo(poSrcDS, GCIF_PAM_DEFAULT);
    1182         106 :         return poDS;
    1183             :     }
    1184             : 
    1185           0 :     return nullptr;
    1186             : }
    1187             : 
    1188             : /************************************************************************/
    1189             : /*                         GDALRegister_WEBP()                          */
    1190             : /************************************************************************/
    1191             : 
    1192          12 : void GDALRegister_WEBP()
    1193             : 
    1194             : {
    1195          12 :     if (GDALGetDriverByName(DRIVER_NAME) != nullptr)
    1196           0 :         return;
    1197             : 
    1198          12 :     GDALDriver *poDriver = new GDALDriver();
    1199          12 :     WEBPDriverSetCommonMetadata(poDriver);
    1200             : 
    1201          12 :     poDriver->pfnOpen = WEBPDataset::Open;
    1202          12 :     poDriver->pfnCreateCopy = WEBPDataset::CreateCopy;
    1203             : 
    1204          12 :     GetGDALDriverManager()->RegisterDriver(poDriver);
    1205             : }

Generated by: LCOV version 1.14