LCOV - code coverage report
Current view: top level - frmts/gtiff - gt_overview.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 532 599 88.8 %
Date: 2025-05-06 02:01:45 Functions: 6 6 100.0 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  GeoTIFF Driver
       4             :  * Purpose:  Code to build overviews of external databases as a TIFF file.
       5             :  *           Only used by the GDALDefaultOverviews::BuildOverviews() method.
       6             :  * Author:   Frank Warmerdam, warmerdam@pobox.com
       7             :  *
       8             :  ******************************************************************************
       9             :  * Copyright (c) 2000, Frank Warmerdam
      10             :  * Copyright (c) 2008-2012, Even Rouault <even dot rouault at spatialys.com>
      11             :  *
      12             :  * SPDX-License-Identifier: MIT
      13             :  ****************************************************************************/
      14             : 
      15             : #include "cpl_port.h"
      16             : 
      17             : #include "gt_overview.h"
      18             : 
      19             : #include <cstdlib>
      20             : #include <cstring>
      21             : 
      22             : #include <algorithm>
      23             : #include <string>
      24             : 
      25             : #include "cpl_conv.h"
      26             : #include "cpl_error.h"
      27             : #include "cpl_progress.h"
      28             : #include "cpl_string.h"
      29             : #include "cpl_vsi.h"
      30             : #include "gdal.h"
      31             : #include "gdal_priv.h"
      32             : #include "gtiff.h"
      33             : #include "gtiffdataset.h"
      34             : #include "tiff.h"
      35             : #include "tiffvers.h"
      36             : #include "tifvsi.h"
      37             : #include "tif_jxl.h"
      38             : #include "xtiffio.h"
      39             : 
      40             : // TODO(schwehr): Explain why 128 and not 127.
      41             : constexpr int knMaxOverviews = 128;
      42             : 
      43             : /************************************************************************/
      44             : /*                         GTIFFWriteDirectory()                        */
      45             : /*                                                                      */
      46             : /*      Create a new directory, without any image data for an overview  */
      47             : /*      or a mask                                                       */
      48             : /*      Returns offset of newly created directory, but the              */
      49             : /*      current directory is reset to be the one in used when this      */
      50             : /*      function is called.                                             */
      51             : /************************************************************************/
      52             : 
      53         958 : toff_t GTIFFWriteDirectory(TIFF *hTIFF, int nSubfileType, int nXSize,
      54             :                            int nYSize, int nBitsPerPixel, int nPlanarConfig,
      55             :                            int nSamples, int nBlockXSize, int nBlockYSize,
      56             :                            int bTiled, int nCompressFlag, int nPhotometric,
      57             :                            int nSampleFormat, int nPredictor,
      58             :                            unsigned short *panRed, unsigned short *panGreen,
      59             :                            unsigned short *panBlue, int nExtraSamples,
      60             :                            unsigned short *panExtraSampleValues,
      61             :                            const char *pszMetadata, const char *pszJPEGQuality,
      62             :                            const char *pszJPEGTablesMode, const char *pszNoData,
      63             :                            const uint32_t *panLercAddCompressionAndVersion,
      64             :                            bool bDeferStrileArrayWriting)
      65             : 
      66             : {
      67         958 :     const toff_t nBaseDirOffset = TIFFCurrentDirOffset(hTIFF);
      68             : 
      69             : #if !(defined(INTERNAL_LIBTIFF) || TIFFLIB_VERSION > 20240911)
      70             :     // This is a bit of a hack to cause (*tif->tif_cleanup)(tif); to be
      71             :     // called. See https://trac.osgeo.org/gdal/ticket/2055
      72             :     // Fixed in libtiff > 4.7.0
      73             :     TIFFSetField(hTIFF, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
      74             :     TIFFFreeDirectory(hTIFF);
      75             : #endif
      76             : 
      77         958 :     TIFFCreateDirectory(hTIFF);
      78             : 
      79             :     /* -------------------------------------------------------------------- */
      80             :     /*      Setup TIFF fields.                                              */
      81             :     /* -------------------------------------------------------------------- */
      82         958 :     TIFFSetField(hTIFF, TIFFTAG_IMAGEWIDTH, nXSize);
      83         958 :     TIFFSetField(hTIFF, TIFFTAG_IMAGELENGTH, nYSize);
      84         958 :     if (nSamples == 1)
      85         594 :         TIFFSetField(hTIFF, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
      86             :     else
      87         364 :         TIFFSetField(hTIFF, TIFFTAG_PLANARCONFIG, nPlanarConfig);
      88             : 
      89         958 :     TIFFSetField(hTIFF, TIFFTAG_BITSPERSAMPLE, nBitsPerPixel);
      90         958 :     TIFFSetField(hTIFF, TIFFTAG_SAMPLESPERPIXEL, nSamples);
      91         958 :     TIFFSetField(hTIFF, TIFFTAG_COMPRESSION, nCompressFlag);
      92         958 :     TIFFSetField(hTIFF, TIFFTAG_PHOTOMETRIC, nPhotometric);
      93         958 :     TIFFSetField(hTIFF, TIFFTAG_SAMPLEFORMAT, nSampleFormat);
      94             : 
      95         958 :     if (bTiled)
      96             :     {
      97         917 :         TIFFSetField(hTIFF, TIFFTAG_TILEWIDTH, nBlockXSize);
      98         917 :         TIFFSetField(hTIFF, TIFFTAG_TILELENGTH, nBlockYSize);
      99             :     }
     100             :     else
     101             :     {
     102          41 :         TIFFSetField(hTIFF, TIFFTAG_ROWSPERSTRIP, nBlockYSize);
     103             :     }
     104             : 
     105         958 :     TIFFSetField(hTIFF, TIFFTAG_SUBFILETYPE, nSubfileType);
     106             : 
     107         958 :     if (panExtraSampleValues != nullptr)
     108             :     {
     109         115 :         TIFFSetField(hTIFF, TIFFTAG_EXTRASAMPLES, nExtraSamples,
     110             :                      panExtraSampleValues);
     111             :     }
     112             : 
     113         958 :     if (GTIFFSupportsPredictor(nCompressFlag))
     114         390 :         TIFFSetField(hTIFF, TIFFTAG_PREDICTOR, nPredictor);
     115             : 
     116             :     /* -------------------------------------------------------------------- */
     117             :     /*      Write color table if one is present.                            */
     118             :     /* -------------------------------------------------------------------- */
     119         958 :     if (panRed != nullptr)
     120             :     {
     121          18 :         TIFFSetField(hTIFF, TIFFTAG_COLORMAP, panRed, panGreen, panBlue);
     122             :     }
     123             : 
     124             :     /* -------------------------------------------------------------------- */
     125             :     /*      Write metadata if we have some.                                 */
     126             :     /* -------------------------------------------------------------------- */
     127         958 :     if (pszMetadata && strlen(pszMetadata) > 0)
     128         641 :         TIFFSetField(hTIFF, TIFFTAG_GDAL_METADATA, pszMetadata);
     129             : 
     130             :     /* -------------------------------------------------------------------- */
     131             :     /*      Write JPEG tables if needed.                                    */
     132             :     /* -------------------------------------------------------------------- */
     133         958 :     if (nCompressFlag == COMPRESSION_JPEG)
     134             :     {
     135         113 :         GTiffWriteJPEGTables(hTIFF,
     136             :                              (nPhotometric == PHOTOMETRIC_RGB) ? "RGB"
     137             :                              : (nPhotometric == PHOTOMETRIC_YCBCR)
     138          54 :                                  ? "YCBCR"
     139             :                                  : "MINISBLACK",
     140             :                              pszJPEGQuality, pszJPEGTablesMode);
     141             : 
     142          59 :         if (nPhotometric == PHOTOMETRIC_YCBCR)
     143             :         {
     144             :             // Explicitly register the subsampling so that JPEGFixupTags
     145             :             // is a no-op (helps for cloud optimized geotiffs)
     146          46 :             TIFFSetField(hTIFF, TIFFTAG_YCBCRSUBSAMPLING, 2, 2);
     147             :         }
     148             :     }
     149             : 
     150         958 :     if (nCompressFlag == COMPRESSION_LERC && panLercAddCompressionAndVersion)
     151             :     {
     152          48 :         TIFFSetField(hTIFF, TIFFTAG_LERC_PARAMETERS, 2,
     153             :                      panLercAddCompressionAndVersion);
     154             :     }
     155             : 
     156             :     /* -------------------------------------------------------------------- */
     157             :     /*      Write no data value if we have one.                             */
     158             :     /* -------------------------------------------------------------------- */
     159         958 :     if (pszNoData != nullptr)
     160             :     {
     161          40 :         TIFFSetField(hTIFF, TIFFTAG_GDAL_NODATA, pszNoData);
     162             :     }
     163             : 
     164         958 :     if (bDeferStrileArrayWriting)
     165             :     {
     166         186 :         TIFFDeferStrileArrayWriting(hTIFF);
     167             :     }
     168             : 
     169             :     /* -------------------------------------------------------------------- */
     170             :     /*      Write directory, and return byte offset.                        */
     171             :     /* -------------------------------------------------------------------- */
     172         958 :     if (TIFFWriteCheck(hTIFF, bTiled, "GTIFFWriteDirectory") == 0)
     173             :     {
     174           0 :         TIFFSetSubDirectory(hTIFF, nBaseDirOffset);
     175           0 :         return 0;
     176             :     }
     177             : 
     178         958 :     TIFFWriteDirectory(hTIFF);
     179         958 :     const tdir_t nNumberOfDirs = TIFFNumberOfDirectories(hTIFF);
     180         958 :     if (nNumberOfDirs > 0)  // always true, but to please Coverity
     181             :     {
     182         958 :         TIFFSetDirectory(hTIFF, static_cast<tdir_t>(nNumberOfDirs - 1));
     183             :     }
     184             : 
     185         958 :     const toff_t nOffset = TIFFCurrentDirOffset(hTIFF);
     186             : 
     187         958 :     TIFFSetSubDirectory(hTIFF, nBaseDirOffset);
     188             : 
     189         958 :     return nOffset;
     190             : }
     191             : 
     192             : /************************************************************************/
     193             : /*                     GTIFFBuildOverviewMetadata()                     */
     194             : /************************************************************************/
     195             : 
     196         519 : void GTIFFBuildOverviewMetadata(const char *pszResampling,
     197             :                                 GDALDataset *poBaseDS, bool bIsForMaskBand,
     198             :                                 CPLString &osMetadata)
     199             : 
     200             : {
     201         519 :     osMetadata = "<GDALMetadata>";
     202             : 
     203        1038 :     auto osNormalizedResampling = GDALGetNormalizedOvrResampling(pszResampling);
     204         519 :     if (!osNormalizedResampling.empty())
     205             :     {
     206         426 :         osMetadata += "<Item name=\"RESAMPLING\" sample=\"0\">";
     207         426 :         osMetadata += osNormalizedResampling;
     208         426 :         osMetadata += "</Item>";
     209             :     }
     210             : 
     211         519 :     if (bIsForMaskBand)
     212             :     {
     213          11 :         osMetadata += "<Item name=\"INTERNAL_MASK_FLAGS_1\">2</Item>";
     214             :     }
     215         508 :     else if (poBaseDS->GetMetadataItem("INTERNAL_MASK_FLAGS_1"))
     216             :     {
     217           0 :         for (int iBand = 0; iBand < 200; iBand++)
     218             :         {
     219           0 :             CPLString osItem;
     220           0 :             CPLString osName;
     221             : 
     222           0 :             osName.Printf("INTERNAL_MASK_FLAGS_%d", iBand + 1);
     223           0 :             if (poBaseDS->GetMetadataItem(osName))
     224             :             {
     225             :                 osItem.Printf("<Item name=\"%s\">%s</Item>", osName.c_str(),
     226           0 :                               poBaseDS->GetMetadataItem(osName));
     227           0 :                 osMetadata += osItem;
     228             :             }
     229             :         }
     230             :     }
     231             : 
     232         519 :     const char *pszNoDataValues = poBaseDS->GetMetadataItem("NODATA_VALUES");
     233         519 :     if (pszNoDataValues)
     234             :     {
     235          12 :         CPLString osItem;
     236             :         osItem.Printf("<Item name=\"NODATA_VALUES\">%s</Item>",
     237           6 :                       pszNoDataValues);
     238           6 :         osMetadata += osItem;
     239             :     }
     240             : 
     241         519 :     if (!EQUAL(osMetadata, "<GDALMetadata>"))
     242         426 :         osMetadata += "</GDALMetadata>";
     243             :     else
     244          93 :         osMetadata = "";
     245         519 : }
     246             : 
     247             : /************************************************************************/
     248             : /*                      GTIFFGetMaxColorChannels()                      */
     249             : /************************************************************************/
     250             : 
     251             : /*
     252             :  * Return the maximum number of color channels specified for a given photometric
     253             :  * type. 0 is returned if photometric type isn't supported or no default value
     254             :  * is defined by the specification.
     255             :  */
     256         219 : static int GTIFFGetMaxColorChannels(int photometric)
     257             : {
     258         219 :     switch (photometric)
     259             :     {
     260         157 :         case PHOTOMETRIC_PALETTE:
     261             :         case PHOTOMETRIC_MINISWHITE:
     262             :         case PHOTOMETRIC_MINISBLACK:
     263         157 :             return 1;
     264          62 :         case PHOTOMETRIC_YCBCR:
     265             :         case PHOTOMETRIC_RGB:
     266             :         case PHOTOMETRIC_CIELAB:
     267             :         case PHOTOMETRIC_LOGLUV:
     268             :         case PHOTOMETRIC_ITULAB:
     269             :         case PHOTOMETRIC_ICCLAB:
     270          62 :             return 3;
     271           0 :         case PHOTOMETRIC_SEPARATED:
     272             :         case PHOTOMETRIC_MASK:
     273           0 :             return 4;
     274           0 :         case PHOTOMETRIC_LOGL:
     275             :         default:
     276           0 :             return 0;
     277             :     }
     278             : }
     279             : 
     280             : /************************************************************************/
     281             : /*                        GTIFFBuildOverviews()                         */
     282             : /************************************************************************/
     283             : 
     284         181 : CPLErr GTIFFBuildOverviews(const char *pszFilename, int nBands,
     285             :                            GDALRasterBand *const *papoBandList, int nOverviews,
     286             :                            const int *panOverviewList,
     287             :                            const char *pszResampling,
     288             :                            GDALProgressFunc pfnProgress, void *pProgressData,
     289             :                            CSLConstList papszOptions)
     290             : 
     291             : {
     292         181 :     return GTIFFBuildOverviewsEx(pszFilename, nBands, papoBandList, nOverviews,
     293             :                                  panOverviewList, nullptr, pszResampling,
     294         181 :                                  papszOptions, pfnProgress, pProgressData);
     295             : }
     296             : 
     297         228 : CPLErr GTIFFBuildOverviewsEx(const char *pszFilename, int nBands,
     298             :                              GDALRasterBand *const *papoBandList,
     299             :                              int nOverviews, const int *panOverviewList,
     300             :                              const std::pair<int, int> *pasOverviewSize,
     301             :                              const char *pszResampling,
     302             :                              const char *const *papszOptions,
     303             :                              GDALProgressFunc pfnProgress, void *pProgressData)
     304             : {
     305         228 :     if (nBands == 0 || nOverviews == 0)
     306           5 :         return CE_None;
     307             : 
     308         223 :     CPLAssert((panOverviewList != nullptr) ^ (pasOverviewSize != nullptr));
     309             : 
     310         223 :     GTiffOneTimeInit();
     311             : 
     312         223 :     TIFF *hOTIFF = nullptr;
     313         223 :     int nBitsPerPixel = 0;
     314         223 :     int nCompression = COMPRESSION_NONE;
     315         223 :     uint16_t nPhotometric = 0;
     316         223 :     int nSampleFormat = 0;
     317         223 :     uint16_t nPlanarConfig = 0;
     318         223 :     int iOverview = 0;
     319         223 :     int nXSize = 0;
     320         223 :     int nYSize = 0;
     321             : 
     322             :     /* -------------------------------------------------------------------- */
     323             :     /*      Verify that the list of bands is suitable for emitting in       */
     324             :     /*      TIFF file.                                                      */
     325             :     /* -------------------------------------------------------------------- */
     326         598 :     for (int iBand = 0; iBand < nBands; iBand++)
     327             :     {
     328         375 :         int nBandBits = 0;
     329         375 :         int nBandFormat = 0;
     330         375 :         GDALRasterBand *hBand = papoBandList[iBand];
     331             : 
     332         375 :         switch (hBand->GetRasterDataType())
     333             :         {
     334         315 :             case GDT_Byte:
     335         315 :                 nBandBits = 8;
     336         315 :                 nBandFormat = SAMPLEFORMAT_UINT;
     337         315 :                 break;
     338             : 
     339           0 :             case GDT_Int8:
     340           0 :                 nBandBits = 8;
     341           0 :                 nBandFormat = SAMPLEFORMAT_INT;
     342           0 :                 break;
     343             : 
     344           4 :             case GDT_UInt16:
     345           4 :                 nBandBits = 16;
     346           4 :                 nBandFormat = SAMPLEFORMAT_UINT;
     347           4 :                 break;
     348             : 
     349          10 :             case GDT_Int16:
     350          10 :                 nBandBits = 16;
     351          10 :                 nBandFormat = SAMPLEFORMAT_INT;
     352          10 :                 break;
     353             : 
     354           2 :             case GDT_UInt32:
     355           2 :                 nBandBits = 32;
     356           2 :                 nBandFormat = SAMPLEFORMAT_UINT;
     357           2 :                 break;
     358             : 
     359           3 :             case GDT_Int32:
     360           3 :                 nBandBits = 32;
     361           3 :                 nBandFormat = SAMPLEFORMAT_INT;
     362           3 :                 break;
     363             : 
     364           1 :             case GDT_UInt64:
     365           1 :                 nBandBits = 64;
     366           1 :                 nBandFormat = SAMPLEFORMAT_UINT;
     367           1 :                 break;
     368             : 
     369           1 :             case GDT_Int64:
     370           1 :                 nBandBits = 64;
     371           1 :                 nBandFormat = SAMPLEFORMAT_INT;
     372           1 :                 break;
     373             : 
     374           0 :             case GDT_Float16:
     375             :                 // Convert Float16 to float.
     376             :                 // TODO: At some point we should support Float16.
     377           0 :                 nBandBits = 32;
     378           0 :                 nBandFormat = SAMPLEFORMAT_IEEEFP;
     379           0 :                 break;
     380             : 
     381          29 :             case GDT_Float32:
     382          29 :                 nBandBits = 32;
     383          29 :                 nBandFormat = SAMPLEFORMAT_IEEEFP;
     384          29 :                 break;
     385             : 
     386           2 :             case GDT_Float64:
     387           2 :                 nBandBits = 64;
     388           2 :                 nBandFormat = SAMPLEFORMAT_IEEEFP;
     389           2 :                 break;
     390             : 
     391           2 :             case GDT_CInt16:
     392           2 :                 nBandBits = 32;
     393           2 :                 nBandFormat = SAMPLEFORMAT_COMPLEXINT;
     394           2 :                 break;
     395             : 
     396           2 :             case GDT_CInt32:
     397           2 :                 nBandBits = 64;
     398           2 :                 nBandFormat = SAMPLEFORMAT_COMPLEXINT;
     399           2 :                 break;
     400             : 
     401           0 :             case GDT_CFloat16:
     402             :                 // Convert Float16 to float.
     403             :                 // TODO: At some point we should support Float16.
     404           0 :                 nBandBits = 64;
     405           0 :                 nBandFormat = SAMPLEFORMAT_COMPLEXIEEEFP;
     406           0 :                 break;
     407             : 
     408           2 :             case GDT_CFloat32:
     409           2 :                 nBandBits = 64;
     410           2 :                 nBandFormat = SAMPLEFORMAT_COMPLEXIEEEFP;
     411           2 :                 break;
     412             : 
     413           2 :             case GDT_CFloat64:
     414           2 :                 nBandBits = 128;
     415           2 :                 nBandFormat = SAMPLEFORMAT_COMPLEXIEEEFP;
     416           2 :                 break;
     417             : 
     418           0 :             case GDT_Unknown:
     419             :             case GDT_TypeCount:
     420           0 :                 CPLAssert(false);
     421             :                 return CE_Failure;
     422             :         }
     423             : 
     424         375 :         if (hBand->GetMetadataItem("NBITS", "IMAGE_STRUCTURE"))
     425             :         {
     426             :             nBandBits =
     427           8 :                 atoi(hBand->GetMetadataItem("NBITS", "IMAGE_STRUCTURE"));
     428             : 
     429           8 :             if (nBandBits == 1 && STARTS_WITH_CI(pszResampling, "AVERAGE_BIT2"))
     430           4 :                 nBandBits = 8;
     431             :         }
     432             : 
     433         375 :         if (iBand == 0)
     434             :         {
     435         223 :             nBitsPerPixel = nBandBits;
     436         223 :             nSampleFormat = nBandFormat;
     437         223 :             nXSize = hBand->GetXSize();
     438         223 :             nYSize = hBand->GetYSize();
     439             :         }
     440         152 :         else if (nBitsPerPixel != nBandBits || nSampleFormat != nBandFormat)
     441             :         {
     442           0 :             CPLError(CE_Failure, CPLE_NotSupported,
     443             :                      "GTIFFBuildOverviews() doesn't support a mixture of band"
     444             :                      " data types.");
     445           0 :             return CE_Failure;
     446             :         }
     447         152 :         else if (hBand->GetColorTable() != nullptr)
     448             :         {
     449           0 :             CPLError(CE_Failure, CPLE_NotSupported,
     450             :                      "GTIFFBuildOverviews() doesn't support building"
     451             :                      " overviews of multiple colormapped bands.");
     452           0 :             return CE_Failure;
     453             :         }
     454         152 :         else if (hBand->GetXSize() != nXSize || hBand->GetYSize() != nYSize)
     455             :         {
     456           0 :             CPLError(CE_Failure, CPLE_NotSupported,
     457             :                      "GTIFFBuildOverviews() doesn't support building"
     458             :                      " overviews of different sized bands.");
     459           0 :             return CE_Failure;
     460             :         }
     461             :     }
     462             : 
     463             :     const auto GetOptionValue =
     464        3407 :         [papszOptions](const char *pszOptionKey, const char *pszConfigOptionKey,
     465        3407 :                        const char **ppszKeyUsed = nullptr)
     466             :     {
     467        3407 :         const char *pszVal = CSLFetchNameValue(papszOptions, pszOptionKey);
     468        3407 :         if (pszVal)
     469             :         {
     470         173 :             if (ppszKeyUsed)
     471          54 :                 *ppszKeyUsed = pszOptionKey;
     472         173 :             return pszVal;
     473             :         }
     474        3234 :         pszVal = CPLGetConfigOption(pszConfigOptionKey, nullptr);
     475        3234 :         if (pszVal && ppszKeyUsed)
     476          57 :             *ppszKeyUsed = pszConfigOptionKey;
     477        3234 :         return pszVal;
     478         223 :     };
     479             : 
     480             :     /* -------------------------------------------------------------------- */
     481             :     /*      Use specified compression method.                               */
     482             :     /* -------------------------------------------------------------------- */
     483         223 :     const char *pszCompressKey = "";
     484             :     const char *pszCompress =
     485         223 :         GetOptionValue("COMPRESS", "COMPRESS_OVERVIEW", &pszCompressKey);
     486             : 
     487         223 :     if (pszCompress != nullptr && pszCompress[0] != '\0')
     488             :     {
     489         102 :         nCompression = GTIFFGetCompressionMethod(pszCompress, pszCompressKey);
     490         102 :         if (nCompression < 0)
     491           0 :             return CE_Failure;
     492             :     }
     493             : 
     494         223 :     if (nCompression == COMPRESSION_JPEG && nBitsPerPixel > 8)
     495             :     {
     496           2 :         if (nBitsPerPixel > 16)
     497             :         {
     498           0 :             CPLError(CE_Failure, CPLE_NotSupported,
     499             :                      "GTIFFBuildOverviews() doesn't support building"
     500             :                      " JPEG compressed overviews of nBitsPerPixel > 16.");
     501           0 :             return CE_Failure;
     502             :         }
     503             : 
     504           2 :         nBitsPerPixel = 12;
     505             :     }
     506             : 
     507             :     /* -------------------------------------------------------------------- */
     508             :     /*      Figure out the planar configuration to use.                     */
     509             :     /* -------------------------------------------------------------------- */
     510         223 :     if (nBands == 1)
     511         151 :         nPlanarConfig = PLANARCONFIG_CONTIG;
     512             :     else
     513          72 :         nPlanarConfig = PLANARCONFIG_SEPARATE;
     514             : 
     515         223 :     bool bSourceIsPixelInterleaved = false;
     516         223 :     bool bSourceIsJPEG2000 = false;
     517         223 :     if (nBands > 1)
     518             :     {
     519          72 :         GDALDataset *poSrcDS = papoBandList[0]->GetDataset();
     520          72 :         if (poSrcDS)
     521             :         {
     522             :             const char *pszSrcInterleave =
     523          72 :                 poSrcDS->GetMetadataItem("INTERLEAVE", "IMAGE_STRUCTURE");
     524          72 :             if (pszSrcInterleave && EQUAL(pszSrcInterleave, "PIXEL"))
     525             :             {
     526          42 :                 bSourceIsPixelInterleaved = true;
     527             :             }
     528             :         }
     529             : 
     530             :         const char *pszSrcCompression =
     531          72 :             papoBandList[0]->GetMetadataItem("COMPRESSION", "IMAGE_STRUCTURE");
     532          72 :         if (pszSrcCompression)
     533             :         {
     534           2 :             bSourceIsJPEG2000 = EQUAL(pszSrcCompression, "JPEG2000");
     535             :         }
     536          72 :         if (bSourceIsPixelInterleaved && bSourceIsJPEG2000)
     537             :         {
     538           1 :             nPlanarConfig = PLANARCONFIG_CONTIG;
     539             :         }
     540          71 :         else if (nCompression == COMPRESSION_WEBP ||
     541          66 :                  nCompression == COMPRESSION_JXL ||
     542             :                  nCompression == COMPRESSION_JXL_DNG_1_7)
     543             :         {
     544           7 :             nPlanarConfig = PLANARCONFIG_CONTIG;
     545             :         }
     546             :     }
     547             : 
     548             :     const char *pszInterleave =
     549         223 :         GetOptionValue("INTERLEAVE", "INTERLEAVE_OVERVIEW");
     550         223 :     if (pszInterleave != nullptr && pszInterleave[0] != '\0')
     551             :     {
     552          31 :         if (EQUAL(pszInterleave, "PIXEL"))
     553          31 :             nPlanarConfig = PLANARCONFIG_CONTIG;
     554           0 :         else if (EQUAL(pszInterleave, "BAND"))
     555           0 :             nPlanarConfig = PLANARCONFIG_SEPARATE;
     556             :         else
     557             :         {
     558           0 :             CPLError(CE_Failure, CPLE_AppDefined,
     559             :                      "INTERLEAVE_OVERVIEW=%s unsupported, "
     560             :                      "value must be PIXEL or BAND. ignoring",
     561             :                      pszInterleave);
     562             :         }
     563             :     }
     564             : 
     565             :     /* -------------------------------------------------------------------- */
     566             :     /*      Figure out the photometric interpretation to use.               */
     567             :     /* -------------------------------------------------------------------- */
     568         223 :     if (nBands == 3)
     569          47 :         nPhotometric = PHOTOMETRIC_RGB;
     570         176 :     else if (papoBandList[0]->GetColorTable() != nullptr &&
     571           7 :              (papoBandList[0]->GetRasterDataType() == GDT_Byte ||
     572         183 :               papoBandList[0]->GetRasterDataType() == GDT_UInt16) &&
     573           6 :              !STARTS_WITH_CI(pszResampling, "AVERAGE_BIT2"))
     574             :     {
     575             :         // Would also apply to other lossy compression scheme, but for JPEG,
     576             :         // this at least avoids a later cryptic error message from libtiff:
     577             :         // "JPEGSetupEncode:PhotometricInterpretation 3 not allowed for JPEG"
     578           6 :         if (nCompression == COMPRESSION_JPEG)
     579             :         {
     580           1 :             CPLError(CE_Failure, CPLE_AppDefined,
     581             :                      "Cannot create JPEG compressed overviews on a raster "
     582             :                      "with a color table");
     583           1 :             return CE_Failure;
     584             :         }
     585             : 
     586           5 :         nPhotometric = PHOTOMETRIC_PALETTE;
     587             :         // Color map is set up after
     588             :     }
     589         186 :     else if (nBands >= 3 &&
     590          16 :              papoBandList[0]->GetColorInterpretation() == GCI_RedBand &&
     591         201 :              papoBandList[1]->GetColorInterpretation() == GCI_GreenBand &&
     592          15 :              papoBandList[2]->GetColorInterpretation() == GCI_BlueBand)
     593             :     {
     594          15 :         nPhotometric = PHOTOMETRIC_RGB;
     595             :     }
     596             :     else
     597         155 :         nPhotometric = PHOTOMETRIC_MINISBLACK;
     598             : 
     599         222 :     const char *pszOptionKey = "";
     600             :     const char *pszPhotometric =
     601         222 :         GetOptionValue("PHOTOMETRIC", "PHOTOMETRIC_OVERVIEW", &pszOptionKey);
     602         222 :     if (!GTIFFUpdatePhotometric(pszPhotometric, pszOptionKey, nCompression,
     603             :                                 pszInterleave, nBands, nPhotometric,
     604             :                                 nPlanarConfig))
     605             :     {
     606           0 :         return CE_Failure;
     607             :     }
     608             : 
     609             :     /* -------------------------------------------------------------------- */
     610             :     /*      Figure out the predictor value to use.                          */
     611             :     /* -------------------------------------------------------------------- */
     612         222 :     int nPredictor = PREDICTOR_NONE;
     613         222 :     if (GTIFFSupportsPredictor(nCompression))
     614             :     {
     615             :         const char *pszPredictor =
     616          69 :             GetOptionValue("PREDICTOR", "PREDICTOR_OVERVIEW");
     617          69 :         if (pszPredictor != nullptr)
     618             :         {
     619           2 :             nPredictor = atoi(pszPredictor);
     620             :         }
     621             :     }
     622             : 
     623             :     /* -------------------------------------------------------------------- */
     624             :     /*      Create the file, if it does not already exist.                  */
     625             :     /* -------------------------------------------------------------------- */
     626             :     VSIStatBufL sStatBuf;
     627         222 :     VSILFILE *fpL = nullptr;
     628             : 
     629         222 :     bool bCreateBigTIFF = false;
     630         222 :     if (VSIStatExL(pszFilename, &sStatBuf, VSI_STAT_EXISTS_FLAG) != 0)
     631             :     {
     632             :         /* --------------------------------------------------------------------
     633             :          */
     634             :         /*      Compute the uncompressed size. */
     635             :         /* --------------------------------------------------------------------
     636             :          */
     637         218 :         double dfUncompressedOverviewSize = 0;
     638             :         int nDataTypeSize =
     639         218 :             GDALGetDataTypeSizeBytes(papoBandList[0]->GetRasterDataType());
     640             : 
     641         553 :         for (iOverview = 0; iOverview < nOverviews; iOverview++)
     642             :         {
     643         335 :             const int nOXSize =
     644         335 :                 panOverviewList ? (nXSize + panOverviewList[iOverview] - 1) /
     645         233 :                                       panOverviewList[iOverview]
     646             :                                 :
     647             :                                 // cppcheck-suppress nullPointer
     648         102 :                     pasOverviewSize[iOverview].first;
     649         335 :             const int nOYSize =
     650         335 :                 panOverviewList ? (nYSize + panOverviewList[iOverview] - 1) /
     651         233 :                                       panOverviewList[iOverview]
     652             :                                 :
     653             :                                 // cppcheck-suppress nullPointer
     654         102 :                     pasOverviewSize[iOverview].second;
     655             : 
     656         335 :             dfUncompressedOverviewSize +=
     657         335 :                 nOXSize * static_cast<double>(nOYSize) * nBands * nDataTypeSize;
     658             :         }
     659             : 
     660             :         /* --------------------------------------------------------------------
     661             :          */
     662             :         /*      Should the file be created as a bigtiff file? */
     663             :         /* --------------------------------------------------------------------
     664             :          */
     665         218 :         const char *pszBIGTIFF = GetOptionValue("BIGTIFF", "BIGTIFF_OVERVIEW");
     666             : 
     667         218 :         if (pszBIGTIFF == nullptr)
     668         163 :             pszBIGTIFF = "IF_SAFER";
     669             : 
     670         218 :         if (EQUAL(pszBIGTIFF, "IF_NEEDED"))
     671             :         {
     672           0 :             if (nCompression == COMPRESSION_NONE &&
     673             :                 dfUncompressedOverviewSize > 4200000000.0)
     674           0 :                 bCreateBigTIFF = true;
     675             :         }
     676         218 :         else if (EQUAL(pszBIGTIFF, "IF_SAFER"))
     677             :         {
     678             :             // Look at the size of the base image and suppose that
     679             :             // the added overview levels won't be more than 1/2 of
     680             :             // the size of the base image. The theory says 1/3 of the
     681             :             // base image size if the overview levels are 2, 4, 8, 16.
     682             :             // Thus take 1/2 as the security margin for 1/3.
     683         165 :             const double dfUncompressedImageSize =
     684         165 :                 nXSize * static_cast<double>(nYSize) * nBands * nDataTypeSize;
     685         165 :             if (dfUncompressedImageSize * 0.5 > 4200000000.0)
     686           5 :                 bCreateBigTIFF = true;
     687             :         }
     688             :         else
     689             :         {
     690          53 :             bCreateBigTIFF = CPLTestBool(pszBIGTIFF);
     691          53 :             if (!bCreateBigTIFF && nCompression == COMPRESSION_NONE &&
     692             :                 dfUncompressedOverviewSize > 4200000000.0)
     693             :             {
     694           2 :                 CPLError(CE_Failure, CPLE_NotSupported,
     695             :                          "The overview file will be larger than 4GB, "
     696             :                          "so BigTIFF is necessary.  "
     697             :                          "Creation failed.");
     698           2 :                 return CE_Failure;
     699             :             }
     700             :         }
     701             : 
     702         216 :         if (bCreateBigTIFF)
     703          54 :             CPLDebug("GTiff", "File being created as a BigTIFF.");
     704             : 
     705         216 :         fpL = VSIFOpenL(pszFilename, "w+");
     706         216 :         if (fpL == nullptr)
     707           1 :             hOTIFF = nullptr;
     708             :         else
     709             :             hOTIFF =
     710         215 :                 VSI_TIFFOpen(pszFilename, bCreateBigTIFF ? "w+8" : "w+", fpL);
     711         216 :         if (hOTIFF == nullptr)
     712             :         {
     713           1 :             if (CPLGetLastErrorNo() == 0)
     714           1 :                 CPLError(CE_Failure, CPLE_OpenFailed,
     715             :                          "Attempt to create new tiff file `%s' "
     716             :                          "failed in VSI_TIFFOpen().",
     717             :                          pszFilename);
     718           1 :             if (fpL != nullptr)
     719           0 :                 CPL_IGNORE_RET_VAL(VSIFCloseL(fpL));
     720           1 :             return CE_Failure;
     721             :         }
     722             :     }
     723             :     /* -------------------------------------------------------------------- */
     724             :     /*      Otherwise just open it for update access.                       */
     725             :     /* -------------------------------------------------------------------- */
     726             :     else
     727             :     {
     728           4 :         fpL = VSIFOpenL(pszFilename, "r+");
     729           4 :         if (fpL == nullptr)
     730           0 :             hOTIFF = nullptr;
     731             :         else
     732             :         {
     733           4 :             GByte abyBuffer[4] = {0};
     734           4 :             VSIFReadL(abyBuffer, 1, 4, fpL);
     735           4 :             VSIFSeekL(fpL, 0, SEEK_SET);
     736           4 :             bCreateBigTIFF = abyBuffer[2] == 43 || abyBuffer[3] == 43;
     737           4 :             hOTIFF = VSI_TIFFOpen(pszFilename, "r+", fpL);
     738             :         }
     739           4 :         if (hOTIFF == nullptr)
     740             :         {
     741           0 :             if (CPLGetLastErrorNo() == 0)
     742           0 :                 CPLError(CE_Failure, CPLE_OpenFailed,
     743             :                          "Attempt to create new tiff file `%s' "
     744             :                          "failed in VSI_TIFFOpen().",
     745             :                          pszFilename);
     746           0 :             if (fpL != nullptr)
     747           0 :                 CPL_IGNORE_RET_VAL(VSIFCloseL(fpL));
     748           0 :             return CE_Failure;
     749             :         }
     750             :     }
     751             : 
     752             :     /* -------------------------------------------------------------------- */
     753             :     /*      Do we have a palette?  If so, create a TIFF compatible version. */
     754             :     /* -------------------------------------------------------------------- */
     755         219 :     unsigned short *panRed = nullptr;
     756         219 :     unsigned short *panGreen = nullptr;
     757         219 :     unsigned short *panBlue = nullptr;
     758             : 
     759         219 :     if (nPhotometric == PHOTOMETRIC_PALETTE)
     760             :     {
     761           5 :         GDALColorTable *poCT = papoBandList[0]->GetColorTable();
     762           5 :         int nColorCount = 65536;
     763             : 
     764           5 :         if (nBitsPerPixel <= 8)
     765           5 :             nColorCount = 256;
     766             : 
     767             :         panRed = static_cast<unsigned short *>(
     768           5 :             CPLCalloc(nColorCount, sizeof(unsigned short)));
     769             :         panGreen = static_cast<unsigned short *>(
     770           5 :             CPLCalloc(nColorCount, sizeof(unsigned short)));
     771             :         panBlue = static_cast<unsigned short *>(
     772           5 :             CPLCalloc(nColorCount, sizeof(unsigned short)));
     773             : 
     774             :         const int nColorTableMultiplier = std::max(
     775          10 :             1,
     776             :             std::min(
     777          10 :                 257,
     778           5 :                 atoi(CSLFetchNameValueDef(
     779             :                     papszOptions, "COLOR_TABLE_MULTIPLIER",
     780             :                     CPLSPrintf(
     781             :                         "%d",
     782           5 :                         GTiffDataset::DEFAULT_COLOR_TABLE_MULTIPLIER_257)))));
     783             : 
     784        1285 :         for (int iColor = 0; iColor < nColorCount; iColor++)
     785             :         {
     786        1280 :             GDALColorEntry sRGB = {0, 0, 0, 0};
     787             : 
     788        1280 :             if (poCT->GetColorEntryAsRGB(iColor, &sRGB))
     789             :             {
     790        2560 :                 panRed[iColor] = GTiffDataset::ClampCTEntry(
     791        1280 :                     iColor, 1, sRGB.c1, nColorTableMultiplier);
     792        2560 :                 panGreen[iColor] = GTiffDataset::ClampCTEntry(
     793        1280 :                     iColor, 2, sRGB.c2, nColorTableMultiplier);
     794        1280 :                 panBlue[iColor] = GTiffDataset::ClampCTEntry(
     795        1280 :                     iColor, 3, sRGB.c3, nColorTableMultiplier);
     796             :             }
     797             :         }
     798             :     }
     799             : 
     800             :     /* -------------------------------------------------------------------- */
     801             :     /*      Do we need some metadata for the overviews?                     */
     802             :     /* -------------------------------------------------------------------- */
     803         438 :     CPLString osMetadata;
     804         219 :     GDALDataset *poBaseDS = papoBandList[0]->GetDataset();
     805         219 :     if (poBaseDS)
     806             :     {
     807             :         const bool bIsForMaskBand =
     808         215 :             nBands == 1 && papoBandList[0]->IsMaskBand();
     809         215 :         GTIFFBuildOverviewMetadata(pszResampling, poBaseDS, bIsForMaskBand,
     810             :                                    osMetadata);
     811             :     }
     812             : 
     813         219 :     if (poBaseDS != nullptr && poBaseDS->GetRasterCount() == nBands)
     814             :     {
     815         209 :         const bool bStandardColorInterp = GTIFFIsStandardColorInterpretation(
     816             :             GDALDataset::ToHandle(poBaseDS),
     817             :             static_cast<uint16_t>(nPhotometric), nullptr);
     818         209 :         if (!bStandardColorInterp)
     819             :         {
     820          18 :             if (osMetadata.size() >= strlen("</GDALMetadata>") &&
     821          18 :                 osMetadata.substr(osMetadata.size() -
     822           9 :                                   strlen("</GDALMetadata>")) ==
     823             :                     "</GDALMetadata>")
     824             :             {
     825           9 :                 osMetadata.resize(osMetadata.size() -
     826             :                                   strlen("</GDALMetadata>"));
     827             :             }
     828             :             else
     829             :             {
     830           0 :                 CPLAssert(osMetadata.empty());
     831           0 :                 osMetadata = "<GDALMetadata>";
     832             :             }
     833          36 :             for (int i = 0; i < poBaseDS->GetRasterCount(); ++i)
     834             :             {
     835             :                 const GDALColorInterp eInterp =
     836          27 :                     poBaseDS->GetRasterBand(i + 1)->GetColorInterpretation();
     837             :                 osMetadata +=
     838             :                     CPLSPrintf("<Item sample=\"%d\" name=\"COLORINTERP\" "
     839             :                                "role=\"colorinterp\">",
     840          27 :                                i);
     841          27 :                 osMetadata += GDALGetColorInterpretationName(eInterp);
     842          27 :                 osMetadata += "</Item>";
     843             :             }
     844           9 :             osMetadata += "</GDALMetadata>";
     845             :         }
     846             :     }
     847             : 
     848             :     /* -------------------------------------------------------------------- */
     849             :     /*      Loop, creating overviews.                                       */
     850             :     /* -------------------------------------------------------------------- */
     851         219 :     int nOvrBlockXSize = 0;
     852         219 :     int nOvrBlockYSize = 0;
     853         219 :     GTIFFGetOverviewBlockSize(papoBandList[0], &nOvrBlockXSize,
     854             :                               &nOvrBlockYSize);
     855             : 
     856         438 :     CPLString osNoData;  // don't move this in inner scope
     857         219 :     const char *pszNoData = nullptr;
     858         219 :     int bNoDataSet = FALSE;
     859         219 :     const double dfNoDataValue = papoBandList[0]->GetNoDataValue(&bNoDataSet);
     860         219 :     if (bNoDataSet)
     861             :     {
     862          12 :         osNoData = GTiffFormatGDALNoDataTagValue(dfNoDataValue);
     863          12 :         pszNoData = osNoData.c_str();
     864             :     }
     865             : 
     866         438 :     std::vector<uint16_t> anExtraSamples;
     867         247 :     for (int i = GTIFFGetMaxColorChannels(nPhotometric) + 1; i <= nBands; i++)
     868             :     {
     869          28 :         if (papoBandList[i - 1]->GetColorInterpretation() == GCI_AlphaBand)
     870             :         {
     871          18 :             anExtraSamples.push_back(GTiffGetAlphaValue(
     872             :                 GetOptionValue("ALPHA", "GTIFF_ALPHA"), DEFAULT_ALPHA_TYPE));
     873             :         }
     874             :         else
     875             :         {
     876          10 :             anExtraSamples.push_back(EXTRASAMPLE_UNSPECIFIED);
     877             :         }
     878             :     }
     879             : 
     880         219 :     const uint32_t *panLercAddCompressionAndVersion = nullptr;
     881         219 :     uint32_t anLercAddCompressionAndVersion[2] = {LERC_VERSION_2_4,
     882             :                                                   LERC_ADD_COMPRESSION_NONE};
     883         219 :     if (pszCompress && EQUAL(pszCompress, "LERC_DEFLATE"))
     884             :     {
     885           5 :         anLercAddCompressionAndVersion[1] = LERC_ADD_COMPRESSION_DEFLATE;
     886           5 :         panLercAddCompressionAndVersion = anLercAddCompressionAndVersion;
     887             :     }
     888         214 :     else if (pszCompress && EQUAL(pszCompress, "LERC_ZSTD"))
     889             :     {
     890           5 :         anLercAddCompressionAndVersion[1] = LERC_ADD_COMPRESSION_ZSTD;
     891           5 :         panLercAddCompressionAndVersion = anLercAddCompressionAndVersion;
     892             :     }
     893             : 
     894         554 :     for (iOverview = 0; iOverview < nOverviews; iOverview++)
     895             :     {
     896         336 :         const int nOXSize = panOverviewList
     897         336 :                                 ? (nXSize + panOverviewList[iOverview] - 1) /
     898         234 :                                       panOverviewList[iOverview]
     899             :                                 :
     900             :                                 // cppcheck-suppress nullPointer
     901         102 :                                 pasOverviewSize[iOverview].first;
     902         336 :         const int nOYSize = panOverviewList
     903         336 :                                 ? (nYSize + panOverviewList[iOverview] - 1) /
     904         234 :                                       panOverviewList[iOverview]
     905             :                                 :
     906             :                                 // cppcheck-suppress nullPointer
     907         102 :                                 pasOverviewSize[iOverview].second;
     908             : 
     909         336 :         unsigned nTileXCount = DIV_ROUND_UP(nOXSize, nOvrBlockXSize);
     910         336 :         unsigned nTileYCount = DIV_ROUND_UP(nOYSize, nOvrBlockYSize);
     911             :         // libtiff implementation limitation
     912         336 :         if (nTileXCount > 0x80000000U / (bCreateBigTIFF ? 8 : 4) / nTileYCount)
     913             :         {
     914           1 :             CPLError(CE_Failure, CPLE_NotSupported,
     915             :                      "File too large regarding tile size. This would result "
     916             :                      "in a file with tile arrays larger than 2GB");
     917           1 :             XTIFFClose(hOTIFF);
     918           1 :             VSIFCloseL(fpL);
     919           1 :             return CE_Failure;
     920             :         }
     921             : 
     922        1005 :         if (GTIFFWriteDirectory(
     923             :                 hOTIFF, FILETYPE_REDUCEDIMAGE, nOXSize, nOYSize, nBitsPerPixel,
     924             :                 nPlanarConfig, nBands, nOvrBlockXSize, nOvrBlockYSize, TRUE,
     925             :                 nCompression, nPhotometric, nSampleFormat, nPredictor, panRed,
     926         335 :                 panGreen, panBlue, static_cast<int>(anExtraSamples.size()),
     927         380 :                 anExtraSamples.empty() ? nullptr : anExtraSamples.data(),
     928             :                 osMetadata,
     929             :                 GetOptionValue("JPEG_QUALITY", "JPEG_QUALITY_OVERVIEW"),
     930             :                 GetOptionValue("JPEG_TABLESMODE", "JPEG_TABLESMODE_OVERVIEW"),
     931         335 :                 pszNoData, panLercAddCompressionAndVersion, false) == 0)
     932             :         {
     933           0 :             XTIFFClose(hOTIFF);
     934           0 :             VSIFCloseL(fpL);
     935           0 :             return CE_Failure;
     936             :         }
     937             :     }
     938             : 
     939         218 :     if (panRed)
     940             :     {
     941           5 :         CPLFree(panRed);
     942           5 :         CPLFree(panGreen);
     943           5 :         CPLFree(panBlue);
     944           5 :         panRed = nullptr;
     945           5 :         panGreen = nullptr;
     946           5 :         panBlue = nullptr;
     947             :     }
     948             : 
     949         218 :     XTIFFClose(hOTIFF);
     950         218 :     if (VSIFCloseL(fpL) != 0)
     951           0 :         return CE_Failure;
     952         218 :     fpL = nullptr;
     953             : 
     954             :     /* -------------------------------------------------------------------- */
     955             :     /*      Open the overview dataset so that we can get at the overview    */
     956             :     /*      bands.                                                          */
     957             :     /* -------------------------------------------------------------------- */
     958         436 :     CPLStringList aosOpenOptions;
     959             :     aosOpenOptions.SetNameValue("NUM_THREADS",
     960         218 :                                 CSLFetchNameValue(papszOptions, "NUM_THREADS"));
     961             :     aosOpenOptions.SetNameValue(
     962         218 :         "SPARSE_OK", GetOptionValue("SPARSE_OK", "SPARSE_OK_OVERVIEW"));
     963             :     aosOpenOptions.SetNameValue(
     964             :         "@MASK_OVERVIEW_DATASET",
     965         218 :         CSLFetchNameValue(papszOptions, "MASK_OVERVIEW_DATASET"));
     966             :     GDALDataset *hODS =
     967         218 :         GDALDataset::Open(pszFilename, GDAL_OF_RASTER | GDAL_OF_UPDATE, nullptr,
     968         218 :                           aosOpenOptions.List());
     969         218 :     if (hODS == nullptr)
     970           0 :         return CE_Failure;
     971             : 
     972             :     /* -------------------------------------------------------------------- */
     973             :     /*      Do we need to set the jpeg quality?                             */
     974             :     /* -------------------------------------------------------------------- */
     975         218 :     TIFF *hTIFF = static_cast<TIFF *>(hODS->GetInternalHandle(nullptr));
     976             : 
     977             :     const char *pszJPEGQuality =
     978         218 :         GetOptionValue("JPEG_QUALITY", "JPEG_QUALITY_OVERVIEW");
     979         218 :     if (nCompression == COMPRESSION_JPEG && pszJPEGQuality != nullptr)
     980             :     {
     981           4 :         const int nJpegQuality = atoi(pszJPEGQuality);
     982           4 :         TIFFSetField(hTIFF, TIFFTAG_JPEGQUALITY, nJpegQuality);
     983           4 :         GTIFFSetJpegQuality(GDALDataset::ToHandle(hODS), nJpegQuality);
     984             :     }
     985             : 
     986             :     const char *pszWebpLevel =
     987         218 :         GetOptionValue("WEBP_LEVEL", "WEBP_LEVEL_OVERVIEW");
     988         218 :     if (nCompression == COMPRESSION_WEBP && pszWebpLevel != nullptr)
     989             :     {
     990           3 :         const int nWebpLevel = atoi(pszWebpLevel);
     991           3 :         if (nWebpLevel >= 1)
     992             :         {
     993           3 :             TIFFSetField(hTIFF, TIFFTAG_WEBP_LEVEL, nWebpLevel);
     994           3 :             GTIFFSetWebPLevel(GDALDataset::ToHandle(hODS), nWebpLevel);
     995             :         }
     996             :     }
     997             : 
     998             :     const char *pszWebpLossless =
     999         218 :         GetOptionValue("WEBP_LOSSLESS", "WEBP_LOSSLESS_OVERVIEW");
    1000         218 :     if (nCompression == COMPRESSION_WEBP && pszWebpLossless != nullptr)
    1001             :     {
    1002           1 :         const bool bWebpLossless = CPLTestBool(pszWebpLossless);
    1003           1 :         TIFFSetField(hTIFF, TIFFTAG_WEBP_LOSSLESS,
    1004             :                      static_cast<int>(bWebpLossless));
    1005           1 :         GTIFFSetWebPLossless(GDALDataset::ToHandle(hODS), bWebpLossless);
    1006             :     }
    1007             : 
    1008             :     const char *pszJPEGTablesMode =
    1009         218 :         GetOptionValue("JPEG_TABLESMODE", "JPEG_TABLESMODE_OVERVIEW");
    1010         218 :     if (nCompression == COMPRESSION_JPEG && pszJPEGTablesMode != nullptr)
    1011             :     {
    1012           0 :         const int nJpegTablesMode = atoi(pszJPEGTablesMode);
    1013           0 :         TIFFSetField(hTIFF, TIFFTAG_JPEGTABLESMODE, nJpegTablesMode);
    1014           0 :         GTIFFSetJpegTablesMode(GDALDataset::ToHandle(hODS), nJpegTablesMode);
    1015             :     }
    1016             : 
    1017         218 :     const char *pszZLevel = GetOptionValue("ZLEVEL", "ZLEVEL_OVERVIEW");
    1018         218 :     if ((nCompression == COMPRESSION_DEFLATE ||
    1019         218 :          anLercAddCompressionAndVersion[1] == LERC_ADD_COMPRESSION_DEFLATE) &&
    1020             :         pszZLevel != nullptr)
    1021             :     {
    1022           2 :         const int nZLevel = atoi(pszZLevel);
    1023           2 :         if (nZLevel >= 1)
    1024             :         {
    1025           2 :             TIFFSetField(hTIFF, TIFFTAG_ZIPQUALITY, nZLevel);
    1026           2 :             GTIFFSetZLevel(GDALDataset::ToHandle(hODS), nZLevel);
    1027             :         }
    1028             :     }
    1029             : 
    1030             :     const char *pszZSTDLevel =
    1031         218 :         GetOptionValue("ZSTD_LEVEL", "ZSTD_LEVEL_OVERVIEW");
    1032         218 :     if ((nCompression == COMPRESSION_ZSTD ||
    1033         218 :          anLercAddCompressionAndVersion[1] == LERC_ADD_COMPRESSION_ZSTD) &&
    1034             :         pszZSTDLevel != nullptr)
    1035             :     {
    1036           2 :         const int nZSTDLevel = atoi(pszZSTDLevel);
    1037           2 :         if (nZSTDLevel >= 1)
    1038             :         {
    1039           2 :             TIFFSetField(hTIFF, TIFFTAG_ZSTD_LEVEL, nZSTDLevel);
    1040           2 :             GTIFFSetZSTDLevel(GDALDataset::ToHandle(hODS), nZSTDLevel);
    1041             :         }
    1042             :     }
    1043             : 
    1044             :     const char *pszMaxZError =
    1045         218 :         GetOptionValue("MAX_Z_ERROR", "MAX_Z_ERROR_OVERVIEW");
    1046         218 :     if (nCompression == COMPRESSION_LERC && pszMaxZError != nullptr)
    1047             :     {
    1048          10 :         const double dfMaxZError = CPLAtof(pszMaxZError);
    1049          10 :         if (dfMaxZError >= 0)
    1050             :         {
    1051          10 :             TIFFSetField(hTIFF, TIFFTAG_LERC_MAXZERROR, dfMaxZError);
    1052          10 :             GTIFFSetMaxZError(GDALDataset::ToHandle(hODS), dfMaxZError);
    1053             :         }
    1054             :     }
    1055             : 
    1056             : #if HAVE_JXL
    1057         218 :     if (nCompression == COMPRESSION_JXL ||
    1058             :         nCompression == COMPRESSION_JXL_DNG_1_7)
    1059             :     {
    1060           5 :         if (const char *pszJXLLossLess =
    1061           5 :                 GetOptionValue("JXL_LOSSLESS", "JXL_LOSSLESS_OVERVIEW"))
    1062             :         {
    1063           5 :             const bool bJXLLossless = CPLTestBool(pszJXLLossLess);
    1064           5 :             TIFFSetField(hTIFF, TIFFTAG_JXL_LOSSYNESS,
    1065             :                          bJXLLossless ? JXL_LOSSLESS : JXL_LOSSY);
    1066           5 :             GTIFFSetJXLLossless(GDALDataset::ToHandle(hODS), bJXLLossless);
    1067             :         }
    1068           5 :         if (const char *pszJXLEffort =
    1069           5 :                 GetOptionValue("JXL_EFFORT", "JXL_EFFORT_OVERVIEW"))
    1070             :         {
    1071           0 :             const int nJXLEffort = atoi(pszJXLEffort);
    1072           0 :             TIFFSetField(hTIFF, TIFFTAG_JXL_EFFORT, nJXLEffort);
    1073           0 :             GTIFFSetJXLEffort(GDALDataset::ToHandle(hODS), nJXLEffort);
    1074             :         }
    1075           5 :         if (const char *pszJXLDistance =
    1076           5 :                 GetOptionValue("JXL_DISTANCE", "JXL_DISTANCE_OVERVIEW"))
    1077             :         {
    1078             :             const float fJXLDistance =
    1079           1 :                 static_cast<float>(CPLAtof(pszJXLDistance));
    1080           1 :             TIFFSetField(hTIFF, TIFFTAG_JXL_DISTANCE, fJXLDistance);
    1081           1 :             GTIFFSetJXLDistance(GDALDataset::ToHandle(hODS), fJXLDistance);
    1082             :         }
    1083           5 :         if (const char *pszJXLAlphaDistance = GetOptionValue(
    1084             :                 "JXL_ALPHA_DISTANCE", "JXL_ALPHA_DISTANCE_OVERVIEW"))
    1085             :         {
    1086             :             const float fJXLAlphaDistance =
    1087           1 :                 static_cast<float>(CPLAtof(pszJXLAlphaDistance));
    1088           1 :             TIFFSetField(hTIFF, TIFFTAG_JXL_ALPHA_DISTANCE, fJXLAlphaDistance);
    1089           1 :             GTIFFSetJXLAlphaDistance(GDALDataset::ToHandle(hODS),
    1090             :                                      fJXLAlphaDistance);
    1091             :         }
    1092             :     }
    1093             : #endif
    1094             : 
    1095             :     /* -------------------------------------------------------------------- */
    1096             :     /*      Loop writing overview data.                                     */
    1097             :     /* -------------------------------------------------------------------- */
    1098             : 
    1099         218 :     int *panOverviewListSorted = nullptr;
    1100         218 :     if (panOverviewList)
    1101             :     {
    1102             :         panOverviewListSorted =
    1103         171 :             static_cast<int *>(CPLMalloc(sizeof(int) * nOverviews));
    1104         171 :         memcpy(panOverviewListSorted, panOverviewList,
    1105         171 :                sizeof(int) * nOverviews);
    1106         171 :         std::sort(panOverviewListSorted, panOverviewListSorted + nOverviews);
    1107             :     }
    1108             : 
    1109         218 :     GTIFFSetThreadLocalInExternalOvr(true);
    1110             : 
    1111         218 :     CPLErr eErr = CE_None;
    1112             : 
    1113             :     // If we have an alpha band, we want it to be generated before downsampling
    1114             :     // other bands
    1115         218 :     bool bHasAlphaBand = false;
    1116         588 :     for (int iBand = 0; iBand < nBands; iBand++)
    1117             :     {
    1118         370 :         if (papoBandList[iBand]->GetColorInterpretation() == GCI_AlphaBand)
    1119          18 :             bHasAlphaBand = true;
    1120             :     }
    1121             : 
    1122         218 :     const auto poColorTable = papoBandList[0]->GetColorTable();
    1123         218 :     if (((((bSourceIsPixelInterleaved && bSourceIsJPEG2000) ||
    1124         102 :            (nCompression != COMPRESSION_NONE)) &&
    1125         218 :           nPlanarConfig == PLANARCONFIG_CONTIG) ||
    1126         110 :          bHasAlphaBand) &&
    1127         110 :         !GDALDataTypeIsComplex(papoBandList[0]->GetRasterDataType()) &&
    1128           1 :         (poColorTable == nullptr || STARTS_WITH_CI(pszResampling, "NEAR") ||
    1129         436 :          poColorTable->IsIdentity()) &&
    1130         110 :         (STARTS_WITH_CI(pszResampling, "NEAR") ||
    1131          75 :          EQUAL(pszResampling, "AVERAGE") || EQUAL(pszResampling, "RMS") ||
    1132          48 :          EQUAL(pszResampling, "GAUSS") || EQUAL(pszResampling, "CUBIC") ||
    1133          10 :          EQUAL(pszResampling, "CUBICSPLINE") ||
    1134          10 :          EQUAL(pszResampling, "LANCZOS") || EQUAL(pszResampling, "BILINEAR") ||
    1135           6 :          EQUAL(pszResampling, "MODE")))
    1136             :     {
    1137             :         // In the case of pixel interleaved compressed overviews, we want to
    1138             :         // generate the overviews for all the bands block by block, and not
    1139             :         // band after band, in order to write the block once and not loose
    1140             :         // space in the TIFF file.
    1141             :         GDALRasterBand ***papapoOverviewBands =
    1142         106 :             static_cast<GDALRasterBand ***>(CPLCalloc(sizeof(void *), nBands));
    1143         322 :         for (int iBand = 0; iBand < nBands && eErr == CE_None; iBand++)
    1144             :         {
    1145         216 :             GDALRasterBand *poSrcBand = papoBandList[iBand];
    1146         216 :             GDALRasterBand *poDstBand = hODS->GetRasterBand(iBand + 1);
    1147         432 :             papapoOverviewBands[iBand] = static_cast<GDALRasterBand **>(
    1148         216 :                 CPLCalloc(sizeof(void *), nOverviews));
    1149             : 
    1150         216 :             int bHasNoData = FALSE;
    1151         216 :             const double noDataValue = poSrcBand->GetNoDataValue(&bHasNoData);
    1152         216 :             if (bHasNoData)
    1153           9 :                 poDstBand->SetNoDataValue(noDataValue);
    1154             :             std::vector<bool> abDstOverviewAssigned(
    1155         432 :                 1 + poDstBand->GetOverviewCount());
    1156             : 
    1157         608 :             for (int i = 0; i < nOverviews && eErr == CE_None; i++)
    1158             :             {
    1159             :                 const bool bDegenerateOverview =
    1160         186 :                     panOverviewListSorted != nullptr &&
    1161         411 :                     (poSrcBand->GetXSize() >> panOverviewListSorted[i]) == 0 &&
    1162          19 :                     (poSrcBand->GetYSize() >> panOverviewListSorted[i]) == 0;
    1163             : 
    1164         734 :                 for (int j = -1;
    1165         734 :                      j < poDstBand->GetOverviewCount() && eErr == CE_None; j++)
    1166             :                 {
    1167         734 :                     if (abDstOverviewAssigned[1 + j])
    1168         336 :                         continue;
    1169             :                     GDALRasterBand *poOverview =
    1170         398 :                         (j < 0) ? poDstBand : poDstBand->GetOverview(j);
    1171         398 :                     if (poOverview == nullptr)
    1172             :                     {
    1173           0 :                         eErr = CE_Failure;
    1174           0 :                         continue;
    1175             :                     }
    1176             : 
    1177             :                     bool bMatch;
    1178         398 :                     if (panOverviewListSorted)
    1179             :                     {
    1180         192 :                         const int nOvFactor = GDALComputeOvFactor(
    1181             :                             poOverview->GetXSize(), poSrcBand->GetXSize(),
    1182             :                             poOverview->GetYSize(), poSrcBand->GetYSize());
    1183             : 
    1184         192 :                         bMatch = nOvFactor == panOverviewListSorted[i] ||
    1185          12 :                                  nOvFactor == GDALOvLevelAdjust2(
    1186           6 :                                                   panOverviewListSorted[i],
    1187             :                                                   poSrcBand->GetXSize(),
    1188             :                                                   poSrcBand->GetYSize())
    1189             :                                  // Deal with edge cases where overview levels
    1190             :                                  // lead to degenerate 1x1 overviews
    1191         198 :                                  || (bDegenerateOverview &&
    1192           0 :                                      poOverview->GetXSize() == 1 &&
    1193           0 :                                      poOverview->GetYSize() == 1);
    1194             :                     }
    1195             :                     else
    1196             :                     {
    1197         206 :                         bMatch = (
    1198             :                             // cppcheck-suppress nullPointer
    1199         206 :                             poOverview->GetXSize() ==
    1200         412 :                                 pasOverviewSize[i].first &&
    1201             :                             // cppcheck-suppress nullPointer
    1202         206 :                             poOverview->GetYSize() ==
    1203         206 :                                 pasOverviewSize[i].second);
    1204             :                     }
    1205         398 :                     if (bMatch)
    1206             :                     {
    1207         392 :                         abDstOverviewAssigned[j + 1] = true;
    1208         392 :                         papapoOverviewBands[iBand][i] = poOverview;
    1209         392 :                         if (bHasNoData)
    1210          14 :                             poOverview->SetNoDataValue(noDataValue);
    1211         392 :                         break;
    1212             :                     }
    1213             :                 }
    1214             : 
    1215         392 :                 CPLAssert(papapoOverviewBands[iBand][i] != nullptr);
    1216             :             }
    1217             :         }
    1218             : 
    1219             :         {
    1220             :             CPLConfigOptionSetter oSetter(
    1221             :                 "GDAL_NUM_THREADS",
    1222         212 :                 CSLFetchNameValue(papszOptions, "NUM_THREADS"), true);
    1223             : 
    1224         106 :             if (eErr == CE_None)
    1225         106 :                 eErr = GDALRegenerateOverviewsMultiBand(
    1226             :                     nBands, papoBandList, nOverviews, papapoOverviewBands,
    1227             :                     pszResampling, pfnProgress, pProgressData, papszOptions);
    1228             :         }
    1229             : 
    1230         322 :         for (int iBand = 0; iBand < nBands; iBand++)
    1231             :         {
    1232         216 :             CPLFree(papapoOverviewBands[iBand]);
    1233             :         }
    1234         106 :         CPLFree(papapoOverviewBands);
    1235             :     }
    1236             :     else
    1237             :     {
    1238             :         GDALRasterBand **papoOverviews = static_cast<GDALRasterBand **>(
    1239         112 :             CPLCalloc(sizeof(void *), knMaxOverviews));
    1240             : 
    1241         266 :         for (int iBand = 0; iBand < nBands && eErr == CE_None; iBand++)
    1242             :         {
    1243         154 :             GDALRasterBand *hSrcBand = papoBandList[iBand];
    1244         154 :             GDALRasterBand *hDstBand = hODS->GetRasterBand(iBand + 1);
    1245             : 
    1246         154 :             int bHasNoData = FALSE;
    1247         154 :             const double noDataValue = hSrcBand->GetNoDataValue(&bHasNoData);
    1248         154 :             if (bHasNoData)
    1249           9 :                 hDstBand->SetNoDataValue(noDataValue);
    1250             : 
    1251             :             // FIXME: this logic regenerates all overview bands, not only the
    1252             :             // ones requested.
    1253             : 
    1254         154 :             papoOverviews[0] = hDstBand;
    1255         154 :             int nDstOverviews = hDstBand->GetOverviewCount() + 1;
    1256         154 :             CPLAssert(nDstOverviews < knMaxOverviews);
    1257         154 :             nDstOverviews = std::min(knMaxOverviews, nDstOverviews);
    1258             : 
    1259             :             // TODO(schwehr): Convert to starting with i = 1 and remove +1.
    1260         229 :             for (int i = 0; i < nDstOverviews - 1 && eErr == CE_None; i++)
    1261             :             {
    1262          75 :                 papoOverviews[i + 1] = hDstBand->GetOverview(i);
    1263          75 :                 if (papoOverviews[i + 1] == nullptr)
    1264             :                 {
    1265           0 :                     eErr = CE_Failure;
    1266             :                 }
    1267             :                 else
    1268             :                 {
    1269          75 :                     if (bHasNoData)
    1270           1 :                         papoOverviews[i + 1]->SetNoDataValue(noDataValue);
    1271             :                 }
    1272             :             }
    1273             : 
    1274         308 :             void *pScaledProgressData = GDALCreateScaledProgress(
    1275         154 :                 iBand / static_cast<double>(nBands),
    1276         154 :                 (iBand + 1) / static_cast<double>(nBands), pfnProgress,
    1277             :                 pProgressData);
    1278             : 
    1279             :             {
    1280             :                 CPLConfigOptionSetter oSetter(
    1281             :                     "GDAL_NUM_THREADS",
    1282         308 :                     CSLFetchNameValue(papszOptions, "NUM_THREADS"), true);
    1283             : 
    1284         154 :                 if (eErr == CE_None)
    1285         154 :                     eErr = GDALRegenerateOverviewsEx(
    1286             :                         hSrcBand, nDstOverviews,
    1287             :                         reinterpret_cast<GDALRasterBandH *>(papoOverviews),
    1288             :                         pszResampling, GDALScaledProgress, pScaledProgressData,
    1289             :                         papszOptions);
    1290             :             }
    1291             : 
    1292         154 :             GDALDestroyScaledProgress(pScaledProgressData);
    1293             :         }
    1294             : 
    1295         112 :         CPLFree(papoOverviews);
    1296             :     }
    1297             : 
    1298             :     /* -------------------------------------------------------------------- */
    1299             :     /*      Cleanup                                                         */
    1300             :     /* -------------------------------------------------------------------- */
    1301         218 :     if (eErr == CE_None)
    1302         217 :         hODS->FlushCache(true);
    1303         218 :     delete hODS;
    1304             : 
    1305         218 :     GTIFFSetThreadLocalInExternalOvr(false);
    1306             : 
    1307         218 :     CPLFree(panOverviewListSorted);
    1308             : 
    1309         218 :     pfnProgress(1.0, nullptr, pProgressData);
    1310             : 
    1311         218 :     return eErr;
    1312             : }

Generated by: LCOV version 1.14